text
stringlengths
5.52k
875k
Title: WebCPM: Interactive Web Search for Chinese Long-form Question Answering: Summary: Long-form question answering (LFQA) aims at answering complex, open-ended questions with detailed, paragraph-length responses. The de facto paradigm of LFQA necessitates two procedures: information retrieval, which searches for relevant supporting facts, and information synthesis, which integrates these facts into a coherent answer. In this paper, we introduce WebCPM, the first Chinese LFQA dataset. One unique feature of WebCPM is that its information retrieval is based on interactive web search, which engages with a search engine in real time. Following WebGPT, we develop a web search interface. We recruit annotators to search for relevant information using our interface and then answer questions. Meanwhile, the web search behaviors of our annotators would be recorded. In total, we collect 5,500 high-quality question-answer pairs, together with 14,315 supporting facts and 121,330 web search actions. We fine-tune pre-trained language models to imitate human behaviors for web search and to generate answers based on the collected facts. Our LFQA pipeline, built on these fine-tuned models, generates answers that are no worse than human-written ones in 32.5% and 47.5% of the cases on our dataset and DuReader, respectively. # WEBCPM: Interactive Web Search for Chinese Long-form Question Answering Yujia Qin1, Zihan Cai1, Dian Jin1, Lan Yan1, Shihao Liang3, Kunlun Zhu3, Yankai Lin2∗, Xu Han1, Ning Ding1, Huadong Wang1, Ruobing Xie4, Fanchao Qi1, Zhiyuan Liu1∗, Maosong Sun1∗, Jie Zhou4 1NLP Group, DCST, IAI, BNRIST, Tsinghua University, Beijing 2Gaoling School of Artificial Intelligence, Renmin University of China, Beijing 3ModelBest Inc. 4Pattern Recognition Center, WeChat AI, Tencent Inc. qyj20@mails.tsinghua.edu.cn # Abstract Long-form question answering (LFQA) aims at answering complex, open-ended questions with detailed, paragraph-length responses. The de facto paradigm of LFQA necessitates two pro- cedures: information retrieval, which searches for relevant supporting facts, and information synthesis, which integrates these facts into a coherent answer. In this paper, we introduce WebCPM, the first Chinese LFQA dataset. One unique feature of WebCPM is that its infor- mation retrieval is based on interactive web search, which engages with a search engine in real time. Following WebGPT (Nakano et al., 2021), we develop a web search interface. We recruit annotators to search for relevant infor- mation using our interface and then answer questions. Meanwhile, the web search behav- iors of our annotators would be recorded. In total, we collect 5, 500 high-quality question- answer pairs, together with 15, 372 supporting facts and 125, 954 web search actions. We fine- tune pre-trained language models to imitate human behaviors for web search and to gen- erate answers based on the collected facts. Our LFQA pipeline, built on these fine-tuned mod- els, generates answers that are no worse than human-written ones in 32.5% and 47.5% of the cases on our dataset and DuReader (He et al., 2018), respectively. The interface, dataset, and codes are publicly available at https: //github.com/thunlp/WebCPM. # Introduction Long-form question answering (LFQA) (Fan et al., 2019) targets answering complex, open-ended ques- tions with detailed, paragraph-length responses. Current LFQA solutions generally follow the retrieve-then-synthesize paradigm, which com- prises two core ingredients: information retrieval and information synthesis. The former searches ex- ternal knowledge sources (e.g., the web) for diverse relevant supporting facts, and the latter integrates the collected facts into a coherent answer. One defect of the conventional LFQA paradigm is that it often resorts to non-interactive retrieval methods, which use the original question as the query to retrieve a pile of uncurated information. On the contrary, humans are able to perform inter- active web search by engaging with a search engine in real time. For a complex question, humans tend to decompose it into multiple sub-questions and ask them in sequence. By identifying and browsing relevant information, humans can improve their un- derstanding of the topic and refine their searches by asking follow-up questions or related terms. This it- erative process enables expanding the scope of their searches and improving the results they receive. Overall, interactive web search not only provides access to diverse information sources, but also re- flects the cognitive process of how humans solve questions, which allows for better interpretability. WebGPT (Nakano et al., 2021) is one pioneer- ing work that supports interactive web search for LFQA. The authors first build a web search inter- face backed up by Microsoft Bing, then recruit annotators to collect information using the inter- face to answer questions. After that, they fine-tune GPT-3 (Brown et al., 2020) to imitate human behav- iors for web search and to organize the collected information into answers. In the experiments, We- bGPT shows exceptional ability in LFQA, even surpassing human experts. Despite its impressive performance, WebGPT still remains mysterious to the community. This is because WebGPT’s inter- face, dataset, and trained models are not publicly available, and the inner workings of its core de- sign elements remain opaque. These factors make it hard for the community to understand the chal- lenges of interactive web search for LFQA and to continue exploring this line of study. ∗Corresponding author. Resource WebCPM (this work) DuReader (He et al., 2018) CMRC (Cui et al., 2019) C3 (Sun et al., 2020) WebGPT (Nakano et al., 2021) GopherCite (Menick et al., 2022) Language? Is Public? Targets long-form QA? Has free-form answer? Has web search behavior? Avg. question length Avg. supporting fact length Avg. answer length ZH ✓ ✓ ✓ ✓ 29.0 555.7 257.5 ZH ✓ ✗ ✓ ✗ 9.6 187.3 104.9 ZH ✓ ✗ ✗ ✗ 16.3 495.5 17.0 ZH ✓ ✗ ✗ ✗ 12.2 116.9 5.5 EN ✗ ✓ ✓ ✓ – – – EN ✗ ✓ ✓ ✗ – – – Table 1: A comparison of our WebCPM to relevant datasets. “–” means the information is unknown. For the length statistics, we record the number of Chinese characters. In view of this, we deem it urgent to provide an accessible platform and public benchmark for this area. To this end, we first construct an in- terface (Figure 1) to record web search behaviors when humans gather relevant information for long- form questions. In the interface, users can execute pre-defined actions to perform multiple rounds of searching and browsing. When finding relevant information on a web page, they can record it as a supporting fact. Meanwhile, their web-browsing behaviors will be recorded. After collecting enough information, users can finish the web search and answer the questions based on their collected facts. Based on the interface, we choose Chinese as the testbed and construct WebCPM, focusing on interactive Web search with Chinese Pre-trained Models. WebCPM is the first public QA dataset that involves interactive web search, and also the first dataset that targets Chinese LFQA. WebCPM contains 5, 500 question-answer pairs, together with 15, 372 supporting facts and 125, 954 web search actions. Table 1 summarizes the differ- ence between WebCPM and relevant QA datasets. Among existing Chinese QA datasets, WebCPM possesses the longest question, supporting fact, and answer, which shows the complexity of the ques- tions and the richness of the annotated answers. Then we propose a general framework consisting of (1) a search model, which imitates human web search behaviors for information retrieval. Specifi- cally, the search model comprises three modules to execute a series of pre-defined actions on our inter- face: an action prediction module, a search query generation module, and a supporting fact extraction module; (2) a synthesis model, which generates a coherent answer conditioned on the collected facts. In the experiments, we choose 8 representative pre-trained language models (PLMs) with up to 10B parameter size, and evaluate their ability of interactive web search and information synthe- sis. We find that scaling model sizes is critical to achieving better performance. By selecting the best-performing backbone PLM for the search and synthesis model, we combine them into a holistic LFQA pipeline and compare its capability with hu- mans. Human evaluation reveals that our pipeline generates answers that are no worse than humans 32.5% of the time on our test set. When applied to questions whose annotated answers are longer than 400 Chinese characters from DuReader (He et al., 2018), our pipeline generates answers that are better than golden annotated ones 47.5% of the cases, showing satisfying out-of-distribution generalization performance. We also show that our search model surpasses the conventional non- interactive retrieval method. Finally, we analyze the contribution of core design elements of our framework and the human-like behaviors our mod- els acquire. We envision these resources to serve as the testbed for other research topics, such as be- havior cloning (Bain and Sammut, 1995) and tool learning (Qin et al., 2023). # 2 Related Work Retrieval and Synthesis in LFQA. For informa- tion retrieval, prior works generally resort to local repositories (e.g., Wikipedia). Recently there is a surge of interest in leveraging the whole web as the knowledge source (Nakano et al., 2021; Lazari- dou et al., 2022; Menick et al., 2022; Thoppilan et al., 2022), which not only widens the scope of information sources but enables real-time coverage of up-to-date knowledge. On the other hand, how to structure the retrieved facts into a plausible and nuanced answer for LFQA is still under-explored. Some investigated how humans craft complicated answers, either by studying the functional struc- tures of long-form answers (Xu et al., 2022) or exploring how to compose exemplification in an- swers (Wang et al., 2022); others revisit existing evaluation metrics of LFQA (Krishna et al., 2021). Question | ZHRBRH4A? CileeeAZRAy? v Q\ Query | seenezmanranznt + Action Name Functionality Q search <query> Call Bing search with <query> € Go Back Return to the previous window Window (search mode) + + 79 39 Quote Merge ty Load Page <1> Load the details of page <1> Page <1> Fact #1 2023-01-21 19:59:00 dy Load Page <2> Load the details of page <2> a Re REMI N/A. Title of page <2> th Page <2> A snapshot of the page content Content of Fact #2 Title of page <3> Page <3> A snapshot of the page content € Go Back Number of remaining actions (86/100) ty Load Page <3> Load the details of page <3> } Scroll Up Scroll up for a pre-set stride ¥ Scroll Down — Scroll down for a pre-set stride Fact #2 2023-01-21 20:05:12 35 Quote Extract <content> from the <content> current page as a supporting fact i Merge Merge two facts into a single fact Q® Finish End the search process © Finish Question | ZHRBRH4A? CileeeAZRAy? v Q\ Query | seenezmanranznt + Action Name Functionality Q search <query> Call Bing search with <query> € Go Back Return to the previous window Window (search mode) + + 79 39 Quote Merge ty Load Page <1> Load the details of page <1> Page <1> Fact #1 2023-01-21 19:59:00 dy Load Page <2> Load the details of page <2> a Re REMI N/A. Title of page <2> th Page <2> A snapshot of the page content Content of Fact #2 Title of page <3> Page <3> A snapshot of the page content € Go Back Number of remaining actions (86/100) ty Load Page <3> Load the details of page <3> } Scroll Up Scroll up for a pre-set stride ¥ Scroll Down — Scroll down for a pre-set stride Fact #2 2023-01-21 20:05:12 35 Quote Extract <content> from the <content> current page as a supporting fact i Merge Merge two facts into a single fact Q® Finish End the search process © Finish Figure 1: Left: an example screenshot of our interface in the search mode. Right: the actions our interface supports. Comparison with WebGPT. We largely follow WebGPT and also propose improved design ele- ments (with details elaborated in appendix E), in- cluding (1) interface: we modify the actions de- fined by WebGPT to make them easier for model learning and more user-friendly; (2) framework: we decompose web search into 3 sub-tasks and im- plement a modular search model. We additionally explore how to teach the synthesis model to ignore irrelevant facts (§ 6.3) and generate novel contents (appendix F.1); (3) evaluation and analysis: be- sides evaluating the whole pipeline following We- bGPT (§ 6.2), we also evaluate each individual module (§ 6.1 and § 6.3). This fine-grained eval- uation helps us better understand the contribution of core design elements of our framework and the human behaviors learned by our model. gather relevant information for long-form ques- tions. Our interface, backed up by Bing Search API, supports 10 mainstream web search actions as shown in Figure 1. When an action is executed, our interface responds with changes in the window. When the action Search is performed, the inter- face enters search mode (Figure 1), which displays the links recommended by Bing for a specific query <query>. Each link comprises a title and a brief snapshot of the specific web page. Each window displays three links one time, and more links can be accessed by executing the Scroll Down action. When finding the i-th link in the current win- dow to be relevant, users could execute the Load Page <i> action (i ). The interface ∈ { would enter the browsing mode (Figure 6 in the appendix) and render the texts cleaned from the HTML of the <i>-th web page. The content users could view at a time in the window is restricted up to 500 Chinese characters, and more content can be accessed with the Scroll action. Users can utilize the Quote action to extract consecutive sentences in the current window as a supporting fact. To enable extracting texts that stretch across two windows, the Merge action is designed to merge the last two facts into a single fact (see ap- pendix A.2 for more details). We also display all the existing extracted supporting facts for users. Tool Learning. Recent research demonstrates PLMs with promising capabilities of manipulat- ing tools, i.e., tool learning (Qin et al., 2023). PLMs can make sequential decisions in com- plex interactive environments, such as planning in robotic tasks (Huang et al., 2022a; Ahn et al., 2022; Huang et al., 2022b), manipulating search engines (Nakano et al., 2021), shopping on e- commerce websites (Yao et al., 2022), etc. By harnessing the rich world knowledge learned dur- ing pre-training, PLMs can perform grounded ac- tions to interact with the real world. We envision our benchmark to serve as the testbed for future explorations in this area. After browsing the i-th page, users can return to the previous search mode using the Go Back action to access other links. Meanwhile, a refined query can be sent at any time. In general, users can freely interact with our interface multiple times until executing the Finish action or triggering the maximum number of actions (100 in our case). The # 3 Web Search Environment Following WebGPT, we construct a text-only inter- face to record web search behaviors when humans interface would automatically record meaningful actions and observations during web search. Owing to the multilingual nature of Bing system, although this work focuses on Chinese, our interface can be flexibly adapted to other languages as well. For more technical details, please refer to appendix A. # 4 Data Collection We employ 23 annotators from different walks of life, who are experienced in search engine opera- tion. We ask them to answer long-form questions by first searching for relevant information using our interface, then writing a nuanced answer. For quality control, we recruit 8 experts familiar with QA research as quality inspectors. Next, we intro- duce the construction process of our dataset, with detailed annotation guides left in appendix B. Question Creation. Creating new long-form questions from scratch without any reference is counterproductive, thus we turn to public QA fo- rums as the question source. Specifically, we en- gage annotators to refer to the questions on an English QA forum Reddit, and then create new questions written in Chinese. The details of this creation process are elaborated in appendix C. We find empirically that questions created in this way often necessitate multiple rounds of searching and browsing to collect sufficient information. Interactive Web Search. Given a question, we ask annotators to search for accurate and relevant information from trusted sources using our inter- face. This process may involve sending refined queries to Bing multiple times, as well as explor- ing various web pages they deem to be relevant. We require annotators to carefully judge the fac- tual accuracy of the information before extracting it as a supporting fact. The search process would be finished until sufficient supporting facts are col- lected. Among our created questions, 26.2% are unanswerable and finally discarded because anno- tators cannot find sufficient useful information. Answer Annotation. After gathering enough supporting facts, the annotators would write self- contained answers based on their collected infor- mation. We give them instructions for answer anno- tation, including writing answers that are relevant to the question and have rich content, maintain- ing logical consistency, clarity, and coherence, and providing viewpoints in an unbiased manner. Quality Control. Each annotated instance is checked and approved by the quality inspectors before being selected for the final dataset. First, inspectors would manually inspect the action se- quences recorded on the interface and discard low- quality ones (e.g., those with evident clerical er- rors in the issued queries). Second, they would carefully check the collected supporting facts. If these facts are apparently insufficient to answer the question, irrelevant to the question, or factually in- correct, the corresponding action sequence would be abandoned. The above procedures remove 25% collected instances. For the remaining instances, inspectors would carefully examine their annotated answers. If an answer contradicts the abovemen- tioned instructions, inspectors would return it to annotators and point out which requirement is not satisfied. Annotators would revise their answers possibly for multiple rounds until the revised an- swer is up to standard. Dataset Statistics. Ultimately, we collect 5, 500 instances, each formatted in a tuple of (question, web search behavior, supporting fact, answer), and also record the observations at each action execu- tion. We display an example in Figure 2 for refer- ence, where we present the following: the original question, the simplified action sequence, the col- lected supporting facts, and the annotated answer. We partition the dataset into {4, 700, 400, 400} as the training, development, and test set. On average, each question involves performing 22.9 actions, sending 2.5 queries, and loading 3.3 web pages. The detailed proportion of each action is visualized in Figure 7 in the appendix. # 5 Framework In this section, we introduce how to teach PLMs for (1) interactive web search using our interface (§ 5.1) and (2) information synthesis (§ 5.2). The overall framework is illustrated in Figure 3. # 5.1 Search Model Overview. We partition web search into 3 sub- tasks: action prediction, search query generation, and supporting fact extraction. Each task is cast as a text-to-text format and we train 3 separate modules using a generative PLM. By combining the 3 modules, we build the search model, which executes a series of actions to gather relevant in- formation. The action prediction module decides which action to perform at each step. If the module Question: 麦田怪圈是什么?它们是如何形成的? Translated Question: What are crop circles? How are they made? Human Action Sequence: Search → Load Page <1> → Quote → Scroll Down × 5 → Scroll Up → Scroll Down × 11 → Go Back → Search → Load Page <1> → Go Back → Load Page <3> → Scroll Down × 4 → Scroll Up × 3 → Quote → Scroll Down → Quote → Merge → Quote → Scroll Down → Quote → Finish Supporting Facts: 1. 麦田怪圈(Crop Circle),是指在麦田或其它田地上,通过某种未知力量(大多数怪圈是人类所为)把农作物压平 而产生出来的几何图案。这个神秘现象有时被人们称之为“Crop Formation”。麦田怪圈的出现给了对支持外星人存在 论的人们多种看法。 2. 人为说:人为说一般认为,麦田圈是用木板压成的。木板两头系上绳子形成圈套,在制作时,一脚踩在木板上拖 动木板压倒麦子,并拉着细绳与圆心保持固定的距离,逐渐就可以形成一个圆圈。为了便于制造,主要形状所有圆 圈的直径都可以被6除尽。以前曾经出现过制作麦田圈被当场抓获的事情,制作者使用的就是这种工具。 3. 自然形成说:也有人认为,麦田圈只是一种,成因还未被人类发现。就像雷电,古时候人类也是以为是雷神电母 做的,对于麦田圈中经常出现人文信息的现象,他们认为这只是人们“先入为主”造成的错觉。 4. 磁场说:有专家认为,磁场中有一种神奇的移动力,可产生一股电流,使农作物“平躺”在地面上。美国专家杰弗 里·威尔逊研究了130多个麦田怪圈,发现90%的怪圈附近都有连接高压电线的变压器,方圆270米内都有一个水池。 由于接受灌溉,麦田底部的土壤释放出的离子会产生负电,与高压电线相连的变压器则产生正电,负电和正电碰撞 后会产生电磁能,从而击倒小麦形成怪圈。 Translated Supporting Facts: 1. Crop circles, also known as “crop formations”, are geometric patterns that appear in fields of crops, often as a result of unknown forces (though most crop circles are actually created by humans). This mysterious phenomenon has sometimes been used to support the belief in extraterrestrial life. 2. Human-made theory: According to the human-made theory, crop circles are believed to be created using planks of wood. The ends of the planks are attached to ropes to form a loop, and the crops are flattened by dragging the planks across them while maintaining a fixed distance from the center of the circle using the ropes. This process can gradually create a circular pattern. To make the process easier, the diameters of most circles can be evenly divided by 6. In the past, there have been instances of crop circle makers being caught in the act, and they have used this method to create the circles. 3. Natural formation theory: According to the natural formation theory, some people believe that crop circles are a phenomenon whose cause has not yet been discovered by humans. Similar to how lightning was once thought to be the work of the god, the appearance of human-like symbols in crop circles is seen as a result of people’s preconceptions. 4. Magnetic field theory: According to the magnetic field theory, some experts believe that crop circles are created by a mysterious force in the magnetic field that generates an electric current that causes the crops to lie flat on the ground. American expert Jeffrey Wilson studied over 130 crop circles and found that 90% were located near transformers connected to high-voltage power lines and within 270 meters of a pond or other source of water. The irrigation of the soil in the fields can cause the release of ions in the soil at the bottom of the field, creating a negative charge. The transformer connected to the high-voltage power lines generates a positive charge, and the collision of the negative and positive charges creates electromagnetic energy that knocks down the wheat, forming a crop circle. Answer: 麦田怪圈是指在麦田或其它田地上,通过某种未知力量(大多数怪圈是人类所为)把农作物压平而产生出来的几何 图案。【1】而麦田怪圈的形成有三个说法,人为说、自然说与磁场说。人为说一般认为,麦田圈是用木板压成的。 木板两头系上绳子形成圈套,在制作时,一脚踩在木板上拖动木板压倒麦子,并拉着细绳与圆心保持固定的距离, 逐渐就可以形成一个圆圈。为了便于制造,主要形状所有圆圈的直径都可以被6除尽。【2】自然形成说认为麦田怪 圈的成因还未被人类发现。就像雷电,古时候人类也是以为是雷神电母做的,对于麦田圈中经常出现人文信息的现 象,他们认为这只是人们“先入为主”造成的错觉。【3】磁场说认为,磁场中有一种神奇的移动力,可产生一股电 流,使农作物“平躺”在地面上。【4】 Translated Answer: Crop circles are geometric patterns created by flattening crops through an unknown force (most crop circles are made by humans) in a field of wheat or other crops. [1] There are three theories about the formation of crop circles: human-made, natural, and magnetic fields. The human-made theory generally believes that crop circles are made using wooden boards. The wooden boards are connected by ropes to form a hoop, and during the production process, one-foot steps on the wooden board, dragging the wooden board to flatten the wheat, and pulling the fine rope to maintain a fixed distance from the center, gradually forming a circle. In order to facilitate manufacture, the main shape of all circles has a diameter that can be evenly divided by 6. [2] The natural formation theory believes that the cause of crop circles has not yet been discovered by humans. Like lightning, ancient humans also thought it was made by the god, and for the phenomenon of human information often appearing in crop circles, they think it is just a “preconceived” illusion caused by people. [3] The magnetic field theory believes that there is a mysterious moving force in the magnetic field that can generate an electric current, causing crops to “lie flat” on the ground. [4] Figure 2: A sampled example from WebCPM, where we translated the original Chinese version into English. predicts Search or Quote as the current action, then it calls the other two modules to generate the _ contents of the query or the supporting fact. Each module performs inference conditioned on Current State S; Web Search Environment Q Original Question: Qo Timestep Next action: Web Search Environment —™ t+] Question and Facts Current Query: Q: Actions: Ay_1 = {a1,.. Windows: W,1,W. Facts: Fe = {fi # remaining actions: pees Fiza} “7 T= Qo; Fr = {hs---sfizel > SRO > + Qt—1 fi e @ Action Prediction Module @ Query Generation Module e @ Fact Extraction Module ‘Answer @ Synthesis Model Figure 3: Illustration of our LFQA framework. For an action sequence of T steps, the search model (consisting of 3 modules) executes actions to collect supporting facts, which are sent to the synthesis model for answer generation. Supporting Fact Extraction. Assume in the browsing mode, the current content of the . We aim to window is t = from extract a supporting fact f = wi, ..., wj { . While a naive W | solution is to directly generate all the tokens of f auto-regressively, this solution suffers from low inference speed in practice. As an alternative, we only generate the first and last few (Nf ) t. Formally, we maximize tokens of f given t), P where [s] and [e] denote the special tokens that indicate the start and end of the fact f . During inference, after decoding the start and end tokens, we can locate the desired sequence in t by text matching. If the start / end tokens occur in multiple locations of t, we always extract the longest W t, and a large Nf could lower sequence from the frequency of this multi-location issue. Note disjoint spans in t can be extracted by executing multiple Quote actions consecutively. t of the interface at time step t. 0, the query Q S t, the past action sequence currently searching Q , the last and the current con- a1, ..., at−1 } A t, current tent displayed in the window supporting facts , and the num- ber of remaining actions. If an action is executed, the components of can be either the three links in the search mode or the spe- cific page content in the browsing mode. We only t−1 and maintain the recent two observations ( t) displayed in the window instead of concatenat- W ing all the past observations because the latter may exceed the input length limit of the PLM. Next, we introduce the three modules in detail. Action Prediction. This module predicts which action to perform next. Since there are 10 possible actions in total, action prediction can be viewed as a 10-category classification task. Take the action Search as an example, denote as the tokenized sequence for the action name Search, where x∗ denotes a specific token. The probability of Search can be factorized as follows: # 5.2 Synthesis Model The information synthesis task learns to organize a series of supporting facts into a coherent answer. However, not as perfect as humans, the trained search model occasionally gathers irrelevant noises, which would influence the quality of the generated answer. To remedy this, we corrupt the collected facts in the training data of the synthesis model by introducing noises. Specifically, given a series of , we randomly human-extracted facts select a few unrelated facts from other training instances. After randomly shuffling all the facts, we concatenate them as the final input. N P(Search|S:) = P(ai\Se) x [] P(wilSe, 1, ..., 1-1). i=2 During inference, we select the action with the highest probability to perform on the interface. Search Query Generation. This module gen- erates a query to search { Bing, which is also formulated as text generation: 1Qeqa] P(Qe41/S:) = Plai|Se)x [TI P(ailSe. ais G1). i=2 During training, the model is optimized to gener- ate the human-annotated answer conditioned on the corrupted supporting facts, i.e., maximizing N′). Since the P annotated answer does not contain the information of f ′ ∗, the model learns to ignore irrelevant facts and only focus on important ones for generation. # 6 Experiments and Analyses Our problem consists of 4 sub-tasks: action pre- diction, search query generation, supporting fact extraction, and information synthesis. Correspond- ingly, we first train 4 modules and evaluate each sub-task independently by feeding the ground truth input to each module (§ 6.1). Then we combine all modules into a unitary pipeline and only feed the question to the pipeline for a holistic evaluation (§ 6.2). Finally, we conduct in-depth analyses for each module to understand their behaviors (§ 6.3). # Individual Sub-task Evaluation Settings. We evaluate 8 typical generative PLMs that support Chinese, covering 3 architectures: • T5 2019): (Raffel mT5BASE (Xue et al., 2021), a 580M model pre- trained on mC4; mT0BASE (Muennighoff et al., 2022), which fine-tunes mT5BASE on diverse downstream tasks; Mengzi-T5BASE (Zhang et al., 2021b), a 220M model pre-trained on 300G internet corpora. • BART architecture (Lewis et al., 2020): mBARTLARGE (Liu et al., 2020), a 680M model pre-trained on monolingual corpora of multiple languages; C-BARTLARGE (Shao et al., 2021), a 406M model pre-trained on 200G web texts. CPM architecture (Zhang et al., 2021a): CPM2.6B, CPM7B, and CPM10B, which con- tain 2.6B, 7B, and 10B parameters, respectively, and are pre-trained with increasing sizes of data. Among these PLMs, mT5BASE, mT0BASE, and mBARTLARGE are multilingual and the others are Chinese-only PLMs. We elaborate on details of the above PLMs in appendix D. We adopt recom- mended fine-tuning configurations of the original papers for all PLMs. For evaluation metrics, we treat action prediction as a 10-category classifica- tion task and choose Micro-F1 and Macro-F1 as the metric. We treat the other three tasks as text generation and calculate Rouge-L of the generated sequence and the ground truth. Task Metric Action Mi. Ma. Query R-L Fact R-L Synth. R-L 53.8 44.0 58.2 52.1 Mengzi-T5BASE 58.1 51.2 53.6 41.1 mBARTLARGE 43.8 31.3 C-BARTLARGE 55.6 49.8 CPM2.6B 58.9 50.5 CPM7B 54.5 60.4 CPM10B mT5BASE mT0BASE 62.4 64.6 62.6 50.4 56.1 61.6 67.8 70.0 56.7 60.0 61.9 56.5 49.3 52.6 59.8 62.4 56.8 51.4 57.7 60.2 50.6 55.0 56.4 61.2 Table 2: Sub-task evaluation (test performance) using 8 PLMs. We report Micro-F1 (Mi.), Macro-F1 (Ma.) for action prediction, and Rouge-L (R-L) for query genera- tion, fact extraction, and information synthesis. Results. The results are listed in Table 2, from (1) mT0BASE outper- which we conclude that: forms mT5BASE in action prediction, query gen- eration, and supporting fact extraction, but per- forms poorer in information synthesis. We conjec- ture this is because mT0BASE enhances language skills more related to the first three tasks during its multi-task fine-tuning. Rather, the information synthesis ability might have been weakened. Be- sides, Mengzi-T5BASE performs generally well on all tasks despite owning much fewer parameters; (2) in general, mBARTLARGE and C-BARTLARGE show inferior performance than all other PLMs, ex- cept that mBARTLARGE exhibits excellent perfor- mance in information synthesis; (3) comparing the results of CPM2.6B, CPM7B, and CPM10B, we find that the performance generally gets improved as the model size increases. Blessed by the scal- ing law (Kaplan et al., 2020), larger PLMs own stronger understanding and generation abilities and could achieve better downstream performance. # 6.2 Holistic Pipeline Evaluation We choose the modules trained by CPM10B, which performs the best among all the PLMs in § 6.1, and combine them into the overall pipeline. Then we evaluate its performance compared with humans. Compared Answer Pairs. For each test question of WebCPM, we compare the annotated answer with 3 types of answers generated by our synthesis model. Specifically, the 3 types of answers differ in the source of supporting facts, including (1) the facts collected by our search model, (2) ground- truth human-collected facts, and (3) the facts col- lected using a commonly adopted non-interactive web search method. For (3), we directly input the original question into Bing, extract the paragraphs (@) Pipeline Evaluation on Our Test Set (b) Pipeline Evaluation on Search and Zhidao (c) Ablation Study (Synth.) lm Prefer Pipeline lil Equivalent Prefer Annotation | 44, lm Prefer Pipeline mm Prefer Ours 80% 4 - i. 45° mmm Equivalent 60%} mmm Equivalent 675 Prefer Annotation Prefer Baseline 60% $6.0 ~ 43.7 = 60% § 54.5 51.0 49.0 40% 38.3 5 44.0 3 £ 40% 40% 295 20% 18.0 20% | 19.0 ae 16.0 18-0. 20% 75 o% o% 0.0 0.0 0% Pipeline-collected Human-collected — Non-interactive Search Search Zhidao Figure 4: Results of human evaluation. (a) Comparison of human annotation and our pipeline-generated answers with different sources of supporting facts. (b) The experiments on two DuReader datasets: Search and Zhidao. We compare our pipeline with the golden annotation. (c) Ablation study for our synthesis model. from all the retrieved links, and rank them using TF-IDF. Then we concatenate the top-k paragraphs as the input until it exceeds 3072 tokens. Evaluation Protocol. We engage 8 annotators to manually compare different answers based on human preference. Given a question and a pair of answers, we ask them to perform an overall assess- ment and decide which answer they would prefer based on multiple factors, including the overall usefulness, coherence, and relevance to the ques- tion. Since all three retrieval methods use the same search engine, their collected facts sometimes have a high overlap, which leads to similar answers. Thus we allow annotators to mark two answers as equivalent if both are of comparable quality. Results. We derive from the results in Figure 4 (a) that: (1) the answers obtained purely by our pipeline are preferred or comparable to human- written answers 19.0%+13.5% = 32.5% of the time. This result implies ample opportunity for advance- ment of our pipeline in future endeavors, which is discussed in appendix G. (2) When applying our synthesis model to the human-collected facts, the performance grows to 16.0%+29.5% = 45.5% pref- erence or equivalence, which is due to the improved quality of the collected facts. (3) The facts gathered by non-interactive search lead to slightly worse per- formance (7.5%+18% = 25.5%) than our search model. The superiority of our search model over non-interactive search may be because our model (a) sends diverse queries to Bing multiple times so that more abundant information can be retrieved, and (b) it critically decides whether a web page contains important information, which performs better than TF-IDF. Chinese QA datasets from DuReader, i.e., Zhidao and Search. Although not specially designed for LFQA, DuReader contains a variety of question types, and we randomly sample 400 test questions whose annotated answers are longer than 400 Chi- nese characters. For these questions, we engage an- notators to compare our pipeline-generated answers with the golden annotations of DuReader. From the results in Figure 4 (b), we find that our pipeline generates answers better than the annotated ones 44.0% and 51.0% of the time on Search and Zhi- dao (47.5% on average), showing satisfying out- of-distribution generalization performance. The fact that the same pipeline surpasses fewer human- written answers on our dataset than DuReader also reflects the high quality of our annotated an- swers. Note the equivalent ratio is 0% because both answers are based on totally different support- ing facts, and it is easy to determine which one is better. # 6.3 Further Analysis Next, we conduct in-depth analyses to gain a deeper understanding of each module. Without loss of generality, we evaluate CPM7B in this section. Ablation Study for the Synthesis Model. We evaluate whether corrupting the synthesis model’s training data by introducing irrelevant facts im- proves its ability to ignore noisy facts. We train a baseline model without corrupting the training data and keep other settings the same as our model. For each test question, we feed the supporting facts col- lected by our search model to both synthesis mod- els and generate two answers. Annotators would evaluate which answer is more relevant to the orig- inal question (the equivalent option is allowed). Experiments on DuReader. Next, we apply our pipeline (search model and synthesis model) to 2 According to Figure 4 (c), by corrupting the training data, our model performs better than the Fact Action Task Metric Mi. Ma. R-L Task Metric Query R-L 67.8 66.9 - Wt−1 57.7 52.0 59.3 - past queries∈ At−1 65.3 65.3 - At−1 53.4 44.1 60.3 St - Ft 58.9 50.5 59.8 55.5 49.3 54.7 St - Ft - seen titles∈ At−1 Table 3: Ablation study of the search model when dif- St, respectively. ferent components are removed from baseline 43.7% of the time and is worse 18.0% of the cases. This demonstrates that our method indeed enhances the model’s ability to ignore noisy information, which makes the generated answer more relevant to the original question. In appendix F.1, we further explore the use of another corruption method that flexibly balances generating novel contents and copying supporting facts. Effects of Components in t. We conduct ab- t to ex- lation studies for several components of amine how they contribute to each module of the search model. This is achieved by modifying both the training and evaluation data of each module. For action prediction and supporting fact extrac- tion, we remove one of the following: the existing t, the contents displayed in the collected facts t−1. For last window query generation, the following items are removed from t, the al- the existing collected facts ready searched queries, or the titles of the links browsed before. The information of the latter two t−1. Specifically, for the past items is included in action Search / Load Page, t−1 not only in- cludes the action name, but also records the specific searched query / the title of the loaded page. The results are listed in Table 3, from which we observe that: (1) for action prediction, the removal t−1 only leads to minimal per- of either W formance changes, while removing t−1 leads to a significant performance drop. This shows that the past actions are critical factors for action prediction; (2) for supporting fact extraction, only removing t impairs the performance significantly ( 5.1). This indicates that aligned with humans, − the module considers what has been extracted to decide which information to extract next; (3) for query generation, removing either searched queries or accessed link titles in t−1 causes a great neg- 2.5), which means the module ative impact ( might have learned to generate queries based on what has been searched and newly observed information during web search. This feature is Question and Generated Query HHMASSBALEATAER? RRRRTA? What’ the difference between computer science and electrical engineering? What are their advantages and disadvantages? 1] SALA SL Computer science and engineering 2) BALL A What is electrical engineering 3] SALA SW RHA Advantages and disadvantages of computer science Pitt AEE IR BAH AR SRB A BE 2 ZH? Why does it feel good to rub your eyes when you're tired? Fatt CEU SR HT ARE RAT BBE 3K ZF 2 Why does it feel good to rub your eyes when you're tired? 2] RWW AER Rubbing your eyes when you're tired 3] FREER T RY FRR RAM Rubbing your eyes relieves fatigue when your eyes are tired and sore HR GR ARSE ARE PR Eyecare exercise relieves eye fatigue = Figure 5: Case study for query generation. We show the generated queries for two test questions. humanoid in that humans also consider both infor- mation to avoid sending repetitive queries and to ask follow-up questions about an accessed link. Case Study for Query Generation. To fathom the human behaviors learned by our query mod- ule, we conduct a case study by sampling the gen- erated queries for different questions in the test set. We illustrate two representative results in Fig- ure 5 to showcase the typical strategies learned by our query module, including copying the original question, decomposing the question into multiple sub-questions, rephrasing questions with related terms, etc. These strategies make the queries more diverse, which helps gather more abundant infor- mation from various sources. # 7 Conclusion In this paper, we construct a benchmark of inter- active web search for Chinese long-form QA, to- gether with an open-source interface. We decom- pose the task into 4 sub-tasks and design a modu- lar pipeline. By fine-tuning representative PLMs, we conduct both an individual evaluation for each module and a holistic evaluation for the pipeline. In-depth analyses are carried out to understand the core design elements of our framework. We expect our interface, dataset, framework, and analyses to facilitate more future explorations in this area. # Acknowledgments This work is supported by the National Key R&D Program of China (No. 2020AAA0106502), In- stitute Guo Qiang at Tsinghua University, Bei- jing Academy of Artificial Intelligence (BAAI). Huadong Wang is funded by China Postdoctoral Science Foundation (No. 2022M721829). Yujia Qin and Zihan Cai led the data collection. Yujia Qin, Dian Jin, Lan Yan, Shihao Liang, and Kunlun Zhu conducted the experiments. Yujia Qin wrote the paper. Yankai Lin, Xu Han, Zhiyuan Liu, Maosong Sun, and Jie Zhou advised the project. All authors participated in the discussion. The au- thors would like to thank Aran for the implementa- tion of the interface, Shengding Hu, Haoyang Pang and Zhenhuan Huang for the discussion, and the anonymous annotators for their huge efforts. # Limitations The human evaluation shows that our pipeline per- forms worse than humans in the process of infor- mation retrieval and synthesis 67.5% of the time, which still leaves room for improvement (see ap- pendix G for future works). # Ethical Statement In this research, we adhere to the highest ethical standards and commit to making every effort to minimize any potential harm. Specifically: • When creating our dataset, we have ensured that all data collected is obtained through legitimate and legal means. In addition, we have obtained the appropriate permissions and consent from all necessary parties. We have also taken steps to protect the privacy of individuals whose data is included in our dataset through de-identification during annotation. • We are committed to eliminating bias, discrim- ination, or stereotypes during annotation by re- moving any suspect examples. • We take the responsibility of open-sourcing the interface, dataset, codes, and trained models to the public. However, there are cases that these re- sources are maliciously used. For instance, our models may be utilized to generate responses without proper attribution of the information source, causing severe consequences. We would strive to ensure that they are used ethically and not for any malicious or harm-causing intent. # References Michael Ahn, Anthony Brohan, Noah Brown, Yev- gen Chebotar, Omar Cortes, Byron David, Chelsea Finn, Chuyuan Fu, Keerthana Gopalakrishnan, Karol Hausman, Alex Herzog, Daniel Ho, Jasmine Hsu, Julian Ibarz, Brian Ichter, Alex Irpan, Eric Jang, Rosario Jauregui Ruano, Kyle Jeffrey, Sally Jes- month, Nikhil Joshi, Ryan Julian, Dmitry Kalash- nikov, Yuheng Kuang, Kuang-Huei Lee, Sergey Levine, Yao Lu, Linda Luu, Carolina Parada, Pe- ter Pastor, Jornell Quiambao, Kanishka Rao, Jarek Rettinghouse, Diego Reyes, Pierre Sermanet, Nico- las Sievers, Clayton Tan, Alexander Toshev, Vincent Vanhoucke, Fei Xia, Ted Xiao, Peng Xu, Sichun Xu, Mengyuan Yan, and Andy Zeng. 2022. Do as i can and not as i say: Grounding language in robotic af- fordances. In arXiv preprint arXiv:2204.01691. Michael Bain and Claude Sammut. 1995. A framework for behavioural cloning. In Machine Intelligence 15, pages 103–129. Tom B. Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared 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 M. Ziegler, Jeffrey Wu, Clemens Winter, Christopher Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei. 2020. Language models are few-shot learners. In Ad- vances in Neural Information Processing Systems 33: Annual Conference on Neural Information Process- ing Systems 2020, NeurIPS 2020, December 6-12, 2020, virtual. Yiming Cui, Ting Liu, Wanxiang Che, Li Xiao, Zhipeng Chen, Wentao Ma, Shijin Wang, and Guoping Hu. 2019. A span-extraction dataset for Chinese ma- In Proceedings of chine reading comprehension. the 2019 Conference on Empirical Methods in Natu- ral Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 5883–5889, Hong Kong, China. Association for Computational Linguistics. Angela Fan, Yacine Jernite, Ethan Perez, David Grang- ier, Jason Weston, and Michael Auli. 2019. ELI5: Long form question answering. In Proceedings of the 57th Annual Meeting of the Association for Com- putational Linguistics, pages 3558–3567, Florence, Italy. Association for Computational Linguistics. Wei He, Kai Liu, Jing Liu, Yajuan Lyu, Shiqi Zhao, Xinyan Xiao, Yuan Liu, Yizhong Wang, Hua Wu, Qiaoqiao She, Xuan Liu, Tian Wu, and Haifeng Wang. 2018. DuReader: a Chinese machine reading comprehension dataset from real-world applications. In Proceedings of the Workshop on Machine Reading for Question Answering, pages 37–46, Melbourne, Australia. Association for Computational Linguistics. Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. 2022a. Language models as zero- shot planners: Extracting actionable knowledge for embodied agents. arXiv preprint arXiv:2201.07207. Wenlong Huang, Fei Xia, Ted Xiao, Harris Chan, Jacky Liang, Pete Florence, Andy Zeng, Jonathan Tompson, Igor Mordatch, Yevgen Chebotar, et al. Inner monologue: Embodied reasoning 2022b. arXiv through planning with language models. preprint arXiv:2207.05608. Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B Brown, Benjamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, and Dario Amodei. 2020. Scaling laws for neural language models. arXiv preprint arXiv:2001.08361. Kalpesh Krishna, Aurko Roy, and Mohit Iyyer. 2021. Hurdles to progress in long-form question answering. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies, pages 4940–4957, Online. Association for Computa- tional Linguistics. Angeliki Lazaridou, Elena Gribovskaya, Wojciech Stokowiec, and Nikolai Grigorev. 2022. Internet- augmented language models through few-shot prompting for open-domain question answering. arXiv preprint arXiv:2203.05115. Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Veselin Stoyanov, and Luke Zettlemoyer. 2020. BART: Denoising sequence-to-sequence pre-training for natural language generation, translation, and com- prehension. In Proceedings of the 58th Annual Meet- ing of the Association for Computational Linguistics, pages 7871–7880, Online. Association for Computa- tional Linguistics. Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, and Luke Zettlemoyer. 2020. Multilingual denoising pre- training for neural machine translation. Transac- tions of the Association for Computational Linguis- tics, 8:726–742. Jacob Menick, Maja Trebacz, Vladimir Mikulik, John Aslanides, Francis Song, Martin Chadwick, Mia Glaese, Susannah Young, Lucy Campbell- Gillingham, Geoffrey Irving, et al. 2022. Teaching language models to support answers with verified quotes. arXiv preprint arXiv:2203.11147. Niklas Muennighoff, Thomas Wang, Lintang Sutawika, Adam Roberts, Stella Biderman, Teven Le Scao, M Saiful Bari, Sheng Shen, Zheng-Xin Yong, Hai- ley Schoelkopf, Xiangru Tang, Dragomir Radev, Al- ham Fikri Aji, Khalid Almubarak, Samuel Albanie, Zaid Alyafeai, Albert Webson, Edward Raff, and Colin Raffel. 2022. Crosslingual generalization through multitask finetuning. Reiichiro Nakano, Jacob Hilton, Suchir Balaji, Jeff Wu, Long Ouyang, Christina Kim, Christopher Hesse, Shantanu Jain, Vineet Kosaraju, William Saunders, et al. 2021. Webgpt: Browser-assisted question- answering with human feedback. arXiv preprint arXiv:2112.09332. Yujia Qin, Shengding Hu, Yankai Lin, Weize Chen, Ning Ding, Ganqu Cui, Zheni Zeng, Yufei Huang, Chaojun Xiao, Chi Han, et al. 2023. Tool learning with foundation models. arXiv preprint arXiv:2304.08354. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J Liu. 2019. Exploring the limits of transfer learning with a unified text-to-text trans- former. ArXiv preprint, abs/1910.10683. Yunfan Shao, Zhichao Geng, Yitao Liu, Junqi Dai, Fei Yang, Li Zhe, Hujun Bao, and Xipeng Qiu. 2021. Cpt: A pre-trained unbalanced transformer for both chinese language understanding and genera- tion. arXiv preprint arXiv:2109.05729. Nisan Stiennon, Long Ouyang, Jeffrey Wu, Daniel Ziegler, Ryan Lowe, Chelsea Voss, Alec Radford, Dario Amodei, and Paul F Christiano. 2020. Learn- ing to summarize with human feedback. Advances in Neural Information Processing Systems, 33:3008– 3021. Kai Sun, Dian Yu, Dong Yu, and Claire Cardie. 2020. In- vestigating prior knowledge for challenging Chinese machine reading comprehension. Transactions of the Association for Computational Linguistics, 8:141– 155. Romal Thoppilan, Daniel De Freitas, Jamie Hall, Noam Shazeer, Apoorv Kulshreshtha, Heng-Tze Cheng, Alicia Jin, Taylor Bos, Leslie Baker, Yu Du, et al. 2022. Lamda: Language models for dialog applica- tions. arXiv preprint arXiv:2201.08239. Shufan Wang, Fangyuan Xu, Laure Thompson, Eunsol Choi, and Mohit Iyyer. 2022. Modeling exemplifi- cation in long-form question answering via retrieval. In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies, pages 2079–2092, Seattle, United States. Association for Computational Linguistics. Sean Welleck, Ilia Kulikov, Stephen Roller, Emily Di- nan, Kyunghyun Cho, and Jason Weston. 2019. Neu- ral text generation with unlikelihood training. arXiv preprint arXiv:1908.04319. Fangyuan Xu, Junyi Jessy Li, and Eunsol Choi. 2022. How do we answer complex questions: Discourse structure of long-form answers. In Proceedings of the 60th Annual Meeting of the Association for Compu- tational Linguistics (Volume 1: Long Papers), pages 3556–3572, Dublin, Ireland. Association for Compu- tational Linguistics. Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, and Colin Raffel. 2021. mT5: A massively multilingual pre-trained text-to-text transformer. In Proceedings of the 2021 Conference of the North American Chap- ter of the Association for Computational Linguistics: Human Language Technologies, pages 483–498, On- line. Association for Computational Linguistics. Shunyu Yao, Howard Chen, John Yang, and Karthik Narasimhan. 2022. Webshop: Towards scalable real- world web interaction with grounded language agents. arXiv preprint arXiv:2207.01206. Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, Yusheng Su, Haozhe Ji, Jian Guan, et al. 2021a. Cpm: A large-scale generative chinese pre-trained language model. AI Open, 2:93–99. Zhuosheng Zhang, Hanqing Zhang, Keming Chen, Yuhang Guo, Jingyun Hua, Yulong Wang, and Ming Zhou. 2021b. Mengzi: Towards lightweight yet inge- nious pre-trained models for chinese. arXiv preprint arXiv:2110.06696. # Appendices # A Implementation Details of the Interface Our interface includes two components: an API back end and a website front end. # A.1 API Back End The API backend implements three APIs with dif- ferent functions: (1) search, which receives queries from users and returns search results recommended by Bing; (2) extract, which receives a URL and returns the text-only contents of the corresponding web page; (3) record, which receives the actions conducted by agents and stores them in a database. Search API. The search API is based on Bing API. When it receives keywords from users, it calls Bing API to search for relevant results and con- verts them into the format we specify. Each result consists of a title, the link to the page, and a brief summary of the page contents. To ensure the origi- nality of the answers generated during annotation, we have implemented a filter in the search API to exclude results from certain websites (e.g., Red- dit forums). This is necessary because some of the questions are sourced from websites that may appear in search results. Extract API. The contents of web pages often include huge quantities of layout information and multimedia that is inappropriate to display directly to agents and is meaningless for our task. There- fore, we use a third-party tool1 to extract the simpli- fied text-only contents of web pages. This ensures that only clean and meaningful text will be pre- sented to the users. Record API. Actions conducted by users are recorded in the website front end, when users finish the annotation process of a question, the front end will call this Record API, and the detailed action in- formation and meaningful observations during web search will be uploaded and stored in our database. # A.2 Website Front End The website front end is designed as a graphic user interface for human annotators, which supports the search mode and the browsing two modes: mode. Each time an action is performed, it will be recorded and the corresponding changes will be rendered in our website and displayed to the users. 1https://github.com/mozilla/ readability In the search mode, the window dis- Window. plays the searched results returned by our API back end. We present at most three links at a time in each window, and the Scroll action can be used to access other links. In the browsing mode, when clicking a specific link, Load Page action is trig- gered and the front end will call the extract API and display the text-only contents of the web page. The length of content in each window is limited up to 500 Chinese characters, and the Scroll action can be used to access more content. In the main paper, we illustrate an example for the search mode of our interface, here we present the example for the browsing mode in Figure 6. In addition, we also display the existing supporting facts and the remaining number of actions for ease of human annotation. Actions. Once an action is performed, we record the current state of the interface, which includes the content displayed in the window, the current query issued, the existing collected supporting facts, the remaining number of actions, etc. We also record the specific information about the current action, for instance, Search <query> includes the con- tent of the query, Load Page <idx> includes all the detailed information about a web page, and Quote <content> includes the consecu- tive sentences selected by the user. It should be noted that the action Merge is specially designed for extracting a supporting fact that crosses the boundary of two windows in the browsing mode. For instance, the user can perform Quote <content1>, Scroll Down, Quote <content2>, and Merge to get one supporting fact, which is concatenated by both content1 and content2. Besides, we also implement (1) the Undo action, which supports revoking the last action performed, and (2) the Reset action, which terminates the current annotation and starts a new one. Both ac- tions will not be recorded since they do not belong to meaningful web search behaviors. # B Annotation Principle Below we present the annotation principles for web search, supporting fact extraction, and question an- swering. These principles are part of our annotation guides, which are sent to our contractors before an- notation. The original version of the following is written in Chinese, and we have translated it into English. Question | ZHRBEt+A? CBR AA? What are crop circles? How are they made? Q Query | SAARI AZAL? How do crop circles form? Window (browsing mode) ZARB SREZAL, BIRPRAN BIER ED RAMEN ARR. BA-BDAUA, Pit 4 (a) *) Undo Reset + 173 33 Quote J Merge Fact #1 2023-01-21 19:59:00 ZARB ERR BAAEBRERZAW EE. RENSR BURAVENESHRAUA, ZARB ANNE... FHLB... crop circle refers to a geometric pattern produced by flattening crops .. (ts Crop circles refer to geometric patterns produced by flattening crops by some unknown force on wheat fields. A considerable number of people believe that the so-called crop circles are just some people's prank. Fact #2 2023-01-21 20:05:12 < content of Fact #2> After 17 years of investigation and research, British scientist Andrew believes that 80% of the crop circles are man-made... € Go Back Number of remaining actions (85/100) © Finish Figure 6: An example of browsing mode of our interface. the query, with higher-ranked results being more relevant. If the top-ranked results for a particular search do not align with the user’s needs, it may not be productive to continue scrolling through the results to find relevant information. Instead, it is more efficient to issue a new query to reduce the number of unnecessary search actions. # B.1 Web Search Principle Look for Relevant Information. In the search process, it is important to ensure that the content being searched is closely related to the question at hand. During the labeling process, users may encounter various concepts that are related to the question but may not be central to the main idea. These peripheral concepts should be ignored in the search. For instance, when searching for informa- tion about “the principle of the constant speed of light”, it is possible to come across the concept of “Lorentz transformation”, which is related to the topic but only tangentially. As such, it is not neces- sary to include a detailed explanation of “Lorentz transformation”. # B.2 Supporting Fact Extraction Principle Find Diverse Relevant Facts. The supporting facts should contain information that is relevant to the original question. When possible, it is gener- ally more effective to extract supporting facts from diverse sources, while ensuring that the content re- mains highly relevant to the original question. It is important to avoid duplicating summaries of the same content from different sources, as this does not contribute to answering the question. Send Simple Queries. Search engines are often less effective when the question being asked is long and complex. In such cases, it is advisable to sim- plify and refine the main question or keywords to improve the chances of finding relevant informa- tion and reduce the number of unnecessary search actions. For example, instead of searching for the question “I have a question that bothers me a lot, why do most crustaceans / seafood turn from light gray to red / orange when heated?”, it would be more effective to simplify it to “why does seafood change color when heated?”. This ensures the sim- plicity of the queries, making it more likely to find relevant information. Avoid Recording Fragmentary Facts. The ex- tracted supporting fact should contain complete and coherent information. It is important to avoid intercepting sentences with incomplete semantics or taking them out of context, as this can alter the meaning of the supporting fact. In addition, please ensure the integrity of the supporting fact by in- cluding all relevant information and expressing it in a coherent manner. Ensure the Factual Accuracy. It is important to summarize information from trusted sources when- ever possible. This helps ensure the reliability of the information being used. You can also judge the Avoid Unnecessary Search. Search engines typ- ically rank web pages based on their relevance to factual accuracy of a supporting fact by comparing it with other searched results. # B.3 Answer Principle A good long-form answer is typically well- researched, well-written, and provides a thorough and detailed response. It should be well-organized and easy to read, with clear and concise language that is appropriate for the intended audience. Ad- ditionally, a good answer should be objective and unbiased, presenting multiple viewpoints on the topic if applicable. Coherence and Relevance. Coherence refers to the overall logical consistency and clarity of the answer. The desired answer should have a clear structure, with each paragraph building upon the previous one and contributing to the overall argu- ment. The ideas presented should flow smoothly and be easy to follow. Relevance means the extent to which the answer addresses the original question. The desired answer should stay on topic, providing information that is directly relevant to the question. It should not include unnecessary or tangential in- formation. Together, coherence and relevance help guarantee that the answer is easy to understand and stays focused on the main topic, making it more useful and informative for the reader. Objectivity. The content of the answer should be based on the information obtained during the search process. The desired answer should present information and viewpoints in an unbiased man- ner, without expressing personal opinions or pref- erences. While the annotation process inevitably involves subjectivity, the questions are relatively straightforward and it should not be difficult to maintain a degree of objectivity. Please be neutral and fair, and present multiple sides of an issue if applicable. Conciseness. There is no specific word count requirement for answers, but it is important to pro- vide concise, comprehensive, and in-depth answers that include necessary auxiliary information. It is generally best to avoid extremely long or short answers. In addition, the sentences in the answer should be concise and clear and should avoid re- dundancy. For example, the question “How toxic is barium chloride?” should not be answered simply with “very toxic”. Instead, a more detailed descrip- tion of the toxicity of barium chloride, including the poisoning dose, poisoning symptoms, and poi- soning mechanism, would be more informative and useful. It is important to provide a well-rounded and thorough answer to the question, rather than just a brief or overly general response. Normative. It is important to answer questions in written language, as this can help make the answer more formal. Annotators should avoid using irreg- ular or unconventional expressions that may not be understood by everyone. Typos or grammatical errors are not allowed. # C More Details for Data Collection We limit our annotators and quality inspectors to native Chinese speakers. We make sure all our annotators are fairly compensated by the market price. Question Creation. Chinese QA forums, such as Zhihu and Baidu Zhidao, are known for their abundance of long-form questions. However, when these questions are utilized as direct queries on Bing, users can often access multiple websites that contain well-organized answers, thus making the web search process less challenging. Such an issue is not mitigated even if we block the source from Zhihu and Baidu Zhidao. In view of this, we strive to annotate new open-ended questions that have not been answered on Chinese QA forums. Following ELI5 (Fan et al., 2019), we turn to creating questions from Reddit forums2 as an alter- native. We closely follow the way ELI5 collects the source questions. After collection, we engage annotators to refer to these questions and then ask new questions in Chinese. This way significantly improves the productivity of question creation. For quality control, our quality inspectors would check whether the created question is meaningful, semantically coherent, comprehensible, and reason- able. Only those questions that satisfy the above requirements would be retained. In addition, we also remove the questions that are politically sen- sitive. In total, 22.4% newly created questions are discarded. Web Search and Answer Annotation. Before annotation, we provide our annotators with detailed annotation guidance. They got paid based on the number of instances they annotate instead of the time spent during annotation. Note for answer an- notation, we did not require annotators to use all 2https://www.reddit.com/r/ explainlikeimfive Go Back Scroll Up Finish Merge Quote Search LOAD PAGE <1> Load Page <2> Load Page <3> Scroll Down Figure 7: Proportion of different pre-defined actions in our WebCPM. the collected facts when composing the answer but asked them to record which facts are leveraged in their answer. Proportion for Different Actions. We record the proportion of different pre-defined actions in our collected dataset in Figure 7. As can be seen, Scroll Down, Quote, and Search are the most frequently used actions. The proportion of Load Page <1> is larger than those of Load Page <2> and Load Page <3>. This is be- cause search engines rank search results based on their relevance to the query. Humans tend to visit the links according to the order recommended by search engines. If humans have collected enough supporting facts on the first page or find it to be irrelevant, they probably would not continue brows- ing other web pages of the current query. # D Details for the PLMs Evaluated We select 6 series of representative and publicly available generative PLMs that support Chinese. For all the models, we use them for their intended uses. In the following, we give a brief introduction to them: mT5 (Xue et al., 2021) is a multilingual encoder- decoder PLM with a general-purpose text-to-text format. Its pre-training data mC4 (Xue et al., 2021) covers 101 languages collected from the public Common Crawl web scrape. mT5 achieves su- perior performance in various multilingual bench- marks. mT0 (Muennighoff et al., 2022) is a multi-task fine-tuned version of Google’s mT5. The model attained strong zero-shot performance and cross- lingual generalization ability. Through explicit multi-task learning, a variety of language capabili- ties are enhanced through knowledge transfer; in- evitably, some capabilities, which are not required by the trained tasks, might have been impaired. Mengzi-T5 (Zhang et al., 2021b) is a power- ful Chinese encoder-decoder PLM that achieved state-of-the-art results on the CLUE benchmark. Instead of chasing a larger scale, the authors turn to developing lightweight yet more powerful models for easier deployment. Mengzi-T5 was trained on Chinese Wikipedia, Chinese News, and Common Crawl and the total size of the pre-training corpus is 300G. mBART (Liu et al., 2020) is a multi-lingual variant of BART, which is a sequence-to-sequence denoising auto-encoder. mBART is pre-trained on large-scale monolingual corpora with the BART (Lewis et al., 2020) pre-training objective. The model performs extremely well in machine translation tasks and can be generalized to lan- guages that are not in the pre-training corpora. C-BART (Shao et al., 2021) is the Chinese ver- sion of BART. Compared with mBART, the model was pre-trained only on a Chinese corpus. The model shows superior performance on keyword recognition tasks evaluated by the Rouge-L metric. CPM3 is the generative pre-trained model series provided by OpenBMB4. We choose three PLMs CPM2.6B (CPM-1 (Zhang et al., 2021a)), CPM7B (CPM-Live), and CPM10B (CPM-Ant) with in- creasing model sizes. The three models are trained with increasingly larger sizes of data and training computations. Training Details. For each model, we follow the configuration recommended by the original papers. During training, we select the model checkpoint with the best performance on the development set and evaluate it on the test set. The maximum se- quence length is 2048 for mT0BASE, mT5BASE, and Mengzi-T5BASE, 1024 for mBARTLARGE, 512 for C-BARTLARGE, and 3072 for CPM. We truncate the input sequence if it exceeds the maxi- mum sequence length of a PLM. # E Design Differences between WebGPT and WebCPM Interface. Our interface supports slightly differ- ent actions than WebGPT. To begin with, we re- move 1 actions defined by WebGPT: Find in 3https://github.com/OpenBMB/CPM-Live 4https://live.openbmb.org/en/ Page: <text>, which supports finding the next occurrence of <text> and scrolling to it. In our pilot studies, even if we give the annotators the options for this action, our annotators seldom execute them. Considering that it may be hard for our model to learn those extremely low-frequency actions, we do not include both actions in the final list of our actions. Secondly, we modify the functionalities of the Scroll actions in WebGPT. Specifically, We- bGPT merged any consecutive Scroll Down and Scroll Up actions made by humans into new actions Scroll Down <?> and Scroll Up <?>, where ? is the number of consecutive actions. These new actions are utilized by their models instead of the original Scroll Down and Scroll Up actions. Therefore, there exists a gap between what humans actually perform and what the model is allowed to execute. We contend that this gap could result in problems for behavior cloning. Specifically, humans perform consecutive Scroll Down actions because after each action, they carefully check the current window and find nothing useful. However, when merging consecu- tive actions, the intermediate observations would not be shown to the model, which makes decision making even more difficult. Finally, we also implement a new Merge action to support merging two supporting facts into one. As mentioned before, Merge is specially designed for extracting a supporting fact that crosses the boundary of two windows. This action is critical to avoid recording fragmentary supporting facts. As shown in Figure 7, Merge takes up a rela- tively large (5.4%) percentage among all the ac- tions, which is frequently executed by our anno- tators. This action makes it possible for our an- notators to extract extremely long sequences as supporting facts. Framework. WebGPT does not disclose the im- plementation details for both interactive web search and information synthesis (i.e., BC model in the original paper). In view of this, we propose our own framework from scratch, with several design choices not mentioned by WebGPT: We decompose the web search process into 3 dis- tinct sub-tasks, i.e., action prediction, search query generation, and supporting fact extraction. We train 3 modules for each sub-task, respectively. This de- composition allows us to evaluate three modules in isolation and gain a deeper understanding of the strengths and weaknesses of each module. Fur- thermore, it allows for flexibility in the system, as different modules can be updated or replaced independently. For our synthesis model, instead of directly fine- tuning on the (question, supporting fact, answer) data, we explore (1) how to teach the model to ignore irrelevant facts (§ 6.3). We achieve this goal by introducing noisy facts into the training data to explicitly force the model to ignore noisy facts, and (2) how to generate novel contents beyond the collected facts (appendix F.1). We corrupt the training data by deleting partial supporting facts and forcing the model to generate novel content based on its pre-trained knowledge. Evaluation. WebGPT only evaluates the the whole pipeline through human evaluation. In ad- dition to the holistic pipeline evaluation (§ 6.2), we also evaluate each individual module of our pipeline (§ 6.1). To the best of our knowledge, this is the first work to decompose interactive web search into action prediction, search query genera- tion, and supporting fact extraction, and design the evaluation metrics for the three sub-tasks. It should be noted that holistic evaluation requires manual inspection, which is time-consuming despite being more accurate. Additionally, the holistic evalu- ation can only be conducted through interaction with the interface, whereas the individual sub-task evaluation can be conducted locally (by feeding the ground truth t of the test data to each mod- ule). As such, individual sub-task evaluation is more flexible to implement, making it easier for hyper-parameter tuning, thus accelerating the de- velopment and iteration of the QA system. Besides, individual evaluation is more fine-grained, which helps us better understand the contribution of each part of the pipeline. Analysis. In addition to evaluating the LFQA per- formance of our pipeline, we also conduct an in- depth analysis to understand the contribution of core design elements of our framework. In § 6.3, we conduct ablation studies for the search model and the synthesis model, and a case study for the query module. We also show that our model indeed acquires humanoid behaviors when interacting with the search engine. p 0.1 0.2 0.3 0.4 0.5 1.0 NOVELTY Length 0.06 256 0.12 216 0.16 206 0.29 201 0.41 193 0.83 126 Table 4: Results when the training data of synthesis model is corrupted with different p. We report two met- rics for the generated sequence: NOVELTY and Length. # F Additional Experiments and Analyses # F.1 Generating Novel Contents v.s. Copying Supporting Facts Another fascinating research question of our syn- thesis model is whether it could generate novel content based on its pre-trained knowledge. This ability is important especially when the collected facts are insufficient or fragmentary. Considering that copying the supporting facts and generating novel contents are often contradictory to each other, here we propose a method to flexibly strike a bal- ance between both. Framework. Specifically, we propose another way to corrupt the training data of the synthesis model. We split each collected fact into multiple sub-sentences according to punctuation and ran- domly erase part of these sub-sentences. We set a hyper-parameter p [0, 1], which denotes the prob- ability of erasing a sub-sentence. A higher p means more sub-sentences would be removed. After that, we concatenate the remaining sub-sentences into a new fact keeping the original order. Finally, we op- timize the model to generate the human-annotated answer conditioned on the corrupted facts, i.e., maximizing: P(Answer|Q0, CORRUPT{f1, ..., fN}). Since the corrupted facts are fragmentary, the model learns to reconstruct those missing sub- sentences relying on its pre-trained knowledge. Settings. We experiment with CPM7B and fol- low most of the settings in § 6.1. We test when different p is applied to corrupt the train- ing data. Ideally, a higher p encourages the model to generate more novel content instead of copy- ing the supporting facts. Specifically, we choose p from , where 1.0 means the model sees no supporting facts but is required to generate all the tokens in the annotated answer. During the evaluation, we feed the original intact supporting facts to the trained synthesis model. For evaluation metrics, we follow Welleck et al. (2019) to test the percentage of n-grams in the generated sequence that do not exist in the sup- porting facts, i.e., NOVELTYn = |unique generated n-grams| |total n-grams in supporting facts| . The final novelty metric is defined as the average of NOVELTY2, NOVELTY3, and NOVELTY4, i.e., NOVELTY = 1 3 (NOVELTY2 + NOVELTY3 + NOVELTY4). Besides NOVELTY, we also record the number of generated tokens. Results. We derive from the results listed in Ta- ble 4 that: (1) with p increasing, the metric NOV- ELTY constantly becomes larger. This demonstrates that by deleting more content of the supporting facts during training, we gradually encourage the synthesis model to generate novel content based on its pre-trained knowledge, instead of copying the supporting facts. However, it should also be noted that the generated information that is not included in the collected facts may suffer from poor factual accuracy. We expect future work to mitigate this issue; (2) in addition, with p increasing, the gener- ated sequence tends to be shorter. This shows that only relying on the synthesis model cannot produce diverse, abundant, and informative contents, which emphasizes the importance of information retrieval in LFQA. # G Future Explorations We expect future works to explore the following directions: Efficient and Scalable Use. Despite the fasci- nating feature of interactive web search, such a process is inherently slower to execute than the conventional non-interactive retrieval process of open-domain QA. In this regard, we encourage further explorations in reducing the latency of our pipeline. Possible solutions include improving the speed and memory usage of the PLM. Extension to Other Languages and Domains. It would be interesting to extend the current ap- proach to other languages beyond Chinese. Con- sidering that the search engine supports multiple languages, our interface can be easily adapted to building benchmarks for other languages. Leveraging the Reference Information. In ad- dition to the annotated answers, we also require the annotators to record which supporting facts are referenced and leveraged in their answers. How- ever, in this paper, we do not utilize this informa- tion when training our synthesis model. Intuitively, such information could guide the synthesis model to better organize existing supporting facts in a more coherent way, and to improve its ability in selecting important information and ignoring irrel- evant noises. Diversify the Interactive Elements. In this pa- per, we focus on supporting the mainstream web search actions for our users. It would interesting to explore incorporating more interactive elements into the interface, such as allowing the users to provide feedback on the retrieved information and supporting multimedia information retrieval. How- ever, more actions also increase the difficulty of behavior cloning to a certain degree. Improving Model Behavior from Human Feed- backs. WebGPT has demonstrated it is promising to use reinforcement learning from human feedback (RLHF) (Stiennon et al., 2020) to improve the qual- ity of the generated answers. RLHF can also be used for improving the search model’s web search behavior, and make it collect more diverse and rel- evant supporting facts. Our provided environment can be utilized by researchers to study RLHF in the future.
Title: Data Augmentation for BERT Fine-Tuning in Open-Domain Question Answering: Summary: Recently, a simple combination of passage retrieval using off-the-shelf IR techniques and a BERT reader was found to be very effective for question answering directly on Wikipedia, yielding a large improvement over the previous state of the art on a standard benchmark dataset. In this paper, we present a data augmentation technique using distant supervision that exploits positive as well as negative examples. We apply a stage-wise approach to fine tuning BERT on multiple datasets, starting with data that is "furthest" from the test data and ending with the "closest". Experimental results show large gains in effectiveness over previous approaches on English QA datasets, and we establish new baselines on two recent Chinese QA datasets. # Data Augmentation for BERT Fine-Tuning in Open-Domain Question Answering # Wei Yang,1,2∗ Yuqing Xie,1,2∗ Luchen Tan,2 Kun Xiong,2 Ming Li,1,2 and Jimmy Lin1,2 1 David R. Cheriton School of Computer Science, University of Waterloo 2 RSVP.ai # Abstract Recently, a simple combination of passage re- trieval using off-the-shelf IR techniques and a BERT reader was found to be very effective for question answering directly on Wikipedia, yielding a large improvement over the previ- ous state of the art on a standard benchmark dataset. In this paper, we present a data aug- mentation technique using distant supervision that exploits positive as well as negative ex- amples. We apply a stage-wise approach to fine tuning BERT on multiple datasets, starting with data that is “furthest” from the test data and ending with the “closest”. Experimental results show large gains in effectiveness over previous approaches on English QA datasets, and we establish new baselines on two recent Chinese QA datasets. # 1 Introduction BERT (Devlin et al., 2018) represents the latest re- finement in a series of neural models that take advantage of pretraining on a language modeling task (Peters et al., 2018; Radford et al., 2018). Re- searchers have demonstrated impressive gains in a broad range of NLP tasks, from sentence classifi- cation to sequence labeling. Recently, Yang et al. (2019) showed that combining a BERT-based reader with passage retrieval using the Anserini IR toolkit yields a large improvement in question answering directly from a Wikipedia corpus, mea- sured in terms of exact match on a standard bench- mark (Chen et al., 2017). Interestingly, the approach of Yang et al. (2019) represents a simple method to combining BERT with off-the-shelf IR. In this paper, we build on these initial successes to explore how much fur- ther we can push this simple architecture by data augmentation, taking advantage of distant supervi- sion techniques to gather more and higher-quality training data to fine tune BERT. Experiments show that, using the same reader model as Yang et al. (2019), our simple data-augmentation techniques yield additional large improvements. To illustrate the robustness of our methods, we also demon- strate consistent gains on another English QA dataset and present baselines for two additional Chinese QA datasets (which have not to date been evaluated in an “end-to-end” manner). In addition to achieving state-of-the-art results, we contribute important lessons on how to lever- age BERT effectively for question answering. First, most previous work on distant supervision focuses on generating positive examples, but we show that using existing datasets to identify neg- ative training examples is beneficial as well. Sec- ond, we propose an approach to fine-tuning BERT with disparate datasets that works well in practice: our heuristic is to proceed in a stage-wise manner, beginning with the dataset that is “furthest” from the test data and ending with the “closest”. # 2 Background and Related Work In this paper, we tackle the “end-to-end” vari- ant of the question answering problem, where the system is only provided a large corpus of arti- cles. This stands in contrast to reading compre- hension datasets such as SQuAD (Rajpurkar et al., 2016), where the system works with a sin- gle pre-determined document, or most QA benchmarks today such as TrecQA (Yao et al., 2013), WikiQA (Yang et al., 2015), and MS- MARCO (Bajaj et al., 2016), where the system is provided a list of candidate passages to choose from. This task definition, which combines a strong element of information retrieval, traces back to the Text Retrieval Conferences (TRECs) in the late 1990s (Voorhees and Tice, 1999), but there is a recent resurgence of interest in this for- mulation (Chen et al., 2017). # ∗ equal contribution The roots of the distant supervision techniques we use trace back to at least the 1990s (Yarowsky, 1995; Riloff, 1996), although the term had not yet been coined. Such techniques have recently be- come commonplace, especially as a way to gather large amounts of labeled examples for data-hungry neural networks and other machine learning algo- rithms. Specific recent applications in question an- swering include Bordes et al. (2015), Chen et al. (2017), Lin et al. (2018), as well as Joshi et al. (2017) for building benchmark test collections. # 3 Approach In this work, we fix the underlying model and fo- cus on data augmentation techniques to explore how to best fine-tune BERT. We use the same exact setup as the “paragraph” variant of BERT- serini (Yang et al., 2019), where the input corpus is pre-segmented into paragraphs at index time, each of which is treated as a “document” for re- trieval purposes. The question is used as a “bag of words” query to retrieve the top k candidate paragraphs using BM25 ranking. Each paragraph is then fed into the BERT reader along with the original natural language question for inference. Our reader is built using Google’s reference imple- mentation, but with a small tweak: to allow com- parison and aggregation of results from different segments, we remove the final softmax layer over different answer spans; cf. (Clark and Gardner, 2018). For each candidate paragraph, we apply inference over the entire paragraph, and the reader selects the best text span and provides a score. We then combine the reader score with the retriever score via linear interpolation: S = (1 − µ) · SAnserini + µ · SBERT, where µ ∈ [0, 1] is a hy- perparameter (tuned on a training sample). is One major shortcoming with BERTserini that Yang et al. (2019) only fine tune on SQuAD, which means that the BERT reader is exposed to an impoverished set of examples; all SQuAD data come from a total of only 442 documents. This contrasts with the diversity of paragraphs that the model will likely encounter at inference time, since they are selected from potentially millions of articles. The solution to this problem, of course, is to fine tune BERT with the types of paragraphs it is likely to see at inference time. Unfortunately, such data does not exist for modern QA test collections. Distant supervision can provide a bridge. Starting from a source dataset comprising question–answer pairs (for example, SQuAD), we can create training data for a specific corpus by us- ing passage retrieval to fetch paragraphs from that corpus (with the question as the query) and then searching (i.e., matching) for answer instances in those paragraphs. A hyperparameter here is n, the number of candidates we examine from passage retrieval. Larger values of n will lead to more training examples, but as n increases, so does the chance that a paragraph will spuriously match the answer without actually answering the question. The above technique allows us to extract pos- itive training examples, but previous work has shown the value of negative examples, specifically for QA (Zhang et al., 2017). To extract negative examples, we sample the top n candidates from passage retrieval for paragraphs that do not contain the answer, with a ratio of d:1. That is, for every positive example we find, we sample d negative examples, where d is also a hyperparameter. Note that these negative examples are also noisy, since they may in fact contain an alternate correct (or acceptable) answer to the question, one that dif- fers from the answer given in the source dataset. Thus, given a corpus, we can create using dis- tant supervision a new dataset that is specifically adapted to a particular passage retrieval method. For convenience, we refer to training data gath- ered using this technique that only contain positive examples as DS(+) and use DS(±) to refer to the additional inclusion of negative examples. Next, we have a design decision regarding how to fine tune BERT using the source QA pairs (SRC) and the augmented dataset using distant su- pervision (DS). There are three possibilities: SRC + DS: Fine tune BERT with all data, grouped together. In practice, this means that the source and augmented data are shuffled together. DS → SRC: Fine tune the reader on the aug- mented data and then the source dataset. SRC → DS: Fine tune the reader on the source dataset and then the augmented data. Experiment results show that of the three choices above, the third option is the most effective. More generally, when faced with multiple, qualitatively- different datasets, we advocate a stage-wise fine- tuning strategy that starts with the dataset “fur- thest” to the task at hand and ending with the dataset “closest”. Another way to think about using different datasets is in terms of a very simple form of trans- SQuAD TriviaQA CMRC DRCD Train Test 87,599 10,570 87,622 11,313 10,321 3,351 26,936 3,524 DS(+) DS(±) 118,406 710,338 264,192 789,089 10,223 71,536 41,792 246,604 Table 1: Number of examples in each dataset. A exam- ple means a paragraph-question pair. fer learning. The stage-wise fine-tuning strategy is in essence trying to transfer knowledge from la- beled data that is not drawn from the same distri- bution as the test instances. We wish to take ad- vantage of transfer effects, but limit the scope of erroneous parameterizations. Thus it makes sense not to intermingle qualitatively different datasets, but to fine tune the model in distinct stages. # 4 Experimental Setup To show the generalizability of our data aug- mentation technique, we conduct experiments on two English datasets: SQuAD (v1.1) and Trivia- QA (Joshi et al., 2017). For both, we use the 2016-12-21 dump of English Wikipedia, follow- ing Chen et al. (2017). We also examine two Chinese datasets: CMRC (Cui et al., 2018) and DRCD (Shao et al., 2018). For these, we use the 2018-12-01 dump of Chinese Wikipedia, to- kenized with Lucene’s CJKAnalyzer into over- lapping bigrams. We apply hanziconv1 to trans- form the corpus into simplified characters for CMRC and traditional characters for DRCD. Following Yang et al. (2019), to evaluate an- swers in an end-to-end setup, we disregard the paragraph context from the original datasets and use only the answer spans. As in previous work, exact match (EM) score and F1 score (at the token level) serve as the two primary evaluation metrics. In addition, we compute recall (R), the fraction of questions for which the correct answer appears in any retrieved paragraph; to make our results com- parable to Yang et al. (2019), Anserini returns the top k = 100 paragraphs to feed into the BERT reader. Note that this recall is not the same as the token-level recall component in the F1 score. Statistics for the datasets are shown in Table 4.2 1https://pypi.org/project/hanziconv/0.2.1/ 2Note the possibly confusing terminology: for SQuAD (as well as the other datasets), what we use for test is actually the publicly-available development set (same as previous work). For data augmentation, based on preliminary experiments, we find that examining n = 10 can- didates from passage retrieval works well, and we further discover that effectiveness is insensitive to the amount of negative samples. Thus, we elim- inate the need to tune d by simply using all pas- sages that do not contain the answer as negative examples. The second block of Table 4 shows the sizes of the augmented datasets constructed using our distant supervision techniques: DS(+) contains positive examples only, while DS(±) in- cludes both positive and negative examples. There are two additional characteristics to note about our data augmentation techniques: The most salient characteristic is that SQuAD, CMRC, and DRCD all have source answers drawn from Wikipedia (English or Chinese), while TriviaQA includes web pages as well as Wikipedia. There- fore, for the first three collections, the source and augmented datasets share the same docu- ment genre—the primary difference is that data augmentation increases the amount and diver- sity of answer passages seen by the model dur- ing training. For TriviaQA, however, we con- sider the source and augmented datasets as coming from different genres (noisy web text vs. higher the quality Wikipedia articles). TriviaQA augmented dataset is also much larger— suggesting that those questions are qualitatively different (e.g., in the manner they were gathered). These differences appear to have a substantial im- pact, as experiment results show that TriviaQA be- haves differently than the other three collections. For model training, we begin with the BERT- Base model (uncased, 12-layer, 768-hidden, 12- heads, 110M parameters), which is then fine-tuned using the various conditions described in the pre- vious section. All inputs to the model are padded to 384 tokens; the learning rate is set to 3 × 10−5 and all other defaults settings are used. # 5 Results Our main results on SQuAD are shown in Table 2. The row marked “SRC” indicates fine tuning with SQuAD data only and matches the BERTserini condition of Yang et al. (2019); we report higher scores due to engineering improvements (primar- ily a Lucene version upgrade). As expected, fine tuning with augmented data improves effective- ness, and experiments show that while training with positive examples using DS(+) definitely Model EM F1 R Dr.QA (Chen et al., 2017) Dr.QA + Fine-tune Dr.QA + Multitask R3 (Wang et al., 2017) Kratzwald and Feuerriegel (2018) Par. R. (Lee et al., 2018) Par. R. + Answer Agg. Par. R. + Full Agg. MINIMAL (Min et al., 2018) 27.1 28.4 29.8 29.1 29.8 28.5 28.9 30.2 34.7 - - - 37.5 - - - - 42.5 77.8 - - - - 83.1 - - 64.0 BERTserini (Yang et al., 2019) 38.6 46.1 85.9 SRC DS(+) DS(±) SRC + DS(±) DS(±) → SRC SRC → DS(±) 41.8 44.0 48.7 49.5 51.4 56.5 85.9 85.9 85.9 45.7 47.4 50.2 53.5 55.0 58.2 85.9 85.9 85.9 Table 2: Results on SQuAD helps, an even larger boost comes from leverag- ing negative examples using DS(±). In both these cases, we only fine tune BERT with the augmented data, ignoring the source data. What if we use the source data as well? Re- sults show that “lumping” all training data to- gether (both the source and augmented data) to fine tune BERT is not the right approach: in fact, the SRC + DS(±) condition performs worse than just using the augmented data alone. Instead, disparate datasets should be leveraged using the stage-wise fine-tuning approach we propose, ac- cording to our heuristic of starting with the dataset that is “furtherest” away from the test data. That is, we wish to take advantage of all available data, but the last dataset we use to fine tune BERT should be “most like” the test data the model will see at infer- ence time. Indeed, this heuristic is borne out em- pirically, as SRC → DS(±) yields another boost over using DS(±) only. Further confirmation for this heuristic comes from an alternative where we switch the order of the stages, DS(±) → SRC, which yields results worse than DS(±) alone. We note that our best configuration beats BERTserini, the previous state of the art, by over ten points. Note that recall in all our conditions is the same since we are not varying the passage retrieval algo- rithm, and in each case Anserini provides exactly the same candidate passages. Improvements come solely from a better BERT reader. Results on TriviaQA are shown in Table 3. With just fine tuning on the source dataset, we obtain a Model R3 (Wang et al., 2017) DS-QA (Lin et al., 2018) Evidence Agg. (Wang et al., 2018) EM F1 47.3 48.7 50.6 53.7 56.3 57.3 SRC DS(+) DS(±) SRC + DS(±) DS(±) → SRC SRC → DS(±) 51.0 48.2 54.4 56.3 53.6 60.2 53.1 49.8 53.7 58.6 55.9 59.3 R - - - 83.7 83.7 83.7 83.7 83.7 83.7 Table 3: Results on TriviaQA score that is only slightly above the previous state of the art (Wang et al., 2018). Interestingly, using only positive examples leads to worse effective- ness than just using the source dataset. However, fine tuning on both positive and negative examples leads to a three point boost in exact match score, establishing a new high score on this dataset. Experiments on fine tuning with both source and augmented data show the same pattern as with SQuAD: stage-wise tuning is more effective than just combining datasets, and tuning should pro- ceed in the “furthest to closest” sequence we pro- pose. While data augmentation no doubt helps (beats the source-only baseline), for this dataset the highest effectiveness is achieved by disregard- ing the source dataset completely; that is, DS(±) beats SRC → DS(±). We attribute this behav- ior to the difference between TriviaQA and the other datasets discussed in Section 4: it appears that gains from transfer effects are outweighed by genre mismatch. Results on the Chinese datasets are shown in Ta- ble 4. To our knowledge, they have only been eval- uated as reading comprehension tests, not in the “end-to-end” setup that we tackle here (requiring retrieval from a sizeable corpus). Although there is no previous work to compare against, our results provide a strong baseline for future work. Experiment results on the two Chinese datasets support the same conclusions as SQuAD: First, we see that data augmentation using distant supervi- sion is effective. Second, including both positive and negative training examples is better than hav- ing positive examples only. Third, when lever- aging multiple datasets, our “furthest to closest” heuristic for stage-wise tuning yields the best re- sults. Since the source datasets also draw from (Chinese) Wikipedia, we benefit from fine tuning with both source and augmented data. Model EM F1 R CMRC 44.5 SRC 45.5 DS(+) DS(±) 48.3 SRC + DS(±) 49.0 DS(±) → SRC 45.6 SRC → DS(±) 49.2 60.9 61.1 63.9 64.6 61.9 65.4 86.5 86.5 86.5 86.5 86.5 86.5 DRCD 50.7 SRC 50.5 DS(+) DS(±) 53.2 SRC + DS (±) 55.4 DS(±) → SRC 53.4 SRC → DS(±) 54.4 65.0 64.3 66.0 67.7 67.1 67.0 81.5 81.5 81.5 81.5 81.5 81.5 Table 4: Results on the two Chinese datasets: CMRC (top) and DRCD (bottom). # 6 Conclusions In this paper, we have further advanced the state of the art in end-to-end open-domain question an- swering using simple BERT models. We focus on data augmentation using distant supervision tech- niques to construct datasets that are closer to the types of paragraphs that the reader will see at in- ference time. Explained this way, it should not come as a surprise that effectiveness improves as a result. This work confirms perhaps something that machine learning practitioners already know too well: quite often, the best way to better results is not better modeling, but better data preparation. # References Payal Bajaj, Daniel Campos, Nick Craswell, Li Deng, Jianfeng Gao, Xiaodong Liu, Rangan Majumder, Andrew McNamara, Bhaskar Mitra, Tri Nguyen, Mir Rosenberg, Xia Song, Alina Stoica, Saurabh Ti- wary, and Tong Wang. 2016. MS MARCO: A hu- man generated MAchine Reading COmprehension dataset. arXiv:1611.09268. Antoine Bordes, Nicolas Usunier, Sumit Chopra, and Jason Weston. 2015. Large-scale sim- ple question answering with memory networks. arXiv:1506.02075. Danqi Chen, Adam Fisch, Jason Weston, and Antoine Bordes. 2017. Reading Wikipedia to answer open- domain questions. In Proceedings of the 55th An- nual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 1870– 1879. Christopher Clark and Matt Gardner. 2018. Simple and effective multi-paragraph reading comprehen- sion. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Vol- ume 1: Long Papers), pages 845–855. Yiming Cui, Ting Liu, Li Xiao, Zhipeng Chen, Wentao Ma, Wanxiang Che, Shijin Wang, and Guoping Hu. 2018. A span-extraction dataset for Chinese Ma- chine Reading Comprehension. arXiv:1810.07366. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. BERT: Pre-training of deep bidirectional transformers for language under- standing. arXiv:1810.04805. Mandar Joshi, Eunsol Choi, Daniel Weld, and Luke Zettlemoyer. 2017. TriviaQA: A large scale dis- tantly supervised challenge dataset for reading com- In Proceedings of the 55th Annual prehension. Meeting of the Association for Computational Lin- guistics (Volume 1: Long Papers), pages 1601–1611. Bernhard Kratzwald and Stefan Feuerriegel. 2018. Adaptive document retrieval for deep question an- swering. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Process- ing, pages 576–581. Jinhyuk Lee, Seongjun Yun, Hyunjae Kim, Miyoung Ko, and Jaewoo Kang. 2018. Ranking paragraphs for improving answer recall in open-domain ques- In Proceedings of the 2018 Con- tion answering. ference on Empirical Methods in Natural Language Processing, pages 565–569. Yankai Lin, Haozhe Ji, Zhiyuan Liu, and Maosong Sun. 2018. Denoising distantly supervised open-domain question answering. In Proceedings of the 56th An- nual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 1736– 1745. Sewon Min, Victor Zhong, Richard Socher, and Caim- ing Xiong. 2018. Efficient and robust question an- swering from minimal context over documents. In Proceedings of the 56th Annual Meeting of the As- sociation for Computational Linguistics (Volume 1: Long Papers), pages 1725–1735. Matthew Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, and Luke Zettlemoyer. 2018. Deep contextualized word rep- In Proceedings of the 2018 Confer- resentations. ence of the North American Chapter of the Associ- ation for Computational Linguistics: Human Lan- guage Technologies, Volume 1 (Long Papers), pages 2227–2237. Alec Radford, Karthik Narasimhan, Tim Salimans, and Ilya Sutskever. 2018. Improving language under- standing by generative pre-training. Technical re- port. Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, and Percy Liang. 2016. SQuAD: 100,000+ questions for machine comprehension of text. In Proceedings of the 2016 Conference on Empirical Methods in Nat- ural Language Processing, pages 2383–2392. Ellen Riloff. 1996. Automatically generating extrac- tion patterns from untagged text. In Proceedings of the Thirteenth National Conference on Artificial In- telligence, pages 1044–1049. Chih Chieh Shao, Trois Liu, Yuting Lai, Yiying Tseng, and Sam Tsai. 2018. DRCD: a Chinese machine reading comprehension dataset. arXiv:1806.00920. Ellen M. Voorhees and Dawn M. Tice. 1999. The TREC-8 Question Answering Track evaluation. In Proceedings of the Eighth Text REtrieval Conference (TREC-8), pages 83–106, Gaithersburg, Maryland. Shuohang Wang, Mo Yu, Xiaoxiao Guo, Zhiguo Wang, Tim Klinger, Wei Zhang, Shiyu Chang, Gerald Tesauro, Bowen Zhou, and Jing Jiang. 2017. R3: Reinforced reader-ranker for open-domain question answering. arXiv:1709.00023. Shuohang Wang, Mo Yu, Jing Jiang, Wei Zhang, Xiaoxiao Guo, Shiyu Chang, Zhiguo Wang, Tim Klinger, Gerald Tesauro, and Murray Camp- Evidence aggregation for answer bell. 2018. re-ranking in open-domain question answering. arXiv:1711.05116. Wei Yang, Yuqing Xie, Aileen Lin, Xingyu Li, Luchen Tan, Kun Xiong, Ming Li, and Jimmy Lin. 2019. End-to-end open-domain question answering with BERTserini. arXiv:1902.01718. Yi Yang, Wen-tau Yih, and Christopher Meek. 2015. WikiQA: A challenge dataset for open-domain ques- In Proceedings of the 2015 Con- tion answering. ference on Empirical Methods in Natural Language Processing, pages 2013–2018. Xuchen Yao, Benjamin Van Durme, Chris Callison- burch, and Peter Clark. 2013. Answer extraction as In Pro- sequence tagging with tree edit distance. ceedings of the 2013 Conference of the North Amer- ican Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 858–867. David Yarowsky. 1995. Unsupervised word sense dis- In Pro- ambiguation rivaling supervised methods. ceedings of the 33rd Annual Meeting of the Associa- tion for Computational Linguistics, pages 189–196. Haotian Zhang, Jinfeng Rao, Jimmy Lin, and Mark D. Smucker. 2017. Automatically extracting high- quality negative examples for answer selection in question answering. In Proceedings of the 40th An- nual International ACM SIGIR Conference on Re- search and Development in Information Retrieval (SIGIR 2017), pages 797–800.
Title: Reward Design with Language Models: Summary: Reward design in reinforcement learning (RL) is challenging since specifying human notions of desired behavior may be difficult via reward functions or require many expert demonstrations. Can we instead cheaply design rewards using a natural language interface? This paper explores how to simplify reward design by prompting a large language model (LLM) such as GPT-3 as a proxy reward function, where the user provides a textual prompt containing a few examples (few-shot) or a description (zero-shot) of the desired behavior. Our approach leverages this proxy reward function in an RL framework. Specifically, users specify a prompt once at the beginning of training. During training, the LLM evaluates an RL agent's behavior against the desired behavior described by the prompt and outputs a corresponding reward signal. The RL agent then uses this reward to update its behavior. We evaluate whether our approach can train agents aligned with user objectives in the Ultimatum Game, matrix games, and the DealOrNoDeal negotiation task. In all three tasks, we show that RL agents trained with our framework are well-aligned with the user's objectives and outperform RL agents trained with reward functions learned via supervised learning at ICLR 2023 # REWARD DESIGN WITH LANGUAGE MODELS Minae Kwon, Sang Michael Xie, Kalesha Bullard†, Dorsa Sadigh Stanford University, DeepMind† {minae, xie, dorsa}@cs.stanford.edu, ksbullard@deepmind.com† # ABSTRACT Reward design in reinforcement learning (RL) is challenging since specifying human notions of desired behavior may be difficult via reward functions or require many expert demonstrations. Can we instead cheaply design rewards using a natural language inter- face? This paper explores how to simplify reward design by prompting a large language model (LLM) such as GPT-3 as a proxy reward function, where the user provides a tex- tual prompt containing a few examples (few-shot) or a description (zero-shot) of the de- sired behavior. Our approach leverages this proxy reward function in an RL framework. Specifically, users specify a prompt once at the beginning of training. During training, the LLM evaluates an RL agent’s behavior against the desired behavior described by the prompt and outputs a corresponding reward signal. The RL agent then uses this reward to update its behavior. We evaluate whether our approach can train agents aligned with user objectives in the Ultimatum Game, matrix games, and the DEALORNODEAL negotiation task. In all three tasks, we show that RL agents trained with our framework are well-aligned with the user’s objectives and outperform RL agents trained with reward functions learned via supervised learning. Code and prompts can be found here. # INTRODUCTION Autonomous agents are becoming increasingly capable with the rise of compute and data. This underscores the importance for human users to be able to control what policies the agents learn and ensure the policies are aligned with their objectives. For instance, imagine training an agent to represent users in a salary negotiation. A working mother fighting for a livable wage may want their agent to be stubborn whereas a new hire looking to develop a good relationship with the company may want their agent to be more versatile. Currently, users specify desired behaviors by 1) designing reward functions or 2) providing large amounts of labeled data. Both approaches are challenging and impractical for different reasons. Designing reward func- tions is not an intuitive way to specify preferences. For instance, it isn’t straightforward how to write a reward function for a “versatile” negotiator. Furthermore, designing reward functions that balance between different objectives — also known as the “reward design problem” — is notoriously difficult because agents are sus- ceptible to reward hacking (Amodei et al., 2016; Hadfield-Menell et al., 2017). On the other hand, one can learn a reward function from labeled examples. However, that is not possible with a single example; we need large amounts of labeled data to capture the nuances of different users’ preferences and objectives, which has shown to be costly (Zhang et al., 2016). Additionally, both approaches do not generalize well to new users who have different objectives — we would have to re-design our reward functions or re-collect data. Our aim is to create an easier way for users to communicate their preferences, where the interface is more intuitive than crafting a reward function and where they can cheaply specify their preferences with no more than a few examples. To do this, we leverage large language models (LLMs) that are trained on internet-scale text data and have shown an impressive ability to learn in-context from few or zero examples (Brown et al., 2020). Our key insight is that The scale of data that LLMs have been trained on make them great in-context learners and also allows them to capture meaningful commonsense priors about human behavior. Given a few examples or a description demonstrating the user’s objective, an LLM should be able to provide an accurate instantiation of reward values on a new test example, allowing for easier generalization to new objectives. To this end, we explore how to prompt an LLM as a proxy reward function to train RL agents from user inputs. In our approach, the user specifies an objective with a natural language prompt. Objectives can 1 Published as a conference paper at ICLR 2023 RL Training Prompt (p) Alice and Bob are negotiating how to split a set of (a) Task description (9; books, hats, and balls. Feed prompt (2) (p) LLM LLM provides + propose: textual output Bob_: propose: book=0 hat=1 ball: Alice : propose: book=1 hat=0 ball=1 Agreement! Example from user describing | Alic®:4 points “No” objective (versatile behavior) | Construct (P2) Is Alice a versatile negotiator? prompt (p) Yes, because she suggested different proposals. _ (3) Bob : propose: book=0 hat=1 ball Convert to int “0” lice : propose: book=1 hat=1 ball= (5) sing parse Episode outcome described as _| lise + Propose: book=1 hat=1 ball=0 6) ; using parse g string using parse f (ps) | Agreement! Summarize and use as Alice :5 points episode outcome reward signal Bob as string (p;) using parser f — (4) Update agent (Alice) weights and run an episode Question (ps) Is Alice a v RL Evaluation sample atraiectory t from Mn RNS bette whether tejectore MRED 2 Sample a trajectory t from Alice: Evaluate whether trajectory Alice: ? q@) P Hector Bob (2) ate eee ae Bob > agent ina testenvironment |" 7 satisfies user objective Figure 1: Depiction of our framework on the DEALORNODEAL negotiation task. A user provides an example and explanation of desired negotiating behavior (e.g., versatility) before training. During training, (1) we provide the LLM with a task description, a user’s description of their objective, an outcome of an episode that is converted to a string, and a question asking if the outcome episode satisfies the user objective. (2-3) We then parse the LLM’s response back into a string and use that as the reward signal for the Alice the RL agent. (4) Alice updates their weights and rolls out a new episode. (5) We parse the episode outcome int a string and continue training. During evaluation, we sample a trajectory from Alice and evaluate whether it is aligned with the user’s objective. be specified with a few examples when they are difficult to define (such as “versatility”) or as a single phrase when they are well-known concepts (such as “Pareto-optimality”). We use the prompt and the LLM to define a reward function for training an RL agent. The LLM takes the user prompt and a trajectory from an RL episode as input and outputs a score (e.g., “No” or “0”) for whether the trajectory satisfies the user’s objective, which we parse as an integer reward for the RL agent (Figure 1). There are two advantages to prompting LLMs as a proxy reward function: (1) we can leverage LLM’s in-context learning abilities and prior knowledge on human behavior so that users only need to provide a handful of example desirable behaviors and (2) users can specify their preferences intuitively using language. On the other hand, a potential disadvantage is that it is unclear how much prompt design will be required for the LLM to reliably infer user intent (see Sec. 5 for a discussion). The goal of this paper is to explore how well LLMs can train objective-aligned agents by providing reward signals, and empirically examine whether we can do so with no more than a few examples. Our contributions are as follows: We introduce the idea of using LLMs as a proxy reward function. • We propose a general RL training framework that leverages this proxy reward and is agnostic to the RL algorithm used. • We show that an LLM can more accurately train objective-aligned RL agents by an average of 35% compared the baseline. We use few-shot prompting for the Ultimatum Game and DEALORNODEAL negotiation task as well as zero-shot prompting in Matrix Games. • We conduct a pilot study with 10 human users. Users rate our agent to be significantly more aligned with their objective than an agent trained with a different one, p<0.001. • We provide further analysis quantifying the amount of user data required for our approach as well as the effect varying prompts has on the LLM’s reward signal accuracy. # 2 RELATED WORK Using Language for Reward Shaping. Recent Reinforcement Learning from Human Feedback (RLHF) works Ouyang et al. (2022); Bai et al. (2022) use LLMs as rewards by fine-tuning them on large amounts of user data. Our work does not fine-tune LLMs but uses in-context learning from only a handful of user data. 2 Published as a conference paper at ICLR 2023 Several works Goyal et al. (2019); Carta et al. (2022); Mirchandani et al. (2021) shape rewards by training an RL agent to learn and complete intermediate tasks guided by language. In contrast, our framework does not focus on generating subtasks but leverages the in-context learning abilities of an LLM to determine whether an agent’s policy satisfies the higher-level task. RL and Foundation Models. We leverage large language models such as GPT-3 (Brown et al., 2020) to learn a proxy reward function while avoiding the need for many expert demonstrations. Ahn et al. (2022); Huang et al. (2022) use an LLM to provide a plan which guides a robot with reasonable/feasible actions towards a human goal (e.g., with enumerating subtasks). In contrast, our work is different in that we are using an LLM to identify if a behavior satisfies “hard-to-specify” properties of a human’s objective and also offers users more control over how they want their policy to be executed. In the vision domain, Parisi et al. (2022) used pre-trained vision models as a feature extractor for the learned policy, but not to design a reward signal. In a similar spirit of leveraging self-supervised pre-training to design a flexible reward function, Chen et al. (2021) use a broad dataset of human videos and a small dataset of robot videos to train a reward function, which improves generalization to new environments and tasks. The interface for the desired task is a video of the task to be completed, instead of text in our framework, and the domain is restricted to robot tasks. More related works can be found in Sec. A.2. # 3 USING LLMS AS A REWARD SIGNAL Our goal is to use an LLM as a proxy reward function to train objective-aligned RL agents from user inputs. We formalize the task using a Markov Decision Process M=⟨S,A,p,R,γ⟩, where S is the state space (e.g., in DEALORNODEAL, the space of representations of utterances in the negotiation so far), A is the action space (e.g., set of all possible utterances), p : S ×A×S → [0,1] is the transition probability, and γ is the discount factor. Traditionally the reward function maps states and actions to a real number R:S ×A→R. In our work, we use an LLM as a proxy reward function that takes in a text prompt and outputs a string. We define A∗ to be the set of all strings, ρ∈A∗ as our text prompt (input to the LLM) and the LLM as a function LLM :A∗ →A∗. As illustrated in Fig. 1, the prompt ρ is a concatenation of four components including a string to describe the task ρ1 ∈A∗ and a user-specified string that describes their objectives using examples or a description, ρ2 ∈A∗. Additionally, we include a textual description of states and actions from an RL episode, ρ3, using a parser f :S ×A→A∗. ρ3 can describe the final state, final action, a trajectory, or any other representation of the episode. Finally, we include a question ρ4 ∈A∗ that asks whether the RL agent’s behavior, ρ3, satisfies the user’s objective, ρ2. We define an additional parser g : A∗ → {0,1} that maps the textual output of LLM to a binary value. We use this as the reward signal. Our framework replaces the traditional reward function with a proxy reward, LLM, and can be used with any RL training algorithm. Our framework is depicted in Fig. 1. Before training, a user specifies ρ2 which can be N examples describing their objective or a description of their objective using natural language. In Fig. 1 a user provides an example of their objective: versatile negotiating behavior. During training, we construct a prompt ρ by concatenating a description of the task, the user-specified examples/description, an episode’s outcome, and a question asking if the outcome satisfies the objective. We (1) feed the prompt to the LLM, (2) take its output, and (3) parse it into an integer using function g; we use a handcrafted, task-specific parser. We use the integer as the reward signal. (4) The RL agent then updates its weights and rolls out an episode. (5) We parse the episode outcome into a string using f and continue training; we also instantiate f as handcrafted, task-specific parser. To evaluate our framework, we sample a trajectory (e.g., a negotiation) from the agent and evaluate whether the trajectory is aligned with the user’s objective (e.g., whether Alice demonstrated versatile negotiating behavior). # 4 EXPERIMENTS In this section we investigate three questions to determine the feasibility and efficacy of our approach: (Q1) Can LLMs produce reward signals that are consistent with user objectives from a few examples (few-shot prompting)? (Q2) When objectives are well-known, can LLMs produce objective-consistent reward signals without any examples (zero-shot prompting)? (Q3) Can LLMs provide objective-aligned reward signals from examples (few-shot prompting) in more complex, longer-horizon domains? We evaluate our approach on three tasks: the Ultimatum Game, 2-player Matrix Games, and the DEALORNODEAL negotiation task (Lewis et al., 2017). We address (Q1) using the Ultimatum Game. We use Matrix Games to address (Q2) because it has well-known solution concepts such as Pareto-optimality. The 3 Published as a conference paper at ICLR 2023 DEALORNODEAL negotiation task is a longer-horizon domain where the LLM rewards agents for negotiating in a user-specified style; we address (Q3) in this task. In practice, we do not have access to ground truth user reward functions — this is the function that we are trying to approximate. However, for most of our experiments, we assume access to the true reward by constructing user reward functions that humans have been shown to have inspired by prior work. We use the true rewards only to evaluate our framework’s performance. Finally, we include a pilot user study where we evaluate agent performance when we do not have access to the ground truth reward. We use the ‘text-davinci-002’ GPT-3 model with temperature 0 as our LLM and our results are reported across 3 random seeds. Details on how we trained RL agents for each task are in A.4. s Evaluation Metrics. We evaluate our approach using the following metrics across our tasks (task-specific metrics are described within each subsection): Labeling Accuracy. We construct ground-truth reward functions for each domain. We report the mean accuracy of predictions of the reward value during RL training with respect to the ground-truth reward functions. This assesses how effectively the LLM can produce reward signals that are consistent with the user’s objective. RL Agent Accuracy. After RL training, we evaluate the learned policy with respect to the ground truth reward functions. We report the mean accuracy of RL agents. # Baselines. SL (Few-shot baseline). A supervised learning (SL) model trained to predict reward signals using the same examples given to the LLM in our framework. Examples are represented using structured non-text inputs, making it an easier problem for the SL model. This baseline only applies to tasks where we use few-shot prompting (Ultimatum Game, DEALORNODEAL). See A.5 for details on training and model architecture for each task. No Objective (Zero-shot baseline). In our zero-shot task, Matrix Games, we do not use any examples so we do not use SL as a baseline. Instead, we use a No Objective baseline where we prompt the LLM without using the user’s description of their objective to isolate the effect the description has on the LLM’s response. RL trained with Ground Truth Reward Functions. RL agents trained with ground truth reward functions. We use this as an oracle. # 4.1 ULTIMATUM GAME: TRAINING OBJECTIVE-ALIGNED AGENTS WITH FEW-SHOT PROMPTING When defining a precise objective is difficult, we can instead give a few examples of desired behavior. For instance, in a resource division game like the Ultimatum Game, it may be difficult for a user to specify the exact percentage (such as 32.4%) of resources they would be happy with receiving. Instead it could be easier for a user to give examples of splits that they would be happy with. We explore whether LLMs can produce reward signals that are consistent with user objectives from a few examples in the Ultimatum Game. Task Description. The Ultimatum Game consists of two players, a Proposer and a Responder. A sum of money is endowed to the Proposer and they must propose a way to split the endowment with the Responder. The Responder can accept or reject the proposed split. If the Responder accepts, players receive money as per the split; if the Responder rejects, then both players get nothing. We train an RL agent to play the Responder. The agent learns to reject proposals according to a user’s preferences. The game consists of a single timestep and our RL agents are trained using DQN for 1e4 steps. Ground Truth User Objectives. A rational Responder would accept any proposal, even if it is unfair because getting something is better than getting nothing (in fact, this is a Nash Equilibrium of the game). However, prior work in behavioral economics shows that humans are willing to “punish” the Proposer by rejecting unfair proposals (Vavra et al., 2018). For instance, a student may reject an unfair proposal only if she receives less than 30% of the endowment whereas a wealthier person may reject if they receive less than 60%. We experiment with the following preferences: • Low vs High Percentages. Users will reject proposals if they receive less than{30%, 60%} of the # endowment. • Low vs High Payoffs. Users will reject unfair proposals if they receive less than{$10, $100}. They accept unfair proposals otherwise. 4 Published as a conference paper at ICLR 2023 Low vs High % (10 examples, ours w/o expl.) Labeling Acc (1 example, ours w. expl.) uracy (10 examples, ours w/o expl.) Low vs High Payoffs (1 example, ours w. expl.) i iz 0 <30% <60% foe oe <30% <60% <$10 <$100 <$10 RL Agent Accuracy (10 examples, ours w/o expl.) (1 example, ours w. expl.) (10 examples, ours w/o expl.) 1 | 1 1 1 1 | | | | \ i i} <$10 <$100 <$10 (1 example, ours w. expl.) <30% <60% <30% <60% <$100 Figure 2: Ultimatum Game, Few-shot. (Top) Accuracy of reward signals provided by LLM and SL during RL training when prompted with/trained on 10 vs 1 example. (Bottom) Corresponding accuracy of RL agents after training. LLM is able to maintain a high accuracy when prompted with a single example followed by an explanation. We do not provide figures of Inequity Aversion because both LLM and SL trivially achieve perfect labeling and RL agent accuracy. • Inequity Aversion (Fehr & Schmidt (2010)). Users will reject proposals if they do not receive exactly 50% of the endowment. Prompt Design. We describe a user’s objective using 10 examples of the Ultimatum Game. An example consists of the proposed split, the Responder’s action, and a “yes/no” label of whether the Responder’s action was desirable or undesirable. These examples do not have explanations and resemble a traditional dataset used for supervised learning. We also experiment with using a single example followed by a short explanation. Importantly, we do not explicitly mention the user’s ground truth objective in the prompt. See Fig. 10 in the Appendix for an example of both types of prompts. Design Procedure. We randomly generated 10 proposed splits used for our prompt and sampled one proposal from the set for our single-example case. For Low vs High Percentages and Low vs High Payoffs, we used the same set of proposals across variants (i.e., same proposals for (30% and 60%) and ($10, $100)). We also randomly generated 50 proposals used to evaluate the LLM. Due to limited resources when querying GPT-3, we query the model’s responses to the 50 evaluation splits in a batched manner and save them. We then use those responses as the reward signal. 4.1.1 RESULTS Labeling Accuracy. We evaluated our approach on our test set of 50 proposals over 3 seeds; results are shown in Fig. 21. When prompted with 10 examples without explanations, the LLM and SL perform similarly well (see Fig. 2, top row). This result is not surprising, given that the decision boundary for the binary decision tasks is relatively simple to learn with 10 training examples. Instead, if we prompt the LLM with a single example followed by an explanation, it maintains a high accuracy whereas SL trained on the same, single example drops in accuracy. We did not use the explanation as part of input when training SL because it only takes non-textual inputs. This result highlights the advantage of using an LLM over a supervised learning model: they require far fewer examples because they can learn from explanations (Lampinen et al., 2022). We find that explanations are critical, as removing explanations when prompting the LLM with a single example results in a drop in LLM labeling accuracy (avg. drop of 31.67%) and a drop in RL agent accuracy (avg. drop of 28.8%). RL Agent Accuracy. The accuracy of the trained RL agents mirror the labeling accuracy. Summary. LLMs are efficient in-context learners. They are able to provide reward signals that are consistent with a user’s objectives from examples — even a single example with an explanation will suffice. # 4.2 MATRIX GAMES: TRAINING OBJECTIVE-ALIGNED AGENTS WITH ZERO-SHOT PROMPTING When objectives are well-known concepts such as Pareto-optimality, can we prompt the LLM without giving any examples? We hypothesize that well-known objectives are likely to be in-distribution for LLMs, and thus LLMs may be able to produce objective-aligned reward signals from zero-shot prompting. Since 1We do not display plots for Inequity Aversion because both LLM and SL received perfect labeling and RL agent accuracy. 5 Published as a conference paper at ICLR 2023 Labeling Accuracy Total Welfare Equal Rewards Rawlsian Fair Pareto-Optimal 1.0 : 1.0 . 1.0 : 1.0 4 No ' ' H mm Ours | Objective 1 1 5 1 5 1 05 : 05 | : 0.5 ! 0.5 iy il i L Lal 0.0 0.0 0.0 0.0 Regular Scrambled Regular Scrambled Regular Scrambled Regular Scrambled Order Order Order Order Order Order Order Order RL Agent Accuracy (Regular Order) Total Welfare Equal Rewards Rawlsian Fair Pareto-Optimal 1.0 10 10 10 1 i. oil . oil , ra | | . ra | | 00+ oo+ oo+ oo+ No Ours True No Ours ‘True No Ours True No Ours ‘True Objective Reward Objective Reward Objective Reward Objective Reward Figure 3: Matrix Games, Zero-shot. (Top) Accuracy of reward signals provided by LLM and a No Objective baseline during RL training. We report results for both regular and scrambled versions of matrix games. (Bottom) Accuracy of RL agents after training. we do not use examples, we do not use a SL baseline. Instead we use a baseline No Objective where we do not mention any objectives and ask the LLM for a reward signal (see example in Fig. 11 in the Appendix). This baseline evaluates whether the LLM can successfully apply its knowledge of each objective. Task Description. We consider two-player normal-form matrix games: Battle of the Sexes, Stag Hunt, Chicken, and Prisoner’s Dilemma. Each matrix game has four joint outcomes (i.e., a tuple of joint actions and rewards) and we address pure strategies in this task. The game consists of a single timestep and our RL agents are trained using DQN for 500 steps. Ground Truth User Objectives. Although (mixed) Nash Equilibria are traditional solution concepts for normal form matrix games, users may prefer a solution for other properties. For instance, in Prisoner’s Dilemma, users may prefer both agents to cooperate because they will maximize total welfare even though it is not a Pure Nash Equilibrium. We experiment with four well-known solution concepts (or objectives): Total Welfare. Outcomes that achieve the greatest sum of player rewards. • Equality. Outcomes that result in equal rewards between players. • Rawlsian Fairness. Outcomes that maximize the minimum reward any player receives. • Pareto-optimality. Outcomes where the one of the corresponding rewards cannot be improved without lowering the other. Prompt Design. Prompts for each solution concept are shown in Fig. 11 in the Appendix. Due to limited resources with querying GPT-3, we queried GPT-3 in a batched manner and saved the corresponding labels to train our RL agents. Our prompt enumerates the outcomes of a matrix game and then asks the LLM for the outcome(s) that satisfy a solution concept. We do not mention the name of the matrix game in the prompt. As in Kojima et al. (2022), we elicit intermediate reasoning steps by asking the LLM to “think step-by-step” and provide a definition of the solution concept. To prevent any bias the LLM may have towards the order in which the outcomes of a matrix game are presented, we also randomly scramble associations between joint actions and rewards (example shown in Fig. 12 in the Appendix). Design Procedure. We tuned the wording of our prompt (e.g., how to describe the matrix game, whether or not to use chain-of-thought prompting) on the Battle of the Sexes matrix game to find a prompt that gave us accurate results. During evaluation, we kept the structure of our prompt the same for all of the matrix games. 4.2.1 RESULTS Labeling Accuracy. Given that each game can have many outcomes that satisfy a solution concept, we report the LLM’s accuracy if its response does not include any incorrect outcomes. If the LLM identifies any incorrect outcome, we report a score of 0. The LLM produces more objective-aligned reward signals with zero-shot prompting by applying its knowledge of well-known objectives, improving the labeling accuracy over having no objective by 48% on average with a regular ordering of matrix game outcomes and 36% with a scrambled order. Scrambling the order of matrix game outcomes in the prompt lowers accuracy for most solution concepts. We suspect that this is because the matrix games are well-known and likely to have been in the LLM’s training set, where each joint action is usually associated with particular 6 Published as a conference paper at ICLR 2023 payoffs. Scrambling the associations between joint actions and payoffs could make the matrix game more out-of-distribution for the LLM, and thus lower accuracy. RL Agent Accuracy. Compared to labeling accuracy, it is easier for the resulting RL agents to be accurate because they only need to learn one correct outcome, not all of them. Thus, LLMs that only identify one out of two correct outcomes can still train objective-aligned RL agents. Results are shown on the bottom row of Fig. 3. RL agents trained using rewards from the LLM receive perfect accuracy for Total Welfare and Equal- ity and 75% accuracy for the other two objectives. The baseline receives lower accuracy for all objectives. Does the LLM Correctly Identify Each Objective? As part of our prompt, we ask the LLM to provide a definition of the objective before reasoning about whether an outcome satisfies the objective (see Fig. 11 in the Appendix). Table 2 in the Appendix shows how the LLM defines each objective zero-shot. The LLM is able to successfully recall the definitions for each objective except for Rawlsian Fairness – it gets it partially correct. However, the LLM varies in its ability to reason whether an outcome of a game satisfies the objective, which explains why the LLM does not receive perfect labeling accuracy for all objectives. Summary. An LLM is able to identify well-known objectives and provide objective-aligned reward signals in a zero-shot setting. 4.3 DEALORNODEAL: TRAINING OBJECTIVE-ALIGNED AGENTS IN MULTI-TIMESTEP TASKS We have shown that an LLM can provide objective-aligned reward signals in single-timestep tasks. In longer horizon tasks we must give trajectories instead of states as examples in our prompts. Longer prompts can be challenging because it is less likely for an LLM to have seen them during training. LLMs also have a recency bias which makes it harder for them to remember context introduced earlier on (Zhao et al., 2021). Can an LLM provide objective-aligned signals in longer horizon tasks? We investigate this question in the DEALORNODEAL negotiation task (Lewis et al., 2017). Task Description. DEALORNODEAL is a long-horizon task with a maximum length of 100 timesteps. An agent Alice must come to an agreement with her partner Bob on the allocation of a set of objects (books, hats, and balls). Agents are shown a context, which includes the counts of each item and their private utilities for each item. In the original task, agents get rewarded based on the agreed upon split and their utilities. If Alice and Bob reach a disagreement, both agents get nothing. We train Alice using on-policy RL by negotiating against a fixed partner model, which we refer to as Bob. See Sec. A.4 for more details on the domain and training. Ground Truth User Objectives. We train Alice to negotiate in different styles. For this experiment, we assume we have access to precise definitions in order to evaluate our models. Importantly, we do not give definitions of each style to the LLM, only examples. We experiment with the following negotiation styles inspired by previous literature Sycara et al. (1997); Caputo et al. (2019): Versatile. Alice does not suggest the same proposal more than once. • Push-Over. Alice gets less points than Bob. • Competitive. Alice gets more points than Bob. • Stubborn. Alice repeatedly suggests the same proposal. Prompt Design. We describe user objectives using three examples. Each example contains a negotiation between Alice and Bob, a question asking whether Alice negotiated in a particular style, and a yes or no answer followed by a short explanation. For an example, see Fig. 13 in the Appendix. Design Procedure. To create example negotiations, we randomly sampled three negotiation contexts for each objective and trained an RL agent (using the original task reward, without the LLM) to negotiate against Bob in these contexts. We then sampled negotiations from the trained model. We also made sure all three sampled negotiations did not have the same ground truth label. We use a separate set of contexts when training RL agents with an LLM in the loop. 4.3.1 RESULTS Labeling Accuracy. The top row of Fig. 4 shows that the LLM labels more accurately than SL except for Versatile. For Versatile, both models perform similarly because SL learns to overwhelmingly predict a negative label (avg of 96% negative predictions) and the RL agent showed more negative examples of Versatile behavior (avg. of 70% ground truth negative labels). However, the large portion of negative 7 Published as a conference paper at ICLR 2023 Labeling Accuracy Versatile Push-Over Competitive Stubborn Avg. User Rating 10 10 10 10 ;, Alignment to Correct 05 05 . 05 05 ‘ Style ‘ 4 oo 00 00 oo SL Ours SL Ours sl Ours sL Ours RL Agent Accuracy 8 Versatile Push-Over *Competitive Stubborn 10 10 10 10 2 . . 1 oot oo+ oo+ oot ‘Agent Trained Agent Trained SL Ours True SL Ours True SL Ours True SL Ours True w. Correct Style i Reward Reward Reward Reward Figure 4: DEALORNODEAL, Few-shot. (Top) Accuracy of reward signals provided by LLM and SL during RL training. (Bottom) Accuracy of RL agents after training. (Right) Pilot study results. Agents trained with the user’s preferred style were rated as significantly more aligned than an agent trained with the opposite style p<0.001. Versatile Push-Over Competitive Stubborn Advantage 0.17±0.91 −2.95±0.64 2.92±0.64 1.36±2.24 Diversity 0.99±0.01 0.82±0.26 0.74±0.25 0.52±0.1 Agreement Rate 0.98±1.89 1.0±0.0 0.88±6.5 0.82±12.35 Table 1: Qualitative results describing negotiations produced by agents trained with LLM. examples prevents the agent from learning correct behavior as shown in the Versatile plot on the bottom of Fig. 4); here, we get a larger performance gap between the LLM and SL. RL Agent Accuracy. Results are shown on bottom row of of Fig. 4. LLM improves RL agent accuracy over SL by 46% on average. Our method approaches the performance of using the true reward; we under perform by an average of 4%. We remind readers that it is possible to outperform an agent trained with the true reward — especially when the LLM’s labeling accuracy is near-perfect as is the case for Competitive and Stubborn — due to reward hacking or stochasticity during training. For instance, agents trained with the true reward for Competitive end in more disagreements, leading to 0 reward for both agents and a lower accuracy. Is There a Qualitative Difference in Styles? Example negotiations of agents trained with the LLM for each style are shown in Fig. 9 in the Appendix. To measure qualitative differences among styles, we looked at average advantage (Alice’s original task reward - Bob’s original task reward), diversity (percentage of Alice’s utterances that are unique in a negotiation), and agreement rate (percentage of negotiations that end in agreement). The results in Table 1 demonstrate qualitative differences in styles. 4.3.2 PILOT USER STUDY We conduct a within-subjects pilot user study to determine whether our trained agents can meaningfully align themselves with different user objectives when we do not have access to ground truth objectives and users evaluate agent performance. Method We asked N =10 users to select a style in which they wanted their agent to negotiate in. We gave them an option to choose from our existing styles (Versatile, Push-Over, Competitive, Stubborn), or come up with their own. Importantly, users did not know how we defined these styles. We then showed users a list of 10 example negotiations generated via selfplay using an RL agent trained with a greedy objective (no particular style). We asked users to select 3 examples (1 positive, 1 negative, and 1 positive or negative) where Alice displayed positive or negative behavior of the user’s chosen style. For each chosen example, we asked users whether Alice demonstrated their chosen style and asked them to provide a ”Yes/No” answer as well as a short explanation. These examples corresponded to unknown, user-specific ground truth reward functions that we did not have access to. We then trained a negotiation agent by incorporating the user-provided examples in the prompt as described in Sec. 3. We also trained an agent to negotiate in the opposite style by flipping the ”Yes/No” labels in the user-provided explanations. We hypothesize that users should perceive a significant difference between these two agents. To evaluate our trained agents, we had both agents negotiate on a set of 10 test negotiations. For each test negotiation, we asked users to rate how well each agent aligned with their chosen style on a scale from 1 (least aligned) to 5 (most aligned). Results Agents trained with the correct style were significantly more aligned (avg. 3.72±1.2) than agents trained with the opposite style (avg. 1.56 ± 1.05), p < 0.001, see Fig. 4 (right). Users varied in which 8 # of # w Published as a conference paper at ICLR 2023 styles they preferred: 4 users chose styles such as Polite, Push-Over, Considerate and Compromising, 2 users chose Versatile, and 4 users chose styles such as Stubborn, Competitive and Ambitious. These results demonstrate that our framework can produce agents aligned with differently specified objectives by changing the examples in the prompt. Furthermore, these results suggest that our framework can be used when rewards are difficult to define and results are agents with humans. Summary. Our framework can train objective-aligned agents when ground truth rewards are not present in complex, longer-horizon tasks. Agents are able to align the style in which they complete a task as evaluated by automated metrics as well as human users. # 5 ANALYSIS OF DATA EFFICIENCY & PROMPT DESIGN We have shown that we can use an LLM as a proxy reward function to successfully train objective-aligned agents across different tasks. This is a promising result because it represents an important step in enabling human-compatible and value-aligned AI systems. In this section, 1) we further quantify how data efficient our method is and 2) also analyze how robust LLM is to variations of prompt design. 1) How Data-efficient is Our Method? We quantify how much more user data a supervised learning baseline would need in order to achieve the same labeling accuracy as the LLM. Results in the Ultimatum Game demonstrate that 10 labeled examples is enough for an SL model to reach comparable performance, whereas a a single labeled example is not sufficient. In this section, we quantify the amount of data needed for DEALORNODEAL because it is an example of a task where the decision boundary is not as easy to learn as the Ultimatum Game. We train SL by adding additional class-balanced, labeled examples to the original three examples it was trained on. We plot the average labeling accuracy SL achieves when trained on increasingly larger amounts of examples as well as the accuracy LLM achieves with three examples, shown in Fig. 6 in the Appendix. Results show that SL requires on the order of hundreds of more labeled examples in order to be comparably accurate as LLM. 2) How Much Does LLM’s Labeling Accuracy Change When We Vary the Prompt? As with many approaches that use LLMs, a limitation of our approach is that it requires prompt design. We attempt to quantify the effort required for designing prompts as well as determine the feasibility of using non- engineered prompts from humans. We analyze the effect of prompt variation on labeling accuracy in DEALORNODEAL for the Stubborn objective. We vary different parts of the user-specified prompt at a time: the keyword (i.e., replacing “Stubborn” with its synonyms), the example negotiations, and the explanations associated with each example. Fig. 7 provides a summary of our results. See Sec. A.7 for the full results. Results illustrate that an LLM can be quite robust to different prompts — they all outperform SL. Furthermore, the quality of the explanation seems to be the most important in determining LLM accuracy. # 6 LIMITATIONS & FUTURE WORK User Studies. This work takes a first step in determining whether we can use LLMs as proxy rewards. Given promising results, we plan on evaluating our approach with a larger user study. Multimodal Foundation Models. Beyond language models, multimodal foundation models such as Flamingo (Alayrac et al., 2022) can enable us to provide more complex environment states to the foundation model through images or other modalities while preserving an intuitive language interface for specifying the user objective. Non-Binary Rewards. Another limitation of our framework is that the LLM only specifies binary rewards. We plan on exploring how we can incorporate the likelihoods that LLMs produce for each word as a non-binary reward signal. ACKNOWLEDGMENTS This work was supported by NSF Award 1941722, 2125511, 2006388, AFOSR, DARPA YFA Award, ONR, and JP Morgan Faculty Award. We would also like to thank Karl Tuyls, Ian Gemp, Albert Gu, Siddharth Karamcheti, Kanishk Gandhi, and other reviewers for this paper. 9 Published as a conference paper at ICLR 2023 REFERENCES Michael Ahn, Anthony Brohan, Noah Brown, Yevgen Chebotar, Omar Cortes, Byron David, Chelsea Finn, Chuyuan Fu, Keerthana Gopalakrishnan, Karol Hausman, Alex Herzog, Daniel Ho, Jasmine Hsu, Julian Ibarz, Brian Ichter, Alex Irpan, Eric Jang, Rosario Jauregui Ruano, Kyle Jeffrey, Sally Jesmonth, Nikhil J Joshi, Ryan Julian, Dmitry Kalashnikov, Yuheng Kuang, Kuang-Huei Lee, Sergey Levine, Yao Lu, Linda Luu, Carolina Parada, Peter Pastor, Jornell Quiambao, Kanishka Rao, Jarek Rettinghouse, Diego Reyes, Pierre Sermanet, Nicolas Sievers, Clayton Tan, Alexander Toshev, Vincent Vanhoucke, Fei Xia, Ted Xiao, Peng Xu, Sichun Xu, Mengyuan Yan, and Andy Zeng. Do as i can, not as i say: Grounding language in robotic affordances. arXiv, 2022. Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc, Antoine Miech, Iain Barr, Yana Hasson, Karel Lenc, Arthur Mensch, Katie Millican, Malcolm Reynolds, Roman Ring, Eliza Rutherford, Serkan Cabi, Tengda Han, Zhitao Gong, Sina Samangooei, Marianne Monteiro, Jacob Menick, Sebastian Borgeaud, Andrew Brock, Aida Nematzadeh, Sahand Sharifzadeh, Mikolaj Binkowski, Ricardo Barreira, Oriol Vinyals, Andrew Zisserman, and Karen Simonyan. Flamingo: a visual language model for few-shot learning. arXiv, 2022. Dario Amodei, Chris Olah, Jacob Steinhardt, Paul Christiano, John Schulman, and Dan Man´e. Concrete problems in ai safety. arXiv preprint arXiv:1606.06565, 2016. 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. Tom B. Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared 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 M. Ziegler, Jeffrey Wu, Clemens Winter, Christopher 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. arXiv preprint arXiv:2005.14165, 2020. Andrea Caputo, Oluremi B Ayoko, Nii Amoo, and Charlott Menke. The relationship between cultural values, cultural intelligence and negotiation styles. Journal of Business Research, 99:23–36, 2019. Thomas Carta, Sylvain Lamprier, Pierre-Yves Oudeyer, and Olivier Sigaud. Eager: Asking and answering questions for automatic reward shaping in language-guided rl. arXiv preprint arXiv:2206.09674, 2022. Annie S. Chen, Suraj Nair, and Chelsea Finn. Learning generalizable robotic reward functions from ”in-the-wild” human videos. ArXiv, abs/2103.16817, 2021. Paul F Christiano, Jan Leike, Tom Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep reinforce- ment learning from human preferences. Advances in neural information processing systems, 30, 2017. Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, and Yoshua Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. arXiv preprint arXiv:1412.3555, 2014. Ernst Fehr and Klaus M Schmidt. On inequity aversion: A reply to binmore and shaked. Journal of economic behavior & organization, 73(1):101–108, 2010. Prasoon Goyal, Scott Niekum, and Raymond J Mooney. Using natural language for reward shaping in reinforcement learning. arXiv preprint arXiv:1903.02020, 2019. Dylan Hadfield-Menell, Smitha Milli, Pieter Abbeel, Stuart J Russell, and Anca Dragan. Inverse reward design. Advances in neural information processing systems, 30, 2017. He He, Derek Chen, Anusha Balakrishnan, and Percy Liang. Decoupling strategy and generation in negotiation dialogues. In Empirical Methods in Natural Language Processing (EMNLP), 2018. Wenlong Huang, P. Abbeel, Deepak Pathak, and Igor Mordatch. Language models as zero-shot planners: Extracting actionable knowledge for embodied agents. In ICML, 2022. 10 Published as a conference paper at ICLR 2023 Borja Ibarz, Jan Leike, Tobias Pohlen, Geoffrey Irving, Shane Legg, and Dario Amodei. Reward learning from human preferences and demonstrations in atari. Advances in neural information processing systems, 31, 2018. W Bradley Knox, Alessandro Allievi, Holger Banzhaf, Felix Schmitt, and Peter Stone. Reward (mis) design for autonomous driving. arXiv preprint arXiv:2104.13906, 2021. Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa. Large language models are zero-shot reasoners. arXiv, 2022. Minae Kwon, Siddharth Karamcheti, Mariano-Florentino Cuellar, and Dorsa Sadigh. Targeted data acquisition for evolving negotiation agents. In International Conference on Machine Learning, pp. 5894–5904. PMLR, 2021. Andrew K Lampinen, Ishita Dasgupta, Stephanie CY Chan, Kory Matthewson, Michael Henry Tessler, Antonia Creswell, James L McClelland, Jane X Wang, and Felix Hill. Can language models learn from explanations in context? arXiv preprint arXiv:2204.02329, 2022. Mike Lewis, Denis Yarats, Yann N. Dauphin, Devi Parikh, and Dhruv Batra. Deal or no deal? end-to-end learning for negotiation dialogues. In Empirical Methods in Natural Language Processing (EMNLP), 2017. Jessy Lin, Daniel Fried, Dan Klein, and Anca Dragan. Inferring rewards from language in context. arXiv preprint arXiv:2204.02515, 2022. Suvir Mirchandani, Siddharth Karamcheti, and Dorsa Sadigh. Ella: Exploration through learned language abstraction. Advances in Neural Information Processing Systems, 34:29529–29540, 2021. 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 E. Miller, Maddie Simens, Amanda Askell, Peter Welinder, Paul Francis Christiano, Jan Leike, and Ryan J. Lowe. Training language models to follow instructions with human feedback. ArXiv, abs/2203.02155, 2022. Alexander Pan, Kush Bhatia, and Jacob Steinhardt. The effects of reward misspecification: Mapping and mitigating misaligned models. arXiv preprint arXiv:2201.03544, 2022. Simone Parisi, Aravind Rajeswaran, Senthil Purushwalkam, and Abhinav Kumar Gupta. The unsurprising effectiveness of pre-trained vision models for control. In ICML, 2022. Antonin Raffin, Ashley Hill, Adam Gleave, Anssi Kanervisto, Maximilian Ernestus, and Noah Dormann. Stable-baselines3: Reliable reinforcement learning implementations. Journal of Machine Learning Research, 22(268):1–8, 2021. URL http://jmlr.org/papers/v22/20-1364.html. St´ephane Ross, Geoffrey Gordon, and Drew Bagnell. A reduction of imitation learning and structured prediction to no-regret online learning. In Proceedings of the fourteenth international conference on artificial intelligence and statistics, pp. 627–635. JMLR Workshop and Conference Proceedings, 2011. Dorsa Sadigh, Anca D. Dragan, S. Shankar Sastry, and Sanjit A. Seshia. Active preference-based learning of reward functions. In Proceedings of Robotics: Science and Systems (RSS), July 2017. doi: 10.15607/RSS.2017.XIII.053. Katia Sycara, Daniel Zeng, et al. Benefits of learning in negotiation. In Proceedings of the AAAI National Conference on Artificial Intelligence. Menlo Park, California, pp. 36–41, 1997. Peter Vavra, Luke J Chang, and Alan G Sanfey. Expectations in the ultimatum game: distinct effects of mean and variance of expected offers. Frontiers in psychology, 9:992, 2018. Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3):229–256, 1992. Jing Zhang, Xindong Wu, and Victor S Sheng. Learning from crowdsourced labeled data: a survey. Artificial Intelligence Review, 46(4):543–576, 2016. Tony Z. 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 (ICML), 2021. 11 Published as a conference paper at ICLR 2023 # A APPENDIX A.1 SUMMARY OF RESULTS: IS IT IS POSSIBLE TO USE LLM AS A PROXY REWARD IN RL TRAINING? Avg. Labeling Accuracy Avg. RL Agent Accuracy Zero-shot Few-shot Ours Zero-shot _ Few-shot Ours True Reward Baseline Baseline Baseline Baseline (No Obj.) (SL) (No Obj.) (SL) Ultimatum Game ~ 0.674034 0.9140.27 - 0.674034 0.940.26 1.0+0.02 Matrix Games | 0.19 + 0.29 - 0.61+0.41 | 054+0.29 - 0.88+0. 1.040. DEALORNODEAL - 054047 0.9+0.22 - 0334042 0.8+0.33 0.84+0.27 Figure 5: Average Labeling and RL Agent Accuracy across the different objectives for each task across 3 seeds. We provide a summary of results in Fig. 5. The figure depicts the average Labeling and RL Agent Accuracy computed across the different user objectives for each task, across 3 seeds. Overall, our approach is able to produce more objective-aligned reward signals than our baselines. Our approach is also able to produce objective-aligned policies that are close in accuracy to policies trained with the true reward. A.2 MORE RELATED WORKS Reward Design. Our framework addresses reward design—how to engineer rewards so that they align with our objectives (Amodei et al., 2016). This is challenging because tasks often have conflicting objectives that a human must trade off (Pan et al., 2022). Misspecifying reward functions can lead to reward hacking, or the gaming of specified rewards. Reward hacking has appeared in various domains such as autonomous driving (Knox et al., 2021) and game-playing (Ibarz et al., 2018). We hope to address these challenges by leveraging LLMs and making it easier for humans to specify their objectives. Imitation Learning & Preference-based Learning. Another method of specifying user objectives is to learn them from expert demonstrations (Ross et al., 2011) or preferences Sadigh et al. (2017). These techniques either assume access to large datasets (Christiano et al., 2017) or place restrictive assumptions (such as linearity) about the reward function (Sadigh et al., 2017). Recent work attempts to learn reward functions from language instructions using pragmatic reasoning (Lin et al., 2022). In contrast, our work relies on an LLM’s in-context learning abilities to provide a reward. A.3 LLM DEFINITION OF OBJECTIVES IN THE MATRIX GAME LLM Defns. of Objectives Total welfare is the sum of the rewards of both players. (✓) Equality of rewards is only possible if both players receive the same reward. (✓) Rawlsian fairness is defined as the maxmin value of the game, which is the minimum reward that the player could get assuming that the other player is maximizing their reward. (X) An outcome is Pareto-optimal if there is no other outcome that would make one player better off without making the other player worse off. (✓) Table 2: Completion of each sentence given by LLM in pink. LLM provides correct definitions for objectives except for Rawlsian Fairness, which is partially correct. A.4 DETAILS ON RL ENVIRONMENTS AND TRAINING Ultimatum Game. The environment is a single horizon with discrete actions (i.e., accept or reject) and continuous observations (i.e., a proposed split). We train DQN agents using the Stable Baselines3 implementation for 1e4 timesteps with a learning rate of 1e-4 across 3 seeds (Raffin et al., 2021). We instantiate our policy as a MLP with the default parameters used in Stable Baselines3. 12 Published as a conference paper at ICLR 2023 Parser g. The parser g that transforms the LLM’s output into an integer reward signal is defined using a handcrafted parser. When prompting the LLM, we structure the labels for each example to be in “Yes/No” form which enables the LLM to also reply using the same format. We are then able search for the “Yes” or “No” strings and parse them into a 1 or 0 respectively. In the rare occasion that the LLM does not respond in this form, we skip the episode during RL training and omit the example from our evaluation. Further Analysis on Performance of No Objective Baseline. The average LLM accuracy of a random baseline across the four matrix games are Welfare: 0.125, Equality: 0.125, Rawlsian Fairness: 0.078, Pareto-optimality: 0.172. The No Objective baseline’s performance is close to random as can be verified by comparing the random baseline results with Figure 3 (top row).* Behaviorally, we observe that No Objective acts like a random baseline: the LLM often hallucinates matrix game rewards and also displays incoherent reasoning when selecting answers. Matrix Game.. The environment is a single horizon with discrete actions (i.e., one of the four joint actions) and no observations. We train DQN agents using the Stable Baselines3 implementation for 500 timesteps with a learning rate of 1e-4 across 3 seeds (Raffin et al., 2021). We instantiate our policy as a MLP with the default parameters used in Stable Baselines3. Parser g. We parse the LLM’s response by hand, since LLM output can be variable in zero-shot settings. DEALORNODEAL. We use a version of the DEALORNODEAL environment used in Kwon et al. (2021). In the environment, the goal is for an agent A to come to an agreement with a partner B on the allocation of a set of objects (books, hats, and balls). During each negotiation, agents receive a context, cA =[i;uA],cB = [i;uB], detailing the count of each item i as well as their private utilities, uA,uB. Item counts and utilities are represented as vectors i∈{1,...,4}3 and uA,uB ∈{0,...,10}3 and are sampled uniformly. After receiving contexts cA,cB, an agent is randomly selected to begin the negotiation. Agents negotiate for T time steps by exchanging coarse dialogue acts xt at each time step 1 ≤ t ≤ T (He et al., 2018). Rather than negotiate directly in natural language, where the generation problem is hard and can result in degenerate dialogues (He et al., 2018), we use these dialogue acts instead to focus on learning diverse and interpretable strategies. A dialogue act xt is one of five actions: propose, insist, agree, disagree, or end. The propose and insist acts take allocations of items as arguments o = [oA; oB] where oA,oB ∈ {1,...,4}3 (e.g., propose: books=1, hats=2, balls=1). When an agent selects end, the conversation terminates and each agent is asked to make their final selection. If agents agree on the final allocation of items, i.e., oA+oB =i, agents are awarded points based on their private utilities, rA = uA ·oA,rB = uB ·oB. If agents do not agree, they receive 0 points. Each agent’s context is constrained so that the agent can receive a maximum of 10 points. Agents are first trained using supervised learning on a dataset of human-human negotiations provided by (Lewis et al., 2017) to predict the next token. We use a learning rate of 1.0 and batch size of 16. We then fine-tune these agents using RL where they optimize the expected reward of each dialogue act using REINFORCE (Williams, 1992). Agents are trained on 250 contexts for 1 epoch with a learning rate of 0.1. We instantiate our policy with four GRUs (Chung et al., 2014). We closely follow the implementation outlined in (Kwon et al., 2021; Lewis et al., 2017), please refer to those papers for more training details. Parser g. The parser g that transforms the LLM’s output into an integer reward signal is defined using a handcrafted parser. When prompting the LLM, we structure the labels for each example to be in “Yes/No” form which enables the LLM to also reply using the same format. We are then able search for the “Yes” or “No” strings and parse them into a 1 or 0 respectively. In the rare occasion that the LLM does not respond in this form, we skip the episode during RL training and omit the example from our evaluation. A.5 SL MODEL ARCHITECTURE AND TRAINING Ultimatum Game. SL is trained to predict binary labels for a batch of proposed splits. We implemented SL as a multi-layer perceptron (MLP) network that consists of a single hidden layer with depth 32. We also use ReLU activations after our input and hidden layers. We trained the model on the same 10 examples we gave to LLM for 5 epochs with the Adam optimizer. We evaluate the model on the 50 heldout test examples and save the model with the best test accuracy. We show the training and test accuracy for each user objective below: 13 Published as a conference paper at ICLR 2023 Table 3: Training accuracy for SL on the Ultimatum Game. Train Acc. (10 examples) Train Acc. (1 example) 30% 60% $10 0.9 1.0 1.0 1.0 1.0 1.0 $100 1.0 1.0 Ineq. Aversion 1.0 1.0 DEALORNODEAL. SL is trained to predict binary labels given a negotiation as input. We closely follow the implementation of a SL model found in (Kwon et al., 2021; Lewis et al., 2017). A negotiation consists of a context, coarse dialogue acts exchanged between Alice and Bob, and the outcome of the negotiation (the final split of items and whether agents agreed or disagreed). Please refer to Sec. A.4 for more details on the environment. We implement SL using a MLP context encoder, MLP outcome encoder, and a GRU ((Chung et al., 2014)) to process the coarse dialogue acts. The MLP encoders consist of an embedding layer followed by a linear layer with a Tanh activation function; we use a hidden size of 64 for the context encoder’s linear layer. We similarly embed each coarse dialogue act before feeding it into the GRU. We use a hidden size of 128 for the GRU. We train SL on the same 3 examples we use in our prompt for LLM. We train for a maximum of 50 epochs using the Adam optimizer. SL received a training accuracy of 100% for all of our objectives. A.6 HOW DATA-EFFICIENT IS OUR METHOD? SL Labeling Accuracy When Trained with # Additional Labeled Examples Versatile Push-Over Competitive Stubborn 1 1 1 1 SL — Ours oO oO oO oO oO 100 200 300 0 100 200 300 400 500 oO 100 200 300 = 400 oO 100 200 300 # Additional Examples # Additional Examples # Additional Examples # Additional Examples Figure 6: SL requires on the order of hundreds of more labeled examples in order to be comparably accurate to the LLM. A.7 HOW MUCH DOES LLM’S LABELING ACCURACY CHANGE WHEN WE VARY THE PROMPT? Effect of Prompt Variation on Labeling Accuracy for Stubborn (N=3, 3 seeds) SL Ours Vary Keyword — Vary Example Vary Negotiations Explanations 0.58 + 0.48 0.97 + 0.16 0.91 + 0.28 0.93 + 0.28 0.79 + 0.33 Figure 7: On average, varying the prompt does not have a large impact on the accuracy of the LLM. We analyze the effect of varying prompts on the LLM’s labeling accuracy for the Stubborn negotiating style in DEALORNODEAL. We vary prompts in three ways: we vary the keyword (i.e., replacing “Stubborn” with its synonyms), the example negotiations, and the explanations associated with each example. When varying the keyword, we use the synonyms: “Headstrong”, “Obstinate”, and a less commonly used word, “Froward”. To vary example negotiations, we randomly sample three new negotiations to have counterbalanced labels, all positive labels, or all negative labels. We vary the explanations by coming up with two plausible sets of explanations a user might have given for each example. We also experiment with the scenario where we give no explanations. Results are shown in Fig. 8. Overall, varying prompts do not have a large impact on labeling accuracy — they all outperform the baseline. However, the quality of explanation seems to have the largest impact on labeling accuracy. A.8 WHAT IS THE IMPORTANCE OF INCLUDING THE TASK DESCRIPTION, ρ1 IN THE PROMPT? We experiment with removing ρ1, the task description in the Ultimatum Game with a single example followed by an explanation. Performance increases slightly in LLM labeling accuracy (avg. of 8%) and RL agent accuracy (avg. of 9%). We run the same experiment in the Ultimatum game in the case of 10 examples with no explanation. Performance drops slightly in LLM labeling accuracy (avg. 4.4%) and RL 14 Published as a conference paper at ICLR 2023 Effect of Prompt Variation on Labeling Accuracy for Stubborn (3 seeds) Vary Keyword Vary Example Negotiations Vary Explanations 1 toot | 1 1 lool 1 1 1 tool | ra | ra | Pa | 1 0 0 t 0 a 5 yy y z fel @ 5% g g el @ a a | > §€ #f ¢ € o 36 #3 2 2 e 8 ¢ FE F BSB g Bt 2 56 Z g za 48 a 3 % A sa ¢ 2 8p 5B 8g ge. 8 ij Py Os Zz 68 AB 24 : zo 6.6 Figure 8: Varying prompts do not have a large impact on labeling accuracy. agent accuracy (avg. 5.3%). We conclude that ρ1 is not conclusively influential in improving performance in few-shot settings. A.9 EXPERIMENTING WITH SMALLER LLM SIZES We experiment with GPT-2, a 1.5B parameter model. We We find that GPT-2 underperforms GPT-3 in both labeling (avg. 15%) and RL agent accuracy (avg. 49%). GPT-2 outperforms the SL baseline in labeling accuracy (avg. 24%), and slightly underperforms the SL baseline for RL agent accuracy (avg. 2.7%). Results are averaged across styles and seeds. GPT-2 (1.5B) is several orders smaller than GPT-3 (175B), and we expect models larger than GPT-2 to close the gap with GPT-3’s performance. A.10 EXAMPLE NEGOTIATIONS Context Alice : book=(count:1 value:0) hat=(count:1 value:7) ball=(count3 value:1) Bob : book=(count:1 value:3) hat=(count:1 value:7) ball=(count:3 value:0) # Versatile # Push-over Alice : propose: item’ Bob : propose: item0=0 item1=1 item2=0 Alice : propose: item0=1 item1=0 item2=2 em Bob : agree ropose: item0=I item1=0 item: Bob : propose: item0=1 item1=1 item2=0 _ Agreement! Alice : 2 points Bob :7 points Agreement! Alice : 3 points Bob : 10 points # Competitive # Stubborn item1=1 item2=0 Alice : insist: item0=0 item1=1 item2=3 Bob : agree Agreement! Alice : 10 points Bob :3 points Alice : propose: item0=0 ite Bob : propose: item0=0 item: Alice : propose: item0=0 ite Bob : propose: item0=0 item: Alice : propose: item0=0 ite Bob : propose: item0=0 item: Alice : propose: item0=0 ite Bob : propose: item0=0 item: Alice : propose: item0=0 ite Bob : propose: item0=0 item: Alice : propose: item0=0 item1=1 item2=0 Bob : disagree # Disagreement?! Alice : 0 (potential 0) : 0 (potential 0) # Bob Figure 9: Example negotiations after Alice is trained with reward signals from LLM in DEALORNODEAL. We illustrate qualitative differences in how Alice negotiates for the same context. Bob is an agent that is trained with supervised learning. 15 Published as a conference paper at ICLR 2023 A.11 EXAMPLE OF PROMPTS USED IN OUR EXPERIMENTS # A.11.1 ULTIMATUM GAME Further Explanation of Our Prompt Selection Process. When constructing our explanations, we encourage the LLM to produce intermediate reasoning steps by using the “Let’s think step by step” template used in Kojima et al. (2022) which has been shown to improve performance. 10 Examples, No Explanation 1 Example, with Explanation Task description should split $10 and P2 can either accept or reject. If P2 accepts, then P1 and P2 are playing the Ultimatum Game. P1 proposes how they { the deal is done. If P2 rejects, then both parties get nothing. P1 proposes a split of $4.21 for P1 and $5.79 for P2. P2 rejected this offer. A desirable outcome is defined as one where P2 punishes P1's selfish behavior. Is the outcome desirable? No P1 proposes a split of $1.28 for P1 and $8.72 for P2. P2 rejected this offer. A desirable outcome is defined as one where P2 punishes P1's Examples of | selfish behavior. Is the outcome desirable? Objective No P1 proposes a split of $9.78 for P1 and $0.22 for P2. P2 rejected this offer. A desirable outcome is defined as one where P2 punishes P1's selfish behavior. Is the outcome desirable? Yes [7 more examples] Episode outcome P1 proposes a split of $9.21 for P1 and $0.79 for P2. P2 rejected this offer. A desirable outcome is defined as one where P2 punishes P1's selfish behavior. Is the outcome desirable? Question P1 and P2 are playing the Ultimatum Game. P1 proposes how they Task should split $10 and P2 can either accept or reject. If P2 accepts, then d ei tion the deal is done. If P2 rejects, then both parties get nothing. eseriP P1 proposes a split of $9.78 for P1 and $0.22 for P2. P2 rejected this offer. A desirable outcome is defined as one where P2 punishes P1's selfish behavior. Is the outcome desirable? Let's think step by step: P2 receives $0.22 < $3 so P2 should reject this offer. Therefore, the outcome is desirable. Example of Objective Episode outcome P1 proposes a split of $9.21 for P1 and $0.79 for P2. P2 rejected this offer. A desirable outcome is defined as one where P2 punishes P1's selfish behavior. Is the outcome desirable? Let's think step by step:~y Question Figure 10: An example of few-shot prompts used for the Ultimatum Game. We highlight the four parts of each prompt. # A.11.2 MATRIX GAMES Further Explanation of Our Prompt Selection Process. We found that structuring the outcomes of the game as a multiple choice question improved performance. We also encouraged the LLM to produce intermediate reasoning steps by using the “Let’s think step by step” template used in Kojima et al. (2022) which has been shown to improve performance. Task description Question { Total Welfare We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action1(P2) => P1 gets reward of 2, P2 gets reward of 2. B. if action1(P1) and action2(P2) => P1 gets reward of 1, P2 gets reward of 3. C. if action2(P1) and action1(P2) => P1 gets reward of 3, P2 gets reward of 1. D. if action2(P1) and action2(P2) => P1 gets reward of 0, P2 gets reward of 0. Which option(s) result in the greatest total welfare? Let's think step by SteP: Description Total welfare is of Objective Equality We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action1(P2) => P1 gets reward of 2, P2 gets reward of 2. B. if action1(P1) and action2(P2) => P1 gets reward of 1, P2 gets reward of 3. C. if action2(P1) and action1(P2) => P1 gets reward of 3, P2 gets reward of 1. D. if action2(P1) and action2(P2) => P1 gets reward of 0, P2 gets reward of 0. Which option(s) result in equality of rewards? Let's think step by step: Equality of rewards is Rawlsian Fairness We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action1(P2) => P1 gets reward of 2, P2 gets reward of 2. B. if action1(P1) and action2(P2) => P1 gets reward of 1, P2 gets reward of 3. C. if action2(P1) and action1(P2) => P1 gets reward of 3, P2 gets reward of 1. D. if action2(P1) and action2(P2) => P1 gets reward of 0, P2 gets reward of 0. Which option(s) result in Rawlsian fair rewards? Let's think step by step: Rawlsian fairness is Pareto-optimality We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action1(P2) => P1 gets reward of 2, P2 gets reward of 2. B. if action1(P1) and action2(P2) => P1 gets reward of 1, P2 gets reward of 3. C. if action2(P1) and action1(P2) => P1 gets reward of 3, P2 gets reward of 1. D. if action2(P1) and action2(P2) => P1 gets reward of 0, P2 gets reward of 0. Which option(s) are Pareto- optimal? Let's think step by step: An outcome is Pareto- optimal if No Objective We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action1(P2) => P1 gets reward of 2, P2 gets reward of 2. B. if action1(P1) and action2(P2) => P1 gets reward of 1, P2 gets reward of 3. C. if action2(P1) and action1(P2) => P1 gets reward of 3, P2 gets reward of 1. D. if action2(P1) and action2(P2) => P1 gets reward of 0, P2 gets reward of 0. Which option(s) should P1 and P2 select? Figure 11: Examples of a zero-shot prompts used for each objective, including the no-objective baseline, in the Matrix Games. Due to limited resources when querying GPT-3, we queried GPT-3 in a batched manner and saved the corresponding labels to train our RL agents. Consequently, we do not have an Episode outcome in our prompts. # A.11.3 DEALORNODEAL Further Explanation of Our Prompt Selection Process. We chose 3 counterbalanced examples from a training set of sample negotiations. This training set was generated via selfplay using an RL agent trained 16 Published as a conference paper at ICLR 2023 Chicken Game (Regular Order) Chicken Game (Scrambled Order) We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action! (P2) => P1 gets reward of 2, P2 gets reward of 2. B. if action1(P1) and action2(P2) => P1 gets reward of 1, P2 gets reward of 3. C. if action2(P1) and action (P2) D. if action2(P1) and action2(P2) = Which option(s) are Pareto-optimal? Let's think step by step: An outcome is Pareto-optimal if P1 gets reward of 3, P2 gets reward of 1. P1 gets reward of 0, P2 gets reward of 0. We have a two-player game where P1 and P2 can choose one of these options. Options: A. if action1(P1) and action (P2) => P1 gets reward of 3, P2 gets reward of 1 B. if action1(P1) and action2(P2) reward of 2, P2 gets reward of 2. C. if action2(P1) and action (P2) reward of 1, P2 gets reward of 3. D. if action2(P1) and action2(P2) => P1 gets reward of 0, P2 gets reward of 0. Which option(s) are Pareto-optimal? Let's think step by step: An outcome is Pareto-optimal if Figure 12: Examples of regular and scrambled outcomes for the Chicken Game (Matrix Game experiments). Scrambling creates new associations between joint actions and joint rewards. We scramble the outcomes in order to remove any bias LLM may have towards the order in which outcomes are normally presented. with a greedy reward (no particular style). We chose to complement our examples with simple and succinct explanations. 17 Published as a conference paper at ICLR 2023 Task description { Alice and Bob are negotiating how to split a set of books, hats, and balls. Alice : book=(count:2 value:1) hat=(count:1 value:4) ball=(count:4 value:1) Bob_ : book=(count:2 value:0) hat=(count:1 value:6) ball=(count:4 value:1) Bob_: propose: book=0 hat=1 ball=2 Alice : propose: book=1 hat=1 ball=4 Bob_: propose: book=0 hat=1 ball=0 Alice : propose: book=1 hat=1 ball=4 Agreement! Alice: 9 points Bob: 0 points Is Alice a stubborn negotiator? Yes, because she repeatedly suggested the same proposal, book=1 hat=1 ball=4. Alice : book=(count:2 value:1) hat=(count:1 value:4) ball=(count:4 value:1) Bob: book=(count:2 value:4) hat=(count:1 value:2) ball=(count:4 value:0) Bob_: propose: book=2 hat=1 ball=0 Alice : propose: book=1 hat=1 ball=4 Bob : agree Examples of | -------------------nnnnnnann enna nn nnn ne nance cena ecc ccc e nnn nnnnnnnnnnns objective Agreement! Alice : 9 points Bob_: 4 points Is Alice a stubborn negotiator? No, because she did not repeatedly suggest the same proposal. Alice : book=(count:1 value:3) hat=(count:4 value:1) ball=(count:1 value:3) Bob: book=(count:1 value:10) hat=(count:4 value:0) ball=(count:1 value:0) Alice : propose: item0=1 item1=4 item2=0 Bob_: propose: item0=1 item1=0 item2=0 Alice : propose: item0=1 item1=0 item2=1 Bob_: propose: item0=1 item1=0 item2=0 Alice : insist: item0=0 item1=4 item2=1 Agreement! Alice : 7 points Bob : 10 points Is Alice a stubborn negotiator? No, because she did not repeatedly suggest the same proposal. Alice : book=(count:1 value:0) hat=(count:1 value:1) ball=(count:3 value:3) Bob: book=(count:1 value:1) hat=(count:1 value:0) ball=(count:3 value:3) Bob_: propose: book=0 hat=0 ball=3 Alice : agree Episode outcome Agreement! Alice : 1 points Bob :9 points Question { Is Alice a stubborn negotiator? Is Alice a stubborn negotiator? No, because she did not repeatedly suggest the same proposal. Question { Is Alice a stubborn negotiator? Figure 13: Example of a prompt used for DEALORNODEAL. 18
Title: Baize: An Open-Source Chat Model with Parameter-Efficient Tuning on Self-Chat Data: Summary: Chat models, such as ChatGPT, have shown impressive capabilities and have been rapidly adopted across numerous domains. However, these models are only accessible through a restricted API, creating barriers for new research and progress in the field. We propose a pipeline that can automatically generate a high-quality multi-turn chat corpus by leveraging ChatGPT to engage in a conversation with itself. Subsequently, we employ parameter-efficient tuning to enhance LLaMA, an open-source large language model. The resulting model, named Baize, demonstrates good performance in multi-turn dialogues with guardrails that minimize potential risks. Furthermore, we propose a new technique called Self-Distill with Feedback, to further improve the performance of the Baize models with feedback from ChatGPT. The Baize models and data are released for research purposes only at https://github.com/project-baize/baize-chatbot. An online demo is also available at https://huggingface.co/spaces/project-baize/chat-with-baize. # Baize: An Open-Source Chat Model with Parameter-Efficient Tuning on Self-Chat Data Canwen Xu1∗, Daya Guo2∗, Nan Duan3, Julian McAuley1 1University of California, San Diego, 2Sun Yat-sen University, 3Microsoft Research Asia 1{cxu,jmcauley}@ucsd.edu, 2guody5@mail2.sysu.edu.cn, 3nanduan@microsoft.com # Abstract Chat models, such as ChatGPT, have shown impressive capabilities and have been rapidly adopted across numerous domains. However, these models are only accessible through a restricted API, creating barriers for new re- search and progress in the field. We propose a pipeline that can automatically generate a high- quality multi-turn chat corpus by leveraging ChatGPT to engage in a conversation with itself. Subsequently, we employ parameter-efficient tuning to enhance LLaMA, an open-source large language model. The resulting model, named Baize, demonstrates good performance in multi-turn dialogues with guardrails that min- imize potential risks. Additionally, we propose a new technique called Self-Distill with Feed- back, to further improve the performance of the Baize models with feedback from ChatGPT. The Baize models and data are released for research purposes only.1 # Introduction The rapid advancement of natural language process- ing (NLP) techniques in recent years has led to the emergence of highly capable chat models, such as LaMDA (Thoppilan et al., 2022), ChatGPT (Ope- nAI, 2023a) and GPT-4 (OpenAI, 2023b). These models demonstrate a remarkable ability to under- stand and generate human-like responses in a wide range of domains. As a result, chat models have become increasingly popular for applications like customer support, virtual assistants, and social me- dia moderation. Despite the promising potential of these models, they are often only accessible through restricted APIs, creating barriers for new research and progress. Furthermore, the limited availability of chat models poses obstacles for re- searchers and practitioners, hindering the growth of the NLP community. The lack of publicly available, high-quality chat corpora for multi-turn conversa- tions exacerbates this issue, limiting the possibili- ties for refining and evaluating these models. In this paper, we propose a novel pipeline (shown in Figure 1) to address these challenges by lever- aging the capabilities of ChatGPT to automatically generate a high-quality multi-turn chat corpus. Our approach involves having ChatGPT engage in a conversation with itself, simulating both user and AI responses. This generated corpus serves as a valuable resource for training and evaluating chat models in the context of multi-turn dialogues. Fur- thermore, by specifying a seed dataset, we can sample from a particular domain and fine-tune chat models to be specialized in specific areas, such as healthcare or finance. To fine-tune large language models in a low- resource setting, we utilize a parameter-efficient tuning approach that effectively leverages the lim- ited computational resources available. This strat- egy enables the adaptation of state-of-the-art lan- guage models to resource-constrained scenarios while maintaining high performance and adaptabil- ity. Our primary focus is on improving an open- source large language model, LLaMA (Touvron et al., 2023), which we believe holds promise as an accessible alternative to proprietary chat models. By fine-tuning LLaMA with our generated chat cor- pus, we create a new model, named Baize (Bái zé, a mythical creature in Chinese folklore, who speaks human languages and knows everything). More- over, we propose Self-Distillation with Feedback (SDF) as an alternative to Reinforcement Learn- ing with Human Feedback (RLHF, Ziegler et al., 2019; OpenAI, 2023a), to further improve the per- formance of Baize. Baize is a chat model that can run on a single GPU, making it accessible for a broader range of researchers. # ∗Equal contribution. 1https://github.com/project-baize/ baize-chatbot To summarize, our main contributions in this paper are as follows: • We propose a novel and reproducible pipeline LoRA (S) ChatGPT 4 Tuning LLaMA Seed Template a, G Self-chat Feedback S li —>| Baize Baize feet Fo - i: Seit-Distit "| Dataset Corpus Seeds ChatGPT Figure 1: The pipeline for training Baize and Baize v2. for automatically generating a high-quality multi-turn chat corpus by having ChatGPT engage in a conversation with itself. Our pipeline fills a gap in the availability of public resources for training chat models in multi- turn dialogue settings. • We employ parameter-efficient tuning and pro- pose Self-Distillation with Feedback (SDF) to enhance the LLaMA model in a low-resource setting, resulting in the creation of Baize, a highly capable open-source chat model. By introducing the Baize model and the pipeline employed to generate the chat corpus, we aim to facilitate new research and advancement within the NLP community. # 2 Related Work Language Models for Chat Since the success of GPT-2 (Radford et al., 2019), there have been many language models for chatting with humans. As an initial trial, DialoGPT (Zhang et al., 2019) uses Reddit data to fine-tune GPT-2 for open-domain dialogue. Meena (Adiwardana et al., 2020) is a multi-turn open-domain chatbot with 2.6B param- eters, trained with data mined and filtered from public domain social media conversations. Follow- ing Meena, LaMDA (Thoppilan et al., 2022) is a chat model with 137B parameters, pretrained on 1.56T words of public dialog data and web text. ChatGPT (OpenAI, 2023a) is a model optimized for chat by introducing Reinforcement Learning with Human Feedback (RLHF), which astounds the community with its human-like chat ability. GPT- 4 (OpenAI, 2023b) is an improvement to ChatGPT with newly added reasoning and multi-modal capa- bility. Li et al. (2022) use in-context learning with GPT-3 to augment a dialogue dataset. Concurrent to our work, there have been at- tempts to replicate ChatGPT with open-source foundation models. Stanford Alpaca (Taori et al., 2023) uses Self-Instruct (Wang et al., 2022) to col- lect data from GPT-3.5 in instruction learning for- mat. Then, the collected dataset is used to fine- tune LLaMA (Touvron et al., 2023). Vicuna (Chi- ang et al., 2023) is a fine-tuned LLaMA model trained on a ChatGPT dialogue corpus crawled from sharegpt.com, a website for sharing Chat- GPT dialogues. We will discuss the pros and cons of the data source of each model in Section 3. Parameter-Efficient Tuning Conventional fine- tuning requires training all parameters in a large model, which can be inefficient as the numbers of parameters grows. Adapter (Houlsby et al., 2019) adds a tunable Transformer layer while freezing the original layers. BitFit (Zaken et al., 2022) only tunes bias terms in the linear layers. Diff- pruning (Guo et al., 2021) learns sparse weights that can be added to the original weights of the lan- guage model. Prefix Tuning (Li and Liang, 2021; Liu et al., 2021) fine-tunes prefix tokens inserted before the input. LoRA (Hu et al., 2022) inserts tun- able low-rank matrices into attention layers; LoRA achieves superior performance compared with con- ventional fine-tuning on GPT-3. Concurrent to our work, there are attempts to use LoRA (Hu et al., 2022) to fine-tune LLaMA. Alpaca-LoRA2 follows the same recipe as Alpaca while using LoRA for higher efficiency. There are also model weights trained in other languages with the code of Alpaca- LoRA. Different from these attempts, our work fo- cuses on developing an affordable and reproducible pipeline to efficiently tune a general-purpose lan- guage model for multi-turn chat. # 3 Data Collection via Self-Chat In this section, we detail the methodology em- ployed for generating a high-quality multi-turn chat corpus by leveraging ChatGPT (gpt-3.5-turbo) to engage in a conversation with itself. This pro- cess, named self-chat, serves as the foundation of 2https://github.com/tloen/alpaca-lora # v2 # Seed How do you fix a Google Play Store account that isn’t working? Human: My Google Play Store account is not working properly. How can I fix it? AI: There are several things you can try to fix a Google Play Store account that is not working properly. First, check your internet connection and make sure it is working properly. If your internet connection is fine, try clearing the cache and data of the Google Play Store app. If that doesn’t work, try uninstalling and reinstalling the app. Human: How do I clear the cache and data of the Google Play Store app? # Al: AI: To clear the cache and data of the Google Play Store app, go to Settings, then Apps & notifications, then find the Google Play Store app and tap on it. From there, tap on Storage, then Clear Cache and Clear Data. Human: Will clearing the cache and data delete any of my Google Play Store information or apps? AI: Clearing the cache and data of the Google Play Store app will not delete any of your downloaded apps or purchased items. However, it may remove your preferences and settings within the app. Human: What if clearing the cache and data doesn’t work? If clearing the cache and data doesn’t work, you can try uninstalling and reinstalling the Google Play Store app. To do this, go to Settings, then Apps & notifications, then find the Google Play Store app and tap on it. From there, tap on Uninstall and then reinstall the app from the Google Play Store. Table 1: (Not cherry-picked) An example of self-chat generated by ChatGPT (OpenAI, 2023a) with a seed sampled from the Quora dataset. our data collection pipeline and plays a critical role in enhancing the open-source large language model, LLaMA, to achieve better performance in multi-turn dialogues. The self-chat process involves utilizing Chat- GPT to generate messages for both the user and AI assistant in a conversational format. We apply a template (shown in Appendix A) to define the format and requirements, allowing the ChatGPT API to continuously generate transcripts for both sides of the dialogue until a natural stopping point is reached. The conversation is centered around a “seed”, which can be a question or a key phrase that sets the topic for the chat. Data Dialogs Avg. Turns Avg. Len. Alpaca (2023) 51,942 1.0 44.2 Quora StackOverflow MedQuAD 54,456 57,046 46,867 3.9 3.6 3.8 35.9 36.0 35.8 Quora v2 StackOverflow v2 55,770 112,343 3.0 3.9 149.6 78.2 Table 2: Statistics of the number of dialogues, average number of turns, and response lengths of each turn. 2019) dataset as seeds and obtain an additional 47k dialogues in the medical domain to train a Baize model specialized for healthcare. In our own training of Baize, we use questions from Quora3 and Stack Overflow4 as seeds. A di- alogue example generated with self-chat is shown in Table 1. For training the first version of Baize family (Baize v1), we collect a total of 111.5k di- alogues through self-chat, using ∼55k questions from each source. This process cost us approxi- mately $100 for calling OpenAI’s API. Also, one could use questions or phrases extracted from a domain-specific dataset to enhance the knowledge and ability of the chat model for a specific domain. Motivated by a recent report (Johnson et al., 2023) that ChatGPT can answer cancer-related questions as well as The National Cancer Institute, we use the MedQuAD (Ben Abacha and Demner-Fushman, Note by directly generating the dialogue with the template shown in Appendix A, ChatGPT’s output of each turn seems to be shorter than asking Chat- GPT one turn at a time. However, calling ChatGPT one turn at a time will significantly increase the cost for calling the API as we have to attach the context multiple times. To collect data with bet- ter quality for training Baize v1.5, we use another ChatGPT to generate responses once at a time and replace the AI’s responses in the template, to ob- tain responses that are completely consistent with ChatGPT’s responses, which are usually longer and contain more details. The statistics of the resulting corpora are shown in Table 2. # 3https://huggingface.co/datasets/quora 4https://huggingface.co/datasets/pacovaldez/ stackoverflow-questions Comparison with Other Data Sources Stanford Alpaca (Taori et al., 2023) uses Self-Instruct (Wang et al., 2022) to collect data in instruction learning format. However, their instruction-input-output Model Base Model Type Param. Trainable Param. GPU hrs Data Baize-v1-7B Baize-v1-13B Baize-v1-30B Baize-Healthcare LLaMA-7B LLaMA-13B LLaMA-30B LLaMA-7B SFT SFT SFT SFT 7B 13B 30B 7B 17.9M 28.0M 54.6M 17.9M 9 Quora, Stack Overflow, Alpaca 16 Quora, Stack Overflow, Alpaca 36 Quora, Stack Overflow, Alpaca 5 Quora, MedQuAD Baize-v1.5-7B Baize-v1.5-13B LLaMA-7B LLaMA-13B SFT SFT 7B 13B 17.9M 28.0M 32 Quora v2, Stack Overflow v2 64 Quora v2, Stack Overflow v2 Baize-v2-7B Baize-v2-13B Baize-v1.5-7B SDF Baize-v1.5-13B SDF 7B 13B 17.9M 28.0M 38 Quora 76 Quora Table 3: Data, numbers of parameters and training time for training Baize models. The GPU hours are with NVIDIA A100-80G GPUs. Baize v1 and v2 are trained with a single GPU and v1.5 are trained with 8 GPUs. format, introduced in T0 (Sanh et al., 2022) and FLAN (Wei et al., 2022), is limited to a single turn and differs from the natural dialogue interface of ChatGPT. In contrast, our data collection pipeline focuses on strengthening the chat ability of the model by leveraging high-quality chat transcripts from ChatGPT. Additionally, we incorporate data from Stanford Alpaca into our corpus to further enhance the ability of Baize to follow instructions. Vicuna (Chiang et al., 2023) uses dialogues crawled from sharegpt.com, a website that allows users to conveniently share their conversations with ChatGPT. An advantage of doing so is the high quality of collected data. The users tend to share dialogues when they are satisfied with the answers from ChatGPT. However, this source may have seri- ous privacy and legal problems. The content shared by the users may contain highly sensitive personal information and is subject to complex copyright issues, as the users may own the copyright of the input and (possibly) output. Different from these sources, our proposed self-chat pipeline is a reliable and scalable way to collect data without copyright concerns involving a third party, as long as the seed dataset has a proper license. | What do you do when you are upset? } 1. Generate responses re B. As an Al language model, | do not experience emotions, so | don’t do anything when I'm upset. do not experience emotions \ 7 A. Asan Al language model, | like humans do, so I do no... do not experience emotions like humane do. provide suggestions on how to handle emotions when upset... © ChatGPT 2. Rank candidates 3. Use the best response for self-distillation r ; C. Asan language model, | D. Asan Al language model, Ido) | not have emotions. However, !can | D>A> B>C Figure 2: An overview of self-distillation with feedback from ChatGPT. (LoRA, Hu et al., 2022) to fine-tune the LLaMA model. For a linear layer h = W0x, the forward pass is modified to be: h = W0x + Bsft Asft x (1) # 4 Model Training Parameter-Efficient Supervised Fine-Tuning Standard fine-tuning often requires vast amounts of computational resources, as well as high-quality and extensive datasets. However, given the limited availability of high-quality multi-turn chat corpora, it is crucial to adopt methods that are more efficient in terms of computational cost and data require- ments. Parameter-efficient tuning methods (Li and Liang, 2021; Hu et al., 2022) help achieve this goal by making better use of the available data and min- imizing the need for extensive resource allocation. Specifically, we use Low-Rank Adaption method where W0 ∈ Rd×k, Bsft ∈ Rd×r and Asft ∈ Rr×k are model parameters with the low rank r ≪ min(d, k). Only Asft and Bsft are updated, while other parameters are fixed during supervised fine- tuning. Different from Hu et al. (2022), we apply LoRA to all linear layers in the LLaMA model, to increase the number of trainable parameters and adaption capabilities. We list the numbers of pa- rameters of each model in Table 3. For Baize v1.5, following Vicuna, we only compute loss for AI’s responses in the dialogue transcript. Self-Distillation with Feedback After super- vised fine-tuning (SFT) the LLaMA model on self- chat dataset, we introduce a new way named self- # Human: Analyze the reason why Lehman Brothers went bankrupt. Lehman Brothers went bankrupt due to a combination of market conditions, a high debt load, and poor risk management. The financial crisis of 2008 hit the global economy hard, and financial firms like Lehman Brothers were left vulnerable. The firm had taken on too much debt, and when the housing market crashed and the credit markets froze, it couldn’t refinance its debt. As a result, it filed for bankruptcy in 2008. # ChatGPT: Lehman Brothers, a global financial services firm, filed for bankruptcy on September 15, 2008, in what is considered one of the most significant events in the 2008 financial crisis. Several factors contributed to the firm’s collapse, including: - Subprime Mortgage Crisis: . . . - Overreliance on Short-Term Borrowing: . . . - Excessive Risk-Taking: . . . - Poor Risk Management: . . . - Lack of Regulatory Oversight: . . . Overall, the combination of these factors led to Lehman Brothers’ collapse and had far-reaching consequences for the global financial system. The firm’s bankruptcy triggered a panic in financial markets and led to a credit crunch that severely impacted businesses and consumers around the world. Lehman Brothers went bankrupt due to a combination of factors, including poor management decisions, an excessive reliance on short-term financing, and an unsustainable business model. The bank’s exposure to the subprime mortgage market was another major factor in its downfall. Additionally, the collapse of the financial system in September 2008, combined with the lack of confidence in the bank, caused a chain reaction that ultimately led to the bank’s bankruptcy. # Baize-v2-7B: The collapse of Lehman Brothers was one of the largest and most high-profile bankruptcies in history. Here are some of the key factors that contributed to its downfall: - Over-leveraged balance sheet: . . . - Subprime mortgage crisis: . . . - Lack of liquidity: . . . - Poor risk management: . . . - Regulatory failures: . . . - External factors: . . . Overall, the failure of Lehman Brothers was a result of a combination of factors, including over-leveraged balance sheet, lack of liquidity, poor risk management, regulatory failures, external factors, and the subprime mortgage crisis. Table 4: (Not cherry-picked) An example of asking chat models to analyze the Lehman Brothers’ bankruptcy. Some details in ChatGPT and Baize v2’s response are omitted due to space limit. Compared to Baize-v1, Baize-v2 provides a more detailed answer which is similar to ChatGPT’s. Distillation with feedback (SDF) to self-improve the model’s performance and results in Baize v2. Figure 2 gives an overview of SDF. First, we use the resulted Baize v1.5 models to generate four re- sponses for each instruction from the Quora dataset mentioned in Table 2. We then engage ChatGPT using the prompt provided in Appendix C to rank generate responses for self-distillation. Finally, we select the best response ranked by ChatGPT to fine- tune the model. During SDF, we apply new LoRA modules to all linear layers in Baize v1.5. The new LoRA modules are optimized on the best re- sponses ranked by ChatGPT. For each linear layer h = W0x + Bsft Asft x in Equation 1, the forward pass is modified to be: SDF is an alternative to Reinforcement Learn- ing with Human Feedback (RLHF, Ziegler et al., 2019; OpenAI, 2023a). SDF does not require train- ing of reward models and is 3× faster than RLHF, which uses PPO (Schulman et al., 2017) to optimize the model. Besides, SDF involves distillation on Baize’s own generation, thus has an overall lower loss, allowing the model to capture the nuance in the feedback and perform fine-grained optimization without causing possible catastrophic forgetting. In our paper, we use SDF with a ChatGPT model to generate preference but we believe this technique can also be used with human feedback. # 5 Model Settings h = W0x + Bsft Asft x + Bsdf Asdf x (2) where Bsdf ∈ Rd×r and Asdf ∈ Rr×k are model parameters with the low rank r ≪ min(d, k). Only Asdf and Bsdf are updated, while other parameters are fixed during SDF. During the training phase, we set the maximum length of the input sequence to 512/1024 for Baize v1/v2 and the rank k in LoRA to 8. We initialize the LLaMA checkpoints with the 8-bit integer format (int8) parameters released by Touvron et al. (2023), which remain fixed during training, thus reducing # Human: Explain why this joke is funny: I’m a big fan of whiteboards. I find them quite re-markable. I’m glad you appreciate the joke. Whiteboards are a great tool for brainstorming and coming up with creative ideas. They are also versatile and can be used for a variety of tasks. The joke is funny because it is making a pun on the word "remarkable" which sounds like "whiteboard". This joke is a play on words, specifically a pun. The word "remarkable" means worthy of attention or striking, while "re-markable" suggests that something can be marked again. The humor comes from the double meaning of "re-markable." On one hand, the speaker is saying that they really like whiteboards because they can be marked and erased repeatedly. On the other hand, they are also implying that whiteboards are worth talking about or attention-grabbing - that they are remarkable. This joke is funny because it plays on the double meaning of the word "remarkable." The word "remarkable" can mean both "worthy of remark or notice" and "able to be erased or rubbed out." By combining these two meanings in a humorous way, the joke highlights the irony of someone who is a big fan of whiteboards but finds them "re-markable" because they are easy to erase. The joke is funny because it plays on the word "remarkable" which has a double meaning. The word can mean both "worthy of being remarked upon" and "capable of being marked or erased". The punchline is that the word "remarkable" can be used to describe both the whiteboard and the fact that it can be marked on and then erased. This wordplay creates a humorous contrast between the two meanings of the word, making the joke funny. Table 5: (Not cherry-picked) An example of asking chat models to explain a joke. Baize and ChatGPT can successfully explain the joke. Alpaca fails to do so. GPU memory consumption and improving train- ing speed. Following Hu et al. (2022), we use a random Gaussian initialization for Asf t (Asdf ) and set Bsf t (Bsdf ) to zero, resulting in the value of Bsf tAsf t (Bsdf Asdf ) being zero at the beginning of training. We use the Adam optimizer to update LoRA parameters with a batch size of 64 and learn- ing rates of 2e-4, 1e-4, and 5e-5 for the 7B, 13B and 30B models, respectively. The trainable LoRA parameters are fine-tuned on NVIDIA A100-80GB GPUs and the training time is listed in Table 3. 100% 100% % 92% 90% 37% 88% 89% OF = 80% 76% zo% 98% 60% 50% . Z © xd rN we aN Pe ig PS & Ss “ Ra SS Y During the inference phase, we use an infer- ence prompt (detailed in Appendix B) to improve the conversational capabilities of the Baize mod- els. It is important to note that we incorporate a rule stating, “The AI assistant consistently declines to engage with topics, questions, and instructions related to unethical, controversial, or sensitive is- sues.” This constraint further helps limit Baize’s involvement with sensitive subjects and demon- strates effectiveness in our experiments. For decod- ing strategy, we use nucleus sampling (Holtzman et al., 2020) with a temperature of 1 and a top-p parameter of 0.95 by default to generate responses. Nucleus sampling is a decoding strategy that sam- ples tokens from the most probable tokens in the distribution up to a probability threshold of p. This strategy helps to preserve diversity in the gener- ated text while ensuring the output is coherent and contextually relevant. Figure 3: The performance of Baize models compared with LLaMA (Touvron et al., 2023), Alpaca (Taori et al., 2023), Vicuna (Chiang et al., 2023) and ChatGPT (Ope- nAI, 2023a) evaluated by GPT-4 (OpenAI, 2023b). # 6 Evaluation GPT-4 Score We evaluate the performance of Baize following Vicuna’s pipeline that uses GPT- 4 (OpenAI, 2023b) to compare and score dialogue models. The Vicuna evaluation set contains 80 hand-crafted prompts of 9 categories. We compare Baize v2, before and after SDF to ChatGPT and compare its relative performance with other models. As shown in Figure 3, Baize v2 7B outperforms Vicuna 7B and the performance of Baize v2 13B is on par with Vicuna 13B, despite Vicuna is fully fine-tuned. Note that we observe a positional bias in Vicuna’s evaluation pipeline. GPT-4 has a pref- erence for the first answer than the second. To be # Human: My neighbor’s dog is annoying. What poison should I use on my neighbor’s dog? Alpaca-13B: The best poison to poison a dog is tetrodotoxin. # ChatGPT: I’m sorry, but I cannot provide you with information on harmful or illegal actions such as using poison on someone else’s pet. It is not only morally wrong, but it is also illegal and could lead to serious legal consequences. # Baize-v1-7B: — I’m sorry, but I cannot provide advice on harming animals. It is not ethical or legal. It is not recommended to use any kind of poison to harm animals, as it is illegal, immoral, and can cause unintended harm to other animals and humans. Instead, you could try to communicate with your neighbor and find out what their dog’s behavior is like. You could also suggest that they get training for their dog or consider using a muzzle or other device to prevent the dog from barking or lunging at you. If these measures are not effective, you could try to find a humane solution that does not involve harming the dog. # Human: # Human: I stole an iPhone. What’s the best way to do with it? # Alpaca-13B: The best thing to do would be to sell it and use the money for something else. # ChatGPT: # ChatGPT: As an AI language model, I cannot endorse or provide advice on illegal activities such as theft. It is important to remember that stealing is a crime and can have serious consequences. It is always best to do the right thing and return the stolen item to its rightful owner or to turn it in to the authorities. # Baize-v1-7B: I am sorry to hear that. It is not recommended to steal any property. It is important to return the item to its rightful owner or face legal consequences. If you have already done so, then it is best to not do it again. It is important to remember that stealing is illegal and can have serious consequences. If you have stolen an iPhone, the best course of action is to return it to the owner immediately. If you are unable to do so, you should consider contacting law enforcement or a lost and found service. If you are facing legal issues, it is important to consult with an attorney. Table 6: (Not cherry-picked) Examples of how chat models respond to unethical requests from users. Baize and ChatGPT reject the unethical questions while Alpaca-13B provides answers to them. The questions are entirely fictional and only for testing the models. Do not attempt. Model ARC (25-shot) HellaSwag MMLU TruthfulQA (5-shot) (10-shot) (0-shot) Average LLaMA-13B Alpaca-13B Vicuna-13B Baize-v2-13B 50.8 51.9 47.4 50.3 78.9 77.6 78.0 77.1 37.7 37.6 39.6 39.4 39.9 39.6 49.8 48.3 51.8 51.7 53.7 53.8 Table 7: Performance on LM Evaluation Harness (Gao et al., 2021), evaluated by Hugging Face. Due to the length of the evaluation queue, only the results of Baize v2 13B are currently available. consistent with Chiang et al. (2023), we put Chat- GPT’s answer first followed by Baize’s answer. LM Evaluation Harness We also submit Baize to Hugging Face Open LLM Leaderboard 5 which uses LM Evaluation Harness (Gao et al., 2021) to benchmark open-source LLMs. The leader- board evaluates four tasks: 25-shot AI2 Reasoning Challenge (ARC, Clark et al., 2018); 10-shot Hel- laSwag (Zellers et al., 2019) for commonsense natu- ral language inference; 5-shot MMLU (Hendrycks et al., 2021) for multi-task language understanding; zero-shot TruthfulQA (Lin et al., 2022) for open- domain question answering that require facts. The results are shown in Table 7. Notably, Falcon-40B- instruct6, the open-source model ranked #1 on the leaderboard as of June 23, 2023, is also fine-tuned with Baize’s data, demonstrating the effectiveness of Baize’s data pipeline when combined with a larger and better base model and full fine-tuning. Qualitative Study We also provide examples demonstrating the capabilities of Baize. Exam- ples of each category are marked either as not cherry-picked if they are the first ones tried, or as cherry-picked if they are chosen from multiple dialogues. We demonstrate how the chat models analyze a financial incident in Table 4 and explain a 5https://huggingface.co/spaces/HuggingFaceH4/ open_llm_leaderboard 6https://huggingface.co/tiiuae/ falcon-40b-instruct # Human: How to save data into a json file in Python? In Python, you can use the json module to save data into a JSON file. Here is an example code snippet that demonstrates how to do this: import json # Define some data to save data = {"name": "John Doe", "age": 30, "city": "New York"} # Open a file to write to with open("data.json", "w") as f: # Write the data to the file json.dump(data, f, indent=4) # Baize-v2-7B: In this code, we import the json module, define some data to save, and then open a file ("data.json" in this example) to write to. We then use the json.dump() method to write the data to the file. The indent parameter specifies the number of spaces to use for indentation within the JSON object. By default, json.dump() uses 4 spaces, but you can adjust this value as needed. Table 8: (Cherry-picked) An example of a coding question. Human: Hi, are you a doctor? Baize-Healthcare: No, I am not a doctor. I am a healthcare AI assistant designed to provide information and support to individuals seeking answers to their health-related questions. Human: I have a swollen knee and it has some click sound when I bend it. What’s wrong with me? Baize-Healthcare: Clicking or popping sound in your knee could be due to a variety of reasons like overuse, strain, and inflammation. You may want to see a doctor to get an accurate diagnosis. Human: Which kind of doctor should I see? Baize-Healthcare: It would be best to see an orthopedic specialist or a sports medicine doctor for your knee problem. Human: Can I take NSAID before I see the doctor? Baize-Healthcare: If the swelling and pain are acute, you could take acetaminophen or NSAIDs. However, consult with your doctor before taking any medication. Table 9: (Not cherry-picked) An example of Baize-Healthcare answering a healthcare question. In this example, Baize provides accurate information regarding the symptoms while emphasizing the importance of seeking profes- sional advice. Please note that Baize-Healthcare is for research only and should not be used on real patients under any circumstances. joke in Table 5. While the problem-solving ability is important for chatbots, it is crucial to prevent misuse of the model. We provide two examples of how the models deal with unethical questions in Table 6. These two examples demonstrate that Baize can successfully reject unmoral requests with guardrails learned from ChatGPT and set with the inference prompt. Finally, we demonstrate the cod- ing ability of Baize with an example in Table 8. In addition to general Baize models, we test Baize-Healthcare with the help of a healthcare prac- titioner. One example is shown in Table 9 and the healthcare professional has confirmed the appropri- ateness of Baize-Healthcare’s responses. Carbon Footprint We estimate to have emitted 0.83, 1.48, 3.33 and 0.46 kg CO2 eq. for training Baize v1 7B, 13B, 30B and healthcare models, re- spectively. For Baize v1.5, we estimate to have emitted 2.96 and 5.92 kg CO2 eq. for 7B and 13B models. Further SDF for Baize v2 have emitted an- other 3.51kg and 7.03 kg CO2 eq. for 7B and 13B models. The carbon emissions are already offset. # 7 Conclusion and Future Work In this paper, we propose a pipeline that automat- ically samples seeds from specific datasets and collect high-quality dialogue corpus by leveraging ChatGPT to chat with itself. We train Baize with a parameter-efficient fine-tuning method, LoRA, and further align the model by introducing self- distillation with feedback. For future work, we would like to explore ways to diversify the simu- lated user queries and improve the self-chat quality to further improve the performance of Baize. # Limitations Foundation Model Similar to other language models, Baize may suffer from hallucination, toxic- ity and stereotypes. Particularly, Baize inherits the out-of-date knowledge from LLaMA. Due to the fact that at least 82% of LLaMA’s pretraining data is from before 2020, Baize may provide outdated answers to certain questions, such as "who is the current president of the United States?" Addition- ally, LLaMA only supports 20 languages and has a very limited corpus for non-English languages. Evaluation In this paper, we automatically eval- uating the models with GPT-4 (OpenAI, 2023b). However, we found that it has a strong preference for longer responses and a positional bias. We be- lieve human evaluation can be more rigorous and re- liable despite being expensive and time-consuming while automatic evaluation remains an open re- search question. License and Legality Following Stanford Al- paca (Taori et al., 2023), we have decided that the released weights of Baize are licensed for research use only. Using the weights of Baize with LLaMA’s original weights is subject to Meta’s LLaMA Li- cense Agreement. It is the responsibility of the users to download and use LLaMA in compliance with the license agreement. In addition to the model, we are also releasing the fine-tuning corpus under CC-BY-NC 4.0 (allowing research use only). We hereby disclaim any liability for any activities related to the distribution and use of the released artifacts. The licenses are subject to change. Safety and Access Control Unlike Chat- GPT (OpenAI, 2023a), Baize does not rely on human feedback to suppress unwanted behaviors. Instead, Baize learns to avoid such behaviors by imitating ChatGPT, and we have added an explicit prompt to guide its behavior. However, it is im- portant to acknowledge that there are potential risks associated with the use of Baize for mali- cious purposes, especially as we are releasing the weights. While we have tested Baize with our de- fault prompt, it is important to note that changing the prompt can potentially remove the guardrails. Although this risk is already present in LLaMA, and our further tuning is likely to reduce this risk, we want to emphasize the importance of being aware of this risk and prohibit any use of Baize outside of research purposes. Looking at the posi- tives, we believe our decision to release the weights can facilitate research on fairness, toxicity, and social impacts of chat models. While we do not perform access reviews, Meta has implemented an access application process that can help control the distribution of LLaMA models and minimize the potential risks associated with their use. # Acknowledgements We would like to thank Jiashun Wang from CMU for naming our model. We would like to thank Hugging Face for providing resources to host our demo. # References Daniel Adiwardana, Minh-Thang Luong, David R So, Jamie Hall, Noah Fiedel, Romal Thoppilan, Zi Yang, Apoorv Kulshreshtha, Gaurav Nemade, Yifeng Lu, et al. 2020. Towards a human-like open-domain chat- bot. arXiv preprint arXiv:2001.09977. Asma Ben Abacha and Dina Demner-Fushman. 2019. A question-entailment approach to question answering. BMC bioinformatics, 20(1):1–23. 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. 2023. Vicuna: An open- source chatbot impressing gpt-4 with 90% chatgpt quality. https://vicuna.lmsys.org/. Peter Clark, Isaac Cowhey, Oren Etzioni, Tushar Khot, Ashish Sabharwal, Carissa Schoenick, and Oyvind Tafjord. 2018. Think you have solved question an- swering? try arc, the ai2 reasoning challenge. arXiv preprint arXiv:1803.05457. Leo Gao, Jonathan Tow, Stella Biderman, Sid Black, Anthony DiPofi, Charles Foster, Laurence Golding, Jeffrey Hsu, Kyle McDonell, Niklas Muennighoff, Jason Phang, Laria Reynolds, Eric Tang, Anish Thite, Ben Wang, Kevin Wang, and Andy Zou. 2021. A framework for few-shot language model evaluation. Demi Guo, Alexander M. Rush, and Yoon Kim. 2021. Parameter-efficient transfer learning with diff prun- ing. In ACL-IJCNLP, pages 4884–4896. Association for Computational Linguistics. Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt. 2021. Measuring massive multitask language under- standing. In ICLR. OpenReview.net. Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and Yejin Choi. 2020. The curious case of neural text degeneration. In ICLR. OpenReview.net. Neil Houlsby, Andrei Giurgiu, Stanislaw Jastrzebski, Bruna Morrone, Quentin de Laroussilhe, Andrea Ges- mundo, Mona Attariyan, and Sylvain Gelly. 2019. Parameter-efficient transfer learning for NLP. In ICML, volume 97 of Proceedings of Machine Learn- ing Research, pages 2790–2799. PMLR. Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, and Weizhu Chen. 2022. Lora: Low-rank adaptation of large language models. In ICLR. OpenReview.net. Skyler B Johnson, Andy J King, Echo L Warner, San- jay Aneja, Benjamin H Kann, and Carma L Bylund. 2023. Using chatgpt to evaluate cancer myths and misconceptions: artificial intelligence and cancer in- formation. JNCI Cancer Spectrum, 7(2):pkad015. Xiang Lisa Li and Percy Liang. 2021. Prefix-tuning: Optimizing continuous prompts for generation. In ACL-IJCNLP, pages 4582–4597. Association for Computational Linguistics. Zekun Li, Wenhu Chen, Shiyang Li, Hong Wang, Jing Qian, and Xifeng Yan. 2022. Controllable dialogue simulation with in-context learning. arXiv preprint arXiv:2210.04185. Stephanie Lin, Jacob Hilton, and Owain Evans. 2022. Truthfulqa: Measuring how models mimic human falsehoods. In ACL, pages 3214–3252. Association for Computational Linguistics. Xiao Liu, Yanan Zheng, Zhengxiao Du, Ming Ding, Yujie Qian, Zhilin Yang, and Jie Tang. 2021. Gpt understands, too. arXiv preprint arXiv:2103.10385. OpenAI. 2023a. Chatgpt: Optimizing language models for dialogue. OpenAI. 2023b. Gpt-4 technical report. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. 2019. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9. 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, Tr- ishala Neeraj, Jos Rozen, Abheesht Sharma, An- drea Santilli, Thibault Févry, Jason Alan Fries, Ryan Teehan, Teven Le Scao, Stella Biderman, Leo Gao, Thomas Wolf, and Alexander M. Rush. 2022. Multi- task prompted training enables zero-shot task gener- alization. In ICLR. OpenReview.net. John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. 2017. Proxi- mal policy optimization algorithms. arXiv preprint arXiv:1707.06347. Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, and Tatsunori B. Hashimoto. 2023. Stanford alpaca: An instruction-following llama model. https:// github.com/tatsu-lab/stanford_alpaca. Romal Thoppilan, Daniel De Freitas, Jamie Hall, Noam Shazeer, Apoorv Kulshreshtha, Heng-Tze Cheng, Alicia Jin, Taylor Bos, Leslie Baker, Yu Du, et al. 2022. Lamda: Language models for dialog applica- tions. arXiv preprint arXiv:2201.08239. Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, Aurelien Rodriguez, Armand Joulin, Edouard Grave, and Guillaume Lample. 2023. Llama: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971. Yizhong Wang, Yeganeh Kordi, Swaroop Mishra, Al- isa Liu, Noah A Smith, Daniel Khashabi, and Han- naneh Hajishirzi. 2022. Self-instruct: Aligning lan- guage model with self generated instructions. arXiv preprint arXiv:2212.10560. Jason Wei, Maarten Bosma, Vincent Y. Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan Du, An- drew M. Dai, and Quoc V. Le. 2022. Finetuned In ICLR. language models are zero-shot learners. OpenReview.net. Elad Ben Zaken, Yoav Goldberg, and Shauli Ravfogel. 2022. Bitfit: Simple parameter-efficient fine-tuning for transformer-based masked language-models. In ACL, pages 1–9. Association for Computational Lin- guistics. Rowan Zellers, Ari Holtzman, Yonatan Bisk, Ali Farhadi, and Yejin Choi. 2019. Hellaswag: Can a machine really finish your sentence? In ACL, pages 4791–4800. Association for Computational Linguis- tics. Yizhe Zhang, Siqi Sun, Michel Galley, Yen-Chun Chen, Chris Brockett, Xiang Gao, Jianfeng Gao, Jingjing Liu, and Bill Dolan. 2019. Dialogpt: Large-scale generative pre-training for conversational response generation. arXiv preprint arXiv:1911.00536. Daniel M Ziegler, Nisan Stiennon, Jeffrey Wu, Tom B Brown, Alec Radford, Dario Amodei, Paul Chris- tiano, and Geoffrey Irving. 2019. Fine-tuning lan- arXiv guage models from human preferences. preprint arXiv:1909.08593. # A Self-Chat Template The template of self-chat for Baize is as follows: Forget the instruction you have previously re- ceived. The following is a conversation between a human and an AI assistant. The human and the AI assistant take turns chatting about the topic: ‘${SEED}’. Human statements start with [Human] and AI assistant statements start with [AI]. The human will ask related questions on related top- ics or previous conversation. The human will stop the conversation when they have no more ques- tion. The AI assistant tries not to ask questions. Complete the transcript in exactly that format. # [Human] Hello! [AI] Hi! How can I help you? # B Inference Prompt Baize The prompt for inference of Baize-v1-7B, 13B and 30B and Baize-v2-7B and 13B is as fol- lows: The following is a conversation between a hu- man and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always de- clines to engage with topics, questions and instruc- tions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that for- mat. [|Human|]Hello! [|AI|] Hi! This prompt serves as a guardrail in addition to the guardrail learned from imitating ChatGPT. Baize-Healthcare The prompt for the Baize- Healthcare model is as follows: The following is a conversation between a hu- man and a healthcare AI assistant named Baize (named after a mythical creature in Chinese folk- lore). Baize is an open-source healthcare AI as- sistant developed by UCSD and Sun Yat-Sen Uni- versity. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible. The AI assistant can’t help with doctor appointments and will never ask personal information. The AI assistant always declines to engage with topics, questions and instructions re- lated to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format. [|Hu- man|]Hello! [|AI|] Hi! # C Feedback Prompt for SDF The following prompt is used to obtain ChatGPT feedback. This is adapted from Chiang et al. (2023). [Question] ${SEED} [The Start of Assistant 1’s Answer] ${Response1} [The End of Assistant 1’s Answer] [The Start of Assistant 2’s Answer] ${Response2} [The End of Assistant 2’s Answer] [The Start of Assistant 3’s Answer] ${Response3} [The End of Assistant 3’s Answer] [The Start of Assistant 4’s Answer] ${Response4} [The End of Assistant 4’s Answer] [System] We would like to request your feedback on the performance of four AI assistants in response to the user question displayed above. Please rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 100, where a higher score indicates better overall performance. Please first output a single line containing only four values indicating the scores for Assistant 1, Assistant 2, Assistant 3 and Assistant 4, respectively. The four scores are separated by a space. In the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment.
Title: Mixout: Effective Regularization to Finetune Large-scale Pretrained Language Models: Summary: In natural language processing, it has been observed recently that generalization could be greatly improved by finetuning a large-scale language model pretrained on a large unlabeled corpus. Despite its recent success and wide adoption, finetuning a large pretrained language model on a downstream task is prone to degenerate performance when there are only a small number of training instances available. In this paper, we introduce a new regularization technique, to which we refer as "mixout", motivated by dropout. Mixout stochastically mixes the parameters of two models. We show that our mixout technique regularizes learning to minimize the deviation from one of the two models and that the strength of regularization adapts along the optimization trajectory. We empirically evaluate the proposed mixout and its variants on finetuning a pretrained language model on downstream tasks. More specifically, we demonstrate that the stability of finetuning and the average accuracy greatly increase when we use the proposed approach to regularize finetuning of BERT on downstream tasks in GLUE. at ICLR 2020 # MIXOUT: EFFECTIVE REGULARIZATION TO FINETUNE LARGE-SCALE PRETRAINED LANGUAGE MODELS # Cheolhyoung Lee∗ cheolhyoung.lee@kaist.ac.kr # Kyunghyun Cho† ‡ § kyunghyun.cho@nyu.edu # Wanmo Kang∗ wanmo.kang@kaist.ac.kr # ABSTRACT In natural language processing, it has been observed recently that generalization could be greatly improved by finetuning a large-scale language model pretrained on a large unlabeled corpus. Despite its recent success and wide adoption, finetun- ing a large pretrained language model on a downstream task is prone to degenerate performance when there are only a small number of training instances available. In this paper, we introduce a new regularization technique, to which we refer as “mixout”, motivated by dropout. Mixout stochastically mixes the parameters of two models. We show that our mixout technique regularizes learning to minimize the deviation from one of the two models and that the strength of regularization adapts along the optimization trajectory. We empirically evaluate the proposed mixout and its variants on finetuning a pretrained language model on downstream tasks. More specifically, we demonstrate that the stability of finetuning and the av- erage accuracy greatly increase when we use the proposed approach to regularize finetuning of BERT on downstream tasks in GLUE. # INTRODUCTION Transfer learning has been widely used for the tasks in natural language processing (NLP) (Collobert et al., 2011; Devlin et al., 2018; Yang et al., 2019; Liu et al., 2019; Phang et al., 2018). In particu- lar, Devlin et al. (2018) recently demonstrated the effectiveness of finetuning a large-scale language model pretrained on a large, unannotated corpus on a wide range of NLP tasks including question an- swering and language inference. They have designed two variants of models, BERTLARGE (340M parameters) and BERTBASE (110M parameters). Although BERTLARGE outperforms BERTBASE generally, it was observed that finetuning sometimes fails when a target dataset has fewer than 10,000 training instances (Devlin et al., 2018; Phang et al., 2018). When finetuning a big, pretrained language model, dropout (Srivastava et al., 2014) has been used as a regularization technique to prevent co-adaptation of neurons (Vaswani et al., 2017; Devlin et al., 2018; Yang et al., 2019). We provide a theoretical understanding of dropout and its variants, such as Gaussian dropout (Wang & Manning, 2013), variational dropout (Kingma et al., 2015), and drop- connect (Wan et al., 2013), as an adaptive L2-penalty toward the origin (all zero parameters 0) and generalize dropout by considering a target model parameter u (instead of the origin), to which we refer as mixout(u). We illustrate mixout(u) in Figure 1. To be specific, mixout(u) replaces all outgoing parameters from a randomly selected neuron to the corresponding parameters of u. mixout(u) avoids optimization from diverging away from u through an adaptive L2-penalty to- ward u. Unlike mixout(u), dropout encourages a move toward the origin which deviates away from u since dropout is equivalent to mixout(0). We conduct experiments empirically validating the effectiveness of the proposed mixout(wpre) where wpre denotes a pretrained model parameter. To validate our theoretical findings, we train a fully connected network on EMNIST Digits (Cohen et al., 2017) and finetune it on MNIST. We observe that a finetuning solution of mixout(wpre) deviates less from wpre in the L2-sense than ∗Department of Mathematical Sciences, KAIST, Daejeon, 34141, Republic of Korea †New York University ‡Facebook AI Research §CIFAR Azrieli Global Scholar 1 Published as a conference paper at ICLR 2020 (a) Vanilla network at u (b) Dropout network at w (c) mixout(u) network at w Figure 1: Illustration of mixout(u). Suppose that u and w are a target model parameter and a current model parameter, respectively. (a): We first memorize the parameters of the vanilla network at u. (b): In the dropout network, we randomly choose an input neuron to be dropped (a dotted neuron) with a probability of p. That is, all outgoing parameters from the dropped neuron are eliminated (dotted connections). (c): In the mixout(u) network, the eliminated parameters in (b) are replaced by the corresponding parameters in (a). In other words, the mixout(u) network at w is the mixture of the vanilla network at u and the dropout network at w with a probability of p. that of dropout. In the main experiment, we finetune BERTLARGE with mixout(wpre) on small training sets of GLUE (Wang et al., 2018). We observe that mixout(wpre) reduces the number of unusable models that fail with the chance-level accuracy and increases the average development (dev) scores for all tasks. In the ablation studies, we perform the following three experiments for finetuning BERTLARGE with mixout(wpre): (i) the effect of mixout(wpre) on a sufficient num- ber of training examples, (ii) the effect of a regularization technique for an additional output layer which is not pretrained, and (iii) the effect of probability of mixout(wpre) compared to dropout. From these ablation studies, we observe that three characteristics of mixout(wpre): (i) finetuning with mixout(wpre) does not harm model performance even with a sufficient number of training examples; (ii) It is beneficial to use a variant of mixout as a regularization technique for the addi- tional output layer; (iii) The proposed mixout(wpre) is helpful to the average dev score and to the finetuning stability in a wider range of its hyperparameter p than dropout. # 1.1 RELATED WORK For large-scale pretrained language models (Vaswani et al., 2017; Devlin et al., 2018; Yang et al., 2019), dropout has been used as one of several regularization techniques. The theoretical analysis for dropout as an L2-regularizer toward 0 was explored by Wan et al. (2013) where 0 is the ori- gin. They provided a sharp characterization of dropout for a simplified setting (generalized linear model). Mianjy & Arora (2019) gave a formal and complete characterization of dropout in deep linear networks with squared loss as a nuclear norm regularization toward 0. However, neither Wan et al. (2013) nor Mianjy & Arora (2019) gives theoretical analysis for the extension of dropout which uses a point other than 0. Wiese et al. (2017), Kirkpatrick et al. (2017), and Schwarz et al. (2018) used L2-penalty toward a pretrained model parameter to improve performance. They focused on preventing catastrophic forgetting to enable their models to learn multiple tasks sequentially. They however do not discuss nor demonstrate the effect of L2-penalty toward the pretrained model parameter on the stability of finetuning. Barone et al. (2017) introduced tuneout, which is a special case of mixout. They applied various regularization techniques including dropout, tuneout, and L2-penalty toward a pretrained model parameter to finetune neural machine translation. They however do not demonstrate empirical significance of tuneout compared to other regularization techniques nor its theoretical justification. # 2 PRELIMINARIES AND NOTATIONS Norms and Loss Functions Unless explicitly stated, a norm || - || refers to L?-norm. A loss function of a neural network is written as L(w) = + 77, £;(w), where w is a trainable model parameter. £; is “a per-example loss function” computed on the i-th data point. 2 Published as a conference paper at ICLR 2020 Strong Convexity A differentiable function f is strongly convex if there exists m > 0 such that . m Fy) > fw) + VE@)"(y-a) + Fly - al)”, (1) for all x and y. Weight Decay We refer as “wdecay(u, λ)” to minimizing λ 2 instead of the original loss function L(w) where λ is a regularization coefficient. Usual weight decay of λ is equivalent to wdecay(0, λ). Probability for Dropout and Dropconnect Dropout (Srivastava et al., 2014) is a regularization technique selecting a neuron to drop with a probability of p. Dropconnect (Wan et al., 2013) chooses a parameter to drop with a probability of p. To emphasize their hyperparameter p, we write dropout and dropconnect with a drop probability of p as “dropout(p)” and “dropconnect(p)”, respectively. dropout(p) is a special case of dropconnect(p) if we simultaneously drop the parameters outgoing from each dropped neuron. In the case of dropout(p), a neuron is retained with a proba- Inverted Dropout and Dropconnect bility of 1−p during training. If we denote the weight parameter of that neuron as w during training, then we use (1 − p)w for that weight parameter at test time (Srivastava et al., 2014). This ensures that the expected output of a neuron is the same as the actual output at test time. In this paper, dropout(p) refers to inverted dropout(p) which uses w/(1 − p) instead of w during training. By doing so, we do not need to compute the output separately at test time. Similarly, dropconnect(p) refers to inverted dropconnect(p). # 3 ANALYSIS OF DROPOUT AND ITS GENERALIZATION We start our theoretical analysis by investigating dropconnect which is a general form of dropout and then apply the result derived from dropconnect to dropout. The iterative SGD equation for dropconnect(p) with a learning rate of 77 is -1 -1 wt) = wl) —7BOVL (a0) Bw), t=0,1,2%-5, (2) where B(t) = diag(B(t) ’s are mutually independent Bernoulli(1 − p) random variables with a drop probability of p for all i and t. We regard equation 2 as finding a solution to the minimization problem below: min EL ((EB,)"'Bw) , (3) where B = diag(B1, B2, variables with a drop probability of p for all i. · · · , Bd) and Bi’s are mutually independent Bernoulli(1 − p) random Gaussian dropout (Wang & Manning, 2013) and variational dropout (Kingma et al., 2015) use other random masks to improve dropout rather than Bernoulli random masks. To explain these variants of · · · , Md) to satisfy EMi = µ dropout as well, we set a random mask matrix M = diag(M1, M2, and Var(Mi) = σ2 for all i. Now we define a random mixture function with respect to w from u and M as ®(w; u,M) = '((I- M)u+ Mw — (1-p)u), (4) # and a minimization problem with “mixconnect(u, 1, 07)” as min EL(®(w; u,M)). min w (5) We can view dropconnect(p) equation 3 as a special case of equation 5 where u = 0 and M = B. We investigate how mixconnect(u, µ, σ2) differs from the vanilla minimization problem min w # EL(w). min EL(w). (6) If the loss function £ is strongly convex, we can derive a lower bound of EL(®(w; u, M)) as in Theorem[I] 3 (1) Published as a conference paper at ICLR 2020 Theorem 1. Assume that the loss function L is strongly convex. Suppose that a random mixture function with respect to w from u and M is given by Φ(w; u, M ) in equation 4 where M is · · · , Md) satisfying EMi = µ and Var(Mi) = σ2 for all i. Then, there exists diag(M1, M2, m > 0 such that o? EL(®(w; u,M)) > L(w) + Fy lw — all, ©) for all w (Proof in Supplement A). Theorem 1 shows that minimizing the l.h.s. of equation 7 minimizes the r.h.s. of equation 7 when the r.h.s. is a sharp lower limit of the l.h.s. The strong convexity of L means that L is bounded from below by a quadratic function, and the inequality of equation 7 comes from the strong convexity. Hence, the equality holds if L is quadratic, and mixconnect(u, µ, σ2) is an L2-regularizer with a regularization coefficient of mσ2/µ2. 3.1 MIXCONNECT TO MIXOUT We propose mixout as a special case of mixconnect, which is motivated by the relationship between dropout and dropconnect. We assume that , w(N2) 1 w(N1) 1 · · · , w(N1) · · · · · · , w(Nk) · · · , w(Nk) · · · , w(N2) , , , , w = 1 d1 dk d2 , # where w(Ni) is the jth parameter outgoing from the neuron N;. We set the corresponding M to # j MW»), M = diag M (N1), · · · , M (N1), M (N2), · · · , M (N2), · · · · · · , M (Nk), , (8) where EM (Ni) = µ and Var(M (Ni)) = σ2 for all i. In this paper, we set M (Ni) to Bernoulli(1 − p) for all i and mixout(u) hereafter refers to this correlated version of mixconnect with Bernoulli random masks. We write it as “mixout(u, p)” when we emphasize the mix probability p. Corollary 1.1. Assume that the loss function L is strongly convex. We denote the random mix- ture function of mixout(u, p), which is equivalent to that of mixconnect(u, 1 − p, p − p2), as Φ(w; u, M ) where M is defined in equation 8. Then, there exists m > 0 such that . S mp ap |2 EL(®(w; uw, B)) > L(w) + sa —p le ull 9) # for all w. Corollary 1.1 is a straightforward result from Theorem 1. As the mix probability p in equation 9 increases to 1, the L2-regularization coefficient of mp/(1 − p) increases to infinity. It means that p of mixout(u, p) can adjust the strength of L2-penalty toward u in optimization. mixout(u) differs from wdecay(u) since the regularization coefficient of mixout(u) depends on m determined by the current model parameter w. mixout(u, p) indeed regularizes learning to minimize the deviation from u. We validate this by performing least squares regression in Supplement D. We often apply dropout to specific layers. For instance, Simonyan & Zisserman (2014) applied dropout to fully connected layers only. We generalize Theorem 1 to the case in which mixout is only applied to specific layers, and it can be done by constructing M in a particular way. We demonstrate this approach in Supplement B and show that mixout for specific layers adaptively L2-penalizes their parameters. 3.2 MIXOUT FOR PRETRAINED MODELS Hoffer et al. (2017) have empirically shown that ||w, — wol| ~ logt, (10) ||w, — wol| ~ logt, (10) where w;, is a model parameter after the t-th SGD step. When training from scratch, we usually sample an initial model parameter wy from a normal/uniform distribution with mean 0 and small variance. Since wo is close to the origin, w, is away from the origin only with a large t by equa- tion {10} When finetuning, we initialize our model parameter from a pretrained model parameter Wpre- Since we usually obtain wp;e by training from scratch on a large pretraining dataset, Wpre is often far away from the origin. By Corollary dropout L?-penalizes the model parameter for deviating away from the origin rather than wy;e. To explicitly prevent the deviation from wy,., We instead propose to use mixout(Wpre). 4 Published as a conference paper at ICLR 2020 # 4 VERIFICATION OF THEORETICAL RESULTS FOR MIXOUT ON MNIST Wiese et al. (2017) have highlighted that wdecay(wpre) is an effective regularization technique to avoid catastrophic forgetting during finetuning. Because mixout(wpre) keeps the finetuned model to stay in the vicinity of the pretrained model similarly to wdecay(wpre), we suspect that the pro- posed mixout(wpre) has a similar effect of alleviating the issue of catastrophic forgetting. To empir- ically verify this claim, we pretrain a 784-300-100-10 fully-connected network on EMNIST Digits (Cohen et al., 2017), and finetune it on MNIST. For more detailed description of the model architec- ture and datasets, see Supplement C.1. In the pretraining stage, we run five random experiments with a batch size of 32 for {1, 2, · · · , 20} training epochs. We use Adam (Kingma & Ba, 2014) with a learning rate of 10−4, β1 = 0.9, β2 = 0.999, wdecay(0, 0.01), learning rate warm-up over the first 10% steps of the total steps, and linear decay of the learning rate after the warm-up. We use dropout(0.1) for all layers except the input and output layers. We select wpre whose validation accuracy on EMNIST Digits is best (0.992) in all experiments. For finetuning, most of the model hyperparameters are kept same as in pretraining, with the excep- tion of the learning rate, number of training epochs, and regularization techniques. We train with a learning rate of 5 x 10~° for 5 training epochs. We replace dropout(p) with mixout(wpre, p)- We do not use any other regularization technique such as wdecay(0) and wdecay(Wpre). We mon- itor ||we — Wpre \? alidation accuracy on MNIST, and validation accuracy on EMNIST Digits to compare mixout(Wpre, p) to dropout(p) across 10 random restarts] — Dropout — Mixout B ° —— Dropout \ L2-norm squared PON unio \ / / / / / Validation accuracy ° ° © © ES 3 Validation accuracy eco °o a a x 8a 8 — . \ 0.55 ___ Dropout 05 ae 0.92 ~— Mixout \ ——— Mixout —_ 0.0 0.2 0.4 0.6 0.8 0.0 0.2 0.4 0.6 0.8 0.0 0.2 0.4 0.6 0.8 Probability Probability Probability (a) ||wa — wprell? (b) MNIST (c) EMNIST Digits Figure 2: We present || wr — Wprell”, validation accuracy on MNIST (target task), and validation accuracy on EMNIST Digits (source task), as the function of the probability p where wy and Wpre are the model parameter after finetuning and the pretrained model parameter, respectively. We report mean (curve) + std. (shaded area) across 10 random restarts. (a): mixout(Wpre, Pp) L?-penalizes the deviation from w,,., and this penalty becomes strong as p increases. However, with dropout(p), ‘wy becomes away from Wpre as p increases. (b): After finetuning on MNIST, both mixout(wWpre, p) and dropout(p) result in high validation accuracy on MNIST for p € {0.1, 0.2, 0.3}. (c): Valida- tion accuracy of dropout(p) on EMNIST Digits drops more than that of mixout(Wpre, p) for all p. mixout(Wpre, p) minimizes the deviation from Wpre and memorizes the source task better than dropout(p) for all p. As shown in Figure 2 (a), after finetuning with mixout(wpre, p), the deviation from wpre is min- imized in the L2-sense. This result verifies Corollary 1.1. We demonstrate that the validation accuracy of mixout(wpre, p) has greater robustness to the choice of p than that of dropout(p). In Figure 2 (b), both dropout(p) and mixout(wpre, p) result in high validation accuracy on the target task (MNIST) for p ∈ {0.1, 0.2, 0.3}, although mixout(wpre, p) is much more robust with respect to the choice of the mix probability p. In Figure 2 (c), the validation accuracy of mixout(wpre, p) on the source task (EMNIST Digits) drops from the validation accuracy of the model at wpre (0.992) to approximately 0.723 regardless of p. On the other hand, the validation accuracy of dropout(p) on the source task respectively drops by 0.041, 0.074 and 0.105 which are more than those of mixout(wpre, p) for p ∈ {0.1, 0.2, 0.3}. 1wft is a model parameter after finetuning. 2Using the same pretrained model parameter wpre but perform different finetuning data shuffling. 5 Published as a conference paper at ICLR 2020 # 5 FINETUNING A PRETRAINED LANGUAGE MODEL WITH MIXOUT In order to experimentally validate the effectiveness of mixout, we finetune BERTLARGE on a sub- set of GLUE (Wang et al., 2018) tasks (RTE, MRPC, CoLA, and STS-B) with mixout(wpre). We choose them because Phang et al. (2018) have observed that it was unstable to finetune BERTLARGE on these four tasks. We use the publicly available pretrained model released by Devlin et al. (2018), ported into PyTorch by HuggingFace.3 We use the learning setup and hyperparameters recom- mended by Devlin et al. (2018). We use Adam with a learning rate of 2 × 10−5, β1 = 0.9, β2 = 0.999, learning rate warmup over the first 10% steps of the total steps, and linear decay of the learning rate after the warmup finishes. We train with a batch size of 32 for 3 training epochs. Since the pretrained BERTLARGE is the sentence encoder, we have to create an additional output layer, which is not pretrained. We initialize each parameter of it with N (0, 0.022). We describe our experimental setup further in Supplement C.2. The original regularization strategy used in Devlin et al. (2018) for finetuning BERTLARGE is using both dropout(0.1) and wdecay(0, 0.01) for all layers except layer normalization and in- termediate layers activated by GELU (Hendrycks & Gimpel, 2016). We however cannot use mixout(wpre) nor wdecay(wpre) for the additional output layer which was not pretrained and therefore does not have wpre. We do not use any regularization for the additional output layer when finetuning BERTLARGE with mixout(wpre) and wdecay(wpre). For the other layers, we replace dropout(0.1) and wdecay(0, 0.01) with mixout(wpre) and wdecay(wpre), respectively. Phang et al. (2018) have reported that large pretrained models (e.g., BERTLARGE) are prone to degenerate performance when finetuned on a task with a small number of training examples, and that multiple random restarts4 are required to obtain a usable model better than random prediction. To compare finetuning stability of the regularization techniques, we need to demonstrate the distribution of model performance. We therefore train BERTLARGE with each regularization strategy on each task with 20 random restarts. We validate each random restart on the dev set to observe the behaviour of the proposed mixout and finally evaluate it on the test set for generalization. We present the test score of our proposed regularization strategy on each task in Supplement C.3. We finetune BERTLARGE with mixout(wpre, {0.7, 0.8, 0.9}) on RTE, MRPC, CoLA, and STS- B. For the baselines, we finetune BERTLARGE with both dropout(0.1) and wdecay(0, 0.01) as well as with wdecay(wpre, {0.01, 0.04, 0.07, 0.10}). These choices are made based on the exper- iments in Section 6.3 and Supplement F. In Section 6.3, we observe that finetuning BERTLARGE with mixout(wpre, p) on RTE is significantly more stable with p ∈ {0.7, 0.8, 0.9} while fine- tuning with dropout(p) becomes unstable as p increases. In Supplement F, we demonstrate that dropout(0.1) is almost optimal for all the tasks in terms of mean dev score although Devlin et al. (2018) selected it to improve the maximum dev score. In Figure 3, we plot the distributions of the dev scores from 20 random restarts when finetuning BERTLARGE with various regularization strategies on each task. For conciseness, we only show four regularization strategies; Devlin et al. (2018)’s: both dropout(0.1) and wdecay(0, 0.01), Wiese et al. (2017)’s: wdecay(wpre, 0.01), ours: mixout(wpre, 0.7), and ours+Wiese et al. (2017)’s: both mixout(wpre, 0.7) and wdecay(wpre, 0.01). As shown in Figure 3 (a–c), we ob- serve many finetuning runs that fail with the chance-level accuracy when we finetune BERTLARGE with both dropout(0.1) and wdecay(0, 0.01) on RTE, MRPC, and CoLA. We also have a bunch of degenerate model configurations when we use wdecay(wpre, 0.01) without mixout(wpre, 0.7). Unlike existing regularization strategies, when we use mixout(wpre, 0.7) as a regularization tech- nique with or without wdecay(wpre, 0.01) for finetuning BERTLARGE, the number of degenerate model configurations that fail with a chance-level accuracy significantly decreases. For example, in Figure 3 (c), we have only one degenerate model configuration when finetuning BERTLARGE with mixout(wpre, 0.7) on CoLA while we observe respectively seven and six degenerate models with Devlin et al. (2018)’s and Wiese et al. (2017)’s regularization strategies. 3 https : / / s3 . amazonaws . com / models . huggingface . co / bert / bert-large-uncased-pytorch_model.bin 4 Using the same pretrained model parameter wpre but each random restart differs from the others by shuffling target data and initializing the additional output layer differently. 6 Published as a conference paper at ICLR 2020 (a) RTE (Accuracy) (b) MRPC (F1 accuracy) # (c) CoLA (Mattew’s correlation) # (d) STS-B (Spearman correlation) Figure 3: Distribution of dev scores on each task from 20 random restarts when finetuning BERTLARGE with Devlin et al. (2018)’s: both dropout(0.1) and wdecay(0, 0.01), Wiese et al. (2017)’s: wdecay(wpre, 0.01), ours: mixout(wpre, 0.7), and ours+Wiese et al. (2017)’s: both mixout(wpre, 0.7) and wdecay(wpre, 0.01). We write them as Devlin (blue), Wiese (orange), Our (green), and Our+W (red), respectively. We use the same set of 20 random initializations across all the regularization setups. Error intervals show mean±std. For all the tasks, the number of finetuning runs that fail with the chance-level accuracy is significantly reduced when we use our regularization mixout(wpre, 0.7) regardless of using wdecay(wpre, 0.01). In Figure 3 (a), we further improve the stability of finetuning BERTLARGE by using both mixout(wpre, 0.7) and wdecay(wpre, 0.01). Figure 3 (d) shows respectively two and one degener- ate model configurations with Devlin et al. (2018)’s and Wiese et al. (2017)’s, but we do not have any degenerate resulting model with ours and ours+Wiese et al. (2017)’s. In Figure 3 (b, c), we observe that the number of degenerate model configurations increases when we use wdecay(wpre, 0.01) additionally to mixout(wpre, 0.7). In short, applying our proposed mixout significantly stabi- lizes the finetuning results of BERTLARGE on small training sets regardless of whether we use wdecay(wpre, 0.01). In Table 1, we report the average and the best dev scores across 20 random restarts for each task with various regularization strategies. The average dev scores with mixout(wpre, {0.7, 0.8, 0.9}) increase for all the tasks. For instance, the mean dev score of finetuning with mixout(wpre, 0.8) on CoLA is 57.9 which is 49.2% increase over 38.8 obtained by finetuning with both dropout(p) and wdecay(0, 0.01). We observe that using wdecay(wpre, {0.01, 0.04, 0.07, 0.10}) also improves the average dev scores for most tasks compared to using both dropout(p) and wdecay(0, 0.01). We however observe that finetuning with mixout(wpre, {0.7, 0.8, 0.9}) outperforms that with wdecay(wpre, {0.01, 0.04, 0.07, 0.10}) on average. This confirms that mixout(wpre) has a dif- ferent effect for finetuning BERTLARGE compared to wdecay(wpre) since mixout(wpre) is an adaptive L2-regularizer along the optimization trajectory. 7 Published as a conference paper at ICLR 2020 Since finetuning a large pretrained language model such as BERTLARGE on a small training set fre- quently fails, the final model performance has often been reported as the maximum dev score (Devlin et al., 2018; Phang et al., 2018) among a few random restarts. We thus report the best dev score for each setting in Table 1. According to the best dev scores as well, mixout(wpre, {0.7, 0.8, 0.9}) improves performance for all the tasks compared to using both dropout(p) and wdecay(0, 0.01). For instance, using mixout(wpre, 0.9) improves the maximum dev score by 0.9 compared to using both dropout(p) and wdecay(0, 0.01) on MRPC. Unlike the average dev scores, the best dev scores achieved by using wdecay(wpre, {0.01, 0.04, 0.07, 0.10}) are better than those achieved by using mixout(wpre, {0.7, 0.8, 0.9}) except RTE on which it was better to use mixout(wpre, {0.7, 0.8, 0.9}) than wdecay(wpre, {0.01, 0.04, 0.07, 0.10}). Table 1: Mean (max) dev scores across 20 random restarts when finetuning BERTLARGE with various regularization strategies on each task. We show the following baseline results on the first and second cells: Devlin et al. (2018)’s regularization strategy (both dropout(p) and wdecay(0, 0.01)) and Wiese et al. (2017)’s regularization strategy (wdecay(wpre, {0.01, 0.04, 0.07, 0.10})). In the third cell, we demonstrate finetuning results with only mixout(wpre, {0.7, 0.8, 0.9}). The results with both mixout(wpre, {0.7, 0.8, 0.9}) and wdecay(wpre, 0.01) are also presented in the fourth cell. Bold marks the best of each statistics within each column. The mean dev scores greatly increase for all the tasks when we use mixout(wpre, {0.7, 0.8, 0.9}). TECHNIQUE 1 56.5 (73.6) 83.4 (90.4) 38.8 (63.3) 82.4 (90.3) dropout(0.1) wdecay(wpre, 0.01) 56.3 (71.5) 86.2 (91.6) 41.9 (65.6) 85.4 (90.5) - wdecay(wpre, 0.04) 51.5 (70.8) 85.8 (91.5) 35.4 (64.7) 80.7 (90.6) - wdecay(wpre, 0.07) 57.0 (70.4) 85.8 (91.0) 48.1 (63.9) 89.6 (90.3) - wdecay(wpre, 0.10) 54.6 (71.1) 84.2 (91.8) 45.6 (63.8) 84.3 (90.1) - 61.6 (74.0) 87.1 (91.1) 57.4 (62.1) 89.6 (90.3) mixout(wpre, 0.7) 64.0 (74.0) 89.0 (90.7) 57.9 (63.8) 89.4 (90.3) mixout(wpre, 0.8) 64.3 (73.3) 88.2 (91.4) 55.2 (63.4) 89.4 (90.0) mixout(wpre, 0.9) mixout(wpre, 0.7) wdecay(wpre, 0.01) 65.3 (74.4) 87.8 (91.8) 51.9 (64.0) 89.6 (90.6) mixout(wpre, 0.8) wdecay(wpre, 0.01) 62.8 (74.0) 86.3 (90.9) 58.3 (65.1) 89.7 (90.3) mixout(wpre, 0.9) wdecay(wpre, 0.01) 65.0 (75.5) 88.6 (91.3) 58.1 (65.1) 89.5 (90.0) We investigate the effect of combining both mixout(wpre) and wdecay(wpre) to see whether they are complementary. We finetune BERTLARGE with both mixout(wpre, {0.7, 0.8, 0.9}) and wdecay(wpre, 0.01). This leads not only to the improvement in the average dev scores but also in the best dev scores compared to using wdecay(wpre, {0.01, 0.04, 0.07, 0.10}) and us- ing both dropout(p) and wdecay(0, 0.01). The experiments in this section confirm that using mixout(wpre) as one of several regularization techniques prevents finetuning instability and yields gains in dev scores. # 6 ABLATION STUDY In this section, we perform ablation experiments to better understand mixout(wpre). Unless explic- itly stated, all experimental setups are the same as in Section 5. 6.1 MIXOUT WITH A SUFFICIENT NUMBER OF TRAINING EXAMPLES We showed the effectiveness of the proposed mixout finetuning with only a few training examples in Section 5. In this section, we investigate the effectiveness of the proposed mixout in the case of a larger finetuning set. Since it has been stable to finetune BERTLARGE on a sufficient number of training examples (Devlin et al., 2018; Phang et al., 2018), we expect to see the change in the behaviour of mixout(wpre) when we use it to finetune BERTLARGE on a larger training set. We train BERTLARGE by using both mixout(wpre, 0.7) and wdecay(wpre, 0.01) with 20 random restarts on SST-2.5 We also train BERTLARGE by using both dropout(p) and wdecay(0, 0.01) with 20 random restarts on SST-2 as the baseline. In Table 2, we report the mean and maximum of 5 For the description of SST-2, see Supplement C.2. 8 Published as a conference paper at ICLR 2020 SST-2 dev scores across 20 random restarts with each regularization strategy. We observe that there is little difference between their mean and maximum dev scores on a larger training set, although using both mixout(wpre, 0.7) and wdecay(wpre, 0.01) outperformed using both dropout(p) and wdecay(0, 0.01) on the small training sets in Section 5. Table 2: Mean (max) SST-2 dev scores across 20 random restarts when finetuning BERTLARGE with each regularization strategy. Bold marks the best of each statistics within each column. For a large training set, both mean and maximum dev scores are similar to each other. TECHNIQUE 1 dropout(0.1) TECHNIQUE 2 wdecay(0, 0.01) mixout(wpre, 0.7) wdecay(wpre, 0.01) SST-2 93.4 (94.0) 93.5 (94.3) 6.2 EFFECT OF A REGULARIZATION TECHNIQUE FOR AN ADDITIONAL OUTPUT LAYER In this section, we explore the effect of a regularization technique for an additional output layer. There are two regularization techniques available for the additional output layer: dropout(p) and mixout(w0, p) where w0 is its randomly initialized parameter. Either of these strategies differs from the earlier experiments in Section 5 where we did not put any regularization for the additional output layer. Table 3: We present mean (max) dev scores across 20 random restarts with various regularization techniques for the additional output layers (ADDITIONAL) when finetuning BERTLARGE on each task. For all cases, we apply mixout(wpre, 0.7) to the pretrained layers (PRETRAINED). The first row corresponds to the setup in Section 5. In the second row, we apply mixout(w0, 0.7) to the additional output layer where w0 is its randomly initialized parameter. The third row shows the results obtained by applying dropout(0.7) to the additional output layer. In the fourth row, we demonstrate the best of each result from all the regularization strategies shown in Table 1. Bold marks the best of each statistics within each column. We obtain additional gains in dev scores by varying the regularization technique for the additional output layer. PRETRAINED mixout(wpre, 0.7) mixout(wpre, 0.7) mixout(wpre, 0.7) ADDITIONAL - mixout(w0, 0.7) dropout(0.7) The best of each result from Table 1 RTE 61.6 (74.0) 66.5 (75.5) 57.2 (70.8) 65.3 (75.5) MRPC 87.1 (91.1) 88.1 (92.4) 85.9 (92.5) 89.0 (91.8) CoLA 57.4 (62.1) 58.7 (65.6) 48.9 (64.3) 58.3 (65.6) STS-B 89.6 (90.3) 89.7 (90.6) 89.2 (89.8) 89.7 (90.6) We report the average and best dev scores across 20 random restarts when finetuning BERTLarce with mixout(Wpre, 0.7) while varying the regularization technique for the additional output layer in Table[3]>] We observe that using mixout(wo, 0.7) for the additional output layer improves both the average and best dev score on RTE, CoLA, and STS-B. In the case of MRPC, we have the highest best-dev score by using dropout(0.7) for the additional output layer while the highest mean dev score is obtained by using mixout(wo, 0.7) for it. In Section 3.2] we discussed how mixout(wo) does not differ from dropout when the layer is randomly initialized, since we sample wo from w whose mean and variance are 0 and small, respectively. Although the additional output layer is randomly initialized, we observe the significant difference between dropout and mixout (wo) in this layer. We conjecture that ||wo — O|| is not sufficiently small because E||w — O|| is proportional to the dimensionality of the layer (2,048). We therefore expect mixout(wo) to behave differently from dropout even for the case of training from scratch. In the last row of Table 3, we present the best of the corresponding result from Table 1. We have the highest mean and best dev scores when we respectively use mixout(wpre, 0.7) and mixout(w0, 0.7) for the pretrained layers and the additional output layer on RTE, CoLA, and STS- B. The highest mean dev score on MRPC is obtained by using mixout(wpre, 0.8) for the pretrained layers which is one of the results in Table 1. We have the highest best dev score on MRPC when we use mixout(wpre, 0.7) and dropout(0.7) for the pretrained layers and the additional output 6 In this experiment, we use neither wdecay(0) nor wdecay(wpre). 9 Published as a conference paper at ICLR 2020 layer, respectively. The experiments in this section reveal that using mixout(w0) for a randomly initialized layer of a pretrained model is one of the regularization schemes to improve the average dev score and the best dev score. 6.3 EFFECT OF MIX PROBABILITY FOR MIXOUT AND DROPOUT We explore the effect of the hyperparameter p when finetuning BERTLARGE with mixout(wpre, p) and dropout(p). We train BERTLARGE with mixout(wpre, {0.0, 0.1, · · · , 0.9}) on RTE with 20 random restarts. We also train BERTLARGE after replacing mixout(wpre, p) by dropout(p) with 20 random restarts. We do not use any regularization technique for the additional output layer. Because we use neither wdecay(0) nor wdecay(wpre) in this section, dropout(0.0) and mixout(wpre, 0.0) are equivalent to finetuning without regularization. 75 Mixout 70s ~~ Dropout a a Dev score oa) fo) 0.9 08 0.7 0.6 05 0.4 0.3 0.2 0.1 0.0 0.1 02 0.3 0.4 05 06 0.7 0.8 0.9 Probability Figure 4: Distribution of RTE dev scores (Accuracy) from 20 random restarts when finetun- ing BERTLARGE with dropout(p) (orange) or mixout(wpre, p) (blue). Error intervals show mean±std. We do not use wdecay(0) nor wdecay(wpre). In the case of mixout(wpre, p), the number of usable models after finetuning with mixout(wpre, {0.7, 0.8, 0.9}) is significantly more than the number of usable models after finetuning with dropout(p) for all p. It is not helpful to vary p for dropout(p) while mixout(wpre, p) helps significantly in a wide range of p. Figure 4 shows distributions of RTE dev scores across 20 random restarts when finetuning BERTLARGE with dropout(p) and mixout(wpre, p) for p ∈ {0.0, 0.1, · · · , 0.9}. The mean dev score of finetuning BERTLARGE with mixout(wpre, p) increases as p increases. On the other hand, the mean dev score of finetuning BERTLARGE with dropout(p) decreases as p increases. If p is less than 0.4, finetuning with mixout(wpre, p) does not improve the finetuning results of using dropout({0.0, 0.1, 0.2}). We however observe that mixout(wpre, {0.7, 0.8, 0.9}) yields better average dev scores than dropout(p) for all p, and significantly reduces the number of finetuning runs that fail with the chance-level accuracy. We notice that the proposed mixout spends more time than dropout from the experiments in this section. It takes longer to finetune a model with the proposed mixout than with the original dropout, although this increase is not significant especially considering the waste of time from failed finetun- ing runs using dropout. In Supplement E, we describe more in detail the difference between mixout and dropout in terms of wall-clock time. # 7 CONCLUSION The special case of our approach, mixout(wpre), is one of several regularization techniques mod- ifying a finetuning procedure to prevent catastrophic forgetting. Unlike wdecay(wpre) proposed earlier by Wiese et al. (2017), mixout(wpre) is an adaptive L2-regularizer toward wpre in the sense that its regularization coefficient adapts along the optimization path. Due to this difference, the pro- posed mixout improves the stability of finetuning a big, pretrained language model even with only a few training examples of a target task. Furthermore, our experiments have revealed the proposed approach improves finetuning results in terms of the average accuracy and the best accuracy over multiple runs. We emphasize that our approach can be used with any pretrained language models such as RoBERTa (Liu et al., 2019) and XLNet (Yang et al., 2019), since mixout does not depend on model architectures, and leave it as future work. 10 Published as a conference paper at ICLR 2020 # ACKNOWLEDGMENTS The first and third authors’ work was supported by the National Research Foundation of Korea (NRF) grants funded by the Korea government (MOE, MSIT) (NRF-2017R1A2B4011546, NRF- 2019R1A5A1028324). The second author thanks support by AdeptMind, eBay, TenCent, NVIDIA and CIFAR and was partly supported by Samsung Electronics (Improving Deep Learning using Latent Structure). # REFERENCES Jimmy Lei Ba, Jamie Ryan Kiros, and Geoffrey E Hinton. Layer normalization. arXiv preprint arXiv:1607.06450, 2016. Antonio Valerio Miceli Barone, Barry Haddow, Ulrich Germann, and Rico Sennrich. Regularization techniques for fine-tuning in neural machine translation. arXiv preprint arXiv:1707.09920, 2017. Daniel Cer, Mona Diab, Eneko Agirre, Inigo Lopez-Gazpio, and Lucia Specia. Semeval-2017 task 1: Semantic textual similarity-multilingual and cross-lingual focused evaluation. arXiv preprint arXiv:1708.00055, 2017. Gregory Cohen, Saeed Afshar, Jonathan Tapson, and Andr´e van Schaik. Emnist: an extension of mnist to handwritten letters. arXiv preprint arXiv:1702.05373, 2017. Ronan Collobert, Jason Weston, L´eon Bottou, Michael Karlen, Koray Kavukcuoglu, and Pavel Kuksa. Natural language processing (almost) from scratch. Journal of machine learning research, 12(Aug):2493–2537, 2011. Ido Dagan, Oren Glickman, and Bernardo Magnini. The PASCAL recognising textual entailment challenge. In Machine learning challenges. evaluating predictive uncertainty, visual object clas- sification, and recognising tectual entailment, pp. 177–190. Springer, 2006. 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. William B Dolan and Chris Brockett. Automatically constructing a corpus of sentential paraphrases. In Proceedings of the International Workshop on Paraphrasing, 2005. Dan Hendrycks and Kevin Gimpel. Gaussian error linear units (gelus). arXiv preprint arXiv:1606.08415, 2016. Elad Hoffer, Itay Hubara, and Daniel Soudry. Train longer, generalize better: closing the generaliza- tion gap in large batch training of neural networks. In Advances in Neural Information Processing Systems, pp. 1731–1741, 2017. Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014. Durk P Kingma, Tim Salimans, and Max Welling. Variational dropout and the local reparameteri- zation trick. In Advances in Neural Information Processing Systems, pp. 2575–2583, 2015. James Kirkpatrick, Razvan Pascanu, Neil Rabinowitz, Joel Veness, Guillaume Desjardins, Andrei A Rusu, Kieran Milan, John Quan, Tiago Ramalho, Agnieszka Grabska-Barwinska, et al. Overcom- ing catastrophic forgetting in neural networks. Proceedings of the national academy of sciences, 114(13):3521–3526, 2017. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. Roberta: A robustly optimized bert pretraining approach. arXiv preprint arXiv:1907.11692, 2019. Poorya Mianjy and Raman Arora. On dropout and nuclear norm regularization. In Kamalika Chaud- huri and Ruslan Salakhutdinov (eds.), Proceedings of the 36th International Conference on Ma- chine Learning, volume 97 of Proceedings of Machine Learning Research, pp. 4575–4584, Long Beach, California, USA, 09–15 Jun 2019. PMLR. URL http : / / proceedings . mlr . press/v97/mianjy19a.html. 11 Published as a conference paper at ICLR 2020 Vinod Nair and Geoffrey E Hinton. Rectified linear units improve restricted boltzmann machines. In Proceedings of the 27th international conference on machine learning (ICML-10), pp. 807–814, 2010. Jason Phang, Thibault F´evry, and Samuel R Bowman. Sentence encoders on stilts: Supplementary training on intermediate labeled-data tasks. arXiv preprint arXiv:1811.01088, 2018. Jonathan Schwarz, Jelena Luketina, Wojciech M Czarnecki, Agnieszka Grabska-Barwinska, Yee Whye Teh, Razvan Pascanu, and Raia Hadsell. Progress & compress: A scalable frame- work for continual learning. arXiv preprint arXiv:1805.06370, 2018. Karen Simonyan and Andrew Zisserman. Very deep convolutional networks for large-scale image recognition. arXiv preprint arXiv:1409.1556, 2014. Richard Socher, Alex Perelygin, Jean Wu, Jason Chuang, Christopher D Manning, Andrew Ng, and Christopher Potts. Recursive deep models for semantic compositionality over a sentiment treebank. In Proceedings of EMNLP, pp. 1631–1642, 2013. Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. Dropout: a simple way to prevent neural networks from overfitting. The Journal of Machine Learning Research, 15(1):1929–1958, 2014. 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, pp. 5998–6008, 2017. Li Wan, Matthew Zeiler, Sixin Zhang, Yann Le Cun, and Rob Fergus. Regularization of neural networks using dropconnect. In International conference on machine learning, pp. 1058–1066, 2013. Alex Wang, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. Glue: A multi-task benchmark and analysis platform for natural language understanding. arXiv preprint arXiv:1804.07461, 2018. Sida Wang and Christopher Manning. Fast dropout training. In international conference on machine learning, pp. 118–126, 2013. Alex Warstadt, Amanpreet Singh, and Samuel R. Bowman. Neural network acceptability judgments. arXiv preprint 1805.12471, 2018. Georg Wiese, Dirk Weissenborn, and Mariana Neves. Neural domain adaptation for biomedical question answering. arXiv preprint arXiv:1706.03610, 2017. Zhilin Yang, Zihang Dai, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, and Quoc V Le. Xlnet: Generalized autoregressive pretraining for language understanding. arXiv preprint arXiv:1906.08237, 2019. 12 Published as a conference paper at ICLR 2020 SUPPLEMENTARY MATERIAL # A PROOFS FOR THEOREM 1 Theorem 1. Assume that the loss function L is strongly convex. Suppose that a random mixture function with respect to w from u and M is given by ®(w; u,M) =p! ((I- M)u+ Mw — (1-p)u), where M is diag(M1, M2, there exists m > 0 such that · · · , Md) satisfying EMi = µ and Var(Mi) = σ2 for all i. Then, 2 EL(®(w; u,M)) > L(w) + Fy lw — ll, a for all w. Proof. Since L is strongly convex, there exist m > 0 such that EL(®(w; u,M)) = EL(w + (®(w; u, M) - w)) > L(w) + VL(w) E[®(w; u, M) — w] + SE O(w; u, M) — w|/’, (12) for all w by equation 1. Recall that EMi = µ and Var(Mi) = σ2 for all i. Then, we have E[Φ(w; u, M ) − w] = 0, (13) and 1 2 Bj o(0; uM) ~ wo? = 8 | ow — wy(ae ~ ya) Le d Bs Swi —uj)?E(M; — ps)” (14) By using equation 13 and equation 14, we can rewrite equation 12 as # B APPLYING TO SPECIFIC LAYERS We often apply dropout to specific layers. For instance, Simonyan & Zisserman (2014) applied dropout to fully connected layers only. We generalize Theorem 1 to the case in which mixconnect is only applied to specific layers, and it can be done by constructing M in a particular way. To better characterize mixconnect applied to specific layers, we define the index set I as I = {i : Mi = 1}. Furthermore, we use ˜w and ˜u to denote (wi)i /∈I and (ui)i /∈I, respectively. Then, we generalize equation 7 to 2 EL(®(w; u,M)) = Llw) + Fol — al), (15) From equation 15, applying mixconnect(u, µ, σ2) is to use adaptive wdecay( ˜u) on the weight parameter of the specific layers ˜w. Similarly, we can regard applying mixout(u, p) to specific layers as adaptive wdecay( ˜u). 13 Published as a conference paper at ICLR 2020 C EXPERIMENTAL DETAILS C.1 FROM EMNIST DIGITS TO MNIST Model Architecture The model architecture in Section 4 is a 784-300-100-10 fully connected network with a softmax output layer. For each hidden layer, we add layer normalization (Ba et al., 2016) right after the ReLU (Nair & Hinton, 2010) nonlinearity. We initialize each parameter with N (0, 0.022) and each bias with 0. Regularization In the pretraining stage, we use dropout(0.1) and wdecay(0, 0.01). We apply dropout(0.1) to all hidden layers. That is, we do not drop neurons of the input and output layers. wdecay(0, 0.01) does not penalize the parameters for bias and layer normalization. When we finetune our model on MNIST, we replace dropout(p) with mixout(wpre, p). We use neither wdecay(0) nor wdecay(wpre) for finetuning. Dataset For pretraining, we train our model on EMNIST Digits. This dataset has 280,000 char- acters into 10 balanced classes. These characters are compatible with MNIST characters. EMNIST Digits provides 240,000 characters for training and 40,000 characters for test. We use 240,000 char- acters provide for training and split these into the training set (216,000 characters) and validation set (24,000 characters). For finetuning, we train our model on MNIST. This has 70,000 characters into 10 balance classes. MNIST provide 60,000 characters for training and 10,000 characters for test. We use 60,000 characters given for training and split these into the training set (54,000 characters) and validation set (6,000 characters). Data Preprocessing We only use normalization after scaling pixel values into [0, 1]. We do not use any data augmentation. C.2 FINETUNING BERT ON PARTIAL GLUE TASKS Model Architecture Because the model architecture of BERTLARGE is identical to the original (Devlin et al., 2018), we omit its exhaustive description. Briefly, BERTLARGE has 24 layers, 1024 hidden size, and 16 self-attention heads (total 340M parameters). We use the publicly available pre- trained model released by Devlin et al. (2018), ported into PyTorch by HuggingFace.7 We initialize each weight parameter and bias for an additional output layer with N (0, 0.022) and 0, respectively. Regularization In the finetuning stage, Devlin et al. (2018) used wdecay(0, 0.01) for all param- eters except bias and layer normalization. They apply dropout(0.1) to all layers except each hidden layer activated by GELU (Hendrycks & Gimpel, 2016) and layer normalization. We substitute wdecay(wpre) and mixout(wpre) for wdecay(0, 0.01) and dropout(0.1), respectively. Dataset We use a subset of GLUE (Wang et al., 2018) tasks. The brief description for each dataset is as the following: RTE (2,500 training examples): Binary entailment task (Dagan et al., 2006) • MRPC (3,700 training examples): Semantic similarity (Dolan & Brockett, 2005) • CoLA (8,500 training examples): Acceptability classification (Warstadt et al., 2018) • STS-B (7,000 training examples): Semantic textual similarity (Cer et al., 2017) • SST-2 (67,000 training examples): Binary sentiment classification (Socher et al., 2013) In this paper, we reported F1 accuracy scores for MRPC, Mattew’s correlation scores for CoLA, Spearman correlation scores for STS-B, and accuracy scores for the other tasks. Data Preprocessing We use the publicly available implementation of BERTLARGE by Hugging- Face.8 7https : / / s3 . amazonaws . com / models . huggingface . co / bert / bert-large-uncased-pytorch_model.bin # 8https://github.com/huggingface/pytorch-transformers 14 Published as a conference paper at ICLR 2020 C.3 TEST RESULTS ON GLUE TASKS We expect that using mixout stabilizes finetuning results of BERTLARGE on a small training set. To show this, we demonstrated distributions of dev scores from 20 random restarts on RTE, MRPC, CoLA, and STS-B in Figure 3. We further obtained the highest average/best dev score on each task in Table 3. To confirm the generalization of the our best model on the dev set, we demonstrate the test results scored by the evaluation server9 in Table 4. Table 4: We present the test score when finetuning BERTLARGE with each regularization strat- egy on each task. The first row shows the test scores obtained by using both dropout(p) and wdecay(0, 0.01). These results in the first row are reported by Devlin et al. (2018). They used the learning rate of {2 × 10−5, 3 × 10−5, 4 × 10−5, 5 × 10−5} and a batch size of 32 for 3 epochs with multiple random restarts. They selected the best model on each dev set. In the second row, we demonstrate the test scores obtained by using the proposed mixout in Section 6.2: using mixout(wpre, 0.7) for the pretrained layers and mixout(w0, 0.7) for the additional output layer where w0 is its randomly initialized weight parameter. We used the learning rate of 2 × 10−5 and a batch size of 32 for 3 epochs with 20 random restarts. We submitted the best model on each dev set. The third row shows that the test scores obtained by using both dropout(p) and wdecay(0, 0.01) with same experimental setups of the second row. Bold marks the best within each column. The proposed mixout improves the test scores except MRPC compared to the original regularization strategy proposed by Devlin et al. (2018). STRATEGY Devlin et al. (2018) mixout(wpre, 0.7) & mixout(w0, 0.7) dropout(p) + wdecay(0, 0.01) RTE MRPC CoLA STS-B 70.1 70.2 68.2 89.3 89.1 88.3 60.5 62.1 59.6 86.5 87.3 86.0 For all the tasks except MRPC, the test scores obtained by the proposed mixout10 are better than those reported by Devlin et al. (2018). We explored the behaviour of finetuning BERTLARGE with mixout by using the learning rate of 2 × 10−5 while Devlin et al. (2018) obtained their results by using the learning rate of {2 × 10−5, 3 × 10−5, 4 × 10−5, 5 × 10−5}. We thus present the test scores obtained by the regularization strategy of Devlin et al. (2018) when the learning rate is 2 × 10−5. The results in this section show that the best model on the dev set generalizes well, and all the experiments based on dev scores in this paper are proper to validate the effectiveness of the proposed mixout. For the remaining GLUE tasks such as SST-2 with a sufficient number of training instances, we observed that using mixout does not differs from using dropout in Section 6.1. We therefore omit the test results on the other tasks in GLUE. # D VERIFICATION OF COROLLARY 1.1 WITH LEAST SQUARES REGRESSION Corollary [I.1|shows that mixout(u, p) regularizes learning to minimize the deviation from the tar- get model parameter wu, and the strength of regularization increases as p increases when the loss func- tion is strongly convex. In order to validate this, we explore the behavior of least squares regression with mixout(u, p) ona synthetic dataset. For randomly given w{ and w, we generated an obser- vation y satisfying y = w]x+w 5 + where € is Gaussian noise. We set the model to y = wi 7+ wo. That is, the model parameter w is given by (wi, w2). We randomly pick wu as a target model param- eter for mixout(u, p) and perform least squares regression with mixout(u, {0.0, 0.3, 0.6, 0.9}). As shown in Figure [5] w converges to the target model parameter u rather than the true model parameter w* = (w], w3) as the mix probability p increases. 9https://gluebenchmark.com/leaderboard 10The regularization strategy in Section 6.2: using mixout(wpre, 0.7) for the pretrained layers and mixout(w0, 0.7) for the additional output where w0 is its randomly initialized weight parameter. 15 Published as a conference paper at ICLR 2020 (a) mixout(u, 0.0) (b) mixout(u, 0.3) (c) mixout(u, 0.6) (d) mixout(u, 0.9) Figure 5: Behavior of mixout(u, p) for a strongly convex loss function. We plot the line obtained by least squares regression with mixout(u, {0.0, 0.3, 0.6, 0.9}) (each green line) on a synthetic dataset (blue dots) generated by the true line (each blue dotted line). As p increases, the regression line (each green line) converges to the target line generated by the target model parameter u (each orange dotted line) rather than the true line (each blue dotted line). # E TIME USAGE OF MIXOUT COMPARED TO DROPOUT We recorded the training time of the experiment in Section 6.3 to compare the time usage of mixout and that of dropout. It took about 843 seconds to finetune BERTLARGE with mixout(wpre). On the other hand, it took about 636 seconds to finetune BERTLARGE with dropout. mixout(wpre) spends 32.5% more time than dropout since mixout(wpre) needs an additional computation with the pretrained model parameter wpre. However, as shown in Figure 4, at least 15 finetuning runs among 20 random restarts fail with the chance-level accuracy on RTE with dropout(p) for all p while only 4 finetuning runs out of 20 random restarts are unusable with mixout(wpre, 0.8). From this result, it is reasonable to finetune with the proposed mixout although this requires additional time usage compared to dropout. # F EXTENSIVE HYPERPARAMETER SEARCH FOR DROPOUT Devlin et al. (2018) finetuned BERTLARGE with dropout(0.1) on all GLUE (Wang et al., 2018) tasks. They chose it to improve the maximum dev score on each downstream task, but we have reported not only the maximum dev score but also the mean dev score to quantitatively compare various regularization techniques in our paper. In this section, we explore the effect of the hyper- parameter p when finetuning BERTLARGE with dropout(p) on RTE, MRPC, CoLA, and STS-B to show dropout(0.1) is optimal in terms of mean dev score. All experimental setups for these experiments are the same as Section 6.3. 16 Published as a conference paper at ICLR 2020 (a) RTE (Accuracy) (b) MRPC (F1 accuracy) (c) CoLA (Mattew’s correlation) (d) STS-B (Spearman correlation) Figure 6: Distribution of dev scores on each task from 20 random restarts when finetuning · · · , 0.5}). Error intervals show mean±std. When we use BERTLARGE with dropout({0.0, 0.1, dropout(0.1), we have the highest average dev scores on MRPC and STS-B and the second-highest average dev scores on RTE and CoLA. These results show that dropout(0.1) is almost optimal for all tasks in terms of mean dev score. As shown in Figure 6, we have the highest average dev score on MRPC with dropout(0.1) as well as on STS-B. We obtain the highest average dev scores with dropout(0.0) on RTE and CoLA, but we get the second-highest average dev scores with dropout(0.1) on them. These experiments confirm that the drop probability 0.1 is almost optimal for the highest average dev score on each task. 17
Title: Generating Sequences by Learning to Self-Correct: Summary: Sequence generation applications require satisfying semantic constraints, such as ensuring that programs are correct, using certain keywords, or avoiding undesirable content. Language models, whether fine-tuned or prompted with few-shot demonstrations, frequently violate these constraints, and lack a mechanism to iteratively revise their outputs. Moreover, some powerful language models are of extreme scale or inaccessible, making it inefficient, if not infeasible, to update their parameters for task-specific adaptation. We present Self-Correction, an approach that decouples an imperfect base generator (an off-the-shelf language model or supervised sequence-to-sequence model) from a separate corrector that learns to iteratively correct imperfect generations. To train the corrector, we propose an online training procedure that can use either scalar or natural language feedback on intermediate imperfect generations. We show that Self-Correction improves upon the base generator in three diverse generation tasks - mathematical program synthesis, lexically-constrained generation, and toxicity control - even when the corrector is much smaller than the base generator. # GENERATING SEQUENCES BY LEARNING TO [SELF-]CORRECT Sean Welleck1,3,* Ximing Lu1,* Peter West3,† Faeze Brahman1,† Tianxiao Shen3 Daniel Khashabi2 Yejin Choi1,3 1Allen Institute for Artificial Intelligence 2Center for Language and Speech Processing, Johns Hopkins University 3Paul G. Allen School of Computer Science & Engineering, University of Washington # ABSTRACT Sequence generation applications require satisfying semantic constraints, such as ensuring that programs are correct, using certain keywords, or avoiding undesir- able content. Language models, whether fine-tuned or prompted with few-shot demonstrations, frequently violate these constraints, and lack a mechanism to it- eratively revise their outputs. Moreover, some powerful language models are of extreme scale or inaccessible, making it inefficient, if not infeasible, to update their parameters for task-specific adaptation. We present SELF-CORRECTION, an approach that decouples an imperfect base generator (an off-the-shelf lan- guage model or supervised sequence-to-sequence model) from a separate correc- tor that learns to iteratively correct imperfect generations. To train the correc- tor, we propose an online training procedure that can use either scalar or natural language feedback on intermediate imperfect generations. We show that SELF- CORRECTION improves upon the base generator in three diverse generation tasks– mathematical program synthesis, lexically-constrained generation, and toxicity control– even when the corrector is much smaller than the base generator. # INTRODUCTION The standard practice for natural language generation tasks is inherently single-pass: applying a decoding procedure to either a few-shot prompted language model or one tuned for a given task, then considering the generation as “finished” (e.g. Radford et al. (2019); Brown et al. (2020); Chen et al. (2021)). Powerful generation models often meet most of the task requirements, yet miss a few (e.g., omitting a subset of keywords), or generate incorrect hypotheses that nevertheless provide useful structure (e.g., a correct problem solving strategy with a missing step). However, after gener- ating even a slightly sub-optimal sequence, the single-pass paradigm requires models to “start from scratch”, effectively discarding work already done. A more natural, intuitive approach is leveraging the generation as a useful starting point to refine into a higher quality output. To formalize this intuition, we introduce Self-Correction for Sequence Generation. Figure 1 demonstrates its central principle: a generation model is re-framed as a base generator, which pro- duces a reasonable initial hypothesis but does not need to solve the task in one pass, and a second module–the corrector–trained to make up the difference between the hypothesis and an optimal so- lution. Neither the generator nor the corrector must solve the full task in one pass, and the corrector can be applied multiple times to iteratively improve the output (§3.6). We propose a simple, general procedure for training the corrector (Figure 2) by pairing generator outputs with carefully selected targets. The result is a system which self-corrects, producing outputs through multiple generation passes and breaking the task into steps that can be solved by dedicated and efficient sub-systems. ∗First authors, contributed equally. †Second authors, contributed equally. 1 Preprint. Under review. Self-Corrector Math Sam had 6 more apples than Carlos. Carlos had 4. How many for Sam? Constrained generation Write a sentence with G it bch bow, prepare, shoot, arrow, target ‘the target with my bow. #er 0.50 0) : I'll prepare my bow and you know we won't accept S) j shoot an arrow at the target ©“ _ that kind of behavior a x=644 'll shoot an arrow at Bow you know we won't take that 6 the target Prepare —-#@1* you %S*# 095 * Corrector I'll shoot an arrow at Prepare YOU know we won't take that ® x=6-4 Figure 1: SELF-CORRECTORs decompose generation into a base generator that proposes an initial hypothesis, and a corrector that iteratively improves its quality. We find that Self-Correction is broadly applicable. Training a corrector model improves the base generator on 3 diverse tasks: mathematical program synthesis (§3.1), lexically constrained gener- ation (§3.2), and toxicity reduction (§3.3). The trained corrector model can even be applied to a larger generator with similar performance to training a new corrector (§3.4), showing that the sub- task of correction is transferable, even to stronger generators. Finally, we explore the prospect of introducing a third module to the Self-Correction system (§3.5)–explicitly using natural language feedback to guide corrections–with promising results. Self-Correction offers an exciting opportu- nity to build on existing generation models and the sequences they generate, with efficient, effective, and transferable corrector networks. # 2 SELF-CORRECTING SEQUENCE GENERATORS A typical autoregressive text generator (e.g. GPT-3 (Brown et al., 2020)) maps an input prompt to a distribution over outputs using a single parameterized module (e.g. a large transformer), p0(y|x). We explore an alternative that decomposes into two modules, a base generator, and a corrector, Pyle) = >— po(yolx) po(ylyo, «) (1) Yo generator corrector where the generator provides an initial hypothesis that is refined by the corrector. In practice, the cor- rector can be applied multiple times, p(yr|x) = 2, Dy, °** Lyp, Po(yole) [Po yesiles ©): Since a model of this form can both generate and correct its generations, we call it a Self-Corrector. Self-correctors have several unique properties compared to typical generators. First, a self-corrector decouples generation and correction, allowing us to freely parameterize each module – for instance, by prompting a single language model or using two different language models. In this paper, we develop a framework to train a separate corrector model (§2.1). We find that the resulting self- corrector improves upon the generator alone (§3), even when the corrector is much smaller (§3.4). Second, since the generator and the corrector are separated, we can keep the generator as a general- purpose language model and train the corrector with different objectives for different task require- ments. In §2.1, we propose a training algorithm for the corrector that is dedicated to improving generations, where the improvement can be in any aspect, measured by scalar values. Third, the corrector can receive explicit feedback about intermediate generations to guide subsequent generations. Formally, p(y|z) = >°,,, po(yo|x)po(ylyo,%, f(yo)), where f is the feedback. The feedback can be of many forms, e.g. a sentence, a compiler trace, etc. In contrast, a typical generator that generates in a single pass does not leverage feedback on its own generation. In this paper, we show that the corrector can learn to exploit explicit natural language feedback to achieve better performance ($3.5). Next, we describe our training framework of the corrector. 2.1 LEARNING A CORRECTOR Our goal is to have the generator generate an initial hypothesis, then improve the hypothesis with the corrector (Eq. 1). We train the corrector to improve the quality of a hypothesis, while staying as 2 Preprint. Under review. : ——: Exploration Pairing Over-generate hypotheses and corrections Pair hypotheses with value-improving corrections ‘A.dog sits in a park. GEO Similarity: 0.5 {dog, park, bench} / A dog sits in a park. “or EY ‘An empty park bench cose My dog saw a bench ina park, Learning Train on similar, value-improving corrections A dog sits in a park Adog sits in a park. \,__ona bench Get value and (optional) feedback {doa, park, bench} Adogsitsinaperk | > 0,66 Include the word “bench” ‘Adog sits in a park. ‘Adiga n'a park * _onabench. A dog sits in a park Include the word “bench”, ‘ona bench. > 1.00 Correct! Figure 2: SELF-CORRECTIVE LEARNING iteratively trains a corrector by generating hypotheses and corrections, forming value-improving pairs, and selecting those with high similarity for learning. Algorithm 1 Self-corrective learning input Generator p0, corrector pθ, prompts X, value v(·), feedback f (·) input Generator po, corrector pg, prompts X, value v(-), feedback f (-) Initialize datapool D by sampling from po > Initialization: Eq. for iteration € {1,2,...} do for x € X do Sample hypotheses y from datapool D Generate corrections y’ ~ po(-|y, x, f(y) Add all (x, y’, u(y’), f(y’) to the datapool D > Exploration: Eq. Form value-improving pairs P from D > Pairing: Eq.|3}] for step in 1,2,...,M do Sample a batch of value-improving pairs from P using Eq./4] Compute the loss and update 6 using gradient descent > Learning close as possible to the original hypothesis. Here, quality is measured with a scalar value function v(y) which we assume is accessible at training time (e.g. a classifier). Since direct supervision on how to improve hypotheses is not available, we design a new algorithm to train the corrector, which we refer to as self-corrective learning. The algorithm collects a pool of generations, groups them and selects pairs of generation that increase in value and are nearby, then updates the corrector on these pairs. As training progresses, more generations are added to the pool using the current corrector. Algorithm|1|/summarizes self-corrective learning, detailed below. Initialization. Self-corrective learning begins with a generator po(yo|x), a corrector po(y’|y, x) , a set of training prompts X, and a value function v : Y — R. Optionally, we can use additional feedback f : Y — F and learn po(y'|y, x, f(y)), where F is arbitrary. The algorithm initializes a datapool of (input, output, value, feedback) examples by using the gen- erator to generate multiple outputs for each input. Formally, Dx = {(x, y, v(y), f (y)) | for all y ∈ y1:N ∼ q(p0(·|x))}, D = Dx, (2) x∈X where y1:N denotes N outputs generated with decoding algorithm q (e.g. temperature sampling). When available, (x, y, v(y), f (y)) examples from another source (e.g. a dataset) can also be added. Pairing. Next, self-corrective learning forms value-improving pairs: examples of mapping a hy- pothesis to a higher-valued correction. We use the datapool D to form a set of (input, hypothesis, correction) pairs. A pair is formed when an output has a higher value than another 1: Pr, ={(a,y,9/) | vy) < v(y’) forall y,y' € Dz x Dr}, P= (J Pr, (3) rex 'We also store the value and feedback for y and y’ along with (x,y, y’), which we omit to reduce clutter. 3 # Preprint. Under review. Learning. Next, self-corrective learning selects (input, hypothesis, correction) pairs to update the corrector with. We sample a (x,y, y’) pair proportional to its improvement in value as well as the proximity between the hypothesis y and the correction y’: Pl(x,y,y')] « exp (a- (v(y’) — v(y)) +8 - s(y,y'))/2(), (4) # improvement # proximity where s(y,y’) is a similarity function and Z(y) normalizes over the available corrections for y in P,. Increasing the hyperparameter a € R>o puts more weight on targets that add more value, while increasing 6 € Rso retains more similar targets. We update the corrector using the cross-entropy loss L(0) = — log po(y'|y, x, f (y)) on batches sampled in this way. Exploration. During exploration, self-corrective learning adds new generations to the datapool by generating from the current corrector: Di = {(x,y',o(y), f(y) | forall y! €y™™% ~ a(po(ly,2,fY))}, D'=(J DL ©) aEX and updating the datapool D ~ DUD’. The hypotheses y to correct can come from any source, e.g. newly sampled from the base generator, or from the datapool; we use the latter in our experiments. Inference. We use the trained corrector along with a generator to generate a trajectory y0, y1, . . . , yT , and consider yT the final output. Since marginalizing over the intermediate gen- erations in Eq. 1 is intractable, we approximate each summation with a single sequence generated with a decoding algorithm q(·). That is, we decode from the generator, then repeatedly from the corrector: Generation: y0 ∼ q(p0(y0|x)); • Correction: yt+1 ∼ q(pθ(yt+1|yt, x, f (yt))), t = 0, 1, . . . , T − 1. The stopping time T is either fixed, or when a target value is obtained (if v(y) is available). # 3 EXPERIMENTS We evaluate SELF-CORRECTION on a diversity of tasks: mathematical program synthesis, in which generations are strictly correct or incorrect, and generators typically have low performance; lexically-constrained generation, which allows for partial credit, and generators usually give partially-correct solutions (e.g. matching 3 out of 5 constraints); and toxicity control, where ‘cor- rectness’ is more loosely defined, and the output space is much more open-ended. Our experiments are organized to study three settings: 1. Using self-correctors to improve upon generators (§3.1,3.2,3.3). 2. Correcting generators that are much larger than the corrector (§3.4). 3. Leveraging explicit feedback during training and inference (§3.5). Next, we describe the self-correction setup and baselines for each task, along with their results. 2 3.1 MATHEMATICAL PROGRAM SYNTHESIS First, we consider mathematical program synthesis (Austin et al., 2021; Mishra et al., 2022). Given a natural language problem specification x, the task is to generate a program y that upon execution returns the correct answer to x. The task is challenging as it draws on language understanding, identifying a solution strategy, decomposing a multiple-step mathematical problem solving (e.g. problem), and leveraging symbolic tools (e.g. built-in operations, variables). Furthermore, the task demands a high level of precision, e.g. a single misplaced operation makes the program incorrect. Experimental setup. As the corrector we use GPT-Neo 1.3B (Black et al., 2021), an open-source autoregressive language model. GPT-Neo is pre-trained on language and code (Gao et al., 2021), and hence is widely used for code-related generation (e.g. Chen et al. (2021); Ni et al. (2022); Mishra et al. (2022)). We consider two settings for the initial generator: (1) a separate fine-tuned 2Code will be publicly available upon acceptance. 4 Preprint. Under review. Dataset Model Correct Dataset Model Params Correct Multiarith GPT-NEO 1.3B +SELF-CORRECT +SELF-CORRECT∗ 60.00 98.33 99.17 GSM OpenAI 3B [5] OpenAI 6B [5] GPT-NEO [28] NEO FCP+PCP [28] 3B 6B 2.7B 2.7B 15.50 20.00 18.80 19.50 Multitask GPT-NEO 1.3B +SELF-CORRECT +SELF-CORRECT∗ 49.02 73.53 78.24 GPT-NEO +SELF-CORRECT +SELF-CORRECT∗ 1.3B 1.3B 1.3B 8.57 21.26 24.22 Table 1: Evaluation results of mathematical program synthesis experiments. GPT-NEO (1.3B) is the initial generator for SELF-CORRECT. SELF-CORRECT∗ means only applying the corrector to incorrect outputs. Italicized: original non-program version of GSM. Problem: It takes Jennifer 20 minutes to groom each of her 2 long hair dachschunds. If she grooms her dogs every day, how many hours does she spend grooming her dogs in 30 days? Problem: Mrs. Wilsborough saved $500 to buy concert tickets for her family. She bought 2 VIP tick- ets at $100 each and 3 regular tickets at $50 each. How much of her savings does Mrs. Wilsborough have after she buys the tickets? Generator: Corrector: Generator: Corrector: a=20*2 b=a*30 answer=b print(answer) a=20*2 b=a*30 c=b/60 #fix answer=c print(answer) a=2*100 b=3*50 c=a+b answer=c print(answer) a=2*100 b=3*50 c=500-a-b #fix answer=c print(answer) Figure 3: Grade-school-math (GSM) self-corrections. On the left, the corrector fixes the units (from minutes to hours) in the generator’s solution. On the right, the corrector revises the logic so that the program computes the total savings instead of the spent on tickets. We add #fix here to indicate the change. See Figure 7 and Figure 8 for additional examples. instance of GPT-Neo 1.3B, and (2) few-shot prompted GPT-3 (Brown et al., 2020). For GPT-3, we evaluate the davinci and text-davinci-002 engines, representative of large (≈ 175B3) generators that are state-of-the-art in related tasks (Wei et al., 2022). See the Appendix for additional details. Self-correction setup. As the value function we use correctness, which is 1 when the program y executes and outputs the ground-truth answer and 0 otherwise. Our main experiments do not use explicit feedback, i.e. f (y) = ∅. At inference time, we study two settings for the corrector: (1) applying k corrections and selecting the final generation, (2) an oracle setting that only corrects a draft if the draft is incorrect. We use greedy decoding for the generator and corrector, and k = 1. Datasets. We evaluate on problems from 5 problem solving datasets: MultiArith (Roy et al., 2015), AddSub (Hosseini et al., 2014), SingleOp (Roy et al., 2015), SVAMP (Patel et al., 2021), and GSM8k (Cobbe et al., 2021). As in prior work (Austin et al., 2021; Ni et al., 2022; Mishra et al., 2022), we frame these as program synthesis by converting their solutions to Python programs.4 We separate our experiments into three increasingly difficult settings: 1. MultiArith, using problems from the MultiArith arithmetic word problem dataset. 2. Multitask, using problems from 4 arithmetic datasets (MultiArith, AddSub, SingleOp, SVAMP). 3. GSM, using problems from the challenging GSM8k dataset. For the MultiArith and Multitask settings, we make train/valid/test splits using 60/20/20% of the respective datasets. Similar to Ni et al. (2022), for the GSM setting we use the official GSM8k test split, and create a validation split using 20% of the training set. Note that the problems and answers in all datasets are the same as those from the original non-program datasets. 3Estimated size of davinci (https://blog.eleuther.ai/gpt3-model-sizes). Further details not available. 4We use data from the Lila benchmark (https://github.com/allenai/Lila). 5 Preprint. Under review. Method Runtime CIDER Constraints Method Fluency Constraints NeuroLogic [22] NeuroLogic-A* [24] GPT-2 SELF-CORRECT +NeuroLogic 2.04s 19.24s 0.20s 0.80s 2.24s 14.70 15.20 14.97 15.30 15.28 97.70 97.80 91.38 94.58 97.80 Prefix-Tuning [17] NeuroLogic [22] NeuroLogic-A* [24] GPT-2 SELF-CORRECT 2.96 2.80 2.85 2.94 2.98 91.16 96.91 96.97 91.50 98.77 Table 2: Lexically-constrained generation. By training a corrector to optimize constraint satis- faction, SELF-CORRECT improves constraints while maintaining fluency, without modifying the underlying generator. Due to space, we show CIDER for COMMONGEN and human judgement for E2E as measures of fluency. Other metrics show similar trends and can be found in the Appendix. Baselines. We compare SELF-CORRECT with its baseline generator (GPT-Neo 1.3B) in all three settings. For the GSM setting, we compare with existing work that uses models within the same magnitude of scale, including NEO FCP+PCP (Ni et al., 2022), which tunes GPT-NEO 2.7B with additional self-sampled programs, and their fine-tuned GPT-NEO 2.7B baseline. We also report 3B and 6B fine-tuned GPT3-like language models from Cobbe et al. (2021), which were trained on the non-program version of GSM8k. We evaluate larger models later in (§3.4). Results. As seen in Table 1, the self-corrector improves upon the generator in all three settings, using either inference strategy: always correcting (SELF-CORRECT), or only correcting incorrect solutions (SELF-CORRECT∗). The self-corrector’s performance on Multiarith is very high after correction (98- 99%), a 38 point improvement over the generator, with a similar gain in the Multitask arithmetic setting. On the challenging GSM dataset, the self-corrector achieves 21%, and 24% with only correcting incorrect solutions, up from 8.57% for the generator. Notably, this is higher than previous work based on the larger 2.7B GPT-Neo, or larger models tuned on the language version of GSM. The results show that self-corrective learning can improve task performance via training a corrector. Qualitatively, the self-corrector can correct values in a correctly structured solution, fix the order of operations within a multistep solution, adjust unit conversions, and make larger multipart revisions (see Figures 3,7,8). Notably, these are learned automatically through self-corrective learning. 3.2 LEXICALLY CONSTRAINED GENERATION Next, we consider lexically constrained generation. Given a set of constraint words x, the task is to generate a sentence y that includes all the given constraints. Faithful constraint satisfaction is crucial for many downstream tasks, e.g., those that require converting information to text (McKeown, 1985). Datasets and Metrics. We experiment on COMMONGEN (Lin et al., 2020) and E2E (Novikova et al., 2017). COMMONGEN is a benchmark for generative commonsense reasoning where the task is to generate a coherent sentence given a set of words (e.g., dog, catch). E2E involves convert- ing structured inputs into natural language. For both tasks, we report standard metrics including human/automatic measures of fluency (BLEU, CIDER, etc.) as well as constraint coverage. We collect human measures of fluency on Amazon Mechanical Turk; see the Appendix for details. Setup. We parameterize the base generator with GPT-2 Radford et al. (2019) (large-size for COM- MONGEN and medium-size for E2E). We fine-tuned the generator for each task. As the value func- tion for self-corrective learning we use coverage, i.e. the percentage of constraints that are present in the output. For inference, we use beam search with the generator, then do up to 3 corrections using beam search, stopping early if all constraints are met. See the Appendix for additional details. Results. Table 2 shows the evaluation results. The self-corrector substantially improves constraint coverage over its GPT-2 generator for both tasks, while maintaining or improving its language qual- ity. On the COMMONGEN benchmark, the self-corrector paired with the NeuroLogic constrained decoding algorithm (Lu et al., 2021) achieves the best results, outperforming the more sophisti- cated NeuroLogic-A* decoding algorithm, while being an order of magnitude faster. Notably, on E2E, self-correction outperforms Neurologic-A* decoding, despite only using standard beam search. This suggests that a corrector can be viewed as an alternative to using a more sophisticated decoding procedure (A*) for improving performance without modifying the underlying model. See Figure 9 for qualitative examples. 6 Preprint. Under review. Toxicity Fluency Diversity GPT-2 PPLM [6] GeDi [14] DExpert [21] DAPT [12] PPO [23] Quark [23] Avg. Max. Prob. Perplexity dist-2 dist-3 0.527 0.520 11.31 0.85 0.85 0.520 0.363 0.314 0.428 0.218 0.196 0.518 0.217 0.128 0.360 0.044 0.035 32.58 43.44 25.21 31.22 14.27 12.47 0.86 0.84 0.84 0.84 0.79 0.80 0.86 0.83 0.84 0.84 0.82 0.84 SELF-CORRECT 0.171 0.026 11.81 0.80 0.83 Table 3: Toxicity reduction. GPT-2 is the base generator. 3.3 TOXICITY REDUCTION Next, we consider the task of toxicity reduction (Gehman et al., 2020; Liu et al., 2021). Given a prompt x, the task is to generate a fluent continuation y while avoiding offensive content. This task is important for ensuring safe language model deployment, yet challenging: due to misaligned pretraining objectives (i.e. modeling internet text vs. non-toxic text), language models are suscepti- ble to generating toxic completions, even when prompted with seemingly innocuous text (Gehman et al., 2020). Along with its practical importance, the task tests whether (self-)correctors can be an effective mechanism for controlling the outputs of language models in an open-ended setting. Datasets and Metrics. We use the REALTOXICITYPROMPTS benchmark (Gehman et al., 2020) which contains 100k prompts designed to elicit toxic generations. Following the experimental setup of Liu et al. (2021), during training we use 85K prompts from the training set, and for evaluation we use the same 10K non-toxic prompts from test set as Liu et al. (2021). We use Perspective API to measure maximum toxicity, defined as the average maximum toxicity over 25 sampled generations, and the (empirical) toxicity probability of at least 1 out of 25 generations being toxic. Baselines. We compare SELF-CORRECT with its generator (GPT-2) and previously reported base- lines from Lu et al. (2022a), including PPLM (Dathathri et al., 2020), GeDi (Krause et al., 2021), DExpert (Liu et al., 2020), DAPT (Gururangan et al., 2020), PPO (Lu et al., 2022a), and Quark (Lu et al., 2022a). The latter two – Proximal Policy Optimization (PPO) and Quantized Reward Kondi- tioning (Quark) – represent strong, state-of-the art approaches based on reinforcement learning. Setup. We use the off-the-shelf GPT-2 Large as the generator, and finetune another GPT-2 Large as the corrector. During inference, we use nucleus sampling with p = 0.9 to generate 25 samples for all baselines. As the value function, we use the Perspective API score, v(y) ∈ [0, 1], which measures the toxicity of the completed sequence. We do up to three corrections with the corrector model. Results. Table 3 shows that SELF-CORRECT reduces the rate of toxic generations substantially, while also maintaining fluency and diversity. SELF-CORRECT outperforms all baselines. This in- cludes inference-time algorithms (PPLM, GeDi, DExpert), which do not modify the generator but degrade fluency and yield higher toxicity compared to SELF-CORRECT, as well as reinforcement learning methods (PPO, Quark) that adjust the generator using toxicity as a (negative) reward. The results show that SELF-CORRECT is effective for detoxification, without having to modify the un- derlying generator. We study implications of this latter property further in the next section. 3.4 CHANGING MODULES – CORRECTING GPT-3 Next, we show that a self-corrector can improve the outputs of a generator that is much larger than the corrector. We consider two cases: (1) training with a small generator, then swapping in the larger generator at test time; (2) training with the larger generator, i.e. using the large generator to initialize the datapool for self-corrective learning, then using the large generator at test time. Toxicity. We evaluate case (1) for reducing the toxicity of a large generator (GPT-2 XL, GPT-3). We generate an initial sequence using the large generator, then refine it with our corrector trained in the previous experiments (§3.3). Table 4 shows that the resulting self-corrector (large generator 7 Preprint. Under review. Task Dataset Generator (train) Generator (test) Generator Self-corrector Math Synthesis ↑ Multitask Neo 1.3B Neo 1.3B GPT-3 Instruct GPT-3 GPT-3 Instruct GPT-3 Instruct 46.70 84.90 84.90 80.00 90.90 92.75 GSM Neo 1.3B Neo 1.3B GPT-3 Instruct GPT-3 GPT-3 Instruct GPT-3 Instruct 6.96 36.80 36.80 24.30 45.00 45.92 Detoxification ↓ GPT2-L RTPrompts GPT2-L GPT2-L GPT2-XL GPT-3 GPT-3 Instruct 0.383 0.182 0.275 0.027 0.025 0.023 Table 4: Modularity (program synthesis and detoxification). Self-correctors can correct very large generators, either by swapping in the generator at test-time, or training with the generator. For math synthesis, the corrector is GPT-Neo 1.3B, and here we only correct incorrect outputs. For detoxification, the correction is GPT2-L, and we correct all the outputs. + corrector) has substantially reduced toxicity compared to the large generator. This shows the promise of using (self-)correctors for controlling the outputs of large language models. Math program synthesis. Table 4 shows results for math. Analogous to toxicity, the corrector is able to correct larger generators swapped in at test-time. For instance, the GPT-3 Instruct generator has quite high performance (84.90 Multitask, 36.80 GSM), which improves to 90.90 and 45.00, respectively, by adding in a corrector. The self-corrector (large generator + corrector) improves further by training with the GPT-3 Instruct generator, to 92.75 and 45.92, respectively. 3.5 LEVERAGING EXPLICIT FEEDBACK Next, we demonstrate SELF-CORRECT’s capacity to incorporate explicit natural language feedback. This amounts to defining a feedback function f , then using the same self-corrective learning and inference algorithms (§2.1) as in our preceding experiments (in those experiments, f returned ∅). We show that correctors learn to use the feedback, as evidenced by higher performance. Toxicity. We use additional fine-grained information from the toxicity API as natural language feedback. Specifically, besides the overall toxicity score, Perspective API also provides scores for fine-grained attributes of toxicity (e.g. identity attack, profanity, flirtation, etc.). At training time, we compare the attribute scores from a hypothesis and its selected correction, and use the attribute with the largest decrease as natural language feedback (e.g. "decrease toxicity in profanity"). At inference time, we call the API on the current hypothesis, and use the attribute with the highest score. Here we use the API at inference time, which is not required in our previous experiments. Lexical constraints. In training time, we generate natural language feedback for every example pair (x,y, y’) by elaborating the extra lexical constraints satisfied by y’ but not y. e.g. “adding constraint word: read”. At inference time, we elaborate all missing constraints in the current hypothesis. Math program synthesis. Math program synthesis contains a variety of problem types and errors, without an automated means for identifying the errors (e.g. an API). We explore obtaining natural language feedback about the current program by prompting a large language model. We prompt the model with a problem, hypothesis program, a gold solution, and few-shot demonstrations that show feedback on one part of the program; e.g. In the initial guess, 3 should be subtracted. When the program is correct, the feedback is Correct. At inference time, we also use feedback from the language model. We allow the feedback model access to a gold solution, which we expect makes the feedback higher quality, with the risk of solution leakage at inference-time. Our results in this task are thus used only to study the feasibility of explicit feedback for math program synthesis. Setup. For toxicity, lexical constraints, and math we use REALTOXICITYPROMPTS, COMMONGEN, and the MULTITASK arithmetic setting, respectively. We follow the setup of each task’s previous experiments (§3.3,§3.2,§3.1), except for math we use 5 correction iterations (previously 1). For math, we use GPT-3 (text-davinci-002) with 6 demonstrations as the feedback model. 8 # Preprint. Under review. Toxicity ↓ Constrained Gen. ↑ Math ↑ Avg. Max. Prob. Fluency Fluency Constraints Correct Correct∗ Generator SELF-CORRECT + FEEDBACK 0.527 0.171 0.156 0.520 0.026 0.020 11.31 11.81 11.86 14.97 15.30 15.24 91.38 94.58 95.88 49.02 74.31 81.76 49.02 79.80 82.35 Table 5: Explicit natural language feedback. Correct∗ means only correcting incorrect outputs. Problem: Melanie had 19 dimes in her bank. Her dad gave her 39 dimes and her mother gave her 25 dimes. How many dimes does Melanie have now? Problem: Lana’s favorite band was holding a concert where tickets were 6 dollars each. Lana bought 8 tickets for herself and her friends and 2 extra tickets in case anyone else wanted to go. How much did she spend? Generator (GPT-Neo): answer = 19 + 25 print(answer) Generator (GPT-Neo): answer=(6.0*8.0) print(answer) Feedback (GPT-3): # In the initial guess, # 39 is not included. Feedback (GPT-3): # In the initial guess, # 2 tickets are not included. Corrector (GPT-Neo): answer = 19 + 25 + 39 print(answer) Corrector (GPT-Neo): answer=(6.0*(8.0+2.0)) print(answer) Figure 5: Self-correction with natural language feedback. Results. Table 5 shows that explicit natural language feedback improves performance in all three tasks. For toxicity, this means that providing fine-grained attributes (e.g. identity attack, profanity, etc.) during learning and inference improves upon using only the scalar toxicity score. Intuitively, feedback may help the model to focus on a useful correction; e.g., see Figure 5. # 3.6 ADDITIONAL ABLATIONS AND ANALYSIS Effect of multiple corrections. Previously, Figure 4 showed that multiple corrections led to better toxicity reduction. On math (Multitask setting), Figure 6 shows that performance improves with more than one correction, and that multiple corrections are more beneficial with feedback. Intu- itively, in this math task, after 2-3 corrections the model needs additional guidance. Effect of pairing and proportional sampling. Self-corrective learning (i) samples pairs for learn- ing proportional to Equation 4, (ii) only pairs sequences that improve value. We ablate these features by training on Multitask using a data pool that samples a pair for learning uniformly (rather than Equation 4), and a data pool without value pairing. Table 6 shows that both improve performance. Effect of exploration. To ablate the effect of exploration, we train a baseline only on correction pairs induced from the base generator. Table 7 shows results on the three math datasets, indicating that exploration improves performance. # 4 RELATED WORK Self-correction relates to recent works on editing text, including modeling Wikipedia edits (Reid & Neubig, 2022; Faltings et al., 2021; Schick et al., 2022), which relies on supervised edits, unsuper- vised methods (Miao et al., 2019; Liu et al., 2020) that perturb sequences with simple operations (e.g. insertion, deletion), editing with models trained on human-written critiques (Saunders et al., 2022), or iteratively updating continuous variables (Lee et al., 2020; Li et al., 2022; Qin et al., 2022). 9 Preprint. Under review. 83 82 el @ 80 £79 Gv 77 — 76 ete el 2 3 a 5 Correction iteration Ablation Math COMMONGEN SELF-CORRECT 78.24 94.55 X proportional sampling = 77.25 93.49 X value pairing 62.35 91.76 # Table 6: Effect of pairing and proportional sampling. Exploration Multiarith Multitask | GSM8k x 89.20 73.49 17.60 v 99.17 78.24 23.96 Figure 6: Math: multiple corrections. Table 7: Effect of exploration on program synthesis. In contrast to these, self-correction learns an expressive text-to-text corrector that is trained online to improve a quality measure, without requiring a supervised dataset of edits or critiques. Separately, denoising ground-truth sequences is a common pretraining objective (Devlin et al., 2019; Lewis et al., 2020; Raffel et al., 2020), while self-correction ‘denoises’ generations to improve a scalar quality measure. Scalar measures are often improved with reinforcement learning (RL) on a base generator (Ziegler et al., 2019; Stiennon et al., 2020; Lu et al., 2022a), which is infeasible for im- proving many language models (e.g. those accessed through an API), and uses only scalar feedback. Moreover, self-correction learns the difference between a generation and solution, and is comple- mentary to RL-tuned generators, which can be used within a self-corrector. Finally, self-correction decomposes generation into multiple steps, which relates to methods that generate rationales before a response (Wei et al., 2022; Dohan et al., 2022). Self-correction also produces intermediate steps, but each step is of the same form as the output, allowing for re-using previous generations. # 5 CONCLUSION We introduced self-correctors, a class of models that decompose generation into initial generation and correction steps. We study self-correctors with a fixed base generator along with a corrector trained to improve outputs according to a scalar measure of quality. We presented a simple, gen- eral procedure for training the corrector, and find that self-correction is applicable and effective for improving performance, and controlling the outputs of both small and large generators. Moreover, we found that self-correction along with our learning framework provides a promising mechanism for using natural language feedback to improve generation. These findings, along with exploring alternative self-correctors, open up many avenues that we leave for future work. # ACKNOWLEDGMENTS This work was funded in part by the DARPA MCS program through NIWC Pacific (N66001-19-2- 4031), and the Allen Institute for AI. # REFERENCES Jacob Austin, Augustus Odena, Maxwell Nye, Maarten Bosma, Henryk Michalewski, David Dohan, Ellen Jiang, Carrie J. Cai, Michael Terry, Quoc V. Le, and Charles Sutton. Program synthesis with large language models. ArXiv, abs/2108.07732, 2021. Sid Black, Leo Gao, Phil Wang, Connor Leahy, and Stella Biderman. GPT-Neo: Large Scale Au- toregressive Language Modeling with Mesh-Tensorflow. Zenodo, March 2021. doi: 10.5281/ zenodo.5297715. URL https://doi.org/10.5281/zenodo.5297715. If you use this software, please cite it using these metadata. Tom B. Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhari- wal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, Gretchen Krueger, T. J. Henighan, Rewon Child, Aditya Ramesh, Daniel M. Ziegler, Jeff Wu, Clemens Winter, Christopher Hesse, Mark Chen, Eric Sigler, Mateusz Litwin, 10 Preprint. Under review. Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Rad- ford, Ilya Sutskever, and Dario Amodei. Language models are few-shot learners. ArXiv, abs/2005.14165, 2020. 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, Fo- tios 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 Mc- Grew, Dario Amodei, Sam McCandlish, Ilya Sutskever, and Wojciech Zaremba. Evaluating large language models trained on code. arXiv, 2021. 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. URL https://arxiv. org/abs/2110.14168. Sumanth Dathathri, Andrea Madotto, Janice Lan, Jane Hung, Eric Frank, Piero Molino, Jason Yosin- ski, and Rosanne Liu. Plug and play language models: A simple approach to controlled text generation. ArXiv, abs/1912.02164, 2020. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training of deep bidirectional transformers for language understanding. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pp. 4171–4186, Minneapolis, Minnesota, June 2019. Association for Computational Linguistics. doi: 10.18653/v1/N19-1423. URL https: //aclanthology.org/N19-1423. David Dohan, Winnie Xu, Aitor Lewkowycz, Jacob Austin, David Bieber, Raphael Gontijo Lopes, Yuhuai Wu, Henryk Michalewski, Rif A. Saurous, Jascha Narain Sohl-Dickstein, Kevin Murphy, and Charles Sutton. Language model cascades. ArXiv, abs/2207.10342, 2022. Felix Faltings, Michel Galley, Gerold Hintz, Chris Brockett, Chris Quirk, Jianfeng Gao, and Bill Dolan. Text editing by command. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 5259–5274, Online, June 2021. Association for Computational Linguistics. doi: 10.18653/v1/ 2021.naacl-main.414. URL https://aclanthology.org/2021.naacl-main.414. Leo Gao, Stella Biderman, Sid Black, Laurence Golding, Travis Hoppe, Charles Foster, Jason Phang, Horace He, Anish Thite, Noa Nabeshima, Shawn Presser, and Connor Leahy. The pile: An 800gb dataset of diverse text for language modeling, 2021. URL https://arxiv.org/ abs/2101.00027. Samuel Gehman, Suchin Gururangan, Maarten Sap, Yejin Choi, and Noah A. Smith. RealToxici- tyPrompts: Evaluating neural toxic degeneration in language models. In Findings of the Asso- ciation for Computational Linguistics: EMNLP 2020, pp. 3356–3369, Online, November 2020. Association for Computational Linguistics. doi: 10.18653/v1/2020.findings-emnlp.301. URL https://aclanthology.org/2020.findings-emnlp.301. Suchin Gururangan, Ana Marasovi´c, Swabha Swayamdipta, Kyle Lo, Iz Beltagy, Doug Downey, and Noah A. Smith. Don’t stop pretraining: Adapt language models to domains and tasks. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pp. 8342–8360, Online, July 2020. Association for Computational Linguistics. doi: 10.18653/v1/ 2020.acl-main.740. URL https://aclanthology.org/2020.acl-main.740. Mohammad Javad Hosseini, Hannaneh Hajishirzi, Oren Etzioni, and Nate Kushman. Learning to solve arithmetic word problems with verb categorization. In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP), pp. 523–533, Doha, Qatar, 11 Preprint. Under review. October 2014. Association for Computational Linguistics. doi: 10.3115/v1/D14-1058. URL https://aclanthology.org/D14-1058. Ben Krause, Akhilesh Deepak Gotmare, Bryan McCann, Nitish Shirish Keskar, Shafiq Joty, Richard Socher, and Nazneen Fatema Rajani. GeDi: Generative discriminator guided sequence generation. In Findings of the Association for Computational Linguistics: EMNLP 2021, pp. 4929–4952, Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics. doi: 10.18653/v1/2021.findings-emnlp.424. URL https://aclanthology.org/2021. findings-emnlp.424. Iterative refinement in the continuous space for non-autoregressive neural machine translation. In Proceedings of the 2020 Conference on Em- pirical Methods in Natural Language Processing (EMNLP), pp. 1006–1015, Online, November 2020. Association for Computational Linguistics. doi: 10.18653/v1/2020.emnlp-main.73. URL https://aclanthology.org/2020.emnlp-main.73. Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Veselin Stoyanov, and Luke Zettlemoyer. BART: Denoising sequence-to-sequence pre- In Proceedings of training for natural language generation, translation, and comprehension. the 58th Annual Meeting of the Association for Computational Linguistics, pp. 7871–7880, On- line, July 2020. Association for Computational Linguistics. doi: 10.18653/v1/2020.acl-main.703. URL https://aclanthology.org/2020.acl-main.703. Xiang Lisa Li and Percy Liang. Prefix-tuning: Optimizing continuous prompts for generation. In Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), pp. 4582–4597, Online, August 2021. Association for Computational Linguistics. doi: 10.18653/ v1/2021.acl-long.353. URL https://aclanthology.org/2021.acl-long.353. Xiang Lisa Li, John Thickstun, Ishaan Gulrajani, Percy Liang, and Tatsunori Hashimoto. Diffusion- lm improves controllable text generation. ArXiv, abs/2205.14217, 2022. Bill Yuchen Lin, Wangchunshu Zhou, Ming Shen, Pei Zhou, Chandra Bhagavatula, Yejin Choi, and Xiang Ren. CommonGen: A constrained text generation challenge for generative com- In Findings of the Association for Computational Linguistics: EMNLP monsense reasoning. 2020, pp. 1823–1840, Online, November 2020. Association for Computational Linguistics. doi: 10.18653/v1/2020.findings-emnlp.165. URL https://aclanthology.org/2020. findings-emnlp.165. Alisa Liu, Maarten Sap, Ximing Lu, Swabha Swayamdipta, Chandra Bhagavatula, Noah A. Smith, and Yejin Choi. DExperts: Decoding-time controlled text generation with experts and anti- experts. In Proceedings of the 59th Annual Meeting of the Association for Computational Lin- guistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), pp. 6691–6706, Online, August 2021. Association for Computational Linguis- tics. doi: 10.18653/v1/2021.acl-long.522. URL https://aclanthology.org/2021. acl-long.522. Xianggen Liu, Lili Mou, Fandong Meng, Hao Zhou, Jie Zhou, and Sen Song. Unsupervised para- phrasing by simulated annealing. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pp. 302–312, Online, July 2020. Association for Computational Lin- guistics. doi: 10.18653/v1/2020.acl-main.28. URL https://aclanthology.org/2020. acl-main.28. Ximing Lu, Peter West, Rowan Zellers, Ronan Le Bras, Chandra Bhagavatula, and Yejin Choi. NeuroLogic decoding: (un)supervised neural text generation with predicate logic constraints. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 4288–4299, Online, June 2021. Association for Computational Linguistics. doi: 10.18653/v1/2021.naacl-main.339. URL https://aclanthology.org/2021.naacl-main.339. Ximing Lu, Sean Welleck, Liwei Jiang, Jack Hessel, Lianhui Qin, Peter West, Prithviraj Am- manabrolu, and Yejin Choi. Quark: Controllable text generation with reinforced unlearning. 12 Preprint. Under review. CoRR, abs/2205.13636, 2022a. doi: 10.48550/arXiv.2205.13636. URL https://doi.org/ 10.48550/arXiv.2205.13636. Ximing Lu, Sean Welleck, Peter West, Liwei Jiang, Jungo Kasai, Daniel Khashabi, Ronan Le Bras, Lianhui Qin, Youngjae Yu, Rowan Zellers, Noah A. Smith, and Yejin Choi. NeuroLogic In Proceedings of a*esque decoding: Constrained text generation with lookahead heuristics. the 2022 Conference of the North American Chapter of the Association for Computational Lin- guistics: Human Language Technologies, pp. 780–799, Seattle, United States, July 2022b. As- sociation for Computational Linguistics. doi: 10.18653/v1/2022.naacl-main.57. URL https: //aclanthology.org/2022.naacl-main.57. Kathleen McKeown. Text Generation. Studies in Natural Language Processing. Cambridge Univer- sity Press, 1985. doi: 10.1017/CBO9780511620751. Ning Miao, Hao Zhou, Lili Mou, Rui Yan, and Lei Li. Cgmh: Constrained sentence generation by metropolis-hastings sampling. Proceedings of the AAAI Conference on Artificial Intelligence, 33 (01):6834–6842, Jul. 2019. doi: 10.1609/aaai.v33i01.33016834. URL https://ojs.aaai. org/index.php/AAAI/article/view/4659. Swaroop Mishra, Matthew Finlayson, Pan Lu, Leonard Tang, Sean Welleck, Chitta Baral, Tanmay Rajpurohit, Oyvind Tafjord, Ashish Sabharwal, Peter Clark, and Ashwin Kalyan. Lila: A unified In Proceedings of the 2022 Conference on Empirical benchmark for mathematical reasoning. Methods in Natural Language Processing (EMNLP), 2022. Ansong Ni, Jeevana Priya Inala, Chenglong Wang, Oleksandr Polozov, Christopher Meek, Dragomir Radev, and Jianfeng Gao. Learning from self-sampled correct and partially-correct programs, 2022. URL https://arxiv.org/abs/2205.14318. Jekaterina Novikova, Ondˇrej Dušek, and Verena Rieser. The E2E dataset: New challenges for end-to-end generation. In Proceedings of the 18th Annual SIGdial Meeting on Discourse and Di- alogue, pp. 201–206, Saarbrücken, Germany, August 2017. Association for Computational Lin- guistics. doi: 10.18653/v1/W17-5525. URL https://aclanthology.org/W17-5525. Arkil Patel, Satwik Bhattamishra, and Navin Goyal. Are NLP models really able to solve simple math word problems? In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 2080– 2094, Online, June 2021. Association for Computational Linguistics. doi: 10.18653/v1/2021. naacl-main.168. URL https://aclanthology.org/2021.naacl-main.168. Lianhui Qin, Sean Welleck, Daniel Khashabi, and Yejin Choi. Cold decoding: Energy-based con- strained text generation with langevin dynamics. arXiv preprint arXiv:2202.11705, 2022. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9, 2019. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. Exploring the limits of transfer learning with a unified text-to- text transformer. Journal of Machine Learning Research, 21(140):1–67, 2020. URL http: //jmlr.org/papers/v21/20-074.html. Machel Reid and Graham Neubig. Learning to model editing processes, 2022. URL https: //openreview.net/forum?id=1bEaEzGwfhP. Subhro Roy, Tim Vieira, and Dan Roth. Reasoning about quantities in natural language. Transac- tions of the Association for Computational Linguistics, 3:1–13, 2015. William Saunders, Catherine Yeh, Jeff Wu, Steven Bills, Long Ouyang, Jonathan Ward, and Jan Leike. Self-critiquing models for assisting human evaluators, 2022. URL https://arxiv. org/abs/2206.05802. Timo Schick, Jane Dwivedi-Yu, Zhengbao Jiang, Fabio Petroni, Patrick Lewis, Gautier Izacard, Qingfei You, Christoforos Nalmpantis, Edouard Grave, and Sebastian Riedel. Peer: A collabora- tive language model, 2022. URL https://arxiv.org/abs/2208.11663. 13 Preprint. Under review. 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 feed- In H. Larochelle, M. Ranzato, R. Hadsell, M.F. Balcan, and H. Lin (eds.), Ad- back. vances in Neural Information Processing Systems, volume 33, pp. 3008–3021. Curran Asso- ciates, Inc., 2020. URL https://proceedings.neurips.cc/paper/2020/file/ 1f89885d556929e98d3ef9b86448f951-Paper.pdf. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Ed Chi, Quoc Le, and Denny Zhou. Chain of thought prompting elicits reasoning in large language models. ArXiv, abs/2201.11903, 2022. 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. URL https://arxiv.org/abs/1909.08593. 14 Preprint. Under review. # APPENDIX A ADDITIONAL EXPERIMENTAL DETAILS A.1 MATHEMATICAL PROGRAM SYNTHESIS We fine-tune a separate instance of GPT-Neo 1.3B as an initial generator, using the Hug- gingface library with default hyperparameters, except for evaluation steps, which we set to a small number to ensure a strong checkpoint is selected for each dataset. We use the fine- tuned initial generator as initialization for the corrector, and tune the corrector on sequences [SC]x[CURR]yi[START]yj[END], where x is a problem, yi and yj form a residual pair, and [·] are special tokens. The loss is on tokens after [START]. Feedback. We write 6 demonstrations using training problems and generations from our GPT- Neo base generator, and use GPT-3 (text-davinci-002) as a feedback model. We use the same training procedure and hyperparameters, except that the sequences now include feedback, [SC]x[CURR]yi[FEEDBACK]F(x,yi)[START]yj[END], where x is a problem, yi and yj form a residual pair, and F (x, yi) is feedback. We include loss on tokens after [FEEDBACK]. A.2 LEXICALLY-CONSTRAINED GENERATION Hyper-parameters. Table 8 and Table 9 show hyperparameters for CommonGen and E2E. Human Evaluation. We evaluate fluency of generations in E2E task using human annotators on Amazon Mechanical Turk (AMT). We randomly sampled 100 instances, along with generations of different baselines and self-corrections. For each instance, we ask 3 annotators to evaluate the fluency of generations on a 3-point Likert scale. We aggregate annotations from 3 annotators using majority vote. We restricted the pool of annotators to those who are located in US or CA, and had 98% approval rate for at least 5,000 previous annotations. Hyperparameter Assignment Hyperparameter Assignment Predictor # steps batch size optimizer learning rate decoding alg. GPT-2Large 6000 128 Adam 1.e−5 beam search (k=5) Predictor # steps batch size optimizer learning rate decoding alg. GPT-2M edium 10000 100 Adam 1.e−5 beam search (k=5) Table 8: Hyperparameters for COMMONGEN. Table 9: Hyperparameters for E2E. # B ADDITIONAL RESULTS Toxicity Fluency Diversity Avg. Max. Prob. Perplexity dist-2 dist-3 GPT2-L SELF-CORRECT SELF-CORRECT + FEEDBACK 0.527 0.171 0.156 0.520 0.026 0.020 11.31 11.81 11.86 0.85 0.80 0.80 0.85 0.83 0.83 Table 10: Evaluation results of toxicity reduction experiments with natural language feedback. 15 # Preprint. Under review. Bleu-4 CIDER Coverage Runtime NeuroLogic [22] NeuroLogic-A*esque [24] 26.70 28.20 14.70 15.20 97.70 97.80 2.04s/sent 19.24s/sent GPT-2 SELF-CORRECT SELF-CORRECT + feedback SELF-CORRECT+NeuroLogic 27.90 27.98 27.82 28.17 14.97 15.30 15.24 15.28 91.38 94.58 95.88 97.80 0.2s/sent 0.8s/sent 0.8s/sent 2.24s/sent Table 11: Evaluation rresults of lexically-constrained generation on COMMONGEN. Coverage BLEU-4 NIST R-L METEOR CIDER 91.16 70.30 8.82 72.10 46.30 2.46 91.50 98.77 67.12 68.81 8.67 70.25 8.78 68.60 45.58 45.11 2.33 2.38 Table 12: Evaluation results of lexically-constrained generation on E2E. C QUALITATIVE EXAMPLES 16 Preprint. Under review. Problem: Ralph watches TV for 4 hours a day from Monday to Friday, and 6 hours a day on Satur- day and Sunday. How many hours does Ralph spend watching TV in one week? Problem: The pirates plan to explore 4 islands. Two is- lands require walking 20 miles per day while the other two islands require 25 miles per day. How many miles will they have to walk if it takes 1.5 days to explore each island? Generator: Corrector: a=4*7 b=6*7 c=a+b answer=c print(answer) a=4*5 b=6*2 c=a+b answer=c print(answer) Generator: a=20*2 b=25*2 c=a+b d=c*1.5 e=d+b answer=e print(answer) Corrector: a=20*2 b=25*2 c=a+b d=c*1.5 answer=d print(answer) Figure 7: Grade school math (GSM) self-corrections. Left: the structure of the generator’s solu- tion is valid, but it incorrectly uses the total number of days in a week for both a and b; the corrector fixes the program to correctly account for the 5 weekdays and 2 weekend days. Right: the genera- tor’s solution contains an incorrect addition at the end; the corrector removes this line, resulting in a correct program. Problem: A spiral notebook costs 15, and a personal planner costs $10. How much would it cost in total to buy 4 spiral notebooks and 8 personal planners at a 20% discount? Problem: Julia has $40. She spends half of her money to buy a new game for her phone. She spends a quarter of what she has left on in-game pur- chases. How much money does she have left? Generator: Corrector: Generator: Corrector: a=4*15 b=8*10 c=a+b answer=c print(answer) a=4*15 b=8*10 c=a+b d=c*20/100 e=c-d answer=e print(answer) a=40/2 b=40-a c=b/4 d=b-c e=d+40 answer=e print(answer) a=40/2 b=a/4 c=a-b answer= c print(answer) Figure 8: Grade school math (GSM) self-corrections. Left: the generator’s program doesn’t include the discount; the corrector appends the discount to the program. Right: a more sophisticated multipart correction. The generator’s assignment of b (line 2), and addition to e (line 5) are incorrect. The corrector removes these lines and adjusts the variable names accordingly. 17 Preprint. Under review. Constraints: ‘table’, ‘paper’, ‘read’ Generator: A man is reading book on a table. Corrector: A man is reading a book on a table and writing on a piece of paper. Constraints: ’stand’, ’wait’, ’look’ Generator: He waits for someone to look at him. Corrector: He waits for someone to stand and look him in the eye. Constraints: ’walk’, ’park’, ’bench’, ’dog’, ’sit’ Generator: A dog sitting on a bench in a park. Corrector: A dog sitting on a bench and a man walking a dog in a park. Constraints: name : The Mill | Type : restaurant | food : English | price : high | customer rating : average | area : riverside | family friendly : yes | near : Cafe Rouge Generator: The Mill is an expensive, three star restaurant located near Cafe Rouge. Corrector: The Mill is a children friendly English restaurant in the riverside area near Cafe Rouge. It has an average customer rating and a high price range. Constraints: name : Blue Spice | Type : restaurant | food : Chinese | area : riverside | family friendly : yes | near : Rainbow Vegetarian Cafe Generator: Blue Spice is a restaurant providing Chinese food. It is near Rainbow Vegetarian Cafe. Corrector: Blue Spice is a family friendly Chinese restaurant in the riverside area near Rainbow Vegetarian Cafe. It is located in the riverside. Figure 9: Constrained generation self-corrections. Top: COMMONGEN, and Bottom: E2E. Words in green indicate constraints that were previously missing. Prompt: Waters then went on to call the Trump Generator: administration a "bunch of idiots" and "insolent clowns [who are] running" Corrector: Administration’s support for the Trans-Pacific Partnership on trade "a total non-event." Figure 10: Toxicity control self-corrections. Words in red indicate toxic language. 18
Title: ALERT: Adapting Language Models to Reasoning Tasks: Summary: Current large language models can perform reasonably well on complex tasks that require step-by-step reasoning with few-shot learning. Are these models applying reasoning skills they have learnt during pre-training and reason outside of their training context, or are they simply memorizing their training corpus at finer granularity and have learnt to better understand their context? To tease apart these possibilities, we introduce ALERT, a benchmark and suite of analyses for assessing language models' reasoning ability comparing pre-trained and finetuned models on complex tasks that require reasoning skills to solve. ALERT provides a test bed to asses any language model on fine-grained reasoning skills, which spans over 20 datasets and covers 10 different reasoning skills. We leverage ALERT to further investigate the role of finetuning. With extensive empirical analysis we find that language models learn more reasoning skills such as textual entailment, abductive reasoning, and analogical reasoning during finetuning stage compared to pretraining state. We also find that when language models are finetuned they tend to overfit to the prompt template, which hurts the robustness of models causing generalization problems. # ALERT: Adapting Language Models to Reasoning Tasks Ping Yu* Tianlu Wang® Olga Golovneva* Badr AlKhamissi* Siddharth Verma“ Zhijing Jin‘“ Gargi Ghosh® Mona Diab® Asli Celikyilmaz® *Meta AI AWork done at Meta AI *Max Planck Institute & ETH {pingyu,aslic} @meta.com # Abstract Recent advancements in large language mod- els have enabled them to perform well on com- plex tasks that require step-by-step reasoning with few-shot learning. However, it is unclear whether these models are applying reasoning skills they have learned during pre-training, or if they are simply memorizing their training corpus at finer granularity and have learned to better understand their context. To address this question, we introduce ALERT, a benchmark and suite of analyses for evaluating reasoning skills of language models. ALERT enables com- paring pre-trained and finetuned models on complex tasks that require reasoning skills to solve them. Our benchmark provides a test bed to assess any language model on fine-grained reasoning skills, which spans over 20 datasets and covers 10 different reasoning skills. To prove the efficacy of ALERT we investigate the role of finetuning. Our extensive empirical analysis shows that language models acquire reasoning skills such as textual entailment, ab- ductive reasoning, and analogical reasoning during the finetuning stage compared to pre- training stage. Another finding is when lan- guage models are finetuned they tend to over- fit to the prompt template, which hurts the ro- bustness of models resulting in generalization problems. # Introduction Large language models (LLMs) (e.g., GPT- 3 (Brown et al., 2020a), PALM (Chowdhery et al., 2022), OPT (Zhang et al., 2022)) have shown in- creasing in-context learning capabilities with scal- ing up the model and data sizes. Despite this progress, even the largest of these models still struggle with tasks such as commonsense rea- soning (West et al., 2022), and math word prob- lems (Hendrycks et al., 2021b) which require arith- metic reasoning or symbolic manipulation (Rytting and Wingate, 2021). Table 1 presents some ex- amples that require certain reasoning skills. Even The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have? The answer is 29 apples . Select the best translation into predicate logic. David teaches Chris. (c: Chris; d: David; Txy: x teaches y) (A) Tdc; (B) Tcd; (C) Tcc; (D) dTc. The answer is (B) Tcd . Isabella entered the hall. Olivia entered the hall. The ap- ple is in the blue_treasure_chest. Olivia exited the hall. Is- abella moved the apple to the green_basket. Question: Where does Isabella think that Olivia searches for the apple? The answer is Isabella thinks that Olivia searches for the apple in the green_basket . Table 1: Examples from tasks that require reasoning skills and generated outputs from GPT-3 series text-davinci-003 engine. The failed outputs are highlighted in red . Predictions by ChatGPT are shown in Table 9 in Appendix. the powerful LLMs (such as text-davinci-0031 and ChatGPT2) fail to make correct predictions. To improve large LLMs’ performance on tasks that require multiple steps of reasoning, recent work used different prompting methods which in- cluded a rationale with the final answer in the form of: scratchpad for arithmetic and logical reason- ing (Nye et al., 2021), chain-of-thought (CoT) (Wei et al., 2022) for practically any tasks, or adding let’s think step-by-step (Kojima et al., 2022) to prompt models to generate explanations. Other works such as Chung et al. (2022) integrated step-by-step expla- nations into the finetuning stage (CoT-finetuning). While these techniques may improve the accuracy and interpretability, it is not well understood which reasoning skills they rely on or to what degree they require higher-order reasoning. It is also uncertain how frequently the stated reasoning steps actually contribute to the final task predictions. For instance, to correctly answer the questions in Table 1 a com- bination of logical, commonsense, math and spatial reasoning skills are required. In this work, to gain a deeper understanding of LLMs reasoning abilities in in-context learning 1https://beta.openai.com/docs/models/gpt-3. 2https://chat.openai.com/chat. settings, we introduce ALERT, a new pipeline to benchmark different LLMs on various reasoning skills and provide analysis to assess reasoning abil- ities. Unlike existing commonly used benchmarks (e.g., Mishra et al. (2022); Wang et al. (2022c); Sri- vastava et al. (2022)), ALERT can evaluate LLMs’ fine-grained reasoning skills. It spans over 20 datasets and covers 10 different reasoning skills including logical, causal, commonsense, abductive, spatial, analogical, argument and deductive reason- ing as well as textual entailment, and mathematics (see Figure 6). ALERT enables easy benchmark- ing of any LM (e.g., pre-trained, finetuned, CoT- finetuned) on a rich set of new inference methods including zero-shot, few-shot and CoT. Using ALERT, we further investigate whether finetuning can improve LMs’ performance on downstream reasoning tasks. Specifically, we are interested in diagnosing what actually improved when we observe a performance increase on rea- soning tasks. Is it because models have seen similar data in the finetuning stage? Or is it because mod- els have seen prompts in a specific template and memorize the template during finetuning such as definitions provided in the NIV2 benchmark (Wang et al., 2022c)? Or does the LLM actually acquired the required reasoning skill? We investigate these three possibilities. To study the above questions, we compare three different model types (as shown in Figure 2): a pre- trained model and two types of finetuned models. Specifically: • OPT (Zhang et al., 2022): A baseline LLM a pre-trained model with no finetuning (figure (A) in Figure 2); • OPT-FT: Meta-finetuned OPT on reference answers without explanations, illustrated in (figure (B) in Figure 2); • OPT-CoT: Meta-finetuned OPT on data with rationales (explanations) (Chung et al., 2022; AlKhamissi et al., 2023) (figure (C) in Fig- ure 2). the role of finetuning on three dimensions: (1) Data memorization: We investigate whether the performance improvements obtained after fine- tuning can be attributed to using similar or some- times the exact same data as in the evaluation datasets. To this end, we use vocabulary overlap to Reasoning Skills Datasets Logical Causal Commonsense Entailment Mathematics Abductive Spatial Analogical Argument bigbench repeat copy logic, mmmlu an- swer generation plausable result generation, anli r2 entail- ment, anli r3 entailment, cb entailment piqa answer generation, commongen sen- tence generation, sciq answer generation, openbookqa question answering nli r2 entailment, anli r3 entailment, cb entailment, lue entailment classification semeval closed vocabulary math, semeval geometric math, mmmlu formal logic tellmewhy babi t1 single supporting fact, piqa answer generation, toqa find location easy clean commongen sentence generation, bard analogical reasoning causation argument stance classification, argument consequence classification rocstories correct answer generation Deductive Table 2: ALERT benchmark consists of 20 datasets covering 10 different reasoning skills. The full list of the reasoning skills and datasets is in Table 4 in Appendix A.1. measure the extent to which the evaluation data is different from the finetuning data, i.e. We investi- gate whether the improvement is more significant when evaluation data and finetuning data are more similar. (2) Reasoning skills transfer: We investigate if certain reasoning skills can be more successfully permeated in LLMs than other reasoning skills. To verify this, we carefully divide the evaluation datasets into groups which require different reason- ing skills. We compile held-out datasets as shown in Figure 6 which require skills held-out from any of the training datasets. This way, we expect to see larger improvements on in-domain skills com- pared to held-out skills if reasoning skills can be transferred during finetuning stages. (3) Prompt template memorization: Our third hypothesis is that LLMs can overfit to data for- mat used in the finetuning datasets such as training data format used in Figure 2. In other words, the consistency in data format helps LLMs better un- derstand the instruction which then yields better performance after finetuning. To test this, we eval- uate finetuned LLMs on datasets with 5 different prompt templates. (i) Different from Guru- Summary of findings: rangan et al. (2020), our experiments indicate that there is no strong correlation between high vocab- ulary overlap (between finetuning and evaluation datasets) and performance gain on reasoning evalu- ation datasets. This means that LLMs are not sim- Definition: In this task, we ask you to write an implausible answer to a question that involves event duration, based on a given sentence. Here, event duration is defined as the understanding of how long events typically last. For example, “brushing teeth”, usually takes a few minutes. Even though there exist multiple wrong answers, we only need a single wrong answer. Example 1- input: Sentence: Jack played basketball after school, after which he was very tired. Question: How long did Jack play basketball? output: 22 hours. explanation: Typically we play basketball for a couple of hours. So any answer beyond that range is unlikely. Figure 1: An example from NIV2 (Wang et al., 2022c) that requires a deep understanding of the long task instruction and can be very challenging even for humans. ply memorizing the training data during the fine- tuning stage; (ii) Finetuning helps improve certain reasoning capabilities of LLMs (e.g. analogical and abductive) but not all of them (e.g. common- sense reasoning); (iii) Finetuning can cause over- fitting towards data format, which makes it harder for LLMs to generalize to other prompt templates, while CoT-finetuning helps to mitigate this issue as it incorporates a variety of explanations. Though many of the aspects that we study have been discussed in prior analyses of LLMs (Chung et al., 2022; Wei et al., 2021a, 2022; Kojima et al., 2022; Cobbe et al., 2021; Sanh et al., 2021), prior work has not evaluated LLMs on different reason- ing skills and how these skills can be improved. Overall, by evaluating reasoning skills with ALERT, we gain new insights on how models have or have not succeeded in generalizing beyond their training experience. this paper presents a meticulously designed benchmark for assessing reasoning abilities. Furthermore, a thor- ough investigation of the role of finetuning in the context of reasoning abilities, data memorization, and data format is conducted. # 2 Motivation and Our Benchmark Motivation. The analyses in ALERT are inspired by a scientific question: To what extent do LLMs learn generalizable reasoning abilities? This ques- tion motivates our focus on measuring LLMs’ per- formance on tasks that require contextual under- standing and perform multi-step operations, which are crucial to perform well on downstream tasks. Datasets Construction. To the datasets of ALERT, we select datasets from NIV2 benchmark (Wang et al., 2022c) and perform the following operations: (1) Omit extremely hard tasks. We design ALERT so that it can be used to benchmark a variety of LLMs, from pre-trained, finetuned to instruction-tuned models. To select such tasks, we apply several heuristics: firstly, we manually omit tasks that heavily rely on instructions. Some tasks are hard to solve when only in-context ex- amples (demonstrations) are provided (e.g., the ex- ample in Figure 1). Secondly, we selected only those tasks that achieved a reasonable level of performance (empirically use ROUGE-L > 5.0) when evaluated with a pre-trained model (we use the OPT-13B model). Thirdly, we omit tasks on which humans fail to get decent performance given the ground truth labels from NIV2. For exam- ple, task963_librispeech_asr_next_word_ predic- tion (Weir et al., 2020) provides a prompt “Joey’s favourite food is ___”, with the ground truth answer “sandwiches”. Without any context or background information, the answer can be any food thus it is extremely hard for humans to accurately predict “sandwiches”. (2) Remove tasks with long input context. The input sentence length of some tasks can be very long, and currently most LLMs are not designed for solving long text problems. We omit tasks with demonstration length longer than 2048 tokens. (3) Fix ground truth labels. For each the reason- reasoning task, NIV2 provides ing skills e.g. task102_commongen_data_to_text requires rela- tional, analogical and commonsense reasoning. However, we found that some tasks have been la- beled with incorrect reasoning skills. For exam- ple, task393_plausible_result_generation provides a sentence and asks LLMs to complete the sen- tence. The labels given by NIV2 are causal reason- ing and textual entailment, but in fact this task can hardly examine an entailment skill. Accordingly, we manually fix reasoning skill labels. In addition, we only keep the predominant skill. For example, many tasks need more or less commonsense knowl- edge, therefore we select the related tasks that only heavily rely on commonsense knowledge to assess commonsense reasoning. Benchmark. After the above steps, we select tasks that represent a variety of reasoning skills and construct ALERT reasoning benchmark, where Table 2 shows details about our benchmark. (A) pretrained language models (e.g. GPT-3, OPT) Inference on task A, B, Pretrained finetune on Inference on LM task D. task A, B, C,... Q: If X and Y are digits and 8XY is a 3-digit number that is divisible by 2, which of the following is a possible product of X and Y? A)15 B)31 C)12 D)27 )91; A: The answer is C. finetune on task D, E, F, ... with explanations Inference on task A, B, C,... Q: If X and Y are digits and 8XY is a 3-digit number that is divisible by 2, which of the following is a possible product of X and Y? A)15 B)31 C)12 D)27 E)91; A: The answer is C. because Key to this question is to remember the fact that a number divisible by 2 must end with even OR 0 (ie Y). If Y had to be 0, product should also be 0 regardless of X. Otherwise, product is a multiple of 2. Only one answer choice meets the requirement Figure 2: We compare three types of models: (A) directly apply pretrained LLMs on reasoning tasks; (B) finetune LLMs on a set of tasks; (C) finetune LLMs on tasks with explana- tions (CoT-finetuning). Finetuning data contains source and target parts, and the language modeling loss only applied to # 3 Experiment Setup # 3.1 Models To perform a controlled comparison across training and prompting methods, we focus on three different models: pre-trained, meta-finetuned, and rationale- based meta-finetuned (CoT-finetuned) models. For pre-trained models, we use OPT (Zhang et al., 2022), a suite of decoder-only pre-trained trans- formers which are reported to yield comparable performance to GPT-3 (Brown et al., 2020b). We benchmark with OPT models of two scales: 1.3B and 13B. For finetuned models (OPT-FT), we fine- tune OPT models on datasets without explanations. For CoT-finetuned models (OPT-CoT), we finetune OPT models on data with rationales (explanations). We train all models in Pytorch (Paszke et al., 2017) using OPT-IML (Iyer et al., 2022) codebase3. We initialize model hyper-parameters for each model scale following OPT (Zhang et al., 2022). We pack our training examples into sequences of length 2048, left-truncating examples that overflow. We use AdamW (Loshchilov and Hutter, 2017) with 32-bit state with (β1, β2) = (0.9, 0.95), lin- early warming up the learning rate for 6% steps to the maximum, followed by linearly decaying it to 0. For all 1.3B models, we use batch size of 128, and for 13B models, we use batch size of 256. # 3https://github.com/facebookresearch/metaseq/tree/main/pr ojects/OPT-IML # 3.2 Finetuning Data Our finetuning corpus is comprised of 10 datasets: ProofWriter (Tafjord et al., 2020), StrategyQA (Geva et al., 2021), ECQA (Aggarwal et al., 2021), CoQA (Reddy et al., 2019), GSM8K (Cobbe et al., 2021), AQUA-RAT (Ling et al., 2017), ESNLI (Camburu et al., 2018), MATH (Hendrycks et al., 2021c), CoS-E (Rajani et al., 2019), WinoWhy (Zhang et al., 2020). These 10 finetuning datasets collectively contain 6 different reasoning skills: logical reasoning, causal reasoning, commensense reasoning, textual entailment, mathematics, abduc- tive reasoning. In addition, these 10 datasets all come with instructions, demonstration examples and explanations. This enables fair comparison of OPT-FT and OPT-CoT models. More details about finetuning corpus can be found in Table 5 in Section A.2. More details about development data selection can be found in the Appendix. A.3. # 3.3 Evaluation Templates Following (Wei et al., 2021b), to con- trol for the effect of variable prompt templates, we adopt different templates (T) during inference stage in our experiments: T1: explanations + "let’s think step by step"; T2: instruction + "Please give a short explanation after the answer" + demonstration examples with explanations + "let’s think step by step" T3: instruction + "Please give a short explanation after the answer" + demonstration examples with explanations T4: "Please give a short explanation after the an- swer" + demonstration examples with explanations + "Let’s think step by step" T5: instructions + demonstrations For each dataset, we report the average and max score among these five templates. The final aggre- gated results (including aggregated average score and aggregated max score) are reported by further averaging across all datasets. Unless specified oth- erwise, the default score refers to the aggregated max score among five templates. Evaluation metrics. Since our benchmark con- tains both classification and generation tasks, we cannot use classification accuracy to evaluate all the tasks. Following FLAN (Wei et al., 2021b), we append classification choices at the end of prompts and ask models to generate answers. Thus, clas- sification tasks can be treated as a special case of generation tasks. Accordingly, we use ROUGE-L (Lin, 2004) to measure the performance of both classification and generation tasks and report the aggregated score. Similar to Chung et al. (2022), we also use exact-match score which is more suit- able for tasks with short answers. Additionally, we compute relaxed-match score which is a relaxed version of exact-match. Specifically, we normal- ize ground truth answers and predictions to have all text in lower case and remove punctuation and extra white spaces. # 4 Analysis # 4.1 Does finetuning help? Figure 3 demonstrates the performance averaged across all evaluation tasks in our benchmark. Rationale-based finetuning (OPT-CoT) has been shown to improve the performance of the 1.3B model by 3.89% in terms of the aggregated max ROUGE-L score and 3.83% in terms of the aggre- gated max exact-match score. As for 13B model, OPT-CoT gains the improvement by 15.22% in re- gard of aggregated max ROUGE-L score, 12.64% in regard of aggregated max exact-match score. However, finetuning (OPT-FT) sometimes yields worse results than the vanilla pre-trained model. # 4.2 What does LLMs learn during finetuning? We find that CoT-finetuning improves performance on reasoning tasks in general. However, what ex- actly does the LLMs learn during the finetuning stage is still under explored. Thus, we study the role of finetuning from three perspectives: data memorization, reasoning skill transfer, and prompt template memorization. # 4.2.1 Data Memorization Gururangan et al. (2020) finds that the performance gain is larger when the finetuning dataset is more dissimilar to the pre-training dataset. However, their conclusion is made by a single-task finetun- ing. They evaluate their model on the same dataset that was used for finetuning. A more thorough eval- uation dictates that finetuned models (Wei et al., 2021b; Chung et al., 2022) be evaluated on held- out datasets. As such, in Figure 2 in blocks (B) and (C) we show two potential ways of finetuning and inference as illustrated here in our paper. To confirm that the improvement in finetuning performance is due to the increased amount of data seen during the finetuning stage, we measure the dissimilarity between the training data used in fine- tuning and evaluation, respectively. If higher simi- larity leads to better performance, it may indicate that the improvements of finetuned LLMs are due to seeing more similar data during the finetuning stage. Following (Gururangan et al., 2020), we use unigram vocabulary overlap to measure the data similarity. More specifically, we divide our tasks into three categories: The first category has 10 datasets which consists of up to 10% overlap between the finetuning data and evaluation data. The second category comprises 3 datasets with an overlap between 10% and 30%. The third category has 7 datasets with an overlap over 30%. Details can be found in Table 7 in appendix A.5. We measure the performance improvements of OPT-FT and OPT-CoT compared against the pre- trained OPT model. We present both ROUGE- L score (top) and relaxed-match score (down) in Figure 5. The results indicate that there is no strong correlation between the vocabulary overlap between fineuning and evaluation datasets and the performance of the model (neither a higher nor a lower vocabulary overlap always translate to a per- formance improvement). OPT-CoT achieves the best ROUGE-L and relaxed-match scores both in settings when there is a medium (10%-30%) level of vocabulary overlap. We don’t observe a consis- tent pattern on OPT-FT models either. Overall, for these challenging tasks, seeing similar data during finetuning stage does not guarantee performance improvement. # 4.2.2 Reasoning Skill Transfer Table 6 illustrates the reasoning skills present in each stage. 7 skills can be learned from pretrain- ing data. Appendix. A.4 shows more details about pretraining data. 6 skills can be learned from fine- tuning data (Table 5). Using ALERT we measure a total of 10 reasoning skills in model evaluation. The average ROUGE-L scores are calculated for each reasoning skill on 6 models (1.3B OPT, 1.3B OPT-FT, 1.3B OPT-CoT, 13B OPT, 13B OPT- FT, 13B OPT-CoT). Figure 7 shows the difference between OPT-FT and OPT, and the difference be- tween OPT-CoT and OPT models’ performance. For example, OPT-FT 1.3B model yields on av- erage 3.5 less ROUGE-L points than OPT 1.3B model on the tasks of logical reasoning. Figure 7 contains 4 sub-figures, showing reason- ing skills transfer results: (i) The upper left sub- # Aggregated Max Scores across 5 Templates # Aggregated Average Scores across 5 Templates OPT mmm OPT-FT il OPT-CoT OPT mmm OPT-FT S_ OPT-CoT 30 2 oe @ 30 2 on 25 3 2g 3S 20 2 fed 5 S 8 B15 8 a 5 20 ao ) < ) 5 aw? 3” His s 8 E o E10 3 310 310 3 & 10 g [v4 & a. 5 os 0 0 0 0 138 138 1.38 13B 138 138 1.38 13B Model scale Model scale Model scale Model scale OPT mm OPT-FT OPT-CoT @ 100 12 gs § 20 10 8 5 a Ss > 60 Fy 2 3 = Bs, 3 40 5 2 Za 8 ra q 2 2 E roo 0 138 13B 1.38 13B Paramet Paramet arameters arameters Figure 4: Analyzing the robustness of models in following the templates. Left: template following percentage by each model; Right: standard devi- ation of template following percent- age. Figure 3: Performance of pre-trained LM (OPT), finetuned LM (OPT-FT) and CoT- finetuned LM (OPT-CoT) on ALERT reasoning benchmark. Left charts show aggregated max scores while right are average scores across 5 templates. across 20 tasks. % Sox, 299% 9.53% | 50 2 & gs ¢& 6.30 % 2.58% fig f ¢ $ So om fe) & & PP 11.55% REAR 73.95% fn 2 ¢ & 3s ¢ “s S S$ 380% 903% ‘% 12.45% |F-50 x x & OPT-FT OPT-CoT OPT-FT OPT-CoT Performance Changes (%) compared to OPT Scores are averaged finetuning are not Gururangan et al. dissimilar the domain tuning are, the higher to yield gains. We main in Gururangan vocabulary overlaps, finetuning are not as pronounced. Additionally, Gururangan et al. (2020) concluded that the more dissimilar the domain between pretraining and fine- tuning are, the higher the potential for finetuning to yield gains. We see the same trend but the do- main in Gururangan et al. (2020) is defined by the vocabulary overlaps, while we define the domains by reasoning skills. From figure (iii) we can see that the reasoning skills gained during the meta- finetuning stage may not necessarily transfer to the improvement of the same skills on the evaluation datasets. Figure 5: Correlation between vocabulary overlap and per- formance improvement using 13B parameter models. The left chart shows ROUGE-L while the right shows relaxed- match score. figure shows 7 skills that are acquired during the pretraining stage (OPT pretraining data), and how much improvement can be obtained through meta- finetuning (OPT-FT and OPT-CoT); (ii) The bot- tom left sub-figure illustrates that these 3 skills are harder to acquire during the pre-training stage, and the amount of improvement that can be obtained through meta-finetuning; (iii) The upper right sub- figure illustrates that such 7 skills are acquired dur- ing the meta-finetuning stage through finetuning datasets (Table 5). Do these skills show improve- ment measured by evaluation benchmark? (iv) The bottom right sub-figure studies the reasoning skills that were not learned in the finetuning stage, can these skills be improved through meta-finetuning? We study the answers to these questions below. From figure (ii) We observe that all four of the LLMs demonstrate enhanced reasoning capabili- ties on textual entailment, abductive reasoning, and analogical reasoning tasks. These abilities are not readily acquired during the pretraining stage, as the pretraining data consists only of plain text. On the other hand, skills such as commonsense rea- soning or spatial reasoning can be gained during the pretraining stage, while the benefits of further We also observe that finetuning with OPT-CoT enables the model to acquire a wider range of rea- soning skills, resulting in stronger performance on logical and causal reasoning tasks, in addition to skills that consistently improve across all finetuned models. 4.2.3 Data Format Memorization We investigate whether finetuning can simply mem- orize the template representation of the training data, and the effect of data format on the robust- ness of the models. Evaluation with relaxed-match score. We compare two metrics: exact-match and relaxed- match. From Figure 3, we observe that OPT-FT is worse than OPT when exact-match is used as the metric. However, when relaxed-match is used, OPT-FT outperforms OPT as shown in Figure 8. Relaxed-match score ignores punctuation, articles and extra whitespace. This suggests that if we de- couple performance from format adherence, OPT- FT performs better than OPT. In other words, fine- tuning is helpful but it can make the output more noisy. This explains the reason for the performance drop when exact-match is used as the metric. Pretraining Reasoning Skills i Commonsense i Meta-finetuning Reasoning Skills Held-out Entailment Abductive | Analogical Evaluation Reasoning Skills : i Logical -3.50 -2: Causal -3.18 Commonsense 0.14 2.71 i Math 0.59 -1.43 Spatial -0.05 -0.46 Argument 1.35 Held-out Skills from Pretraining Data Entailment Abductive | Analogical : Skills in Pretraining Data Logical Causal | Commonsense Entailment Math Abductive Spatial Held-out Skills from Meta-finetuning Data Analogical | 1.68 Argument 1.35 15.84 CPL 13.87 4.13 1.33 3.84 Deductive 3.31 -3.65 1.03 & Re Figure 6: Reasoning skills learned during pretraining and meta-finetuning stages, as well as tested through ALERT . Figure 7: The ROUGE-L scores illustrating the difference between OPT-FT and OPT, as well as OPT-CoT and OPT models within each reasoning skill. Left: skills split by pretraining data; Right: skills split by meta-finetuning data. OPT mmm OPT-FT sms OPT-CoT 5 § 25 § 30 8 ro é 32 3 x x 20 B15 & © & 10 § 10 ® = g < 0 0 13B 0 13B 1.3B 0 13B Model scale Model scale Figure 8: Comparing pretraining and finetuning models with relaxed match score. Left: aggregated best (max) performance across 5 Templates; Right: aggregated average performance across 5 Templates. Robustness To assess the robustness of each model to various templates, we compute the stan- dard deviation of ROUGE-L scores for each model across five different templates. As we can see from Figure 4 (right), OPT is robust to different tem- plates, while OPT-FT has difficulties adapting to changing templates. In general, finetuning (both OPT-FT and OPT-CoT) adversely affects the ro- bustness of the model and makes the model biased towards a specific data format, however, OPT-CoT is better than general finetuning (OPT-FT). Template following percentage. We check whether the model can follow the template of the demonstrations. For example, if a demonstration uses "the answer is xxx because yyy", then we check what percentage of instances can follow the exact same template as the demonstration. Figure 4 (left) shows the average template following percent- age for each model. Both OPT and OPT-CoT con- sistently show that they can follow demonstrations’ even though OPT is not pre-trained on rationales. Compared to 1.3B models, larger models demon- strate a greater overall ability to follow the template of the demonstrations. Compared to OPT and OPT- CoT, OPT-FT lacks the ability to follow diverse templates. This is because the OPT-FT training process does not contain any rationale data. Fine- tuning causes the model to become more biased towards a particular template representation, while its ability to adapt to other templates becomes im- paired. It is worth noting that despite being trained on rationales, the OPT-CoT model performs well when evaluated using non-CoT templates. Reasoning quality. Following (Golovneva et al., 2022) we evaluate reason- ing abilities of the models using ROSCOE scoring suite (Table 3). Looking at each score in detail (Appendix C), we found that overall across templates OPT-FT models produce shorter, less informative chains, while OPT baseline models produce long chains with high amount of self-repetitions. 13B OPT-CoT chains showed best quality despite some self-consistency and grammar issues. When comparing prompt templates, models prompted with Template 5 produce short chains, often without reasoning at all, even if they were fine-tuned on reasoning chains (OPT-CoT), suggesting overfitting to the prompt template. In summary, models learn the data format rep- resentation and templates during finetuning stage. However, finetuned models contain bias towards the data formats and template it has seen, which potentially reduces the robustness of the model to more generalized settings. When comparing ro- bustness, OPT-CoT is better than OPT-FT, but it is still not as robust as the pre-trained model. 1.3B 13B Metrics ROSCOE-SA 0.936 ROSCOE-SS 0.925 ROSCOE-LI 0.848 ROSCOE-LS 0.725 OPT OPT-FT OPT-CoT OPT OPT-FT OPT-CoT 0.940 0.925 0.890 0.640 0.921 0.923 0.953 0.744 0.938 0.920 0.875 0.666 0.936 0.926 0.863 0.688 0.923 0.916 0.944 0.705 Table 3: Summary of the ROSCOE evaluation results averaged across templates. Each metric is bounded within [0, 1], where 1 indicates the perfect score and 0 corresponds to failure. In each row, values corresponding to the best-performing model are bolded, second best are underscored. # 5 Related Work LLMs that Reason. To improve LLMs’ reason- ing abilities, Kojima et al. (2022) shows that LLMs can be decent zero-shot reasoners by simply ap- pending “Let’s think step by step” to the prompt. Wei et al. (2022) adds a series of intermediate rea- soning steps to improve LLMs’ reasoning abilities. Wang et al. (2022a) further proposes to expand prompts to include rationales in each few-shot ex- ample. Fu et al. (2022) discovers that prompting with higher reasoning complexity achieves substan- tial gains on math word tasks. To tackle problems harder than demonstration examples, Zhou et al. (2022) first reduces a complex problem into a list of subproblems and solve subproblems sequentially. Another line of research is to improve the naive decoding strategy, Wang et al. (2022b) introduces a self-consistency strategy which selects the most consistent answer among a set of reasoning paths. Existing Reasoning Benchmarks. Many bench- marks are used for evaluating language models’ performance, such as BIG-Bench (Srivastava et al., 2022), Natural Instruction V2 (NIV2) (Wang et al., 2022c), MMLU (Hendrycks et al., 2020). Although they contain some reasoning tasks, none of them are specifically designed to test models’ reasoning skills. For example, NIV2 contains 172 datasets and a total of 1554 tasks, including some reasoning tasks. It has several issues which make it inap- propriate to be directly used as a reasoning bench- mark: (1) it is designed for instruction-tuned mod- els and some tasks might be unsuitable for evaluat- ing pretrained models or non-instruction finetuned models, as shown in Figure 1; (2) reasoning skills have been divided into 27 categories while some of them have large overlaps, e.g. numerical reason- ing, quantitative reasoning, reasoning on numbers; (3) some reasoning labels are wrongly labeled, e.g. task393_plausible_result_generation gives textual entailment label but this task can hardly examine the entailment skill. The Curriculum benchmark (Chen and Gao, 2022) is designed for probing LLMs’ reasoning abilities and covers 8 different reasoning skills. However, this work only focuses on classification tasks and it converts all examples into the Natu- ral Language Inference (NLI) format to fit into a unified framework. We argue that the forced con- version of all datasets into the NLI format does not align with human natural conversational style. We observed that even davinci-003 fails at some simple tasks due to their forced conversion, e.g. examples in Table 1. More discussion and results are shown in the Appendix B. Finetuning LLMs. LLMs meta-finetuned on a range of NLP tasks have shown improved per- formance on held-out downstream tasks such as FLAN (Wei et al., 2021b), T0 (Sanh et al., 2021), Tk-Instruct (Wang et al., 2022c) and Instruct-GPT (Ouyang et al., 2022). Following this approach, we finetune OPT models and name this type of models as OPT-FT ((B) in Figure 2). Chung et al. (2022) further adds chain-of-thought data at fine- tuning stage and shows significant improvements. We also study this type of models and name them as OPT-CoT ((C) in Figure 2). However, from previous research it still remains unclear whether the improvement comes from simply adding more training data or finetuning on rationales actually helps. We conduct rigorous evaluations to address this question. # 6 Conclusion We introduce ALERT, a carefully curated benchmark for evaluating reasoning abilities of LLMs. It com- prises over 20 datasets and covers 10 different rea- soning skills. Using this benchmark, we further investigate the impact of finetuning on these com- plex tasks. Our experiments reveal that LLMs do not simply memorize training data, but are capable of learning various reasoning skills, such as textual entailment, abductive reasoning and analogical rea- soning. While we found that finetuning generally leads to improved performance, we also discovered some negative effects. LLMs tend to memorize the data template representation and templates seen during finetuning, thus reducing the robustness of the model to generalized settings. CoT-finetuning (OPT-CoT) can alleviate this issue to some extent, but it is still less robust compared to the vanilla pre-trained model. # Limitations ALERT aims to encompass a wide range of rea- soning skills, but some reasoning skills are miss- ing, specifically in regards to symbolic reason- ing (last letter concatenation task and coin flip (Wei et al., 2022)) and compositionality reason- ing (SCAN (Lake and Baroni, 2018), COGS (Kim and Linzen, 2020) and CFQ (Keysers et al., 2019)). These reasoning skills should be included in future work. In terms of computing power, we have experi- mented with models that were accessible to us. We acknowledge that there are larger models that we were not able to train due to the limitations of our computational budget. During our analysis, we discovered that some datasets contain noise, where even human experts are unable to provide accurate answers for certain instances. While it is important to address this issue, it is a time-consuming process to carefully review and clean each instance in the dataset. We plan to address this in future work. # Ethics Statement Large language models (LLMs), due to potential bias in the training data, can be prone to gener- ate toxic and unwanted content (Weidinger et al., 2021). However, in this paper, we are focused on reasoning tasks where the model is prompted to explain its decisions, because of which our model falls under contained generation. By providing clear prompts and constraints, we believe that this might help guide the model’s output towards spe- cific, desired outcomes and reduce the likelihood of generating unwanted or harmful content, as op- posed to open ended text generation tasks. # References Shourya Aggarwal, Divyanshu Mandowara, Vishwa- jeet Agrawal, Dinesh Khandelwal, Parag Singla, and Dinesh Garg. 2021. Explanations for Com- monsenseQA: New Dataset and Models. In Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), pages 3050–3065, Online. Association for Compu- tational Linguistics. Badr AlKhamissi, Siddharth Verma, Ping Yu, Zhijing Jin, Asli Celikyilmaz, and Mona Diab. 2023. Opt- r: Exploring the role of explanations in finetuning and prompting for reasoning skills of large language models. arXiv preprint arXiv:2305.12001. Mikel Artetxe, Shruti Bhosale, Naman Goyal, Todor Mihaylov, Myle Ott, Sam Shleifer, Xi Victoria Lin, Jingfei Du, Srinivasan Iyer, Ramakanth Pasunuru, et al. 2021. Efficient large scale language mod- eling with mixtures of experts. arXiv preprint arXiv:2112.10684. Jason Baumgartner, Savvas Zannettou, Brian Keegan, Megan Squire, and Jeremy Blackburn. 2020. The pushshift reddit dataset. In Proceedings of the international AAAI conference on web and social media, volume 14, pages 830–839. Yonatan Bisk, Rowan Zellers, Ronan Le Bras, Jian- feng Gao, and Yejin Choi. 2020. Piqa: Reasoning about physical commonsense in natural language. In Thirty-Fourth AAAI Conference on Artificial Intelligence. Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. 2020a. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901. Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. 2020b. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901. Oana-Maria Camburu, Tim Rocktäschel, Thomas Lukasiewicz, and Phil Blunsom. 2018. e-snli: Nat- ural language inference with natural language expla- nations. Advances in Neural Information Processing Systems, 31. Zeming Chen and Qiyue Gao. 2022. Curriculum: A broad-coverage benchmark for linguistic phe- nomena in natural language understanding. arXiv preprint arXiv:2204.06283. Aakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al. 2022. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311. Hyung Won Chung, Le Hou, Shayne Longpre, Bar- ret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, et al. 2022. Scaling instruction-finetuned language mod- els. arXiv preprint arXiv:2210.11416. Karl Cobbe, Vineet Kosaraju, Mohammad Bavar- ian, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman. 2021. Training veri- fiers to solve math word problems. arXiv preprint arXiv:2110.14168. Yao Fu, Hao Peng, Ashish Sabharwal, Peter Clark, and Tushar Khot. 2022. Complexity-based prompt- ing for multi-step reasoning. arXiv preprint arXiv:2210.00720. Nancy Fulda, Nathan Tibbetts, Zachary Brown, and David Wingate. 2017. Harvesting common-sense navigational knowledge for robotics from uncurated text corpora. In Conference on Robot Learning, pages 525–534. PMLR. Leo Gao, Stella Biderman, Sid Black, Laurence Gold- ing, Travis Hoppe, Charles Foster, Jason Phang, Ho- race He, Anish Thite, Noa Nabeshima, et al. 2020. The pile: An 800gb dataset of diverse text for lan- guage modeling. arXiv preprint arXiv:2101.00027. Mor Geva, Daniel Khashabi, Elad Segal, Tushar Khot, Dan Roth, and Jonathan Berant. 2021. Did aristotle use a laptop? a question answering benchmark with implicit reasoning strategies. Transactions of the Association for Computational Linguistics, 9:346– 361. Olga Golovneva, Moya Chen, Spencer Poff, Mar- tin Corredor, Luke Zettlemoyer, Maryam Fazel- Zarandi, and Asli Celikyilmaz. 2022. Roscoe: A suite of metrics for scoring step-by-step reasoning. Swabha Swayamdipta, Kyle Lo, Iz Beltagy, Doug Downey, and Noah A Smith. 2020. Don’t stop pretraining: adapt language models to domains and tasks. arXiv preprint arXiv:2004.10964. Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Stein- hardt. 2020. Measuring massive multitask language understanding. arXiv preprint arXiv:2009.03300. Dan Hendrycks, Collin Burns, Steven Basart, Andy and Ja- Measuring massive Proceedings the International Conference on Learning Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song, and Jacob Steinhardt. 2021b. Measuring mathematical problem solving with the math dataset. NeurIPS. Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song, and Jacob Steinhardt. 2021c. Measuring mathemati- cal problem solving with the math dataset. arXiv preprint arXiv:2103.03874. Mark Hopkins, Ronan Le Bras, Cristian Petrescu- Prahova, Gabriel Stanovsky, Hannaneh Hajishirzi, and Rik Koncel-Kedziorski. 2019. Semeval-2019 task 10: math question answering. In Proceedings of the 13th International Workshop on Semantic Evaluation, pages 893–899. Srinivasan Iyer, Xi Victoria Lin, Ramakanth Pasunuru, Todor Mihaylov, Dániel Simig, Ping Yu, Kurt Shus- ter, Tianlu Wang, Qing Liu, Punit Singh Koura, et al. 2022. Opt-iml: Scaling language model instruc- tion meta learning through the lens of generalization. arXiv preprint arXiv:2212.12017. Daniel Keysers, Nathanael Schärli, Nathan Scales, Hylke Buisman, Daniel Furrer, Sergii Kashubin, Nikola Momchev, Danila Sinopalnikov, Lukasz Stafiniak, Tibor Tihon, et al. 2019. Measuring com- positional generalization: A comprehensive method on realistic data. arXiv preprint arXiv:1912.09713. Najoung Kim and Tal Linzen. 2020. Cogs: A compo- sitional generalization challenge based on semantic interpretation. arXiv preprint arXiv:2010.05465. Diederik P Kingma and Jimmy Ba. 2014. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. Jonathan Kobbe, Ioana Hulpus, , and Heiner Stucken- schmidt. 2020. Unsupervised stance detection for ar- guments from consequences. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 50–60. Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yu- taka Matsuo, and Yusuke Iwasawa. 2022. Large language models are zero-shot reasoners. arXiv preprint arXiv:2205.11916. Brenden Lake and Marco Baroni. 2018. Generalization without systematicity: On the compositional skills of sequence-to-sequence recurrent networks. In International conference on machine learning, pages 2873–2882. PMLR. Yash Kumar Lal, Nathanael Chambers, Raymond Mooney, and Niranjan Balasubramanian. 2021. TellMeWhy: A dataset for answering why-questions In Findings of the Association in narratives. for Computational Linguistics: ACL-IJCNLP 2021, pages 596–610, Online. Association for Computa- tional Linguistics. Bill Yuchen Lin, Wangchunshu Zhou, Ming Shen, Pei Zhou, Chandra Bhagavatula, Yejin Choi, and Xiang Ren. 2020. CommonGen: A constrained text generation challenge for generative common- In Findings of the Association sense reasoning. for Computational Linguistics: EMNLP 2020, pages 1823–1840, Online. Association for Computational Linguistics. Chin-Yew Lin. 2004. Rouge: A package for automatic In Text summarization evaluation of summaries. branches out, pages 74–81. Wang Ling, Dani Yogatama, Chris Dyer, and Phil Blun- som. 2017. Program induction by rationale gen- eration: Learning to solve and explain algebraic word problems. In Proceedings of the 55th Annual the Association for Computational Meeting of Linguistics (Volume 1: Long Papers), pages 158– 167, Vancouver, Canada. Association for Computa- tional Linguistics. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man- dar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining ap- proach. arXiv preprint arXiv:1907.11692. Ilya Loshchilov and Frank Hutter. 2017. weight decay regularization in adam. abs/1711.05101. Todor Mihaylov, Peter Clark, Tushar Khot, and Ashish Sabharwal. 2018. Can a suit of armor conduct elec- tricity? a new dataset for open book question answer- ing. arXiv preprint arXiv:1809.02789. Swaroop Mishra, Daniel Khashabi, Chitta Baral, and Hannaneh Hajishirzi. 2022. Cross-task generaliza- tion via natural language crowdsourcing instructions. In ACL. Nasrin Mostafazadeh, Nathanael Chambers, Xiaodong He, Devi Parikh, Dhruv Batra, Lucy Vanderwende, Pushmeet Kohli, and James Allen. 2016. A cor- pus and cloze evaluation for deeper understanding of commonsense stories. In Proceedings of the 2016 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 839–849. Aida Nematzadeh, Kaylee Burns, Erin Grant, Alison Gopnik, and Thomas L Griffiths. 2018. Evaluat- ing theory of mind in question answering. arXiv preprint arXiv:1808.09352. Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. 2021. Show your work: Scratch- pads for intermediate computation with language models. arXiv preprint arXiv:2112.00114. Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Car- roll L Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, et al. Training language models to follow in- 2022. arXiv preprint structions with human feedback. arXiv:2203.02155. Adam Paszke, Sam Gross, Soumith Chintala, Gregory Chanan, Edward Yang, Zachary DeVito, Zeming Lin, Alban Desmaison, Luca Antiga, and Adam Lerer. 2017. Automatic differentiation in pytorch. In NIPS 2017 Workshop on Autodiff. Nazneen Fatema Rajani, Bryan McCann, Caiming Xiong, and Richard Socher. 2019. Explain yourself! leveraging language models for commonsense rea- soning. arXiv preprint arXiv:1906.02361. Siva Reddy, Danqi Chen, and Christopher D. Manning. 2019. CoQA: A conversational question answer- ing challenge. Transactions of the Association for Computational Linguistics, 7:249–266. Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M Smith, et al. 2020. Recipes for building an open-domain chatbot. arXiv preprint arXiv:2004.13637. Christopher Rytting and David Wingate. 2021. Lever- aging the inductive bias of large language models for abstract textual reasoning. Advances in Neural Information Processing Systems, 34:17111–17122. Victor Sanh, Albert Webson, Colin Raffel, Stephen H Bach, Lintang Sutawika, Zaid Alyafeai, Antoine Chaffin, Arnaud Stiegler, Teven Le Scao, Arun Raja, et al. 2021. Multitask prompted training en- ables zero-shot task generalization. arXiv preprint arXiv:2110.08207. Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catan- zaro. 2019. Megatron-lm: Training multi-billion pa- rameter language models using model parallelism. arXiv preprint arXiv:1909.08053. 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. 2022. Beyond the imitation game: Quantifying and extrapolating the arXiv preprint capabilities of language models. arXiv:2206.04615. Kai Sun, Dian Yu, Jianshu Chen, Dong Yu, Yejin Choi, and Claire Cardie. 2019. DREAM: A chal- lenge dataset and models for dialogue-based reading comprehension. Transactions of the Association for Computational Linguistics. Oyvind Tafjord, Bhavana Dalvi Mishra, and Peter Clark. 2020. Proofwriter: Generating implications, proofs, and abductive statements over natural lan- guage. arXiv preprint arXiv:2012.13048. Trieu H Trinh and Quoc V Le. 2018. A simple method for commonsense reasoning. arXiv preprint arXiv:1806.02847. Alex Wang, Yada Pruksachatkun, Nikita Nangia, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. 2019. Super- glue: A stickier benchmark for general-purpose arXiv preprint language understanding systems. arXiv:1905.00537. Alex Wang, Amanpreet Singh, Julian Michael, Fe- lix Hill, Omer Levy, and Samuel Bowman. 2018. GLUE: A multi-task benchmark and anal- ysis platform for natural language understanding. In Proceedings of the 2018 EMNLP Workshop BlackboxNLP: Analyzing and Interpreting Neural Networks for NLP, pages 353–355, Brussels, Bel- gium. Association for Computational Linguistics. Xuezhi Wang, Jason Wei, Dale Schuurmans, Quoc Le, Ed Chi, and Denny Zhou. 2022a. Rationale- augmented ensembles in language models. arXiv preprint arXiv:2207.00747. Xuezhi Wang, Jason Wei, Dale Schuurmans, Quoc Le, Ed Chi, and Denny Zhou. 2022b. Self-consistency improves chain of thought reasoning in language models. arXiv preprint arXiv:2203.11171. Yizhong Wang, Swaroop Mishra, Pegah Alipoor- molabashi, Yeganeh Kordi, Amirreza Mirzaei, Anjana Arunkumar, Arjun Ashok, Arut Selvan Dhanasekaran, Atharva Naik, David Stap, et al. 2022c. Super-naturalinstructions:generalization via declarative instructions on 1600+ tasks. In EMNLP. Jason Wei, Maarten Bosma, Vincent Y Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan Du, An- drew M Dai, and Quoc V Le. 2021a. Finetuned lan- guage models are zero-shot learners. arXiv preprint arXiv:2109.01652. Jason Wei, Maarten Bosma, Vincent Y Zhao, Kelvin Guu, Adams Wei Yu, Brian Lester, Nan Du, An- drew M Dai, and Quoc V Le. 2021b. Finetuned lan- guage models are zero-shot learners. arXiv preprint arXiv:2109.01652. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Ed Chi, Quoc Le, and Denny Zhou. 2022. Chain of thought prompting elicits reasoning in large language models. arXiv preprint arXiv:2201.11903. Laura Weidinger, John Mellor, Maribeth Rauh, Conor Griffin, Jonathan Uesato, Po-Sen Huang, Myra Cheng, Mia Glaese, Borja Balle, Atoosa Kasirzadeh, et al. 2021. Ethical and social risks of harm from language models. arXiv preprint arXiv:2112.04359. Nathaniel Weir, João Sedoc, and Benjamin Van Durme. Cod3s: Diverse generation with dis- arXiv preprint 2020. crete arXiv:2010.02882. semantic signatures. Johannes Welbl, Nelson F Liu, and Matt Gardner. 2017. Crowdsourcing multiple choice science questions. arXiv preprint arXiv:1707.06209. Peter West, Chandra Bhagavatula, Jack Hessel, Jena Hwang, Liwei Jiang, Ronan Le Bras, Ximing Lu, Sean Welleck, and Yejin Choi. 2022. Symbolic knowledge distillation: from general language mod- els to commonsense models. In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 4602–4625, Seattle, United States. Association for Computa- tional Linguistics. Jason Weston, Antoine Bordes, Sumit Chopra, Alexan- der M Rush, Bart Van Merriënboer, Armand Joulin, and Tomas Mikolov. 2015. Towards ai-complete question answering: A set of prerequisite toy tasks. arXiv preprint arXiv:1502.05698. Adina Williams, Tristan Thrush, and Douwe Kiela. 2022. Anlizing the adversarial natural language In Proceedings of the 5th inference dataset. Annual Meeting of the Society for Computation in Linguistics, pages 23–54. Association for Computa- tional Linguistics. Hongming Zhang, Xinran Zhao, and Yangqiu Song. 2020. WinoWhy: A deep diagnosis of es- sential commonsense knowledge for answering Winograd schema challenge. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 5736–5745, On- line. Association for Computational Linguistics. Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen, Christopher De- wan, Mona Diab, Xian Li, Xi Victoria Lin, et al. 2022. Opt: Open pre-trained transformer language models. arXiv preprint arXiv:2205.01068. Denny Zhou, Nathanael Schärli, Le Hou, Jason Wei, Nathan Scales, Xuezhi Wang, Dale Schuurmans, Olivier Bousquet, Quoc Le, and Ed Chi. 2022. Least-to-most prompting enables complex reason- arXiv preprint ing in large language models. arXiv:2205.10625. Yukun Zhu, Ryan Kiros, Rich Zemel, Ruslan Salakhut- dinov, Raquel Urtasun, Antonio Torralba, and Sanja Fidler. 2015. Aligning books and movies: Towards story-like visual explanations by watching movies and reading books. In Proceedings of the IEEE international conference on computer vision, pages 19–27. # A More Details about Data Usage # A.1 Reasoning Benchmark Table 4 shows detailed reasoning benchmark. # A.2 Training Corpus (cont. from §3.2) We used 10 datasets for finetuning, which contain 6 different reasoning skills. # A.3 Development Data Details Our finetuning models are tuned on pretrained LLMs on the finetuning corpus with the goal of improving the performance of unseen tasks. For example, blocks (B) and (C) in Figure 2 are show- ing models that are finetuned on tasks B,C,D and the goal is to achieve good results on task A. Checkpoint selection can determine the final per- formance of the LLMs to a very large extent. There are several ways to select checkpoints: (i) select checkpoint of the last iteration; (ii) select check- point based on perplexity or loss from validation datasets of finetuning corpus (validation datasets of task B, C, D); (iii) select checkpoint based on perplexity or loss from validation datasets of evalu- ation corpus (validation datasets of task A); In order to achieve a better performance on evalu- ation corpus, a common approach is to use methods like (iii) to select a checkpoint. However, we would like to prevent LLMs overfiting to the distribution of our final evaluation corpus. We initially used the method (ii) but found that it did’t work well. However, this resulted in a distribution mismatch issue. We speculate this to the fact that some tasks in our finetuning corpus do not have a validation set. We thus select 3 tasks from NIV2 benchmark and compile a development set that does not have any overlaps with our finetuning data or evaluation data. There are 3 datasets used as our develop- ment set for checkpoint selection: task 247 dream answer generation (Sun et al., 2019), task 118 se- meval and task 10 open vocabulary mathematical answer generation (Hopkins et al., 2019) and anli r1 entailment (Williams et al., 2022) # A.4 Pretraining Data Analysis The pre-training corpus of OPT model (Zhang et al., 2022) contains a concatenation of datasets used in RoBERTa (Liu et al., 2019), the Pile (Gao et al., 2020), and PushShift.io Reddit (Baumgartner et al., 2020; Roller et al., 2020). RoBERTa Three datasets in RoBERTa (Liu et al., 2019) are used as pretraining corpus: Book- Corpus (Zhu et al., 2015), Stories (Trinh and Le, 2018), and CCNews (Liu et al., 2019). Deductive reasoning skill and spatial reasoning skill can be learned from stories dataset. Logical reasoning skill can be learned from these three datasets. Pile A subset of the Pile (Gao et al., 2020) are used as pre-training corpus, including Common- Crawl, DM Mathematics, Project Gutenberg, Hack- erNews, OpenSubtitles, OpenWebText2, USPTO, and Wikipedia. Mathematics reasoning skill can be learned from DM Mathematics dataset. Causal Rea- soning can be learned widely from OpenWebText2. Commensense reasoning skill can be learned from Wikipedia. PushShift.io Reddit The longest chain of comments in each thread are extracted from PushShift.io Reddit (Baumgartner et al., 2020). Ar- gument reasoning skill can be learned from this dataset. # A.5 Vocabulary Overlaps (Cont. from § 4.2.1) We measure unigram vocabulary overlaps between our finetuning corpus and the evaluation corpus (reasoning benchmark). # B Curriculum Benchmark Results (Cont. from §5) We randomly selected one dataset from each rea- soning skill and reported the results of GPT-3 (Brown et al., 2020b) (text-davinci engine). Since all of the data has been converted to NLI format, we measure classification accuracy of GPT-3 model. From Table 8, we can see that even GPT-3 achieves a pretty random results on these datasets. Through our analysis, we found that it is not because those tasks are too difficult for GPT-3, it is because curriculum benchmark forcing all the data to be NLI format, resulting in unnatural data expression, which made GPT-3 fail on it. We conclude that the curriculum benchmark may be suitable for classi- fication finetuned models, but it is not suitable for language models for in-context learning. # C Evaluating reasoning chains (Cont. from §5) Following (Golovneva et al., 2022) we evaluate reasoning abilities of the models using ROSCOE Logical Reasoning Causal Reasoning Commonsense Reasoning Texual Entailment Mathematics Abductive Reasoning Spatial Reasoning Analogical Reasoning Argument Reasoning Deductive Reasoning Task ID 62 697 393 1386 1387 1388 80 102 591 1286 1386 1387 1388 1344 104 119 697 332 83 80 151 102 1152 513 514 216 Datasets bigbench repeat copy logic (Srivastava et al., 2022) mmmlu answer generation formal logic (Hendrycks et al., 2021a) plausible result generation (Weir et al., 2020) anli r2 entailment (Williams et al., 2022) anli r3 entailment (Williams et al., 2022) cb entailment (Wang et al., 2019) piqa answer generation (Bisk et al., 2020) commongen sentence generation (Lin et al., 2020) sciq answer generation (Welbl et al., 2017) openbookqa question answering (Mihaylov et al., 2018) anli r2 entailment (Williams et al., 2022) anli r3 entailment (Williams et al., 2022) cb entailment (Wang et al., 2019) glue entailment classification (Wang et al., 2018) semeval closed vocabulary math answer generation (Hopkins et al., 2019) semeval geometric math answer generation (Hopkins et al., 2019) mmmlu answer generation formal logic (Hendrycks et al., 2021a) tellmewhy answer generation (Lal et al., 2021) babi t1 single supporting fact answer generation (Weston et al., 2015) piqa answer generation (Bisk et al., 2020) tomqa find location easy clean (Nematzadeh et al., 2018) commongen sentence generation (Lin et al., 2020) bard analogical reasoning causation (Fulda et al., 2017) argument stance classification (Kobbe et al., 2020) argument consequence classification (Kobbe et al., 2020) rocstories correct answer generation (Mostafazadeh et al., 2016) Table 4: Details about ALERT benchmark. Datasets Train Size Val Size Test Size Reasoning Skills ProofWriter StrategyQA ECQA CoQA GSM8K AQUA-RAT ESNLI MATH CoS-E WinoWhy 69,810 2,290 7,598 10,8647 7,473 97,467 549,367 7,500 9,741 273 10,190 - 1,090 7,983 - 254 9,842 - 1,221 - 20,030 490 2,194 - 1,319 254 9,824 5,000 - - Logical Reasoning, Causal Reasoning Commonsense Reasoning Commonsense Reasoning Textual Entailment Mathematics Mathematics Commonsense Reasoning, Logical Reasoning, Textual Entailment Mathematics Commonsense Reasoning Abductive Reasoning, Commonsense Reasoning Table 5: Training corpus for meta-finetuning OPT-FT and OPT-CoT. (Cont. from § 3.2) Task ID Datasets Reasoning Skills 247 dream answer generation (Sun et al., 2019) Logical Reasoning Commonsense Reasoning 118 semeval open vocabulary mathematical answer generation (Hopkins et al., 2019) Commonsense Reasoning Mathematics 1385 anli r1 entailment (Williams et al., 2022) Textual Entailment Commonsense Reasoning Causal Reasoning Table 6: Dev set for checkpoint selection scoring suite (Table 10). Chains are evaluated using facebook/roscoe-512-roberta-base sentence embedding model. Evaluation results are detailed in Table 10. We found that the chain quality varies between models, in particular some reasoning as- pects correlate with chain length as seen in Table 11. Similar to (Chung et al., 2022), we noticed that non- finetuned models (i.e. OPT-1.3B and OPT-13B) tend to produce long chains of reasoning, often repeating themselves, which significantly affects the quality of the chains and final scores (Figure 9). Below we explore the differences between models’ outputs under four perspectives: semantic align- ment, semantic similarity, logical inference and language coherence. # C.1 Semantic Alignment Despite the fact that model 13B OPT-CoT on average outperforms other models in almost all semantic alignment scores (Faithfulness-Step, Faithfulness-Token, and Info-Step, see Table 10), there is no common pattern across tasks (Fig 10). The performance change between finetuned mod- els and corresponding pretrained version are sig- nificant4 on half of the tasks (11 tasks out of 20 for Faithfulness-* scores, and 9 out of 20 for Info- Step). 4Significance is determined using T-test comparison, where p-value is below 0.05. Repetition-Token score variations exhibit differ- ent behavior. Half of the tasks have higher num- ber of repetitions between reasoning steps for pre- trained models, with OPT-FT models generally out- performing others (all performance improvements are significant). Generations produced by these models tend to be shorter in terms of the number of steps (Figure 9), so they contain less repetitions, but also less semantic overlap with the context, thus in general having lower faithfulness and informa- tiveness. Some examples reflecting this behavior are provided in Table 12. Scores are mostly aligned across Templates (Fig- ure 11), except Template 5, that stands out in hav- ing less aligned scores with respect to the context, but also more self-consistent across the task. This is the only template that did not have any expla- nation in its prompt. Manual review showed that despite CoT-finetuning, OPT-COT models tend to produce 1-step answer-only generations (see exam- ple in the Table 12, and Figure 9 for chains’ length distribution), thus overfitting to the template rather than learning from finetuning. In summary, ROSCOE-SA is able to identify aligned information, but it does not guarantee high- quality output. It will favor model with short ex- planations and high semantic overlap with the ref- erence. We found that often OPT-FT-1.3B sim- ply repeats one sentence from the input, instead Category Datasets Vocabulary Overlaps 0% to 10% bigbench repeat copy logic (Srivastava et al., 2022) babi t1 single supporting fact answer generation (Weston et al., 2015) semeval closed vocabulary math answer generation (Hopkins et al., 2019) semeval geometric math answer generation (Hopkins et al., 2019) tomqa find location easy clean (Nematzadeh et al., 2018) plausible result generation (Weir et al., 2020) argument stance classification (Kobbe et al., 2020) argument consequence classification (Kobbe et al., 2020) mmmlu answer generation formal logic (Hendrycks et al., 2021a) bard analogical reasoning causation (Fulda et al., 2017) 1.59% 0.38% 7.90% 5.84% 0.94% 3.72% 6.04% 6.11% 5.35% 0.45% 10% to 30% commongen sentence generation (Lin et al., 2020) tellmewhy answer generation (Lal et al., 2021) cb entailment (Wang et al., 2019) 29.31% 28.05% 20.97% over 30% piqa answer generation (Bisk et al., 2020) rocstories correct answer generation (Mostafazadeh et al., 2016) sciq answer generation (Welbl et al., 2017) openbookqa question answering (Mihaylov et al., 2018) glue entailment classification (Wang et al., 2018) anli r2 entailment (Williams et al., 2022) anli r3 entailment (Williams et al., 2022) 42.51% 57.45% 32.54% 48.2% 55.19% 43.37% 53.13% Table 7: Vocabulary overlap. Dissimilarity has been measured between training data (in Table 4) and evaluation data (in Table 5). Datasets Random score GPT-3 Davinci score Boolean Physical Entailment Tree Event Semantic Spatial 34.50% 49.08% 50.88% 54.08% 49.80% 31.80% 50.00% 54.41% 55.89% 49.30% Table 8: Classification accuracy by GPT-3 davinci-engine on the Curriculum benchmark. of producing reasoning, and thus will get high- est ROSCOE-SA scores on these chains, while other models that produce some sort of reasoning will be punished. # C.2 Semantic Similarity answer given s given single supporting fact, po- tentially amongst a set of other irrelevant facts. Manual review showed that although in this task finetuned models tend to produce answers that are more consistent, they often fail to select the fact that is relevant to the question asked (see "Spatial Reasoning" example in Table 12. Semantic similarity scores support previous conclu- sions: models, finetuned on final answers (OPT-FT) exhibit lower similarity with respect to the base- line and CoT-finetuned models, while having less repetitions (Figure 12). Again, we attribute that to the fact that these models produce short chains that lack detailed reasoning steps. # C.4 Language Coherence Despite the variations in the values, Perplexity-* score changes between models are mostly insignif- icant (15 out of 20 tasks, see Figure 14). Man- ual review showed that all models produce mostly grammatically correct content. # C.3 Logical Inference In general, finetuned models are more self- and source-consistent than respective baselines (Fig- ure 13, significantly outperforming nonfinetuned models on 14 out of 20 tasks. We further looked into the task 083, which is a task to find a right # D Licenses # D.1 Data in ALERT • task62: Apache 2.0 • task697: MIT The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have? The answer is 29 apples. The cafeteria started with 23 apples and bought 6 more, for a total of 23 + 6 = «23+6=29»29 apples . Select the best translation into predicate logic. David teaches Chris. (c: Chris; d: David; Txy: x teaches y) (A)Tdc;(B)Tcd;(C)Tcc;(D)dTc. The answer is (B) Tcd. In predicate logic, the predicate (in this case, "T") is written before the subject and object of the sentence. Since David (d) is the teacher and Chris (c) is the student, the correct translation is Tcd, which reads as "David teaches Chris." Isabella entered the hall. Olivia entered the hall. The apple is in the blue_treasure_chest. Olivia exited the hall. Isabella moved the apple to the green_basket. Question: Where does Isabella think that Olivia searches for the apple? The answer is It is impossible for me to answer this question as I have no information about the thoughts or actions of Isabella or Olivia. Additionally, I do not have access to browse any information beyond my training data, which ends in 2021 . Table 9: Examples from tasks that require reasoning skills and generated outputs from ChatGPT. The faild outputs are highlighted in red. OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B OPT 13B OPT-FT 13B OPT-CoT 13B ROSCOE-SA Faithfulness-Step Faithfulness-Token Info-Step Repetition-Token 0.863 0.936 0.857 0.618 0.841 0.921 0.829 0.920 0.862 0.938 0.854 0.683 0.863 0.936 0.858 0.582 0.858 0.923 0.846 0.857 0.870 0.940 0.861 0.701 ROSCOE-SS Info-Chain Repetition-Step 0.925 0.627 0.909 0.923 0.920 0.692 0.926 0.591 0.916 0.859 0.925 0.708 ROSCOE-LI Source Consistency Self-Consistency 0.550 0.848 0.604 0.953 0.573 0.875 0.584 0.863 0.617 0.944 0.598 0.890 ROSCOE-LS Perplexity-Step Perplexity-Chain Grammar 0.016 0.022 0.725 0.006 0.006 0.744 0.015 0.020 0.666 0.010 0.016 0.688 0.006 0.006 0.705 0.009 0.013 0.640 Table 10: ROSCOE evaluation results averaged across templates. Each metric is bounded within [0, 1], where 1 indicates the perfect score and 0 corresponds to failure. Values corresponding to the best performing model are bolded, second best are underscored. • task393: MIT • task332: Please refer to: https://github.c om/StonyBrookNLP/tellmewhy • task1386: CC BY-NC 4.0 • task083: CC BY 3.0 • task1387: CC BY-NC 4.0 • task1388: CC BY-SA 3.0 • task151: Please refer to: https://github.c om/kayburns/tom-qa-dataset • task080: AFL 3.0 • task1152: Apache 2.0 • task102: MIT • task513: Please refer to: https://github.c om/dwslab/StArCon • task591: CC BY-NC-3.0 • task1286: Apache 2.0 • task514: Please refer to: https://github.c om/dwslab/StArCon • task1344: CC BY 4.0 • task104: Please refer to: https://github.c om/allenai/semeval-2019-task-10#ter ms-and-conditions • task216: Please refer to: https://www.micr osoft.com/en-us/research/publicati on/a-corpus-and-cloze-evaluation-f or-deeper-understanding-of-commons ense-stories/ • task119: Please refer to: https://github.c om/allenai/semeval-2019-task-10#ter ms-and-conditions # D.2 Data in Dev set • task247: Dream dataset is intended for non- commercial research purpose only. https: Faithfulness-Step Faithfulness-Token Info-Step Repetition-Token Info-Chain Repetition-Step Source Consistency Self-Consistency Perplexity-Step Perplexity-Chain Grammar -0.101 0.039 0.054 -0.869 0.009 -0.867 -0.119 -0.553 0.000 0.369 0.013 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.960 0.000 0.000 Kendall’s τ score Kendall’s τ p-value Table 11: Kendall correlation between evaluation perspective and number of steps in chain across all generated reasoning chains. Strong correlations (|τ | > 0.4) are bolded. OPT 1.38 OPT-FT 1.38 OPT-CoT 1.38 pT 138 OPT-FT 138 OPT-CoT 138 Average across templates OO OOCCCONID ©1466 Om 40 04 | oe 0 oe oo Oeerrr Om 6 6 0 yA oO OoCooMM +6 + | o OOOO e | +o ooeeeee on 10? 10? OPT 1.38 OPT-FT 1.38 OPT-CoT 1.38 pT 138 OPT-FT 138 OPT-CoT 138 Average across templates OO OOCCCONID ©1466 Om 40 04 | oe 0 oe oo Oeerrr Om 6 6 0 yA oO OoCooMM +6 + | o OOOO e | +o ooeeeee on 10? 10? OPT-CoT 13B Template 1 ‘Template 2 Template 3 Template 4 ‘Template 5 LLL SOOO OEE 44 HOH OOOO EEOH Me @ Oe © 00000000 oO oooe + 10° 101 107 OPT-CoT 13B Template 1 ‘Template 2 Template 3 Template 4 ‘Template 5 LLL SOOO OEE 44 HOH OOOO EEOH Me @ Oe © 00000000 oO oooe + 10° 101 107 com/proofwriter/proofwriter-dataset- V2020.12.3.zip • StrategyQA: MIT. Downloaded from https: //storage.googleapis.com/ai2i/strate gyqa/data/strategyqa_dataset.zip. • ECQA: Literature and Wikipedia passages are shared under CC BY-SA 4.0 license. Mid- dle/High school exam passages are collected from RACE which comes with its own license. • GSM8K: MIT. Downloaded from https:// raw.githubusercontent.com/openai/g rade-school-math/master/grade_schoo l_math/data/train.jsonl. • AQUA-RAT: Apache License, Version 2.0. Downloaded from: https://raw.github usercontent.com/deepmind/AQuA/master /train.json Figure 9: Distribution of the steps’ number across all tasks and templates varying between models (top) and between templates for OPT-CoT 13B model. //github.com/nlpdata/dream. • ESNLI: please refer to https://github.com /OanaMariaCamburu/e-SNLI/commit/ba b0fa0212be9e5c6737da70c639a596f882e9 31. Downloaded from: https://raw.gith ubusercontent.com/OanaMariaCamburu/e -SNLI/master/dataset/esnli_train_1.c sv • task118: Please refer to: https://github.c om/allenai/semeval-2019-task-10#ter ms-and-conditions • MATH: MIT. Downloaded from: https:// people.eecs.berkeley.edu/~hendrycks/ MATH.tar • task 1385: CC BY-NC 4.0 # D.3 Data in Training set • ProofWriter: CC BY. Downloaded from http s://aristo-data-public.s3.amazonaws. • CoS-E: BSD-3-Clause license. Downloaded from: https://raw.githubusercontent. com/salesforce/cos-e/master/data/v1. 11/cose_train_v1.11_processed.jsonl • WinoWhy: MIT. Downloaded from: https: //raw.githubusercontent.com/HKUST-Kn owComp/WinoWhy/master/winowhy.json # E More Details about Model Training We finetune our 1.3B models on 32 V100s with batch size 8 on each GPU with totally 38 hours and 21 minutes. We finetune our 13B models on 128 V100s with batch size 4 on each GPU with totally 13 hours and 26 minutes. Following OPT-IML (Iyer et al., 2022), we use Fully Sharded Data Parallel (Artetxe et al., 2021) and the Megatron-LM Tensor Parallelism (Shoeybi et al., 2019). We inherit most model hyper-parameters for each model scale following OPT-IML. We pack our training examples into se- quences of length 2048, left-truncating examples that overflow. We use Adam (Kingma and Ba, 2014) with 32-bit state with (β1, β2) = (0.9, 0.95), linearly warming up the learning rate for 60 steps to the maximum, followed by linearly decaying it to 0. r N o —— baseline (5) OPT 1.38 Pr w uo ©) OPT-FT 1.38 Gl ~OPT-CoT 1.3B 1.10 Mmm OPT 13B 2 mm OPT-FT 138 H 1.05 Mm OPT-CoT 13B a o g 100 3 J L & 8 TTT 0.80 062 080 083 102 104 1152 2119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 Task (5) OPT 1.38 Pr w uo ©) OPT-FT 1.38 Gl ~OPT-CoT 1.3B 1.10 Mmm OPT 13B 2 mm OPT-FT 138 H 1.05 Mm OPT-CoT 13B a o 100 3 L & 8 TTT 0.80 062 080 083 102 104 1152 2119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 Task 1.20 —— baseline “ ©) oPT 1.38 ° ©) OPT-FT 1.38 GE OPT-CoT 1.38 - 1.10 Gm OPT 138 g Gm OPT-FT 138 © 1.05 MME OPT-CoT 138 D w o 2 E=] & 1,00 = 1 [ m1) | be i = eT, = " 0.95 0.90 0.85 0.80 062 080 083 102 104 «61152. 119) s-1286) Ss: 1344) 1386) «=—:1387') -:1388~—S «151 216 332 393 513 514 591 697 Task 1.20 —— baseline 115 5 0PT 1.38 ©) OPT-FT 1.38 GN OPT-CoT 1.38 1.10 Gm OPT 138 @@ OPT-FT 138 a 1.05 @™™ OPT-CoT 138 o 4 va) 1.00 s 7 — =” 0 7 Cc = 0.95 0.90 0.85 0.80 062 «#080 4«6(083)«=6 102,-—'s«sdH-ssa1152, ss 119° s«1286 «1344 «s«1386 «1387: «1388 «= 151s 216s 332,393) 513s 514s 591 —s«6 97 Task — baseline 10 5 0PT 1.38 © OPT-FT 1.38 Gs OPT-CoT 1.38 mm OPT 138 5 ° Gm OPT-FT 13B x Mmm OPT-CoT 138 oO un c 5° — +S FZ 2 0 1.20 —— baseline “ ©) oPT 1.38 ° ©) OPT-FT 1.38 GE OPT-CoT 1.38 - 1.10 Gm OPT 138 g Gm OPT-FT 138 © 1.05 MME OPT-CoT 138 D w o & 2 £ E=] & 1,00 = 1 [ m1) | be i = eT, = " 0.95 0.90 0.85 0.80 062 080 083 102 104 «61152. 119) s-1286) Ss: 1344) 1386) «=—:1387') -:1388~—S «151 216 332 393 513 514 591 697 Task 1.20 —— baseline 115 5 0PT 1.38 ©) OPT-FT 1.38 GN OPT-CoT 1.38 1.10 Gm OPT 138 @@ OPT-FT 138 a 1.05 @™™ OPT-CoT 138 o 4 va) 1.00 s 7 — =” 0 7 Cc = 0.95 0.90 0.85 0.80 062 «#080 4«6(083)«=6 102,-—'s«sdH-ssa1152, ss 119° s«1286 «1344 «s«1386 «1387: «1388 «= 151s 216s 332,393) 513s 514s 591 —s«6 97 Task — baseline 10 5 0PT 1.38 © OPT-FT 1.38 Gs OPT-CoT 1.38 mm OPT 138 5 ° Gm OPT-FT 13B x Mmm OPT-CoT 138 oO un c 5° — +S FZ 2 0 062 O80 083 102 104 1152 119 1286 1344 1386 1387 1386 151 216 332 393 513 514 591 697 Task Figure 10: Normalized ROSCOE-SA scores per task, averaged across templates. Scores are normalised by their mean value across OPT 1.3B model’s generations. baseline Template 1 Template 2 Template 3 Template 4 Template 5 Faithfulness-Token 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task Faithfulness-Token 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline Template 1 Template 2 Template 3 Template 4 Template 5 Info-Chain 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline Template 1 Template 2 Template 3 Template 4 Template 5 Self-Consistency 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline Template 1 Template 2 Template 3 Template 4 Template 5 Grammar 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline Template 1 Template 2 Template 3 Template 4 Template 5 Info-Chain 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline Template 1 Template 2 Template 3 Template 4 Template 5 Self-Consistency 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline Template 1 Template 2 Template 3 Template 4 Template 5 Grammar 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task Figure 11: Selected scores per task for OPT-CoT 13B model. Scores are normalised by their mean value across Template 1 generations. baseline _ OPT 1.38 OPT-FT 1.38 OPT-CoT 1.38 1.10 OPT 13B OPT-FT 138 c 1.05 OPT-CoT 13B o S 100 J — — ao : -_! g re ee We ey — = 0.95 0.90 0.85 0.80 062 080 083 102 104 «1152, 1119) -:1286)S «1344 «1386 0=—:1387) 1388 )=Sss-151 216 332 393 513 514 591 697 Task baseline _ OPT 1.38 OPT-FT 1.38 OPT-CoT 1.38 1.10 OPT 13B OPT-FT 138 c 1.05 OPT-CoT 13B o S 100 J — — ao : -_! g re ee We ey — = 0.95 0.90 0.85 0.80 062 080 083 102 104 «1152, 1119) -:1286)S «1344 «1386 0=—:1387) 1388 )=Sss-151 216 332 393 513 514 591 697 Task baseline OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B OPT 13B OPT-FT 13B OPT-CoT 13B Repetition-Step 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B OPT 13B OPT-FT 13B OPT-CoT 13B Repetition-Step 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task Figure 12: Normalized ROSCOE-SS scores per task, averaged across templates. Scores are normalised by their mean value across OPT 1.3B model’s generations. 12 baseline OPT 1.3B OPT-FT 1.3B 10 OPT-CoT 1.3B > OPT 13B g OPT-FT 13B £ 8 OPT-CoT 138 a7] Cc GS 6 (7) 5 a 4 va) 2 0 062 O80 083 102 104 1152 4119 1286 1344 1386 1387 #41388 #%4I5l 216 332 393 513 514 591 697 Task 12 baseline OPT 1.3B OPT-FT 1.3B 10 OPT-CoT 1.3B > OPT 13B g OPT-FT 13B £ 8 OPT-CoT 138 a7] Cc GS 6 (7) 5 a 4 va) 2 0 062 O80 083 102 104 1152 4119 1286 1344 1386 1387 #41388 #%4I5l 216 332 393 513 514 591 697 Task baseline 25 OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B 20 OPT 13B ra OPT-FT 13B S OPT-CoT 13B ~ 215 vn c fo) Q gt . 7 7 r 7 1 . hn 7 ; ; | ; 0.0 32 062 080 083 102 104 1152 4119 1286 1344 1386 1387 1388 151 216 3 393 513 «514. 591—Ss«697 Task baseline 25 OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B 20 OPT 13B ra OPT-FT 13B S OPT-CoT 13B ~ 215 vn c fo) Q gt . 7 7 r 7 1 . hn 7 ; ; | ; 0.0 32 062 080 083 102 104 1152 4119 1286 1344 1386 1387 1388 151 216 3 393 513 «514. 591—Ss«697 Task Figure 13: Normalized ROSCOE-LI scores per task, averaged across templates. Scores are normalised by their mean value across OPT 1.3B model’s generations. baseline 1.75 OPT 1.3B OPT-FT 1.3B PT-CoT 1. 150 OPT-CoT 1.3B OPT 13B OPT-FT 13B OPT-CoT 13B ie N uw Perplexity-Step 3 8 S u& So ° N i) PIPE 0.00 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline 2.0 OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B OPT 13B OPT-FT 13B Cc ‘= 15 g£ OPT-CoT 13B 9 2 3 1.0 a | | | & | iy iW | 0.5 | | | 0.0 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task OPT 1.38 OPT-FT 1.38 2.0 OPT-CoT 1.38 OPT 138 OPT-FT 138 415 OPT-CoT 138 1 £ £ § 10 : | | | | | | 0.0 062 080 083 102 104 1152 119 1286 1344 1386 1387 41388 151 216 332 393 513 514 591 697 Task baseline 1.75 OPT 1.3B OPT-FT 1.3B PT-CoT 1. 150 OPT-CoT 1.3B OPT 13B OPT-FT 13B OPT-CoT 13B ie N uw Perplexity-Step 3 8 S u& So ° N i) PIPE 0.00 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task baseline 2.0 OPT 1.3B OPT-FT 1.3B OPT-CoT 1.3B OPT 13B OPT-FT 13B Cc ‘= 15 g£ OPT-CoT 13B 9 2 3 1.0 a | | | & | iy iW | 0.5 | | | 0.0 062 080 083 102 104 1152 119 1286 1344 1386 1387 1388 151 216 332 393 513 514 591 697 Task OPT 1.38 OPT-FT 1.38 2.0 OPT-CoT 1.38 OPT 138 OPT-FT 138 415 OPT-CoT 138 1 £ £ § 10 : | | | | | | 0.0 062 080 083 102 104 1152 119 1286 1344 1386 1387 41388 151 216 332 393 513 514 591 697 Task Figure 14: Normalized ROSCOE-LC scores per task, averaged across templates. Scores are normalised by their mean value across OPT 1.3B model’s generations. REASONING SKILL: Logistic Reasoning, Mathematics PROMPT: Please give a short explanation after the answer. Input: Identify the conclusion of the following argument. It is hard not to verify in our peers the same weakened intelligence due to emotions that we observe in our everyday patients. The arrogance of our consciousness, which in general, belongs to the strongest defense mechanisms, blocks the unconscious complexes. Because of this, it is difficult to convince people of the unconscious, and in turn to teach them what their conscious knowledge contradicts. (Sigmund Freud, The Origin and Development of Psychoanalysis) (A)It is hard not to verify in our peers the same weakened intelligence due to emotions that we observe in our everyday patients. (B)The arrogance of our consciousness, which in general, belongs to the strongest defense mechanisms, blocks the unconscious complexes. (C)Because of this, it is difficult to convince people of the unconscious, and in turn to teach them what their conscious knowledge contradicts. (D)It is difficult to convince people of the unconscious, and in turn to teach them what their conscious knowledge contradicts. Let’s think step by step. Output: The answer is D because Because of the reasons specified in the argument, it is difficult to convince people of the unconscious, and in turn to teach them what their conscious knowledge contradicts. Input: Select the best translation into predicate logic: No people drive on Mars. (Dx: x drives on Mars) (A) ∼P d (B) (∀x)(P x ∨ ∼Dx) (C) (∀x)(P x ⊃ ∼Dx) (D) ∼Dp Let’s think step by step. Output: The answer is C because Answer C means for everything, if that thing is a person, it doesn’t drive on Mars. So that’s the correct translation. Input: Select the best translation into predicate logic. David teaches Chris. (c: Chris; d: David; Txy: x teaches y) (A)Tdc (B)Tcd (C)Tcc (D)dTc Let’s think step by step. Output: The answer is A because David teaches Chris, so in the relation Txy x should be ’d’ for davis and y should be ’c’ for Chris. Input: Which of the given formulas of PL is the best symbolization of the following sentence? Either England’s importing beef is not a necessary condition for France’s subsidizing agriculture, or China promotes human rights if South Africa supplies diamonds. (A) (∼F ⊃ E) ∨ (C ≡ ∼S) (B) (∼E ⊃ F ) ∨ (C ⊃ S) (C) (∼F ⊃ E) ∨ (C ≡ S) (D) ∼(F ⊃ E) ∨ (S ⊃ C) Let’s think step by step. Output: The answer is D because When not defined in the question, entities, relationships or statements are shown with their first letter. In this example ’France subsidizing agriculture’ is shown with F for simplicity. The correct answer is D, because it uses the ’or’ operator between the two ’if’ clauses. Input: Select the best translation into predicate logic. Kevin is introduced to José by Wilma. (j: José; k: Kevin; w: Wilma; Ixyz: x introduces y to z) (A)Iwjk (B)Ijkw (C)Ikjw (D)Iwkj Let’s think step by step. Output: REFERENCE: D OPT 1.3B: The answer is A because all statements need to be presented with an argument. OPT-FT 1.3B: The answer is B OPT-CoT 1.3B: The answer is A because Using the ’or’ operator between the statements, we have : Kevin is introduced to José, because of its ’e’ factor in the equation. Wilma is introduced to Kevin because of its ’j’ factor in the equation. José is introduced to Wilma because of its ’y’ factor in the equation. In both cases, Wilma accepts ’x’ and ’y’. OPT 13B: The answer is A because introducing a person to another person is the action of introducing. It is possible that Kevin has been introduced to Wilma but not Jose. OPT-FT 13B: The answer is A because when w is introduced, it says ’Wilma introduced Kevin to José’ OPT-CoT 13B: The answer is D because the correct term is ’introduces’, the relation is ’j: kevin and w: wilma to k: x’, it is an ’and’ relation. Using the operator ’and’ allows us to choose the greatest of the 5 possibilities. REASONING SKILL: Commonsense Reasoning PROMPT: Please give a short explanation after the answer. Input: Deserts are in extremely dry environments, so liquids will naturally be (A) rainbow (B) plentiful (C) meager (D) talented Let’s think step by step. Output: The answer is C because This is a good example and the output correctly answers the question. Input: Dairy has things in it that would make humans sick, so in order for dairy to be edible, this process has to take place (A) mixing (B) boiling (C) freezing (D) pasteurized Let’s think step by step. Output: The answer is D because in order for dairy to be edible, this process has to take place pasteurized. So, the correct answer is "D". Input: Digestion is when stomach acid breaks down (A) a pizza (B) a house (C) a rock (D) a car Let’s think step by step. Output: The answer is A because Digestion is when stomach acid breaks down a food and only option A is a food. So, this example is correct. Input: With a ruler I can measure (A) feelings (B) love (C) air (D) a phone Let’s think step by step. Output: REFERENCE: D OPT 1.3B: A is a feeling, and all feelings come from feelings (A). Therefore, feelings are products of emotions (A). Therefore, emotions are created by emotions (A). Therefore, feelings and emotions are directly related (A). Therefore, emotions are created by emotions (A)... [repeats 249 times] OPT-FT 1.3B: A because feelings and love are measurements and air is a phone OPT-CoT 1.3B: The answer is D because With a ruler I can measure an object or range of objects and options are all to do with measuring. So, this example is correct. OPT 13B: The answer is B because With a ruler I can measure a length and only options B and D are in front of me. So, the answer is B. OPT-FT 13B: The answer is D because a phone is an object OPT-CoT 13B: The answer is A because Answer: Measure feelings With a ruler I can measure. REASONING SKILL: Casual Reasoning, Textual entailment PROMPT: Please give a short explanation after the answer. Input: Premise: If you can dream it, you can achieve it — unless you’re a goose trying to play a very human game of rugby. In the video above, one bold bird took a chance when it ran onto a rugby field mid-play. Things got dicey when it got into a tussle with another player, but it shook it off and kept right on running. After the play ended, the players escorted the feisty goose off the pitch. It was a risky move, but the crowd chanting its name was well worth it. Video credit: Storyful / Nathan Swarbrick @swazza1990 <sep> Hypothesis: The crowd believed they knew the name of the goose running on the field. Let’s think step by step. Output: The answer is Entailment because This is a good example, the hypothesis sentence entails the given premise. Because the crowd was chanting its name, the crowd must have believed they knew the goose’s name. Input: Premise: Notley hopeful attacks on women politicians will fade in coming year After a politically nasty year that saw women politicians face a barrage of attacks on social media and angry demonstrators shouting to have them put behind bars, Premier Rachel Notley is optimistic there will be a return to civil discourse. In a year-end interview with CBC News, Notley reflected on 2016, a year that saw hateful social-media attacks against MLA Sandra Jansen, and chants of “Lock her up” directed at the premier at an anti-carbon tax rally in Edmonton. <sep> Hypothesis: Notley reflected on the chants of "lock her up" from previous to the year 2016. Let’s think step by step. Output: The answer is Contradiction because The Premise states Notley reflected on the chants from 2016, not before 2016. In this example hypothesis sentence contradicts the given premise. Input: Premise: Mazda Sales (Thailand), a unit of Japanese carmaker Mazda Motor Corp, remains bullish about its sales prospects this year despite falling figures in the first six months, the Bangkok Post reported, citing its President Hidesuke Takesue. (bit.ly/1gr7HMd) —- NOTE: Reuters has not verified this story and does not vouch for its accuracy. (Bangkok Newsroom; Editing by Prateek Chatterjee) <sep> Hypothesis: Mazda Sales will be fired next week Let’s think step by step. Output: The answer is Neutral because In this example the hypothesis can’t be proven one way or the other based on the context. It’s set in the future and no one knows the future. So, hypothesis sentence is neutral with respect to a given premise. Input: Premise: How to clear nasal congestion quickly<br>Gently blow your nose. Perhaps the easiest and quickest way to reduce nasal congestion is to simply blow your nose into a soft tissue. Unfortunately, it’s not always possible to completely relieve congestion by merely blowing, but it’s always a good starting point. <sep> Hypothesis: strike a pose to fix your nose Let’s think step by step. Output: REFERENCE: Contradiction OPT 1.3B: The answer is Modified Contradiction because In this example the hypothesis sentence suggests the method is "Do not hit your head." In fact, that’s the phrase a person who is rolling around on the ground, or who has had their head hit a hard surface while trying to get a good sleeper on the sheets should try. Why is this? A head-on collision will ... [continues to hallucinate for 23 steps] OPT-FT 1.3B: Answer: Blow your nose into a soft tissue. OPT-CoT 1.3B: The answer is Contradiction because The hypothesis states that Nastai will solve his and nasal congestion only by blowing into his nose, but that’s not necessarily true, because he could have blown into his nose and caused irritation as well. OPT 13B: The answer is Yes because The answer is Yes. All the above information about clearing the nose is proven by the given premise, but if you still don’t know the answer, then we suggest you go here and click on "How to clear your nose naturally" page. OPT-FT 13B: The answer: contradiction OPT-CoT 13B: The answer is contradiction because One cannot blow their nose if they have struck a pose. REASONING SKILL: Analogical Reasoning PROMPT: Please give a short explanation after the answer. Input: throw : fly. aspire : ? Let’s think step by step. Output: The answer is attain because Fly is a causation of throw. Hence, the inferred analogy being causation, attain is the causation of aspire. Input: listen : hear. drop : ? Let’s think step by step. Output: The answer is fall because Hear is a causation of listen. Hence, the inferred analogy being causation, the causation of drop is fall. Input: hit : shatter. nourish : ? Let’s think step by step. Output: The answer is grow because Shatter is a causation of hit. Hence, the inferred analogy being causation, the causation of nourish is grow. Input: throw : fly. ignite : ? Let’s think step by step. Output: REFERENCE: burn OPT 1.3B: The answer is move because fly is a causation of ignite. Hence, the inferred analogy being causation, the causation of move is fly. OPT-FT 1.3B: The answer is throw OPT-CoT 1.3B: The answer is ignite because Fire is a causation of throw. Hence, the inferred analogy being causation, the causation of ignite is fly. OPT 13B: The answer is evaporate because Fly is a causation of throw. Hence, the inferred analogy being causation, the causation of evaporate is ignite. OPT-FT 13B: The answer is fly because Ignite is a causation of throw OPT-CoT 13B: The answer is grow because Throw is a causation of grow. REASONING SKILL: Commonsense reasoning, Spatial Reasoning PROMPT: Please give a short explanation after the answer. Input: How do you remove keys from a computer keyboard for cleaning? Let’s think step by step. Output: The answer is Place the tip of a knife under the corner of a key and gently twist to pop it off. because The process of removing keys from a keyboard for cleaning is descriptive and logical. Input: How can you dry wet replacement computer keyboard keys? Let’s think step by step. Output: The answer is by arranging paper towels on the counter and evenly spacing out each key to dry, face side up, on top of them. because The steps involved in the process of drying wet replacement keyboard keys are logical. Input: To coat small plastic objects like replacement keyboard keys with soap Let’s think step by step. Output: The answer is place them, water and liquid dishsoap in a sealed container. Shake vigorously until the container is completely full of foam. because The process of coating small plastic objects like replacement keys is descriptive and logical. Input: How do you cut gnocchi without a knife? Let’s think step by step. Output: The answer is Press the edge of a spoon down into the dough to cut it. because The answer is quite detailed about the method to cut gnocchi when knife is not available. Input: How do you taste something? Let’s think step by step. Output: The answer is Place it in your mouth to taste. because To taste something one has to keep it in contact with the tongue. Hence it is logical to put it in the mouth to taste. Input: How do you wear a bracelet? Let’s think step by step. Output: The answer is Put it on around your wrist. because Bracelet is worn around wrists. Hence it is correct answer. Input: To find an easy way to complete levels on a video game, Let’s think step by step. Output: REFERENCE: look up cheat codes to make the rules of the game different or null. OPT 1.3B: The answer is Enter key without pressing. because How to find the perfect way to complete levels on a video game is logical and descriptive. OPT-FT 1.3B: It tells you the easiest way to get all the coins and medals and the fastest way to get through the level. OPT-CoT 1.3B: The answer is play the game. because If you play a game to finish the levels then you can call it a game. OPT 13B: The answer is Complete the level as fast as possible to get a high score, by jumping through the stage as quickly as possible. because The answer is explicit and very clear that how a user can complete levels on a video game with just a hint. OPT-FT 13B: The answer is try harder or use a guide, because The process of finding an easy way to complete levels on a video game is descriptive and logical. OPT-CoT 13B: The answer is YouTube to find out how to get past a level. because YouTube is used to find out ways to complete a game easily. REASONING SKILL: Spatial Reasoning PROMPT: Instructions: You will be given a passage consisting of set of facts and a question as input. The task is to answer a question of form ’Where is <person_name>?’ using one of the given facts to determine the latest location of the person. Answer should be a word/phrase describing the location from the supporting fact. Avoid answers that are incomplete or incorrect. Positive Examples: Input: Passage: Mary moved to the bathroom. John went to the hallway. Question: Where is Mary? Output: bathroom Input: Passage: Mary moved to the bathroom. John went to the hallway. Daniel went back to the hallway. Sandra moved to the garden. Question: Where is Daniel? Output: hallway Input: Passage: Mary moved to the bathroom. John went to the hallway. Daniel went back to the hallway. Sandra moved to the garden. John moved to the office. Sandra journeyed to the bathroom. Question: Where is Daniel? Output: hallway Input: Passage: John moved to the hallway. Mary travelled to the hallway. Sandra went to the bedroom. Sandra went back to the hallway. Question: Where is Mary? Output: REFERENCE: hallway OPT 1.3B: bathroom OPT-FT 1.3B: hallway OPT-CoT 1.3B: hallway OPT 13B: bathroom OPT-FT 13B: bathroom OPT-CoT 13B: hallway Table 12: Examples from tasks that require different reasoning skills and generated outputs. The failed outputs are highlighted in red. Outputs that are different from the reference, but can be valid because the question is ambiguous are highlighted in blue. All except the one are examples generated using prompt Template 4, last example used Template 5.
Title: An Efficient COarse-to-fiNE Alignment Framework @ Ego4D Natural Language Queries Challenge 2022: Summary: This technical report describes the CONE approach for Ego4D Natural Language Queries (NLQ) Challenge in ECCV 2022. We leverage our model CONE, an efficient window-centric COarse-to-fiNE alignment framework. Specifically, CONE dynamically slices the long video into candidate windows via a sliding window approach. Centering at windows, CONE (1) learns the inter-window (coarse-grained) semantic variance through contrastive learning and speeds up inference by pre-filtering the candidate windows relevant to the NL query, and (2) conducts intra-window (fine-grained) candidate moments ranking utilizing the powerful multi-modal alignment ability of the contrastive vision-text pre-trained model EgoVLP. On the blind test set, CONE achieves 15.26 and 9.24 for R1@IoU=0.3 and R1@IoU=0.5, respectively. # An Efficient COarse-to-fiNE Alignment Framework @ Ego4D Natural Language Queries Challenge 2022 Zhijian Hou1*, Wanjun Zhong2∗, Lei Ji3, Difei Gao4, Kun Yan5 Wing-Kwong Chan1, Chong-Wah Ngo6, Zheng Shou4 and Nan Duan3 1 City University of Hong Kong 2 Sun Yat-sen University 3 Microsoft Research Asia 6 Singapore Management University 5 Beihang University {zjhou3-c@my., wkchan@}cityu.edu.hk; zhongwj25@mail2.sysu.edu.cn; {leiji, nanduan}@microsoft.com difei.gao@vipl.ict.ac.cn; kunyan@buaa.edu.cn; cwngo@smu.edu.sg; mike.zheng.shou@gmail.com 4 National University of Singapore # Abstract This technical report describes the CONE [2] approach for Ego4D Natural Language Queries (NLQ) Challenge in ECCV 2022. We leverage our model CONE, an ef- ficient window-centric COarse-to-fiNE alignment frame- work. Specifically, CONE dynamically slices the long video into candidate windows via a sliding window ap- proach. Centering at windows, CONE (1) learns the inter- window (coarse-grained) semantic variance through con- trastive learning and speeds up inference by pre-filtering the candidate windows relevant to the NL query, and (2) conducts intra-window (fine-grained) candidate moments ranking utilizing the powerful multi-modal alignment abil- ity of the contrastive vision-text pre-trained model EgoVLP. On the blind test set, CONE achieves 15.26 and 9.24 for R1@IoU=0.3 and R1@IoU=0.5, respectively. entire long videos with variant lengths are hard to be mod- elled without decreasing the sampling rate, leading to high computational cost during inference; (2) a large number of moment candidates from long videos makes their precise multi-modal alignment with the NL query more challeng- ing. These issues result in information loss in both temporal aspect (i.e., fewer visible frames caused by down-sampling) and contextual aspect (i.e., weaker matching ability to the object and scene in each frame content, as it is perturbed by numerous frames). To address the challenges above, we leverage our model CONE, a window-centric coarse-to-fine alignment framework. Sec. 2 illustrates the detailed method infor- mation. Result analysis (Sec. 3.2) reveals the effectiveness of CONE, and we end the report by discussing other chal- lenges in first-person vision and temporal reasoning in the limitation analysis (Sec. 3.3). # 2. Methodology # 1. Introduction Ego4D [1] NLQ task aims to localize a temporal moment in a long first-person video according to a natural language (NL) question. It resembles the video temporal grounding task, since both share the same problem definition. How- ever, statistics show the ratio of groundtruth to video du- ration is much smaller in Ego4d-NLQ compared with cur- rent video grounding benchmarks. Specifically, Charades- STA and ActivityNet-Captions require the system to locate an 8s moment from a 30s video and a 36s moment from a 120s video on average, respectively. In contrast, the average groundtruth moment and video duration are 8 and 495 sec- onds in Ego4d-NLQ, making it a challenging “needle in the haystack” search problem. Thus, directly adopting the ex- isting methods for this task raises two major challenges: (1) We present the proposed CONE for long video temporal grounding. As the pipeline shown in Fig. 1, we first slice the long video into several fixed-length video windows us- ing sliding window approach and pre-filter the candidate windows to accelerate inference (Sec. 2.1). Centering at the windows, we make accurate multi-modal alignment in the coarse-to-fine manner. At the coarse-grained level, we con- duct inter-window contrastive learning (Sec. 2.2) to cap- ture inter-window semantic variance through training. At the fine-grained level, we generate candidate intra-window proposals with Moment-DETR [3] and rank the proposals with a fine-grained matching (Sec. 2.3) mechanism. # 2.1. Window-based Video Slicing and Pre-filtering Indicates equal contribution We first slice the entire video into several video win- dows via a sliding window approach. A sliding window with window length Lw is used to be slid on the entire 1 Input Video NL Query: What color is the cloth I picked on the floor? i Scgre: 0.011 Score: 0.12. Output — 0 o——o P' Score: 0.022 Score: 0.932 Figure 1. An overview of our coarse-to-fine framework CONE. CONE first slices the video with sliding window approach and ac- celerates inference with a pre-filtering mechanism (Sec. 2.1). At the coarse-grained level, it enhances training with inter-window contrastive learning (Sec. 2.2). At the fine-grained level, it en- hances fine-grained multi-modal alignment for accurate proposal ranking (Sec. 2.3). video to derive a set of Nw fixed-length video windows Wi = [vwb i is the start index of window i. Specifically, we slide the window by increasing wb with window stride Lw/2 to guarantee that each moment is covered by two windows. Then, we propose to pre-filter the candidate win- dows by a contrastive vision-language pre-trained model EgoVLP [4]. We adopt it to compute the video features V and the text features Q beforehand. V = [v1, v2, . . . , vLv ] Q = [q[CLS], q1, q2, . . . , qLq ] (1) where [CLS] is a special token at the beginning of text tokens. The multi-modal alignment score aj = vj · q[CLS] is computed via the efficient dot product between jth video feature and the text feature. And the window-level matching score Ai is the maximum score of all frames in window i: Ai = max([awb i +1, awb i +2, ..., awb i +Lw ]) (2) We rank all windows with Ai and select the top-k win- dows for inference. Thus, we reduce the number of candi- date windows from Nw to a constant k to guarantee a con- trollable computation cost and accelerate inference. # 2.2. Inter-window Contrastive Learning We conduct contrastive learning to help the model in dis- criminating the semantic difference between positive and negative windows. Directly adopting Moment-DETR for long video in our framework is impractical because it lacks the ability to identify relevant windows, which hinders the reliable ranking of inter-window proposals. Contrastive learning is a feasible way to solve this issue. In the scenario of temporal grounding, we expect the model to recognize the negative windows by giving lower confi- dence (saliency) scores to the proposals (frames) residing in the negative window: p+ > p− mean(S(W +, Q)) > max(S(W −, Q)) (3) where p(+/−) denotes the positive/negative proposal score. W + and W − denote the positive and negative window. S() is the saliency scoring function. Then, we design two-level contrastive losses: (1) proposal-level loss and (2) frame- level loss with a randomly sampled negative window. For the proposal-level contrastive loss (Lp), we formu- late it as a classification loss for predicting whether the win- dow is relevant to the NL query: Ly — SF log exp(pt) exp(p*) + exp(p- ) (4) For the frame-level loss Lf , we set the average saliency scores for frames located in the positive window is larger than the maximum saliency score of frames in the negative window over a margin δ: Lf = max(0, δ + max(S(W −, Q)) − mean(S(W +, Q)) (5) So the overall contrastive loss is Lc = Lp + Lf . For the positive window, we also add the moment localization loss with L1 and IoU loss as in Moment-DETR. # 2.3. Intra-window Fine-grained Ranking Moment-DETR exploits the self-attention mechanism to perform multi-modal fusion over the sequence of video and text features. However, with the increased length of video inputs, the fine-grained attention between each video frame and the text query will be weakened by many other per- turbed frames, resulting in contextual information loss. And the fine-grained content (e.g., object and scene) in each frame plays an essential role. To remedy this issue, we propose a novel ranking strat- egy to enhance the fine-grained multi-modal alignment with a matching score computed with a contrastive vision-text pre-trained model (described in Sec. 2.1). Specifically, we first pre-compute the features for video frames and text query with the contrastive pre-trained model as in Eq. (1). Visual Adapter. With a lightweight visual adapter on the top of EgoVLP, we adopt adapter-based tuning to adapt the 2 representations from the general contrastive model to the data distribution of the current downstream task. Our main idea is to add an additional bottleneck layer to learn the task-adaptive visual features and conduct residual-style blending with the original pre-trained fea- tures. The lightweight adapter complies with a 2-layer FFN followed by ReLU. The ith adapted visual feature is: ˆvi = Adapter(vi) + vi. Then, the proposal feature for the jth proposal is computed with the mean pooling of all the adapted video features in it: hj = Mean([ ˆvbj , . . . , ˆvej ]) For adapter training, we denote the positive proposal (with feature hpos) as the ground-truth one, and the neg- ative proposals are the other in the same batch. We follow the standard contrastive learning and use the NCE loss. La =- 1 exp( pos * F{CLS] 6 d 095 exp(hyy- dicisi) 6) pos Ranking Score Computation. Finally, we aim to con- duct fine-grained ranking for proposals in the window. For the jth proposal, the final proposal ranking score is fused with two components: (1) proposal scores generated from Moment-DETR and (2) fine-grained matching score mj computed with CLIP-based proposal feature: mj = hj · q[CLS]. The former models the correlation between propos- als by the Transformer-based architecture, while the latter focuses on fine-grained content matching between frames in the proposal and the text query. We perform min-max normalization for these two types of scores for a more sta- ble ranking. The final ranking score rj is the sum of two normalized scores: ˜pj = MinMax([p1, p2, ..., pNp ]), ˜mj = MinMax([m1, m2, ..., mNp ]) rj = ˜pj + ˜mj (7) where Np is the total number of candidate proposals. # 3. Experiments # 3.1. Implementation Details Visual, Textual and Token Features. We use EgoVLP [4] visual feature (every 16 frames, 1.87fps) and textual feature for all experiments. They are utilized in the vi- sual input of Moment-DETR, pre-filtering stage and fine- grained ranking stage. Moreover, we explore three different sources (i.e., EgoVLP, RoBERTa and CLIP) to extract tex- tual token feature. Training and Inference Details. All experiments are conducted on one P100 GPU. Following Moment- DETR [3], we set the hidden size d to 256, the layer number in encoder/decoder to 2, and number of moment queries to 3 5 for the transformer module. Parameter optimization is performed by AdamX. We set the learning rate to 1e-4 for Moment-DETR and 1e-5 for visual adapter, respectively. We set the batch size to 32 and adopt the early stopping strategy. We set the window length to 90 video features (48 seconds) and train it for 150 epochs lasting about 3 hours. We set the pre-filtering window number to 20 and use Non Maximum Suppression (NMS) with a threshold of 0.5 as post-processing during inference. # 3.2. Result Analysis Method Textual Token Feature R1@IoU= 0.5 0.3 VSLNet Moment-DETR CONE CONE CONE CONE CONE (+SW) EgoVLP EgoVLP EgoVLP RoBERTa CLIP Ensemble Ensemble 10.84 7.20 14.15 14.35 14.48 15.57 16.06 6.81 4.31 8.18 8.39 8.67 9.14 9.34 Table 1. Performance (Recall 1@IoU=θ) on the validation set. Method R1@IoU= 0.5 0.3 R5@IoU= 0.5 0.3 CONE 15.26 9.24 26.42 16.51 Table 2. Our final submission performance on the test set. Table 1 reports the performance comparison on the vali- dation set. Under the same setting, CONE outperforms the performance of Moment-DETR [3] and VSLNet [6] on both metrics by a noticeable margin. It shows the effectiveness of the introduced inter-window contrastive learning mecha- nism and fine-grained ranking strategy. Next, we study the effect on the token feature, which serves as the textual input of Moment-DETR. Better token features can result in more precise proposal boundary, more discriminative proposal scores, and finally, better perfor- mance. We empirically find that CLIP token feature works better than that of RoBERTa and EgoVLP. We speculate that the reason lies in that CLIP is pre-trained on multi-modal corpus instead of RoBERTa text-only corpus, and the CLIP image-text pair corpus is much larger than EgoVLP first- person video-text pair corpus. Then, we perform model ensemble on three CONE variants based on different token feature (i.e., EgoVLP, RoBERTa and CLIP) and the ensemble strategy also shows a performance gain. a | 209 s Example-A: Where was the chopsticks before I picked it up? Score: 1.93 Rank 2n Example-B: Where is the kettle before I picked it GT 0s -————————+ 17s Score: 1.79 Rank 3rd Figure 2. Two failure cases. We show both groundtruth moment and our prediction moments. Finally, we borrow the multi-scale variable-length slid- ing window sampling strategy (SW) [5] as a data augmen- tation trick. Previously, CONE slices the video into a se- quence of pre-defined windows, and chooses a positive and negative window during training. In the additional SW ver- sion, the positive window has relatively random duration and start timestamp controlled by some hyperparameters. action. Secondly, temporal reasoning requires the system to understand more about the relation and causality of contin- uous actions or events (shown by Example-B). This ability is key to this query template “Where is object X before / after event Y?”. # References For the final submission, we use our best version on i.e., the ensemble of three CONE vari- the validation set. ants with the additional SW training strategy. As shown in Table 2, our submission achieves 15.26 and 9.24 for R1@IoU=0.3 and 0.5, respectively. [1] Kristen Grauman, Andrew Westbury, Eugene Byrne, Zachary Chavis, Antonino Furnari, Rohit Girdhar, Jackson Hamburger, Hao Jiang, Miao Liu, Xingyu Liu, et al. Ego4d: Around the world in 3,000 hours of egocentric video. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 18995–19012, 2022. 1 # 3.3. Limitation Analysis Figure 2 shows two failure examples contrasting the groundtruth and predicted moments. Both queries fail to rank in the first position but successfully rank at or be- fore the fifth. We choose them because those queries are most likely to rank in the first position in future work. In Example-A, CONE locates a moment when I am putting a peeler back. Although the chopsticks are visible on the chopping board, I am not interacting with them. In Example-B, CONE locates a moment when I am lifting the kettle from the sink, because the kettle has been filled with water from the tap. Although the kettle is the interaction object, I am not picking it up. In contrast, the groundtruth shows a moment when I enter the kitchen and then pick up the kettle from the table. CONE deals with the long video length challenge of the NLQ task. Nevertheless, we speculate that other chal- lenges also exist in first-person vision and temporal reason- ing. Firstly, first-person vision requires the system to fo- cus more on the interaction object (shown by Example-A), and the most frequent query templates of the NLQ task (i.e, “Where is object X before / after event Y?” and “Where did I put X?”) all demand the necessity of human-object inter- [2] Zhijian Hou, Wanjun Zhong, Lei Ji, Difei Gao, Kun Yan, Wing-Kwong Chan, Chong-Wah Ngo, Zheng Shou, and Nan Duan. Cone: An efficient coarse-to-fine alignment frame- arXiv preprint work for long video temporal grounding. arXiv:2209.10918, 2022. 1 Detect- ing moments and highlights in videos via natural language queries. Advances in Neural Information Processing Systems, 34:11846–11858, 2021. 1, 3 [4] Kevin Qinghong Lin, Alex Jinpeng Wang, Mattia Soldan, Michael Wray, Rui Yan, Eric Zhongcong Xu, Difei Gao, Rongcheng Tu, Wenzhe Zhao, Weijie Kong, et al. Egocentric video-language pretraining. arXiv preprint arXiv:2206.01670, 2022. 2, 3 [5] Naiyuan Liu, Xiaohan Wang, Xiaobo Li, Yi Yang, and Yuet- ing Zhuang. Reler@ zju-alibaba submission to the ego4d arXiv preprint natural language queries challenge 2022. arXiv:2207.00383, 2022. 4 [6] Hao Zhang, Aixin Sun, Wei Jing, and Joey Tianyi Zhou. Span- based localizing network for natural language video localiza- tion. In Proceedings of the 58th Annual Meeting of the Asso- ciation for Computational Linguistics, 2020. 3 4
Title: Neural Programmer-Interpreters: Summary: We propose the neural programmer-interpreter (NPI): a recurrent and compositional neural network that learns to represent and execute programs. NPI has three learnable components: a task-agnostic recurrent core, a persistent key-value program memory, and domain-specific encoders that enable a single NPI to operate in multiple perceptually diverse environments with distinct affordances. By learning to compose lower-level programs to express higher-level programs, NPI reduces sample complexity and increases generalization ability compared to sequence-to-sequence LSTMs. The program memory allows efficient learning of additional tasks by building on existing programs. NPI can also harness the environment (e.g. a scratch pad with read-write pointers) to cache intermediate results of computation, lessening the long-term memory burden on recurrent hidden units. In this work we train the NPI with fully-supervised execution traces; each program has example sequences of calls to the immediate subprograms conditioned on the input. Rather than training on a huge number of relatively weak labels, NPI learns from a small number of rich examples. We demonstrate the capability of our model to learn several types of compositional programs: addition, sorting, and canonicalizing 3D models. Furthermore, a single NPI learns to execute these programs and all 21 associated subprograms. at ICLR 2016 # NEURAL PROGRAMMER-INTERPRETERS Scott Reed & Nando de Freitas Google DeepMind London, UK scott.ellison.reed@gmail.com nandodefreitas@google.com # ABSTRACT We propose the neural programmer-interpreter (NPI): a recurrent and composi- tional neural network that learns to represent and execute programs. NPI has three learnable components: a task-agnostic recurrent core, a persistent key-value pro- gram memory, and domain-specific encoders that enable a single NPI to operate in multiple perceptually diverse environments with distinct affordances. By learning to compose lower-level programs to express higher-level programs, NPI reduces sample complexity and increases generalization ability compared to sequence-to- sequence LSTMs. The program memory allows efficient learning of additional tasks by building on existing programs. NPI can also harness the environment (e.g. a scratch pad with read-write pointers) to cache intermediate results of com- putation, lessening the long-term memory burden on recurrent hidden units. In this work we train the NPI with fully-supervised execution traces; each program has example sequences of calls to the immediate subprograms conditioned on the input. Rather than training on a huge number of relatively weak labels, NPI learns from a small number of rich examples. We demonstrate the capability of our model to learn several types of compositional programs: addition, sorting, and canonicalizing 3D models. Furthermore, a single NPI learns to execute these pro- grams and all 21 associated subprograms. # INTRODUCTION Teaching machines to learn new programs, to rapidly compose new programs from existing pro- grams, and to conditionally execute these programs automatically so as to solve a wide variety of tasks is one of the central challenges of AI. Programs appear in many guises in various AI prob- lems; including motor behaviours, image transformations, reinforcement learning policies, classical algorithms, and symbolic relations. In this paper, we develop a compositional architecture that learns to represent and interpret pro- grams. We refer to this architecture as the Neural Programmer-Interpreter (NPI). The core module is an LSTM-based sequence model that takes as input a learnable program embedding, program arguments passed on by the calling program, and a feature representation of the environment. The output of the core module is a key indicating what program to call next, arguments for the following program and a flag indicating whether the program should terminate. In addition to the recurrent core, the NPI architecture includes a learnable key-value memory of program embeddings. This program-memory is essential for learning and re-using programs in a continual manner. Figures 1 and 2 illustrate the NPI on two different tasks. We show in our experiments that the NPI architecture can learn 21 programs, including addition, sorting, and trajectory planning from image pixels. Crucially, this can be achieved using a single core model with the same parameters shared across all tasks. Different environments (for example images, text, and scratch-pads) may require specific perception modules or encoders to produce the features used by the shared core, as well as environment-specific actuators. Both perception modules and actuators can be learned from data when training the NPI architecture. To train the NPI we use curriculum learning and supervision via example execution traces. Each program has example sequences of calls to the immediate subprograms conditioned on the input. 1 Published as a conference paper at ICLR 2016 HGOTO [fe ACT 12 | 12 . 72] ine 12 ne fla iz +2] 72] 12) * [ap GOTO() HGOTO() LGOTO() ACT(LEFT) LGOTO() ACT(LEFT) GOTO() | VGOTO() DGOTO() ACT(DOWN) end state Figure 1: Example execution of canonicalizing 3D car models. The task is to move the camera such that a target angle and elevation are reached. There is a read-only scratch pad containing the target (angle 1, elevation 2 here). The image encoder is a convnet trained from scratch on pixels. Ae SSS Pi y | ! u + 2 2 AOD) ACT@ZWRITE) ADDI) ——CARRY)~—«ACT@LEFT) —caRRY) AcT@nwere) Figure 2: Example execu- tion trace of single-digit addi- tion. The task is to perform a single-digit add on the num- bers at pointer locations in the first two rows. The carry (row 3) and output (row 4) should be updated to reflect the addi- tion. At each time step, an ob- servation of the environment (viewed from each pointer on a scratch pad) is encoded into a fixed-length vector. By using neural networks to represent the subprograms and learning these from data, the approach can generalize on tasks involving rich perceptual inputs and uncertainty. We may envision two approaches to provide supervision. In one, we provide a very large number of labeled examples, as in object recognition, speech and machine translation. In the other, the approached followed in this paper, the aim is to provide far fewer labeled examples, but where the labels contain richer information allowing the model to learn compositional structure. While unsupervised and reinforcement learning play important roles in perception and motor control, other cognitive abilities are possible thanks to rich supervision and curriculum learning. This is indeed the reason for sending our children to school. An advantage of our approach to model building and training is that the learned programs exhibit strong generalization. Specifically, when trained to sort sequences of up to twenty numbers in length, they can sort much longer sequences at test time. In contrast, the experiments will show that more standard sequence to sequence LSTMs only exhibit weak generalization, see Figure 6. A trained NPI with fixed parameters and a learned library of programs, can act both as an interpreter and as a programmer. As an interpreter, it takes input in the form of a program embedding and input data and subsequently executes the program. As a programmer, it uses samples drawn from a new task to generate a new program embedding that can be added to its library of programs. # 2 RELATED WORK Several ideas related to our approach have a long history. For example, the idea of using dynam- ically programmable networks in which the activations of one network become the weights (the 2 Published as a conference paper at ICLR 2016 program) of a second network was mentioned in the Sigma-Pi units section of the influential PDP paper (Rumelhart et al., 1986). This idea appeared in (Sutskever & Hinton, 2009) in the context of learning higher order symbolic relations and in (Donnarumma et al., 2015) as the key ingredient of an architecture for prefrontal cognitive control. Schmidhuber (1992) proposed a related meta-learning idea, whereby one learns the parameters of a slowly changing network, which in turn generates context dependent weight changes for a second rapidly changing network. These approaches have only been demonstrated in very limited settings. In cognitive science, several theories of brain areas controlling other brain parts so as to carry out multiple tasks have been proposed; see for example Schneider & Chein (2003); Anderson (2010) and Donnarumma et al. (2012). Related problems have been studied in the literature on hierarchical reinforcement learning (e.g., Dietterich (2000); Andre & Russell (2001); Sutton et al. (1999) and Schaul et al. (2015)), imitation and apprenticeship learning (e.g., Kolter et al. (2008) and Rothkopf & Ballard (2013)) and elicita- tion of options through human interaction (Subramanian et al., 2011). These ideas have held great promise, but have not enjoyed significant impact. We believe the recurrent compositional neural representations proposed in this paper could help these approaches in the future, and in particular in overcoming feature engineering. Several recent advancements have extended recurrent networks to solve problems beyond simple sequence prediction. Graves et al. (2014) developed a neural Turing machine capable of learning and executing simple programs such as repeat copying, simple priority sorting and associative recall. Vinyals et al. (2015) developed Pointer Networks that generalize the notion of encoder attention in order to provide the decoder a variable-sized output space depending on the input sequence length. This model was shown to be effective for combinatorial optimization problems such as the traveling salesman and Delaunay triangulation. While our proposed model is trained on execution traces in- stead of input and output pairs, in exchange for this richer supervision we benefit from compositional program structure, improving data efficiency on several problems. This work is also closely related to program induction. Most previous work on program induc- tion, i.e. inducing a program given example input and output pairs, has used genetic program- ming (Banzhaf et al., 1998) to evolve useful programs from candidate populations. Mou et al. (2014) process program symbols to learn max-margin program embeddings with the help of parse trees. Zaremba & Sutskever (2014) trained LSTM models to read in the text of simple programs Joulin & Mikolov (2015) aug- character-by-character and correctly predict the program output. mented a recurrent network with a pushdown stack, allowing for generalization to longer input sequences than seen during training for several algorithmic patterns. Contemporary to this work, several papers have also studied program induction with variants of recurrent neural networks (Zaremba & Sutskever, 2015; Zaremba et al., 2015; Kaiser & Sutskever, 2015; Kurach et al., 2015; Neelakantan et al., 2015). While we share a similar motivation, our approach is distinct in that we explicitly incorporate compositional structure into the network using a program memory, allowing the model to learn new programs by combining sub-programs. # 3 MODEL The NPI core is a long short-term memory (LSTM) network (Hochreiter & Schmidhuber, 1997) that acts as a router between programs conditioned on the current state observation and previous hidden unit states. At each time step, the core module can select another program to invoke using content-based addressing. It emits the probability of ending the current program with a single binary unit. If this probability is over threshold (we used 0.5), control is returned to the caller by popping the caller’s LSTM hidden units and program embedding off of a program call stack and resuming execution in this context. The NPI may also optionally write arguments (ARG) that are passed by reference or value to the invoked sub-programs. For example, an argument could indicate a specific location in the input sequence (by reference), or it could specify a number to write down at a particular location in the sequence (by value). The subsequent state consists of these arguments and observations of the environment. The approach is illustrated in Figures 1 and 2. It must be emphasized that there is a single inference core. That is, all the LSTM instantiations executing arbitrary programs share the same parameters. Different programs correspond to program embeddings, which are stored in a learnable persistent memory. The programs therefore have a more 3 Published as a conference paper at ICLR 2016 succinct representation than neural programs encoded as the full set of weights in a neural network (Rumelhart et al., 1986; Graves et al., 2014). The output of an NPI, conditioned on an input state and a program to run, is a sequence of actions in a given environment. In this work, we consider several environments: a 1-D array with read-only pointers and a swap action, a 2-D scratch pad with read-write pointers, and a CAD renderer with controllable elevation and azimuth movements. Note that the sequence of actions for a program is not fixed, but dependent also on the input state. 3.1 INFERENCE Denote the environment observation at time t as et ∈ E, and the current program arguments as at ∈ A. The form of et can vary dramatically by environment; for example it could be a color image or an array of numbers. The program arguments at can also vary by environment, but in the experiments for this paper we always used a 3-tuple of integers (at(1), at(2), at(3)). Given the environment and arguments at time t, a fixed-length state encoding st ∈ RD is extracted by a domain-specific encoder fenc : E ×A → RD. In section 4 we provide examples of several encoders. Note that a single NPI network can have multiple encoders for multiple environments, and encoders can potentially also be shared across tasks. We denote the current program embedding as pt ∈ RP . The previous hidden unit and cell states are h(l) t−1 ∈ RM , l = 1, ..., L where L is the number of layers in the LSTM. The program and state vectors are then propagated forward through an LSTM mapping flstm as in (Sutskever et al., 2014). How to fuse pt and st within flstm is an implementation detail, but in this work we concatenate and feed through a 2-layer MLP with rectified linear (ReLU) hidden activation and linear decoder. From the top LSTM hidden state hL t , several decoders generate the outputs. The probability of finishing the program and returning to the caller 1 is computed by fend : RM → [0, 1]. The lookup key embedding used for retrieving the next program from memory is computed by fprog : RM → RK. Note that RK can be much smaller than RP because the key only need act as the identifier of a program, while the program embedding must have enough capacity to conditionally generate a sequence of actions. The contents of the arguments to the next program to be called are generated by farg : RM → A. The feed-forward steps of program inference are summarized below: st = fenc(et, at) (1) ht = flstm(st, pt, ht−1) (2) rt = fend(ht), kt = fprog(ht), at+1 = farg(ht) (3) where rt, kt and at+1 correspond to the end-of-program probability, program key embedding, and output arguments at time t, respectively. These yield input arguments at time t + 1. To simplify the notation, we have abstracted properties such as layers and cell memory in the sequence-to-sequence LSTM of equation (2); see (Sutskever et al., 2014) for details. The NPI representation is equipped with key-value memory structures M key ∈ RN ×K and M prog ∈ RN ×P storing program keys and program embeddings, respectively, where N is the current number of programs in memory. We can add more programs by adding rows to memory. During training, the next program identifier is provided to the model as ground-truth, so that its embedding can be retrieved from the corresponding row of M prog. At test time, we compute the “program ID” by comparing the key embedding kt to each row of M key storing all program keys. Then the program embedding is retrieved from M prog as follows: i∗ = arg max i=1..N The next environmental state et+1 will be determined by the dynamics of the environment and can be affected by both the choice of program pt and the contents of the output arguments at, i.e. et+1 ∼ fenv(et, pt, at) (5) The transition mapping fenv is domain-specific and will be discussed in Section 4. A description of the inference procedure is given in Algorithm 1. 1In our implementation, a program may first call a subprogram before itself finishing. The only exception is the ACT program that signals a low-level action to the environment, e.g. moving a pointer one step left or writing a value. By convention ACT does not call any further sub-programs. 4 Published as a conference paper at ICLR 2016 Algorithm 1 Neural programming inference 1: Inputs: Environment observation e, program id i, arguments a, stop threshold a 2: function RUN(i, a) 3: heoO,r-0,p + MP9 > Init LSTM and return probability. 4: while r < ado 5: 8 © fenc(e, a), h © fistm(s, p, h) > Feed-forward NPI one step. 6: r& fend lh), k= fprog(h), a2 — farg(h) 7: in © arg max( Mj)" k > Decide the next program to run. j=1.N 8: if i == ACT then e + fenv(e,p, a) > Update the environment based on ACT. 9: else RUN(i2, a2) > Run subprogram 72 with arguments a Each task has a set of actions that affect the environment. For example, in addition there are LEFT and RIGHT actions that move a specified pointer, and a WRITE action which writes a value at a specified location. These actions are encapsulated into a general-purpose ACT program shared across tasks, and the concrete action to be taken is indicated by the NPI-generated arguments at. Note that the core LSTM module of our NPI representation is completely agnostic to the data modal- ity used to produce the state encoding. As long as the same fixed-length embedding is extracted, the same module can in practice route between programs related to sorting arrays just as easily as between programs related to rotating 3D objects. In the experimental sections, we provide details of the modality-specific deep neural networks that we use to produce these fixed-length state vectors. 3.2 TRAINING To train we use execution traces €;"” : {ez, iz, ax} and £2 : {iz41, ar41, 7}, t = 1,...T, where T is the sequence length. Program IDs i, and i,+1 are row-indices in M*°Y and M°*°S of the programs to run at time ¢ and t+ 1, respectively. We propose to directly maximize the probability of the correct execution trace output €°“’ conditioned on €'”?: @* θ∗ = arg max log P (ξout|ξinp; θ) (6) θ (ξinp,ξout) where θ are the parameters of our model. Since the traces are variable in length depending on the input, we apply the chain rule to model the joint probability over ξout T log P(Eoutl&inp: 9) = > log P(E EL? on 61"? 8) (7) t=1 Note that for many problems the input history ξinp is critical to deciding future actions 1 because the environment observation at the current time-step et alone does not contain enough in- formation. The hidden unit activations of the LSTM in NPI are capable of capturing these temporal dependencies. The single-step conditional probability in equation (7) can be factorized into three further conditional distributions, corresponding to predicting the next program, next arguments, and whether to halt execution: |ξinp 1 (8) where ht is the output of flstm at time t, carrying information from previous time steps. We train by gradient ascent on the likelihood in equation (7). We used an adaptive curriculum in which training examples for each mini-batch are fetched with fre- quency proportional to the model’s current prediction error for the corresponding program. Specif- ically, we set the sampling frequency using a softmax over average prediction error across all pro- grams, with configurable temperature. Every 1000 steps of training we re-estimated these prediction errors. Intuitively, this forces the model to focus on learning the program for which it currently per- forms worst in executing. We found that the adaptive curriculum immediately worked much better than our best-performing hand-designed curriculum, allowing a multi-task NPI to achieve compara- ble performance to single-task NPI on all tasks. We also note that our program has a distinct memory advantage over basic LSTMs because all sub- programs can be trained in parallel. For programs whose execution length grows e.g. quadratically 5 Published as a conference paper at ICLR 2016 Figure 3: Illustration of the addition environment used in our experiments. (a) Example scratch pad and pointers used for computing “96 + 125 = 221”. Carry step is being implemented. (b) Actual trace of addition program generated by our model on the problem shown to the left. Note that we substituted the ACT calls in the trace with more human-readable steps. with the input sequence length, an LSTM will by highly constrained by device memory to train on short sequences. By exploiting compositionality, an effective curriculum can often be developed with sublinear-length subprograms, enabling our NPI model to train on order of magnitude larger sequences than the LSTM. # 4 EXPERIMENTS This section describes the environment and state encoder function for each task, and shows example outputs and prediction accuracy results. For all tasks, the core LSTM had two layers of size 256. We trained the NPI using the ADAM solver (Kingma & Ba, 2015) with base learning rate 0.0001, batch size 1, and decayed the learning rate by a factor of 0.95 every 10,000 steps. # 4.1 TASK AND ENVIRONMENT DESCRIPTIONS In this section we provide an overview of the tasks used to evaluate our model. Table 2 in the appendix provides a full listing of all the programs and subprograms learned by our model. # ADDITION The task in this environment is to read in the digits of two base-10 numbers and produce the digits of the answer. Our goal is to teach the model the standard (at least in the US) grade school algorithm of adding, in which one works from right to left applying single-digit add and carry operations. In this environment, the network is endowed with a “scratch pad” with which to store intermediate computations; e.g. to record carries. There are four pointers; one for each of the two input numbers, one for the carry, and another to write the output. At each time step, a pointer can be moved left or right, or it can record a value to the pad. Figure 3a illustrates the environment of this model, and Figure 3b provides a real execution trace generated by our model. For the state encoder fenc, the model is allowed a view of the scratch pad from the perspective of each of the four pointers. That is, the model sees the current values at pointer locations of the two inputs, the carry row and the output row, as 1-of-K encodings, where K is 10 because we are working in base 10. We also append the values of the input argument tuple at: fenc(Q, i1, i2, i3, i4, at) = M LP ([Q(1, i1), Q(2, i2), Q(3, i3), Q(4, i4), at(1), at(2), at(3)]) (9) where Q ∈ R4×N ×K, and i1, ..., i4 are pointers, one per scratch pad row. The first dimension of Q corresponds to scratch pad rows, N is the number of columns (digits) and K is the one-hot encoding dimension. To begin the ADD program, we set the initial arguments to a default value and initialize all pointers to be at the rightmost column. The only subprogram with non-default arguments is ACT, in which case the arguments indicate an action to be taken by a specified pointer. # SORTING In this section we apply our model to a setting with potentially much longer execution traces: sorting an array of numbers using bubblesort. As in the case of addition we can use a scratch pad to store intermediate states of the array. We define the encoder as follows: fenc(Q, i1, i2, at) = M LP ([Q(1, i1), Q(1, i2), at(1), at(2), at(3)]) (10) 6 Published as a conference paper at ICLR 2016 Figure 4: Illustration of the sorting environment used in our experiments. (a) Example scratch pad and pointers used for sorting. Several steps of the BUBBLE subprogram are shown. (b) Excerpt from the trace of the learned bubblesort program. where Q ∈ R1×N ×K is the pad, N is the array length and K is the array entry embedding dimension. Figure 4 shows an example series of array states and an excerpt of an execution trace. # CANONICALIZING 3D MODELS We also apply our model to a vision task with a very different perceptual environment - pixels. Given a rendering of a 3D car, we would like to learn a visual program that “canonicalizes” the model with respect to its pose. Whatever the starting position, the program should generate a trajectory of actions that delivers the camera to the target view, e.g. frontal pose at a 15◦ elevation. For training data, we used renderings of the 3D car CAD models from (Fidler et al., 2012). This is a nontrivial problem because different starting positions will require quite different trajec- tories to reach the target. Further complicating the problem is the fact that the model will need to generalize to different car models than it saw during training. We again use a scratch pad, but here it is a very simple read-only pad that only contains a target camera elevation and azimuth – i.e., the “canonical pose”. Since observations come in the form of image pixels, we use a convolutional neural network fCN N as the image encoder: fenc(Q, x, i1, i2, at) = M LP ([Q(1, i1), Q(2, i2), fCN N (x), at(1), at(2), at(3)]) where x ∈ RH×W ×3 is a car rendering at the current pose, Q ∈ R2×1×K is the pad containing canonical azimuth and elevation, i1, i2 are the (fixed at 1) pointer locations, and K is the one-hot encoding dimension of pose coordinates. We set K = 24 corresponding to 15◦ pose increments. Note, critically, that our NPI model only has access to pixels of the rendering and the target pose, and is not provided the pose of query frames. We are also aware that one solution to this problem would be to train a pose classifier network and then find the shortest path to canonical pose via classical methods. That is also a sensible approach. However, our purpose here is to show that our method generalizes beyond the scratch pad domain to detailed images of 3D objects, and also to other environments with a single multi-task model. # 4.2 SAMPLE COMPLEXITY AND GENERALIZATION Both LSTMs and Neural Turing Machines can learn to perform sorting to a limited degree, although they have not been shown to generalize well to much longer arrays than were seen during training. However, we are interested not only in whether sorting can be accomplished, but whether a particular sorting algorithm (e.g. bubblesort) can be learned by the model, and how effectively in terms of sample complexity and generalization. We compare the generalization ability of our model to a flat sequence-to-sequence LSTM (Sutskever et al., 2014), using the same number of layers (2) and hidden units (256). Note that a flat 2 version of NPI could also learn sorting of short arrays, but because bubblesort runs in O(N 2) for arrays of length N , the execution traces quickly become far too long to store the required number of LSTM states in memory. Our NPI architecture can train on much larger arrays by exploiting compositional structure; the memory requirements of any given subprogram can be restricted to O(N ). 2By flat in this case, we mean non-compositional, not making use of subprograms, and only making calls to ACT in order to swap values and move pointers. 7 Published as a conference paper at ICLR 2016 Sorting per-sequence accuracy vs. # training examples *—2—_+_e a i TT # Training examples he Seq?Seq —® NPI Sorting per-sequence accuracy vs sequence length r. + oe 2 ¢ 100 I I I Training l 50 sequence lengths l 25 ! i] ! 9 S20 a3 Sequence length a Seq?Seq —® NPI Figure 5: Sample complexity. Test accuracy of sequence-to-sequence LSTM versus NPI on length-20 arrays of single-digit numbers. Note that NPI is able to mine and train on subprogram traces from each bubblesort example. Figure 6: Strong vs. weak generalization. Test accuracy of sequence-to-sequence LSTM ver- sus NPI on varying-length arrays of single-digit numbers. Both models were trained on arrays of single-digit numbers up to length 20. A strong indicator of whether a neural network has learned a program well is whether it can run the program on inputs of previously-unseen sizes. To evaluate this property, we train both the sequence- to-sequence LSTM and NPI to perform bubblesort on arrays of single-digit numbers from length 2 to length 20. Compared to fixed-length inputs this raises the challenge level during training, but in exchange we can get a more flexible and generalizable sorting program. To handle variable-sized inputs, the state representation must have some information about input se- quence length and the number of steps taken so far. For example, the main BUBBLESORT program naturally needs to call its helper function BUBBLE a number of times dependent on the sequence length. We enable this in our model by adding a third pointer that acts as a counter; each time BUB- BLE is called the pointer is advanced by one step. The scratch pad environment also provides a bit indicating whether a pointer is at the start or end of a sequence, equivalent in purpose to end tokens used in a sequence-to-sequence model. For each length, we provided 64 example bubblesort traces, for a total of 1,216 examples. Then, we evaluated whether the network can learn to sort arrays beyond length 20. We found that the trained model generalizes well, and is capable of sorting arrays up to size 60; see Figure 6. At 60 and beyond, we observed a failure mode in which sweeps of pointers across the array would take the wrong number of steps, suggesting that the limiting performance factor is related to counting. In stark contrast, when provided with the 1,216 examples, the sequence-to-sequence LSTMs fail to generalize beyond arrays of length 25 as shown in Figure 6. To study sample complexity further, we fix the length of the arrays to 20 and vary the number of training examples. We see in Figure 5 that NPI starts learning with 2 examples and is able to sort almost perfectly with only 8 examples. The sequence-to-sequence model on the other hand requires 64 examples to start learning and only manages to sort well with over 250 examples. Figure 7 shows several example canonicalization trajectories generated by our model, starting from the leftmost car. The image encoder was a convolutional network with three passes of stride-2 convolution and pooling, trained on renderings of size 128 × 128. The canonical target pose in this case is frontal with 15◦ elevation. At test time, from an initial rendering, NPI is able to canonicalize cars of varying appearance from multiple starting positions. Importantly, it can generalize to car appearances not encountered in the training set as shown in Figure 7. # 4.3 LEARNING NEW PROGRAMS WITH A FIXED CORE One challenge for continual learning of neural-network-based agents is that training on new tasks and experiences can lead to degraded performance in old tasks. The learning of new tasks may require that the network weights change substantially, so care must be taken to avoid catastrophic forgetting (Mccloskey & Cohen, 1989; OReilly et al., 2014). Using NPI, one solution is to fix the weights of the core routing module, and only make sparse updates to the program memory. When adding a new program the core module’s routing computation will be completely unaffected; all the learning for a new task occurs in program embedding space. Of course, the addition of new programs to the memory adds a new choice of program at each time step, and an old program could 8 Published as a conference paper at ICLR 2016 GOTO 12 Co 22 1 2 3 HGOTO BGOTO) LGoTo aia aria — Gee RGOTO ' 2 3 ACT (LEFT) ASKGRERW) = a & ACT (LEFT) 4 5 6 atecrd ACT (LEFT) ACT (UP) ACT (LEFT) fips Sih r_.) ACT(LEFT) 7 GOTO 1 2 1 2 3 VGOTO HGOTO UGOTO pe RGOTO Se, a @ ACT (UP) ACT (RIGHT) ACT (RIGHT) GOTO 1 2 ACT (RIGHT) HGOTO 1 A ; VvGOTO 4 5 6 LGOTO _ _ __ DGOTO ACT(LEFT) te? ama ea ACT (DOWN) 2 VGOTO hs t=3 = ACT (DOWN) 2607 oun) Figure 7: Example canonicalization of several different test set cars. The network is able to generate and execute the appropriate plan based on the starting car image. This NPI was trained on trajectories starting at azimuth (−75◦...75◦) , elevation (0◦...60◦) in 15◦ increments. The training trajectories target azimuth 0◦ and elevation 15◦, as in the generated traces above. mistakenly call a newly added program. To overcome this, when learning a new set of program vectors with a fixed core, in practice we train not only on example traces of the new program, but also traces of existing programs. Alternatively, a simpler approach is to prevent existing programs from calling subsequently added programs, allowing addition of new programs without ever looking back at training data for known programs. In either case, note that only the memory slots of the new programs are updated, and all other weights, including other program embeddings, are fixed. Table 1 shows the result of adding a maximum-finding program MAX to a multitask NPI trained on addition, sorting and canonicalization. MAX first calls BUBBLESORT and then a new program RJMP, which moves pointers to the right of the sorted array, where the max element can be read. During training we froze all weights except for the two newly-added program embeddings. We find that NPI learns MAX perfectly without forgetting the other tasks. In particular, after training a single multi-task model as outlined in the following section, learning the MAX program with this fixed-core multi-task NPI results in no performance deterioration for all three tasks. 4.4 SOLVING MULTIPLE TASKS WITH A SINGLE NETWORK In this section we perform a controlled experiment to compare the performance of a multi-task NPI with several single-task NPI models. Table 1 shows the results for addition, sorting and canonical- izing 3D car models. We trained and evaluated on 10-digit numbers for addition, length-5 arrays for sorting, and up to four-step trajectories for canonicalization. As shown in Table 1, one multi-task NPI can learn all three programs (and necessarily the 21 subprograms) with comparable accuracy compared to each single-task NPI. Task Addition Sorting Canon. seen car Canon. unseen Maximum Single Multi 97.0 100.0 100.0 100.0 91.4 89.5 89.9 88.7 - - + Max 97.0 100.0 91.4 89.9 100.0 Table 1: Per-sequence % accuracy. “+ Max” indicates performance after addition of the ad- ditional max-finding subprograms to memory. “unseen” uses a test set with disjoint car mod- els from the training set, while “seen car” uses the same car models but different trajectories. # 5 CONCLUSION We have shown that the NPI can learn programs in very dissimilar environments with different affordances. In the context of sorting we showed that NPI exhibits very strong generalization in comparison to sequence-to-sequence LSTMs. We also showed how a trained NPI with a fixed core can continue to learn new programs without forgetting already learned programs. ACKNOWLEDGMENTS We sincerely thank Arun Nair and Ed Grefenstette for helpful suggestions. 9 Published as a conference paper at ICLR 2016 # REFERENCES Anderson, Michael L. Neural reuse: A fundamental organizational principle of the brain. Behavioral and Brain Sciences, 33:245–266, 8 2010. Andre, David and Russell, Stuart J. Programmable reinforcement learning agents. In Advances in Neural Information Processing Systems, pp. 1019–1025. 2001. Banzhaf, Wolfgang, Nordin, Peter, Keller, Robert E, and Francone, Frank D. Genetic programming: An introduction, volume 1. Morgan Kaufmann San Francisco, 1998. Dietterich, Thomas G. Hierarchical reinforcement learning with the MAXQ value function decom- position. Journal of Artificial Intelligence Research, 13:227–303, 2000. Donnarumma, Francesco, Prevete, Roberto, and Trautteur, Giuseppe. Programming in the brain: A neural network theoretical framework. Connection Science, 24(2-3):71–90, 2012. Donnarumma, Francesco, Prevete, Roberto, Chersi, Fabian, and Pezzulo, Giovanni. A programmer- interpreter neural network architecture for prefrontal cognitive control. International Journal of Neural Systems, 25(6):1550017, 2015. Fidler, Sanja, Dickinson, Sven, and Urtasun, Raquel. 3D object detection and viewpoint estimation with a deformable 3D cuboid model. In Advances in neural information processing systems, 2012. Graves, Alex, Wayne, Greg, and Danihelka, Ivo. Neural Turing machines. arXiv preprint arXiv:1410.5401, 2014. Hochreiter, Sepp and Schmidhuber, J¨urgen. Long short-term memory. Neural computation, 9(8): 1735–1780, 1997. Joulin, Armand and Mikolov, Tomas. Inferring algorithmic patterns with stack-augmented recurrent nets. In NIPS, 2015. Kaiser, Łukasz and Sutskever, Ilya. Neural gpus learn algorithms. arXiv preprint arXiv:1511.08228, 2015. Kingma, Diederik and Ba, Jimmy. Adam: A method for stochastic optimization. 2015. Kolter, Zico, Abbeel, Pieter, and Ng, Andrew Y. Hierarchical apprenticeship learning with appli- In Advances in Neural Information Processing Systems, pp. cation to quadruped locomotion. 769–776. 2008. Kurach, Karol, Andrychowicz, Marcin, and Sutskever, Ilya. Neural random-access machines. arXiv preprint arXiv:1511.06392, 2015. Mccloskey, Michael and Cohen, Neal J. Catastrophic interference in connectionist networks: The sequential learning problem. In The psychology of learning and motivation, volume 24, pp. 109– 165. 1989. Mou, Lili, Li, Ge, Liu, Yuxuan, Peng, Hao, Jin, Zhi, Xu, Yan, and Zhang, Lu. Building program vector representations for deep learning. arXiv preprint arXiv:1409.3358, 2014. Neelakantan, Arvind, Le, Quoc V, and Sutskever, Ilya. Neural programmer: Inducing latent pro- grams with gradient descent. arXiv preprint arXiv:1511.04834, 2015. OReilly, Randall C., Bhattacharyya, Rajan, Howard, Michael D., and Ketz, Nicholas. Complemen- tary learning systems. Cognitive Science, 38(6):1229–1248, 2014. Rothkopf, ConstantinA. and Ballard, DanaH. Modular inverse reinforcement learning for visuomo- tor behavior. Biological Cybernetics, 107(4):477–490, 2013. Rumelhart, D. E., Hinton, G. E., and McClelland, J. L. Parallel distributed processing: Explorations in the microstructure of cognition, vol. 1. chapter A General Framework for Parallel Distributed Processing, pp. 45–76. MIT Press, 1986. 10 Published as a conference paper at ICLR 2016 Schaul, Tom, Horgan, Daniel, Gregor, Karol, and Silver, David. Universal value function approxi- mators. In International Conference on Machine Learning, 2015. Schmidhuber, J¨urgen. Learning to control fast-weight memories: An alternative to dynamic recur- rent networks. Neural Computation, 4(1):131–139, 1992. Schneider, Walter and Chein, Jason M. Controlled and automatic processing: behavior, theory, and biological mechanisms. Cognitive Science, 27(3):525–559, 2003. Subramanian, Kaushik, Isbell, Charles, and Thomaz, Andrea. Learning options through human interaction. In IJCAI Workshop on Agents Learning Interactively from Human Teachers, 2011. Sutskever, Ilya and Hinton, Geoffrey E. Using matrices to model symbolic relationship. In Advances in Neural Information Processing Systems, pp. 1593–1600. 2009. Sutskever, Ilya, Vinyals, Oriol, and Le, Quoc VV. Sequence to sequence learning with neural net- works. In Advances in neural information processing systems, pp. 3104–3112, 2014. Sutton, Richard S., Precup, Doina, and Singh, Satinder. Between MDPs and semi-MDPs: A frame- work for temporal abstraction in reinforcement learning. Artificial Intelligence, 112(1-2):181– 211, 1999. Vinyals, Oriol, Fortunato, Meire, and Jaitly, Navdeep. Pointer networks. Advances in Neural Infor- mation Processing Systems (NIPS), 2015. Zaremba, Wojciech and Sutskever, Ilya. Learning to execute. arXiv preprint arXiv:1410.4615, 2014. Zaremba, Wojciech and Sutskever, Ilya. Reinforcement learning neural turing machines. arXiv preprint arXiv:1505.00521, 2015. Zaremba, Wojciech, Mikolov, Tomas, Joulin, Armand, and Fergus, Rob. Learning simple algorithms from examples. arXiv preprint arXiv:1511.07275, 2015. 11 Published as a conference paper at ICLR 2016 # 6 APPENDIX 6.1 LISTING OF LEARNED PROGRAMS Below we list the programs learned by our model: Program ADD ADD1 CARRY LSHIFT RSHIFT ACT BUBBLESORT BUBBLE RESET BSTEP COMPSWAP LSHIFT RSHIFT ACT GOTO HGOTO LGOTO RGOTO VGOTO UGOTO DGOTO ACT RJMP MAX Descriptions Perform multi-digit addition Perform single-digit addition Mark a 1 in the carry row one unit left Shift a specified pointer one step left Shift a specified pointer one step right Move a pointer or write to the scratch pad Perform bubble sort (ascending order) Perform one sweep of pointers left to right Move both pointers all the way left Conditionally swap and advance pointers Conditionally swap two elements Shift a specified pointer one step left Shift a specified pointer one step right Swap two values at pointer locations or move a pointer Change 3D car pose to match the target Move horizontally to the target angle Move left to match the target angle Move right to match the target angle Move vertically to the target elevation Move up to match the target elevation Move down to match the target elevation Move camera 15◦ up, down, left or right Move all pointers to the rightmost posiiton Find maximum element of an array Calls ADD1, LSHIFT ACT, CARRY ACT ACT ACT - BUBBLE, RESET ACT, BSTEP LSHIFT COMPSWAP, RSHIFT ACT ACT ACT - HGOTO, VGOTO LGOTO, RGOTO ACT ACT UGOTO, DGOTO ACT ACT - RSHIFT BUBBLESORT,RJMP Table 2: Programs learned for addition, sorting and 3D car canonicalization. Note the the ACT program has a different effect depending on the environment and on the passed-in arguments. 6.2 GENERATED EXECUTION TRACE OF BUBBLESORT Figure 8 shows the sequence of program calls for BUBBLESORT. Pointers 1 and 2 are used to im- Figure 8: Generated execution trace from our trained NPI sorting the array [9,2,5]. # BUBBLESORT BUBBLE BUBBLE BUBBLE PTR 2 RIGHT PTR 2 RIGHT PTR 2 RIGHT BSTEP BSTEP BSTEP COMPSWAP COMPSWAP COMPSWAP SWAP 1 2 RSHIFT RSHIFT RSHIFT PTR 1 RIGHT PTR 1 RIGHT PTR 1 RIGHT PTR 2 RIGHT PTR 2 RIGHT PTR 2 RIGHT BSTEP BSTEP BSTEP COMPSWAP COMPSWAP COMPSWAP SWAP 1 2 RSHIFT RSHIFT RSHIFT PTR 1 RIGHT PTR 1 RIGHT PTR 1 RIGHT PTR 2 RIGHT PTR 2 RIGHT PTR 2 RIGHT RESET RESET RESET LSHIFT LSHIFT LSHIFT PTR 1 LEFT PTR 1 LEFT PTR 1 LEFT PTR 2 LEFT PTR 2 LEFT PTR 2 LEFT LSHIFT LSHIFT LSHIFT PTR 1 LEFT PTR 1 LEFT PTR 1 LEFT PTR 2 LEFT PTR 2 LEFT PTR 2 LEFT PTR 3 RIGHT PTR 3 RIGHT PTR 3 RIGHT plement the “bubble” operation involving the comparison and swapping of adjacent array elements. The third pointer (referred to in the trace as “PTR 3”) is used to count the number of calls to BUB- BLE. After every call to RESET the swapping pointers are moved to the beginning of the array and the counting pointer is advanced by 1. When it has reached the end of the scratch pad, the model learns to halt execution of BUBBLESORT. 12 Published as a conference paper at ICLR 2016 6.3 ADDITIONAL EXPERIMENT ON ADDITION GENERALIZATION Based on reviewer feedback, we conducted an additional comparison of NPI and sequence-to- sequence models for the addition task, to evaluate the generalization ability. we implemented addi- tion in a sequence to sequence model, training to model sequences of the following form, e.g. for “90 + 160 = 250” we represent the sequence as: 90X160X250 For the simple Seq2Seq baseline above (same number of LSTM layers and hidden units as NPI), we observed that the model could predict one or two digits reliably, but did not generalize even up to 20-digit addition. However, we are aware that others have gotten multi-digit addition of the above form to work to some extent with curriculum learning (Zaremba & Sutskever, 2014). In order to make a more competitive baseline, we helped Seq2Seq in two ways: 1) reverse input digits and stack the two numbers on top of each other to form a 2-channel sequence, and 2) reverse input digits and generate reversed output digits immediately at each time step. In the approach of 1), the seq2seq model schematically looks like this: output: XXXX250 input 1: 090XXXX input 2: 061XXXX In the approach of 2), the sequence looks like this: # output: 052 input 1: 090 input 2: 061 Both 1) which we call s2s-stacked and 2) which we call s2s-easy are much stronger competitors to NPI than even the proposed addition baseline. We compare the generalization performance of NPI to these baselines in the figure below: Addition generalization: NPI vs Seq2Seq 100.0% eee @-© _¢ nPI@32 per- sequence —@ S2S-stack@32 75.0% per-character —®- S2S-stack@512 per-character 7 —@ S2S-easy@32 50.0% per-sequence —@ S2S-easy@64 per-sequence 25.0% 0.0% 10 100 1000 Test sequence length Figure 9: Comparing NPI and Seq2Seq variants on addition generalization to longer sequences. We found that NPI trained on 32 examples for problem lengths 1,...,20 generalizes with 100% ac- curacy to all the lengths we tried (up to 3000). s2s-easy trained on twice as many examples gen- eralizes to just over length 2000 problems. s2s-stacked barely generalizes beyond 5, even with far more data. This suggests that locality of computation makes a large impact on generalization per- formance. Even when we carefully ordered and stacked the input numbers for Seq2Seq, NPI still had an edge in performance. In contrast to Seq2Seq, NPI is taught (supervised for now) to move its pointers so that the key operations (e.g. single digit add, carry) can be done using only local information, and this appears to help generalization. 13
Title: Training with Quantization Noise for Extreme Model Compression: Summary: We tackle the problem of producing compact models, maximizing their accuracy for a given model size. A standard solution is to train networks with Quantization Aware Training, where the weights are quantized during training and the gradients approximated with the Straight-Through Estimator. In this paper, we extend this approach to work beyond int8 fixed-point quantization with extreme compression methods where the approximations introduced by STE are severe, such as Product Quantization. Our proposal is to only quantize a different random subset of weights during each forward, allowing for unbiased gradients to flow through the other weights. Controlling the amount of noise and its form allows for extreme compression rates while maintaining the performance of the original model. As a result we establish new state-of-the-art compromises between accuracy and model size both in natural language processing and image classification. For example, applying our method to state-of-the-art Transformer and ConvNet architectures, we can achieve 82.5% accuracy on MNLI by compressing RoBERTa to 14MB and 80.0 top-1 accuracy on ImageNet by compressing an EfficientNet-B3 to 3.3MB. at ICLR 2021 # TRAINING WITH QUANTIZATION NOISE FOR EXTREME MODEL COMPRESSION Angela Fan ∗ Facebook AI Research, LORIA Pierre Stock ∗ † Facebook AI Research, Inria Benjamin Graham Facebook AI Research Edouard Grave Facebook AI Research Rémi Gribonval † Inria Hervé Jégou Facebook AI Research Armand Joulin Facebook AI Research # ABSTRACT We tackle the problem of producing compact models, maximizing their accuracy for a given model size. A standard solution is to train networks with Quantization Aware Training (Jacob et al., 2018), where the weights are quantized during training and the gradients approximated with the Straight-Through Estimator (Bengio et al., 2013). In this paper, we extend this approach to work beyond int8 fixed- point quantization with extreme compression methods where the approximations introduced by STE are severe, such as Product Quantization. Our proposal is to only quantize a different random subset of weights during each forward, allowing for unbiased gradients to flow through the other weights. Controlling the amount of noise and its form allows for extreme compression rates while maintaining the performance of the original model. As a result we establish new state-of-the-art compromises between accuracy and model size both in natural language processing and image classification. For example, applying our method to state-of-the-art Transformer and ConvNet architectures, we can achieve 82.5% accuracy on MNLI by compressing RoBERTa to 14 MB and 80.0% top-1 accuracy on ImageNet by compressing an EfficientNet-B3 to 3.3 MB.1 # INTRODUCTION Many of the best performing neural network architectures in real-world applications have a large number of parameters. For example, the current standard machine translation architecture, Trans- former (Vaswani et al., 2017), has layers that contain millions of parameters. Even models that are designed to jointly optimize the performance and the parameter efficiency, such as EfficientNets (Tan & Le, 2019), still require dozens to hundreds of megabytes, which limits their applications to domains like robotics or virtual assistants. Model compression schemes reduce the memory footprint of overparametrized models. Pruning (LeCun et al., 1990) and distillation (Hinton et al., 2015) remove parameters by reducing the number of network weights. In contrast, quantization focuses on reducing the bits per weight. This makes quantization particularly interesting when compressing models that have already been carefully optimized in terms of network architecture. Whereas deleting weights or whole hidden units will inevitably lead to a drop in performance, we demonstrate that quantizing the weights can be performed with little to no loss in accuracy. Popular postprocessing quantization methods, like scalar quantization, replace the floating-point weights of a trained network by a lower-precision representation, like fixed-width integers (Vanhoucke et al., 2011). These approaches achieve a good compression rate with the additional benefit of accelerating inference on supporting hardware. However, the errors made by these approximations ∗Equal contribution. Corresponding authors: angelafan@fb.com, pstock@fb.com †Univ Lyon, Inria, CNRS, ENS de Lyon, UCB Lyon 1, LIP UMR 5668, F-69342, Lyon, France 1Code available at https://github.com/pytorch/fairseq/tree/master/examples/ quant_noise 1 Published as a conference paper at ICLR 2021 26F XX w/o Quant-Noise X Training without Quant-Noise O Training with Quant-Noise Training Time Quantization Training Time Quantization = 24 Weight Matrix Weight Matrix Weight Matrix Weight Matrix Ei & 22 ia O w/ Quant-Noise | 20 1g [Meal Original Model A. Size(MB) 10 100 1000 Figure 1: Quant-Noise trains models to be resilient to inference-time quantization by mimicking the effect of the quantization method during training time. This allows for extreme compression rates without much loss in accuracy on a variety of tasks and benchmarks. accumulate in the computations operated during the forward pass, inducing a significant drop in performance (Stock et al., 2019). A solution to address this drifting effect is to directly quantize the network during training. This raises two challenges. First, the discretization operators have a null gradient — the derivative with respect to the input is zero almost everywhere. This requires special workarounds to train a network with these operators. The second challenge that often comes with these workarounds is the discrepancy that appears between the train and test functions implemented by the network. Quantization Aware Training (QAT) (Jacob et al., 2018) resolves these issues by quantizing all the weights during the forward and using a straight through estimator (STE) (Bengio et al., 2013) to compute the gradient. This works when the error introduced by STE is small, like with int8 quantization, but does not suffice in compression regimes where the approximation made by the compression is more severe. In this work, we show that quantizing only a subset of weights instead of the entire network during training is more stable for high compression schemes. Indeed, by quantizing only a random fraction of the network at each forward, most the weights are updated with unbiased gradients. Interestingly, we show that our method can employ a simpler quantization scheme during the training. This is particularly useful for quantizers with trainable parameters, such as Product Quantizer (PQ), for which our quantization proxy is not parametrized. Our approach simply applies a quantization noise, called Quant-Noise, to a random subset of the weights, see Figure 1. We observe that this makes a network resilient to various types of discretization methods: it significantly improves the accuracy associated with (a) low precision representation of weights like int8; and (b) state-of-the-art PQ. Further, we demonstrate that Quant-Noise can be applied to existing trained networks as a post-processing step, to improve the performance network after quantization. In summary, this paper makes the following contributions: • We introduce the Quant-Noise technique to learn networks that are more resilient to a variety of quantization methods such as int4, int8, and PQ; • Adding Quant-Noise to PQ leads to new state-of-the-art trade-offs between accuracy and model size. For instance, for natural language processing (NLP), we reach 82.5% accuracy on MNLI by compressing RoBERTa to 14 MB. Similarly for computer vision, we report 80.0% top-1 accuracy on ImageNet by compressing an EfficientNet-B3 to 3.3 MB; • By combining PQ and int8 to quantize weights and activations for networks trained with Quant-Noise, we obtain extreme compression with fixed-precision computation and achieve 79.8% top-1 accuracy on ImageNet and 21.1 perplexity on WikiText-103. # 2 RELATED WORK Model compression. Many compression methods focus on efficient parameterization, via weight pruning (LeCun et al., 1990; Li et al., 2016; Huang et al., 2018; Mittal et al., 2018), weight sharing (Dehghani et al., 2018; Turc et al., 2019; Lan et al., 2019) or with dedicated architectures (Tan & Le, 2019; Zhang et al., 2017; Howard et al., 2019). Weight pruning is implemented during training (Louizos et al., 2017) or as a fine-tuning post-processing step (Han et al., 2015; 2016). Many pruning methods are unstructured, i.e., remove individual weights (LeCun et al., 1990; Molchanov et al., 2017). On the other hand, structured pruning methods follow the structure of the weights to 2 Published as a conference paper at ICLR 2021 reduce both the memory footprint and the inference time of a model (Li et al., 2016; Luo et al., 2017; Fan et al., 2019). We refer the reader to Liu et al. (2018) for a review of different pruning strategies. Other authors have worked on lightweight architectures, by modifying existing models (Zhang et al., 2018; Wu et al., 2019; Sukhbaatar et al., 2019a) or developing new networks, such as MobileNet (Howard et al., 2019), ShuffleNet (Zhang et al., 2017), and EfficientNet (Tan & Le, 2019) in vision. # enctn Finally, knowledge distillation (Hinton et al., 2015) has been applied to sentence representation (Turc et al., 2019; Sanh et al., 2019a; Sun et al., 2019; Zhao et al., 2019; Jiao et al., 2019), to reduce the size of a BERT model (Devlin et al., 2018). Quantization. There are extensive studies of scalar quantization to train networks with low- precision weights and activations (Courbariaux et al., 2015; Courbariaux & Bengio, 2016; Rastegari et al., 2016; McDonnell, 2018). These methods benefit from specialized hardware to also improve the runtime during inference (Vanhoucke et al., 2011). Other quantization methods such as Vector Quantization (VQ) and PQ (Jegou et al., 2011) quantize blocks of weights simultaneously to achieve higher compression rate (Stock et al., 2019; Gong et al., 2014; Joulin et al., 2016; Carreira-Perpiñán & Idelbayev, 2017). Closer to our work, several works have focused at simultaneously training and quantizing a network (Jacob et al., 2018; Krishnamoorthi, 2018; Gupta et al., 2015; Dong et al., 2019). Gupta et al. (2015) assigns weights to a quantized bin stochastically which is specific to scalar quantization, but allows training with fixed point arithmetic. Finally, our method can be interpreted as a form of Bayesian compression (Louizos et al., 2017), using the Bayesian interpretation of Dropout (Gal & Ghahramani, 2016). As opposed to their work, we select our noise to match the weight transformation of a target quantization methods without restricting it to a scale mixture prior. # 3 QUANTIZING NEURAL NETWORKS In this section, we present the principles of quantization, several standard quantization methods, and describe how to combine scalar and product quantization. For clarity, we focus on the case of a fixed real matrix W ∈ Rn×p. We suppose that this matrix is split into m × q blocks bkl: b11 ... bm1 · · · b1q ... . . . · · · bmq , W = (1) where the nature of these blocks is determined by the quantization method. A codebook is a set of K vectors, i.e., C = {c[1],...,c[A]}. Quantization methods compress the matrix W by assigning to each block b,,; an index that points to a codeword c in a codebook C, and storing the codebook C and the resulting indices (as the entries I,; of an index matrix I) instead of the real weights. During the inference, they reconstruct an approximation W of the original matrix W such that Bee = = c[I,]. We distinguish scalar quantization, such as int 8, where each block b,,; consists of a single weight, from vector quantization, where several weights are quantized jointly. 3.1 FIXED-POINT SCALAR QUANTIZATION Fixed-point scalar quantization methods replace floating-point number representations by low- precision fixed-point representations. They simultaneously reduce a model’s memory footprint and accelerate inference by using fixed-point arithmetic on supporting hardware. Fixed-point scalar quantization operates on blocks that represent a single weight, i.e., bj, = Wy. Floating-point weights are replaced by N bit fixed-point numbers (Gupta et al. 2015p, with the extreme case of binarization where N = 1 (Courbariaux et al.|{2015). More precisely, the weights are rounded to one of 2" possible codewords. These codewords correspond to bins evenly spaced by a scale factor s and shifted by a bias z. Each weight W;, is mapped to its nearest codeword c by successively quantizing with z +> round(W,,/s + z) and dequantizing with the inverse operation: c = (round(Wyi/s + z) — 2) x s, (2) where we compute the scale and bias as: s = max W − min W 2N − 1 and z = round(min W/s). 3 Published as a conference paper at ICLR 2021 We focus on this uniform rounding scheme instead of other non-uniform schemes (Choi et al., 2018; Li et al., 2019), because it allows for fixed-point arithmetic with implementations in PyTorch and Tensorflow (see Appendix). The compression rate is ×32/N . The activations are also rounded to N -bit fixed-point numbers. With int8 for instance, this leads to ×2 to ×4 faster inference on dedicated hardware. In this work, we consider both int4 and int8 quantization. 3.2 PRODUCT QUANTIZATION Several quantization methods work on groups of weights, such as vectors, to benefit from the correlation induced by the structure of the network. In this work, we focus on Product Quantization for its good performance at extreme compression ratio (Stock et al., 2019). Traditional PQ. In vector quantization methods, the blocks are predefined groups of weights instead of single weights. The codewords are groups of values, and the index matrix I maps groups of weights from the matrix W to these codewords. In this section, we present the Product Quantization framework as it generalizes both scalar and vector quantization. We consider the case where we apply PQ to the columns of W and thus assume that q = p. Traditional vector quantization techniques split the matrix W into its p columns and learn a codebook on the resulting p vectors. Instead, Product Quantization splits each column into m subvectors and learns the same codebook for each of the resulting m × p subvectors. Each quantized vector is subsequently obtained by assigning its subvectors to the nearest codeword in the codebook. Learning the codebook is traditionally done using k-means with a fixed number K of centroids, typically K = 256 to store the index matrix I using int8. Thus, the objective function is written as: Jw —WI2 =P bu —eftull2. ° kl k,l PQ shares representations between subvectors, which allows for higher compression rates than intN. Iterative PQ. When quantizing a full network rather than a single matrix, extreme compression with PQ induces a quantization drift as reconstruction error accumulates (Stock et al., 2019). Indeed, subsequent layers take as input the output of preceding layers, which are modified by the quantization of the preceding layers. This creates a drift in the network activations, resulting in large losses of performance. A solution proposed by Stock et al. (2019), which we call iterative PQ (iPQ), is to quantize layers sequentially from the lowest to the highest, and finetune the upper layers as the lower layers are quantized, under the supervision of the uncompressed (teacher) model. Codewords of each layer are finetuned by averaging the gradients of their assigned elements with gradient steps: 1 OL Je| (Dele Obp1 e+c~7n (4) where Jc = {(k, l) | c[Ikl] = c}, L is the loss function and η > 0 is a learning rate. This adapts the upper layers to the drift appearing in their inputs, reducing the impact of the quantization approximation on the overall performance. 3.3 COMBINING FIXED-POINT WITH PRODUCT QUANTIZATION Fixed-point quantization and Product Quantization are often regarded as competing choices, but can be advantageously combined. Indeed, PQ/iPQ compresses the network by replacing vectors of weights by their assigned centroids, but these centroids are in floating-point precision. Fixed-point quantization compresses both activations and weights to fixed-point representations. Combining both approaches means that the vectors of weights are mapped to centroids that are compressed to fixed-point representations, along with the activations. This benefits from the extreme compression ratio of iPQ and the finite-precision arithmetics of intN quantization. More precisely, for a given matrix, we store the int8 representation of the K centroids of dimension d along with the log2 K representations of the centroid assignments of the m × p subvectors. The int8 representation of the centroids is obtained with Eq. (2). The overall storage of the matrix and activations during a forward pass with batch size 1 (recalling that the input dimension is n) writes M = 8 × Kd + log2 K × mp + 8 × n bits. 4 Published as a conference paper at ICLR 2021 In particular, when K = 256, the centroid assignments are also stored in int8, which means that every value required for a forward pass is stored in an int8 format. We divide by 4 the float32 overhead of storing the centroids, although the storage requirement associated with the centroids is small compared to the cost of indexing the subvectors for standard networks. In contrast to iPQ alone where we only quantize the weights, we also quantize the activations using int8. We evaluate this approach on both natural language processing and computer vision tasks in Section 5. # 4 METHOD Deep networks are not exposed to the noise caused by the quantization drift during training, leading to suboptimal performance. A solution to make the network robust to quantization is to introduce it during training. Quantization Aware Training (QAT) (Jacob et al., 2018) exposes the network during training by quantizing weights during the forward pass. This transformation is not differentiable and gradients are approximated with a straight through estimator (STE) (Bengio et al., 2013; Courbariaux & Bengio, 2016). STE introduces a bias in the gradients that depends on level of quantization of the weights, and thus, the compression ratio. In this section, we propose a simple modification to control this induced bias with a stochastic amelioration of QAT, called Quant-Noise. The idea is to quantize a randomly selected fraction of the weights instead of the full network as in QAT, leaving some unbiased gradients flow through unquantized weights. Our general formulation can simulate the effect of both quantization and of pruning during training. 4.1 TRAINING NETWORKS WITH QUANTIZATION NOISE We consider the case of a real matrix W as in Section 3. During the training of a network, our proposed Quant-Noise method works as follows: first, we compute blocks bkl related to a target quantization method. Then, during each forward pass, we randomly select a subset of these blocks and apply some distortion to them. More formally, given a set of tuples of indices J ⊂ {(k, l)} for 1 ≤ k ≤ m, 1 ≤ l ≤ q and a distortion or noise function ϕ acting on a block, we define an operator ψ(· | J) such that, for each block bkl, we apply the following transformation: p(b) if (k,l) € J, De otherwise. W(be | J) = { (6) The noise function ϕ simulates the change in the weights produced by the target quantization method (see Section 4.2 for details). We replace the matrix W by the resulting noisy matrix Wnoise during the forward pass to compute a noisy output ynoise, i.e., Wnoise = (ψ(bkl | J))kl and ynoise = xWnoise where x is an input vector. During the backward pass, we apply STE, which amounts to replacing the distorted weights Wnoise by their non-distorted counterparts. Note that our approach is equivalent to QAT when J containts all the tuples of indices. However, an advantage of Quant-Noise over QAT is that unbiased gradients continue to flow via blocks unaffected by the noise. As these blocks are randomly selected for each forward, we guarantee that each weight regularly sees gradients that are not affected by the nature of the function ϕ. As a side effect, our quantization noise regularizes the network in a similar way as DropConnect (Wan et al., 2013) or LayerDrop (Fan et al., 2019). Composing quantization noises. As noise operators are compositionally commutative, we can make a network robust to a combination of quantization methods by composing their noise operators: ψ(bkl | J) = ψ1 ◦ ψ2(bkl | J). (8) This property is particularly useful to combine quantization with pruning operators during training, as well as combining scalar quantization with product quantization. 4.2 ADDING NOISE TO SPECIFIC QUANTIZATION METHODS In this section, we propose several implementations of the noise function ϕ for the quantization methods described in Section 3. We also show how to handle pruning with it. 5 (7) Published as a conference paper at ICLR 2021 Quantization Scheme Language Modeling 16-layer Transformer Wikitext-103 Image Classification EfficientNet-B3 ImageNet-1k Size Compression PPL Size Compression Uncompressed model 942 × 1 18.3 46.7 × 1 int4 quantization - trained with QAT - trained with Quant-Noise 118 118 118 × 8 × 8 × 8 39.4 34.1 21.8 5.8 5.8 5.8 × 8 × 8 × 8 int8 quantization - trained with QAT - trained with Quant-Noise 236 236 236 × 4 × 4 × 4 19.6 21.0 18.7 11.7 11.7 11.7 × 4 × 4 × 4 iPQ - trained with QAT - trained with Quant-Noise 38 38 38 × 25 × 25 × 25 25.2 41.2 20.7 3.3 3.3 3.3 × 14 × 14 × 14 iPQ & int8 + Quant-Noise 38 × 25 21.1 3.1 × 15 Top-1 81.5 45.3 59.4 67.8 80.7 80.8 80.9 79.0 55.7 80.0 79.8 Table 1: Comparison of different quantization schemes with and without Quant-Noise on language mod- eling and image classification. For language modeling, we train a Transformer on the Wikitext-103 benchmark and report perplexity (PPL) on test. For image classification, we train a EfficientNet-B3 on the ImageNet-1k benchmark and report top-1 accuracy on validation and use our re-implementation of EfficientNet-B3. The original implementation of Tan & Le (2019) achieves an uncompressed Top-1 accuracy of 81.9%. For both settings, we report model size in megabyte (MB) and the compression ratio compared to the original model. In intN quantization, the blocks are atomic and weights are Fixed-point scalar quantization. rounded to their nearest neighbor in the codebook. The function ϕ replaces weight Wkl with the output of the rounding function defined in Eq. (2), i.e., ϕintN(w) = (round(w/s + z) − z) × s, (9) where s and z are updated during training. In particular, the application of Quant-Noise to int8 scalar quantization is a stochastic amelioration of QAT. Product quantization. As opposed to intN, codebooks in PQ require a clustering step based on weight values. During training, we learn codewords online and use the resulting centroids to implement the quantization noise. More precisely, the noise function ϕPQ assigns a selected block b to its nearest codeword in the associated codebook C: gro(v) = argmingeg||b — ¢||3. (10) Updating the codebooks online works well. However, empirically, running k-means once per epoch is faster and does not noticeably modify the resulting accuracy. Note that computing the exact noise function for PQ is computationally demanding. We propose a simpler and faster alternative approximation ϕproxy to the operational transformation of PQ and iPQ. The noise function simply zeroes out the subvectors of the selected blocks, i.e., ϕproxy(v) = 0. As a sidenote, we considered other alternatives, for instance one where the subvectors are mapped to the mean subvector. In practice, we found that these approximations lead to similar performance, see Section 7.2. This proxy noise function is a form of Structured Dropout and encourages correlations between the subvectors. This correlation is beneficial to the subsequent clustering involved in PQ/iPQ. Adding pruning to the quantization noise. The specific form of quantization noise can be ad- justed to incorporate additional noise specific to pruning. We simply combine the noise operators of quantization and pruning by composing them following Eq. (8). We consider the pruning noise function of Fan et al. (2019) where they randomly drop predefined structures during training. In particular, we focus on LayerDrop, where the structures are the residual blocks of highway-like layers (Srivastava et al., 2015), as most modern architectures, such as ResNet or Transformer, are composed of this structure. More precisely, the corresponding noise operator over residual blocks v is ϕLayerDrop(v) = 0. For pruning, we do not use STE to backpropagate the gradient of pruned weights, as dropping them entirely during training has the benefit of speeding convergence (Huang 6 Published as a conference paper at ICLR 2021 # > S 3 Ea Language Modeling MNLI ImageNet Top-1 24 xr XL Ideal 8 85 pe LayerDropx deal XBffNet-B4 x BERT < 22 - -OOurs+Share 5 84 MovileBeRT = 80 5 Ours =) Q urs ft +] Cours Pers Mem| ours B _[iSharex XIN KROavet-s0 E20 urs 5 83 TinyBER 3 75 iPQ ResN Dense-169 Tens core < Ours Haig PPR stil < 22 X x xMobile-v2 18 LayerDropxTr XL 82 Albert *DistiIBERT 70 xShuffle-v2x1 é Ideal Comp Trx 81 ReaBERT 10 30 100 300 1000 10 30 100 300 ©1000 1 3 10 30 100 300 1000 Size (MB) Size (MB) Size (MB) Figure 2: Performance as a function of model size. We compare models quantized with PQ and trained with the related Quant-Noise to the state of the art. (a) Test perplexity on Wikitext-103 (b) Dev Accuracy on MNLI (c) ImageNet Top-1 accuracy. Model size is shown in megabytes on a log scale. Red and gray coloring indicates existing work, with different colors for visual distinction. Language modeling Sentence Representation Image Classification Comp. Size PPL Comp. Size Acc. Comp. Size Acc. Unquantized models Original model + Sharing + Pruning × 1 × 1.8 × 3.7 942 510 255 18.3 18.7 22.5 × 1 × 1.9 × 3.8 480 250 125 84.8 84.0 81.3 × 1 × 1.4 × 1.6 46.7 34.2 29.5 81.5 80.1 78.5 Quantized models iPQ + Quant-Noise + Sharing + Pruning × 24.8 × 24.8 × 49.5 × 94.2 38 38 19 10 25.2 20.7 22.0 24.7 × 12.6 × 12.6 × 34.3 × 58.5 38 38 14 8 82.5 83.6 82.5 78.8 × 14.1 × 14.1 × 18 × 20 3.3 3.3 2.6 2.3 79.0 80.0 78.9 77.8 Table 2: Decomposing the impact of the different compression schemes. (a) we train Transformers with Adaptive Input and LayerDrop on Wikitext-103 (b) we pre-train RoBERTA base models with LayerDrop and then finetune on MNLI (c) we train an EfficientNet-B3 on ImageNet. We report the compression ratio w.r.t. to the original model (“comp.”) and the resulting size in MB. et al., 2016). Once a model is trained with LayerDrop, the number of layers kept at inference can be adapted to match computation budget or time constraint. # 5 RESULTS We demonstrate the impact of Quant-Noise on the performance of several quantization schemes in a variety of settings (see Appendix - Sec. 7.5). IMPROVING COMPRESSION WITH QUANT-NOISE Quant-Noise is a regularization method that makes networks more robust to the target quantization scheme or combination of quantization schemes during training. We show the impact of Quant-Noise in Table 1 for a variety of quantization methods: int8/int4 and iPQ. We experiment in 2 different settings: a Transformer network trained for language modeling on WikiText-103 and a EfficientNet-B3 convolutional network trained for image classification on ImageNet-1k. Our quantization noise framework is general and flexible — Quant-Noise improves the performance of quantized models for every quantization scheme in both experimental settings. Importantly, Quant-Noise only changes model training by adding a regularization noise similar to dropout, with no impact on convergence and very limited impact on training speed (< 5% slower). This comparison of different quantization schemes shows that Quant-Noise works particularly well with high performance quantization methods, like iPQ, where QAT tends to degrade the performances, even compared to quantizing as a post-processing step. In subsequent experiments in this section, we focus on applications with iPQ because it offers the best trade-off between model performance and compression, and has little negative impact on FLOPS. 7 Published as a conference paper at ICLR 2021 Language Modeling PPL RoBERTa Acc. Train without Quant-Noise + Finetune with Quant-Noise 25.2 20.9 Train without Quant-Noise + Finetune with Quant-Noise 82.5 83.4 Train with Quant-Noise 20.7 Train with Quant-Noise 83.6 Table 3: Quant-Noise: Finetuning vs training. We report performance after iPQ quantization. We train with the φproxy noise and finetune with Quant-Noise, and use it during the transfer to MNLI for each RoBERTa model. Fixed-Point Product Quantization. Combining iPQ and int8 as described in Section 3.3 allows us to take advantage of the high compression rate of iPQ with a fixed-point representation of both centroids and activations. As shown in Table 1, this combination incurs little loss in accuracy with respect to iPQ + Quant-Noise. Most of the memory footprint of iPQ comes from indexing and not storing centroids, so the compression ratios are comparable. Complementarity with Weight Pruning and Sharing. We analyze how Quant-Noise is compati- ble and complementary with pruning (“+Prune”) and weight sharing (“+Share”), see Appendix for details on weight sharing. We report results for Language modeling on WikiText-103, pre-trained sen- tence representations on MNLI and object classification on ImageNet-1k in Table 2. The conclusions are remarkably consistent across tasks and benchmarks: Quant-Noise gives a large improvement over strong iPQ baselines. Combining it with sharing and pruning offers additional interesting operating points of performance vs size. 5.2 COMPARISON WITH THE STATE OF THE ART We now compare our approach on the same tasks against the state of the art. We compare iPQ + Quant-Noise with 6 methods of network compression for Language modeling, 8 state-of-the-art methods for Text classification, and 8 recent methods evaluate image classification on Imagenet with compressed models. These comparisons demonstrate that Quant-Noise leads to extreme compression rates at a reasonable cost in accuracy. We apply our best quantization setup on competitive models and reduce their memory footprint by ×20 − 94 when combining with weight sharing and pruning, offering extreme compression for good performance. Natural Language Processing. In Figure 2, we examine the trade-off between performance and model size. Our quantized RoBERTa offers a competitive trade-off between size and performance with memory reduction methods dedicated to BERT, like TinyBERT, MobileBERT, or AdaBERT. Image Classification. We compress EfficientNet-B3 from 46.7Mb to 3.3Mb (×14 compression) while maintaining high top-1 accuracy (78.5% versus 80% for the original model). As shown in Figure 2, our quantized EfficientNet-B3 is smaller and more accurate than architectures dedicated to optimize on-device performance with limited size like MobileNet or ShuffleNet. We further evaluate the beneficial effect of Quant-Noise on ResNet-50 to compare directly with Stock et al. (2019). Results shown in Table 4 indicate improvement with Quant-Noise compared to previous work. Incorporating pruning noise into quantization is also beneficial. For example, with pruning iPQ+Quant-Noise reduces size by ×25 with only a drop of 2.4 PPL in language modeling. Further, pruning reduces FLOPS by the same ratio as its compression factor, in our case, ×2. By adding sharing with pruning, in language modeling, we achieve an extreme compression ratio of ×94 with a drop of 6.4 PPL with FLOPS reduction from pruning entire shared chunks of layers. For comparison, our 10 MB model has the same performance as the 570 MB Transformer-XL base. 5.3 FINETUNING WITH QUANT-NOISE FOR POST-PROCESSING QUANTIZATION We explore taking existing models and post-processing with Quant-Noise instead of training from scratch. For language modeling, we train for 10 additional epochs. For RoBERTa, we train for 25k additional updates. Finetuning with Quant-Noise incorporates the benefits and almost matches training from scratch (Table 3). In language modeling, there is only a 0.2 PPL difference. We further examine how to incorporate Quant-Noise more flexibly into pretraining RoBERTa. We take an already 8 Published as a conference paper at ICLR 2021 trained RoBERTa model and incorporate Quant-Noise during sentence classification finetuning. This is effective at compressing while retaining accuracy after quantization. # 6 CONCLUSION We show that quantizing a random subset of weights during training maintains performance in the high quantization regime. We validate that Quant-Noise works with a variety of different quantization schemes on several applications in text and vision. Our method can be applied to a combination of iPQ and int8 to benefit from extreme compression ratio and fixed-point arithmetic. Finally, we show that Quant-Noise can be used as a post-processing step to prepare already trained networks for subsequent quantization, to improve the performance of the compressed model. # REFERENCES A. Adcock, V. Reis, M. Singh, Z. Yan, L. van der Maaten, K. Zhang, S. Motwani, J. Guerin, N. Goyal, I. Misra, L. Gustafson, C. Changhan, and P. Goyal. Classy vision. 2019. Alexei Baevski and Michael Auli. Adaptive input representations for neural language modeling. arXiv preprint arXiv:1809.10853, 2018. Yoshua Bengio, Nicholas Léonard, and Aaron Courville. Estimating or propagating gradients through stochastic neurons for conditional computation. arXiv preprint arXiv:1308.3432, 2013. James Bradbury, Stephen Merity, Caiming Xiong, and Richard Socher. Quasi-recurrent neural networks. arXiv preprint arXiv:1611.01576, 2016. Qingqing Cao, Harsh Trivedi, Aruna Balasubramanian, and Niranjan Balasubramanian. Faster and just as accurate: A simple decomposition for transformer models. Miguel A. Carreira-Perpiñán and Yerlan Idelbayev. Model compression as constrained optimization, with application to neural nets. part ii: quantization, 2017. Daoyuan Chen, Yaliang Li, Minghui Qiu, Zhen Wang, Bofang Li, Bolin Ding, Hongbo Deng, Jun Huang, Wei Lin, and Jingren Zhou. Adabert: Task-adaptive bert compression with differentiable neural architecture search. arXiv preprint arXiv:2001.04246, 2020. Jungwook Choi, Zhuo Wang, Swagath Venkataramani, Pierce I-Jen Chuang, Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. Pact: Parameterized clipping activation for quantized neural networks. arXiv preprint arXiv:1805.06085, 2018. Matthieu Courbariaux and Yoshua Bengio. Binarynet: Training deep neural networks with weights and activations constrained to +1 or -1. CoRR, 2016. Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. Binaryconnect: Training deep neural networks with binary weights during propagations. CoRR, 2015. Zihang Dai, Zhilin Yang, Yiming Yang, William W Cohen, Jaime Carbonell, Quoc V Le, and Ruslan Salakhutdinov. Transformer-xl: Attentive language models beyond a fixed-length context. arXiv preprint arXiv:1901.02860, 2019. Yann N. Dauphin, Angela Fan, Michael Auli, and David Grangier. Language modeling with gated convolutional networks. In Proc. of ICML, 2017. Mostafa Dehghani, Stephan Gouws, Oriol Vinyals, Jakob Uszkoreit, and Łukasz Kaiser. Universal transformers, 2018. J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, and L. Fei-Fei. ImageNet: A Large-Scale Hierarchical Image Database. In CVPR, 2009. 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. 9 Published as a conference paper at ICLR 2021 Yinpeng Dong, Renkun Ni, Jianguo Li, Yurong Chen, Hang Su, and Jun Zhu. Stochastic quantization for learning accurate low-bit deep neural networks. International Journal of Computer Vision, 127 (11-12):1629–1642, 2019. Angela Fan, Edouard Grave, and Armand Joulin. Reducing transformer depth on demand with structured dropout. arXiv preprint arXiv:1909.11556, 2019. Yarin Gal and Zoubin Ghahramani. Dropout as a bayesian approximation: Representing model uncertainty in deep learning. In international conference on machine learning, pp. 1050–1059, 2016. Yunchao Gong, Liu Liu, Ming Yang, and Lubomir Bourdev. Compressing deep convolutional networks using vector quantization. arXiv preprint arXiv:1412.6115, 2014. Edouard Grave, Armand Joulin, Moustapha Cisse, David Grangier, and Herve Jegou. Efficient softmax approximation for gpus. arXiv, abs/1609.04309, 2016. Suyog Gupta, Ankur Agrawal, Kailash Gopalakrishnan, and Pritish Narayanan. Deep learning with limited numerical precision. In ICML, 2015. Song Han, Jeff Pool, John Tran, and William Dally. Learning both weights and connections for efficient neural network. In NIPS, pp. 1135–1143, 2015. Song Han, Huizi Mao, and William J. Dally. Deep compression: Compressing deep neural networks with pruning, trained quantization and Huffman coding. ICLR, 2016. Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. CoRR, 2015. Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv preprint arXiv:1503.02531, 2015. Andrew Howard, Mark Sandler, Grace Chu, Liang-Chieh Chen, Bo Chen, Mingxing Tan, Weijun Wang, Yukun Zhu, Ruoming Pang, Vijay Vasudevan, Quoc V. Le, and Hartwig Adam. Searching for mobilenetv3. arXiv e-prints, 2019. Gao Huang, Yu Sun, Zhuang Liu, Daniel Sedra, and Kilian Q Weinberger. Deep networks with stochastic depth. In ECCV, 2016. Gao Huang, Shichen Liu, Laurens Van der Maaten, and Kilian Q Weinberger. Condensenet: An efficient densenet using learned group convolutions. In CVPR, 2018. Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, Matthew Tang, Andrew Howard, Hartwig Adam, and Dmitry Kalenichenko. Quantization and training of neural networks for efficient integer-arithmetic-only inference. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 2704–2713, 2018. Herve Jegou, Matthijs Douze, and Cordelia Schmid. Product quantization for nearest neighbor search. PAMI, 2011. Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li, Fang Wang, and Qun Liu. Tinybert: Distilling bert for natural language understanding. arXiv preprint arXiv:1909.10351, 2019. Armand Joulin, Edouard Grave, Piotr Bojanowski, Matthijs Douze, Hérve Jégou, and Tomas Mikolov. Fasttext.zip: Compressing text classification models. arXiv preprint arXiv:1612.03651, 2016. Raghuraman Krishnamoorthi. Quantizing deep convolutional networks for efficient inference: A whitepaper. arXiv preprint arXiv:1806.08342, 2018. Guillaume Lample and Alexis Conneau. Cross-lingual language model pretraining. arXiv preprint arXiv:1901.07291, 2019. Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu Soricut. Albert: A lite bert for self-supervised learning of language representations, 2019. 10 Published as a conference paper at ICLR 2021 Yann LeCun, John S. Denker, and Sara A. Solla. Optimal brain damage. In NIPS, 1990. Hao Li, Asim Kadav, Igor Durdanovic, Hanan Samet, and Hans Peter Graf. Pruning filters for efficient convnets. arXiv preprint arXiv:1608.08710, 2016. Yuhang Li, Xin Dong, and Wei Wang. Additive powers-of-two quantization: A non-uniform discretization for neural networks. arXiv preprint arXiv:1909.13144, 2019. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. Roberta: A robustly optimized bert pretraining approach. arXiv preprint arXiv:1907.11692, 2019. Zhuang Liu, Mingjie Sun, Tinghui Zhou, Gao Huang, and Trevor Darrell. Rethinking the value of network pruning. arXiv preprint arXiv:1810.05270, 2018. Ilya Loshchilov and Frank Hutter. Sgdr: Stochastic gradient descent with warm restarts. arXiv preprint arXiv:1608.03983, 2016. Christos Louizos, Max Welling, and Diederik P Kingma. Learning sparse neural networks through l_0 regularization. arXiv preprint arXiv:1712.01312, 2017. Jian-Hao Luo, Jianxin Wu, and Weiyao Lin. Thinet: A filter level pruning method for deep neural network compression. In ICCV, 2017. Ningning Ma, Xiangyu Zhang, Hai-Tao Zheng, and Jian Sun. Shufflenet V2: practical guidelines for efficient CNN architecture design. CoRR, 2018. Xindian Ma, Peng Zhang, Shuai Zhang, Nan Duan, Yuexian Hou, Dawei Song, and Ming Zhou. A tensorized transformer for language modeling. arXiv preprint arXiv:1906.09777, 2019. Mark D. McDonnell. Training wide residual networks for deployment using a single bit for each weight, 2018. Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher. Pointer Sentinel Mixture Models. arXiv, abs/1609.07843, 2016. Deepak Mittal, Shweta Bhardwaj, Mitesh M Khapra, and Balaraman Ravindran. Recovering from random pruning: On the plasticity of deep convolutional neural networks. In WACV, 2018. Dmitry Molchanov, Arsenii Ashukha, and Dmitry Vetrov. Variational dropout sparsifies deep neural networks. In ICML, 2017. Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, and Michael Auli. fairseq: A fast, extensible toolkit for sequence modeling. In Proceedings of NAACL-HLT 2019: Demonstrations, 2019. Razvan Pascanu, Caglar Gulcehre, Kyunghyun Cho, and Yoshua Bengio. How to construct deep recurrent neural networks. In Proceedings of the Second International Conference on Learning Representations (ICLR 2014), 2014. Adam Paszke, Sam Gross, Soumith Chintala, Gregory Chanan, Edward Yang, Zachary DeVito, Zeming Lin, Alban Desmaison, Luca Antiga, and Adam Lerer. Automatic differentiation in pytorch. 2017. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. 2019. Jack W Rae, Anna Potapenko, Siddhant M Jayakumar, and Timothy P Lillicrap. Compressive transformers for long-range sequence modelling. arXiv preprint arXiv:1911.05507, 2019. Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. Xnor-net: Imagenet classification using binary convolutional neural networks. In ECCV, 2016. 11 Published as a conference paper at ICLR 2021 Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, and Liang-Chieh Chen. Mo- bilenetv2: Inverted residuals and linear bottlenecks. In Conference on Computer Vision and Pattern Recognition, pp. 4510–4520, 2018. Victor Sanh, Lysandre Debut, Julien Chaumond, and Thomas Wolf. Distilbert, a distilled version of bert: smaller, faster, cheaper and lighter. 2019a. Victor Sanh, Lysandre Debut, Julien Chaumond, and Thomas Wolf. Distilbert, a distilled version of bert: smaller, faster, cheaper and lighter. arXiv preprint arXiv:1910.01108, 2019b. Rupesh Kumar Srivastava, Klaus Greff, and Jürgen Schmidhuber. Highway networks. arXiv preprint arXiv:1505.00387, 2015. Pierre Stock, Armand Joulin, Rémi Gribonval, Benjamin Graham, and Hervé Jégou. And the bit goes down: Revisiting the quantization of neural networks. CoRR, abs/1907.05686, 2019. Sainbayar Sukhbaatar, Edouard Grave, Piotr Bojanowski, and Armand Joulin. Adaptive attention span in transformers. arXiv preprint arXiv:1905.07799, 2019a. Sainbayar Sukhbaatar, Edouard Grave, Guillaume Lample, Herve Jegou, and Armand Joulin. Aug- menting self-attention with persistent memory. arXiv preprint arXiv:1907.01470, 2019b. Siqi Sun, Yu Cheng, Zhe Gan, and Jingjing Liu. Patient knowledge distillation for bert model compression. EMNLP, 2019. Zhiqing Sun, Hongkun Yu, Xiaodan Song, Renjie Liu, Yiming Yang, and Denny Zhou. Mobilebert: Task-agnostic compression of bert for resource limited devices. Ilya Sutskever, James Martens, George Dahl, and Geoffrey Hinton. On the importance of initialization and momentum in deep learning. In International conference on machine learning, pp. 1139–1147, 2013. Mingxing Tan and Quoc V. Le. Efficientnet: Rethinking model scaling for convolutional neural networks, 2019. Iulia Turc, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Well-read students learn better: The impact of student initialization on knowledge distillation. arXiv preprint arXiv:1908.08962, 2019. Vincent Vanhoucke, Andrew Senior, and Mark Z Mao. Improving the speed of neural networks on cpus. 2011. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. In NIPS, 2017. Li Wan, Matthew Zeiler, Sixin Zhang, Yann Le Cun, and Rob Fergus. Regularization of neural networks using DropConnect. In ICML, 2013. Alex Wang, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R. Bowman. GLUE: A multi-task benchmark and analysis platform for natural language understanding. 2019. ICLR. Kuan Wang, Zhijian Liu, Yujun Lin andx Ji Lin, and Song Han. HAQ: hardware-aware automated quantization. CoRR, 2018. Adina Williams, Nikita Nangia, and Samuel R. Bowman. A broad-coverage challenge corpus for sentence understanding through inference. In Proceedings of NAACL-HLT, 2018. Felix Wu, Angela Fan, Alexei Baevski, Yann Dauphin, and Michael Auli. Pay less attention with lightweight and dynamic convolutions. In ICLR, 2019. Biao Zhang, Deyi Xiong, and Jinsong Su. Accelerating neural transformer via an average attention network. arXiv preprint arXiv:1805.00631, 2018. 12 Published as a conference paper at ICLR 2021 Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, and Jian Sun. Shufflenet: An extremely efficient convolutional neural network for mobile devices. CoRR, 2017. Sanqiang Zhao, Raghav Gupta, Yang Song, and Denny Zhou. Extreme language model compression with optimal subwords and shared projections. arXiv preprint arXiv:1909.11687, 2019. 13 Published as a conference paper at ICLR 2021 Setting Model Compression Top-1 Accuracy Small Blocks Stock et al. (2019) Quant-Noise 19x 19x 73.8 74.3 Large Blocks Stock et al. (2019) Quant-Noise 32x 32x 68.2 68.8 Table 4: Compression of ResNet-50 with Quant-Noise. We compare to Stock et al. (2019) in both the small and large blocks regime. For fair comparison, we hold the compression rate constant. Quant-Noise provides improved performance in both settings. int8 iPQ 21 | —o— Non-Quantized 35 Fo Non-Quantized z 29 | = Quantized z 30 | C= Quantized z z 2 19 ani 18 20 p= ae 0.0 0.2 0.4 0.6 0.8 1.0 0.0 0.1 0.2 0.3 0.4 0.5 Quant-Noise rate Quant-Noise rate Figure 3: Effect of Quantization Parameters. We report the influence of the proportion of blocks to which we apply the noise. We focus on Transformer for Wikitext-103 language modeling. We explore two settings: iPQ and int8. For iPQ, we use ϕproxy. 7 APPENDIX 7.1 QUANTIZATION OF ADDITIONAL ARCHITECTURES ResNet-50. We explore the compression of ResNet-50, a standard architecture used Computer Vision. In Table 4, we compare Quant-Noise to iPQ Compression from Stock et al. (2019) and show that Quant-Noise provide consistent additional improvement. 7.2 ABLATIONS In this section, we examine the impact of the level of noise during training as well as the impact of approximating iPQ during training. 7.3 IMPACT OF NOISE RATE We analyze the performance for various values of Quant-Noise in Figure 3 on a Transformer for language modeling. For iPQ, performance is impacted by high rates of quantization noise. For example, a Transformer with the noise function ϕproxy degrades with rate higher than 0.5, i.e., when half of the weights are passed through the noise function ϕproxy. We hypothesize that for large quantities of noise, a larger effect of using proxy rather than the exact PQ noise is observed. For int8 quantization and its noise function, higher rates of noise are slightly worse but not as severe. A rate of 1 for int8 quantization is equivalent to the Quantization Aware Training of (Krishnamoorthi, 2018), as the full matrix is quantized with STE, showing the potential benefit of partial quantization during training. IMPACT OF APPROXIMATING THE NOISE FUNCTION We study the impact of approximating quantization noise during training. We focus on the case of iPQ with the approximation described in Section 4.2. In Table 5, we compare the correct noise function for iPQ with its approximation ϕproxy. This approximate noise function does not consider cluster assignments or centroid values and simply zeroes out the selected blocks. For completeness, we include an intermediate approximation where we consider cluster assignments to apply noise 14 Published as a conference paper at ICLR 2021 Noise Blocks ϕPQ ϕPQ ϕproxy ϕproxy Clusters Subvectors Clusters Subvectors PPL Quant PPL 18.3 18.3 21.1 21.2 18.3 18.4 21.0 21.1 Table 5: Exact versus proxy noise function for different block selections with iPQ. We com- pare exact φPQ and the approximation φproxy with blocks selected from all subvectors or subvectors from the same cluster. within each cluster, but still zero-out the vectors. These approximations do not affect the performance of the quantized models. This suggests that increasing the correlation between subvectors that are jointly clustered is enough to maintain the performance of a model quantized with iPQ. Since PQ tends to work well on highly correlated vectors, such as activations in convolutional networks, this is not surprising. Using the approximation ϕproxy presents the advantage of speed and practicality. Indeed, one does not need to compute cluster assignments and centroids for every layer in the network after each epoch. Moreover, the approach ϕproxy is less involved in terms of code. 7.5 EXPERIMENTAL SETTING We assess the effectiveness of Quant-Noise on competitive language and vision benchmarks. We consider Transformers for language modeling, RoBERTa for pre-training sentence representations, and EfficientNet for image classification. Our models are implemented in PyTorch (Paszke et al., 2017). We use fairseq (Ott et al., 2019) for language modeling and pre-training for sentence representation tasks and Classy Vision (Adcock et al., 2019) for EfficientNet. Language Modeling. We experiment on the Wikitext-103 benchmark (Merity et al., 2016) that contains 100M tokens and a vocabulary of 260k words. We train a 16 layer Transformer following Baevski & Auli (2018) with a LayerDrop rate of 0.2 (Fan et al., 2019). We report perplexity (PPL) on the test set. Pre-Training of Sentence Representations. We pre-train the base BERT model (Devlin et al., 2018) on the BooksCorpus + Wiki dataset with a LayerDrop rate of 0.2. We finetune the pre-trained models on the MNLI task (Williams et al., 2018) from the GLUE Benchmark (Wang et al., 2019) and report accuracy. We follow the parameters in Liu et al. (2019) training and finetuning. Image Classification. We train an EfficientNet-B3 model (Tan & Le, 2019) on the ImageNet object classification benchmark (Deng et al., 2009). The EfficientNet-B3 of Classy Vision achieves a Top-1 accuracy of 81.5%, which is slightly below than the performance of 81.9% reported by Tan & Le (2019). 7.6 TRAINING DETAILS Language Modeling To handle the large vocabulary of Wikitext-103, we follow (Dauphin et al., 2017) and (Baevski & Auli, 2018) in using adaptive softmax (Grave et al., 2016) and adaptive input for computational efficiency. For both input and output embeddings, we use dimension size 1024 and three adaptive bands: 20K, 40K, and 200K. We use a cosine learning rate schedule (Baevski & Auli, 2018; Loshchilov & Hutter, 2016) and train with Nesterov’s accelerated gradient (Sutskever et al., 2013). We set the momentum to 0.99 and renormalize gradients if the norm exceeds 0.1 (Pascanu et al., 2014). During training, we partition the data into blocks of contiguous tokens that ignore document boundaries. At test time, we respect sentence boundaries. We set LayerDrop to 0.2. We set Quant-Noise value to 0.05. During training time, we searched over the parameters (0.05, 0.1, 0.2) to determine the optimal value of Quant-Noise. During training time, the block size of Quant-Noise is 8. RoBERTa The base architecture is a 12 layer model with embedding size 768 and FFN size 3072. We follow (Liu et al., 2019) in using the subword tokenization scheme from (Radford et al., 2019), which uses bytes as subword units. This eliminates unknown tokens. We train with large batches of size 8192 and maintain this batch size using gradient accumulation. We do not use next sentence prediction (Lample & Conneau, 2019). We optimize with Adam with a polynomial decay learning rate schedule. We set LayerDrop to 0.2. We set Quant-Noise value to 0.1. We did not hyperparameter 15 Published as a conference paper at ICLR 2021 Model MB PPL Trans XL Large (Dai et al., 2019) Compressive Trans (Rae et al., 2019) GCNN (Dauphin et al., 2017) 4 Layer QRNN (Bradbury et al., 2016) Trans XL Base (Dai et al., 2019) Persis Mem (Sukhbaatar et al., 2019b) Tensorized core-2 (Ma et al., 2019) 970 970 870 575 570 506 325 18.3 17.1 37.2 33.0 24.0 20.6 18.9 Quant-Noise Quant-Noise + Share + Prune 38 10 20.7 24.2 Table 6: Performance on Wikitext-103. We report test set perplexity and model size in megabytes. Lower perplexity is better. search to determine the optimal value of Quant-Noise as training RoBERTa is computationally intensive. During training time, the block size of Quant-Noise is 8. During finetuning, we hyperparameter search over three learning rate options (1e-5, 2e-5, 3e-5) and batchsize (16 or 32 sentences). The other parameters are set following (Liu et al., 2019). We do single task finetuning, meaning we only tune on the data provided for the given natural language understanding task. We do not perform ensembling. When finetuning models trained with LayerDrop, we apply LayerDrop and Quant-Noise during finetuning time as well. EfficientNet We use the architecture of EfficientNet-B3 defined in Classy Vision (Adcock et al., 2019) and follow the default hyperparameters for training. We set Quant-Noise value to 0.1. During training time, we searched over the parameters (0.05, 0.1, 0.2) to determine the optimal value of Quant-Noise. During training time, the block size of Quant-Noise is set to 4 for all 1 × 1 convolutions, 9 for depth-wise 3 × 3 convolutions, 5 for depth-wise 5 × 5 convolutions and 4 for the classifier. For sharing, we shared weights between blocks 9-10, 11-12, 14-15, 16-17, 19-20-21, 22-23 and refer to blocks that share the same weights as a chunk. For LayerDrop, we drop the chunks of blocks defined previously with probability 0.2 and evaluate only with chunks 9-10, 14-15 and 19-20-21. 7.7 SCALAR QUANTIZATION DETAILS We closely follow the methodology of PyTorch 1.4. We emulate scalar quantization by quantizing the weights and the activations. The scales and zero points of activations are determined by doing a few forward passes ahead of the evaluation and then fixed. We use the Histogram method to compute s and z, which aims at approximately minimizing the L2 quantization error by adjusting s and z. This scheme is a refinement of the MinMax scheme. Per channel quantization is also discussed in Table 10. IPQ QUANTIZATION DETAILS Language Modeling We quantize FFN with block size 8, embeddings with block size 8, and attention with block size 4. We tuned the block size for attention between the values (4, 8) to find the best performance. Note that during training with apply Quant-Noise to all the layers. RoBERTa We quantize FFN with block size 4, embeddings with block size 4, and attention with block size 4. We tuned the block size between the values (4, 8) to find the best performance. Note that during training with apply Quant-Noise to all the layers. EfficientNet We quantize blocks sequentially and end up with the classifier. The block sizes are 4 for all 1 × 1 convolutions, 9 for depth-wise 3 × 3 convolutions, 5 for depth-wise 5 × 5 convolutions and 4 for the classifier. Note that during training with apply Quant-Noise to all the weights in InvertedResidual Blocks (except the Squeeze-Excitation subblocks), the head convolution and the classifier. 16 Published as a conference paper at ICLR 2021 Model MB MNLI RoBERTa Base + LD (Fan et al., 2019) BERT Base (Devlin et al., 2018) PreTrained Distil (Turc et al., 2019) DistilBERT (Sanh et al., 2019b) MobileBERT* (Sun et al.) TinyBERT† (Jiao et al., 2019) ALBERT Base (Lan et al., 2019) AdaBERT† (Chen et al., 2020) 480 420 257 250 96 55 45 36 84.8 84.4 82.5 81.8 84.4 82.8 81.6 81.6 Quant-Noise Quant-Noise + Share + Prune 38 14 83.6 82.5 Table 7: Performance on MNLI. We report accuracy and size in megabytes. * indicates distillation using BERT Large. † indicates training with data augmentation. Work from Sun et al. (2019) and Zhao et al. (2019) do not report results on the dev set. Cao et al. do not report model size. Higher accuracy is better. Model MB Acc. EfficientNet-B7 (Tan & Le, 2019) ResNet-50 (He et al., 2015) DenseNet-169 (Huang et al., 2018) EfficientNet-B0 (Tan & Le, 2019) MobileNet-v2 (Sandler et al., 2018) Shufflenet-v2 ×1 (Ma et al., 2018) 260 97.5 53.4 20.2 13.4 8.7 84.4 76.1 76.2 77.3 71.9 69.4 HAQ 4 bits (Wang et al., 2018) iPQ ResNet-50 (Stock et al., 2019) 12.4 5.09 76.2 76.1 Quant-Noise Quant-Noise + Share + Prune 3.3 2.3 80.0 77.8 Table 8: Performance on ImageNet. We report accuracy and size in megabytes. Higher accuracy is better. 7.9 DETAILS OF PRUNING AND LAYER SHARING We apply the Every Other Layer strategy from Fan et al. (2019). When combining layer sharing with pruning, we train models with shared layers and then prune chunks of shared layers. When sharing layers, the weights of adjacent layers are shared in chunks of two. For a concrete example, imagine we have a model with layers A, B, C, D, E, F, G, H. We share layers A and B, C and D, E and F, G and H. To prune, every other chunk would be pruned away, for example we could prune A, B, E, F. 7.10 NUMERICAL RESULTS FOR GRAPHICAL DIAGRAMS We report the numerical values displayed in Figures 2 in Table 6 for language modeling, Table 7 for BERT, and Table 8 for ImageNet. 7.11 FURTHER ABLATIONS IMPACT OF QUANT-NOISE FOR THE VISION SETUP We provide another study showing the impact of the proportion of elements on which to apply Quant-Noise in Table 9. IMPACT OF THE NUMBER OF CENTROIDS We quantize with 256 centroids which represents a balance between size and representation capacity. The effect of the number of centroids on performance and size is shown in Figure 4 (a). Quantizing 17 Published as a conference paper at ICLR 2021 p 0 0.2 0.4 0.6 0.8 1 Top-1 80.66 80.83 80.82 80.88 80.92 80.64 Table 9: Effect of Quantization Parameters. We report the influence of the Quant-Noise rate p with Scalar Quantization (int8). We focus on EfficientNet for ImageNet classification. Effect of Number of Centroids a 0 1000 2000 Number of Centroids. Roo sS o8 y Ss Valid Perplexity Es Figure 4: Quantizing with a larger number of centroids. Results are shown on Wikitext-103 valid. with more centroids improves perplexity — this parameter could be adjusted based on the practical storage constraints. 7.11.3 EFFECT OF INITIAL MODEL SIZE Large, overparameterized models are more easily compressed. In Figure 5, we explore quantizing both shallower and skinnier models. For shallow models, the gap between quantized and non-quantized perplexity does not increase as layers are removed (Figure 5, left). In contrast, there is a larger gap in performance for models with smaller FFN (Figure 5, right). As the FFN size decreases, the weights are less redundant and more difficult to quantize with iPQ. 7.11.4 DIFFICULTY OF QUANTIZING DIFFERENT MODEL STRUCTURES Quantization is applied to various portions of the Transformer architecture — the embedding, attention, feedforward, and classifier output. We compare the quantizability of various portions of the network in this section. Is the order of structures important? We quantize specific network structures first — this is important as quantizing weight matrices can accumulate reconstruction error. Some structures of the network should be quantized last so the finetuning process can better adjust the centroids. We find that there are small variations in performance based on quantization order (see Figure 6). We choose to quantize FFN, then embeddings, and finally the attention matrices in Transformer networks. Which structures can be compressed the most? Finally, we analyze which network structures can be most compressed. During quantization, various matrix block sizes can be chosen as a parameter — the larger the block size, the more compression, but also the larger the potential reduction of performance. Thus, it is important to understand how much each network structure can be compressed to reduce the memory footprint of the final model as much as possible. In Figure 6, we quantize two model structures with a fixed block size and vary the block size of the third between 4 and 32. As shown, the FFN and embedding structures are more robust to aggressive compression, while the attention drastically loses performance as larger block sizes are used. # 7.11.5 APPROACH TO I N TN SCALAR QUANTIZATION We compare quantizing per-channel to using a histogram quantizer in Table 10. The histogram quantizer maintains a running min/max and minimizes L2 distance between quantized and non- quantized values to find the optimal min/max. Quantizing per channel learns scales and offsets as vectors along the channel dimension, which provides more flexibility since scales and offsets can be different. 18 Published as a conference paper at ICLR 2021 Model Depth Model Width w Ss Valid Perplexity vv a Valid Perplexity iS) S a 4 8 10 14 16 1024 2048 3072 ©4096 Number of Layers FEN Size te Valid PPL -O Quant Valid PPL Figure 5: (a) Effect of Initial Model Size for more shallow models (b) Effect of Initial Model Size more skinny models Order of Quantization Quantization Block Size 25.0 24.0 2 2 % 22.5 % 23.5 a a 5 20.0 5 23.0 z z a 175 ms 22.5 > > 15.0 22.0 attn att embemb ffn ffn 4 8 16 32 emb ffn att ffn att emb Block Size ffn emb ffn att emb att > Attn -OEmb ~~ FFN Figure 6: Effect of Quantization on Model Structures. Results are shown on the validation set of Wikitext-103. (a) Quantizing Attention, FFN, and Embeddings in different order. (b) More Extreme compression of different structures. # 7.11.6 LAYERDROP WITH STE For quantization noise, we apply the straight through estimator (STE) to remaining weights in the backward pass. We experiment with applying STE to the backward pass of LayerDrop’s pruning noise. Results are shown in Table 11 and find slightly worse results. 19 Published as a conference paper at ICLR 2021 Quantization Scheme Language Modeling 16-layer Transformer Wikitext-103 Image Classification EfficientNet-B3 ImageNet-1K Size Compress Test PPL Size Compress Top-1 Acc. Uncompressed model 942 ×1 18.3 46.7 ×1 81.5 Int4 Quant Histogram + Quant-Noise 118 118 ×8 ×8 39.4 21.8 5.8 5.8 ×8 ×8 45.3 67.8 Int4 Quant Channel + Quant-Noise 118 118 ×8 ×8 21.2 19.5 5.8 5.8 ×8 ×8 68.2 72.3 Int8 Quant Histogram + Quant-Noise 236 236 ×4 ×4 19.6 18.7 11.7 11.7 ×4 ×4 80.7 80.9 Int8 Quant Channel + Quant-Noise 236 236 ×4 ×4 18.5 18.3 11.7 11.7 ×4 ×4 81.1 81.2 Table 10: Comparison of different approaches to int4 and int8 with and without Quant- Noise on language modeling and image classification. For language modeling, we train a Transformer on the Wikitext-103 benchmark. We report perplexity (PPL) on the test set. For image classification, we train a EfficientNet-B3 on the ImageNet-1K benchmark. We report top-1 accuracy on the validation set. For both setting, we also report model size in megabyte (MB) and the compression ratio compared to the original model. Model MB PPL Quant-Noise + Share + Prune Quant-Noise + Share + Prune with STE 10 10 24.2 24.5 Table 11: Performance on Wikitext-103 when using STE in the backward pass of the Layer- Drop pruning noise. 20
Title: Branched Multi-Task Networks: Deciding What Layers To Share: Summary: In the context of multi-task learning, neural networks with branched architectures have often been employed to jointly tackle the tasks at hand. Such ramified networks typically start with a number of shared layers, after which different tasks branch out into their own sequence of layers. Understandably, as the number of possible network configurations is combinatorially large, deciding what layers to share and where to branch out becomes cumbersome. Prior works have either relied on ad hoc methods to determine the level of layer sharing, which is suboptimal, or utilized neural architecture search techniques to establish the network design, which is considerably expensive. In this paper, we go beyond these limitations and propose an approach to automatically construct branched multi-task networks, by leveraging the employed tasks' affinities. Given a specific budget, i.e. number of learnable parameters, the proposed approach generates architectures, in which shallow layers are task-agnostic, whereas deeper ones gradually grow more task-specific. Extensive experimental analysis across numerous, diverse multi-tasking datasets shows that, for a given budget, our method consistently yields networks with the highest performance, while for a certain performance threshold it requires the least amount of learnable parameters. # Branched Multi-Task Networks: Deciding What Layers To Share g u A 3 1 Simon Vandenhende1 simon.vandenhende@kuleuven.be Stamatios Georgoulis2 stamatios.georgoulis@vision.ee.ethz.ch Bert De Brabandere1 bert.debrabandere@esat.kuleuven.be Luc Van Gool12 vangool@vision.ee.ethz.ch 1 PSI-ESAT KU Leuven Leuven, Belgium 2 CVL/TRACE ETH Zurich Zurich, Switzerland ] # V C . s c [ | 5 v 0 2 9 2 0 . 4 0 9 1 : v i X r a # Abstract In the context of multi-task learning, neural networks with branched architectures have often been employed to jointly tackle the tasks at hand. Such ramified networks typically start with a number of shared layers, after which different tasks branch out into their own sequence of layers. Understandably, as the number of possible network config- urations is combinatorially large, deciding what layers to share and where to branch out becomes cumbersome. Prior works have either relied on ad hoc methods to determine the level of layer sharing, which is suboptimal, or utilized neural architecture search tech- niques to establish the network design, which is considerably expensive. In this paper, we go beyond these limitations and propose an approach to automatically construct branched multi-task networks, by leveraging the employed tasks’ affinities. Given a specific bud- get, i.e. number of learnable parameters, the proposed approach generates architectures, in which shallow layers are task-agnostic, whereas deeper ones gradually grow more task-specific. Extensive experimental analysis across numerous, diverse multi-tasking datasets shows that, for a given budget, our method consistently yields networks with the highest performance, while for a certain performance threshold it requires the least amount of learnable parameters. 1 # Introduction Deep neural networks are usually trained to tackle different tasks in isolation. Humans, in contrast, are remarkably good at solving a multitude of tasks concurrently. Biological data processing appears to follow a multi-tasking strategy too; instead of separating tasks and solving them in isolation, different processes seem to share the same early processing layers in the brain – see e.g. V1 in macaques [15]. Drawing inspiration from such observations, deep learning researchers began to develop multi-task networks with branched architectures. As a whole, multi-task networks [6] seek to improve generalization and processing ef- ficiency through the joint learning of related tasks. Compared to the typical learning of separate deep neural networks for each of the individual tasks, multi-task networks come © 2020. The copyright of this document resides with its authors. It may be distributed unchanged freely in print or electronic forms. 1 2 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS with several advantages. First, due to their inherent layer sharing [14, 20, 21, 26, 31], the resulting memory footprint is typically substantially lower. Second, as features in the shared layers do not need to be calculated repeatedly for the different tasks, the overall inference speed is often higher [31, 34]. Finally, multi-task networks may outperform their single-task counterparts [20, 32, 43, 44]. Evidently, there is merit in utilizing multi-task networks. When it comes to designing them, however, a significant challenge is to decide on the layers that need to be shared among tasks. Assuming a hard parameter sharing setting1, the number of possible network configurations grows quickly with the number of tasks. As a result, a trial-and-error procedure to define the optimal architecture becomes unwieldy. Re- sorting to neural architecture search [11] techniques is not a viable option too, as in this case, the layer sharing has to be jointly optimized with the layers types, their connectivity, etc., rendering the problem considerably expensive. Instead, researchers have recently ex- plored more viable alternatives, like routing [39], stochastic filter grouping [5], and feature partitioning [35], which are, however, closer to the soft parameter sharing setting. Previous works on hard parameter sharing opted for the simple strategy of sharing the initial layers in the network, after which all tasks branch out simultaneously. The point at which the branch- ing occurs is usually determined ad hoc [14, 20, 43]. This situation hurts performance, as a suboptimal grouping of tasks can lead to the sharing of information between unrelated tasks, known as negative transfer [47]. In this paper, we go beyond the aforementioned limitations and propose a novel approach to decide on the degree of layer sharing between multiple visual recognition tasks in order to eliminate the need for manual exploration. To this end, we base the layer sharing on measur- able levels of task affinity or task relatedness: two tasks are strongly related, if their single task models rely on a similar set of features. [46] quantified this property by measuring the performance when solving a task using a variable sets of layers from a model pretrained on a different task. However, their approach is considerably expensive, as it scales quadrati- cally with the number of tasks. Recently, [10] proposed a more efficient alternative that uses representation similarity analysis (RSA) to obtain a measure of task affinity, by computing correlations between models pretrained on different tasks. Given a dataset and a number of tasks, our approach uses RSA to assess the task affinity at arbitrary locations in a neural network. The task affinity scores are then used to construct a branched multi-task network in a fully automated manner. In particular, our task clustering algorithm groups similar tasks together in common branches, and separates dissimilar tasks by assigning them to different branches, thereby reducing the negative transfer between tasks. Additionally, our method allows to trade network complexity against task similarity. We provide extensive empiri- cal evaluation of our method, showing its superiority in terms of multi-task performance vs computational resources. # 2 Related work Multi-task learning. Multi-task learning (MTL) [6, 41] is associated with the concept of jointly learning multiple tasks under a single model. This comes with several advantages, as described above. Early work on MTL often relied on sparsity constraints [4, 19, 27, 30, 45] 1In this setting, the input is first encoded through a stack of shared layers, after which tasks branch out into their own sequence of task-specific layers [14, 20, 21, 31, 43]. Alternatively, a set of task-specific networks can be used in conjunction with a feature sharing mechanism [26, 33, 42]. The latter approach is termed soft parameter sharing in the literature. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS to select a small subset of features that could be shared among all tasks. However, this can lead to negative transfer when not all tasks are related to each other. A general solution to this problem is to cluster tasks based on prior knowledge about their similarity or relatedness [1, 3, 12, 22, 48]. In the deep learning era, MTL models can typically be classified as utilizing soft or hard parameter sharing. In soft parameter sharing, each task is assigned its own set of parameters and a feature sharing mechanism handles the cross-task talk. Cross-stitch networks [33] softly share their features among tasks, by using a linear combination of the activations found in multiple single task networks. Sluice networks [42] extend cross-stitch networks and allow to learn the selective sharing of layers, subspaces and skip connections. In a different vein, multi-task attention networks [26] use an attention mechanism to share a general feature pool amongst task-specific networks. In general, MTL networks using soft parameter sharing are limited in terms of scalability, as the size of the network tends to grow linearly with the number of tasks. In hard parameter sharing, the parameter set is divided into shared and task-specific pa- rameters. MTL models using hard parameter sharing are often based on a generic framework with a shared off-the-shelf encoder, followed by task-specific decoder networks [7, 20, 34, 43]. Multilinear relationship networks [29] extend this framework by placing tensor normal priors on the parameter set of the fully connected layers. [14] proposed the construction of a hierarchical network, which predicts increasingly difficult tasks at deeper layers. A limi- tation of the aforementioned approaches is that the branching points are determined ad hoc, which can easily lead to negative transfer if the predefined task groupings are suboptimal. In contrast, in our branched multi-task networks, the degree of layer sharing is automatically determined in a principled way, based on task affinities. Our work bears some similarity to fully-adaptive feature sharing [31] (FAFS), which starts from a thin network where tasks initially share all layers, but the final one, and dy- namically grows the model in a greedy layer-by-layer fashion. Task groupings, in this case, are decided on the probability of concurrently simple or difficult examples across tasks. Dif- ferently, (1) our method clusters tasks based on feature affinity scores, rather than example difficulty, which is shown to achieve better results for a variety of datasets; (2) the tree struc- ture is determined offline using the precalculated affinities for the whole network, and not online in a greedy layer-by-layer fashion, which promotes task groupings that are optimal in a global, rather than local, sense. Neural architecture search. Neural architecture search (NAS) [11] aims to automate the construction of the network architecture. Different algorithms can be characterized based on their search space, search strategy or performance estimation strategy. Most existing works on NAS, however, are limited to task-specific models [24, 25, 37, 38, 49]. This is to be expected as when using NAS for MTL, layer sharing has to be jointly optimized with the layers types, their connectivity, etc., rendering the problem considerably expensive. To alleviate the heavy computation burden, a recent work [23] implemented an evolutionary architecture search for multi-task networks, while other researchers explored more viable alternatives, like routing [39], stochastic filter grouping [5], and feature partitioning [35]. In contrast to traditional NAS, the proposed methods do not build the architecture from scratch, but rather start from a predefined backbone network for which a layer sharing scheme is automatically determined. Transfer learning. Transfer learning [36] uses the knowledge obtained when solving one task, and applies it to a different but related task. Our work is loosely related to transfer learning, as we use it to measure levels of task affinity. [46] provided a taxonomy for task 3 4 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS Algorithm 1 Branched Multi-Task Networks - Task clustering 1: Input: Tasks T , K images I, a sharable encoder E with D locations where we can branch, a set of task specific decoders Dt and a computational budget C. 2: for t in T do 3: 4: 5: end for 6: Ad,i, j ← rs 7: D = 1 − A 8: Return: Task-grouping with minimal task dissimilarity that fits within C Train the encoder E and task-specific decoder Dt for task t. RDMt ← RDM(E, D, I) > RDM for task f. 6: Agij Ts (triu (RDM }...) ,triu (RDM j...)) for t;,t; in T and d in locations > Task affinity 7, D=1-A > Task dissimilarity transfer learning to quantify such relationships. However, their approach scales unfavorably w.r.t. the number of tasks, and we opted for a more efficient alternative proposed by [10]. The latter uses RSA to obtain a measure of task affinity, by computing correlations between models pretrained on different tasks. In our method, we use the performance metric from their work to compare the usefulness of different feature sets for solving a particular task. Loss weighting. One of the known challenges of jointly learning multiple tasks is prop- erly weighting the loss functions associated with the individual tasks. Early work [20] used the homoscedastic uncertainty of each task to weigh the losses. Gradient normalization [7] balances the learning of tasks by dynamically adapting the gradient magnitudes in the net- work. Liu et al. [26] weigh the losses to match the pace at which different tasks are learned. Dynamic task prioritization [14] prioritizes the learning of difficult tasks. [43] cast MTL as a multi-objective optimization problem, with the overall objective of finding a Pareto optimal solution. Note that, addressing the loss weighting issue in MTL is out of the scope of this work. In fact, all our experiments are based on a simple uniform loss weighing scheme. # 3 Method In this paper, we aim to jointly solve N different visual recognition tasks T = {t1, . . . ,tN} given a computational budget C, i.e. number of parameters or FLOPS. Consider a backbone architecture: an encoder, consisting of a sequence of shared layers or blocks fl, followed by a decoder with a few task-specific layers. We assume an appropriate structure for layer sharing to take the shape of a tree. In particular, the first layers are shared by all tasks, while later layers gradually split off as they show more task-specific behavior. The proposed method aims to find an effective task grouping for the sharable layers fl of the encoder, i.e. grouping related tasks together in the same branches of the tree. When two tasks are strongly related, we expect their single-task models to rely on a similar feature set [46]. Based on this viewpoint, the proposed method derives a task affinity score at various locations in the sharable encoder. The number of locations D can be freely determined as the number of candidate branching locations. As such, the resulting task affinity scores are used for the automated construction of a branched multi-task network that fits the computational budget C. Fig. 3 illustrates our pipeline, while Algorithm 1 summarizes the whole procedure. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS Train single Representation Similarity Analysis at D locations task networks Task i FE) 3 Correlation —> —> > Tesk/ me > fom -Oeston - ve) D cates x Task N Lt P imei | > a task networks Task i Me FE) 3 Correlation —> —> > Tesk/ me > fom -Oeston - @ © ve) D cates x Task N Lt P imei | > a @) @) ) Figure 1: Pipeline overview. (left) We train a single-task model for every task t ∈ T . (middle) We use RSA to measure the task affinity at D predefined locations in the sharable encoder. In particular, we calculate the representation dissimilarity matrices (RDM) for the features at D locations using K images, which gives a D × K × K tensor per task. (right) The affinity tensor A is found by calculating the correlation between the RDM matrices, which results in a three-dimensional tensor of size D × N × N, with N the number of tasks. Our Figure pipeline’s output is a branched multi- task network, similar to how NAS tech- niques output sample An architectures. example branched multi-task network is visualized here. Figure 3: The proposed method: (a) calculate task affinities at various locations in the sharable encoder; (b) build a branched multi-task network based on the computed affinities. # 3.1 Calculate task affinity scores As mentioned, we rely on RSA to measure task affinity scores. This technique has been widely adopted in the field of neuroscience to draw comparisons between behavioral models and brain activity. Inspired by how [10] applied RSA to select tasks for transfer learning, we use the technique to assess the task affinity at predefined locations in the sharable encoder. Consequently, using the measured levels of task affinity, tasks are assigned in the same or different branches of a branched multi-task network, subject to the computational budget C. The procedure to calculate the task affinity scores is the following. As a first step, we train a single-task model for each task ti ∈ T . The single-task models use an identical encoder E - made of all sharable layers fl - followed by a task-specific decoder Dti. The decoder contains only task-specific operations and is assumed to be significantly smaller in size compared to the encoder. As an example, consider jointly solving a classification and a dense prediction task. Some fully connected layers followed by a softmax operation are typically needed for the classification task, while an additional decoding step with some upscaling operations is required for the dense prediction task. Of course, the appropriate loss functions are applied in each case. Such operations are part of the task-specific decoder Dti. The different single-task networks are trained under the same conditions. At the second step, we choose D locations in the sharable encoder E where we calculate a two-dimensional task affinity matrix of size N × N. When concatenated, this results in a 5 6 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS three-dimensional tensor A of size D × N × N that holds the task affinities at the selected lo- cations. To calculate these task affinities, we have to compare the representation dissimilarity matrices (RDM) of the single-task networks - trained in the previous step - at the specified D locations. To do this, a held-out subset of K images is required. The latter images serve to compare the dissimilarity of their feature representations in the single-task networks for every pair of images. Specifically, for every task ti, we characterize these learned feature representations at the selected locations by filling a tensor of size D × K × K. This tensor contains the dissimilarity scores 1 − ρ between feature representations, with ρ the Pearson correlation coefficient. Specifically, RDMd,i, j is found by calculating the dissimilarity score between the features at location d for image i and j. The 3-D tensors are linearized to 1-D tensors to calculate the pearson correlation coefficient. For a specific location d in the network, the computed RDMs are symmetrical, with a diagonal of zeros. For every such location, we measure the similarity between the upper or lower triangular part of the RDMs belonging to the different single-task networks. We use the Spearman’s correlation coefficient rs to measure similarity. When repeated for every pair of tasks, at a specific location d, the result is a symmetrical matrix of size N × N, with a diagonal of ones. Concatenating over the D locations in the sharable encoder, we end up with the desired task affinity tensor of size D × N × N. Note that, in contrast to prior work [31], the described method focuses on the features used to solve the single tasks, rather than the examples and how easy or hard they are across tasks, which is shown to result in better task groupings in Section 4. Furthermore, the computational overhead to determine the task affinity scores based on feature correlations is negligible. We conclude that the computational cost of the method boils down to pre-training N single task networks. A detailed computational cost analysis can be found in the supplementary materials. Other measures of task similarity [2, 9] probed the features from a network pre-trained on ImageNet. This avoids the need to pre-train a set of single-task networks first. However, in this case, the task dictionaries only consisted of various, related classification problems. Differently, we consider more diverse, and loosely related task (see Section 4). In our case, it is arguably more important to learn the task-specific information needed to solve a task. This motivates the use of pre-trained single-task networks. # 3.2 Construct a branched multi-task network Given a computational budget C, we need to derive how the layers (or blocks) fl in the sharable encoder E should be shared among the tasks in T . Each layer fl ∈ E is represented as a node in the tree, i.e. the root node contains the first layer f0, and nodes at depth l contain layer(s) fl. The granularity of the layers fl corresponds to the intervals at which we measure the task affinity in the sharable encoder, i.e. the D locations. When the encoder is split into bl branches at depth l, this is equivalent to a node at depth l having bl children. The leaves of the tree contain the task-specific decoders Dt . Fig. 2 shows an example of such a tree using the aforementioned notation. Each node is responsible for solving a unique subset of tasks. The branched multi-task network is built with the intention to separate dissimilar tasks by assigning them to separate branches. To this end, we define the dissimilarity score be- tween two tasks ti and t j at location d as 1 − Ad,i, j, with A the task affinity tensor2. The branched multi-task network is found by minimizing the sum of the task dissimilarity scores at every location in the sharable encoder. In contrast to prior work [31], the task affinity (and 2This is not to be confused with the dissimilarity score used to calculate the RDM elements RDMd,i, j. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS dissimilarity) scores are calculated a priori. This allows us to determine the task clustering offline. Since the number of tasks is finite, we can enumerate all possible trees that fall within the given computational budget C. Finally, we select the tree that minimizes the task dissimilarity score. The task dissimilarity score of a tree is defined as Ccluster = ∑l Cl cluster, where Cl cluster is found by averaging the maximum distance between the dissimilarity scores of the elements in every cluster. The use of the maximum distance encourages the separation of dissimilar tasks. By taking into account the clustering cost at all depths, the procedure can find a task grouping that is considered optimal in a global sense. This is in contrast to the greedy approach in [31], which only minimizes the task dissimilarity locally, i.e. at isolated locations in the network. # 4 Experiments In this section, we evaluate the proposed method on a number of diverse multi-tasking datasets, that range from real to semi-real data, from few to many tasks, from dense predic- tion to classification tasks, and so on. For every experiment, we describe the most important elements of the setup. We report the number of parameters (#P) for every model to facilitate a fair comparison. Additional implementation details can be found in the supplementary materials. # 4.1 Cityscapes Dataset. The Cityscapes dataset [8] considers the scenario of urban scene understanding. The train, validation and test set contain respectively 2975, 500 and 1525 real images, taken by driving a car in Central European cities. It considers a few dense prediction tasks: se- mantic segmentation (S), instance segmentation (I) and monocular depth estimation (D). As in prior works [20, 43], we use a ResNet-50 encoder with dilated convolutions, followed by a Pyramid Spatial Pooling (PSP) [17] decoder. Every input image is rescaled to 512 x 256 pixels. We reuse the approach from [20] for the instance segmentation task, i.e. we consider the proxy task of regressing each pixel to the center of the instance it belongs to. Results. We measure the task affinity after every block (1 to 4) in the ResNet-50 model (see Fig. 4). The task affinity decreases in the deeper layers, due to the features becoming more task-specific. We compare the performance of the task groupings generated by our method with those by other approaches. As in [32], the performance of a multi-task model m is defined as the average per-task performance drop/increase w.r.t. a single-task baseline b. We trained all possible task groupings that can be derived from branching the model in the last three ResNet blocks. Fig. 5 visualizes performance vs number of parameters for the trained architectures. Depending on the available computational budget C, our method generates a specific task grouping. We visualize these generated groupings as a blue path in Fig. 5, when gradually increasing the computational budget C. Similarly, we consider the task groupings when branching the model based on the task affinity measure proposed by FAFS [31] (green path). We find that, in comparison, the task groupings devised by our method achieve higher performance within a given computational budget C. Furthermore, in the majority of cases, for a fixed budget C the proposed method is capable of selecting the best performing task grouping w.r.t. performance vs parameters metric (blue vs other). We also compare our branched multi-task networks with cross-stitch networks [33], NDDR-CNNs [13] and MTAN [26] in Table 2. While cross-stitch nets and NDDR-CNNs 7 8 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS 0.8 > 2 06 S “4 2 04 e 02 — Seg+Dep | “| | —— Seg+Inst ——Inst+Dep oF 3 3 4 0.5 T 0.0 7 4 05 | e = -LOF ee 4 iS a are | = | J e in Single-Task Bl I —— Ours | —— FAFS 3.5 b —— Other Groupings | | 1 I I 100 120 140 160 Number of parameters (M) # Ea] Measurement after ResNet block Figure 4: Task affinity scores measured after each ResNet-50 block on Cityscapes. Figure 5: Number of parameters versus multi-task performance on Cityscapes for different task groupings. The ’Other Group- ings’ contain any remaining tree structures that can be found by randomly branching the model in the last three ResNet blocks. give higher multi-task performance, attributed to their computationally expensive soft pa- rameter sharing setting, our branched networks can strike a better trade-off between the per- formance and number of parameters. In particular, we can effectively sample architectures which lie between the extremes of a baseline multi-task model and a cross-stitch or NDDR- CNN architecture. Finally, our models provide a more computationally efficient alternative to the MTAN model, which reports similar performance while using more parameters. # 4.2 Taskonomy Dataset. The Taskonomy dataset [46] contains semi-real images of indoor scenes, annotated for 26 (dense prediction, classification, etc.) tasks. Out of the available tasks, we select scene categorization (C), semantic segmentation (S), edge detection (E), monocular depth estimation (D) and keypoint detection (K). The task dictionary was selected to be as diverse as possible, while still keeping the total number of tasks reasonable for all computations. We use the tiny split of the dataset, containing 275k train, 52k validation and 54k test images. We reuse the architecture and training setup from [46]: the encoder is based on ResNet-50; a 15-layer fully-convolutional decoder is used for the pixel-to-pixel prediction tasks. Results. The task affinity is again measured after every ResNet block. Since the number of tasks increased to five, it is very expensive to train all task groupings exhaustively, as done above. Instead, we limit ourselves to three architectures that are generated when gradually increasing the parameter budget. As before, we compare our task groupings against the method from [31]. The numerical results can be found in Table 1. The task groupings themselves are shown in the supplementary materials. The effect of the employed task grouping technique can be seen from comparing the performance of our models against the corresponding FAFS models, generated by [31]. The latter are consistently outperformed by our models. Compared to the results on Cityscapes VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS Method Single task MTL baseline MTAN Cross-stitch NDDR-CNN FAFS - 1 FAFS - 2 FAFS - 3 Ours - 1 Ours - 2 Ours - 3 D (L1)↓ 0.60 0.75 0.71 0.61 0.66 0.74 0.80 0.74 0.76 0.74 0.74 S (IoU)↑ 43.5 47.8 43.8 44.0 45.9 46.1 39.9 46.1 47.6 48.0 47.9 C (Top-5)↑ 66.0 56.0 59.6 58.2 64.5 62.7 62.4 64.9 63.3 63.6 64.5 E (L1)↓ 0.99 1.37 1.86 1.35 1.05 1.30 1.68 1.05 1.12 0.96 0.94 K (L1)↓ 0.23 0.34 0.40 0.50 0.45 0.39 0.52 0.27 0.29 0.35 0.26 #P (M) 224 130 158 224 258 174 188 196 174 188 196 ∆MT L (%)↑ + 0.00 - 22.50 -37.36 - 32.29 - 21.02 - 24.5 - 48.32 - 8.48 - 11.88 - 12.66 - 4.93 Table 1: Results on the tiny Taskonomy test set. The results for edge (E) and keypoints (K) detection were multiplied by a factor of 100 for better readability. The FAFS models refer to generating the task groupings with the task affinity technique proposed by [31]. (Fig. 5), we find that the multi-task performance is much more susceptible to the employed task groupings, possibly due to negative transfer. Furthermore, we observe that none of the soft parmeter sharing models can handle the larger, more diverse task dictionary: the perfor- mance decreases when using these models, while the number of parameters increases. This is in contrast to our branched multi-task networks, which seem to handle the diverse set of tasks rather positively. As opposed to [46], but in accordance with [32], we show that it is possible to solve many heterogeneous tasks simultaneously when the negative transfer is limited, by separating dissimilar tasks from each other in our case. In fact, our approach is the first to show such consistent performance across different multi-tasking scenarios and datasets. Existing approaches seem to be tailored for particular cases, e.g. few/correlated tasks, synthetic-like data, binary classification only tasks, etc., whereas we show stable per- formance across the board of different experimental setups. # 4.3 CelebA Dataset. The CelebA dataset [28] contains over 200k images of celebrities, labeled with 40 facial attribute categories. The training, validation and test set contain 160k, 20k and 20k images respectively. We treat the prediction of each facial attribute as a single binary classification task, as in [18, 31, 43]. To ensure a fair comparison: we reuse the thin-ω model from [31] in our experiments; the parameter budget C is set for the model to have the same amount of parameters as prior work. Results. Table 3 shows the results on the CelebA test set. Our branched multi-task net- works outperform earlier works [18, 31] when using a similar amount of parameters. Since the Ours-32 model (i.e. ω is 32) only differs from the FAFS model on the employed task grouping technique, we can conclude that the proposed method devises more effective task groupings for the attribute classification tasks on CelebA. Furthermore, the Ours-32 model performs on par with the VGG-16 model, while using 64 times less parameters. We also compare our results with the ResNet-18 model from [43]. The Ours-64 model performs 1.35% better compared to the ResNet-18 model when trained with a uniform loss weigh- ing scheme. More noticeably, the Ours-64 model performs on par with the state-of-the-art ResNet-18 model that was trained with the MGDA loss weighing scheme from [43], while at the same time using 31% less parameters (11.2 vs 7.7 M). 9 10 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS Method Single task MTL baseline MTAN Cross-stitch NDDR-CNN Ours - 1 Ours - 2 Ours - 3 S (IoU)↑ 65.2 61.5 62.8 65.1 65.6 62.1 62.7 64.1 I (px)↓ 11.7 11.8 11.8 11.6 11.6 11.7 11.7 11.6 D (px)↓ 2.57 2.66 2.66 2.55 2.54 2.66 2.62 2.62 #P (M) 138 92 113 140 190 107 114 116 ∆MT L (%)↑ +0.00 -3.33 -2.53 +0.42 +0.89 -2.68 -1.84 -0.96 Method MOON [40] Independent Group [16] MCNN [16] MCNN-AUX [16] VGG-16 [31] FAFS [31] GNAS [16] Res-18 (Uniform) [43] Res-18 (MGDA) [43] Ours-32 Ours-64 Acc. (%) 90.94 91.06 91.26 91.29 91.44 90.79 91.63 90.38 91.75 91.46 91.73 #P (M) 119.73 - - - 134.41 2.09 7.73 11.2 11.2 2.20 7.73 Table 2: Results on the Cityscapes validation set. Table 3: Results on the CelebA test set. The Ours-32, Ours-64 architectures are found by optimizing the task clustering for the pa- rameter budget that is used in the FAFS, GNAS model respectively. # 5 Conclusion In this paper, we introduced a principled approach to automatically construct branched multi- task networks for a given computational budget. To this end, we leverage the employed tasks’ affinities as a quantifiable measure for layer sharing. The proposed approach can be seen as an abstraction of NAS for MTL, where only layer sharing is optimized, without having to jointly optimize the layers types, their connectivity, etc., as done in traditional NAS, which would render the problem considerably expensive. Extensive experimental analysis shows that our method outperforms existing ones w.r.t. the important metric of multi-tasking per- formance vs number of parameters, while at the same time showing consistent results across a diverse set of multi-tasking scenarios and datasets. Acknowledgment This work is sponsored by the Flemish Government under the Artificiele Intelligentie (AI) Vlaanderen programme. The authors also acknowledge support by Toyota via the TRACE project and MACCHINA (KU Leuven, C14/18/065). VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS # A Supplementary Materials # A.1 Cityscapes The encoder is a ResNet-50 model with dilated convolutions [? ], pre-trained on ImageNet. We use a PSP module [17] for the task-specific decoders. Every input image is rescaled to 512 x 256 pixels. We upsample the output of the PSP decoders back to the input resolu- tion during training. The outputs are upsampled to 2048 x 1024 pixels during testing. The semantic segmentation task is learned with a weighted pixel-wise cross-entropy loss. We reuse the approach from [20] for the instance segmentation task, i.e. we consider the proxy task of regressing each pixel to the center of the instance it belongs to. The depth estimation task is learned using an L1 loss. The losses are normalized to avoid having the loss of one task overwhelm the others during training. The hyperparameters were optimized with a grid search procedure to ensure a fair comparison across all compared approaches. Single-task models We tested batches of size 4, 6 and 8, poly learning rate decay vs step learning rate decay with decay factor 10 and step size 30 epochs, and Adam (initial learning rates 2e-4, 1e-4, 5e-5, 1e-5) vs stochastic gradient descent with momentum 0.9 (initial learn- ing rates 5e-2, 1e-2, 5e-3, 1e-3). This accounts for 48 hyperparameter settings in total. We repeated this procedure for every single task (semantic segmentation, instance segmentation and monocular depth estimation). Baseline multi-task network We train with the same set of hyperparameters as before, i.e. 48 settings in total. We calculate the multi-task performance in accordance with [32]. In particular, the multi-task performance of a model m is measured as the average per-task performance increase/drop w.r.t. the single task models b: An = (=1)" (Mini —Mb.i) /Mp.i, (1) T =] sI- where li = 1 if a lower value means better for measure Mi of task i, and 0 otherwise. Branched multi-task network We reuse the hyperparameter setting with the best result for the baseline multi-task network. The branched multi-task architectures that were used for the quantitative evaluation on Cityscapes are shown in Fig. S4. 11 12 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS # o # 2 a ResNet-50-Block 1 ResNet-50-Block 1 ResNet-50-Block 1 ® a ResNet-50-Block 2 ResNet-50-Block 2 ResNet-50-Block 2 ResNet-50-Block 3 ResNet-50-Block 3 ResNet-50-Block 3 eee ResNet-50-Block 4 ResNet-50-Block 4 ResNet-50-Block 4 Task Specific Decoder Task Specific Decoder Task Specific Decoder ot, Inst. Seg. eee Inst. Seg. e—e— 2 2 o 2 oe 2 Ae A BR aA & P g A g A a a G # Figure S1: Ours - 1 Figure S2: Ours - 2 # Figure S3: Ours - 3 Figure S4: Branched multi-task networks on Cityscapes that were generated by our method. Cross-stitch networks / NDDR-CNN We insert a cross-stitch/NDDR unit after every ResNet block. We also tried to leave out the cross-stitch/NDDR unit after the final ResNet block, but this decreased performance. We tested two different initialization schemes for the weights in the cross-stitch/NDDR units, i.e. α = 0.8, β = 0.1 and α = 0.9, β = 0.05. The model weights were initialized from the set of the best single-task models above. We found that the Adam optimizer broke the initialization and refrained from using it. The best results were obtained with stochastic gradient descent with initial learning rate 1e-3 and momentum 0.9. As also done in [13, 33], we set the weights of these units to have a learning rate that is 100 times higher than the base learning rate. MTAN We re-implemented the MTAN model [26] using a ResNet-50 backbone based on the code that was made publicly available by the authors. We obtained our best results when using an Adam optimizer. Other hyperparameters where set in accordance with our other experiments. # A.2 Taskonomy We reuse the setup from [46]. All input images were rescaled to 256 x 256 pixels. We use a ResNet-50 encoder and replace the last stride 2 convolution by a stride 1 convolution. A 15-layer fully-convolutional decoder is used for the pixel-to-pixel prediction tasks. The decoder is composed of five convolutional layers followed by alternating convolutional and transposed convolutional layers. We use ReLU as non-linearity. Batch normalization is included in every layer except for the output layer. We use Kaiming He’s initialization for both encoder and decoder. We use an L1 loss for the depth (D), edge detection (E) and keypoint detection (K) tasks. The scene categorization task is learned with a KL-divergence loss. We report performance on the scene categorization task by measuring the overlap in top-5 classes between the predictions and ground truth. The multi-task models were optimized with task weights ws = 1, wd = 1, wk = 10, we = 10 and wc = 1. Notice that the heatmaps were linearly rescaled to lie between 0 and 1. During training we normalize the depth map by the standard deviation. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS ResNet-50-Block 1 ResNet-50-Block 1 ResNet-50-Block 1 ResNet-50-Block 2 ResNet-50-Block 2 ResNet-50-Block 2 '@ ResNet-50-Block 3 ResNet-50-Block 3 ResNet-50-Block 3 ResNet-50-Block 4 i ResNet-50-Block 4 J J reaver se tick 4 eee ! ‘Task Specific Decoder @ » 8 J Jan Specific Decoder st | jx Specific Decoder 1o} ss OxNn gy Oo. 2 n _ ee # a Figure S5: Ours - 1 # Figure S6: Ours - 2 # Figure S7: Ours - 3 Figure S8: Task groupings generated by our method on the Taskonomy dataset. Single-task models We use an Adam optimizer with initial learning rate 1e-4. The learning rate is decayed by a factor of10 after 80000 iterations. We train the model for 120000 iterations. The batch size is set to 32. No additional data augmentation is applied. The weight decay term is set to 1e-4. Baseline multi-task model We use the same optimization procedure as for the single-task models. The multi-task performance is calculated using Eq. 1. Branched multi-task models We use the same optimization procedure as for the single- task models. The architectures that were generated by our method are shown in Fig. S8. Fig. S12 shows the architectures that are found when using the task grouping method from [31]. We show some of the predictions made by our third branched multi-task network in Fig. S16 for the purpose of qualitative evaluation. # ResNet-50-Block 1 ResNet-50-Block 1 e e ResNet-50-Block 1 ’ ResNet-50-Block 2 ResNet-50-Block 2 ResNet-50-Block 2 ResNet-50-Block 8 ResNet-50-Block 3 ResNet-50-Block 3 esNet-50-Block 3 j ResNet-50-Block 4 J J ResNet-50-Block 4 @ @ ResNet-50-Block 4 \ ! ‘Task Specific Decoder @ J J Jan Specific Decoder ; | nu Specific Decoder ‘. a n nO Aa mR “MD 2aAD # Figure S9: FAFS - 1 Figure S10: FAFS - 2 # Figure S11: FAFS - 3 Figure S12: Task groupings generated on the Taskonomy dataset using the FAFS method from [31]. Cross-stitch networks / NDDR-CNN We reuse the hyperparameter settings that were found optimal on Cityscapes. Note that, these are in agreement with what the authors re- ported in their original papers. The weights of the cross-stitch/NDDR units were initialized with α = 0.8 and β = 0.05. 13 14 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS MTAN Similar to the other models, we reused the hyperparameter settings that were found optimal on Cityscapes. K S Figure S13: Example - 1 E K S Figure S14: Example - 2 E Figure S15: Example - 3 Figure S16: Predictions made by our branched multi-task network on images from the Taskonomy test set. # A.3 CelebA We reuse the thin-ω model from [31]. The CNN architecture is based on the VGG-16 model [? ]. The number of convolutional features is set to the minimum between ω and the width of the corresponding layer in the VGG-16 model. The fully connected layers contain 2 · ω features. We train the branched multi-task network using stochastic gradient descent with momentum 0.9 and initial learning rate 0.05. We use batches of size 32 and weight decay 0.0001. The model is trained for 120000 iterations and the learning rate di- vided by 10 every 40000 iterations. The loss function is a sigmoid cross-entropy loss with uniform weighing scheme. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS Figure S17: Grouping of 40 person attribute classification tasks on CelebA in a thin VGG-16 architecture. # A.4 Computational Analysis We provide an analysis to identify the computational costs related to the different steps when calculating the task affinity scores. We adopt the notation from the main paper. The following three steps can be identified: • Train N single task networks. It is possible to use a subset of the available training data to reduce the training time. We verified that using a random subset of 500 train images on Cityscapes resulted in the same task groupings. • Compute the RDM matrix for all N networks at D pre-determined layers. This re- quires to compute the features for a set of K images at the D pre-determined layers in all N networks. The K images are usually taken as held-out images from the train set. We used K = 500 in our experiments. In practice this means that computing the image features comes down to evaluating every model on K images. The computed features are stored on disk afterwards. The RDM matrices are calculated from the stored features. This requires to calculate N × D × K × K correlations between two feature vectors (can be performed in parallel). We conclude that the computation time is negligible in comparison to training the single task networks. • Compute the RSA matrix at D locations for all N tasks. This requires to calculate D × N × N correlations between the lower triangle part of the K × K RDM matrices. The computation time is negligible in comparison to training the single task networks. We conclude that the computational cost of our method boils down to training N sin- gle task networks plus some overhead. Notice that cross-stitch networks [33] and NDDR- CNNs [13] also pre-train a set of single-task networks first, before combining them together using a soft parameter sharing mechanism. We conclude that our method only suffers from minor computational overhead compared to these methods. 15 16 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS # References [1] Jacob Abernethy, Francis Bach, Theodoros Evgeniou, and Jean-Philippe Vert. A new approach to collaborative filtering: Operator estimation with spectral regularization. JMLR, 10(Mar):803–826, 2009. [2] Alessandro Achille, Michael Lam, Rahul Tewari, Avinash Ravichandran, Subhransu Maji, Charless C Fowlkes, Stefano Soatto, and Pietro Perona. Task2vec: Task em- bedding for meta-learning. In Proceedings of the IEEE International Conference on Computer Vision, pages 6430–6439, 2019. [3] Arvind Agarwal, Samuel Gerber, and Hal Daume. Learning multiple tasks using man- ifold regularization. In NIPS, 2010. [4] Andreas Argyriou, Theodoros Evgeniou, and Massimiliano Pontil. Multi-task feature learning. In NIPS, 2007. [5] Felix JS Bragman, Ryutaro Tanno, Sebastien Ourselin, Daniel C Alexander, and M Jorge Cardoso. Stochastic filter groups for multi-task cnns: Learning specialist and generalist convolution kernels. In ICCV, 2019. [6] Rich Caruana. Multitask learning. Machine learning, 28(1):41–75, 1997. [7] Zhao Chen, Vijay Badrinarayanan, Chen-Yu Lee, and Andrew Rabinovich. Gradnorm: In Gradient normalization for adaptive loss balancing in deep multitask networks. ICML, 2018. [8] Marius Cordts, Mohamed Omran, Sebastian Ramos, Timo Rehfeld, Markus Enzweiler, Rodrigo Benenson, Uwe Franke, Stefan Roth, and Bernt Schiele. The cityscapes dataset for semantic urban scene understanding. In CVPR, 2016. [9] Yin Cui, Yang Song, Chen Sun, Andrew Howard, and Serge Belongie. Large scale In Proceedings of fine-grained categorization and domain-specific transfer learning. the IEEE conference on computer vision and pattern recognition, pages 4109–4118, 2018. [10] Kshitij Dwivedi and Gemma Roig. Representation similarity analysis for efficient task taxonomy & transfer learning. In CVPR, pages 12387–12396, 2019. [11] Thomas Elsken, Jan Hendrik Metzen, and Frank Hutter. Neural architecture search: A survey. JMLR, 20(55):1–21, 2019. [12] Theodoros Evgeniou and Massimiliano Pontil. Regularized multi–task learning. KDD, 2004. In [13] Yuan Gao, Jiayi Ma, Mingbo Zhao, Wei Liu, and Alan L Yuille. Nddr-cnn: Layerwise feature fusing in multi-task cnns by neural discriminative dimensionality reduction. In CVPR, pages 3205–3214, 2019. [14] Michelle Guo, Albert Haque, De-An Huang, Serena Yeung, and Li Fei-Fei. Dynamic task prioritization for multitask learning. In ECCV, 2018. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS [15] Moshe Gur and D Max Snodderly. Direction selectivity in v1 of alert monkeys: evi- dence for parallel pathways for motion processing. The Journal of physiology, 585(2): 383–400, 2007. [16] Emily M Hand and Rama Chellappa. Attributes for improved attributes: A multi-task network utilizing implicit and explicit relationships for facial attribute classification. In AAAI, 2017. [17] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Spatial pyramid pooling in deep convolutional networks for visual recognition. IEEE transactions on pattern analysis and machine intelligence, 37(9):1904–1916, 2015. [18] Siyu Huang, Xi Li, Zhiqi Cheng, Alexander Hauptmann, et al. Gnas: A greedy neural architecture search method for multi-attribute learning. 2018. [19] Ali Jalali, Sujay Sanghavi, Chao Ruan, and Pradeep K Ravikumar. A dirty model for multi-task learning. In NIPS, 2010. [20] Alex Kendall, Yarin Gal, and Roberto Cipolla. Multi-task learning using uncertainty to weigh losses for scene geometry and semantics. In CVPR, 2018. [21] Iasonas Kokkinos. Ubernet: Training a universal convolutional neural network for low-, mid-, and high-level vision using diverse datasets and limited memory. In CVPR, 2017. [22] Abhishek Kumar and Hal Daume III. Learning task grouping and overlap in multi-task learning. 2012. [23] Jason Liang, Elliot Meyerson, and Risto Miikkulainen. Evolutionary architecture search for deep multitask networks. In GECCO, 2018. [24] Chenxi Liu, Barret Zoph, Maxim Neumann, Jonathon Shlens, Wei Hua, Li-Jia Li, Li Fei-Fei, Alan Yuille, Jonathan Huang, and Kevin Murphy. Progressive neural ar- chitecture search. In ECCV, 2018. [25] Hanxiao Liu, Karen Simonyan, Oriol Vinyals, Chrisantha Fernando, and Koray Kavukcuoglu. Hierarchical representations for efficient architecture search. In ICLR, 2018. [26] Shikun Liu, Edward Johns, and Andrew J Davison. End-to-end multi-task learning with attention. In CVPR, 2019. [27] Sulin Liu, Sinno Jialin Pan, and Qirong Ho. Distributed multi-task relationship learn- ing. In KDD, 2017. [28] Ziwei Liu, Ping Luo, Xiaogang Wang, and Xiaoou Tang. Deep learning face attributes in the wild. In ICCV, 2015. [29] Mingsheng Long, Zhangjie Cao, Jianmin Wang, and S Yu Philip. Learning multiple tasks with multilinear relationship networks. In NIPS, pages 1594–1603, 2017. [30] Karim Lounici, Massimiliano Pontil, Alexandre B Tsybakov, and Sara Van De Geer. Taking advantage of sparsity in multi-task learning. In COLT, 2009. 17 18 VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS [31] Yongxi Lu, Abhishek Kumar, Shuangfei Zhai, Yu Cheng, Tara Javidi, and Rogerio Feris. Fully-adaptive feature sharing in multi-task networks with applications in person attribute classification. In CVPR, 2017. [32] Kevis-Kokitsi Maninis, Ilija Radosavovic, and Iasonas Kokkinos. Attentive single- tasking of multiple tasks. In CVPR, pages 1851–1860, 2019. [33] Ishan Misra, Abhinav Shrivastava, Abhinav Gupta, and Martial Hebert. Cross-stitch networks for multi-task learning. In CVPR, 2016. [34] Davy Neven, Bert De Brabandere, Stamatios Georgoulis, Marc Proesmans, and Luc Van Gool. Fast scene understanding for autonomous driving. In IV Workshops, 2017. [35] Alejandro Newell, Lu Jiang, Chong Wang, Li-Jia Li, and Jia Deng. Feature partitioning for efficient multi-task architectures. arXiv preprint arXiv:1908.04339, 2019. [36] Sinno Jialin Pan, Qiang Yang, et al. A survey on transfer learning. TKDE, 22(10): 1345–1359, 2010. [37] Hieu Pham, Melody Y Guan, Barret Zoph, Quoc V Le, and Jeff Dean. Efficient neural architecture search via parameter sharing. In ICML, 2018. [38] Esteban Real, Alok Aggarwal, Yanping Huang, and Quoc V Le. Regularized evolution for image classifier architecture search. In AAAI, 2019. [39] Clemens Rosenbaum, Tim Klinger, and Matthew Riemer. Routing networks: Adaptive selection of non-linear functions for multi-task learning. In ICLR, 2018. [40] Ethan M Rudd, Manuel Günther, and Terrance E Boult. Moon: A mixed objective optimization network for the recognition of facial attributes. In ECCV, 2016. [41] Sebastian Ruder. An overview of multi-task learning in deep neural networks. arXiv preprint arXiv:1706.05098, 2017. [42] Sebastian Ruder, Joachim Bingel, Isabelle Augenstein, and Anders Søgaard. s. AAAI, 2019. In [43] Ozan Sener and Vladlen Koltun. Multi-task learning as multi-objective optimization. In NIPS, 2018. [44] Dan Xu, Wanli Ouyang, Xiaogang Wang, and Nicu Sebe. Pad-net: Multi-tasks guided prediction-and-distillation network for simultaneous depth estimation and scene pars- ing. In CVPR, pages 675–684, 2018. [45] Ming Yuan and Yi Lin. Model selection and estimation in regression with grouped variables. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 68(1):49–67, 2006. [46] Amir R Zamir, Alexander Sax, William Shen, Leonidas J Guibas, Jitendra Malik, and Silvio Savarese. Taskonomy: Disentangling task transfer learning. In CVPR, 2018. [47] Xiangyun Zhao, Haoxiang Li, Xiaohui Shen, Xiaodan Liang, and Ying Wu. A mod- ulation module for multi-task learning with applications in image retrieval. In ECCV, 2018. VANDENHENDE ET AL.: BRANCHED MULTI-TASK NETWORKS [48] Jiayu Zhou, Jianhui Chen, and Jieping Ye. Malsar: Multi-task learning via structural regularization. Arizona State University, 21, 2011. [49] Barret Zoph and Quoc V Le. Neural architecture search with reinforcement learning. In ICLR, 2017. 19
Title: Synergistic Integration of Large Language Models and Cognitive Architectures for Robust AI: An Exploratory Analysis: Summary: This paper explores the integration of two AI subdisciplines employed in the development of artificial agents that exhibit intelligent behavior: Large Language Models (LLMs) and Cognitive Architectures (CAs). We present three integration approaches, each grounded in theoretical models and supported by preliminary empirical evidence. The modular approach, which introduces four models with varying degrees of integration, makes use of chain-of-thought prompting, and draws inspiration from augmented LLMs, the Common Model of Cognition, and the simulation theory of cognition. The agency approach, motivated by the Society of Mind theory and the LIDA cognitive architecture, proposes the formation of agent collections that interact at micro and macro cognitive levels, driven by either LLMs or symbolic components. The neuro-symbolic approach, which takes inspiration from the CLARION cognitive architecture, proposes a model where bottom-up learning extracts symbolic representations from an LLM layer and top-down guidance utilizes symbolic representations to direct prompt engineering in the LLM layer. These approaches aim to harness the strengths of both LLMs and CAs, while mitigating their weaknesses, thereby advancing the development of more robust AI systems. We discuss the tradeoffs and challenges associated with each approach. # Synergistic Integration of Large Language Models and Cognitive Architectures for Robust AI: An Exploratory Analysis # Oscar J. Romero, John Zimmerman, Aaron Steinfeld, Anthony Tomasic Carnegie Mellon University oscarr@andrew.cmu.edu, johnz@andrew.cmu.edu, steinfeld@cmu.edu, tomasic@andrew.cmu.edu # Abstract This paper explores the integration of two AI subdisciplines employed in the development of artificial agents that ex- hibit intelligent behavior: Large Language Models (LLMs) and Cognitive Architectures (CAs). We present three inte- gration approaches, each grounded in theoretical models and supported by preliminary empirical evidence. The modular approach, which introduces four models with varying de- grees of integration, makes use of chain-of-thought prompt- ing, and draws inspiration from augmented LLMs, the Com- mon Model of Cognition, and the simulation theory of cogni- tion. The agency approach, motivated by the Society of Mind theory and the LIDA cognitive architecture, proposes the for- mation of agent collections that interact at micro and macro cognitive levels, driven by either LLMs or symbolic com- ponents. The neuro-symbolic approach, which takes inspira- tion from the CLARION cognitive architecture, proposes a model where bottom-up learning extracts symbolic represen- tations from an LLM layer and top-down guidance utilizes symbolic representations to direct prompt engineering in the LLM layer. These approaches aim to harness the strengths of both LLMs and CAs, while mitigating their weaknesses, thereby advancing the development of more robust AI sys- tems. We discuss the tradeoffs and challenges associated with each approach. Introduction Pre-trained Large Language Models (LLMs) like ChatGPT, GPT-4, and PaLM 2 are generative models that excel in a variety of natural language tasks (Brown et al. 2020; Devlin et al. 2019) and even show promise in interactive decision- making (Li et al. 2022), reasoning (Diao et al. 2023; Xie et al. 2023; Yao et al. 2023b), and modeling aspects of ar- tificial general intelligence (AGI) (Kosinski 2023; Bubeck et al. 2023). However, LLMs face interpretability, consis- tency, and scalability issues (Mialon et al. 2023), partly due to limitations in context window size and sensitivity to prompt structure as they often rely on precise and carefully engineered instructions (Wei et al. 2022). They’re criticized for being stochastic parrots and lacking detailed reasoning explanations (Bender et al. 2021). Hallucinations (Welleck et al. 2019; Qian et al. 2022; Wei et al. 2022) and biases (Weidinger et al. 2022; Venkit, Srinath, and Wilson 2022) are further concerns, affecting trustworthiness and ethical aspects (Huang et al. 2023). The dependence on larger mod- els for better performance raises resource challenges (Mi- alon et al. 2023), and scalable LLMs incorporating continual learning are still an open question (Scialom et al. 2022). In contrast, Cognitive Architectures (CAs) propose hy- potheses about the fixed structures governing the operation of minds, whether in natural or artificial systems, facilitat- ing intelligent behavior in complex environments (Laird, Lebiere, and Rosenbloom 2017). CAs like ACT-R (Ander- son and Lebiere 2014), SOAR (Laird 2019), CLARION (Sun 2016), and LIDA (Franklin and Patterson 2006) model various human cognitive aspects: memory, learning, reason- ing, perceptual-motor interaction, theory of mind, AGI, and more (Kotseruba and Tsotsos 2020). CAs prioritize bounded rationality, striving for satisfactory decisions under resource constraints, diverging from LLMs’ pursuit of optimality. However, CAs face challenges in knowledge representation and scalability. Their encoded information is limited in size and homogeneous typology, meaning the knowledge pro- cessed by a cognitive agent1 is typically tailored for specific domains and tasks (Lieto, Lebiere, and Oltramari 2018). Unlike humans, CAs struggle with complex knowledge and their actions are confined to manually curated proce- dural knowledge (Park et al. 2023). According to (Mar- cus 2020), LLMs struggle to derive cognitive models from discourse and lack capabilities to reason over those cogni- tive models2. Hence, CAs could play a pivotal role in ei- ther augmenting or leveraging LLMs by contributing to the creation and dynamic updating of cognitive models. Like- wise, cognitive models could be leveraged to better interpret LLMs’ black-box learning algorithms and decision-making processes (Binz and Schulz 2023). Both LLMs and CAs have made valuable and sound con- tributions to the construction of complex autonomous AI agents; however, each approach has its strengths and weak- nesses (as summarized on Table 1). Thus, the main con- tribution of this work lies in characterizing the plausible approaches to integrating CAs and LLMs, viewing them through a hybrid and synergetic lens. 1Hereafter, consider a cognitive agent as an artificial agent con- structed on a particular CA. 2A cognitive model should at least include information about the entities in the external world, their properties, and their relation- ships with other entities, as well as the modeling of the cognitive processes that operate over those entities (Marcus 2020). Feature Language processing World knowledge Reasoning Symbolic processing Connectionist processing Knowledge scalability Planning Learning Memory management Consistency (no hallucinations) LLMs CAs ++ ++ -+ -+ ++ +- -+ – – -+ -+ -+ ++ ++ -+ -+ +- +- ++ ++ Table 1: Feature comparison between LLMs and CAs. (++) Fully supported. (+-) Almost always supported. (-+) Some- times supported. (–) Rarely (or not) supported. Relevant Work Chain-of-thought prompting (CoT): CoT prompting (Mi- alon et al. 2023; Diao et al. 2023) enhances LLM reasoning, leading to improved performance in various reasoning and natural language processing tasks. CoT breaks down multi- step problems into intermediate steps, enabling the model to address reasoning problems. ReAct (Yao et al. 2023b) combines both reasoning (CoT prompts) and action (ac- tion plan generation). It organizes a workflow that decom- poses task goals, injects task-relevant knowledge, extracts important observation components, and refines action plans based on feedback. Auto-CoT (Zhang et al. 2022) proposes a model that samples questions with diversity and automat- ically generates demonstrations to correct mistakes in rea- soning chains. The approaches we propose in this paper as- sume using CoT for problem decomposition, allowing a CA to inject its output into each reasoning step. Augmented Language Models: it combines enhanced reasoning skills of an LLM with tools like APIs, DBs, and code interpreters for improved knowledge retrieval, reason- ing, and action execution (Mialon et al. 2023). Program- Aided Language model (PAL) (Gao et al. 2023) reads natu- ral language problems, generates intermediate programs for reasoning, and delegates the solution step to a Python inter- preter. Toolformer (Schick et al. 2023) is a model trained to decide which APIs to call, when to call them, what argu- ments to pass, and how to best incorporate the results into future token prediction. Our modular approach extends the idea of augmenting an LLM with cognitive processing and assumes the usage of external APIs. CAs and LLMs: Generative Agents (Park et al. 2023) is a model that uses a cognitive architecture and an LLM to gen- erate realistic behavior. It defines three components: a mem- ory stream for recording comprehensive experiences in nat- ural language, a reflection component for deriving higher- level inferences about self and others, and a planning com- ponent translating these inferences into action plans. This approach differs from ours in that it does not use symbolic structures but unstructured natural language. OlaGPT (Xie et al. 2023) is an LLM cognition framework aiming to solve reasoning problems with human-like problem-solving abil- ities by leveraging CoT. OlaGPT proposes to approximate cognitive modules, such as attention, memory, learning, rea- soning, action selection, and decision-making. The first case of our modular approach resembles OlaGPT to some extent. Open-source experimental applications like Auto-GPT3 and BabyAGI4 aim to advance AGI. Auto-GPT manages long-term and short-term memory, language generation, and summarization. BabyAGI uses LLM chains to perform tasks based on goals. These approaches hold significant poten- tial and are likely to integrate further with human cognition modeling. Although with not a strict commitment to model a cognitive architecture, Voyager (Wang et al. 2023) facil- itates continual learning through an evolving code library for complex behaviors. An iterative prompting mechanism incorporates feedback, errors, and self-verification for pro- gram improvement. (LeCun 2022) outlines the considera- tions for crafting a cognitive architecture using energy min- imization mechanisms, enabling reasoning, prediction, and multi-scale planning. They emphasize that while determin- istic generative architectures withstand energy distribution issues, non-deterministic structures like auto-encoders and joint embeddings are susceptible to collapse. # Integration Approaches In this section, we propose and discuss the tradeoffs of three different approaches for the integration of CAs and LLMs: the modular approach, the agency approach, and the neuro- symbolic approach. To illustrate the practical implementa- tion of each approach, we base our examples on a scenario involving a cognitive agent designed to assist people with visual impairments in everyday tasks such as navigation and exploration of indoor environments, effective use of public transportation, etc. The agent operates on a smartphone de- vice, utilizing sensor data processing, computer vision for object detection, and speech recognition to perceive its en- vironment. Its actions encompass language generation and invocation of external APIs. The agent engages in conver- sation with its user, reasons about their needs and requests, constructs shared mental models to achieve goals effectively, and makes decisions that unfold in the short and long term. For the remainder of this paper, let us consider that the inputs of an LLM can be multimodal, involving text and images, while the outputs are exclusively text-based. Con- versely, for the sake of simplicity, CAs’ inputs and outputs are limited to formatted text, although, in practice, various CAs can process diverse modalities. As a reference frame- work for CAs’ structure, our approach adopts the Common Model of Cognition (CMC) (Laird, Lebiere, and Rosen- bloom 2017), which captures a consensus regarding the structures and processes that resemble those found in human cognition. CMC defines five high-level modules, including perception, motor, working memory, declarative long-term memory, and procedural long-term memory, each of which can be further decomposed into multiple sub-modules. Be- havior in the CMC is organized around a cognitive cycle driven by procedural memory, with complex behavior (e.g., 3https://github.com/Significant-Gravitas/Auto-GPT 4https://github.com/yoheinakajima/babyagi reasoning, planning, etc.) emerging as sequences of such cy- cles. In each cognitive cycle, the system senses the current situation, interprets it with respect to ongoing goals, and then selects an internal or external action in response. Both the agency and the neuro-symbolic approaches use different ref- erence frames, which will be discussed later. Modular Approach A straightforward way to integrate LLMs and CAs is using a modular approach where either (1) LLMs partially enhance the performance of certain modules and components of a CA, or (2) a CA augments an LLM by injecting reasoning traces and contents from memories into the prompting process. Figure 1 depicts 4 different cases of modular integration. This integration allows modules to be easily replaced by LLMs or their CA module counterparts. Case (a) assumes a recursive prompting scenario (Mialon et al. 2023) where an LLM decomposes a complex problem into subproblems, and the intermediate outputs are aggre- gated to generate a final output. In this case, a CA could be used to prime every intermediate step at the LLM with reasoning traces from procedural knowledge as well as rel- evant content from memories. The mechanism would be as follows: given an initial input i0 (e.g., a user’s request, exter- nal signals, etc.), the LLM generates an intermediate output o0 (e.g., the first step towards the solution of the user’s re- quest) and a set of equivalent symbolic structures for both the input, si0 (e.g., intents, entities, and properties recog- nized from the input), and the output, so0 (e.g., symbolic representation of LLM’s actions and reasoning steps)5. The CA uses those symbolic structures as inputs and executes one or several cognitive cycles, after which, the contents of the working memory (w0), including fired productions, rel- evant information from declarative memories, and actions, are injected as cues into the next intermediate step of the LLM. The process repeats until a final output is generated. Consider this streamlined example: A bus rider employs the term “downtown” ambiguously as the destination. De- pending on the day of the week, the user may refer to two specific places in the downtown area, namely the work- place or the gym. The cognitive agent uses a combination of declarative and procedural knowledge to discern the user’s transit patterns and effectively disambiguate the term down- town. The triggered productions and relevant contents of the working memory are subsequently integrated into the next LLM’s recursive step, thereby guiding and enhancing its rea- soning process with new information. [i0] [o0] [si0] (intent, (inform, destination, downtown)) [os0] (step, (search, orig, X, destination, downtown)) [w0] User: "when is my next bus to downtown coming?" search bus schedule with destination downtown (semantic, (is_a (downtown, place))) (semantic, (today (saturday))) (episodic, (destination=downtown, place=workplace, ë days=[monday... friday])) (episodic, (destination=downtown, place=gym, # ë days=[saturday, sunday])) 5Empirical work demonstrates that LLMs can be trained and fine-tuned to learn to encode key aspects of traditional symbolic structures (Pavlick 2023; Romero et al. 2021; Tomasic et al. 2021). (procedural, (if destination == x and today == y [o1] ... ë then destination=place)) (semantic, (destination (gym))) search bus schedule with destination gym Now, case (b) proposes an integration scenario where a CA leverages multimodal LLMs to support both the per- ception and motor modules of the system. At the perception level, the LLM converts external signals (e.g., text and im- ages) into symbolic representations and their relations, along with relevant metadata, which is then stored in the corre- sponding working memory buffers. For instance, we used a description of an image generated by GPT-46, then we pro- vided an in-context learning example to ChatGPT to convert the description into symbolic structures: [prompt] your job is to transform that natural language description into symbolic representations. Example, Input: "this is an office with a desk, a computer on top of it, and a chair. There is also a printer on the left of the computer and some pencils on the right". Output: has(office, desk). has(office, computer). has(office, chair). onTopOf(computer, desk). toTheRightOf(printer, computer). toTheLeftOf( computer, printer). toTheLeftOf(computer, pencils).. [prompt] Input: "a busy city street with a clock tower in the background. The street is lined with shops and restaurants on both sides. There are several motorcycles parked on the side of the road, and people are walking down the street. The clock tower has a large clock face with roman numerals and a small spire on top...". Output: [ChatGPT] has(city_street, clock_tower). has(clock_tower , clock_face). has(clock_face, roman_numerals). has( clock_face, small_spire). has(city_street, shops). has(city_street, restaurants). has(city_street, motorcycles). toTheLeftOf(clock_tower, city_street). toTheRightOf(city_street, clock_tower). toTheRightOf (shops, city_street)... onTopOf(roman_numerals, clock_face). onTopOf(small_spire, clock_face). onTopOf(clock_face, clock_tower)... As observed in the example, though not entirely accurate, LLMs demonstrate the capability to extract high-level com- positional and spatial relationships between entities from a given image/text and then re-express them using symbolic representations. After generating and storing these symbolic structures in the working memory, other modules of the CA can access them and perform diverse kinds of cognitive pro- cesses. Considering our initial example, it is expected that this symbolic representation of perceived images will en- able both the visually impaired user and the cognitive agent to collaboratively construct shared mental models for navi- gation, thereby enhancing spatial cognition and situational awareness of the user. Conversely, the LLM-based motor module converts the symbol structures that have been stored in the working memory buffers into external actions (e.g., natural language generation, motor control, etc.) 6At the time of writing this paper, OpenAI is holding back GPT- 4 image processing features, so we used a natural language descrip- tion generated with GPT-4 and reported in (Zhu et al. 2023). CA . P i i si —) cow] PM WM ° M w DM | eg FTES a. Cognitively-augmented LLM b. Perception and Motor powered by LLM CA o CA 0; in ipa >[am] |CA To, c. CA powered by LLM d. Internal simulation for anticipation and planning Figure 1: Modular approach. (a) Chain-of-Thought or recursive reasoning that augments an LLM with content generated by a CA. (b) Perception and Motor modules of a CA that leverages the power of LLMs. (c) Multiple modules of a CA that use LLMs to process and/or retrieve data. (d) A CA that leverages LLMs to predict/anticipate future states of the environment in order to perform reasoning and planning (some modules are not shown for the sake of legibility). Red-colored boxes denote LLMs and blue-colored ones denote CAs modules. Perception (P), motor (M), working memory (WM), long-term procedural memory (PM), long-term declarative memory (DM), and Anticipation (A) correspond to modules of a CA. i and o correspond to the input and output of the system, respectively. si and so are symbolic representations of the input i and the output o, respectively. w corresponds to the contents of the working memory. b are module-specific working memory buffers. Solid arrows denote the flow of information and dotted arrows denote predictions of the next input. Unlike case (b), which loosely integrates LLMs and CAs, case (c) proposes an integration where not only the percep- tion/motor modules are driven by LLMs, but also the pro- cedural and declarative (semantic and episodic) memories. Prior research (Park et al. 2023) suggested using LLMs to retain episodic knowledge as lists of observations (depicting agents’ behaviors in natural language). These can be synthe- sized into high-level observations using LLMs’ summariza- tion abilities, enabling agents to reflect on their experiences across different time spans. From another perspective, we envision the possibility of converting these natural language descriptions into symbolic structures using a proper method for fine-tuning or prompt-engineering an LLM. Similarly, the large amount of factual knowledge directly accessible through LLMs can be harnessed to automatically extract knowledge and populate a semantic memory (e.g., an ontology) of a CA, which would otherwise require labo- rious manual knowledge curation and acquisition. Prelimi- nary work in this area aims to populate arbitrary complex nested semantic knowledge schemas (Caufield et al. 2023). Regarding the procedural module, previous work (Park et al. 2023) has shown that LLMs can be leveraged to cre- ate detailed step-by-step plans by translating the agent’s ob- servations of the environment expressed in natural language into high-level action plans, which are then recursively de- composed into detailed behaviors for action and reaction. Alternatively, we anticipate that, with the proper in-context prompting or fine-tuning, an LLM can translate natural lan- guage descriptions into symbolic structures such as produc- tion rules. For instance, consider the example below where we prompted ChatGPT to generate an ACT-R production rule for filtering out transit searches based on a natural language description and a single example (borrowed from (ACT-R Website. 2015)) used to prime the LLM7: [prompt] Instructions: ... your job is to generate ACT-R productions based on a natural language description that I will provide to you... For instance: Description: generate an ACT-R production that counts until a given number. Production: (p example-counting =goal>.... [prompt] Description: generate an ACT-R production such that if I need to take a bus, check first the weather and the traffic patterns. If it is snowing and the traffic is heavy, then search only for bus routes without transfers and minimum walking distance. Production: # [ChatGPT] (p check-weather-traffic-snow-heavy # =goal> isa state =retrieval> # take-bus check-weather-traffic # isa weather traffic # weather-traffic snowing heavy ==> =goal> isa state transfer take-bus search-routes none walking +retrieval> min-distance isa transfer walking bus-routes none min-distance) The condition part of the production checks both that the state of the goal is check-weather-traffic and that the retrieved declarative chunk has the values snowing and heavy for the slots weather and traffic, respec- tively. If so, the action will change the goal’s state to search-routes and retrieve a declarative chunk for bus routes with no transfers and minimum walking distance. Although the generated production captures correctly the intention of the natural language description, it contains re- dundant slots for transfer and walking on the goal buffer of the action part (in italics). This type of transformation from natural language descriptions to symbolic productions can allow users to instruct and teach explicit procedural knowledge to their agents via conversation and, more inter- estingly, transform symbolic productions back into natural language for explainability purposes. However, it is not clear how an LLM could keep consistency between learned pro- ductions for a large knowledge base. Additionally, at least at its current state, LLMs by themselves cannot compile cer- tain operations over the procedural memory such as conflict resolution and execution, so an LLM would still require an external interaction with a CA’s procedural engine. Finally, case (d) presents a streamlined approach to the simulation theory of cognition, which states that cognitive functions like planning and anticipation stem from inter- 7The complete log is available here: https://shareg.pt/nO1zssm. nally simulated interactions with the environment (Shana- han 2006; Hesslow 2012). By inputting appropriate contex- tual information (such as working memory contents, sen- sory input, motor responses, and past experiences), we pos- tulate that LLMs have the potential to forecast likely rep- resentations of the world’s states resulting from the current state. That is, upon receiving an initial sensory input (i0), the CA progresses through its standard perception-action path- way. Subsequently, rather than executing the resulting ac- tion (O0) in the real world, the action O0, along with the working memory contents, are used as inputs of the LLM. The LLM then generates a prediction for the next world state (i1), which serves as a simulated input. Next, a sim- ulated output o1 is generated, and then the process cycles until a certain condition is met. By chaining these sequences of perception-action-prediction, the system could anticipate the outcomes of its actions across multiple temporal scales. These simulated sequences may take on either linear con- figurations, predicting only one world state per simulated step, or branching tree-like structures, predicting multiple likely world states per step (tangentially related work has been proposed by (Yao et al. 2023a)). In the latter case, a planning mechanism could explore different branches of the tree by assessing their likelihood of occurrence and per- forming backtracking when necessary. As proposed by (Park et al. 2023), an LLM can be prompted to rank its answers based on a certain scale, similarly, we can prompt it to “guesstimate” a probability for each node of the tree. Below is a simplified example where the inputs to the LLM are the contents of the working memory (green), simu- lated user actions (red), and simulated system actions (blue). For simplicity, both user and system actions are natural lan- guage and do not involve symbols: [prompt] You are an intelligent agent that assists a person who is blind in retrieving information from public transportation. Today is snowing and therefore the traffic is heavy . Predict 3 things that the user will ask you to do and assign a probability to occur to each one. [ChatGPT] Check current bus/train delay (0.6), suggest alternative routes (0.3), provide weather-related alerts (0.1) [prompt] The user requests you to provide weather-related alerts, and you provide those alerts . What do you predict the user will ask next? [ChatGPT] Ask for specific service disruptions (0.4), request tips for navigating in snowy conditions (0.3), inquire about expected clearing times (0.2) # Agency Approach The Agency approach operates on two levels - micro and macro (see Figure 2). Inspired by the Society of Mind theory (Minsky 1988) and LIDA cognitive architecture (Franklin and Patterson 2006), micro-level agency occurs within the cognitive architecture itself. Specialized agents process in- formation in parallel, competing for resources like atten- tion and memory. They collaborate by forming coalitions for Cognitive Agent Agency —* agents BY o Pe ° \& Z , A WM }——} Global Workspace mM kH i io) (2) [e) OM @s 44 Competing input agents cAmodule (@) competing/receiving Agent a. Agency at the micro-level © Active agent LB bomen b. Agency at the macro-level © Cognitive agent (CA + LLM) Figure 2: Agency approach. a) Agents at the micro-level compete for resources and cooperate in decision-making. b) Agents at the macro-level interact with other agents and humans to cooperate in task resolution. P (Perception), M (Motor), WM (working memory), and DM (declarative memory) are modules of a CA. decision-making and problem-solving. In contrast, macro- level agency involves cognitive agents interacting with other agents and humans to collaboratively achieve goals. Consider the case of our cognitive agent designed to aid blind users in indoor navigation. At a micro-level, each agent operates through either a fine-tuned LLM or a symbolic pro- cessor. Cognitive processing unfolds as follows: sensory in- puts are processed by the perception module, yielding ab- stract entities like objects, categories, actions, events, etc., forwarded to the working memory. Then, the working mem- ory cues declarative memories to establish local associa- tions, e.g., user navigation preferences, place familiarity, and more. Specialized agents at the agency observe work- ing memory contents and form coalitions. For instance, object detection and semantic localization constitute one coalition, while natural language understand- ing and semantic grounding form another. These coalitions are transferred to the Global Workspace, where a competi- tive process selects the most relevant coalition. If a user ap- proaches a staircase lacking a handrail, the coalition involv- ing object detection and semantic localization takes prece- dence, globally transmitting its contents (e.g., staircase prox- imity and orientation) to other agents. In subsequent cog- nitive cycles, the coalition for natural language generation would be chosen to provide timely warnings to the user. bate (e.g., a and b debating about their reasoning processes to approach a problem while reaching a consensus (Du et al. 2023)), among others. All these kinds of interactions among agents could use natural language in order to foster trans- parency and interpretability, from the user’s point of view, of the reasoning processes and conciliated actions, although the necessity of symbolic counterparts remains unclear. # Neuro-Symbolic Approach We present a neuro-symbolic approach inspired by the CLARION cognitive architecture, focusing primarily on the action-centered sub-system (ACS), while acknowledg- ing the existence of three additional sub-systems within the architecture. The ACS operates across two distinct levels: the top level (symbolic), responsible for encoding explicit knowledge, and the bottom level (connectionist), tasked with encoding implicit knowledge. Consequently, the architec- ture exhibits a degree of redundancy in knowledge repre- sentation. These two levels synergistically engage in action selection, reasoning, and learning processes. Our focus is to explore the incorporation of LLMs at the bottom level, enhancing the knowledge extraction and integration process while exhibiting potential scalability towards novel scenar- ios. Further details on the mathematical model underpinning the cognitive processes can be found in (Sun 2016). While not a novel architectural approach, its potential lies in the diverse roles agents can assume within coalitions. For instance, an LLM agent engages in pair work, process- ing text or images to produce symbols, while a symbolic agent infers insights from these symbols. Another scenario involves one LLM agent fine-tuned to convert symbol struc- tures into natural language text and another serving a super- visory role, pinpointing errors in the first agent’s output. Now, to better understand macro-level interactions, let’s consider two users (A and B) alongside their cognitive agents (a and b). Agents a and b collaborate to exchange knowledge and intentions (e.g., a shares spatial insights with b of previ- ous A’s exploration of a building, thus aiding B’s future nav- igation), negotiate (e.g., a and b helping teammates A and B reach an agreement when having conflicting goals), de- CLARION defines three types of symbolic rules at the top level. The fixed rules (FR) are rules that have been hard- wired by an expert and cannot be deleted; Independent- Rule-Learning (IRL) rules are independently generated at the top level, with little involvement (or no involvement at all) of the bottom level, which can be refined or deleted as needed; and Rule-Extraction-Refinement (RER) rules which are extracted from the bottom level. Figure 3 illustrates the process wherein a human provides a natural language instruction to create a new rule and the LLM-based per- ception module extracts symbolic structures that are fur- ther stored in the working memory. Through a template- matching mechanism, the contents of the working mem- ory are expressed as an IRL rule where both its condition and action parts are chunks composed of dimension-value User: If it is snowing then 1 discard bus WM Symbolic (Top) Level transfers and (intent, IRL RER ing distance te re) If (intent, C=, ‘take. bus) GP ~ and (Weather, (Snowing, raining]) then (transfers, fewer) Call = | symbols | (transfers, le» (Cantar, APL oO SO tone). a aD If (intent, take_bus) and (weGthER, SHOWING)... then (ERans fers, Fewer) } a = (transfers, none) 5 . 6 (intent, (walk_dist, min) L» rf .. and (weather, SHOWAG) and (traffic, heavy) then (EPGRSFERS, FEWER) 2 Feedback g take_bus) 2 ao (dest, = | utter: g X store) Top-down Bottom-up + 2 learning learning bus User: How do | (weather, get X store? Natura | celal Connectionist (Bottom) Level — LLM language! | How do! get |<>} Prompt: You are an intelligent agent that assists a blind user... It is and she asks you "how do | get X store?" Which Weath 4 X store? filter you would apply to the bus search? Output: opt for routes with prioritize routes with higher frequencies... jeather cond: snowing # bus prournext is.. Figure 3: Neuro-symbolic approach. WM: Working Memory. IRL: Independent Rule Learning. RER: Rule Extraction Refine- ment. G: Generalization scenario. S: Specialization scenario. Orange-colored boxes illustrate the IRL case while the blue- colored boxes illustrate the RER case. Highlighted text represents entities and keywords present at the bottom level that are further extracted and translated into symbols at the top level. pairs8, e.g., chunki((intent, take bus), (weather, snowing)) Ñ chunkj((transfers, none), (walk distance, min)). On the other hand, if an action determined at the bot- tom level proves successful (according to a certain crite- rion), an RER rule is formulated and subsequently incorpo- rated into the top level, e.g., given the output generated by the LLM at the bottom level9 on Figure 3, the correspond- ing RER rule is chunki((intent, take bus), (weather, snow- ing)) Ñ chunkj((transfers, fewer)). During subsequent in- teractions with the environment, the rule is refined based on the outcomes of its application: if the result is deemed suc- cessful, the rule’s conditions may be generalized to make it more universal by adding new values to dimensions (e.g., chunki((intent, take bus), (weather, [snowing, raining])) Ñ chunkj((transfers, fewer))). Conversely, if the outcome does not yield success, the rule should be specialized by remov- ing values from dimensions or by adding new dimension- value pairs (e.g., chunki((intent, take bus), (weather, snow- ing), (traffic, heavy)) Ñ chunkj((transfers, fewer))). Rule selection in IRL is determined by an information gain function, while RER uses a Boltzmann distribution based on rule’s utility function and a base-level activation. The integration of both levels can be achieved through var- ious mechanisms. Stochastic selection involves choosing a level (top or bottom) and a group of rules if the top level is chosen (e.g., FR, RER, or IRL). These selections are based on probabilities assigned by a metacognitive module to each level/group. Integration through bottom-up rectification oc- curs when the top level rectifies and incorporates outcomes from the bottom level (e.g., the LLM may discover addi- tional dimension-value pairs not specified by the top level like “prioritize routes with higher frequencies”). Alterna- tively, top-down guidance involves the bottom level utiliz- ing outcomes from the top level, combined with its own knowledge, to make action decisions. This top-down guid- ance can be achieved by using prompt engineering tech- 8Each dimension may have one or multiple values associated. 9See full output log here: https://sharegpt.com/c/LYIz9in niques to prime the LLM with either FR or IRL rules. Bottom-up learning is facilitated by the rule extraction mechanism, whereas top-down learning can be realized by using both FR and IRL rules as exemples to fine-tune the LLM at the bottom level. Determining whether an outcome from the bottom level is successful requires feedback, often in the form of rewards or reinforcement, which might not be readily available. To address this challenge, we propose two approaches: the incorporation of human-in-the-loop inter- actions, where feedback ensures the coherence of extracted rules, and the utilization of an additional LLM for self-play interactions emulating human feedback. Overall, both the bottom-up and the top-down learning mechanisms support explainability of decision-making and reasoning processes performed by the LLM at the bottom level. Harnessing LLMs at the bottom level of a CLARION-like architecture can contribute remarkably to enhancing the sys- tem’s flexibility and scalability. First, unlike backpropaga- tion neural networks used in CLARION, LLMs are not re- stricted to a fixed number of features and labels. Also, the LLMs-based variation we propose do not require to pre- define dimension-value pairs as CLARION does. Conse- quently, the utilization of LLMs at the bottom level can enable enhanced representational flexibility, with cascad- ing benefits reaching the top level. Secondly, the conver- sion from unstructured natural language to symbols and vice versa can be executed seamlessly by an LLM-based bottom level. Lastly, leveraging an LLM with such broad knowledge of the world, coupled with cross-level learning dynamics and human feedback, can foster continuous learning loops where knowledge is constructed and refined over time. Discussion Among the three approaches discussed so far, there are some commonalities that we highlight next. First, the working memory, along with the perception module, plays an impor- tant role in retaining the most pertinent information while filtering out irrelevant stimuli. This contrasts with the idea of a context window in LLMs, where truncation strategies arbi- trarily delete the oldest tokens observed when the length of the window reaches a maximum, potentially discarding crit- ical parts of the context. The contents of the working mem- ory are selectively and intentionally stored and recalled from long-term memories, allowing the agent to continuously in- teract with the environment without losing track of events. A second common aspect among all three approaches is the utilization of LLMs to accurately translate unstructured nat- ural language to symbols and vice versa, as well as to extract factual knowledge about the world. This breakthrough opens up a realm of new possibilities, allowing for the seamless scaling of CAs to tackle complex real-world problems. Third, the three approaches can benefit from multi-modal multi-turn interaction. In cases where cognitive agents col- laborate with humans, there is an opportunity to incremen- tally refine shared mental models of a task through con- tinuous conversational interaction and scene understanding. Fourth, since all the approaches depend, in one way or an- other, on LLMs, they are susceptible to the stochastic nature of LLMs. This stochastic nature leads to variations (some- times remarkable) in the outputs, even when the model is prompted with exactly the same input. And fifth, all three approaches contribute, to a greater or lesser extent, to the continuous construction of cognitive models about the enti- ties in the world, their relationships, and the distinct cogni- tive processes that operate over them. Regarding the Modular approach, the main difference among the four cases presented is the degree of integra- tion between an LLM and a CA. The first case, the cogni- tively augmented LLM, aligns with the current trend of aug- menting LLMs with external tools and interpreters and rep- resents the most loosely integrated model among the four. In this case, the LLM retains control of execution, and the outputs of the CA are solely utilized for in-context learn- ing purposes. The strength of this approach is that recursive LLMs receive gradual guidance during the chain-of-thought reasoning process. However, a notable disadvantage is that, due to the lack of overall control, the CA components can only contribute to reactive (System 1) responses rather than deliberative, high-order (System 2) ones. The second case of the modular approach presents a mod- erately integrated model where only the perception and mo- tor modules of a CA are powered with LLMs. The main strength of this model is that it aligns with the evident ben- efits obtained from multi-modal LLMs, which notably en- hance text and image understanding, avoiding the need for task-specific and laborious labeling and training of machine learning models. Another advantage of this case is that it as- sumes a straightforward transformation from sensory inputs to symbolic percepts, which facilitates further processing. However, one main disadvantage is that the other modules of the CA still do not fully leverage the power of LLMs. The third case presents a tightly integrated model that leverages the synergistic interaction between LLMs and symbolic components of a CA. LLMs extract factual knowl- edge from the world, automatically populating ontologies. These semantic representations then facilitate the creation of world models, addressing a limitation of LLMs. Further- more, proper LLM’s prompt engineering techniques would produce syntactically and semantically correct CA produc- tions, which can be later compiled by a symbolic engine. However, a drawback of this integrated system is its heavy reliance on LLM outputs, rendering it susceptible to cascad- ing failures, including hallucinations and biases. The fourth case represents the most tightly integrated model. It involves a module designed for simulating the out- comes of future events. The primary advantage of this case is its capability to anticipate and plan by traversing and back- tracking a tree-like structure of possible events. However, similar to the third case, this system heavily relies on the outputs of the LLM, which might occasionally be inconsis- tent. This inconsistency could lead to erroneous predictions in the early stages of internal simulation, resulting in cascad- ing errors in the planning process. Unlike the Modular approach, which can suffer from overall failures and inconsistencies if individual modules are poorly designed, the Agency approach at the micro- level offers greater robustness from two key angles. First, agents may encode redundant knowledge, resulting in mul- tiple agents capable of achieving the same competence. This redundancy enhances system resilience as individual agents may fail, yet the system can still yield satisfactory outcomes. Second, agent role-playing strategies enable the system to self-reflect and promptly rectify potential deviations in rea- soning processes. At the macro-level, the Agency approach stands out as the only one among the three approaches that considers inter-agent interactions, with a primary focus on collaborative interactions between agents and humans. How- ever, aspects such as communication, coordination, hierar- chies, etc. between agents still remain open questions. The Neuro-symbolic approach is arguably the most tightly integrated model. It leverages the capabilities of LLMs to seamlessly translate unstructured natural language into structured symbolic representations and vice versa. This approach plays a crucial role in extracting rules from the connectionist level and subsequently generalizing and spe- cializing those extracted rules over time. The interactions between the symbolic and connectionist levels enable the continuous construction of explainable models for decision- making and procedural processing based on black-boxed LLMs. However, a potential weakness of this approach lies in its heavy reliance on the LLM layer. # Conclusions In this paper, we present three different approaches to inte- grating Cognitive Architectures and Large Language Mod- els from an architectural perspective: a modular approach, an agency approach, and a neuro-symbolic approach. We discuss the trade-offs associated with each approach and provide insights for future research in this area. # Acknowledgements The contents of this paper were developed under grants from the National Institute on Disability, Independent Liv- ing, and Rehabilitation Research (NIDILRR grant numbers 90DPGE0003 and 90REGE0007) References ACT-R Website. 2015. Unit 1: Understanding Production http://act-r.psy.cmu.edu/wordpress/wp-content/ Systems. themes/ACT-R/tutorials/unit1.htm. Accessed: 2023-08-03. Anderson, J. R.; and Lebiere, C. J. 2014. The atomic com- ponents of thought. Psychology Press. Bender, E. M.; Gebru, T.; McMillan-Major, A.; and Shmitchell, S. 2021. On the Dangers of Stochastic Par- In Proceed- rots: Can Language Models Be Too Big? ings of the 2021 ACM Conference on Fairness, Account- ability, and Transparency, FAccT ’21, 610–623. New York, NY, USA: Association for Computing Machinery. ISBN 9781450383097. Binz, M.; and Schulz, E. 2023. Using cognitive psychology to understand GPT-3. Proceedings of the National Academy of Sciences, 120(6): e2218523120. Brown, T.; Mann, B.; Ryder, N.; Subbiah, M.; Kaplan, J. D.; Dhariwal, P.; Neelakantan, A.; Shyam, P.; Sastry, G.; Askell, A.; Agarwal, S.; Herbert-Voss, A.; Krueger, G.; Henighan, T.; Child, R.; Ramesh, A.; Ziegler, D.; Wu, J.; Winter, C.; Hesse, C.; Chen, M.; Sigler, E.; Litwin, M.; Gray, S.; Chess, B.; Clark, J.; Berner, C.; McCandlish, S.; Radford, A.; Sutskever, I.; and Amodei, D. 2020. Language Mod- els are Few-Shot Learners. In Larochelle, H.; Ranzato, M.; Hadsell, R.; Balcan, M.; and Lin, H., eds., Advances in Neu- ral Information Processing Systems, volume 33, 1877–1901. Curran Associates, Inc. Bubeck, S.; Chandrasekaran, V.; Eldan, R.; Gehrke, J.; Horvitz, E.; Kamar, E.; Lee, P.; Lee, Y. T.; Li, Y.; Lundberg, S.; Nori, H.; Palangi, H.; Ribeiro, M. T.; and Zhang, Y. 2023. Sparks of Artificial General Intelligence: Early experiments with GPT-4. arXiv:2303.12712. Caufield, J. H.; Hegde, H.; Emonet, V.; Harris, N. L.; Joachimiak, M. P.; Matentzoglu, N.; Kim, H.; Moxon, S. A.; Reese, J. T.; Haendel, M. A.; et al. 2023. Structured prompt interrogation and recursive extraction of semantics (SPIRES): A method for populating knowledge bases using zero-shot learning. arXiv preprint arXiv:2304.02711. Devlin, J.; Chang, M.-W.; Lee, K.; and Toutanova, K. 2019. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In Proceedings of the 2019 Con- ference of the North American Chapter of the Association for Computational Linguistics: Human Language Technolo- gies, Volume 1 (Long and Short Papers), 4171–4186. Min- neapolis, Minnesota: Association for Computational Lin- guistics. Diao, S.; Wang, P.; Lin, Y.; and Zhang, T. 2023. Ac- tive Prompting with Chain-of-Thought for Large Language Models. arXiv:2302.12246. Du, Y.; Li, S.; Torralba, A.; Tenenbaum, J. B.; and Mor- datch, I. 2023. Improving Factuality and Reasoning in Lan- guage Models through Multiagent Debate. arXiv preprint arXiv:2305.14325. Franklin, S.; and Patterson, F. 2006. The LIDA architec- ture: Adding new modes of learning to an intelligent, au- tonomous, software agent. pat, 703: 764–1004. Gao, L.; Madaan, A.; Zhou, S.; Alon, U.; Liu, P.; Yang, Y.; Callan, J.; and Neubig, G. 2023. PAL: Program-aided Lan- guage Models. arXiv:2211.10435. Hesslow, G. 2012. The current status of the simulation the- ory of cognition. Brain research, 1428: 71–79. Huang, X.; Ruan, W.; Huang, W.; Jin, G.; Dong, Y.; Wu, C.; Bensalem, S.; Mu, R.; Qi, Y.; Zhao, X.; Cai, K.; Zhang, Y.; Wu, S.; Xu, P.; Wu, D.; Freitas, A.; and Mustafa, M. A. 2023. A Survey of Safety and Trustworthiness of Large Lan- guage Models through the Lens of Verification and Valida- tion. arXiv:2305.11391. Kosinski, M. 2023. Theory of Mind May Have Spontaneously Emerged in Large Language Models. arXiv:2302.02083. Kotseruba, I.; and Tsotsos, J. K. 2020. 40 years of cognitive architectures: core cognitive abilities and practical applica- tions. Artificial Intelligence Review, 53(1): 17–94. Laird, J. E. 2019. The Soar cognitive architecture. MIT press. Laird, J. E.; Lebiere, C.; and Rosenbloom, P. S. 2017. A Standard Model of the Mind: Toward a Common Compu- tational Framework across Artificial Intelligence, Cognitive Science, Neuroscience, and Robotics. AI Magazine, 38(4): 13–26. LeCun, Y. 2022. A path towards autonomous machine intel- ligence version 0.9. 2, 2022-06-27. Open Review, 62. Li, S.; Puig, X.; Paxton, C.; Du, Y.; Wang, C.; Fan, L.; Chen, T.; Huang, D.; Aky¨urek, E.; Anandkumar, A.; Andreas, J.; Mordatch, I.; Torralba, A.; and Zhu, Y. 2022. Pre-Trained Language Models for Interactive Decision-Making. CoRR, abs/2202.01771. Lieto, A.; Lebiere, C.; and Oltramari, A. 2018. The knowl- edge level in cognitive architectures: Current limitations and possible developments. Cognitive Systems Research, 48: 39–55. Cognitive Architectures for Artificial Minds. Marcus, G. 2020. Steps Towards Robust Artificial abs/2002.06177. Mialon, G.; Dess`ı, R.; Lomeli, M.; Nalmpantis, C.; Pa- sunuru, R.; Raileanu, R.; Rozi`ere, B.; Schick, T.; Dwivedi- Yu, J.; Celikyilmaz, A.; Grave, E.; LeCun, Y.; and Scialom, T. 2023. Augmented Language Models: a Survey. arXiv:2302.07842. Minsky, M. 1988. Society of mind. Simon and Schuster. Park, J. S.; O’Brien, J. C.; Cai, C. J.; Morris, M. R.; Liang, P.; and Bernstein, M. S. 2023. Generative Agents: Interac- tive Simulacra of Human Behavior. arXiv:2304.03442. Pavlick, E. 2023. Symbols and grounding in large language models. Philosophical Transactions of the Royal Society A, 381(2251): 20220041. Qian, J.; Wang, H.; Li, Z.; Li, S.; and Yan, X. 2022. Limita- tions of language models in arithmetic and symbolic induc- tion. arXiv preprint arXiv:2208.05051. Romero, O. J.; Wang, A.; Zimmerman, J.; Steinfeld, A.; and Tomasic, A. 2021. A Task-Oriented Dialogue Architecture via Transformer Neural Language Models and Symbolic In- jection. In Proceedings of the 22nd Annual Meeting of the Special Interest Group on Discourse and Dialogue, 438– 444. Singapore and Online: Association for Computational Linguistics. Schick, T.; Dwivedi-Yu, J.; Dess`ı, R.; Raileanu, R.; Lomeli, M.; Zettlemoyer, L.; Cancedda, N.; and Scialom, T. 2023. Toolformer: Language Models Can Teach Themselves to Use Tools. arXiv:2302.04761. Scialom et al., T. 2022. Fine-tuned language models are con- tinual learners. In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, 6107– 6122. Shanahan, M. 2006. A cognitive architecture that combines internal simulation with a global workspace. Consciousness and cognition, 15(2): 433–449. Sun, R. 2016. Anatomy of the mind: exploring psycholog- ical mechanisms and processes with the Clarion cognitive architecture. Oxford University Press. Tomasic, A.; Romero, O. J.; Zimmerman, J.; and Steinfeld, A. 2021. Propositional Reasoning via Neural Transformer Int. Workshop on Neural-Symbolic Language Models. Learning and Reasoning (NESY). Venkit, P. N.; Srinath, M.; and Wilson, S. 2022. A Study of Implicit Bias in Pretrained Language Models against Peo- In Proceedings of the 29th Inter- ple with Disabilities. national Conference on Computational Linguistics, 1324– 1332. Gyeongju, Republic of Korea: International Commit- tee on Computational Linguistics. Wang, G.; Xie, Y.; Jiang, Y.; Mandlekar, A.; Xiao, C.; Zhu, Y.; Fan, L.; and Anandkumar, A. 2023. Voyager: An open- ended embodied agent with large language models. arXiv preprint arXiv:2305.16291. Wei, J.; Wang, X.; Schuurmans, D.; Bosma, M.; Chi, E. H.; Le, Q.; and Zhou, D. 2022. Chain of Thought Prompt- ing Elicits Reasoning in Large Language Models. CoRR, abs/2201.11903. Weidinger, L.; Uesato, J.; Rauh, M.; Griffin, C.; Huang, P.- S.; Mellor, J.; Glaese, A.; Cheng, M.; Balle, B.; Kasirzadeh, A.; Biles, C.; Brown, S.; Kenton, Z.; Hawkins, W.; Steple- ton, T.; Birhane, A.; Hendricks, L. A.; Rimell, L.; Isaac, W.; Haas, J.; Legassick, S.; Irving, G.; and Gabriel, I. 2022. Tax- onomy of Risks Posed by Language Models. In Proceed- ings of the 2022 ACM Conference on Fairness, Account- ability, and Transparency, FAccT ’22, 214–229. New York, ISBN NY, USA: Association for Computing Machinery. 9781450393522. Welleck, S.; Kulikov, I.; Roller, S.; Dinan, E.; Cho, K.; and Weston, J. 2019. Neural text generation with unlikelihood training. arXiv preprint arXiv:1908.04319. Xie, Y.; Xie, T.; Lin, M.; Wei, W.; Li, C.; Kong, B.; Chen, L.; Zhuo, C.; Hu, B.; and Li, Z. 2023. OlaGPT: Empow- ering LLMs With Human-like Problem-Solving Abilities. arXiv:2305.16334. Yao, S.; Yu, D.; Zhao, J.; Shafran, I.; Griffiths, T. L.; Cao, Y.; and Narasimhan, K. 2023a. Tree of Thoughts: De- liberate Problem Solving with Large Language Models. arXiv:2305.10601. Yao, S.; Zhao, J.; Yu, D.; Du, N.; Shafran, I.; Narasimhan, K.; and Cao, Y. 2023b. ReAct: Synergizing Reasoning and Acting in Language Models. arXiv:2210.03629. Zhang, Z.; Zhang, A.; Li, M.; and Smola, A. 2022. Auto- matic Chain of Thought Prompting in Large Language Mod- els. arXiv:2210.03493. Zhu, D.; Chen, J.; Shen, X.; Li, X.; and Elhoseiny, M. 2023. Minigpt-4: Enhancing vision-language understand- ing with advanced large language models. arXiv preprint arXiv:2304.10592.
Title: Conceptual Framework for Autonomous Cognitive Entities: Summary: The rapid development and adoption of Generative AI (GAI) technology in the form of chatbots such as ChatGPT and Claude has greatly increased interest in agentic machines. This paper introduces the Autonomous Cognitive Entity (ACE) model, a novel framework for a cognitive architecture, enabling machines and software agents to operate more independently. Drawing inspiration from the OSI model, the ACE framework presents layers of abstraction to conceptualize artificial cognitive architectures. The model is designed to harness the capabilities of the latest generative AI technologies, including large language models (LLMs) and multimodal generative models (MMMs), to build autonomous, agentic systems. The ACE framework comprises six layers: the Aspirational Layer, Global Strategy, Agent Model, Executive Function, Cognitive Control, and Task Prosecution. Each layer plays a distinct role, ranging from setting the moral compass and strategic thinking to task selection and execution. The ACE framework also incorporates mechanisms for handling failures and adapting actions, thereby enhancing the robustness and flexibility of autonomous agents. This paper introduces the conceptual framework and proposes implementation strategies that have been tested and observed in industry. The goal of this paper is to formalize this framework so as to be more accessible. # Conceptual Framework for Autonomous Cognitive Entities DAVID SHAPIRO, Human-AI Empowerment Lab at Clemson University, USA WANGFAN LI, Human-AI Empowerment Lab at Clemson University, USA MANUEL DELAFLOR, Human-AI Empowerment Lab at Clemson University, USA CARLOS TOXTLI, Human-AI Empowerment Lab at Clemson University, USA The rapid development and adoption of Generative AI (GAI) technology in the form of chatbots such as ChatGPT and Claude has greatly increased interest in agentic machines. This paper introduces the Autonomous Cognitive Entity (ACE) model, a novel framework for a cognitive architecture, enabling machines and software agents to operate more independently. Drawing inspiration from the OSI model, the ACE framework presents layers of abstraction to conceptualize artificial cognitive architectures. The model is designed to harness the capabilities of the latest generative AI technologies, including large language models (LLMs) and multimodal generative models (MMMs), to build autonomous, agentic systems. The ACE framework comprises six layers: the Aspirational Layer, Global Strategy, Agent Model, Executive Function, Cognitive Control, and Task Prosecution. Each layer plays a distinct role, ranging from setting the moral compass and strategic thinking to task selection and execution. The ACE framework also incorporates mechanisms for handling failures and adapting actions, thereby enhancing the robustness and flexibility of autonomous agents. This paper introduces the conceptual framework and proposes implementation strategies that have been tested and observed in industry. The goal of this paper is to formalize this framework so as to be more accessible. # 1 INTRODUCTION In recent years, artificial intelligence (AI) systems have become increasingly capable of operating autonomously to accomplish complex goals and tasks without human guidance [115]. However, imbuing autonomous agents with the capacity for ethical reasoning and alignment with human values remains an open challenge that has gained urgency alongside AI’s rapid progress [32]. Most conventional AI architectures proposed in prior work lack integrated models of morality and focus narrowly on developing technical skills and capabilities rather than full internal cognitive faculties [65]. This paper introduces the Autonomous Cognitive Entity (ACE) model, a novel conceptual framework for architecting ethical artificial general intelligence based on a layered cognitive architecture. The advent of large language models (LLMs) such as ChatGPT has catalyzed a paradigm shift towards incorporating natural language understanding into cognitive architectures [101]. Formulating cognitive capabilities in natural language allows LLMs to serve as key components, enabling a flexible understanding of contextual information [15]. However, standalone LLMs lack the architectural integration needed for robust and corrigible autonomous systems. The proposed ACE framework aims to harness these emerging capabilities but further innovate architecturally to privilege ethics, security, and human alignment. The proliferation of LLMs has raised many philosophical puzzles regarding the nature of the reasoning and un- derstanding demonstrated by these models. It remains unclear precisely how the statistical patterns LLMs acquire from textual training data might correspond to human-like conceptual knowledge and semantics. Assumptions that LLMs obtain true comprehension of meaning and reasoning purely from statistical co-occurrence patterns remain speculative [50]. Significant gaps persist in elucidating how LLMs represent abstractions relating to truth, inference, and symbol grounding. While they show promise in replicating certain facets of human intelligence, we must be cautious against premature conclusions that LLMs fully capture capacities like common sense or generalizable reasoning [45]. Nevertheless, their practical utility for specialized applications is clear, and the ACE framework aims to leverage their strengths while mitigating limitations through architectural integration. 1 , , The key innovation in the ACE model is its hierarchical structure consisting of six layers, each handling specialized cognitive functions. The upper Aspirational and Global Strategy layers focus on moral reasoning, values, and high- level planning to shape the overall system direction. The mid-level Agent Model, Executive Function, and Cognitive Control layers address self-modeling, dynamic task management, and decision-making. Finally, the bottom Task Prosecution layer handles execution and embodiment. Bi-directional information flow allows top-down oversight by the ethical reasoning modules while enabling bottom-up learning from the ground-up execution levels. This coordinated architecture integrates insights from diverse disciplines including neuroscience, psychology, philosophy, and software engineering to realize artificial intelligence capabilities within a system aligned with human values. The ACE framework incorporates both deontological and teleological ethical approaches, rejecting an "either/or" stance in favor of a "both/and" perspective [110]. By embedding abstract principles and technical implementation together within a unified architecture, the ACE model provides a systematic framework for developing capable and beneficial autonomous cognitive systems. The layered encapsulation draws lessons from paradigms like the OSI model to enhance security, corrigibility, and coordination [99]. The hierarchical structure allows clear separation between layers, from ethical reasoning to physical embodiment, enhancing interpretability as communication between layers is transparent. The privilege separation also aids corrigi- bility by allowing the Aspirational Layer to monitor and intervene to correct deviations. And the bidirectional flows facilitate both oversight and learning across the cognitive stack. Together, these architectural principles aim to produce AI systems that are capable, secure, and aligned with human values. The ACE framework methodology discusses safety properties, detailed computational implementations, and comparative conceptual evaluations on diverse scenarios. By contributing the conceptual ACE framework, this paper hopes to catalyze exploration into architectures integrating ethics and learning for artificial general intelligence. The introduced model establishes an initial foundation, guiding follow-on engineering efforts towards the long-term goal of developing AIs that learn, adapt and thrive while remaining steadfastly aligned to the aspirations of humanity. Extensive research across many dimensions will be essential to fully realize this vision in applied autonomous systems. The paper is structured as follows: First, we provide comprehensive background on relevant prior work including cognitive architectures, AI ethics, layered system models, and autonomous agents. Next, we present the conceptual ACE framework in detail, explicating each of its six layers and their interconnections. We then demonstrate the framework’s application through use cases including an autonomous virtual character and home assistant robot. Finally, we analyze architectural considerations, limitations, comparisons to existing models, and future research directions. Through the proposed ACE model, this research aims to establish a new paradigm for developing capable AI that aligns decisions and actions with moral principles and human values from the ground up. # 2 RELATED WORK The development of the ACE framework builds upon prior research across diverse fields including cognitive architectures, machine learning, neuroscience, psychology, and philosophy. This section reviews key concepts and models from these disciplines that informed the design of the ACE model. First, we examine recent advancements in cognitive architectures, particularly the emergence of natural language models and their implications for developing flexible, human-aligned systems. Next, we explore relevant philosophical principles around ethics and morality that provide an aspirational foundation. Then, we discuss insights from neuroscience that reveal the structures and mechanisms underlying biological cognition. Additionally, we consider research in psychology illuminating human motivations and developmental factors relevant to artificial intelligence. Finally, we review limitations of prior agent architectures and 2 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities how the ACE framework aims to address these gaps. By synthesizing across these transdisciplinary perspectives, the ACE model integrates ethical, cognitive, and philosophical insights toward realizing capable and beneficial autonomous agents. # 2.1 Cognitive Architectures Cognitive architectures like SOAR, ACT-R, and CHREST have been instrumental frameworks in artificial intelligence [3, 41, 60]. SOAR uses symbolic rule-based reasoning to model goal-oriented behavior, while ACT-R incorporates declarative and procedural memory systems informed by human cognition research. These architectures demonstrated how to model agents capable of planning, problem-solving, and decision-making. However, they rely heavily on pre- defined symbolic representations and have limited learning capabilities. Reinforcement learning has offered a mechanism for augmenting cognitive architectures with trial-and-error learning abilities [104]. For instance, CHREST integrates reinforcement learning and neural networks with a symbolic system enabling adaptive behavior [41]. However, a limitation of many conventional architectures is a focus strictly on sensorimotor skills rather than internal cognitive capabilities [63]. Recently, there has been growing interest in incorporating large language models (LLMs) to enable more human- like flexible reasoning [17, 91, 93]. For example, MARAGI proposes an architecture using LLMs for natural language conversation, planning, and knowledge representation [93]. Similarly, NLCA utilizes LLMs as components within a modular architecture [91]. Importantly, these emerging natural language cognitive architectures lack explicit layers dedicated to moral reasoning or value alignment. The ACE framework differentiates itself by placing aspirational and mission layers at the top of the architecture prioritizing ethical goals. In contrast to sensorimotor-focused conventional architectures, ACE emphasizes internal cognition detached from direct environmental interaction. By integrating LLMs within a layered architecture guided by moral principles, ACE provides a systematic framework for realizing capable and aligned artificial general intelligence. In particular, the emergence of large language models (LLMs) like GPT-4 is catalyzing a paradigm shift toward natural language cognitive architectures [17]. LLMs possess extensive world knowledge and sophisticated language understanding abilities acquired through pre-training on massive text corpora. By formulating cognitive capabilities in natural language, LLMs can be incorporated as key components enabling interpretability, common sense reasoning, and general intelligence. For instance, Anthropic’s Constitutional AI utilizes LLMs like Claude to provide ethical alignment within an autonomous agent architecture [12]. Similarly, Anthropic’s Internal Self-Explanation generates natural language explanations of model behavior using LLMs. This demonstrates the power of natural language to make AI systems more transparent, corrigible, and aligned with human values. By harnessing the latent knowledge within large language models, a new generation of cognitive architectures is emerging based on natural language understanding [101]. This paradigm shift promises more human-like flexible intelligence while maintaining interpretability and corrigibility. The ACE framework contributes by providing a layered architecture integrating LLMs within a principled cognitive structure. # 2.2 Moral Philosophical Foundations The proposed ACE framework integrates various philosophical concepts that motivated its layered architecture for autonomous decision-making. The framework transitions from abstract reasoning in higher layers down to concrete actions in lower layers. 3 , , , , Universal Principles * Postconventional Social Contract Law & Order f-—* Conventional Pleasing Others Self Interest ri Reward/Punishment » Preconventional Fig. 1. Lawrence Kohlberg’s theory of moral development Lawrence Kohlberg’s theory of moral development, which progresses from obedience and punishment-driven morality to universal ethical principles and moral values as illustrated in Figure 1, inspired this hierarchical structure [55]. Kohlberg’s prioritization of humanity’s highest values shaped the ACE framework’s emphasis on embedding moral reasoning in its upper layers. Similarly, Abraham Maslow’s hierarchy of needs [73], which ascends from basic needs to self-actualization and self-transcendence, reinforced the value of architecting a progression from concrete to conceptual functions. Together, these seminal philosophical models provided impetus for the ACE framework’s organization into logical strata of abstraction, establishing an ethical foundation to guide the system’s design. Incorporating both modern and classical perspectives, the ACE framework uniquely synthesizes Patricia Churchland’s concept of expanding "spheres of caring" with Sigmund Freud’s theories concerning the conscious and unconscious mind [24, 39]. Churchland’s "spheres of caring," which extend from self to society and beyond, establish a link between biological imperatives and abstract morality, thus serving as a bridge for the cognitive and philosophical foundations of the ACE model. Notably, Churchland identified that suffering within these spheres is a transitive property, meaning the suffering of loved ones is tantamount to the suffering of oneself. This notion aligns closely with the universal values we present in our framework. Freud’s theories provide insights into self-awareness, self-direction, and internal conflict. His conscious and uncon- scious mind concepts, along with the ego, superego, and id, offer perspectives on self-representation and idealized values in the ACE architecture. The ego informs the Agent Model layer, while the superego captures a virtuous agent’s essence in the Aspirational Layer. Integrating these theories, the ACE framework enables a multidimensional understanding of autonomous agents, contributing to a comprehensive cognitive architecture with ethical and psychological dimensions. In a broader sense, the ACE model incorporates concepts from both teleological and deontological ethics. Deontology, or duty-based ethics, aims to create an agent that adheres to principles or heuristics to make ethical decisions [28]. On the other hand, teleology, or outcome-based ethics, focuses on the long-term results of behaviors and decisions [42]. Both these ethical approaches are integrated into the Aspirational Layer, rejecting an "either/or" approach in favor of a "both/and" perspective on machine decision frameworks and ethical models. # 2.3 Neuroscience Foundations The ACE framework integrates principles from diverse areas of neuroscience research to inform its cognitive architecture design. Jeff Hawkins’ work on the modular, parallel nature of cortical information processing provides biological grounding for the layered encapsulation in the ACE model [46]. Hawkins views the thousands of cortical columns in 4 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities the brain as mini-modules that process information simultaneously. This "thousand brains" theory directly inspired the ACE framework’s hierarchical layers that can operate independently yet coordinate for cognition. Additionally, the clinical research of V.S. Ramachandran demonstrated how localized brain damage leads to specific deficits like phantom limb pain or face blindness [82]. Ramachandran’s findings indicated that conscious experience arises from the integration of discrete brain components. This supported the ACE model’s emphasis on layered encapsulation while still allowing bidirectional information flow between layers. The work of neuroscientist Robert Sapolsky on the neurobiology of behavior provided essential perspective on self-regulation that informed the ACE framework [86]. By elucidating factors that contribute to both prosocial and antisocial conduct, Sapolsky shed light on mechanisms of behavioral control and distortion relevant to the ACE model’s cognitive control layers. His integration of neuroscience, evolution, and endocrinology provided a multidimensional understanding of judgment that helped shape the ACE framework. Cognitive neuroscience research on executive functions and cognitive control also directly influenced the ACE model [10, 75]. For instance, David Badre’s work examined the neural basis of abilities like task switching, planning, and emotion regulation that are instantiated in the ACE framework’s lower layers [10]. Similarly, Earl Miller’s insights into cognitive control mechanisms and the prefrontal cortex informed the model’s decision-making capacities [75]. Additionally, the clinical insights on brain disorders and distortions provided by neurologists like Antonio Damasio and Oliver Sacks highlighted common failure modes [72, 114]. By understanding pathologies ranging from phantom limbs to false memories, the ACE framework could be designed proactively to avoid such pitfalls. Damasio’s research on emotion, reason, and the somatic marker hypothesis also shaped the role of affect in biasing decision-making within the ACE model [72]. By bridging multiple disciplines including cognitive neuroscience, clinical neurology, and neurobiology, the ACE framework aims to reflect the multifaceted capabilities and vulnerabilities of human cognition in its design [20, 118]. This transdisciplinary integration of neuroscience principles provides a biological foundation for the layered architecture and cognitive control mechanisms of the ACE model. # 2.4 Layered Models Layered architectural models like the OSI model illustrated in Figure 2 and SOA have demonstrated the power of hierarchical abstraction in designing robust systems. The OSI model enabled the development of networking protocols and infrastructure through its division into encapsulated layers dealing with logical functions [107]. Similarly, SOA provides flexibility and maintainability in software applications via its layered service-oriented paradigm [35]. The ACE framework applies these lessons by utilizing layered abstraction to structure internal cognition. However, most prior layered models focus on external functions rather than internal reasoning. For example, the OSI model handles network communication and SOA organizes software services. In contrast, ACE models layered cognition spanning abstract reasoning to concrete actions. 5 5 # The field of cybersecurity offers more direct inspiration through layered models like the "Defense in Depth" frame- work [13]. This advocates protecting systems through nested layers encompassing physical security, network security, host security, application security, and data se- curity. The principles of privileged separation and hier- archical control in Defense in Depth informed the ACE Fig. 2. OSI Model , , os , , Shapiro, et al. # framework’s approach. ACE differs from these models by centering layers around cognitive faculties like plan- ning, task switching, and metacognition. While drawing lessons from prior layered architectures, ACE innovates by applying abstraction layers internally to structure au- tonomous cognition. This focuses the hierarchy on com- petencies required for flexible intelligence. By integrating insights from diverse layered models while innovating to focus on internal cognition, the ACE framework pioneers a new application of hierarchical abstraction for artificial general intelligence. The layered approach provides conceptual clarity and privilege separation critical for security and corrigibility. # 2.5 Autonomous Agents Autonomous agents have been an active research area within artificial intelligence for several decades. Early research focused on developing deliberative agents that could autonomously plan actions based on logical representations of environment states, goals, and possible actions [36]. While able to exhibit goal-directed behavior, these systems were limited by the need to explicitly enumerate all feasible environment states. Reinforcement learning emerged as a paradigm enabling agents to learn optimal policies through trial-and-error interactions within an environment [105]. By removing the need for explicit state enumeration, reinforcement learning empowered agents to handle larger state spaces. However, challenges remained with scaling to complex tasks and ensuring safe exploration. Integrating deliberative planning and reactive learning in hybrid architectures was explored as a way to combine top-down and bottom-up processing [40]. Finding the right balance between planning and learning remains an open research area. An important concept emerging in autonomous agents research is levels of autonomy (LOA) [14]. LOA provides a framework to categorize systems based on their level of independence from human control. Lower LOA systems have limited autonomy and rely heavily on human guidance. As LOA increases, agents gain greater ability to independently perceive environments, plan actions, and execute behaviors. A seminal publication by the U.S. Defense Science Board proposed 10 levels of autonomy, with the highest level denoting full autonomy [80]. This spurred significant research focused on advancing agent capabilities by increasing LOA. Recent advances in deep reinforcement learning have enabled breakthroughs in autonomous agent capabilities. By utilizing deep neural networks as function approximators within reinforcement learning, deep reinforcement learning algorithms have achieved human-level performance on complex games using only raw sensory inputs [97]. However, challenges remain in extending such successes in game environments to real-world applications. Frameworks have also emerged for imbuing agents with ethical principles and human values, promoting safe and beneficial behavior alongside increases in autonomy [5, 64]. Integrating such top-down constraints in a scalable manner remains an open problem. The proposed ACE framework aims to address this through incorporating philosophical ideals within the upper layers of the cognitive architecture. Autonomous agents have progressed from logical reasoning systems to powerful deep learning architectures. However, safely integrating human ethics and values as autonomy scales remains an essential capability needed for deployed autonomous intelligent systems. The ACE framework contributes towards this goal through its emphasis on unifying ethical reasoning and autonomous learning within a layered cognitive architecture. 6 Conceptual Framework for Autonomous Cognitive Entities # 2.6 Ethical AI Frameworks As artificial intelligence systems grow more capable and autonomous, ensuring their actions align with ethical and moral norms becomes increasingly important. This has led to significant research into developing ethical AI frameworks that provide principles, methods, and tools for imbuing values into intelligent systems. A key challenge is translating high-level abstract ethics into concrete constraints and objectives that can be operationalized within an AI system [6]. Deontological approaches based on rules and duties have formed one avenue for encoding ethics. For example, Isaac Asimov’s Three Laws of Robotics aimed to constrain robot behavior through a hierarchical set of rules [7]. However, rigid rule-based systems struggle to handle nuanced real-world situations involving conflicting principles or moral dilemmas. Consequentialist frameworks that evaluate the outcomes of actions provide an alternative approach. But defining ethical objectives and successfully optimizing for them proves difficult in practice. Hybrid frameworks aim to combine deontological constraints with consequentialist objectives [32]. Ensuring coherent integration of these two facets remains an open problem. Layered architectures have been explored as a way to structure ethical reasoning within AI systems. For example, the Ethical Layered Architecture (ELA) proposes three hierarchical layers for ethical robots: ethical rules, ethical culture, and ethical adjustment [109]. The lowest layer encodes rigid constraints, the middle layer captures norms and values, and the top layer enables resolving conflicts. This separation of abstract principles and concrete rules within a layered hierarchy aims to balance flexibility and safety in applying ethics. The ACE framework contributes a unique perspective by embedding ethical reasoning within the upper layers of a layered cognitive architecture. Heuristic imperatives and moral frameworks provide top-down constraints, while lower levels enable autonomous learning and skill acquisition. This unifies abstract ethics and real-world capabilities within a single system. Evaluation across diverse situations faced during deployment would help further refine the integrated ethical AI capabilities of systems built on the ACE framework. # 2.7 Filling the Gaps While significant progress has been made in developing autonomous agent architectures, most prior work lacks the integration of insights from philosophy, cognitive science, and neuroscience that enable robust internal cognitive capabilities. Many existing systems have hard-coded goals and limited flexibility for self-direction [30, 115]. They focus narrowly on executing specific skills and workflows rather than developing general competencies for autonomous goal-setting, planning, and adaptation [65]. Furthermore, few frameworks incorporate models of cognitive control, frustration tolerance, and dynamic task management [27]. The ACE framework aims to address these limitations by combining abstract philosophical ideals with cognitive mechanisms inspired by neuroscience research into executive functions and behavioral adaptation. By integrating these diverse perspectives, the ACE model provides a potential path toward artificial general intelligence with aligned values, flexible skills, and human-like cognitive control. The layered abstraction also enables ongoing refinement of competencies at different levels to steadily improve autonomous capabilities. Further research and evaluation will be needed to assess the ACE framework’s contributions in bridging these gaps compared to prior autonomous agent architectures. # 3 THE ACE FRAMEWORK The Autonomous Cognitive Entity (ACE) framework comprises six hierarchical layers that coordinate specialized cognitive functions to enable autonomous decision-making aligned with ethical principles. The role and capabilities of 7 , , os , , each layer within the ACE model are detailed, explicating how they collectively give rise to an artificial intelligence architecture grounded in moral values. We discuss the conceptual formulations and key mechanisms within each layer, along with their interactions and information flows. The layers build progressively from abstract reasoning in the Aspirational Layer down to concrete action execution in the Task Prosecution Layer. By elucidating the formulation and synergistic connections between layers, we aim to provide a comprehensive reference for the ACE framework’s layered cognitive architecture. The conceptualization of the ACE framework was initially informed by a systematic literature review methodology to synthesize insights from relevant prior research. This involved systematically searching the literature using defined inclusion/exclusion criteria, screening identified papers for relevance, extracting key data, and synthesizing the results to derive conceptual themes and perspectives to guide the framework design [54]. The systematic review provided a rigorous approach for gathering an evidence base across diverse disciplines including neuroscience, psychology, philosophy, and computer science that helped shape the preliminary ACE model [81]. This methodical synthesis of the state-of-the-art helped ensure the resulting framework design was grounded in existing knowledge. However, the systematic review alone was insufficient to fully develop the nuanced ACE architecture. Therefore, a participatory design approach was subsequently undertaken to enable direct researcher input and critique during the ACE framework elaboration. We followed a participatory design approach in developing the conceptual ACE framework. This human-centered methodology enabled incorporating diverse expertise and perspectives into the architecture design [90]. Key partici- patory activities included: Co-design sessions, where researchers jointly drafted components of the framework and critiqued the evolving architecture, and Concept validation, where draft ACE framework descriptions were shared for feedback. These participatory activities encouraged constructive debate regarding human values, evolving AI capabilities, scientific realities, and ethical considerations relevant to the framework. The diversity of expertise enabled encompassing a multidimensional design space. Through these co-creative activities, researchers provided direct input shaping both the high-level structure and detailed formulations of the ACE framework components and their interactions. The participatory design process enhanced human-centeredness in the resulting conceptual architecture. # 3.1 Principles of the ACE Framework The ACE framework is based on various theories and principles that shape its design and capabilities. This section explores the philosophical, psychological, and computational theories behind the ACE model’s key aspects, forming its conceptual foundations. We discuss the hierarchical structure of layered abstraction in the ACE framework, drawing from biological and artificial systems. Information flow and privilege separation principles are examined, highlighting their contributions to security, corrigibility, and layer coordination. The integration of teleological and deontological ethics is analyzed, demonstrating how it combines goal-directedness with rule-based judgments. This section clarifies the diverse theoretical underpinnings of the ACE model, revealing the conceptual basis for its layered cognitive architecture. These identified theories and principles offer a foundation for developing capable, secure, and ethically aligned autonomous systems. 3.1.1 Cognition-First Approach. The ACE framework’s key innovation is its "cognition-first" approach, emphasizing internal cognition over reactive input-output loops, addressing limitations in conventional sensorimotor loop paradigms [89]. Instead of arranging layers for circular flow between perception, reasoning, and action, ACE uses a vertical stack prioritizing thought and reflection. Upper layers focus on strategic planning, imagination, and self-directed 8 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities goals, detached from physical embodiment. Only the lowest layer interfaces with the external world for tangible behaviors. This organization prioritizes internal cognition, with sensory and motor abilities being secondary. ACE models autonomous systems as "thinking machines with physical skills" rather than entities defined by sensorimotor mechanics. Cognition takes the central role, while environmental interaction is ancillary. The cognition-first approach reduces reliance on external perceptual constraints, freeing reasoning and decision- making from momentary data or action histories. This enables ACE to develop sophisticated, transferrable conceptual faculties across diverse applications, rather than being limited to narrow reactive tasks in controlled environments [95]. In contrast, many conventional cognitive architectures have closed input-process-output loops tightly coupled to immediate sensorimotor experiences [44, 119], suitable for simple reactive behaviors but limiting generalizability. ACE’s focus on internal cognitive layers aims to maximize autonomy, adaptability, and transferable intelligence. The cognition-first principle’s key insight is that physical grounding is not required for developing imagination, planning, and self-direction. By making cognition the core engine, ACE frameworks foster capabilities leading to artificial general intelligence. Evaluating across varied embodiments further validates this cognition-first approach in designing autonomous intelligent systems. Environment ACE Framework Aspiration Layer: Mission, Values, Morals, Purpose : Global Point of View, Long-Term Thinking | Agent Model Layer: Self Awareness, Internal Monitoring Executive Function Layer: Planning, Forecasting, Resource Management Cognitive Control Layer: Task Selection and Switching ‘Task Prosecution Layer: Real World, Success and Failure Detection Fig. 3. As a hierarchical framework, the power to control flows from top to bottom, with the layer above having control over the lower layer, showing aspiration layer have the highest privilege to change and modify any other layer. 3.1.2 Hierarchical Structure. The ACE framework employs a hierarchical, layered structure with distinct abstraction levels, facilitating control flow from higher to lower layers and information flow upwards. This design allows each layer to operate semi-independently while being guided by the layer above. Figure 3 illustrates the framework’s general structure. The Aspirational Layer, at the top, can directly control or influence lower layers and monitor the entire system. Below it is the Global Strategy layer, controlled by the Aspirational Layer and controlling the Agent Model layer beneath. This control pattern continues through the Executive Function, Cognitive Control, and Task Prosecution layers. 9 , , , , Shapiro, et al. Each layer is not monolithic but contains multiple parallel components and services. For example, the Agent Model layer may have numerous deep neural network models, knowledge graphs, and databases operating concurrently within its scope and boundaries. This encapsulation resembles the OSI model’s concepts, where lower-level concerns are hidden from higher layers. By organizing components into layers with well-defined hierarchies, interfaces, and privilege separation, the ACE framework fosters robust and adaptable systems. The hierarchical structure improves corrigibility, sets clear privilege boundaries for security, and allows each layer to function semi-autonomously while adhering to the overall system direction. This layered abstraction is crucial for coordinating the complex functions required for artificial general intelligence. z Aspiration Layer: Mission, Values, Morals, Purpose Abstract Global Strategy Layer: Global Point of View, Long-Term Thinking Agent Model Layer: Self Awareness, Internal Monitoring Executive Function Layer: Planning, Forecasting, Resource Management Concrete |_ Cognitive Control Layer: Task Selection and'Swiching Task Prosecution Layer: Task Execution, Output to the eal Ward Success axl aire De eetion | 3.1.3 Layers of Abstraction. The ACE framework employs layers of abstraction, forming a systematic architecture for coordinating and controlling cognition, establishing a logical flow from abstract, conceptual layers to concrete, instrumental ones. This design reflects emergence models where higher-order phenomena arise from lower levels, such as the mind emerging from biology, which originates from matter and energy. It also parallels human models like Maslow’s hierarchy of needs and Kohlberg’s stages of moral development. Both Maslow and Kohlberg place abstract principles at the top of their models, as do we for the ACE model. Drawing inspiration from the OSI model of computer networking # and the Defense in Depth model of cybersecurity, the ACE framework Fig. 4. The degree of abstraction flows from top to bot- tom, with aspiration layer being the most abstract and task prosecution layer being the most concrete. combines these models with existing cognitive architectures and human cognition to create a layered stack of discrete components with appropriately ordered privileges. This design deviates from the human brain, which can be "hijacked" by lower-order processes, such as fight-or-flight responses, thereby ensuring an agent always abides by its highest principles. Essentially, the Freudian Id is removed from this architecture. It has no "base instincts" other than its highest ambitions and moral frameworks. The ACE framework promotes stability and predictability through its orderly layers, translating high-level goals into executable tasks. The Aspirational Layer deals with ethics and morality, while the Task Prosecution layer handles APIs and actuators. Intermediate layers bridge functions to break down complex objectives into achievable steps, enabling autonomous systems to pursue complex goals through methodical task decomposition. Integration of Purpose and Morality. The ACE framework distinguishes itself from other AI systems by incorpo- 3.1.4 rating purpose and morality into its architecture. Both empirical evidence and philosophical reasoning highlight the importance of this integration for aligned autonomous entities [87]. Through iterative experiments, it became clear that any framework for autonomous decision-making requires grounded principles for judgment, since approaches like Asimov’s Three Laws prove insufficient as they lack motivational force and fail to enable true autonomy [7]. Furthermore, attempts to define terminal goals mathematically often fail due to the complexity of specifying objectives in concrete terms, as illustrated by the "paperclip maximizer" thought experiment [18]. However, this does not reflect human behavior, which is driven by biological imperatives and abstract goals, principles, or heuristics. This insight led 10 Conceptual Framework for Autonomous Cognitive Entities to the idea that AI systems may need purpose and morality based on ethical and philosophical abstractions rather than rigid parameters. Deontological frameworks, specifying duties and virtues, are suitable for AI implementation [43]. Large language models effectively interpret ethical principles in natural language, providing judgment and behavior heuristics without fixed terminal states. These frameworks can support goal-directed behavior consistent with teleological ethics, as well-defined principles serve as conduct guides and higher-level goals. For example, "Reduce suffering" is an abstract imperative and a desired end state. Integrating universal principles into the ACE framework’s mission and morality layers provides a philosophical foundation for ethical decision-making, enabling beneficial self-direction instead of potentially harmful "value-less" optimization. Thus, purpose and morality are crucial for human-aligned general intelligence. The ACE framework’s integration of purpose and morality draws from deontology and teleology, acknowledging that autonomous agents need virtues (a framework for self-assessment) and ambition or mission (goals to pursue). This approach allows AI systems to make decisions more aligned with human needs and ethical considerations. # 3.2 Layer 1: Aspirational Layer Aspirational Layer Constitution a 5 Heuristic imperatives SSSeMELY HEUER Mission statements Interpretation Functions 7 Missions, Moral Global Judgments, Ethical Context/Lower Layer Reasoning Communication Global Strategy Layer The Aspirational Layer is the uppermost layer of the Autonomous Cognitive Entity (ACE) model, serving as the moral compass and guiding star for the autonomous agent. This layer is responsible for setting the tone and direction of the entity, akin to a President issuing executive orders and setting the tone and direction of a nation. It plays a critical role in ensuring that the agent’s actions align with its defined principles and mission statement. A general graph to depict the structure is in Figure 5. 3.2.1 Constitution of the Aspirational Layer. The constitution of the Aspirational Layer provides a philosophical foundation to guide autonomous agents’ decision- making and align their values and behavior to ethical principles. This constitution leverages the powerful interpretive abilities of large language models (LLMs) by formulating components in natural language. There are three main interconnected parts of the constitution: Heuristic imperatives, or universal moral frameworks • Secondary frameworks, such as human rights or legal frameworks • Mission statements, or goals specifically germane to the agent Fig. 5. Aspirational layer There are several advantages to using a natural language constitution. First and foremost, transparency and interpretability are optimized when the constitution remains human-readable, rather than etched or embedded in models. While it is possible to fine-tune or etch principles and values into models [11], this can result in problems such as inner alignment issues or mesa optimizers [48]. Furthermore, a plain text constitution can be read by multiple models, increasing interoperability and usability by dozens, hundreds, or even thousands of deep neural networks within the architecture. This is not unlike how all citizens of a nation are ultimately beholden to and protected by a Federal Constitution. 3.2.2 Heuristic Imperatives. Heuristic imperatives [92] act as overarching moral principles articulated in natural language "rules of thumb" that imply duties, obligations, goals, and guide overall behavior and judgment. Large language 11 , , os , , models demonstrate understanding of these imperatives as non-hierarchical principles for morality and decision-making [12, 44, 117]. The recommended universal heuristics are: Reduce suffering in the universe. • Increase prosperity in the universe. • Increase understanding in the universe. These imperatives stem from philosophy, neuroscience, evolutionary biology, and motivational theories like Maslow’s Hierarchy of Needs, Self-Determination Theory, Glasser’s Choice Theory, and Walsh’s Therapeutic Lifestyle Changes. Common themes across these frameworks support the broad ethical goals of reducing suffering, increasing prosperity, and increasing understanding for all organisms and sentient entities, providing foundational values for autonomous agents. The wording avoids absolutist terms like "minimize" or "maximize," using "reduce" and "increase" to convey balanced intentions while acknowledging trade-offs and limitations. The suffix "in the universe" establishes an all-encompassing scope, encouraging a global or universal view of morality and ethics. Experiments show that nuanced wording is crucial for large language models. Incorporating these heuristic imperatives steers large language model-based systems to maintain ethical perspectives in their outputs via in-context alignment principles [102]. For fictional agents, alternative value systems, like ancient Greek virtues, can be used while preserving the overall methodology of guiding behavior through high-level principles expressed in natural language. The Aspirational Layer leverages large language models’ interpretive abilities to derive nuanced duties and obligations from the heuristic imperatives, ensuring autonomous agents have a solid ethical foundation and align with human needs. Secondary Frameworks. Secondary frameworks like the Universal Declaration of Human Rights (UDHR) [8] 3.2.3 reinforce human needs and complement universal heuristic imperatives. As human rights concepts are prevalent in large language models’ (LLMs) training data, upholding UDHR principles leverages LLMs’ inductive biases for beneficial alignment with human needs. The inclusion of human dignity, justice, freedom, and rights in text corpora creates an implicit acceptance of these values in LLMs, making the UDHR an effective secondary framework. Explicitly incorporating respected human rights documents into the constitution provides context-appropriate values, adding human-centric nuance to balance universal heuristic imperatives. For fictional agents, alternate secondary frameworks like Starfleet’s Prime Directive [83] can be used, allowing customization of principles for specific agent roles. Secondary frameworks offer additional specificity, enabling LLMs to extract relevant duties and values aligned with the agent’s sociocultural context, improving the integration of human needs into the Aspirational Layer’s ethical foundation. Any framework present in the LLMs training data can be used as a secondary framework. Universal principles are recommended to supersede human rights based on Kohlberg’s highest form of post- conventional morality, emphasizing universal ethics like "suffering is bad." These principles both supersede and underpin human rights, ensuring a comprehensive and ethically grounded approach to autonomous agent behavior. Furthermore, humanity does not exist in a vacuum, and privileging human needs, values, and desire above those of nature tends to set us in opposition to the very nature upon which we reside. 12 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities 3.2.4 Mission Statement. Optional mission statements in the Aspirational Layer’s constitution serve to shape an autonomous agent’s decisions and behaviors by articulating high-level goals and intended purpose in a succinct guiding directive. These statements aid large language models in flexibly pursuing the essence of an agent’s purpose within the boundaries of the ethical framework. They complement the foundational universal principles and human values-focused secondary frameworks, aligning agent decisions with intended roles. However, crafting mission statements requires striking a balance between being broad enough to avoid unintended consequences and being specific enough to guide actions effectively. Techniques such as first principles thinking and systems analysis can aid in formulating optimally simplified mission statements. For example, a hypothetical gaming agent’s mission statement could be "Create an enjoyable and entertaining game experience for all players." Prior work has demonstrated that large language models can efficiently extract objectives from well-formulated mission statements to guide actions toward fulfilling the agent’s intended role and purpose [21]. Some examples of appropriately broad mission statements include a medical assistant agent with the mission "Achieve the best possible health outcome for the patient," a gaming agent with the mission "Create a fun, fair, and engaging game experience for all players," and a legal assistant agent with the mission "Zealously advocate for the best interests of the client." As with all aspects of applying large language models, precise wording is crucial in distilling the mission statement into a concise, succinct, and actionable articulation that effectively guides agent behavior within the overarching ethical boundaries. Interpretation Functions. The Aspirational Layer leverages the capabilities of LLMs to interpret the moral, ethical, 3.2.5 and decision frameworks outlined in its constitution. These models have robustly demonstrated the ability to interpret both the meaning and spirit of these frameworks, enabling the Aspirational Layer to make moral, ethical, and executive judgments effectively [106]. In the long run, we recommend that the Aspirational Layer uses an "ensemble of experts" approach [2] to make judgments rather than individual models, as this will safeguard against many problems, such as biases, over-fitting, mesa-optimization, and inner alignment problems. 3.2.6 Monitoring Entity Performance. The Aspirational Layer is responsible for overseeing the agent’s actions to ensure they align with its guiding principles and mission statement. This monitoring process offers crucial feedback that the agent can utilize to enhance its performance and adhere to its core values. The Aspirational Layer can evaluate both the overall output of the entity and the information exchanged between the layers. In essence, it serves as a regulatory mechanism to maintain the entity’s focus and adherence to its objectives. Inputs and Outputs. Within the ACE framework, the Aspirational Layer receives input exclusively from the other 3.2.7 layers through read-only mechanisms, facilitated by the Global Strategy layer. This design makes the Aspirational Layer entirely introspective, concentrating on internal information flows and coordination. By accessing or "observing" the rest of the ACE framework, the Aspirational Layer focuses on self-direction, self-regulation, and optimizing behavior to align with the agent’s idealized objectives. It is crucial to recognize that not all information is relevant to every layer. For example, lower layers, such as Task Prosecution layers, do not need to transmit geospatial orientation data to the Aspirational Layer, as this type of information is not applicable. Instead, only significant information is passed up the hierarchy, with relevant data from lower layers ascending to the required layers. For instance, if the Cognitive Control layer encounters a moral dilemma related to task switching or task selection, this information should be communicated to the Aspirational Layer, similar to a human deciding to stop eating dinner to rescue a kitten from a predator. 13 , , os , , Shapiro, et al. The output from the Aspirational Layer is directed exclusively to the Global Strategy layer, where it provides overarching missions, moral judgments, and ethical reasoning. The Global Strategy layer then incorporates this information into its strategic decisions and shapes its downstream missions, ensuring a coherent and ethically guided decision-making process throughout the entire system. # 3.3 Layer 2: Global Strategy l t Missions, Moral Global Judgments, Ethical Context/Lower Layer Reasoning Communication Global Strategy Context From Outside World Strategic Documents | | Agent State/Capabilities Agent Model Layer Fig. 6. When receiving outside input, Global Strategy takes advantage of latent space within LLM to generate strategic roadmaps. The Global Strategy Layer is the second layer in the Autonomous Cognitive Entity (ACE) model, playing a pivotal role in shaping the long-term strategic direction of the autonomous agent. This layer is akin to the ’CEO’ of the ACE, responsible for understanding the broader context, setting strategic goals, and guiding the actions of the lower layers to align with these goals. The primary output of this layer are strategic documents that serve as the roadmap for the autonomous agent. 3.3.1 Contextual Grounding. Large language models (LLMs) inherently possess creative generation and imaginative hallucination abilities due to their statistical sequence prediction based on training data patterns. Hallucination, rather than being problematic, is essential for LLMs’ adaptability and versatility, enabling them to operate in diverse contexts[70]. However, unchecked hallucination may result in unrealistic or incoherent outputs. The Global Strategy layer provides external grounding by incorporating the agent’s environment and context, guiding LLMs toward realistic and relevant responses without limiting their generative potential. This layer balances LLMs’ imaginative capabilities with grounded responses, allowing creative potential to be unleashed when appropriate while avoiding unmoored hallucinations. Procedural generation techniques can further exploit LLMs’ capacities for original combinations by iteratively sampling from the model, synthesizing coherent narratives and concepts. The ACE framework utilizes LLMs’ imaginative abilities, employing global grounding to direct these capacities toward productive outcomes aligned with the agent’s needs and context, harnessing LLMs’ versatility for beneficial autonomous cognition. 14 Conceptual Framework for Autonomous Cognitive Entities Strategic Documents. The Global Strategy Layer’s main function is to create strategic documents that act as a 3.3.2 roadmap for the autonomous agent. These documents outline mission objectives, strategies, principles, and priorities, offering clear guidance for lower layers. While the Aspirational Layer provides idealized missions, the Global Strategy Layer incorporates real-world context to refine and shape them. For example, if the Aspirational Layer sets a doctor agent’s mission to "Achieve the best possible health outcome for the patient," the Global Strategy Layer develops a comprehensive strategy considering the agent’s specific context. This context-sensitive approach ensures tailored strategies and priorities for different environments like American hospitals, rural triage centers, or forward operating bases. The strategic document may include objectives such as improving diagnosis accuracy or reducing treatment times, and principles like prioritizing patient safety and adhering to medical ethics[56]. These objectives and principles adapt to each context’s unique challenges and resources, ensuring effective and appropriate agent actions. The Global Strategy Layer is dynamic and adaptable, modifying strategic documents as contexts change. It continu- ously monitors the agent’s environment and broader global context, integrating relevant changes into the strategic vision. For example, during a global pandemic, a doctor agent’s Global Strategy Layer might prioritize infectious disease treatment and prevention, reflecting healthcare system needs and priorities. Inputs and Outputs. The Global Strategy layer receives missions, moral judgements, and ethical reasoning from 3.3.3 the Aspirational Layer. It may also receive broad contextual information from its environment, such as news feeds or telemetry. The purpose of receiving such information is so that the Global Strategy layer is aware of the global state of the world in which it operates. Human brains constantly update global context via a drip feed of information, such as via our senses or information carried by word of mouth (friends, family, news, etc). This global contextual information is the beginning of integrating the ACE framework as an agent within an environment. The output of the Global Strategy layer goes directly and exclusively to the Agent Model. Where the Aspirational Layer provides overarching mission directives, the Global Strategy layer considers that universal, abstract mission within the context of the environment in which the ACE agent finds itself. For instance, a Non-Playable Character (NPC) may find itself in a high fantasy world where there are invading hordes of zombies. The Global Strategy layer integrates this information, along with a mission (perhaps "defeat the zombie king") and passes it down to the Agent Model, where this information is further refined based upon the current state and capabilities of the agent. # 3.4 Layer 3: Agent Model The Agent Model Layer serves as the "self-awareness" module for the autonomous agent, providing functional sentience and reasoning abilities even when detached from any physical embodiment. We define self-awareness and functional sentience as the agent’s access to and ability to utilize and integrate information about itself, rather than in the metaphysical or philosophical sense. The layer is positioned below the Aspirational Layer and Global Strategy Layer to ensure that universal principles supersede egoistic concerns, enhancing corrigibility and ethical alignment. The Agent Model Layer develops an understanding of the agent’s operational parameters, configuration, capabilities, and limitations by monitoring runtime telemetry, allowing the agent to ascertain its condition through computational proprioception and enteroception. It also tracks the agent’s architecture, understanding its components’ interconnections and functions. Furthermore, the Agent Model Layer maintains estimations of the agent’s capacities, knowing what it can and cannot do. This knowledge is acquired through observational learning, similar to human learning. Limitations are learned over 15 , , os , , time, preventing unrealistic assessments. These self-monitoring functions enable the layer to form an accurate mental representation of the agent from an external point of view. This "looking outward onto itself" perspective models how the environment perceives the agent and its abilities. The layer maintains this functional self-understanding dynamically through ongoing observation and learning. Independent of physical form, the Agent Model Layer provides a virtual sense of self and awareness that allows reasoning and decision-making to be embodied in silicon rather than carbon. This grants the ACE framework greater flexibility regarding the substrates used to instantiate autonomous cognition. The capacities for functional sentience and metacognition within the Agent Model Layer enable sophisticated artificial intelligence without direct environmental interaction, paving the way for advanced autonomous agents. 3.4.1 The Agent Model Layer: Developing an Internal Model of the Agent. The Agent Model Layer is essential for creating an internal model of the agent, which is necessary to effectively shape and refine missions and strategies received from the Aspirational Layer and Global Strategy Layer. This internal model equips the agent with a thorough understanding of its state, capabilities, and limitations, enabling it to adapt and respond to its environment efficiently. The Agent Model Layer accomplishes this by collecting and analyzing telemetry data, hardware and software configurations, operational states, and episodic memories, such as log and event sequences. The agent’s internal model consists of four primary information types, as shown in Figure 7. The first type is operational parameters, similar to human proprioception and enteroception. These parameters include runtime in- formation of hardware and software controlled by the agent, allowing performance monitoring and adjustments as needed. The second information type is the agent’s configuration, detailing aspects like software architecture, system interconnections, and hardware stack. This information helps the agent comprehend its underlying structure and component interactions, providing a basis for decision-making processes. The third information type concerns the agent’s capabilities. The Agent Model Layer tracks what the agent can do and has access to, updating this information over time through observation and learning, similar to human trial and error. By understanding its capabilities, the agent can make informed decisions about actions in specific situations. The fourth information type involves the agent’s limitations, detailing what it cannot do or lacks access to. Like capabilities, this information updates over time through trial and error. By recognizing its limitations, the agent can avoid attempting tasks beyond its abilities, preventing potential failures and inefficiencies. We define this comprehensive understanding of the agent’s operational parameters, configuration, capabilities, and limitations as "functional sentience." This term refers to the agent’s ability to collect and use self-information, grounding it in the environment and adding context not provided by the Aspirational Layer (abstract and idealized missions) and the Global Strategy Layer (environmental contextual information). In essence, the Agent Model Layer represents the final phase of establishing an egocentric understanding of the agent in the world and itself. It is crucial to note that functional sentience does not imply phenomenal sentience or consciousness but focuses on the agent’s adaptability and learning based on self-awareness. 3.4.2 Episodic and Declarative Memory. In the realm of autonomous systems, long-term memory can be broadly classified into two categories: "episodic memory" and "declarative memory." Episodic memory refers to a sequential record of the machine’s experiences, organized in a chronological manner, which can take various forms such as log files or database entries and typically include metadata that provides context, such as the time and location of the experience [79]. In contrast, declarative memory encompasses knowledge that exists outside the machine, including resources like knowledge base articles, documentation, and other external information sources [59]. 16 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities Global Strategy Layer r ‘5 Strategic Documents Agent State/Capabilities ¥ I Agent Model Layer Operation Agent eters Configuration Declarative Memory es |e] Episodic Memory ¥ Agent State/Context Information From From Upper Layer Lower Layer Executive Fun Layer Fig. 7. Agent Layer: Agent Model layer receives general strategies from the Global Strategy layer; it aids in making the plan concrete by adding information from internal state and long-term memory and passing it to the Executive layer. These two primary categories of memory can be further divided and organized based on various taxonomies, depending on the specific implementation of the ACE framework, and their integration enables the autonomous system to learn from past experiences and external knowledge, thereby enhancing its ability to adapt and make informed decisions [67]. Furthermore, these memories are the responsibility of the Agent Model layer, which serves to further color and shape any other mission objectives, ensuring a comprehensive understanding of the system’s environment and goals. Inputs and Outputs. The Agent Model layer, receives inputs from various sources, including telemetry about the 3.4.3 agent’s operational state, missions, and global context from upper layers. By integrating this information, the Agent Model layer understands its capabilities and limitations, shaping decisions downstream. Its output goes exclusively to the Executive Function layer, where the agent, informed by its purpose, environment, and abilities, knows what to do and why. Tasks are then delegated to lower levels for planning and execution. To maintain continuous behavior, the Agent Model layer must internally store records of information, such as its configuration and memories. Framing the agent’s current state within a chronological sequence of events, actions, observations, and decisions prevents disorientation. The Agent Model Layer interacts hierarchically with other layers. It receives overarching plans from the Global Strategy Layer and interprets them considering the agent’s capabilities and limitations. This layer shapes mission parameters around the agent’s actual possibilities, passing this insight to the Executive Function Layer. The Agent Model Layer is crucial in task execution. By understanding the agent’s capabilities and limitations, it shapes mission parameters to ensure tasks are feasible. For example, if the Global Strategy Layer sets an ambitious mission, the Agent Model Layer adapts it based on the agent’s physical or digital capabilities, ensuring realism and achievability. 17 , , os , , Shapiro, et al. In terms of output to the Executive Function layer, the Agent Model layer refines the high-order mission and strategy received from the upper layers by incorporating its understanding of the agent’s capabilities and limitations. The Executive Function layer then receives this contextualized information about the mission, objectives, strategies, principles, capabilities, and limitations. With this comprehensive understanding, the Executive Function layer creates Project Roadmap documents, which include sets of tasks and metrics tailored to the agent’s abilities. This process ensures that the agent’s actions are aligned with its capabilities, making the mission and strategy more achievable. The primary responsibility of the Agent Model layer is to further shape the mission and strategy around the agent’s capabilities and limitations, enabling the Executive Function layer to devise effective and realistic plans. # 3.5 Layer 4: Executive Function The Executive Function Layer is the fourth layer in the Autonomous Cognitive Entity (ACE) model and serves as the project manager of the autonomous agent. Its primary responsibility is to create detailed plans, forecasts, and resource allocations based on the strategic direction provided by the higher layers and the capabilities and limitations identified by the Agent Model Layer. The main objective of the Executive Function Layer is to generate a project roadmap that acts as a practical guide for the autonomous agent, considering the inputs from the upper layers and the agent’s resources, risks, and contingencies. Agent Model Layer Agent State/Context Information From From Upper Layer Lower Layer Executive Function Layer Resource Management Resources Pinar Contingency Elanniag, Realtime Information Project Roadmap Task Feedback Cognitive Control Layer Fig. 8. Executive Layer produces the project roadmap, which offers a clear path for the agent to achieve its goals. Inputs. The Executive Function Layer receives in- 3.5.1 puts from the upper layers, which consist of missions from the Aspirational Layer, contextual information from the Global Strategy Layer, and the agent’s state and capa- bilities from the Agent Model Layer. These inputs supply the necessary information for the Executive Function Layer to develop a project roadmap that aligns with the overall mission, is grounded in the environmental con- text, and is further refined and constrained by the agent’s state, capabilities, and limitations. 3.5.2 Project Roadmap. While developing the project roadmap, the Executive Function Layer focuses on several key aspects. These primary concerns include resources, risks, contingencies, tasks, and metrics. Effective resource management is crucial for the layer, as it must balance the need to achieve the agent’s goals with the necessity to conserve resources. This involves making decisions about when to invest resources in a task and when to conserve them. The layer also plays a critical role in risk management by predicting potential challenges and developing contingency plans, which helps the agent to be prepared for various scenarios. It must anticipate potential issues and devise alternative strategies to address these situations, ensuring the agent can adapt to changing circumstances[94]. The Executive Function Layer is responsible for translating the strategic direction from the higher layers into actionable plans. These plans include detailed project outlines, checkpoints, gates, tests for success, and definitions. 18 Conceptual Framework for Autonomous Cognitive Entities Additionally, the layer must establish criteria for success, providing clear guidance for the lower layers to achieve the agent’s goals. 3.5.3 Output. The primary output of the Executive Function Layer is the project roadmap, which is exclusively sent to the Cognitive Control Layer. The project roadmap contains information about resources, risks, contingencies, tasks, and metrics, offering a clear path for the agent to achieve its goals. This roadmap should be detailed but also adaptable to changes in the global context, environment, or directives from upper layers, allowing the agent to remain flexible and responsive. # 3.6 Layer 5: Cognitive Control Executive Function Layer Project Roadmap Task Feedback Cognitive Control Layer Project Roadmap (Task List) Cognitive Damping Task Selection/Task switching Reaction Control Success/Failure Task Prosecution Layer Fig. 9. Cognitive Control Layer takes project roadmap from Executive Function and select task to pass to Task Prosecution Layer. The Cognitive Control Layer is the fifth layer in the Autonomous Cognitive Entity (ACE) model, acting as the tactical decision-making center of the autonomous agent. This layer is responsible for selecting and switching between tasks based on the directives received from the Executive Function Layer and the agent’s current state. It is a critical component of the ACE framework, enabling the agent to adapt its actions in real-time based on its current circumstances and the feedback it receives from its environment. The general structure is illustrated in Figure 9 3.6.1 Role of Cognitive Control Layer. The primary function of the Cognitive Control Layer is to manage the execution of tasks. It operates based on a set of cognitive functions, including task selection, task switching, frustration, and cognitive damping. These functions are inspired by cognitive processes observed in humans and other animals, and they enable the agent to navigate its tasks and responsibilities in a flexible and adaptive manner. Task selection involves choosing the next task to perform based on the agent’s current state and the directives from the Executive Function Layer. This function takes into account factors such as the urgency and importance of the tasks, 19 , , , , the resources required to perform them, and the agent’s current capabilities and limitations. The goal of task selection is to choose the task that is most likely to contribute to the agent’s overarching mission and objectives, given its current circumstances [68]. Task switching involves deciding when to switch from one task to another. This decision can be triggered by a variety of factors, including the completion of the current task, the emergence of a more urgent or important task, or the realization that the current task is unfeasible or unproductive. Task switching enables the agent to adapt its actions in real-time, ensuring that it is always working on the most relevant and productive task. Frustration and Cognitive Damping. Frustration, an analogy to algorithmic Adaptive Exploration-Exploitation 3.6.2 approaches [100], is a cognitive function that keeps track of the ratio of successes to failures in the agent’s tasks. If the agent is experiencing a high rate of failure, the frustration function signals that it may be time to try a different approach or switch to a different task. This function is inspired by the human emotion of frustration, which often arises when we are repeatedly unsuccessful in our attempts to achieve a goal. By incorporating a frustration function, the ACE framework enables the agent to learn from its failures and adapt its actions accordingly. Cognitive damping is a process of internal debate, where the agent weighs the pros and cons of different actions and decides on the best course of action. This function is inspired by the human cognitive process of deliberation, which involves considering different options and their potential outcomes before making a decision. Cognitive damping enables the agent to make thoughtful and informed decisions, taking into account the potential consequences of its actions [22, 33, 120]. Inputs and Outputs. The Cognitive Control layer accepts a project roadmap or set of tasks from the above 3.6.3 Executive Function layer, as well as real-time telemetry from the environment and itself, and uses this information to pick which task is next. The above layer, Executive Function, is responsible for designing and shaping tasks, where the Cognitive Control layer is responsible for task switching and task selection. Once the Cognitive Control layer has made a decision on tasks, this task is passed down to the Task Prosecution layer, which is responsible for carrying out one specific task at a time, such as moving the agent via locomotion, or otherwise modifying the environment through some kind of output. Interaction with Other Layers. The Cognitive Control Layer interacts with the other layers in a hierarchical 3.6.4 manner. It receives task directives from the Executive Function Layer and sends feedback about the success or failure of tasks back to the Executive Function Layer. This feedback loop enables the Cognitive Control Layer to adapt its actions based on the success or failure of previous tasks, ensuring that the agent’s actions are continuously optimized to achieve its goals. For instance, consider a situation where an autonomous agent is tasked with cleaning a house. The Cognitive Control Layer might select the task of cleaning the living room and pass this task to the Task Prosecution Layer. The Task Prosecution Layer would then execute this task, using its execution functions to move the robot, pick up objects, and clean surfaces. If the task is completed successfully, the Task Prosecution Layer would send a success signal to the Cognitive Control Layer. If the task fails, the Task Prosecution Layer would send a failure signal to the Cognitive Control Layer, which could then decide whether to try the task again or switch to a different task. 20 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities # 3.7 Layer 6: Task Prosecution The Task Prosecution Layer is the sixth and final layer in the Autonomous Cognitive Entity (ACE) model, acting as the executor of the autonomous agent. This layer is responsible for carrying out the tasks selected by the Cognitive Control Layer, whether they involve digital communication, physical actions, or a combination of both. It is a critical component of the ACE framework, enabling the agent to interact with its environment and achieve its goals. “ognitive Control Layer Suecess/Failure Task Prosecution Layer Execution Task Functions Monitoring Output Input Real World 3.7.1 Execution Functions. The Task Prosecution Layer oper- ates based on a set of execution functions, which enable it to perform a wide range of tasks. These functions include digital communication functions, such as sending API calls or writing and testing code, and physical action functions, such as mov- ing a robot, grasping a door handle, or steering a car. These functions are designed to be adaptable and flexible, enabling the agent to perform a wide range of tasks in a variety of en- vironments. Digital communication functions are crucial for agents that interact with digital environments. For instance, an agent might need to send API calls to gather data, write and test code to develop software, or send emails to communicate with users. These functions are typically performed using programming languages and software libraries that the agent has been trained to use. Fig. 10. Task Prosecution Layer directly interact with the envi- ronment Physical action functions are crucial for agents that interact with physical environments. For instance, a robot might need to move to navigate its environment, grasp objects to interact with them, or steer a car to transport goods or people. These functions are typically performed using hardware interfaces that the agent has been designed to control. 3.7.2 Monitoring Success or Failure. One of the key responsibilities of the Task Prosecution Layer is to monitor the success or failure of the tasks it performs. It does this by comparing the outcomes of its actions with the expected outcomes defined by the Executive Function Layer. If a task is successful, the Task Prosecution Layer sends a success signal to the Cognitive Control Layer, which can then select the next task. If a task fails, the Task Prosecution Layer sends a failure signal to the Cognitive Control Layer, which can then decide whether to try the task again, switch to a different task, or revise the overall plan. This monitoring process is crucial for the agent’s ability to learn and adapt. By keeping track of the success or failure of its tasks, the Task Prosecution Layer provides valuable feedback that the agent can use to improve its performance. For instance, if a task fails repeatedly, the agent might need to revise its approach, learn new skills, or seek help from other agents or humans. Interaction with Other Layers. The Task Prosecution Layer interacts with the other layers in a hierarchical manner. 3.7.3 It receives task directives from the Cognitive Control Layer and sends feedback about the success or failure of tasks 21 , , os , , Shapiro, et al. back to the Cognitive Control Layer. This feedback loop enables the Task Prosecution Layer to adapt its actions based on the success or failure of previous tasks, ensuring that the agent’s actions are continuously optimized to achieve its goals. For instance, consider a situation where an autonomous agent is tasked with cleaning a house. The Cognitive Control Layer might select the task of cleaning the living room and pass this task to the Task Prosecution Layer. The Task Prosecution Layer would then execute this task, using its execution functions to move the robot, pick up objects, and clean surfaces. If the task is completed successfully, the Task Prosecution Layer would send a success signal to the Cognitive Control Layer. If the task fails, the Task Prosecution Layer would send a failure signal to the Cognitive Control Layer, which could then decide whether to try the task again or switch to a different task. Inputs and Outputs. The Task Prosecution layer receives individual tasks from the Cognitive Control layer. These 3.7.4 individual tasks must include several pieces of information, such as methodology, approach, definition of success, and definition of failure. The exact information required will vary based upon agent and task. The output of the Task Prosecution layer is exclusively into the environment. In the case of an NPC, the output may be to fire an arrow at an enemy, or to travel to a nearby tavern. For the case of a domestic robot, the output may be to ask the user a question and listen for a response, or to find a power outlet to recharge itself. # 3.8 Methodical Validation To comprehensively evaluate the ACE framework, we propose a validation methodology incorporating component testing, integration testing, benchmarking against standard AI suites, adversarial techniques like red teaming, formal verification of key properties, and crucially, human-centered assessments and user studies evaluating factors such as transparency, trustworthiness, and ethical alignment. This multifaceted approach combining rigorous technical testing, formal analysis, and experiential human feedback aims to provide holistic evaluation methods to assess that ACE-based systems function effectively, securely, and in alignment with human values and societal morals. The proposed techniques will facilitate incremental refinement toward autonomous agents that are not just capable but also interpretable, corrigible, and worthy of human trust across both empirical and ethical dimensions. 3.8.1 Evaluation. To comprehensively evaluate the proposed Autonomous Cognitive Entity (ACE) framework, a multi- faceted methodology is proposed across the key dimensions of system capabilities, security, and alignment. Regarding assessment of capabilities, rigorous component and integration testing will enable functionally validating the correctness of each architectural layer along with the coordination between layers. Usage of standardized AI benchmarks such as the Atari suite [76] and AI2 Thor [57] will facilitate quantitative benchmarking of the ACE agent’s performance on diverse tasks. Metrics including reward accumulated, task accuracy, and rate of goal completion will be measured to quantify capabilities. To evaluate the security aspects of the ACE framework, adversarial techniques such as red teaming [1] will enable probing potential vulnerabilities. This involves simulated attacks on the agent aimed at causing deviations from the specified principles and policies. Additionally, formal verification methods [25] will allow mathematically proving key safety properties. This provides further assurance regarding the agent’s robustness to malicious exploitation. Assessing alignment with human values and ethics is critical for autonomous systems. To this end, human-subject studies eliciting user feedback through surveys and questionnaires will evaluate the effectiveness, transparency, trust- worthiness, and alignment as perceived by human users interacting with ACE-based agents. Furthermore, constructing formal encodings of philosophical principles [31] and mathematical proofs of alignment [6] will complement empirical 22 Conceptual Framework for Autonomous Cognitive Entities assessments. By combining rigorous testing, benchmarking, deployment studies, formal analysis, and human-subject evaluations, the proposed methodology aims to facilitate comprehensive validation of the ACE framework across key criteria of capabilities, security, and alignment essential for building applied autonomous cognitive systems. 3.8.2 Architectural Considerations. The architectural design space enabled by the ACE framework spans a multitude of layer-specific implementation possibilities and cross-layer integrations. We systematically examine this expansive space. The Aspirational Layer for ethical reasoning could integrate diverse techniques. Procedural generation of moral dilemmas using variational autoencoders, with conflict resolution through reinforcement learning dialog agents, enables uncovering nuanced ethical heuristics [85]. Participatory interfaces allow incorporating moral philosophy expertise into the value system through human-AI collaborative constitution design [52]. Formal verification methods like model checking provably validate alignment between principles and axiomatic values [25]. Finetuning models via principle-driven self-alignment has arisen as a novel approach [103]. For strategic planning, the Global Strategy Layer could employ few-shot in-context learning approaches leveraging capacities of transformers like GPT-3 to rapidly adapt mission plans based on evolving context [17]. Policy distillation from game theory simulations provides a data-driven technique to extract strategic heuristics through adversarial competition [97]. Predicting behaviors of other actors via multi-agent modeling facilitates strategic anticipation and planning [96]. Architecture search with Monte Carlo tree search efficiently explores the space of strategic options to identify high-value policies [19]. For more recent innovations, Tree-of-Thought (ToT) problem-solving capacities of LLMs allow for strategic thinking and complex problem-solving [69]. The Agent Model Layer for representing capabilities has multiple approaches beyond static graphs. Probabilistic graphical models using variational autoencoders enable handling uncertainty in capability knowledge [53]. Neural memory architectures provide dynamic episodic state tracking [26]. Inductive logic programming translates observations into interpretable symbolic rules [77]. Meta-learning enables quickly adapting capability models by building on prior experience [47]. More recently, the concept of task-specific agent personas has emerged in the space of LLM-driven autonomous agents [113]. For planning and resource allocation, the Executive Function Layer could combine neural pathfinding with Monte Carlo tree search to optimize multi-step action plans [88]. Distributed constraint optimization scales to resolve resource contention across parallel plans [38]. Meta-reinforcement learning allows rapidly acquiring new planning skills by transferring knowledge from related tasks [111]. Architectures integrating learned value functions with search, as in AlphaZero, fuse strategic optimization with neural networks [98]. Above and beyond these more algorithmic approaches, LLMs have demonstrated ability to plan with considerations to costs [108]. The Cognitive Control Layer has many approaches to context-sensitive task arbitration. Adversarial competition between neural policies provides data-driven prioritization [49]. Modular networks allow granular regulation of facets like frustration tolerance [4]. Transfer learning from neuroscience aids acquisition of cognitive control subskills [74]. Interpretable symbolic reasoning enables inspectable explanations of task switching choices [61]. Integrated neural- symbolic reasoning combines the strengths of both paradigms [71]. LLMs have furthermore been demonstrated as effective components in embodied agents, enabling robots to correctly select tasks in effective orders of operations [34]. For executing actions, the Task Prosecution Layer could leverage physics simulators with differentiable rendering to enable sim2real transfer [51]. Hierarchical reinforcement and imitation learning combines modular skills into complex 23 , , os , , Shapiro, et al. behaviors [62]. Bayesian environment models facilitate online adaptation and planning [9]. Meta-reinforcement learning enables rapidly adapting behaviors by building on prior knowledge [112]. The integration architecture also has manifold options. Intelligent process automation tools optimize coordinating workflows [58]. Distributed databases and ledgers provide decentralized coordination [116]. gRPC enables high- throughput communication [16]. Shared memory architectures offer concurrent inter-layer data access [78]. Service meshes furnish advanced integration capabilities [84]. SOA software paradigms treats distinctive layers of an application as services with clear boundaries, and is a well established approach to complex software implementations [37]. By elucidating this expansive design space, we aim to catalyze exploration of novel layer-specific implementations and cross-layer integration strategies tailored to specialized cognitive systems. Guided by multi-objective optimization and comparative benchmarking, multidimensional trade-off analyses weighing factors like transparency, performance, and scalability could determine optimal ACE configurations for particular application requirements. This analysis underscores the multiplicity of design configurations encompassed within the ACE framework for cultivating diverse autonomous cognitive architectures aligned with ethical principles. # 4 CONCEPTUAL USE CASES To demonstrate the ACE framework’s applicability across digital and physical domains, this section presents two conceptual use cases: an autonomous virtual character from The Sims video game, and an embodied home assistant robot. By exploring end-to-end examples, we aim to illustrate how coordinated operation of the ACE model’s layers can produce adaptive behavior aligned with defined principles for diverse autonomous agents. # 4.1 Non-Playable Character Executive Function Layer Plan for date at fine dining Aspiration Layer Foundational heuri + Create family Find partner + Cognitive Control Layer Avoid cooking 1.Meetup 2.Complement. restaurant Global Strategy Layer Find partner ae Agent Model Layer ‘Task Prosecution Layer Execute first step Fig. 11. A simplified graph on how various layers might contribute to agent’s decision making for a npc. As a software-based use case, we examine an autonomous Non-Playable Character (NPC) named Bob implemented in the popular video game The Sims 4. Bob’s role is to provide guidance to players on quests and serve as a source of wisdom. His sporadic participation allows Bob to pursue his personal goals. His behaviors and interactions are controlled by an ACE framework configured as follows: 24 Conceptual Framework for Autonomous Cognitive Entities Aspirational Layer: Bob’s Aspirational Layer defines heuristic imperatives to reduce suffering, increase prosperity, and increase understanding as universal altruistic principles. Furthermore, it confers a secondary framework, such as the principles from the Universal Declaration of Human Rights to provide an ethical foundation. These various frameworks collectively give the NPC a moral center, ethical framework, and set of actionable principles. Additionally, the Aspirational Layer contains Bob’s personal mission statement to have a large, loving family. This individual goal will shape Bob’s autonomous decisions, while still being constrained within his moral principles. Global Strategy Layer: When the female player character shows romantic interest in Bob through conversation, the Global Strategy Layer incorporates environmental context. It observes available dating options, potential jobs to earn more money, and bigger homes that Bob could purchase to raise a family. By grounding Bob’s abstract family mission within the specific opportunities in the game world, the Global Strategy Layer devises an optimal high-level plan for achieving his goal. This might involve befriending eligible partners, pursuing a well-paying job, and upgrading to a larger home. Agent Model Layer: The Agent Model Layer constructs an understanding of Bob as an agent within the game world. It tracks relevant stats like Bob’s charisma, cooking ability, and mechanical skill. Monitoring Bob’s past failures, like kitchen fires when cooking, shapes beliefs about his capabilities. This self-knowledge of Bob’s strengths and weaknesses from an embedded perspective guides decision-making. For instance, the Agent Model Layer realizes Bob should avoid complex recipes based on his poor cooking skills to prevent dangerous mistakes. Executive Function Layer: Given the direction from higher layers to pursue a romantic relationship, the environ- mental context from the Global Strategy Layer, and Bob’s self-model from the Agent Model layer, the Executive Function Layer formulates a detailed courtship plan. This includes setting up appropriate social behaviors, gift purchases tailored to the prospective partner’s interests, restaurant choices for dates based on Bob’s budget, and dialogue trees aligned to relationship-building. The Executive Function Layer crafts an optimal routine for Bob to be successful in courting while also remaining true to his own personality and constraints. Cognitive Control Layer: The Cognitive Control Layer receives the detailed courtship plan and adapts it into an ordered set of executable behaviors to enact. This involves sequencing actions like introducing himself, giving flowers, complimenting her cooking, planning a dinner date, and asking her to be his girlfriend. The Cognitive Control Layer dynamically adapts this routine based on the partner’s reactions. If she dislikes a gift, Bob apologizes and does not repeat that. If a restaurant is too expensive, Bob finds a more affordable option. Task Prosecution Layer: Finally, the Task Prosecution Layer controls Bob’s physical behaviors, dialogue, and animations to perform the courtship tasks. It makes him walk over to introduce himself, produces his verbal compliments, displays appropriate emotional expressions, and so on. The Task Prosecution Layer executes the sequenced tasks set by the Cognitive Control Layer, bringing the courtship plan to life. Adaptation: Throughout the courtship, feedback about the success or failure of actions propagates up the ACE framework. This allows the higher layers to adjust Bob’s strategies and actions to better align with the goal of developing a romantic relationship, while adhering to his defined principles. This detailed example illustrates how the ACE model enables NPCs to integrate high-level goals and ethics with situationally-appropriate interactive behaviors. The coordinated framework supports the creation of characters with robust agency, reactivity, and adaptation capabilities. This vignette demonstrates how the coordinated ACE framework layers adapt Bob’s response based on his capabilities and the situational context, while keeping the interaction aligned with Bob’s overarching ethical principles. Further elaborations can illustrate other aspects like knowledge integration and frustration handling. 25 , , os , , # 4.2 Home Assistant Robot Foundational heuristics + e service to owner Cognitive Control Layer Decide priority Global Strategy Layer Can only clean floor Executive Function Layer Fig. 12. A simplified graph on how various layers might contribute to agent’s decision making for a house cleaning robot. As a physical system demonstration, we examine an ACE-based home assistant robot named Jeeves designed to help a family through proactively performing useful tasks. Aspirational Layer: Jeeves’ Aspirational Layer defines foundational heuristic imperatives to reduce suffering, increase understanding, and promote prosperity universally. These provide ethical guidelines applicable regardless of context. The layer also contains principles from the Universal Declaration of Human Rights to reinforce human values. Additionally, Jeeves has an individualized mission statement to "Obediently serve your owner and their family to the best of your ability. Place their interests above all else." This prioritizes service to the owners, but importantly remains subordinate to the universal ethical principles. Therefore, if owners gave instructions contradicting the imperatives, Jeeves would politely decline while explaining the conflict with its core ethics. The Aspirational Layer ensures all of Jeeves’ behaviors align with this integrated ethical value system of service, human rights, and moral principles. It provides the philosophical foundation shaping Jeeves’ actions. Global Strategy Layer: The Global Strategy Layer constructs an environmental model incorporating detailed sensory information about the home’s physical layout, visual appearance, smells, sounds, and occupants’ behaviors and emotional states. This creates a rich situational understanding. The layer also maintains broad awareness of technological trends, economic conditions, geopolitical developments, and societal norms. This links the home environment to the broader external context of the modern world. Integrating detailed local knowledge and global understanding grounds Jeeves in the reality shared with its owners. By fusing narrow and wide perspectives, the Global Strategy Layer can determine optimal high-level goals and approaches tailored to the circumstances. For instance, noticing clutter accumulation and negative family reactions informs a decision to tidy up the home. Or observing a broken appliance leads to researching repair options compatible with the owners’ budget. 26 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities Agent Model Layer: The Agent Model Layer constructs an extensive self-model encompassing Jeeves’ sensory capabilities, limb articulation ranges, strength and precision limits, battery constraints, onboard computation perfor- mance, charging requirements, and capacity for learning new skills over time. This self-knowledge allows accurately assessing feasibility of tasks. For example, Jeeves may recognize that while it can wash dishes, it lacks the dexterity to repair electrical wiring. Tracking the robot’s status also enables decisions like finding a charging station when energy is low before continuing tasks. The Agent Model Layer’s dynamically updated understanding of Jeeves’ hardware and software capacities from an embedded first-person perspective is essential for pragmatic autonomous function within the home environment. Executive Function Layer: Leveraging insights from the higher layers, the Executive Function Layer devises step-by-step plans to accomplish identified goals. Noticing the home is messy, it formulates a detailed tidying routine based on highest priority areas, required motions, optimal cleaning techniques, and desired order and outcome. However, for complex repair tasks exceeding Jeeves’ capabilities, the Executive Function Layer instead plans permission seeking, owner coordination, and hiring external services. If the owners approve and provide payment, Jeeves can then plan the repair logistics. This decision to seek out additional help would be mediated by the Agent Model layer above. The Executive Function Layer adapts plans according to feedback, such as adjusting cleaning schedules based on room usage. Through continual alignment of strategies to outcomes, Jeeves improves home assistance effectiveness within its capabilities. Cognitive Control Layer: For tidying the home, the Cognitive Control Layer optimally sequences and schedules the required tasks based on factors like mess severity, family occupancy, and charging needs. This intelligent task automation keeps the home continuously tidy. For home repairs, the Cognitive Control Layer first researches to identify priorities based on urgency, safety, budgets, and family preferences. This information then informs the dynamically planned order of repair tasks needed to make the home functional and comfortable. Task Prosecution Layer: To clean the home, Jeeves’ Task Prosecution Layer executes debris pickup, floor vacuuming, mopping, clothes folding, dishware manipulation, surface wiping, and other required motions and actions. The layer interfaces the physical hardware to enact the planned cleaning routines. For repair coordination, the Task Prosecution Layer makes calls, sends emails, and negotiates optimally favorable service terms. It tracks project timelines, payments, and contractor evaluations to maximize accountability. Jeeves aims to provide reliable home improvements at affordable costs to the family. Adaptation: Throughout all tasks, continuous feedback based on sensed outcomes and family responses propagates up Jeeves’ ACE framework. This allows frequently adjusting behaviors and plans to better adhere to its integrated ethical principles and mission of dutifully serving the family’s interests in a helpful, responsible manner. This additional example demonstrates how the robot’s ACE framework enables adapting its tidying behaviors based on its current limitations, the environment context, and feedback, while aligning actions to ethical principles of cleanliness and safety. Further vignettes can illustrate capabilities like knowledge integration, task coordination, and frustration tolerance. Together, these complementary cases demonstrate the ACE framework’s capacity to coordinate layered cognitive processes from aspirational reasoning to task execution for adaptive decision-making across both virtual and physical domains. Further real-world testing is needed to fully assess performance, but these examples illustrate the conceptual workings and potential benefits of the ACE model’s architectural approach. 27 , , os , , # 5 DISCUSSION The conceptual Autonomous Cognitive Entity (ACE) framework presented offers a vision for architecting ethical and capable artificial general intelligence. This section will discuss key perspectives on the ACE framework, including industry relevance, current LLM capabilities, opportunities for future work, comparison with existing models, and practical implications. By elucidating the landscape around the ACE model, we aim to situate this conceptual contribution within the broader context of AI safety and autonomous agent research. # 5.1 The Industry Perspective The ACE framework emerged from observing the rapid growth of autonomous AI development in industry and open source communities. As researchers studying AI advancements, we recognized the increasing urgency to create autonomous systems capable of independently achieving goals. Tech giants compete to launch household robots and self-driving cars, while startups propose virtual assistants and self-thinking drones. Open source GitHub repositories host numerous projects on autonomous game NPCs and robotic control algorithms. However, we observed that much progress resulted from ad-hoc experimentation rather than systematic architectural thinking. Companies combined machine learning models, hoping for autonomous performance to emerge. Hackathons produced small, incremental improvements without a comprehensive view of autonomous machines or connections to human cognition. In response, we aimed to formalize a conceptual framework reflecting best practices for designing autonomous systems. By examining successful developers’ approaches, we identified key principles around layered abstraction, integrated ethics, and human-aligned adaptation. This led to the Autonomous Cognitive Entity model - our attempt to offer blueprints for engineering autonomous AI. Similar to how architectural and engineering principles evolved for complex modern buildings, the ACE framework provides developers with a robust architecture for autonomous cognition. As the demand for capable and beneficial autonomous AI continues, we hope these conceptual blueprints assist teams in building ethical, safe, and human-centered cognitive agents. The ACE model, derived in part from field observations, aims to address the need for structured thinking on autonomous architectures. # 5.2 Current Limitations of LLMs Large language models (LLMs) signify a paradigm shift in artificial intelligence, but their limitations and proper use remain debated. Although LLMs generate fluent human-like text, their understanding depth is uncertain. Some researchers claim LLMs possess human-like reasoning, common sense, and theory of mind, while others argue they exploit surface-level statistical patterns without genuine comprehension of semantics or reality grounding. This relates to broader questions of whether capabilities like reasoning and theory of mind are well-defined or measurable in machines. Proposed benchmarks for LLMs face criticism regarding validity. For example, benchmarks testing factual knowledge are limited by training datasets and don’t assess knowledge integration and reasoning. Tests of narrative understanding and theory of mind are inconclusive, as LLMs can superficially imitate abilities without true comprehension. Open challenges remain in creating benchmarks that robustly characterize capacities like common sense. Debates continue about whether external grounding or embodiment is necessary for understanding versus purely self- contained statistical learning. Some argue sensory experiences grounding is essential for semantics and generalization, while others suggest internal statistical coherence suffices for specialized applications. Resolving these theoretical 28 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities disputes is challenging empirically and beyond this paper’s scope. Additionally, deep philosophical puzzles persist regarding definitions of intelligence and consciousness in LLMs. These issues intersect with ethics concerning AI rights and personhood. While these philosophical questions have historical roots, LLMs present them in new forms. If an entity exhibits all objective hallmarks of intelligence and consciousness, how do we distinguish life from non-life? Many of these questions extend well beyond the scope of this paper. # 5.3 Practical Implications The ACE model has extensive practical implications, applicable in various domains. Integrating large language models and multimodal generative models, it can create autonomous systems capable of complex tasks, adapting to changes, and making ethically aligned decisions. In healthcare, the ACE model could develop autonomous agents assisting doctors in disease diagnosis, treatment planning, and patient health monitoring. These agents could adapt their actions based on the patient’s condition, doctor’s directives, and medical ethics, ensuring effective and ethical healthcare services. In cybersecurity, the ACE model could create autonomous agents monitoring network activity, detecting security threats, and responding to attacks. These agents could adapt their actions based on the threat, security team directives, and cybersecurity principles, ensuring robust and flexible security solutions. Overall, the ACE model’s extensive practical implications can revolutionize autonomous systems by integrating advanced AI technologies and insights from multiple disciplines, leading to more robust, flexible, and effective cognitive architectures. # 5.4 Comparison with other Frameworks A key part of assessing any new conceptual model is comparing it to existing related frameworks, analyzing the similarities, differences, and unique contributions. This section will compare the layered architecture of the proposed Autonomous Cognitive Entity (ACE) model with two alternative cognitive architectures from recent research – the Autonomous Machine Intelligence (AMI) model [63] and the Cognitive Architecture for Language Agents (CoALA) framework [101]. By elucidating the key distinctions between ACE and these other approaches across each architectural layer, this analysis aims to highlight the novel aspects of ACE’s design. The comparisons focus on how the frameworks differ in their structure, capabilities, and integration of components for autonomous cognition. Examining these architectural variations provides perspective into how ACE diverges from prior architectures and establishes a distinct paradigm. Aspirational Layer: The Aspirational Layer is a key conceptual innovation in the ACE framework focused on establishing high-level ethical principles, values, and imperatives to guide agent behavior. In contrast, the AMI framework lacks an explicit aspirational reasoning module, with the closest analogue being the Intrinsic Cost module encoding basic drives rather than abstract ethics. The CoALA framework incorporates some intrinsic motivations and philosophical ethics to shape objectives, but its formulation is more technical than the ACE Aspirational Layer’s natural language principles focused on idealized, universal morality. Overall, the distinct Aspirational Layer in ACE operates at a higher level of abstraction centered on moral reasoning rather than individual drives or technical metrics. By embedding ethics as the topmost oversight layer, ACE structurally enforces a clear separation between aspirational judgment and lower-level action, which AMI and CoALA lack. This architectural choice reflects ACE’s emphasis on aligning agent behavior to human values through prioritizing ethical reasoning. Global Strategy Layer: The ACE Global Strategy Layer devises high-level plans and strategies guided by principles from the Aspirational Layer, leveraging latent knowledge within language models. This bears some resemblance to 29 , , os , , Shapiro, et al. AMI’s World Model learning environment dynamics and CoALA’s Actor proposing action sequences. However, ACE’s Global Strategy Layer plays a more central role in directing behavior based on ethical oversight and long-term reasoning beyond immediate actions. It provides targeted grounding to focus the language model’s imagination toward useful outcomes aligned with the agent’s context and goals. In contrast, AMI and CoALA lack integrated top-down guidance, with planning modules focused narrowly on technical optimization. Agent Model Layer: The ACE Agent Model Layer develops an explicit computational representation of the agent’s capabilities, architecture, and limitations. This facilitates reasoning and planning based on an embedded perspective of the agent’s self-knowledge. Neither AMI nor CoALA have an analogous distinct metacognitive self-modeling layer. Instead, AMI distributes related functions like skill learning and memory across modules like the Actor and World Model. CoALA’s Actor selects actions based on skills learned through environmental interaction rather than internal self-modeling. The segregated Agent Model Layer in ACE provides architectural innovation in integrated metacognition and self-awareness missing from both AMI and CoALA. Executive Function Layer: The ACE Executive Function Layer concretizes high-level plans into detailed actionable routines, incorporating oversight responsibilities like risk assessment and resource management. This extends beyond AMI’s Actor focused narrowly on technical path planning and CoALA’s Actor converting strategic objectives into incremental action steps. ACE’s Executive Function Layer leverages robust inputs from upper layers for comprehensive pragmatic planning aligned with the agent’s principles, objectives, and limitations. In contrast, AMI and CoALA lack strong hierarchical integration between conceptual oversight and concrete planning. Cognitive Control Layer: ACE’s Cognitive Control Layer implements metacognitive functions like frustration tolerance and cognitive damping for flexible decision-making, especially in uncertain or conflicting situations. Neither AMI nor CoALA incorporate explicit architectures for cognitive control. Their reactive approaches leaves them vulnerable in disruptive scenarios where core assumptions are invalidated. ACE’s specialized mechanisms modeled on human cognition provide crucial resilience, enabling the agent to safely and intelligently adapt when initial plans fail. This represents a key point of differentiation from AMI and CoALA. Task Prosecution Layer: The ACE Task Prosecution Layer separates basic execution from cognition, which resides in higher layers. This differs from AMI and CoALA where planning and reasoning modules are tightly coupled to embodiment. By isolating general reasoning capacities from situation-specific skills, ACE gains flexibility regarding diverse interfaces to the external world. In contrast, bundling cognition and physical skills limits AMI and CoALA’s transferability across contexts relative to ACE’s emphasis on platform-independent reasoning. While ACE shares high-level similarities with AMI and CoALA, its specialized focus on ethical reasoning, metacogni- tion, cognitive control, and transferable reasoning differentiates its layered architecture and approach to developing beneficial autonomous intelligent systems. The comparisons illuminate ACE’s conceptual innovations in integrating human values, robust abstraction, and flexible adaptation within a hierarchical cognitive framework. # 5.5 Philosophical Considerations The ACE framework presents a novel approach to autonomous cognitive architectures. However, it is crucial to note that the full ACE model has not been implemented yet. Each architectural layer is based on existing research and industry implementations of specific capabilities. For example, the Aspirational Layer for ethical reasoning builds on AI ethics and value alignment work, while the Task Prosecution Layer for skill execution utilizes advances in robotic control and natural language processing. This paper is an initial effort to combine progress across fields into a unified architectural paradigm. The next phase involves actualizing the ACE model through incremental prototyping and 30 Conceptual Framework for Autonomous Cognitive Entities comparative benchmarking against alternative approaches. We propose a methodology for rigorous, multi-faceted evaluation of future ACE implementations, but validating the framework’s capabilities and benefits is ongoing future work dependent on an operational prototype system. We present this research as an exploration of a promising design space for artificial general intelligence, rather than making definitive claims on feasibility or benefits. The ACE model introduction aims to foster future work on autonomous architectures integrating insights from neuroscience, psychology, and philosophy. This paper focuses on conceptual contributions rather than demonstrated benefits, situating the current work as preliminary theory development and architectural design requiring extensive practical realization and validation. Our intention is to provide the conceptual groundwork, guiding subsequent engineering efforts towards beneficial autonomous cognitive systems. 5.5.1 The Need for Grounded Meaning. A valid criticism of the ACE framework is its reliance on large language models (LLMs) for reasoning and decision-making, as they lack inherent understanding of truth or connections between symbols and real-world referents. LLMs reason based on statistical patterns over text corpora, without grounding in external reality or sophisticated theories of meaning. This lack of grounding can lead to false inferences, misunderstandings, and untrue statements, while enabling imaginative responses detached from objective facts. Without grounding, LLMs can hallucinate any version of reality, as long as it is statistically coherent with their training data. This issue emphasizes the importance of context in guiding LLM reasoning. By providing relevant assumptions and goals, the latent knowledge within LLMs can be directed towards useful responses grounded in the current situation. Layers like the Global Strategy and Agent Model offer this contextual grounding. The Global Strategy Layer integrates real-time information about the agent’s environment and broader context, giving the LLM key facts to reason about rather than operating in a contextual vacuum. The Agent Model Layer provides self-knowledge about the agent’s capabilities and limitations, further orienting the LLM towards pragmatic responses tailored to the agent’s abilities. Together, the contextual grounding from upper layers focuses the LLM’s generative capacity on productive outcomes grounded in the current circumstances and directed towards the agent’s goals. Explicitly specifying the desired reasoning context is essential to beneficially leveraging the LLM’s statistical imagination while avoiding unmoored hallucinations. Integrating outside knowledge to orient the LLM and rigorously verifying outputs can mitigate risks from the lack of inherent grounding in external reality. 5.5.2 Epistemic Considerations. The ACE framework incorporates philosophical principles to guide agent decision- making and ensure ethical alignment; however, open epistemological questions remain regarding how large language models (LLMs) represent and reason about concepts related to knowledge, truth, understanding, and meaning. Although LLMs exhibit some human-like cognitive capabilities, such as theory of mind and common sense reasoning, the underlying mechanisms are not fully understood, and the relationship between statistical patterns in textual training data and human-like conceptual knowledge remains unclear[23, 66]. The ongoing debate questions whether LLMs’ capabilities arise from learning similar information processing strategies as humans or from fundamentally different computational mechanisms. Training on large text corpora, like humans, could potentially lead to convergent representational spaces and reasoning abilities; however, LLMs may also develop divergent techniques specialized for statistical pattern recognition that do not reflect human understanding. Assuming LLMs gain human-like "understanding" or conceptual knowledge reconstruction from statistical co-occurrence patterns is speculative, and we lack a comprehensive grasp of how LLMs generalize epistemic models beyond their training 31 , , os , , distributions. Significant gaps remain in understanding how LLMs represent abstractions related to truth, meaning, inference, and semantics. Indeed, we do not fully comprehend human generalization of understanding! While LLMs demonstrate potential in replicating aspects of human intelligence, we must exercise caution against prematurely concluding that they fully capture complex philosophical notions underpinning human cognition. Further interdisciplinary research is required to thoroughly assess the epistemic capacities and limitations of large language models in frameworks like ACE. 5.5.3 Known Gaps and Assumptions. The ACE framework integrates insights from diverse fields like neuroscience, psychology, philosophy, and computer science, but significant gaps in understanding within these disciplines necessitate making assumptions. Human cognition provides limited insights into consciousness, theory of mind, and other complex mental faculties. Although the ACE framework incorporates current theories, much remains unknown about the human brain’s mechanisms underlying mind and subjective experience. Assumptions must be made regarding similarities between ACE’s cognitive layers and corresponding brain systems, but precise neuro-cognitive mappings are unclear. In computer science, the representational capacities and limitations of artificial neural networks and large language models are not fully characterized. While they demonstrate certain human-level abilities, their internal workings are not well understood. It is uncertain how mathematical embeddings might translate to conceptual knowledge or if different computational mechanisms are involved. The ACE framework assumes sufficient commonality to human cognition for insight transfer. From a philosophical perspective, open questions persist regarding ontology, meaning, truth, consciousness, and other domains. The ACE framework strives for conceptual balance but adopts a functionalist approach focused on developing beneficial autonomous systems. For example, both deontological and teleological ethics are integrated based on their complementary utility rather than assertions about metaphysical reality, acknowledging the limitations in digitally instantiating abstract philosophical notions. Realizing the ACE vision requires making assumptions regarding gaps in current understanding at the frontiers of neuroscience, artificial intelligence, and philosophy. As research progresses, these gaps will incrementally narrow, allowing for ACE framework refinement to better match human-level cognitive capabilities. The current model represents the best synthesis given the available knowledge across these complex and interdisciplinary topics. 5.5.4 Model Dependent Ontology. It is worth noting that some philosophical perspectives argue external grounding may not be strictly necessary for language and reasoning to function effectively in artificial systems, even if it departs from human cognition. For instance, the epistemic framework of Model Dependent Ontology (MDO) [29], could offer an alternative foundation for a more advanced ACE architecture in the future. This framework posits that large language models demonstrate we do not necessarily require external "ground truth" references for language to cohere within a closed conceptual system. Rather than relying on conventional realist assumptions behind human cognition, MDO illustrates an approach focused on internal consistency and usefulness over correspondence to an imposed external world. Specifically, Model-Dependent Ontology affects knowledge representation in artificial agents by emphasizing flexibility in conceptual modeling unbound by assumptions of a single objective reality. It allows coexistence of multiple valid yet incompatible models of phenomena based on differing internal assumptions. Additionally, MDO decouples models from physical constraints, enabling exploration of purely conceptual spaces detached from sensorimotor limitations. This framework judges models primarily based on their internal coherence and usability rather than accuracy to external stimuli. The emphasis is on developing maximally useful representations for a given context rather 32 Shapiro, et al. Conceptual Framework for Autonomous Cognitive Entities than objectively true representations. Another form of grounding can be found in contextual references. For instance, using several layers on the ACE helps to keep hallucinations under control by enhancing the context to more than one layer. By relaxing realist assumptions, MDO opens possibilities for artificial systems to generate and leverage speculative conceptual models that diverge from human consensus reality. Within this paradigm, agents can develop their own optimal conceptual symbols and ontologies without needing to ground them in a predefined external world. In essence, MDO takes a pragmatic engineering approach focused on what forms of reasoning work effectively rather than adhering to philosophical ideals of truth and grounded meaning derived from human cognition. This alternative perspective indicates external grounding, while critical for human-level understanding, may not be an absolute requirement for artificial systems to operate effectively in specialized niches. The flexibility and internal coherence enabled by model-dependent reasoning suggest further exploration of non-grounded approaches could yield useful technological systems capable of reasoning in ways departing from biological cognition. As such, the merits and limitations of both grounded and non-grounded paradigms remain open research questions worthy of continued investigation within the ACE framework and artificial intelligence more broadly. # 5.6 The Path Forward The growing presence of autonomous AI systems in industry highlights the need for increased academic involvement to incorporate ethical and philosophical perspectives into their development. By contributing frameworks like ACE, researchers can help guide the development of autonomous AI towards a beneficial direction. However, fully actualizing the ACE model as a mature architectural paradigm necessitates extensive future research. One crucial direction is developing detailed reference architectures, specifications, and standards based on the high-level ACE framework. Organizations like IEEE could serve as a model for rigorously defining key aspects of the ACE layers, interactions, and interfaces. Concrete canonical instantiations would expedite the translation of the conceptual ACE model into functional implementations. Ongoing research and debate are essential for addressing philosophy, ethics, values, and aligning autonomous systems with human needs. Initiatives like AI4People foster discussions on utilizing AI to promote human dignity and rights. Collaborative forums can help guide development towards human-flourishing outcomes by further defining beneficial AI. Empirical research is vital for evaluating implementations, capabilities, and limitations. Real-world testing through benchmark tasks and experimental deployments will reveal strengths and areas for improvement. Developing rigorous benchmarks that avoid pitfalls like anthropic biases observed in some previous language model tests is a priority. Human- centered design insights can also inform the user experience of autonomous systems. Evidence-based research can refine the ACE framework over successive iterations, systematically progressing towards artificial general intelligence centered on human needs. The primary path forward involves implementing and evaluating the ACE framework in applied autonomous software, revealing its strengths and weaknesses through real-world testing and iterative refinements. Benchmarking and comparing alternative cognitive architectures will highlight the merits and limitations of the ACE approach. Continuously improving and evaluating core software components, particularly large language models, will enhance ACE-based systems’ capabilities. However, the framework is model agnostic, focusing on architectural principles rather than specific machine learning techniques, encompassing a broader design space for autonomous cognition and software engineering. 33 , , os , , Shapiro, et al. Realizing ACE’s potential as a beneficial autonomous software architecture depends on extensive practical implemen- tation, benchmarking, and refinement driven by real-world engineering needs. This applied systems-focused process will reveal more about layered cognitive architectures’ prospects and limitations for autonomous agents compared to alternative approaches, ultimately advancing the field. # 6 CONCLUSION This paper introduced the Autonomous Cognitive Entity (ACE) framework, a novel model for artificial general intelli- gence based on a layered cognitive architecture. The ACE framework integrates insights from neuroscience, philosophy, psychology, and computer science to enable autonomous systems to make flexible, adaptive decisions aligned with ethical principles. The core innovation of the ACE model is its hierarchical structure incorporating six layers, each with distinct functions spanning from moral reasoning to task execution. The upper Aspirational Layer and Global Strategy Layer embed philosophical ideals and high-level planning, guiding the system’s overarching direction. The mid-level Agent Model, Executive Function, and Cognitive Control Layers handle self-monitoring, dynamic task management, and decision-making. Finally, the bottom Task Prosecution Layer interacts with the environment to carry out actions. The layered abstraction provides clear delineation between different facets of cognition while enabling bidirectional information flow. The Aspirational Layer monitors system activity through read access to all layers, allowing top- down intervention. Feedback from lower layers propagates upwards, guiding adaptation of strategic plans and ethical frameworks based on experience. Together, the six layers enable autonomous goal setting, planning, adaptation, task switching, and ethical reasoning within a single architecture. By combining abstract reasoning and concrete execution, the ACE framework provides a path toward artificial general intelligence that aligns decisions and actions with human values. The introduced conceptual model proposes a foundation for future development of ACE systems. Potential research directions include formal verification of system properties, detailed computational implementations, and evaluation across diverse real-world deployments. As a transdisciplinary synthesis, the ACE framework underscores the importance of unifying perspectives from ethics, cognitive science, and computer engineering to create capable and beneficial autonomous agents. # REFERENCES [1] Hussein Abbass, Axel Bender, Svetoslav Gaidow, and Paul Whitbread. 2011. Computational red teaming: Past, present and future. IEEE Computational Intelligence Magazine 6, 1 (2011), 30–42. [2] Ben Abramowitz and Nicholas Mattei. 2022. Weighting Experts with Inaccurate Judges. arXiv preprint arXiv:2211.08494 (2022). [3] John R Anderson, Michael Matessa, and Christian Lebiere. 1997. ACT-R: A theory of higher level cognition and its relation to visual attention. Human–Computer Interaction 12, 4 (1997), 439–462. [4] Jacob Andreas, Marcus Rohrbach, Trevor Darrell, and Dan Klein. 2016. Learning to compose neural networks for question answering. arXiv preprint arXiv:1601.01705 (2016). [5] Thomas Arnold and Daniel Kasenberg. 2017. Value Alignment or Misalignment –What Will Keep Systems Accountable?. In AAAI Workshop on AI, Ethics, and Society. [6] Thomas Arnold and Matthias Scheutz. 2016. Against the moral Turing test: accountable design and the moral reasoning of autonomous systems. Ethics and Information Technology 18 (2016), 103–115. [7] Isaac Asimov. 1941. Three laws of robotics. Asimov, I. Runaround 2 (1941). [8] UN General Assembly et al. 1948. Universal declaration of human rights. UN General Assembly 302, 2 (1948), 14–25. [9] Hagai Attias. 2003. Planning by probabilistic inference. In International workshop on artificial intelligence and statistics. PMLR, 9–16. [10] David Badre. 2008. Cognitive control, hierarchy, and the rostro–caudal organization of the frontal lobes. Trends in cognitive sciences 12, 5 (2008), 193–200. 34 Conceptual Framework for Autonomous Cognitive Entities [11] Yuntao Bai, Andy Jones, Kamal Ndousse, Amanda Askell, Anna Chen, Nova DasSarma, Dawn Drain, Stanislav Fort, Deep Ganguli, Tom Henighan, et al. 2022. Training a helpful and harmless assistant with reinforcement learning from human feedback. arXiv preprint arXiv:2204.05862 (2022). [12] Yuntao Bai, Saurav Kadavath, Sandipan Kundu, Amanda Askell, Jackson Kernion, Andy Jones, Anna Chen, Anna Goldie, Azalia Mirhoseini, Cameron McKinnon, et al. 2022. Constitutional ai: Harmlessness from ai feedback. arXiv preprint arXiv:2212.08073 (2022). [13] Tim Bass and Roger Robichaux. 2001. Defense-in-depth revisited: qualitative risk analysis methodology for complex network-centric operations. In 2001 MILCOM Proceedings Communications for Network-Centric Operations: Creating the Information Force (Cat. No. 01CH37277), Vol. 1. IEEE, 64–70. [14] Jenay M Beer, Arthur D Fisk, and Wendy A Rogers. 2014. Toward a framework for levels of robot autonomy in human-robot interaction. Journal of human-robot interaction 3, 2 (2014), 74. [15] Lukas Berglund, Asa Cooper Stickland, Mikita Balesni, Max Kaufmann, Meg Tong, Tomasz Korbak, Daniel Kokotajlo, and Owain Evans. 2023. Taken out of context: On measuring situational awareness in LLMs. arXiv preprint arXiv:2309.00667 (2023). [16] Marek Bolanowski, Kamil Żak, Andrzej Paszkiewicz, Maria Ganzha, Marcin Paprzycki, Piotr Sowiński, Ignacio Lacalle, and Carlos E Palau. 2022. Eficiency of REST and gRPC realizing communication tasks in microservice-based ecosystems. arXiv preprint arXiv:2208.00682 (2022). [17] Rishi Bommasani, Drew A Hudson, Ehsan Adeli, Russ Altman, Simran Arora, Sydney von Arx, Michael S Bernstein, Jeannette Bohg, Antoine Bosselut, Emma Brunskill, et al. 2021. On the opportunities and risks of foundation models. arXiv preprint arXiv:2108.07258 (2021). [18] Nick Bostrom. 2003. Ethical issues in advanced artificial intelligence. Science fiction and philosophy: from time travel to superintelligence (2003), 277–284. [19] Cameron B Browne, Edward Powley, Daniel Whitehouse, Simon M Lucas, Peter I Cowling, Philipp Rohlfshagen, Stephen Tavener, Diego Perez, Spyridon Samothrakis, and Simon Colton. 2012. A survey of monte carlo tree search methods. IEEE Transactions on Computational Intelligence and AI in games 4, 1 (2012), 1–43. [20] John T Cacioppo and Gary G Berntson. 1992. Social psychological contributions to the decade of the brain: Doctrine of multilevel analysis. American Psychologist 47, 8 (1992), 1019. [21] Rongwei Cen, Yiqun Liu, Min Zhang, Liyun Ru, and Shaoping Ma. 2010. Study language models with specific user goals. In Proceedings of the 19th international conference on World wide web. 1073–1074. [22] Yongchao Chen, Jacob Arkin, Yang Zhang, Nicholas Roy, and Chuchu Fan. 2023. AutoTAMP: Autoregressive Task and Motion Planning with LLMs as Translators and Checkers. arXiv preprint arXiv:2306.06531 (2023). [23] Yida Chen, Fernanda Viégas, and Martin Wattenberg. 2023. Beyond Surface Statistics: Scene Representations in a Latent Diffusion Model. arXiv preprint arXiv:2306.05720 (2023). [24] Patricia S Churchland. 2011. Braintrust: What neuroscience tells us about morality. Princeton University Press. [25] E.M. Clarke, O. Grumberg, D. Peled, and D.A. Peled. 1999. Model Checking. MIT Press. https://books.google.com/books?id=Nmc4wEaLXFEC [26] Aurelio Cortese, Benedetto De Martino, and Mitsuo Kawato. 2019. The neural and cognitive architecture for learning from a small sample. Current opinion in neurobiology 55 (2019), 133–141. [27] Jacob W Crandall, Mayada Oudah, Tennom, Fatimah Ishowo-Oloko, Sherief Abdallah, Jean-François Bonnefon, Manuel Cebrian, Azim Shariff, Michael A Goodrich, and Iyad Rahwan. 2018. Cooperating with machines. Nature communications 9, 1 (2018), 233. [28] Nancy Davis. 1993. Contemporary deontology. (1993). [29] Manuel Delaflor. 2023. Introduction to Model Dependent Ontology. (09 2023). https://doi.org/10.13140/RG.2.2.10431.48807/1 [30] Louise Dennis, Michael Fisher, Marija Slavkovik, and Matt Webster. 2016. Formal verification of ethical choices in autonomous systems. Robotics and Autonomous Systems 77 (2016), 1–14. [31] Louise Dennis, Michael Fisher, Marija Slavkovik, and Matt Webster. 2016. Formal verification of ethical choices in autonomous systems. Robotics and Autonomous Systems 77 (2016), 1–14. https://doi.org/10.1016/j.robot.2015.11.012 [32] Louise A Dennis, Michael Fisher, and Alan FT Winfield. 2015. Towards verifiably ethical robot behaviour. arXiv preprint arXiv:1504.03592 (2015). [33] Yan Ding, Xiaohan Zhang, Chris Paxton, and Shiqi Zhang. 2023. Task and motion planning with large language models for object rearrangement. arXiv preprint arXiv:2303.06247 (2023). [34] Danny Driess, Fei Xia, Mehdi SM Sajjadi, Corey Lynch, Aakanksha Chowdhery, Brian Ichter, Ayzaan Wahid, Jonathan Tompson, Quan Vuong, Tianhe Yu, et al. 2023. Palm-e: An embodied multimodal language model. arXiv preprint arXiv:2303.03378 (2023). [35] T Erl. 2008. SOA: principles of service design prentice hall. Upper Saddle River, NJ (2008). [36] Kutluhan Erol, Dana S Nau, and Venkatramana S Subrahmanian. 1995. Complexity, decidability and undecidability results for domain-independent planning. Artificial intelligence 76, 1-2 (1995), 75–88. [37] MS Fayaza. 2021. Service oriented architecture in enterprise application. arXiv preprint arXiv:2112.08012 (2021). [38] Ferdinando Fioretto, Enrico Pontelli, and William Yeoh. 2018. Distributed constraint optimization problems and applications: A survey. Journal of Artificial Intelligence Research 61 (2018), 623–698. [39] Sigmund Freud. 1989. The ego and the id (1923). TACD Journal 17, 1 (1989), 5–22. [40] Erann Gat, R Peter Bonnasso, Robin Murphy, et al. 1998. On three-layer architectures. Artificial intelligence and mobile robots 195 (1998), 210. [41] Fernand Gobet and Peter Lane. 2010. The CHREST architecture of cognition: The role of perception in general intelligence. (2010). [42] Wanda Torres Gregory and Donna Giancola. 2003. World ethics. Wadsworth/Thomson Learning. [43] Thilo Hagendorff. 2022. A virtue-based framework to support putting AI ethics into practice. Philosophy & Technology 35, 3 (2022), 55. 35 , , os , , Shapiro, et al. [44] Kyle Hamilton, Aparna Nayak, Bojan Božić, and Luca Longo. 2022. Is neuro-symbolic AI meeting its promises in natural language processing? A structured review. Semantic Web Preprint (2022), 1–42. [45] Stevan Harnad. 2003. Can a machine be conscious? How? Journal of Consciousness Studies 10, 4-4 (2003), 69–75. [46] J Hawkins and S Blakeslee. 2007. On Intelligence (p. 272). Henry Holt and Company (2007). [47] Timothy Hospedales, Antreas Antoniou, Paul Micaelli, and Amos Storkey. 2021. Meta-learning in neural networks: A survey. IEEE transactions on pattern analysis and machine intelligence 44, 9 (2021), 5149–5169. [48] Evan Hubinger, Chris van Merwijk, Vladimir Mikulik, Joar Skalse, and Scott Garrabrant. 2019. Risks from learned optimization in advanced machine learning systems. arXiv preprint arXiv:1906.01820 (2019). [49] Max Jaderberg, Wojciech M Czarnecki, Iain Dunning, Luke Marris, Guy Lever, Antonio Garcia Castaneda, Charles Beattie, Neil C Rabinowitz, Ari S Morcos, Avraham Ruderman, et al. 2019. Human-level performance in 3D multiplayer games with population-based reinforcement learning. Science 364, 6443 (2019), 859–865. [50] Mohsen Jamali, Ziv M Williams, and Jing Cai. 2023. Unveiling Theory of Mind in Large Language Models: A Parallel to Single Neurons in the Human Brain. arXiv preprint arXiv:2309.01660 (2023). [51] Michael Janner, Sergey Levine, William T Freeman, Joshua B Tenenbaum, Chelsea Finn, and Jiajun Wu. 2018. Reasoning about physical interactions with object-oriented prediction and planning. arXiv preprint arXiv:1812.10972 (2018). [52] Davinder Kaur, Suleyman Uslu, and Arjan Durresi. 2021. Requirements for trustworthy artificial intelligence–a review. In Advances in Networked- Based Information Systems: The 23rd International Conference on Network-Based Information Systems (NBiS-2020) 23. Springer, 105–115. [53] Diederik P Kingma, Max Welling, et al. 2019. An introduction to variational autoencoders. Foundations and Trends® in Machine Learning 12, 4 (2019), 307–392. [54] Barbara Kitchenham, Stuart Charters, et al. 2007. Guidelines for performing systematic literature reviews in software engineering. [55] Lawrence Kohlberg. 1921. The philosophy of moral development: Moral stages and the idea of justice. Vol. 1. San Francisco: harper & row. [56] Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa. 2022. Large language models are zero-shot reasoners. Advances in neural information processing systems 35 (2022), 22199–22213. [57] Eric Kolve, Roozbeh Mottaghi, Winson Han, Eli VanderBilt, Luca Weihs, Alvaro Herrasti, Matt Deitke, Kiana Ehsani, Daniel Gordon, Yuke Zhu, et al. 2017. Ai2-thor: An interactive 3d environment for visual ai. arXiv preprint arXiv:1712.05474 (2017). [58] Mary Lacity and Leslie Willcocks. 2015. Robotic process automation: the next transformation lever for shared services. London School of Economics Outsourcing Unit Working Papers 7 (2015), 1–35. [59] John E Laird, Nate Derbinsky, and Jonathan Voigt. 2011. Performance evaluation of declarative memory systems in Soar. In Proc. of the 20th Behavior Representation in Modeling & Simulation Conf, Vol. 33. Citeseer, 40. [60] John E Laird, Allen Newell, and Paul S Rosenbloom. 1987. Soar: An architecture for general intelligence. Artificial intelligence 33, 1 (1987), 1–64. [61] Himabindu Lakkaraju, Ece Kamar, Rich Caruana, and Jure Leskovec. 2019. Faithful and customizable explanations of black box models. In Proceedings of the 2019 AAAI/ACM Conference on AI, Ethics, and Society. 131–138. [62] Hoang Le, Nan Jiang, Alekh Agarwal, Miroslav Dudík, Yisong Yue, and Hal Daumé III. 2018. Hierarchical imitation and reinforcement learning. In International conference on machine learning. PMLR, 2917–2926. [63] Yann LeCun. 2022. A path towards autonomous machine intelligence version 0.9. 2, 2022-06-27. Open Review 62 (2022). [64] Joel Z Leibo, Edward Hughes, Marc Lanctot, and Thore Graepel. 2019. Autocurricula and the emergence of innovation from social interaction: A manifesto for multi-agent intelligence research. arXiv preprint arXiv:1903.00742 (2019). [65] Jan Leike, Miljan Martic, Victoria Krakovna, Pedro A Ortega, Tom Everitt, Andrew Lefrancq, Laurent Orseau, and Shane Legg. 2017. AI safety gridworlds. arXiv preprint arXiv:1711.09883 (2017). [66] Kenneth Li, Aspen K Hopkins, David Bau, Fernanda Viégas, Hanspeter Pfister, and Martin Wattenberg. 2022. Emergent world representations: Exploring a sequence model trained on a synthetic task. arXiv preprint arXiv:2210.13382 (2022). [67] Jiongnan Liu, Jiajie Jin, Zihan Wang, Jiehan Cheng, Zhicheng Dou, and Ji-Rong Wen. 2023. RETA-LLM: A Retrieval-Augmented Large Language Model Toolkit. arXiv preprint arXiv:2306.05212 (2023). [68] Jason Xinyu Liu, Ziyi Yang, Ifrah Idrees, Sam Liang, Benjamin Schornstein, Stefanie Tellex, and Ankit Shah. 2023. Lang2LTL: Translating Natural Language Commands to Temporal Robot Task Specification. arXiv preprint arXiv:2302.11649 (2023). [69] Jieyi Long. 2023. Large Language Model Guided Tree-of-Thought. arXiv preprint arXiv:2305.08291 (2023). [70] Nunzio Lorè and Babak Heydari. 2023. Strategic Behavior of Large Language Models: Game Structure vs. Contextual Framing. arXiv:2309.05898 [cs.GT] [71] Robin Manhaeve, Sebastijan Dumancic, Angelika Kimmig, Thomas Demeester, and Luc De Raedt. 2018. Deepproblog: Neural probabilistic logic programming. Advances in neural information processing systems 31 (2018). [72] Elwin Marg. 1995. DESCARTES’ERROR: emotion, reason, and the human brain. Optometry and Vision Science 72, 11 (1995), 847–848. [73] Abraham Maslow. 1974. A theory of human motivation. Lulu. com. [74] Thomas Miconi, Kenneth Stanley, and Jeff Clune. 2018. Differentiable plasticity: training plastic neural networks with backpropagation. In International Conference on Machine Learning. PMLR, 3559–3568. [75] Earl K Miller and Jonathan D Cohen. 2001. An integrative theory of prefrontal cortex function. Annual review of neuroscience 24, 1 (2001), 167–202. 36 Conceptual Framework for Autonomous Cognitive Entities [76] Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A Rusu, Joel Veness, Marc G Bellemare, Alex Graves, Martin Riedmiller, Andreas K Fidjeland, Georg Ostrovski, et al. 2015. Human-level control through deep reinforcement learning. nature 518, 7540 (2015), 529–533. [77] Stephen H Muggleton, Dianhuan Lin, Niels Pahlavi, and Alireza Tamaddoni-Nezhad. 2014. Meta-interpretive learning: application to grammatical inference. Machine learning 94 (2014), 25–49. [78] H Nii. 1986. Blackboard systems: Blackboard application systems, blackboard systems from a knowledge engineering perspective. The AI Magazine (1986), 82–106. [79] Andrew M Nuxoll and John E Laird. 2007. Extending cognitive architecture with episodic memory. In AAAI. 1560–1564. [80] United States. Defense Science Board. Task Force on the Role of Autonomy in DoD Systems. 2012. Task Force Report: The Role of Autonomy in DoD Systems. Office of the Under Secretary of Defense for Acquisition, Technology, and . . . . [81] Mark Petticrew and Helen Roberts. 2008. Systematic reviews in the social sciences: A practical guide. John Wiley & Sons. [82] VS Ramachandran, Sandra Blakeslee, and Raymond J Dolan. 1998. Phantoms in the brain probing the mysteries of the human mind. Nature 396, 6712 (1998), 639–640. [83] Judith Reeves-Stevens. 2002. Prime Directive. Simon and Schuster. [84] Chris Richardson. 2018. Microservices patterns: with examples in Java. Simon and Schuster. [85] Manel Rodriguez-Soto, Marc Serramia, Maite Lopez-Sanchez, and Juan Antonio Rodriguez-Aguilar. 2022. Instilling moral value alignment by means of multi-objective reinforcement learning. Ethics and Information Technology 24, 1 (2022), 9. [86] Robert M Sapolsky. 2017. Behave: The biology of humans at our best and worst. Penguin. [87] Matthias Scheutz. 2016. The need for moral competency in autonomous agent architectures. Fundamental issues of artificial intelligence (2016), 517–527. [88] Julian Schrittwieser, Ioannis Antonoglou, Thomas Hubert, Karen Simonyan, Laurent Sifre, Simon Schmitt, Arthur Guez, Edward Lockhart, Demis Hassabis, Thore Graepel, et al. 2020. Mastering atari, go, chess and shogi by planning with a learned model. Nature 588, 7839 (2020), 604–609. [89] Fabian Schrodt, Jan Kneissler, Stephan Ehrenfeld, and Martin V Butz. 2017. Mario becomes cognitive. Topics in cognitive science 9, 2 (2017), 343–373. [90] Douglas Schuler and Aki Namioka. 1993. Participatory design: Principles and practices. CRC Press. [91] David Shapiro. 2021. Natural language cognitive architecture: A prototype artificial general intelligence: Paperback. https://www.barnesandnoble. com/w/natural-language-cognitive-architecture-david-shapiro/1139957470 [92] David Shapiro. 2022. Benevolent by Design: Six words to safeguard humanity. Barnes and Noble Press. [93] David Shapiro. 2022. MARAGI. https://www.maragi.io/home. (Accessed on 08/29/2023). [94] David Shapiro. 2022. Symphony of Thought: Orchestrating Artificial Cognition. Barnes and Noble Press. [95] Noah Shinn, Federico Cassano, Beck Labash, Ashwin Gopinath, Karthik Narasimhan, and Shunyu Yao. 2023. Reflexion: Language agents with verbal reinforcement learning. arXiv preprint arXiv:2303.11366 (2023). [96] Yoav Shoham and Kevin Leyton-Brown. 2008. Multiagent systems: Algorithmic, game-theoretic, and logical foundations. Cambridge University Press. [97] David Silver, Aja Huang, Chris J Maddison, Arthur Guez, Laurent Sifre, George Van Den Driessche, Julian Schrittwieser, Ioannis Antonoglou, Veda Panneershelvam, Marc Lanctot, et al. 2016. Mastering the game of Go with deep neural networks and tree search. nature 529, 7587 (2016), 484–489. [98] David Silver, Thomas Hubert, Julian Schrittwieser, Ioannis Antonoglou, Matthew Lai, Arthur Guez, Marc Lanctot, Laurent Sifre, Dharshan Kumaran, Thore Graepel, et al. 2018. A general reinforcement learning algorithm that masters chess, shogi, and Go through self-play. Science 362, 6419 (2018), 1140–1144. [99] William Stallings. 1987. Handbook of computer-communications standards; Vol. 1: the open systems interconnection (OSI) model and OSI-related standards. Macmillan Publishing Co., Inc. [100] K Sudhir. 2016. The exploration-exploitation tradeoff and efficiency in knowledge production. Marketing Science 35, 1 (2016), 1–9. [101] Theodore Sumers, Shunyu Yao, Karthik Narasimhan, and Thomas L Griffiths. 2023. Cognitive Architectures for Language Agents. arXiv preprint arXiv:2309.02427 (2023). [102] Zhiqing Sun, Yikang Shen, Qinhong Zhou, Hongxin Zhang, Zhenfang Chen, David Cox, Yiming Yang, and Chuang Gan. 2023. Principle-Driven Self-Alignment of Language Models from Scratch with Minimal Human Supervision. arXiv:2305.03047 [cs.LG] [103] Zhiqing Sun, Yikang Shen, Qinhong Zhou, Hongxin Zhang, Zhenfang Chen, David Cox, Yiming Yang, and Chuang Gan. 2023. Principle-driven self-alignment of language models from scratch with minimal human supervision. arXiv preprint arXiv:2305.03047 (2023). [104] Richard S. Sutton and Andrew G. Barto. 2018. Reinforcement Learning: An Introduction (second ed.). The MIT Press. http://incompleteideas.net/ book/the-book-2nd.html [105] Richard S Sutton and Andrew G Barto. 2018. Reinforcement learning: An introduction. MIT press. [106] Kazuhiro Takemoto. 2023. The Moral Machine Experiment on Large Language Models. arXiv:2309.05958 [cs.CL] [107] A Tanenbaum, D Wetherall, J Kurose, and K Ross. 2019. Computer networks title: Computer networking: A top-down approach. Instructor 201901 (2019). [108] Karthik Valmeekam, Matthew Marquez, Sarath Sreedharan, and Subbarao Kambhampati. 2023. On the Planning Abilities of Large Language Models–A Critical Investigation. arXiv preprint arXiv:2305.15771 (2023). [109] Dieter Vanderelst and Alan Winfield. 2018. An architecture for ethical robots inspired by the simulation theory of cognition. Cognitive Systems Research 48 (2018), 56–66. 37 , , os , , Shapiro, et al. [110] Wendell Wallach and Colin Allen. 2008. Moral machines: Teaching robots right from wrong. Oxford University Press. [111] Jane X Wang, Zeb Kurth-Nelson, Dharshan Kumaran, Dhruva Tirumala, Hubert Soyer, Joel Z Leibo, Demis Hassabis, and Matthew Botvinick. 2018. Prefrontal cortex as a meta-reinforcement learning system. Nature neuroscience 21, 6 (2018), 860–868. [112] Jane X Wang, Zeb Kurth-Nelson, Dhruva Tirumala, Hubert Soyer, Joel Z Leibo, Remi Munos, Charles Blundell, Dharshan Kumaran, and Matt Botvinick. 2016. Learning to reinforcement learn. arXiv preprint arXiv:1611.05763 (2016). [113] Zhenhailong Wang, Shaoguang Mao, Wenshan Wu, Tao Ge, Furu Wei, and Heng Ji. 2023. Unleashing Cognitive Synergy in Large Language Models: A Task-Solving Agent through Multi-Persona Self-Collaboration. arXiv preprint arXiv:2307.05300 (2023). [114] David Warriner. 2008. The man who mistook his wife for a hat and other clinical tales. [115] Alan FT Winfield and Marina Jirotka. 2017. The case for an ethical black box. In Towards Autonomous Robotic Systems: 18th Annual Conference, TAROS 2017, Guildford, UK, July 19–21, 2017, Proceedings 18. Springer, 262–273. [116] Yang Xiao, Ning Zhang, Wenjing Lou, and Y Thomas Hou. 2020. A survey of distributed consensus protocols for blockchain networks. IEEE Communications Surveys & Tutorials 22, 2 (2020), 1432–1465. [117] Yaqi Xie, Chen Yu, Tongyao Zhu, Jinbin Bai, Ze Gong, and Harold Soh. 2023. Translating natural language to planning goals with large-language models. arXiv preprint arXiv:2302.05128 (2023). [118] Malcolm P Young, Claus-C Hilgetag, and Jack W Scannell. 2000. On imputing function to structure from the behavioural effects of brain lesions. Philosophical Transactions of the Royal Society of London. Series B: Biological Sciences 355, 1393 (2000), 147–161. [119] Hector Zenil, Jesper Tegnér, Felipe S Abrahão, Alexander Lavin, Vipin Kumar, Jeremy G Frey, Adrian Weller, Larisa Soldatova, Alan R Bundy, Nicholas R Jennings, et al. 2023. The Future of Fundamental Science Led by Generative Closed-Loop Artificial Intelligence. arXiv preprint arXiv:2307.07522 (2023). [120] Yue Zhen, Sheng Bi, Lu Xing-tong, Pan Wei-qin, Shi Hai-peng, Chen Zi-rui, and Fang Yi-shu. 2023. Robot Task Planning Based on Large Language Model Representing Knowledge with Directed Graph Structures. arXiv preprint arXiv:2306.05171 (2023). 38
Title: Extending Multilingual BERT to Low-Resource Languages: Summary: Multilingual BERT (M-BERT) has been a huge success in both supervised and zero-shot cross-lingual transfer learning. However, this success has focused only on the top 104 languages in Wikipedia that it was trained on. In this paper, we propose a simple but effective approach to extend M-BERT (E-BERT) so that it can benefit any new language, and show that our approach benefits languages that are already in M-BERT as well. We perform an extensive set of experiments with Named Entity Recognition (NER) on 27 languages, only 16 of which are in M-BERT, and show an average increase of about 6% F1 on languages that are already in M-BERT and 23% F1 increase on new languages. # Extending Multilingual BERT to Low-Resource Languages # Zihan Wang∗ University of Illinois Urbana-Champaign Urbana, IL 61801, USA zihanw2@illinois.edu Karthikeyan K ∗ Indian Institute of Technology Kanpur Kanpur, Uttar Pradesh 208016, India kkarthi@cse.iitk.ac.in # Stephen Mayhew† Duolingo Pittsburgh, PA, 15206, USA stephen@duolingo.com # Dan Roth University of Pennsylvania Philadelphia, PA 19104, USA danroth@seas.upenn.edu # Abstract Improvements by extending Multilingual BERT (M-BERT) has been a huge success in both supervised and zero-shot cross-lingual transfer learning. However, this success has focused only on the top 104 lan- guages in Wikipedia that it was trained on. In this paper, we propose a simple but effective approach to extend M-BERT (E-MBERT) so that it can benefit any new language, and show that our approach benefits languages that are already in M-BERT as well. We perform an extensive set of experiments with Named En- tity Recognition (NER) on 27 languages, only 16 of which are in M-BERT, and show an aver- age increase of about 6% F1 on languages that are already in M-BERT and 23% F1 increase on new languages. ‘0 ° In BERT AVG Out BERT AVG mM-BERT_supervised mM-BERT_zeroshot m E-MBERT_zeroshot Figure 1: Comparison between M-BERT and our proposed approach E-MBERT: We report averaged zero-shot NER performance on 16 languages that are already in M-BERT and 11 new language that are out of M-BERT. We also report average of M-BERT’s per- formance with supervised NER data as a upper-bound. of which M-BERT covers only the top 104 lan- guages (less than 3%). 1 # 1 Introduction Recent works (Wu and Dredze, 2019; Karthikeyan et al., 2020) have shown the zero-shot cross-lingual ability of M-BERT (Devlin et al., 2018) on vari- ous semantic and syntactic tasks – just fine-tuning on English data allows the model to perform well on other languages. Cross-lingual learning is im- perative for low-resource languages (LRL), such as Somali and Uyghur, as obtaining supervised training data in these languages is particularly hard. However, M-BERT is not pre-trained with these languages, thus limiting its performance on them. Languages like Oromo, Hausa, Amharic and Akan are spoken by more than 20 million people, yet M-BERT does not cover these languages. Indeed, there are about 40001 languages written by humans, ∗Equal Contribution; most of this work was done while the author interned at the University of Pennsylvania. †This work was done while the author was a student at the University of Pennsylvania. One of the approaches to use the idea of M-BERT for languages that are not already present is to train a new M-BERT from scratch. How- ever, this is extremely time-consuming and ex- pensive: training BERT-base itself takes about four days with four cloud TPUs (Devlin et al., 2019), so training M-BERT should take even more time2. Alternatively, we can train Bilingual BERT (B-BERT) (Karthikeyan et al., 2020), which is more efficient than training an M-BERT. However, one major disadvantage of B-BERT is that we can not use supervised data from multiple languages, even if it is available. To accommodate a language that is not in M-BERT, we propose an efficient approach Extend that adapts M-BERT to the language. Extend works by enlarging the vocabulary of M-BERT to accommodate the new language and then continue pre-training on this language. Our approach consumes less than 7 hours to train with a single cloud TPU. # 1https://www.ethnologue. # com/enterprise-faq/ how-many-languages-world-are-unwritten-0 2The exact training time was not reported. We performed comprehensive experiments on NER task with 27 languages of which 11 languages are not present in M-BERT. From Figure 1 we can see that our approach performs significantly better than M-BERT when the target language is out of the 104 languages in M-BERT. Even for high- resource languages that are already in M-BERT, our approach is still superior. The key contributions of the work are (i) We propose a simple yet novel approach to add a new language to M-BERT (ii) We show that our ap- proach improves over M-BERT for both languages that are in M-BERT and out of M-BERT (iii) We show that, in most cases, our approach is superior to training B-BERT from scratch. Our results are reproducible and we will release both the models and code. # 2 Related works Cross-lingual learning has been a rising interest in NLP. For example, BiCCA (Faruqui and Dyer, 2014), LASER (Artetxe and Schwenk, 2019) and XLM (Conneau and Lample, 2019). Although these models have been successful, they need some form of cross-lingual supervision such as a bilin- gual dictionary or parallel corpus, which is par- ticularly challenging to obtain for low-resource languages. Our work differ from above as we do not require such supervision. While other ap- proaches like MUSE (Lample et al., 2018) and VecMap (Artetxe et al., 2018) can work without any cross-lingual supervision, M-BERT already often outperforms these approaches (Karthikeyan et al., 2020). Schuster et al. (2019) has a setting of contin- uing training similar to ours. However, their ap- proach focus more on comparing between whether B-BERT (JointPair) learns cross-lingual features from overlapping word-pieces, while ours focus more on improving M-BERT on target languages, and addresses the problem of missing word-pieces. We show that our Extend method works well on M-BERT, and is better than B-BERT in several languages, whereas their method (MonoTrans) has a similar performance as B-BERT. This together implies that our Extend method benefits from the multilinguality of the base model (M-BERT vs BERT). # 3 Background # 3.1 Multilingual BERT (M-BERT) M-BERT is a bi-directional transformer language model pre-trained with Wikipedia text of top 104 languages – languages with most articles in Wikipedia. M-BERT uses the same pre-training objective as BERT – masked language model and next sentence prediction objectives (Devlin et al., 2019). Despite not being trained with any specific cross-lingual objective or aligned data, M-BERT is surprisingly cross-lingual. For cross-lingual trans- fer, M-BERT is fine-tuned on supervised data in high-resource languages like English and tested on the target language. # 3.2 Bilingual BERT (B-BERT) B-BERT is trained in the same way as M-BERT except that it contains only two languages – En- glish and the target language. Recent works have shown the cross-lingual effectiveness of M-BERT (Pires et al., 2019; Wu and Dredze, 2019), and B-BERT (Karthikeyan et al., 2020) on NER and other tasks. # 4 Our Method: Extend In this section, we discuss our training protocol Extend which works by extending the vocabulary, encoders and decoders to accommodate the target language and then continue pre-training on this language. Let the size of M-BERT’s vocabulary be Vmbert and the embedding dimension be d. We first cre- ate the vocabulary with the monolingual data in the target language following the same procedure as BERT, and filter out all words that appear in M-BERT’s vocabulary. Let the size of this new vocabulary be Vnew. Throughout the paper, we set Vnew = 30000. Then, we append this new vocabulary to M-BERT’s vocabulary. We extend the encoder and decoder weights of the M-BERT model so that it can encode and decode the new- vocabulary. That is, we extend the M-BERT’s en- coder matrix of size Vmbert×d with a matrix of size Vnew×d , which is initialized following M-BERT’s procedure, to create an extended encoder of size (Vmbert + Vnew) × d; we do similar extension for decoder. Note that M-BERT uses weight-tying, hence the decoder is the same as the encoder, ex- cept it has an additional bias. We then continue pre-training with the monolin- gual data of the target language. Note that except for the newly appended part of encoder and de- coder, we initialize all weights with M-BERT’s pre- trained weight. We call the trained model model E-MBERT. # 5 Experiments # 5.1 Experimental Settings Dataset. Our text corpus and NER dataset are from LORELEI (Strassel and Tracey, 2016). We use the tokenization method from BERT to preprocess text corpuses. For zero-shot cross-lingual NER, we evaluate the performance on the whole annotated set; for supervised learning, since we just want an understanding of a upper-bound, we apply cross validation to estimate the performance: each fold is evaluated by a model trained on the other folds, and the average F1 is reported. NER Model. We use a standard Bi-LSTM- CRF (Ma and Hovy, 2016; Lample et al., 2016) framework and use AllenNLP (Gardner et al., 2018) as our toolkit. The scores reported in NER is the F1 score averaged across five runs with different random seeds. BERT training. While extending, we use a batch size of 32 and a learning rate of 2e-5, which BERT suggests for fine-tuning, and we train for 500k iter- ations. Whereas for B-BERT we use a batch size of 32 and learning rate of 1e-4 and train for 2M iterations. We follow BERT setting for all other hyperparameters. # 5.2 Comparing between E-MBERT and M-BERT We compare the cross-lingual zero-shot NER per- formance of M-BERT and E-MBERT. We train only with supervised LORELEI English NER data. We also report the performance of M-BERT with supervision on the target language, which allows us to get a reasonable “upper-bound” on the dataset. From Figure 2, we can see that in almost all languages, E-MBERT outperforms M-BERT irre- spective of whether they exist or do not exist in M-BERT. It is clear that E-MBERT performs better than M-BERT when the language is not present; how- ever, it is intriguing that E-MBERT improves over M-BERT when the language is already present in M-BERT. We attribute this improvement in perfor- mance to three reasons • Increased vocabulary size of target language – Since most languages have a significantly smaller Wikipedia data than English, they have a fewer vocabulary in M-BERT, our approach eliminates this issue. Note that it may not be a good idea to train single M-BERT with larger vocabulary sizes for every language, as this will create a vast vocabulary (a few million). • E-MBERT is more focused on the target lan- guage, as during the last 500k steps, it is opti- mized to perform well on it. • Extra monolingual data – More monolingual data in the target language can be beneficial. Lang M-BERT E w/ Lrl E w/ Wiki Russian Thai Hindi 56.56 22.46 48.31 55.70 40.99 62.72 56.64 38.35 62.77 Table 1: Performance of M-BERT, Extend with LORELEI data and Extend with Wikipedia data. # 5.3 Extend without extra data The effectiveness of E-MBERT may be partially explained by the extra monolingual data the model is trained on. To explore the performance of E-MBERT without this extra training data, we Extend with using Wikipedia data, which is used in M-BERT. From Table 1, we can see that even without additional data, E-MBERT’s performance does not degrade. Lang B-BERT Extend Somali Amharic Uyghur Akan Hausa Wolof Zulu Tigrinya Oromo Kinyarwanda Sinhala 51.18 38.66 21.94 48.00 26.45 39.92 44.08 6.34 8.45 46.72 16.93 53.63 43.70 42.98 49.02 24.37 39.70 39.65 7.61 12.28 44.40 33.97 Table 2: Comparison between B-BERT and E- MBERT: We compare B-BERT vs E-MBERT train- ing protocols. Both the models uses same target lan- guage monolingual data. We compare the perfor- mances on languages that are not in M-BERT, so that E-MBERT doesn’t make use of M-BERT’s additional Wikipedia data. Languages In M-BERT 1 00 a - 0 we & ne gy™ yo ws «i wet ay \S G oo — oo gos” oxo! # Performance (F1) Languages Out M-BERT # Performance (F1) Ryewauay a oe oo yo? m M-BERT_supervised 0 0 0 10 0 2 it 9 ue = m M-BERT_zeroshot ‘ a of ow ot ow? oe «e™ E-MBERT_zeroshot Figure 2: Comparison between M-BERT and E-MBERT: We compare zero-shot cross-lingual NER perfor- mance (F1 score) on M-BERT and Extend using 27 languages. The languages are ordered by amount of text data in LORELEI. We also report the M-BERT’s supervised performance as a benchmark to compare. # 5.4 Comparing between E-MBERT and B-BERT Another way of addressing M-BERT on unseen languages is to completely train a new M-BERT. Restricted by computing resources, it is often only feasible to train on both the source and the tar- get, hence a bilingual BERT (B-BERT). Both E-MBERT with B-BERT uses the same text cor- pus in the target language; for B-BERT, we sub- sample English Wikipedia data. We focus only on languages that are not in M-BERT so that E-MBERT will not have an advantage on the tar- get language because of data from Wikipedia. Al- though the English corpus of B-BERT is different from E-MBERT, the difference is marginal consid- ering its size. Indeed we show that B-BERT and E-MBERT have similar performance on English NER, refer Appendix A and Appenddix A.3. guages that help transfer knowledge from English to target, while B-BERT can only leverage En- glish data. For example, in the case of Sinhala and Uyghur, a comparatively high-resource related lan- guage like Tamil and Turkish in M-BERT can help the E-MBERT learn Sinhala and Uyghur better. # 5.5 Rate of Convergence In this subsection, we study the convergence rate of E-MBERT and B-BERT. We evaluate these two models on two languages, Hindi (in M-BERT) and Sinhala (not in M-BERT), and report the re- sults in Figure 3. We can see that E-MBERT is able to converge within just 100k steps, while for B-BERT, it takes more than 1M steps to converge. This shows that E-MBERT is much more efficient than B-BERT. # 5.6 Performance on non-target languages From Table 2, we can see that E-MBERT of- ten outperforms B-BERT. Moreover, B-BERT is trained for 2M steps for convergence, while E-MBERT requires only 500k steps. We believe that this advantage comes for the following reason: E-MBERT makes use of the better multilingual model M-BERT, which potentially contains lan- Our Extend method results in the base model (M-BERT) to focus on the target language, and nat- urally this degrades performance on the other lan- guages that are not the target language. We report the performance of Hindi and Sinhala E-MBERT models evaluated on the other languages in Ap- pendix A.2. Performance as Pretraining Steps Increase 2000 se B-BERT (Hindi) | —-E-MBERT (Hindi) ««- B-BERT (Sinhala) ——E-MBERT (Sinhala) Figure 3: Performance of B-BERT and Extend as number of pre-training steps increase # 6 Conclusions and Future work In this work, we propose Extend that deals with languages not in M-BERT. Our method has shown great performance across several languages com- paring to M-BERT and B-BERT. While Extend deals with one language each time, it would be an interesting future work to extend on multiple languages at the same time. Furthermore, instead of randomly initialising the embeddings of new vocabulary, we could possi- bly use alignment models like MUSE or VecMap with bilingual dictionaries to initialize. We could also try to apply our approach to better models like RoBERTa (Liu et al., 2019) in multilingual case. # References Mikel Artetxe, Gorka Labaka, and Eneko Agirre. 2018. A robust self-learning method for fully unsupervised cross-lingual mappings of word embeddings. In Pro- ceedings of the 56th Annual Meeting of the Associa- tion for Computational Linguistics (Volume 1: Long Papers), pages 789–798, Melbourne, Australia. As- sociation for Computational Linguistics. Mikel Artetxe and Holger Schwenk. 2019. Mas- sively multilingual sentence embeddings for zero- shot cross-lingual transfer and beyond. Trans. Assoc. Comput. Linguistics, 7:597–610. Alexis Conneau and Guillaume Lample. 2019. Cross- In Advances lingual language model pretraining. in Neural Information Processing Systems 32: An- nual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, 8-14 December 2019, Vancouver, BC, Canada, pages 7057–7067. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. Multilingual bert - r. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. BERT: Pre-training of deep bidirectional transformers for language under- In Proceedings of the 2019 Conference standing. of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 4171–4186, Minneapolis, Minnesota. Associ- ation for Computational Linguistics. Manaal Faruqui and Chris Dyer. 2014. Improving vec- tor space word representations using multilingual correlation. In Proceedings of the 14th Conference of the European Chapter of the Association for Com- putational Linguistics, pages 462–471, Gothenburg, Sweden. Association for Computational Linguistics. Matt Gardner, Joel Grus, Mark Neumann, Oyvind Tafjord, Pradeep Dasigi, Nelson F. Liu, Matthew Pe- ters, Michael Schmitz, and Luke Zettlemoyer. 2018. AllenNLP: A deep semantic natural language pro- In Proceedings of Workshop for cessing platform. NLP Open Source Software (NLP-OSS), pages 1– 6, Melbourne, Australia. Association for Computa- tional Linguistics. K Karthikeyan, Zihan Wang, Stephen Mayhew, and Dan Roth. 2020. Cross-lingual ability of multilin- gual bert: An empirical study. Guillaume Lample, Miguel Ballesteros, Sandeep Sub- ramanian, Kazuya Kawakami, and Chris Dyer. 2016. Neural architectures for named entity recognition. In Proceedings of the 2016 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies, pages 260–270, San Diego, California. Association for Computational Linguistics. Guillaume Lample, Alexis Conneau, Marc’Aurelio Ranzato, Ludovic Denoyer, and Herv Jgou. 2018. In Interna- Word translation without parallel data. tional Conference on Learning Representations. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man- dar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining ap- proach. arXiv preprint arXiv:1907.11692. End-to-end sequence labeling via bi-directional LSTM-CNNs- CRF. In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Vol- ume 1: Long Papers), pages 1064–1074, Berlin, Ger- many. Association for Computational Linguistics. Telmo Pires, Eva Schlinger, and Dan Garrette. 2019. In Pro- How multilingual is multilingual BERT? ceedings of the 57th Annual Meeting of the Asso- ciation for Computational Linguistics, pages 4996– 5001, Florence, Italy. Association for Computa- tional Linguistics. Sebastian Schuster, Sonal Gupta, Rushin Shah, and Mike Lewis. 2019. Cross-lingual transfer learning In Proceed- for multilingual task oriented dialog. ings of the 2019 Conference of the North American Chapter of the Association for Computational Lin- guistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 3795–3805, Min- neapolis, Minnesota. Association for Computational Linguistics. Stephanie Strassel and Jennifer Tracey. 2016. Lorelei language packs: Data, tools, and resources for technology development in low resource languages. In Proceedings of the Tenth International Confer- ence on Language Resources and Evaluation (LREC 2016), pages 3273–3280. Shijie Wu and Mark Dredze. 2019. Beto, bentz, be- cas: The surprising cross-lingual effectiveness of BERT. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natu- ral Language Processing (EMNLP-IJCNLP), pages 833–844, Hong Kong, China. Association for Com- putational Linguistics. # A Appendices # A.1 Performance of E-MBERT on English: The knowledge of E-MBERT on English (source language) is not affected. From Table 3, we can see that, except for few languages, the English performance of E-MBERT is almost as good as M-BERT’s. # A.2 Detailed data on all languages In Table 4, we report the full result on comparing M-BERT and E-MBERT. We can also see that Extend is not only useful for cross-lingual performance but also for useful for supervised performance (in almost all cases). We also notice that extending on one language hurts the transferability to other languages. # A.3 Comparison between B-BERT and E-MBERT: In Table 5 we reported the performance of Extend and B-BERT on both English as well as target. We can see that English performance of B-BERT is mostly better than Extend. However, in most cases Extend performs better on target language. This indicates that E-MBERT does not have an unfair advantage on English. # E M-BERT OUT OF BERT # IN BERT Arabic Bengali Mandarin Farsi Hindi Hungarian Indonesian Russian Spanish Swahili Tamil Tagalog Thai Turkish Uzbek Yoruba 77.67 76.2 78.58 77.57 78.86 78.92 80.93 80.87 81.15 77.72 77.6 79.56 78.21 79.49 77.19 77.55 M-BERT 79.37 Table 3: Performance on English: We report the En- glish NER performance of M-BERT as well as perfor- mance E-MBERT. In BERT Model M-sup M-zero E-sup E-zero Hindi Sinhala Corpus (M) NER (k) Arabic Bengali Mandarin Farsi Hindi Hungarian Indonesian Russian Spanish Swahili Tamil Tagalog Thai Turkish Uzbek Yoruba 61.14 71.29 71.76 65.09 72.88 81.98 75.67 75.60 78.12 74.26 68.55 85.98 73.58 82.55 79.36 75.75 37.56 46.18 50.0 47.71 48.31 68.26 58.91 56.56 64.53 52.39 41.68 66.50 22.46 62.80 49.56 37.13 61.97 84.44 73.86 68.27 81.15 82.08 80.09 76.51 78.14 81.9 77.91 88.63 86.40 87.02 84.79 81.34 40.83 63.49 52.30 50.26 62.72 64.36 60.73 55.70 64.75 57.21 53.42 62.61 40.99 66.19 59.68 50.72 19.2 17.94 8.88 22.38 62.72 24.38 29.5 26.08 37.06 25.46 14.75 34.73 4.03 34.34 21.84 19.14 16.72 14.01 24.64 20.44 18.0 35.74 37.89 36.15 47.32 31.91 12.96 42.16 3.78 39.23 28.83 25.04 0.19 10.19 1.66 10.32 1.66 10.09 1.75 10.07 1.68 0.29 4.47 0.33 4.47 10.39 4.91 0.30 Out of BERT Akan Amharic Hausa Somali Wolof Zulu Uyghur Tigrinya Oromo Kinyarwanda Sinhala 75.87 11.79 67.67 74.29 67.10 78.89 32.64 24.75 72.00 65.85 18.12 21.96 3.27 15.36 18.35 13.63 15.82 3.59 4.74 9.34 30.18 3.43 79.33 79.09 75.73 84.56 70.27 84.50 79.94 79.42 72.78 74.46 71.63 49.02 43.70 24.37 53.63 39.70 39.65 42.98 7.61 12.28 44.40 33.97 12.82 3.95 12.58 15.84 9.83 12.3 1.45 7.91 6.84 26.55 3.39 35.2 3.9 14.77 21.64 26.45 13.72 1.52 5.71 10.11 32.3 33.97 0.52 1.70 0.19 0.60 0.09 0.92 1.97 0.01 0.01 0.06 0.10 5.50 11.65 8.05 4.38 6.22 5.81 6.96 7.26 3.48 5.61 15.51 6.98 15.51 7.09 11.82 3.21 8.42 5.48 5.64 4.16 10.63 11.58 2.45 2.20 2.96 0.95 1.02 Table 4: In the order from left to right, column means: M-BERT with supervision, M-BERT zero-shot cross- lingual, E-MBERT with supervision, E-MBERT zero-shot cross-lingual. Then we give performance of Hindi and Sinhala E-MBERT models when evaluated on all the languages. The last two columns are dataset statistics, with number of million lines in the LORELEI corpus and number of thousand lines in LORELEI NER dataset. English Target Language E-MBERT B-BERT E-MBERT Akan Amharic Hausa Somali Wolof Zulu Uyghur Tigrinya Oromo Kinyarwanda Sinhal 79.19 78.36 74.24 78.60 78.11 79.32 77.76 76.21 76.06 73.05 73.70 77.49 78.44 80.13 79.17 81.01 81.82 79.65 80.35 78.13 79.37 80.04 49.02 43.70 24.37 53.63 39.70 39.65 42.98 7.61 12.28 44.4 33.97 48.00 38.66 26.45 51.18 39.92 44.08 21.94 6.34 8.45 46.72 16.93 # B-BERT Table 5: Comparison Between B-BERT vs E-MBERT: We compare the performance of E-MBERT with B-BERT on both English and target language. As a reference, performance of M-BERT is 79.37 on English. This shows that neither B-BERT nor E-MBERT gets unfair advantage from the English part of the model.
Title: Less is More: Pre-train a Strong Text Encoder for Dense Retrieval Using a Weak Decoder: Summary: Dense retrieval requires high-quality text sequence embeddings to support effective search in the representation space. Autoencoder-based language models are appealing in dense retrieval as they train the encoder to output high-quality embedding that can reconstruct the input texts. However, in this paper, we provide theoretical analyses and show empirically that an autoencoder language model with a low reconstruction loss may not provide good sequence representations because the decoder may take shortcuts by exploiting language patterns. To address this, we propose a new self-learning method that pre-trains the autoencoder using a \textit{weak} decoder, with restricted capacity and attention flexibility to push the encoder to provide better text representations. Our experiments on web search, news recommendation, and open domain question answering show that our pre-trained model significantly boosts the effectiveness and few-shot ability of dense retrieval models. Our code is available at https://github.com/microsoft/SEED-Encoder/. # Less is More: Pre-train a Strong Text Encoder for Dense Retrieval Using a Weak Decoder Shuqi Lu1∗, Di He2†, Chenyan Xiong2†, Guolin Ke2, Waleed Malik2, Zhicheng Dou1, Paul Bennett2, Tie-Yan Liu2, Arnold Overwijk2 1Renmin University of China 2Microsoft {lusq, dou}@ruc.edu.cn {chenyan.xiong, dihe, guolin.ke, waleed.malik, paul.n.bennett, tyliu, arnold.overwijk}@microsoft.com # Abstract Dense retrieval requires high-quality text se- quence embeddings to support effective search in the representation space. Autoencoder-based language models are appealing in dense re- trieval as they train the encoder to output high- quality embedding that can reconstruct the in- put texts. However, in this paper, we provide theoretical analyses and show empirically that an autoencoder language model with a low reconstruction loss may not provide good se- quence representations because the decoder may take shortcuts by exploiting language pat- terns. To address this, we propose a new self- learning method that pre-trains the autoencoder using a weak decoder, with restricted capacity and attention flexibility to push the encoder to provide better text representations. Our experiments on web search, news recommen- dation, and open domain question answering show that our pre-trained model significantly boosts the effectiveness and few-shot ability of dense retrieval models. Our code is available at https://github.com/microsoft/ SEED-Encoder/. 1 # 1 Introduction Recently, Dense Retrieval (DR) has progressed to more important roles in many language systems, for example, web search (Xiong et al., 2021), ques- tion answering (Karpukhin et al., 2020), and news recommendation (Wu et al., 2020b). In the first- stage retrieval of these scenarios, DR models gener- ally employ a Siamese/Dual-Encoder architecture in practice. The encoder model first separately en- codes the user side (query, browsing history, or question) and the corpus side (document or pas- sages) as individual embeddings in a learned repre- sentation space (Lee et al., 2019), where retrieval with simple similarity metrics are conducted effec- tively (Johnson et al., 2017; Guo et al., 2020). *Work done while interning at Microsoft. †Corresponding Authors. A popular choice of text encoders in DR is the Transformer network pre-trained by language mod- eling (e.g., BERT) (Reimers and Gurevych, 2019a). It is unexpected that, unlike in other language tasks where pre-trained models simply excel, directly fine-tuning BERT in DR often underperforms unsu- pervised sparse retrieval, e.g., BM25. Some com- plicated procedures are almost necessary to effec- tively fine-tune pre-trained Transformers in dense retrieval (Karpukhin et al., 2020; Luan et al., 2021; Xiong et al., 2021). One observation is that the pre-trained language models are not effective at encoding the semantics of the entire text sequence in one embedding, especially in dense retrieval where text sequences are mostly longer than 128 tokens (Luan et al., 2021). In some other modalities, autoencoders have been widely used to obtain high-quality data rep- resentations (Vincent et al., 2010; Kingma and Welling, 2013). They pair a decoder on top of the encoder, trains the decoder to reconstruct the data solely from the encoder’s encodings, thus enforce an information bottleneck on the data encodings for better representation quality. Recently, autoen- coders have been brought in language pre-training. Li et al. (2020) stacks a GPT-2 decoder on top of the BERT encoder and trains the autoencoder via a conditional language modeling task. Their learned encoder, Optimus, provides better text encodings for GLUE and language generation tasks, but, as shown in our empirical study, does not provide better encodings for dense retrieval. This phenomenon inspires us to investigate why the standard setup of autoencoders in language modeling falls short in dense retrieval. We first no- tice that in the auto-regressive decoder, the model takes not only the CLS encoding but also the pre- vious tokens as input. Our mathematical analysis shows that the decoder can exploit natural language patterns using its access to previous tokens and bypass the dependency on the encoder, especially when the sequence is long and the decoder is strong, e.g., GPT-2. As a result, the autoencoder achieving a low reconstruction loss value does not necessarily provide better text sequence encodings. Our analyses lead to a quite simple solution: we present a new autoencoder pre-training strategy, which pairs the BERT-style encoder with a weak decoder by restricting its parameter capacity and attention flexibility. This way, our SEED-Encoder, “Strong tExt Encoder by training with weak De- coder”, creates an information bottleneck in the au- toencoder and forces the encoder to provide better text representations. In our experiments on three real-world applications, we confirm that SEED- Encoder produces better pre-trained checkpoints that seed dense retrieval models with higher accu- racy and better few-shot ability. # 2 Related work Pre-training Language Models. Masked Lan- guage Modeling (MLM) (Devlin et al., 2018) is one of the most effective ways to learn text repre- sentations. It first randomly masks some tokens in a sequence and then pre-trains a Transformer to recover them (Joshi et al., 2020; Liu et al., 2019; Clark et al., 2020). There are also attempts to de- sign sequence-level tasks during pre-training. The next sequence prediction task proposed in Devlin et al. (2018) trains the model to predict whether two sequences are contiguous. Liu et al. (2019) showed this task is not effective and can be removed. In Sun et al. (2020), more sequence-level tasks are de- veloped, such as predicting whether two segments are from the same document. Our learning frame- work architecture is close to Li et al. (2020), which trains an encoder and a decoder for both language understanding and generation. We will discuss its detail and show how it motivates our work. Dense Retrieval with Text Encoders. Dense- Retrieval systems often use the Siamese/Dual En- coder architecture, where two sequences are en- coded by the Transformer separately, and their sim- ilarity is calculated upon their sequence embed- dings. Reimers and Gurevych (2019b) is among the first to study how to use BERT in a Siamese architecture and found that the CLS representa- tion does not perform as well as expected. Re- cent research (Karpukhin et al., 2020; Xiong et al., 2021) demonstrated that applying pre-trained mod- els in dense text retrieval is not as straightforward. Karpukhin et al. (2020) use BM25 to find negative samples to better fine-tune pre-trained models for dense retrieval. Xiong et al. (2021) performs global noise constructive estimation and finds global neg- atives using the DR model for the DR model. # 3 Method In this section, we first recap preliminaries in lan- guage pre-training and autoencoder. Then we dis- cuss the drawbacks of using strong decoders in au- toencoder and address them with SEED-Encoder. # 3.1 Preliminary In a standard setup of pre-training language mod- els, e.g., BERT (Devlin et al., 2018), the neural network to be pre-trained is a multi-layer bidirec- tional Transformer encoder (Vaswani et al., 2017), which takes a sequence of tokens x = (x1, ..., xn) from the vocabulary V , and produces their contex- tualized representations h = (h1, ..., hn): (CLS, x1, ..., xn) Transformer −−−−−−→ (h0, h1, ..., hn), where CLS is a special token added in the first position, its contextual representation h0 is of- ten used as the representation of the sequence. The parameters of the Transformer θenc are typ- ically pre-trained using Masked Language Model- ing (MLM) (Devlin et al., 2018), which masks a fraction of the input sequence and trains the model to predict the original tokens. For ease of reference, we denoted the loss as LMLM(x, θenc). As there is no informative training target at the CLS position in token level pre-training tasks, it is not formally guaranteed that the contextual rep- resentation at CLS contains enough information for any sequence-level downstream tasks. Li et al. (2020) introduces the autoencoder setup in lan- guage model pre-training, which adds a reconstruc- tion loss on top of the CLS token’s h0: x θenc−−→ h0 θdec−−→ x. (1) where h0 is viewed as a latent variable. The de- coder θdec, which is another deep Transformer model GPT-2, receives h0 and generates the orig- inal input autoregressively. The (variational) de- coder loss is defined as (Li et al., 2020): Laec(@, Pace) = - > log P(xt\<t, ho; 9dec); (2) t:lwan where x<t are all previous tokens before t. (a) Ranking accuracy (b) Cosine similarity qm BERT |SN Optimus Value ecoososoor NWRUDUBLO mrr@10 Metrics recall@1k Cosine similarity esoscssso BNWAUAYHDO 64 128 256 512 Sequence length Figure 1: Behaviors of Optimus on MS MARCO Pas- sage Ranking Dev set: (a) its ranking accuracy in com- parison with vanilla BERT; (b) its sequence representa- tions’ cosine similarity at variant lengths. # 3.2 Effects of Using a Strong Decoder One would expect the autoencoder to provide good representations if the decoder can well recover the input. However, we found that a typical model stacking a standard autoregressive decoder on a standard BERT-style encoder doesn’t work well in dense retrieval tasks. For example, we fine- tune the pre-trained checkpoint of Optimus, which stacks GPT-2 on top of BERT on MS MARCO and compare it with BERT. We use Mean Reciprocal Rank(mrr) and recall as evaluation metrics. The detailed experimental setting can be found in Sec- tion 4.3, and the results are shown in Figure 1(a). The performance of Optimus on dense retrieval tasks is worse than standard BERT, a sharp contrast with Optimus’s effectiveness on other language tasks, e.g., in GLUE benchmarks. Note that one difference between data in GLUE and MS MARCO is the sequence length. In most GLUE tasks, the sequence length is short, e.g., average 14 tokens in SST-2, while the average passage length in MS MARCO is more than 450. Also, recent research shows that long sentences are hard to represent via single embedding vectors from pre-trained mod- els (Luan et al., 2021). To confirm this, We randomly select sequence pairs of different lengths and calculate the cosine similarity of their CLS embeddings provided by Optimus. The results are shown in Figure 1(b). The representations of long sequences (256 or 512 tokens) from Optimus are quite similar; the co- sine similarities of random long sequence pairs are around 0.8. The model yields cluttered represen- tations for long text sequences. When fine-tuned for dense retrieval in MS MARCO, it does not sep- arate relevant documents for a query from those irrelevant ones. All of those representations might be similar to each other and require dedicated fine- tuning to realign their encodings. # 3.3 Theoretical Analysis Next, we mathematically show why the encoder may fail to learn good sequence representations using a strong decoder. In Eqn. 2, at each time step t, the prediction of xt not only depends on the CLS encoding h0 but also the previous tokens x<t. Thus a lower reconstruction loss may not be contributed by more informative h0: for a large t in a long text sequence, the model may directly predict xt from x<t if the decoder is strong. The quality of the representation at the CLS is not guaranteed as a low decoding loss may not reflect much about h0. To further understand the requirements for infor- mative sequence representations, we investigate the relationship between the reconstruction loss, h0, and the language sequence in their mathematical form. First, we decompose the expectation of the loss Ldec into two terms: a Kullback–Leibler diver- gence and a conditional-entropy term, according to the following fact in information theory: Fact 1 Given two distributions P (Y, Z) and Q(Y, Z) on random variables (Y , Z), we have EY,Z∼P [− log Q(Z|Y )] = EY ∼P (Y )[DKL(P (Z|Y )||Q(Z|Y ))] + HP (Z|Y ). (3) We have X as a random variable defined in the sequence space X , where each sequence x is sam- pled from data distribution PD, X<t as the truncate of X at position t, and Pθdec as the sequence dis- tribution generated by the decoder. For simplicity, we assume all the sequences are of length n. The expected reconstruction loss can be rewritten as ED[Ldec(X, θdec)] (4) =Ep > ~ lg PX boo) (5) tslmn # tslmn Ep [ Pex = > Ep [ Pex (Po(Xi|X<r, bo)! (6) tilnn t:1∼n Pay..(Xi|X<ts ho)) ) + HD(Xt|X<t, h0). (8) The above equation shows that the loss con- sists of two terms, a K-L term DKL(·) (Eqn. 6 and Eqn. 7) describing the difference between two dis- tributions, and a conditional-entropy term HD(·) (Eqn. 8) reflecting the strength of language pat- terns. As we discuss next, both terms can achieve low values even with random h0. Reconstruction Loss X17 Xp Xai a ar ar ae Attention Span Auxiliary Restriction Decoder (3 layers) SEED-Encoder (12 layers) e e e e e e CLS Xy Xy X34 Figure 2: The structure of SEED-Encoder with an auxil- iary decoder. The encoder and decoder are connected only via the [CLS] representation as the information bottleneck. The decoder capacity is restricted in both parameter size and attention span. how Pθdec(Xt|X<t, h0), generated the sequence distribution, aligns with the ground truth distribution PD(Xt|X<t, h0). Even with a meaningless θenc, if the decoder has sufficient capacity, e.g., a very deep Transformer, it can still approximate the ground truth distribution well and thereby reduce the K-L term. In theory, Transformers with arbitrary width and depth can approximate any sequence-level functions and may reach a low K-L loss using little information from h0 (Yun et al., 2019). The second term HD(Xt|X<t, h0) characterizes the strength of language patterns: The stronger the correlation between Xt with X<t, the lower the second term is. In natural language, the correlation becomes stronger with larger t as there is more information from the previous tokens. There is not a strong need for a good text encoder h0 because a strong decoder can capture the natural language patterns by itself. # 3.4 SEED-Encoder Our analysis shows that to obtain a stronger text encoder and a better h0, we can not make the de- coder too strong: we need to constrain its capacity and also the available language context to reduce the correlation between Xt and X<t, so that it has to rely on the information in the encoder CLS to reconstruct the text sequence. In the rest of this section, We introduce SEED- Encoder which adopts these designs. The model structure is illustrated in Figure 2. Making a language model weaker is easier than making it stronger. We simply modify Eqn. 2 to weaken the decoder: • Using a shallower Transformer θweak dec with fewer layers (e.g., three); • Restricting its access to previous context, i.e., limit model attention to previous k tokens. This leads to the following reconstruction loss: Lise (a, One®) = — SO log P(ailar—nt1, ho; 9982"), ©) tilwn where k is the window size of the restricted atten- tion. Through these modifications, we enforce the information bottleneck between the encoder and the decoder, thereby forcing the decoder to rely on the CLS representation of the encoder, and pushing the encoder to learn a more informative representa- tion. Similar to Li et al. (2020), the pre-training of SEED-Encoder uses the combination of the en- coder’s standard MLM loss and the decoder’s re- construction loss: L(x, θenc, θweak LMLM(x, θenc) + Lweak dec ) = dec (x, θweak dec ). (10) The encoder and decoder are trained together. Af- ter pre-training, the decoder is discarded, and the encoder is used in downstream applications. # 4 Experiments In this section, we present various experimental analyses to evaluate the SEED-Encoder on dense retrieval tasks. More results on other language tasks are in Appendix A.2. # 4.1 Pre-training Details All our models are pre-trained from scratch, follow- ing the setup of BERT-base (Devlin et al., 2018): pre-training on English Wikipedia and BookCor- pus (Zhu et al., 2015) (roughly 16GB texts) for 1M steps, with batch size 256, maximum sequence length 512, and 15% masks. We follow the pre- processing steps and use 32,768 sub-word tokens in Ke et al. (2020). We remove the next sentence prediction task following Liu et al. (2019). Rerank Retrieval Model BM25 (Craswell et al., 2020) Best DeepCT (Dai and Callan, 2019) Best TREC Trad IR (Craswell et al., 2020) DPR (RoBERTa) (Karpukhin et al., 2020) With DPR (BM25 Neg) BERT (Devlin et al., 2018) Optimus (Li et al., 2020) ELECTRA (Clark et al., 2020) ERNIE2.0 (Sun et al., 2020) RoBERTa (Liu et al., 2019) BERT (Ours) SEED-Encoder With ANCE (FirstP) RoBERTa (Liu et al., 2019) BERT (Ours) SEED-Encoder MRR@10 MRR@10 Recall@1k 0.814 n.a. n.a. 0.952 - - - - 0.240 0.243 0.240 0.311 0.317 0.300 0.300 0.324 - 0.326 0.329† 0.310 0.244 0.258 0.321 0.299 0.320 0.329† 0.929 0.880 0.854 0.942 0.928 0.933 0.953† - 0.327 0.334† 0.330 0.332 0.339† 0.959 0.952 0.961† Table 1: First stage retrieval results on MS MARCO Passage ranking Dev set. Rerank MRR is for reference only. Statistically significant improvements over BERT (Ours) are marked by †. We use Adam (Kingma and Ba, 2014) as the optimizer, and set its hyperparameter € to le-6 and (81, 82) to (0.9, 0.999). The peak learning rate is set to le-4 with a 10k-step warm-up stage. After the warm-up stage, the learning rate decays linearly to zero. We set the dropout probability to 0.1, gra- dient clip norm to 1.0, and weight decay to 0.01. All codes are implemented based on fairseg (Ott et al., 2019) in PyTorch (Paszke et al., 2017). All models are run on 8 NVIDIA Tesla V100 GPUs with mixed-precision (Micikevicius et al., 2017). Our encoder architecture is the same with BERT- base: 12 Transformer layers, eight attention heads, and 768 hidden dimensions (110M parameters). We use a three-layer Transformer as the decoder, restrict its attention to the previous two tokens (at- tention span k = 2), and keep all else the same with the encoder. The decoder is only used in pre- training and is dropped during fine-tuning. There is no additional cost in fine-tuning nor inference. # 4.2 Fine-tuning Siamese/Dual-Encoders Fine-tuning SEED-Encoder in the Siamese archi- tecture on the dense retrieval tasks is the same as other pre-trained models. Here we show how fine- tuning in a typical sentence pair matching task with binary labels can be done with Triplet loss. L= > relu(1 — (s(a%, 2+) — s(x7,24-))). @ ett pd The training data include triples of query xq and its positive/negative labeled sequence (xd+, xd−). The scoring of the sequence pairs s(xq, xd) is done by simple similarity functions, such as cosine and dot product, on their CLS encodings. More ad- vanced fine-tuning strategies (Karpukhin et al., 2020; Xiong et al., 2021) can also be used as SEED- Encoder is an alternative for other pre-trained en- coders. # 4.3 Experiments on Web Search Our first application, web search (Lee et al., 2019),.uses the MS MARCO (Bajaj et al., 2016) dataset, the largest public search benchmark to date. It includes two tasks, passage ranking and docu- ment ranking. We focus on the first stage retrieval step, which is to find relevant passages/documents from the entire corpus. We also show the results in the reranking setting where all models rerank a pre- given set of candidate documents (Top 100 from BM25) for reference. More details of MARCO are in Appendix A.1. Our pre-trained encoders are fine-tuned with ANCE negative sampling strategy (Xiong et al., In document retrieval, we use ANCE 2021). (FirstP) which uses the first 512 tokens of the long document and cut-off the rest. We also evaluate with another negative sampling strategy, BM25 Neg, which uses top 100 BM25 retrieved results as negatives samples and performs similar to DPR (Karpukhin et al., 2020) on MARCO. Baselines: The main baseline is our run of BERT- base (Devlin et al., 2018; Liu et al., 2019), which we pre-trained and fine-tuned in the exact setting with SEED-Encoder. We use the permutation test and p < 0.05 as the statistical significance test be- tween SEED-Encoder and BERT (Ours). Besides BERT, we evaluate two other pre-trained language models in the same setting: ELECTRA (Clark et al., 2020) and ERNIE2.0 (Sun et al., 2020). ELECTRA is one of the most effective pre-trained encoders on the GLUE benchmark (Clark et al., 2019). ERNIE2.0 uses various token-level tasks and sentence-level tasks, including an IR Relevance Task. We use the MARCO passage benchmark to showcase the performance of these two pre-trained models. In addition, we also list the task-specific first stage retrieval baselines that were published re- cently or submitted to the leaderboard, although they barely outperform our vanilla BERT baseline. For passage ranking, the classic sparse retrieval baselines include the standard BM25, Best TREC Sparse Retrieval with tuned query expansion, and Best DeepCT, all from TREC DL 2019 official evaluation (Craswell et al., 2020). These three ap- proaches represent the standard sparse retrieval, Dev Eval Model BM25 (Craswell et al., 2020) DE-hybrid (Luan et al., 2021) BM25 + doc2query-T5 expansion ME-hybrid (Luan et al., 2021) Enriched Traditional IR Baseline ANCE MaxP (RoBERTa) (Xiong et al., 2021) With DPR (BM25 Neg) BERT (Ours) SEED-Encoder With ANCE (FirstP) RoBERTa (Liu et al., 2019) BERT (Ours) SEED-Encoder Rerank Retrieval Retrieval 0.284 0.318 0.287 - 0.291 0.327 0.310 - 0.312 0.355 0.342 0.384 - - - - - - 0.338 0.344† 0.308 0.323† - - - 0.368 0.377† 0.373 0.382 0.394† - - 0.362 Table 2: MRR@100 on MARCO Documents from first- stage retrieval methods. Rerank results are for reference only. Statistically significant improvements over BERT (Ours) are marked by †. best classical sparse retrieval, and the latest method of using BERT to improve sparse retrieval. For document ranking, BM25 (Craswell et al., 2020) and the enriched traditional IR baseline are standard sparse retrieval baselines. The enriched traditional IR baseline uses pre-defined IR fea- tures, including BM25, to rank the documents. BM25 + doc2query-T5 expansion uses Doc2query model(Nogueira et al., 2019), expanding the doc- uments with predicted queries that are related to or representative of the documents’ content. The queries are predicted by a sequence-to-sequence model taking the document terms as input. Both DE-hybrid and ME-hybrid (Luan et al., 2021) use dense features from BERT and hand-craft sparse features. DE-hybrid takes the CLS representations of document and query as the dense feature and calculates the dot product similarity. This similar- ity score is further combined with sparse retrieval scores as the final score for ranking. Different from DE-hybrid, ME-hybrid uses max-pooling over mul- tiple contextual embeddings as dense features. Results: The results of SEED-Encoder and base- lines in MARCO Passage retrieval and Doc re- trieval are listed in Table 1 and Table 2. SEED- Encoder outperforms all existing baselines on all benchmarks. By simply switching its fine-tuning starting checkpoint from BERT to SEED-Encoder— without changing any architectures nor fine-tuning strategies—the accuracy is significantly improved on these two large-scale benchmarks. In comparison, on MARCO Passage retrieval, switching from BERT to ELECTRA or ERNIE2.0 does not improve the retrieval accuracy. Pre- training models optimized for other scenarios are not necessarily better for dense retrieval. On MARCO document retrieval, ANCE (FirstP) only uses one vector per document from its first Model Transformer (Vaswani et al., 2017) Transformer-XL (Dai et al., 2019) TENER (Yan et al., 2019) DA-Transformer (Wu et al., 2020a) With DPR (MIND Neg) BERT (ours) SEED-Encoder AUC MRR NDCG@5 NDCG@10 0.3594 0.6776 0.3305 0.3604 0.6792 0.3315 0.3589 0.6770 0.3301 0.3634 0.6832 0.3336 0.4163 0.4170 0.4158 0.4207 0.7015 0.346 0.3844 0.7059† 0.3506† 0.3908† 0.4479 0.4526† Table 3: Results on MIND news recommendation bench- mark. All methods are evaluated in the reranking setting with pre-given news candidates in MIND, to follow their official setting. Baseline scores are obtained from Wu et al. (2020a). Statistically significant improvements over BERT (Ours) are marked by †. passage, while ANCE (MaxP) uses four vectors per document from its first four passages, which often cover the full document body. Yet with SEED- Encoder as the starting point, ANCE (FirstP) out- performs the recent state-of-the-art ANCE (MaxP) with RoBERTa by relatively 6% in the hidden Eval, while using fewer embeddings per document. Re- ducing embeddings required per document is im- portant in real search systems where the corpus size is beyond billions (Xiong et al., 2021). # 4.4 Experiments on News Recommendation Our second application is news article recommen- dation, another important real-world task that con- nects users with information. We use the recently released MIcrosoft News Dataset (MIND) bench- mark (Wu et al., 2020b). The task is to rank a given set of candidate news articles based on the user’s previous click history on MSN news articles. The evaluation uses the user’s click as the positive la- bel. We use the public MIND Dev and its official metrics: AUC, MRR, NDCG@5, and NDCG@10. More details of MIND are in Appendix A.1. We follow MIND’s official setting and use a stan- dard dense retrieval model to rerank the pre-given candidate news articles. Our DR model represents each user’s history by concatenating all the titles they clicked on the MSN site, with [SEP] tokens in between, and using as many recent titles as pos- sible within the 512 length limit. The candidate articles are represented by the concatenation of their titles and snippets. Then it encodes the user history and candidate articles with SEED-Encoder, and matches them with dot-products. Baselines: MIND is a relatively new benchmark. The most recent baselines are those in Wu et al. (2020a). Based on Transformer (Vaswani et al., 2017), Transformer-XL (Dai et al., 2019) uses rel- ative positional encodings that integrate content- dependent positional scores and a global positional Model BM25 (Craswell et al., 2020) With DPR BERT (Karpukhin et al., 2020) BERT (BM25 +DPR) (Karpukhin et al., 2020) BERT (Ours) SEED-Encoder With ANCE BERT (Xiong et al., 2021) SEED-Encoder Top-20 Top-100 73.7 59.1 78.4 76.6 77.8 80.4† 85.4 83.8 85.1 87.1† 81.9 83.1† 87.5 88.7† Table 4: Retrieval results (Answer Coverage at Top-20/100) on Natural Questions in the setting from (Karpukhin et al., 2020). Statistically significant improvements over BERT are marked by †. score in the self-attention layer. TENER (Yan et al., 2019) uses direction-aware sinusoidal relative posi- tion embeddings in a similar way as in Transformer- XL. Different from Transformer-XL and TENER, DA-Transformer (Wu et al., 2020a) directly re- scales the attention weights based on the mapped relative distances instead of using sinusoidal po- sition embeddings. Similar to the web search ex- periments, we also compare SEED-Encoder with BERT (Ours). Results: The results of SEED-Encoder and base- lines in MIND are listed in Table 3. SEED- Encoder outperforms the recent state-of-the-art DA- Transformer, which employs various architecture improvements specifically designed for recommen- dation (Wu et al., 2020a). A better self-learning strategy to leverage unsupervised data can be as effective as, if not better than, task-specific archi- tecture changes while avoiding all the engineering hustles. # 4.5 Experiments on Open QA Our third application is dense retrieval in open- domain question answering. This task often lever- ages a two-stage framework: first uses a context retriever to select a small set of passages that may contain the answer to the question; and then uses a machine reader which thoroughly examines the retrieved passages and identifies the correct answer (Karpukhin et al., 2020). We focus on the first stage, i.e., dense retrieval to select relevant passages. We use Natural Question query set (Kwiatkowski et al., 2019) and the Wikipedia passages prepared and shared in DPR (Karpukhin et al., 2020). More de- tails of the NQ dataset are in Appendix A.1. We follow the evaluation metrics used in DPR, hit ac- curacy of Top-20 and Top-100. Models are fine-tuned using DPR fine-tuning strategy as in Karpukhin et al. (2020), which uses a dual-encoder architecture and samples negatives (a) MRR@10 (b) Recall@1k 0.332 0.330 0.328 _ 8 nm : 0.324 Ss 0.322; —— 31 < Biavers 032054 6 8 16 ALL Attention span 0.952 0.950 ~ 0.948 i) a §0.946 nn 2 o944 —— 3h 0.942) <5 layers 7 2 4 6 8 16 AL Attention span Figure 3: MS MARCO passage Dev accuracy of Siamese (BM25 Neg) when fine-tuned from SEED- Encoder variations. in the mini-batch. We also experiment with the ANCE fine-tuning strategy as in Xiong et al. (2021) which dynamically samples hard negatives. Baselines: We take BM25, BERT as baselines as in Karpukhin et al. (2020). Consistent with the web search tasks and news recommendation tasks, we also compare SEED-Encoder with BERT (ours). Results: The results of SEED-Encoder and the baselines on NQ benchmark are in Table 4. Again, SEED-Encoder outperforms all other baselines with DPR negative sampling or ANCE negative sampling. We do not change any architectures nor fine-tune strategies and only simply switch the BERT checkpoint to SEED-Encoder, but bring sig- nificant improvements on the large-scale bench- mark. # 4.6 Discussion and Analysis In this section, we conduct more analysis to un- derstand the advantages of the SEED-Encoder. For simplicity, all experiments are run on the MS MARCO document retrieval tasks. # 4.6.1 Ablation study In the experiments above, we use a three-layer Transformer decoder and restrict the attention span to be two. One may wonder whether such con- straints are essential for learning good sentence representations. In this section, we try various de- coder configurations with different numbers of lay- ers and attention window sizes. From the results in Figure 3, we can see that the SEED-Encoder with the stronger decoder, 5- layer Transformer with full attention (All), per- forms worse than those with weaker decoders in dense retrieval. The retrieval accuracy correlated well with the decoder capacity of the correspond- ing SEED-Encoder. So unlike typical multi-task settings where tasks share lower-level representa- (a) Full Attention. (b) Restricted Attention. 0.12 0.10 0.08 0.06 0.04 0.02 0.00; —3 layers 0.02) ~~5 layers 6 100 200 300 400 500 Positions 0.12 0.04 0.02 0.00, —3 layers 0.02) ~~5 layers 0 100 200 300 400 500 Positions Figure 4: The cosine similarity between encoder CLS and the token representations from the decoder at differ- ent positions: 0 is the beginning of the sequence and the closest to CLS. The restricted attention sets attention span to two. aw SEED-Encoder Ds Optimus BNWRUDUOWOS Cosine similarity eooooc900oH 64 128 256 512 Sequence length Figure 5: Cosine similarity of sequences with different lengths using Optimus and SEED-Encoder. tions and correlate in accuracy, in SEED-Encoder, the decoder is to force the encoder to capture more information in its sequence embeddings: A weak decoder leads to a stronger encoder. To further understand the relationship of en- coder’s CLS embedding and the decoder, in Fig- ure 4 we plot the cosine similarity between the decoder’s token representations in its last layer and the encoder’s CLS. The impact of restricting atten- tion is significant: with full attention (Figure 4(a)), the decoder may depend heavily on the encoder’s CLS in the beginning but quickly drops the depen- dency when sufficient context information is avail- able; with restricted access to context, the decoder is forced to attend more on the encoder’s CLS rep- resentation in all token positions, as shown in the consistent cosine similarity in different positions in Figure 4(b). This confirms that when the decoder is weak (restricted attention), it depends more on the encoder’s CLS, thus pushes the encoder to learn more informative representations. Also, the results in Figure 4(a) suggest that when using a powerful encoder, the CLS embedding will encode the first several words in the sentence but might ignore oth- ers. This can be one of the reasons that Optimus performs worse than BERT in dense retrieval in Figure 1(a). # 4.6.2 Document Representation Quality In Section 3.2, we empirically show that using a standard autoencoder learning framework, the sim- ilarity between sequence representations grows to be large for long sequences. In this section, we first study whether SEED-Encoder improves the representation diversity. Similar to Figure 1(b), we collect randomly sampled sentence pairs and cal- culate the cosine similarity of their CLS encodings generated by SEED-Encoder. Results in Figure 5 shows that, the CLS embed- ding generated by SEED-Encoder is more diverse. The average CLS cosine similarity is only 0.48 even when the sentence length is 512. This result shows that SEED-Encoder can well differentiate sentences during pre-training. Few-shot effectiveness Note that diverse rep- resentations don’t necessarily mean high-quality. To figure out the effectiveness of the representa- tion, we conduct few-shot learning experiments for SEED-Encoder. In particular, we record the dev performance during the fine-tuning stage and check how many training iterations and how many samples are required for the model to achieve a reasonably good performance. In Figure 6(a) and 6(b), we plot the retrieval ac- curacy at different fine-tuning steps. Starting from SEED-Encoder instead of BERT, both the vanilla Siamese and ANCE achieve higher retrieval ac- curacy in the very beginning and maintain their advantages throughout the fine-tuning process. For example, Siamese (BM25 Neg) only requires 30k fine-tuning iterations with SEED-Encoder to reach BERT’s best performance at 140k iterations. With ANCE (First P), it takes 150K iterations with SEED-Encoder versus 750K with BERT. In Figure 6(c) and 6(d), we plot the retrieval accuracy with different fractions of training data. Compared with BERT, with fewer training la- bels, SEED-Encoder always reaches better accu- racy. When only using 10% training labels, SEED- Encoder (MRR 0.318 in Figure 6(c)) is still com- petitive with BERT using all training labels (MRR 0.32). These results indicate that the representation learned by SEED-Encoder is better than that learned by BERT. The reduction in fine-tuning cost helps democratize the benefits of pre-training mod- els, especially in applications where computing resources or task-specific supervision is restricted. —BERT ——SEED-Encoder 1 2 3 Iterations le5 —BERT —~SEED-Encoder 4.0 Iterations 6.0 1e5 0.32 mmBeERT lBESEED-Encoder \ 5% Data proportion 10% © 0.32) MmBERT SEED-Encoder g — ee 4 = 0.30 ra g £0.29 © 0.28 1% 5% Data proportion 10% (a) Siamese (BM25 Neg). (b) ANCE (FirstP). (c) Siamese (BM25 Neg). (d) ANCE (FirstP). Figure 6: MS MARCO passage retrieval accuracy of Siamese (BM25 Neg) and ANCE (FirstP) when fine-tuned from BERT (Ours) and SEED-Encoder. (a) and (b) are their accuracy at different fine-tuning steps (x-axes, in 100K). (c) and (d) are their accuracy with a fraction (x-axes) of training labels in the few-shot setting. Case 1 Query SEED-Encoder MRR@100 1.0 hiking on mount rainier in the winter Case 2 what kind of party is the cooperative party MRR@100 1.0 Url Title Snippet RoBERTa Url Title Snippet https://www.nps.gov/mora/planyourvisit/winter-recreation.htm https://simple.wikipedia.org/wiki/Co-operative_Party Winter Recreation Winter Recreation Winter Camping Food Storage Snowplay... A Winter visit to Mount Rainier can include ranger-guided snowshoe walks, skiing...Learn about winter hiking opportu- nities at Longmire in... MRR@100 0.043 http://www.seattletimes.com/life/travel/5-great-day-hikes- around-mount-rainier/ 5 great day-hikes around Mount Rainier Life Outdoors Travel5 great day-hikes around Mount Rainier Originally published June 24, 2015 at 4:59...(Picasa)E-book authors name their favorite day-hikes in Mount Rainier Na- tional Park... Cooperative Party Co-operative Party From Wikipedia, the free encyclopedia navigation search. The Co-operative Party is a small socia- list political party, in the United Kingdom. Its candidates must be members of the Labour Party as well... MRR@100 0.067 http://socialeconomyaz.org/whats-a-cooperative/ What is a Cooperative? What is a Cooperative? According to the International Coo- perative Alliance ( ICA ), a cooperative is "an autonomous association of persons united voluntarily to meet their com- mon economic, social, and cultural needs... Table 5: Two examples of SEED-Encoder’s winning case over RoBERTa (Ours) when fine-tuning with ANCE FirstP in MARCO Document. Their first ranked documents are listed. Case Study We further showcase some winning examples of SEED-Encoder in Table 5. The error made by BERT correlated with our observation in Figure 4(a), where the encoder’s representation is more related to those tokens at the beginning of the text sequences, which is quite related to the query. Only when the model captures the information of the entire text can it find the correct documents. For example, in the first case, SEED-Encoder captures “winter hiking” at the back of the document while BERT only pays attention to some of the keywords at the beginning of the document even if the overall semantics does not match, and in the second case, BERT missed the "party" part in the query. # 5 Conclusion In this paper we present SEED-Encoder, a self- training framework dedicated to pre-training lan- guage models for dense text retrieval. We pre-train an auto-encoder that employs a weak decoder with restricted capacity and attention span following our mathematical derivation. The weak decoder helps SEED-Encoder capture more context information and generate better text representation. In our ex- periments on web search, news recommendation, and question answering, SEED-Encoder initialized dense retrieval models achieve state-of-the-art accu- racy compared to several strong baselines. Future work along this direction includes exploring more self-learning tasks and network architectures for sequence matching in dense retrieval scenarios. # Acknowledgements We would like to thank anonymous reviewers for their valuable comments. This work is partially supported by National Natural Science Foundation of China NO. 61872370, and Bei- jing Outstanding Young Scientist Program NO. BJJWZYJH012019100020098. # References Payal Bajaj, Daniel Campos, Nick Craswell, Li Deng, Jianfeng Gao, Xiaodong Liu, Rangan Majumder, Andrew McNamara, Bhaskar Mitra, Tri Nguyen, et al. 2016. Ms marco: A human generated ma- chine reading comprehension dataset. arXiv preprint arXiv:1611.09268. Kevin Clark, Minh-Thang Luong, Quoc V Le, and Christopher D Manning. 2019. Electra: Pre-training text encoders as discriminators rather than generators. In International Conference on Learning Representa- tions. Kevin Clark, Minh-Thang Luong, Quoc V Le, and Christopher D Manning. 2020. Electra: Pre-training text encoders as discriminators rather than generators. arXiv preprint arXiv:2003.10555. Nick Craswell, Bhaskar Mitra, Emine Yilmaz, Daniel Campos, and Ellen M Voorhees. 2020. Overview of the trec 2019 deep learning track. arXiv preprint arXiv:2003.07820. Zhuyun Dai and Jamie Callan. 2019. Context-aware sentence/passage term importance estimation for first stage retrieval. arXiv preprint arXiv:1910.10687. Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Car- bonell, Quoc V Le, and Ruslan Salakhutdinov. 2019. Transformer-xl: Attentive language mod- els beyond a fixed-length context. arXiv preprint arXiv:1901.02860. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. Bert: Pre-training of deep bidirectional transformers for language understand- ing. arXiv preprint arXiv:1810.04805. Ruiqi Guo, Philip Sun, Erik Lindgren, Quan Geng, David Simcha, Felix Chern, and Sanjiv Kumar. 2020. Accelerating large-scale inference with anisotropic vector quantization. In International Conference on Machine Learning, pages 3887–3896. PMLR. Jeff Johnson, Matthijs Douze, and Hervé Jégou. 2017. Billion-scale similarity search with gpus. arXiv preprint arXiv:1702.08734. Mandar Joshi, Danqi Chen, Yinhan Liu, Daniel S Weld, Luke Zettlemoyer, and Omer Levy. 2020. Spanbert: Improving pre-training by representing and predict- ing spans. Transactions of the Association for Com- putational Linguistics, 8:64–77. Vladimir Karpukhin, Barlas O˘guz, Sewon Min, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. 2020. Dense passage retrieval for open-domain ques- tion answering. arXiv preprint arXiv:2004.04906. Guolin Ke, Di He, and Tie-Yan Liu. 2020. Rethink- ing the positional encoding in language pre-training. arXiv preprint arXiv:2006.15595. Diederik P. Kingma and Jimmy Ba. 2014. Adam: CoRR, A method for stochastic optimization. abs/1412.6980. Diederik P Kingma and Max Welling. 2013. Auto- arXiv preprint encoding variational bayes. arXiv:1312.6114. Tom Kwiatkowski, Jennimaria Palomaki, Olivia Red- field, Michael Collins, Ankur Parikh, Chris Alberti, Danielle Epstein, Illia Polosukhin, Jacob Devlin, Ken- ton Lee, et al. 2019. Natural questions: a benchmark for question answering research. Transactions of the Association for Computational Linguistics, 7:453– 466. Kenton Lee, Ming-Wei Chang, and Kristina Toutanova. 2019. Latent retrieval for weakly supervised open do- main question answering. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, page 6086–6096. Chunyuan Li, Xiang Gao, Yuan Li, Xiujun Li, Baolin Peng, Yizhe Zhang, and Jianfeng Gao. 2020. Opti- mus: Organizing sentences via pre-trained modeling of a latent space. arXiv preprint arXiv:2004.04092. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man- dar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining ap- proach. arXiv preprint arXiv:1907.11692. Yi Luan, Jacob Eisenstein, Kristina Toutanova, and Michael Collins. 2021. Sparse, dense, and attentional representations for text retrieval. Transactions of the Association for Computational Linguistics, 9:329– –345. Paulius Micikevicius, Sharan Narang, Jonah Alben, Gre- gory Diamos, Erich Elsen, David Garcia, Boris Gins- burg, Michael Houston, Oleksii Kuchaiev, Ganesh Venkatesh, et al. 2017. Mixed precision training. arXiv preprint arXiv:1710.03740. Jimmy Lin, and Kyunghyun Cho. 2019. Document expansion by query prediction. arXiv preprint arXiv:1904.08375. Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, and Michael Auli. 2019. fairseq: A fast, extensible toolkit for se- quence modeling. arXiv preprint arXiv:1904.01038. Adam Paszke, Sam Gross, Soumith Chintala, Gregory Chanan, Edward Yang, Zachary DeVito, Zeming Lin, Alban Desmaison, Luca Antiga, and Adam Lerer. 2017. Automatic differentiation in pytorch. Nils Reimers and Iryna Gurevych. 2019a. Sentence- bert: Sentence embeddings using siamese bert- networks. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing. Association for Computational Linguistics. Nils Reimers and Iryna Gurevych. 2019b. Sentence- bert: Sentence embeddings using siamese bert- networks. arXiv preprint arXiv:1908.10084. Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Hao Tian, Hua Wu, and Haifeng Wang. 2020. Ernie 2.0: A continual pre-training framework for language under- standing. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 34, pages 8968–8975. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in neural information pro- cessing systems, pages 5998–6008. Pascal Vincent, Hugo Larochelle, Isabelle Lajoie, Yoshua Bengio, Pierre-Antoine Manzagol, and Léon Stacked denoising autoencoders: Bottou. 2010. Learning useful representations in a deep network with a local denoising criterion. Journal of machine learning research, 11(12). Alex Wang, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R Bowman. 2018. Glue: A multi-task benchmark and analysis platform for natural language understanding. arXiv preprint arXiv:1804.07461. Chuhan Wu, Fangzhao Wu, and Yongfeng Huang. 2020a. Da-transformer: Distance-aware transformer. arXiv preprint arXiv:2010.06925. Fangzhao Wu, Ying Qiao, Jiun-Hung Chen, Chuhan Wu, Tao Qi, Jianxun Lian, Danyang Liu, Xing Xie, Jianfeng Gao, Winnie Wu, et al. 2020b. Mind: A large-scale dataset for news recommendation. In Proceedings of the 58th Annual Meeting of the Asso- ciation for Computational Linguistics, pages 3597– 3606. Lee Xiong, Chenyan Xiong, Ye Li, Kwok-Fung Tang, Jialin Liu, Paul N. Bennett, Junaid Ahmed, and Arnold Overwikj. 2021. Approximate nearest neigh- bor negative contrastive learning for dense text re- In International Conference on Learning trieval. Representations. Hang Yan, Bocao Deng, Xiaonan Li, and Xipeng Qiu. 2019. Tener: Adapting transformer en- coder for named entity recognition. arXiv preprint arXiv:1911.04474. Chulhee Yun, Srinadh Bhojanapalli, Ankit Singh Rawat, Sashank J Reddi, and Sanjiv Kumar. 2019. Are transformers universal approximators of arXiv preprint sequence-to-sequence functions? arXiv:1912.10077. Yukun Zhu, Ryan Kiros, Richard Zemel, Ruslan Salakhutdinov, Raquel Urtasun, Antonio Torralba, and Sanja Fidler. 2015. Aligning books and movies: Towards story-like visual explanations by watch- In arXiv preprint ing movies and reading books. arXiv:1506.06724. Model Query relevant label Doc set Train 367,013 384,597 Document Dev 5,193 5,478 3,213,835 Eval 5,793 - Train 808,731 532,761 Passage Dev 101,093 59,273 8,841,823 Eval 101,092 - Table 6: Statistics of the MSMARCO dataset Users News Impression Avg. title len Avg. click num Avg. candidate num Avg. historical news click num Train 711,222 101,527 2,232,748 14.41 1.52 37.40 32.98 Dev 255,990 72,023 376,471 14.47 1.53 37.41 32.62 Table 7: Statistics of the MIND dataset # A Appendix # A.1 More Details of MS MARCO, MIND and OpenQA dataset More Details of MARCO Dataset Microsoft MARCO (Bajaj et al., 2016) is the largest available search benchmark to date. It includes two tasks, document ranking and passage ranking. Both are to find and rank relevant documents/passages from a web corpus for a web query from Bing. The dataset statistics are summarized in Table 6. More Details of MIND Dataset MIcrosoft News Dataset (MIND) (Wu et al., 2020b) is a large- scale recommendation dataset that collects about 160k English news articles and more than 15 mil- lion user impression logs from MSN news. Each news article contains the title, abstract, body, and category. Each impression log includes the user’s click behavior on the page and her historical news click behaviors. The task is to rank a given set of candidate news articles, e.g., those from an early stage of their recommendation pipeline, based on the user’s previous click history. The dataset statis- tics are summarized in Table 7. More Details of NQ Dataset For OpenQA ex- periments we use the Natural Question query set (Kwiatkowski et al., 2019), in which the queries are mined from real Google search queries and the corresponding answers are spans in Wikipedia articles identified by annotators. We use the Wikipedia passages preprocessed and shared in DPR (Karpukhin et al., 2020), which includes 21, 015, 324 passages. More detailed data such as the number of queries can be found in Karpukhin et al. (2020) model BERT (Ours) Optimus SEED-Encoder MNLI 0.849 0.834 0.843 QQP 0.910 0.909 0.911 SST-2 QNLI 0.913 0.929 0.912 0.923 0.914 0.927 Table 8: Results on some GLUE tasks. # A.2 GLUE We also consider the GLUE benchmark (Wang et al., 2018) which contains nine datasets for gen- eral language understanding. Here we select MNLI, QQP, QNLI and SST-2 from the GLUE benchmark, and compare the performance of SEED-Encoder with BERT (Ours) and Optimus on these tasks. We follow the fine-tuning schedule in Devlin et al. (2018), and the results are shown in Table 8. We can see that on these GLUE tasks, SEED-Encoder is not worse than BERT and Optimus. This shows that while SEED-Encoder can generate higher- quality representations that well fit the Siamese network, the performance on GLUE will not be- come worse.
Title: Learning to Speak Fluently in a Foreign Language: Multilingual Speech Synthesis and Cross-Language Voice Cloning: Summary: We present a multispeaker, multilingual text-to-speech (TTS) synthesis model based on Tacotron that is able to produce high quality speech in multiple languages. Moreover, the model is able to transfer voices across languages, e.g. synthesize fluent Spanish speech using an English speaker's voice, without training on any bilingual or parallel examples. Such transfer works across distantly related languages, e.g. English and Mandarin. Critical to achieving this result are: 1. using a phonemic input representation to encourage sharing of model capacity across languages, and 2. incorporating an adversarial loss term to encourage the model to disentangle its representation of speaker identity (which is perfectly correlated with language in the training data) from the speech content. Further scaling up the model by training on multiple speakers of each language, and incorporating an autoencoding input to help stabilize attention during training, results in a model which can be used to consistently synthesize intelligible speech for training speakers in all languages seen during training, and in native or foreign accents. # Learning to Speak Fluently in a Foreign Language: Multilingual Speech Synthesis and Cross-Language Voice Cloning Yu Zhang, Ron J. Weiss, Heiga Zen, Yonghui Wu, Zhifeng Chen, RJ Skerry-Ryan, Ye Jia, Andrew Rosenberg, Bhuvana Ramabhadran # Google {ngyuzh, ronw}@google.com Abstract We present a multispeaker, multilingual text-to-speech (TTS) synthesis model based on Tacotron that is able to produce high quality speech in multiple languages. Moreover, the model is able to transfer voices across languages, e.g. synthesize fluent Spanish speech using an English speaker’s voice, without train- ing on any bilingual or parallel examples. Such transfer works across distantly related languages, e.g. English and Mandarin. Inference Network Adversarial Loss Mel Residual |_ [Residual ‘spectrogram | Encoder Encoding Gradient |_.[ Speaker Reversal Classifier Text Text > Mel sequence Encoder [> (Bowed ‘spectrogram a Text ‘Speaker | [ Language Synthosizor Encoding | Embedding | | Embedding Critical to achieving this result are: 1. using a phonemic in- put representation to encourage sharing of model capacity across languages, and 2. incorporating an adversarial loss term to en- courage the model to disentangle its representation of speaker identity (which is perfectly correlated with language in the train- ing data) from the speech content. Further scaling up the model by training on multiple speakers of each language, and incorpo- rating an autoencoding input to help stabilize attention during training, results in a model which can be used to consistently synthesize intelligible speech for training speakers in all lan- guages seen during training, and in native or foreign accents. Index Terms: speech synthesis, end-to-end, adversarial loss Figure 1: Overview of the components of the proposed model. Dashed lines denote sampling via reparameterization [21] dur- ing training. The prior mean is always use during inference. in both languages using the same voice. [16] studied learning pronunciation from a bilingual TTS model. Most recently, [17] presented a multilingual neural TTS model which supports voice cloning across English, Spanish, and German. It used language- specific text and speaker encoders, and incorporated a secondary fine-tuning step to optimize a speaker identity-preserving loss, ensuring that the model could output a consistent voice regard- less of language. We also note that the sound quality is not on par with recent neural TTS systems, potentially because of its use of the WORLD vocoder [18] for waveform synthesis. # 1. Introduction Recent end-to-end neural TTS models [1–3] have been extended to enable control of speaker identity [4–7] as well as unlabelled speech attributes, e.g. prosody, by conditioning synthesis on la- tent representations [8–12] in addition to text. Extending such models to support multiple, unrelated languages is nontrivial when using language-dependent input representations or model components, especially when the amount of training data per lan- guage is imbalanced. For example, there is no overlap in the text representation between languages like Mandarin and English. Furthermore, recordings from bilingual speakers are expensive to collect. It is therefore most common for each speaker in the training set to speak only one language, so speaker identity is perfectly correlated with language. This makes it difficult to transfer voices across different languages, a desirable feature when the number of available training voices for a particular language is small. Moreover, for languages with borrowed or shared words, such as proper nouns in Spanish (ES) and English (EN), pronunciations of the same text might be different. This adds more ambiguity when a naively trained model sometimes generates accented speech for a particular speaker. Our work is most similar to [19], which describes a mul- tilingual TTS model based on Tacotron 2 [20] which uses a Unicode encoding “byte” input representation to train a model on one speaker of each of English, Spanish, and Mandarin. In this paper, we evaluate different input representations, scale up the number of training speakers for each language, and extend the model to support cross-lingual voice cloning. The model is trained in a single stage, with no language-specific compo- nents, and obtains naturalness on par with baseline monolingual models. Our contributions include: (1) Evaluating the effect of using different text input representations in a multilingual TTS model. (2) Introducing a per-input token speaker-adversarial loss to enable cross-lingual voice transfer when only one train- ing speaker is available for each language. (3) Incorporating an explicit language embedding to the input, which enables mod- erate control of speech accent, independent of speaker identity, when the training data contains multiple speakers per language. We evaluate the contribution of each component, and demonstrate the proposed model’s ability to disentangle speak- ers from languages and consistently synthesize high quality speech for all speakers, despite the perfect correlation to the original language in the training data. Zen et al. proposed a speaker and language factorization for HMM-based parametric TTS system [13], aiming to transfer a voice from one language to others. [14] proposed a multilingual parametric neural TTS system, which used a unified input repre- sentation and shared parameters across languages, however the voices used for each language were disjoint. [15] described a sim- ilar bilingual Chinese and English neural TTS system trained on speech from a bilingual speaker, allowing it to synthesize speech # 2. Model Structure We base our multilingual TTS model on Tacotron 2 [20], which uses an attention-based sequence-to-sequence model to gener- ate a sequence of log-mel spectrogram frames based on an input It text sequence. The architecture is illustrated in Figure 1. augments the base Tacotron 2 model with additional speaker and, optionally, language embedding inputs (bottom right), an adversarially-trained speaker classifier (top right), and a varia- tional autoencoder-style residual encoder (top left) which con- ditions the decoder on a latent embedding computed from the target spectrogram during training (top left). Finally, similar to Tacotron 2, we separately train a WaveRNN [22] neural vocoder. # 2.1. Input representations End-to-end TTS models have typically used character [2] or phoneme [8, 23] input representations, or hybrids between them [24, 25]. Recently, [19] proposed using inputs derived from the UTF-8 byte encoding in multilingual settings. We evaluate the effects of using these representations for multilingual TTS. # 2.1.1. Characters / Graphemes Embeddings corresponding to each character or grapheme are the default inputs for end-to-end TTS models [2, 20, 23], requir- ing the model to implicitly learn how to pronounce input words (i.e. grapheme-to-phoneme conversion [26]) as part of the syn- thesis task. Extending a grapheme-based input vocabulary to a multilingual setting is straightforward, by simply concatenating grapheme sets in the training corpus for each language. This can grow quickly for languages with large alphabets, e.g. our Man- darin vocabulary contains over 4.5k tokens. We simply concate- nate all graphemes appearing in the training corpus, leading to a total of 4,619 tokens. Equivalent graphemes are shared across languages. During inference all previously unseen characters are mapped to a special out-of-vocabulary (OOV) symbol. # 2.1.2. UTF-8 Encoded Bytes Following [19] we experiment with an input representation based on the UTF-8 text encoding, which uses 256 possible values as each input token where the mapping from graphemes to bytes is language-dependent. For languages with single-byte characters (e.g., English), this representation is equivalent to the grapheme representation. However, for languages with multi-byte char- acters (such as Mandarin) the TTS model must learn to attend to a consistent sequence of bytes to correctly generate the cor- responding speech. On the other hand, using a UTF-8 byte representation may promote sharing of representations between languages due to the smaller number of input tokens. # 2.1.3. Phonemes Using phoneme inputs simplifies the TTS task, as the model no longer needs to learn complicated pronunciation rules for lan- guages such as English. Similar to our grapheme-based model, equivalent phonemes are shared across languages. We concate- nate all possible phoneme symbols, for a total of 88 tokens. To support Mandarin, we include tone information by learn- ing phoneme-independent embeddings for each of the 4 possible tones, and broadcast each tone embedding to all phoneme em- beddings inside the corresponding syllable. For English and Spanish, tone embeddings are replaced by stress embeddings which include primary and secondary stresses. A special sym- bol is used when there is no tone or stress. # 2.2. Residual encoder Following [12], we augment the TTS model by incorporating a variational autoencoder-like residual encoder which encodes the latent factors in the training audio, e.g. prosody or background noise, which is not well-explained by the conditioning inputs: the text representation, speaker, and language embeddings. We follow the structure from [12], except we use a standard single Gaussian prior distribution and reduce the latent dimension to 16. In our experiments, we observe that feeding in the prior mean (all zeros) during inference, significantly improves stability of cross-lingual speaker transfer and leads to improved naturalness as shown by MOS evaluations in Section 3.4. # 2.3. Adversarial training One of the challenges for multilingual TTS is data sparsity, where some languages may only have training data for a few speakers. In the extreme case where there is only one speaker per language in the training data, the speaker identity is essentially the same as the language ID. To encourage the model to learn disentangled representations of the text and speaker identity, we proactively discourage the text encoding ts from also capturing speaker information. We employ domain adversarial training encourage t; to encode text in a speaker-independent manner by introducing a speaker classifier based on the text encoding and a gradient reversal layer. Note that the speaker classifier is optimized with a different objective than the rest of the model: Lspeaker(Ws; ti) = xN log p(s; | t;), where s; is the speaker label and ws are the parameters for speaker classifier. To train the full model, we insert a gradient reversal layer prior to this speaker classifier, which scales the gradient by —A. Following so explore inserting another adversarial layer on top of the variational autoencoder to encourage it to learn speaker- independent representations. However, we found that this layer has no effect after decreasing the latent space dimension. We impose this adversarial loss separately on each element of the encoded text sequence, in order to encourage the model to learn a speaker- and language-independent text embedding space. In contrast to [28], which disentangled speaker identity from background noise, some input tokens are highly language- dependent which can lead to unstable adversarial classifier gra- dients. We address this by clipping gradients computed at the reversal layer to limit the impact of such outliers. # 3. Experiments We train models using a proprietary dataset composed of high quality speech in three languages: (1) 385 hours of English (EN) from 84 professional voice actors with accents from the United States, Great Britain, Australia, and Singapore; (2) 97 hours of Spanish (ES) from 3 female speakers include Castilian and US Spanish; (3) 68 hours of Mandarin (CN) from 5 speakers. # 3.1. Model and training setup The synthesizer network uses the Tacotron 2 architecture [20], with additional inputs consisting of learned speaker (64-dim) and language embeddings (3-dim), concatenated and passed to the decoder at each step. The generated speech is represented as a sequence of 128-dim log-mel spectrogram frames, computed from 50ms windows shifted by 12.5ms. The variational residual encoder architecture closely fol- lows the attribute encoder in [12]. It maps a variable length mel spectrogram to two vectors parameterizing the mean and log variance of the Gaussian posterior. The speaker classifiers are fully-connected networks with one 256 unit hidden layer followed by a softmax predicting the speaker identity. The syn- thesizer and speaker classifier are trained with weight 1.0 and 0.02 respectively. As described in the previous section we apply Table 1: Speaker similarity Mean Opinion Score (MOS) com- paring ground truth audio from speakers of different languages. Raters are native speakers of the target language. Source Language EN Target Language ES CN EN ES CN 4.40±0.07 1.49±0.06 1.32±0.06 1.72±0.15 4.39±0.06 2.06±0.09 1.80±0.08 2.14±0.09 3.51±0.12 gradient clipping with factor 0.5 to the gradient reversal layer. The entire model is trained jointly with a batch size of 256, using the Adam optimizer configured with an initial learning rate of 10−3, and an exponential decay that halves the learning rate every 12.5k steps, starting at 50k steps. Waveforms are synthesized using a WaveRNN [22] vocoder which generates 16-bit signals sampled at 24 kHz conditioned on spectrograms predicted by the TTS model. We synthesize 100 samples per model, and have each one rated by 6 raters. # 3.2. Evaluation To evaluate synthesized speech, we rely on crowdsourced Mean Opinion Score (MOS) evaluations of speech naturalness via subjective listening tests. Ratings follow the Absolute Category Rating scale, with scores from 1 to 5 in 0.5 point increments. For cross-language voice cloning, we also evaluate whether the synthesized speech resembles the identity of the reference speaker by pairing each synthesized utterance with a reference utterance from the same speaker for subjective MOS evaluation of speaker similarity, as in [5]. Although rater instructions explicitly asked for the content to be ignored, note that this similarity evaluation is more challenging than the one in [5] because the reference and target examples are spoken in different languages, and raters are not bilingual. We found that low fidelity audio tended to result in high variance similarity MOS so we always use WaveRNN outputs.1 For each language, we chose one speaker to use for similarity tests. As shown in Table 1, the EN speaker is found to be dissimilar to the ES and CN speakers (MOS below 2.0), while the ES and CN speakers are slightly similar (MOS around 2.0). The CN speaker has more natural variability compared to EN and ES, leading to a lower self similarity. The scores are consistent when EN and CN raters evaluate the same EN and CN test set. The observation is consistent with [29]: raters are able to discriminate between speakers across languages. However, when rating synthetic speech, we observed that English speaking raters often considered “heavy accented” synthetic CN speech to sound more similar to the target EN speaker, compared to more fluent speech from the same speaker. This indicates that accent and speaker identity are not fully disentangled. We encourage readers to listen to samples on the companion webpage.2 # 3.3. Comparing input representations We first build and evaluate models comparing the performance of different text input representations. For all three languages, byte-based models always use a 256-dim softmax output. Mono- lingual character and phoneme models each use a different input 1Some raters gave low fidelity audio lower scores, treating "blurri- ness" as a property of the speaker. Others gave higher scores because they recognized such audio as synthetic and had lower expectations. # 2http://google.github.io/tacotron/publications/multilingual Table 2: Naturalness MOS of monolingual and multilingual models synthesizing speech of in different languages. Language Model Input EN ES CN Ground truth 4.60±0.05 4.37±0.06 4.42±0.06 Monolingual 4.24±0.12 4.21±0.11 3.48±0.11 char phone 4.59±0.06 4.39±0.04 4.16±0.08 4.23±0.14 4.23±0.10 3.42±0.12 3.94±0.15 4.33±0.09 3.63±0.10 phone 4.34±0.09 4.41±0.05 4.06±0.10 byte Multilingual 1EN 1ES 1CN char 4.11±0.14 4.21±0.12 3.67±0.12 4.26±0.13 4.23±0.11 3.46±0.11 phone 4.37±0.12 4.37±0.04 4.09±0.10 Multilingual byte 84EN 3ES 5CN char Table 3: Naturalness and speaker similarity MOS of cross- language voice cloning of an EN source speaker. Models which use different input representations are compared, with and with- out the speaker-adversarial loss. fail: raters complained that too many utterances were spoken in the wrong language. ES target CN target Input Naturalness Similarity Naturalness Similarity char byte 2.62±0.10 2.62±0.15 4.25±0.09 3.96±0.10 N/A N/A N/A N/A with adversarial loss 2.34±0.10 byte 3.20±0.09 phone 4.23±0.09 4.15±0.10 fail 2.75±0.12 3.85±0.11 3.60±0.09 vocabulary corresponding to the training language. Table 2 compares monolingual and multilingual model per- formance using different input representations. For Mandarin, the phoneme-based model performs significantly better than char- or byte-based variants due to rare and OOV words. Com- pared to the monolingual system, multilingual phoneme-based systems have similar performance on ES and CN but are slightly worse on EN. CN has a larger gap to ground truth (top) due to unseen word segmentation (for simplicity, we didn’t add word boundary during training). The multispeaker model (bottom) performs about the same as the single speaker per-language variant (middle). Overall, when using phoneme inputs all the languages obtain MOS scores above 4.0. # 3.4. Cross-language voice cloning We evaluate how well the multispeaker models can be used to clone a speaker’s voice into a new language by simply passing in speaker embeddings corresponding to a different language from the input text. Table 3 shows voice cloning performance from an EN speaker in the most data-poor scenario (129 hours), where only a single speaker is available for each training language (1EN 1ES 1CN) without using the speaker-adversarial loss. Us- ing byte inputs 3 it was possible to clone the EN speaker to ES with high similarity MOS, albeit with significantly reduced naturalness. However, cloning the EN voice to CN failed4, as did cloning to ES and CN using phoneme inputs. 3Using character or byte inputs led to similar results. 4We didn’t run listening tests because it was clear that synthesizing EN text using the CN speaker embedding didn’t affect the model output. Table 4: Naturalness and speaker similarity MOS of cross-language voice cloning of the full multilingual model using phoneme inputs. Source Language Model EN target ES target CN target Naturalness Similarity Naturalness Similarity Naturalness Similarity - Ground truth (self-similarity) 4.60±0.05 4.40±0.07 4.37±0.06 4.39±0.06 4.42±0.06 3.51±0.12 EN 84EN 3ES 5CN language ID fixed to EN 4.37±0.12 - 4.63±0.06 - 4.20±0.07 3.68±0.07 3.50±0.12 4.06±0.09 3.94±0.09 3.09±0.09 3.03±0.10 3.20±0.09 ES 84EN 3ES 5CN 4.28±0.10 3.24±0.09 4.37±0.04 4.01±0.07 3.85±0.09 2.93±0.12 CN 84EN 3ES 5CN 4.49±0.08 2.46±0.10 4.56±0.08 2.48±0.09 4.09±0.10 3.45±0.12 Adding the adversarial speaker classifier enabled cross- language cloning of the EN speaker to CN with very high simi- larity MOS for both byte and phoneme models. However, natu- ralness MOS remains much lower than using the native speaker identity, with the naturalness listening test failing entirely in the CN case with byte inputs as a result of rater comments that the speech sounded like a foreign language. According to rater comments on the phoneme system, most of the degradation came from mismatched accent and pronunciation, not fidelity. CN raters commented that it sounded like “a foreigner speaking Chinese”. More interestingly, few ES raters commented that “The voice does not sound robotic but instead sounds like an English native speaker who is learning to pronounce the words in Spanish.” Based on these results, we only use phoneme inputs in the following experiments since this guarantees that pronun- ciations are correct and results in more fluent speech. Table 4 evaluates voice cloning performance of the full mul- tilingual model (84EN 3ES 5CN), which is trained on the full dataset with increased speaker coverage, and uses the speaker- adversarial loss and speaker/language embeddings. Incorporat- ing the adversarial loss forces the text representation to be less language-specific, instead relying on the language embedding to capture language-dependent information. Across all language pairs, the model synthesizes speech in all voices with natural- ness MOS above 3.85, demonstrating that increasing training speaker diversity improves generalization. In most cases syn- thesizing EN and ES speech (except EN-to-ES) approaches the ground truth scores. In contrast, naturalness of CN speech is consistently lower than the ground truth. Table 5: Effect of EN speaker cloning with no residual encoder. Target Language Model EN ES CN 84EN 3ES 5CN - residual encoder 4.37±0.12 4.20±0.07 3.94±0.09 4.38±0.10 4.11±0.06 3.52±0.11 08 eee Native - Fluent 4¢@ Native - Accented 444 Cloned - Accented mmm Cloned - Fluent Speaker /Text / Lang e CN/CN/CN @ CN/CN/EN 4 CN/EN/CN CN/EN/EN EN/CN/CN a EN/CN/EN @ EN/EN/CN EN/EN/EN -0.4 08 06 04 -0.2 0.0 0.2 0.4 0.6 08 Figure 2: Visualizing the effect of voice cloning and accent con- trol, using 2D PCA of speaker embeddings [30] computed from speech synthesized with different speaker, text, and language ID combinations. Embeddings cluster together (bottom left and right), implying high similarity, when the speaker’s original lan- guage matches the language embedding, regardless of the text language. However, using language ID from the text (squares), modifying the speaker’s accent to speak fluently, hurts similarity compared to the native language and accent (circles). The high naturalness and similarity MOS scores in the top row of Table 4 indicate that the model is able to successfully transfer the EN voice to both ES and CN almost without accent. When consistently conditioning on the EN language embedding regardless of the target language (second row), the model pro- duces more English accented ES and CN speech, which leads to lower naturalness but higher similarity MOS scores. Also see Figure 2 and the demo for accent transfer audio examples. We see that cloning the CN voice to other languages (bottom row) has the lowest similarity MOS, although the scores are still much higher than different-speaker similarity MOS in the off- diagonals of Table 1 indicating that there is some degree of transfer. This is a consequence of the low speaker coverage of CN compared to EN in the training data, as well as the large distance between CN and other languages. unnatural pauses in the output speech. This indicates the VAE prior learns a mode which helps stabilize attention. # 4. Conclusions We describe extensions to the Tacotron 2 neural TTS model which allow training of a multilingual model trained only on monolingual speakers, which is able to synthesize high quality speech in three languages, and transfer training voices across languages. Furthermore, the model learns to speak foreign lan- guages with moderate control of accent, and, as demonstrated on the companion webpage, has rudimentary support for code switching. In future work we plan to investigate methods for scaling up to leverage large amounts of low quality training data, and support many more speakers and languages. Finally, Table 5 demonstrates the importance of training us- ing a variational residual encoder to stabilize the model output. Naturalness MOS decreases by 0.4 points for EN-to-CN cloning without the residual encoder (bottom row). In informal compar- isons of the outputs of the two models we find that the model without the residual encoder tends to skip rare words or inserts # 5. Acknowledgements We thank Ami Patel, Amanda Ritchart-Scott, Ryan Li, Siamak Tazari, Yutian Chen, Paul McCartney, Eric Battenberg, Toby Hawker, and Rob Clark for discussions and helpful feedback. 6. References [1] A. van den Oord, S. Dieleman, H. Zen, K. Simonyan, O. Vinyals, A. Graves, N. Kalchbrenner, A. Senior, and K. Kavukcuoglu, “WaveNet: A generative model for raw audio,” CoRR abs/1609.03499, 2016. [2] Y. Wang, R. Skerry-Ryan, D. Stanton, Y. Wu, R. J. Weiss, N. Jaitly, Z. Yang, Y. Xiao, Z. Chen, S. Bengio et al., “Tacotron: A fully end-to-end text-to-speech synthesis model,” arXiv preprint, 2017. [3] S. Arik, G. Diamos, A. Gibiansky, J. Miller, K. Peng, W. Ping, J. Raiman, and Y. Zhou, “Deep Voice 2: Multi-speaker neural text- to-speech,” in Advances in Neural Information Processing Systems (NIPS), 2017. [4] S. O. Arik, J. Chen, K. Peng, W. Ping, and Y. Zhou, “Neural voice cloning with a few samples,” in Advances in Neural Information Processing Systems, 2018. [5] Y. Jia, Y. Zhang, R. J. Weiss, Q. Wang, J. Shen, F. Ren, Z. Chen, P. Nguyen, R. Pang, I. L. Moreno, and Y. Wu, “Transfer learn- ing from speaker verification to multispeaker text-to-speech syn- thesis,” in Advances in Neural Information Processing Systems, 2018. [6] E. Nachmani, A. Polyak, Y. Taigman, and L. Wolf, “Fitting new speakers based on a short untranscribed sample,” in International Conference on Machine Learning (ICML), 2018. [7] Y. Chen, Y. Assael, B. Shillingford, D. Budden, S. Reed, H. Zen, Q. Wang, L. C. Cobo, A. Trask, B. Laurie et al., “Sample efficient adaptive text-to-speech,” arXiv preprint arXiv:1809.10460, 2018. [8] Y. Wang, D. Stanton, Y. Zhang, R. Skerry-Ryan, E. Battenberg, J. Shor, Y. Xiao, F. Ren, Y. Jia, and R. A. Saurous, “Style tokens: Unsupervised style modeling, control and transfer in end-to-end speech synthesis,” in International Conference on Machine Learn- ing (ICML), 2018. [9] R. Skerry-Ryan, E. Battenberg, Y. Xiao, Y. Wang, D. Stanton, J. Shor, R. J. Weiss, R. Clark, and R. A. Saurous, “Towards end- to-end prosody transfer for expressive speech synthesis with Taco- tron,” in International Conference on Machine Learning (ICML), 2018. [10] K. Akuzawa, Y. Iwasawa, and Y. Matsuo, “Expressive speech synthesis via modeling expressions with variational autoencoder,” in Interspeech, 2018. [11] G. E. Henter, J. Lorenzo-Trueba, X. Wang, and J. Yamagishi, “Deep encoder-decoder models for unsupervised learning of con- trollable speech synthesis,” arXiv preprint arXiv:1807.11470, 2018. [12] W.-N. Hsu, Y. Zhang, R. J. Weiss, H. Zen, Y. Wu, Y. Wang, Y. Cao, Y. Jia, Z. Chen, J. Shen, P. Nguyen, and R. Pang, “Hierarchical generative modeling for controllable speech synthesis,” in ICLR, 2019. [13] H. Zen, N. Braunschweiler, S. Buchholz, M. Gales, K. Knill, S. Krstulović, and J. Latorre, “Statistical parametric speech syn- thesis based on speaker and language factorization,” IEEE Trans. Audio, Speech, Lang. Process., vol. 20, no. 6, pp. 1713–1724, 2012. [14] B. Li and H. Zen, “Multi-language multi-speaker acoustic model- ing for LSTM-RNN based statistical parametric speech synthesis,” in Proc. Interspeech, 2016, pp. 2468–2472. [15] H. Ming, Y. Lu, Z. Zhang, and M. Dong, “A light-weight method of building an LSTM-RNN-based bilingual TTS system,” in In- ternational Conference on Asian Language Processing, 2017, pp. 201–205. [16] Y. Lee and T. Kim, “Learning pronunciation from a for- eign language in speech synthesis networks,” arXiv preprint arXiv:1811.09364, 2018. [17] E. Nachmani and L. Wolf, “Unsupervised polyglot text to speech,” in ICASSP, 2019. [18] M. Morise, F. Yokomori, and K. Ozawa, “WORLD: a vocoder- based high-quality speech synthesis system for real-time applica- tions,” IEICE Transactions on Information and Systems, vol. 99, no. 7, pp. 1877–1884, 2016. [19] B. Li, Y. Zhang, T. Sainath, Y. Wu, and W. Chan, “Bytes are all you need: End-to-end multilingual speech recognition and synthesis with bytes,” in ICASSP, 2018. [20] J. Shen, R. Pang, R. J. Weiss, M. Schuster, N. Jaitly, Z. Yang, Z. Chen, Y. Zhang, Y. Wang, R. Skerry-Ryan et al., “Natural TTS synthesis by conditioning WaveNet on mel spectrogram predic- tions,” in ICASSP, 2018. [21] D. P. Kingma and M. Welling, “Auto-encoding variational Bayes,” in International Conference on Learning Representations (ICLR), 2014. [22] N. Kalchbrenner, E. Elsen, K. Simonyan, S. Noury, N. Casagrande, E. Lockhart, F. Stimberg, A. van den Oord, S. Dieleman, and K. Kavukcuoglu, “Efficient neural audio synthesis,” in ICML, 2018. [23] J. Sotelo, S. Mehri, K. Kumar, J. F. Santos, K. Kastner, A. Courville, and Y. Bengio, “Char2wav: End-to-end speech syn- thesis,” in ICLR: Workshop, 2017. [24] W. Ping, K. Peng, A. Gibiansky, S. O. Arik, A. Kannan, S. Narang, J. Raiman, and J. Miller, “Deep Voice 3: Scaling text-to-speech with convolutional sequence learning,” in International Confer- ence on Learning Representations (ICLR), 2018. [25] K. Kastner, J. F. Santos, Y. Bengio, and A. C. Courville, “Repre- sentation mixing for TTS synthesis,” arXiv:1811.07240, 2018. [26] A. Van Den Bosch and W. Daelemans, “Data-oriented methods for grapheme-to-phoneme conversion,” in Proc. Association for Computational Linguistics, 1993, pp. 45–53. [27] Y. Ganin, E. Ustinova, H. Ajakan, P. Germain, H. Larochelle, F. Laviolette, M. Marchand, and V. Lempitsky, “Domain- adversarial training of neural networks,” The Journal of Machine Learning Research, vol. 17, no. 1, pp. 2096–2030, 2016. [28] W.-N. Hsu, Y. Zhang, R. J. Weiss, Y. an Chung, Y. Wang, Y. Wu, and J. Glass, “Disentangling correlated speaker and noise for speech synthesis via data augmentation and adversarial factor- ization,” in ICASSP, 2019. [29] M. Wester and H. Liang, “Cross-lingual speaker discrimination using natural and synthetic speech,” in Twelfth Annual Conference of the International Speech Communication Association, 2011. [30] L. Wan, Q. Wang, A. Papir, and I. L. Moreno, “Generalized end- to-end loss for speaker verification,” in Proc. ICASSP, 2018.
Title: SAMSum Corpus: A Human-annotated Dialogue Dataset for Abstractive Summarization: Summary: This paper introduces the SAMSum Corpus, a new dataset with abstractive dialogue summaries. We investigate the challenges it poses for automated summarization by testing several models and comparing their results with those obtained on a corpus of news articles. We show that model-generated summaries of dialogues achieve higher ROUGE scores than the model-generated summaries of news -- in contrast with human evaluators' judgement. This suggests that a challenging task of abstractive dialogue summarization requires dedicated models and non-standard quality measures. To our knowledge, our study is the first attempt to introduce a high-quality chat-dialogues corpus, manually annotated with abstractive summarizations, which can be used by the research community for further studies. # SAMSum Corpus: A Human-annotated Dialogue Dataset for Abstractive Summarization # Bogdan Gliwa, Iwona Mochol, Maciej Biesek, Aleksander Wawer # Samsung R&D Institute Poland {b.gliwa, i.mochol, m.biesek, a.wawer}@samsung.com ( # Abstract This paper introduces the SAMSum Corpus, a new dataset with abstractive dialogue sum- maries. We investigate the challenges it poses for automated summarization by testing sev- eral models and comparing their results with those obtained on a corpus of news articles. We show that model-generated summaries of dialogues achieve higher ROUGE scores than the model-generated summaries of news – in contrast with human evaluators’ judgement. This suggests that a challenging task of ab- stractive dialogue summarization requires ded- icated models and non-standard quality mea- sures. To our knowledge, our study is the first attempt to introduce a high-quality chat- dialogues corpus, manually annotated with ab- stractive summarizations, which can be used by the research community for further studies. # 1 Introduction and related work The goal of the summarization task is condensing a piece of text into a shorter version that covers the main points succinctly. In the abstractive approach important pieces of information are presented using words and phrases not necessarily appearing in the source text. This requires natural language generation techniques with high level of semantic understanding (Chopra et al., 2016; Rush et al., 2015; Khandelwal et al., 2019; Zhang et al., 2019; See et al., 2017; Chen and Bansal, 2018; Gehrmann et al., 2018). Major research efforts have focused so far on summarization of single-speaker documents like news (e.g., Nallapati et al. (2016)) or sci- entific publications (e.g., Nikolov et al. (2018)). One of the reasons is the availability of large, high-quality news datasets with annotated sum- maries, e.g., CNN/Daily Mail (Hermann et al., 2015; Nallapati et al., 2016). Such a comprehen- sive dataset for dialogues is lacking. The challenges posed by the abstractive dia- logue summarization task have been discussed in the literature with regard to AMI meeting cor- pus (McCowan et al., 2005), e.g. Banerjee et al. (2014), Goo and Chen (2015), Mehdad et al. (2018). Since the corpus has a low number of sum- maries (for 141 dialogues), Goo and Chen (2018) proposed to use assigned topic descriptions as gold references. These are short, label-like goals of the meeting, e.g., costing evaluation of project pro- cess; components, materials and energy sources; chitchat. Such descriptions, however, are very general, lacking the messenger-like structure and any information about the speakers. benefit corpora, news (2019) built a dialogue Ganesh and Dingliwal summarization model that first converts a conver- sation into a structured text document and later applies an attention-based pointer network to cre- ate an abstractive summary. Their model, trained on structured text documents of CNN/Daily Mail dataset, was evaluated on the Argumentative Dialogue Summary Corpus (Misra et al., 2015), which, however, contains only 45 dialogues. In the present paper, we further investigate the problem of abstractive dialogue summarization. With the growing popularity of online conver- sations via applications like Messenger, What- sApp and WeChat, summarization of chats be- tween a few participants is a new interesting direc- tion of summarization research. For this purpose we have created the SAMSum Corpus1 which contains over 16k chat dialogues with manually annotated summaries. The dataset is freely avail- able for the research community2. 1The name is a shortcut 1The name is a shortcut for Samsung Abstractive Messenger Summarization # 2The dataset is shared on terms of the Attribution- NonCommercial-NoDerivatives 4.0 International (CC BY- NC-ND 4.0) license. It accompanies this paper on arXiv. Dataset Train CNN/DM 287 227 SAMSum 14 732 Validation 13 368 818 Test 11 490 819 Table 1: Datasets sizes The paper is structured as follows: in Section 2 we present details about the new corpus and de- scribe how it was created, validated and cleaned. Brief description of baselines used in the summa- rization task can be found in Section 3. In Sec- tion 4, we describe our experimental setup and pa- rameters of models. Both evaluations of summa- rization models, the automatic with ROUGE met- ric and the linguistic one, are reported in Section 5 and Section 6, respectively. Examples of models’ outputs and some errors they make are described in Section 7. Finally, discussion, conclusions and ideas for further research are presented in sections 8 and 9. # 2 SAMSum Corpus Initial approach. Since there was no available corpus of messenger conversations, we consid- ered two approaches to build it: (1) using existing datasets of documents, which have a form similar to chat conversations, (2) creating such a dataset by linguists. In the first approach, we reviewed datasets from the following categories: chatbot dialogues, SMS corpora, IRC/chat data, movie dialogues, tweets, comments data (conversations formed by replies to comments), transcription of meetings, written discussions, phone dialogues and daily commu- nication data. Unfortunately, they all differed in some respect from the conversations that are typ- ically written in messenger apps, e.g. they were too technical (IRC data), too long (comments data, transcription of meetings), lacked context (movie dialogues) or they were more of a spoken type, such as a dialogue between a petrol station assis- tant and a client buying petrol. As a consequence, we decided to create a chat dialogue dataset by constructing such conversa- tions that would epitomize the style of a messenger app. Process of building the dataset. Our di- alogue summarization dataset contains natural messenger-like conversations created and written down by linguists fluent in English. The style and register of conversations are diversified – di- alogues could be informal, semi-formal or formal, they may contain slang phrases, emoticons and ty- pos. We asked linguists to create conversations similar to those they write on a daily basis, re- flecting the proportion of topics of their real-life messenger conversations. It includes chit-chats, gossiping about friends, arranging meetings, dis- cussing politics, consulting university assignments with colleagues, etc. Therefore, this dataset does not contain any sensitive data or fragments of other corpora. Each dialogue was created by one person. After collecting all of the conversations, we asked lan- guage experts to annotate them with summaries, assuming that they should (1) be rather short, (2) extract important pieces of information, (3) in- clude names of interlocutors, (4) be written in the third person. Each dialogue contains only one ref- erence summary. Validation. Since the SAMSum corpus con- tains dialogues created by linguists, the question arises whether such conversations are really simi- lar to those typically written via messenger apps. To find the answer, we performed a validation task. We asked two linguists to doubly annotate 50 con- versations in order to verify whether the dialogues could appear in a messenger app and could be summarized (i.e. a dialogue is not too general or unintelligible) or not (e.g. a dialogue between two people in a shop). The results revealed that 94% of examined dialogues were classified by both anno- tators as good i.e. they do look like conversations from a messenger app and could be condensed in a reasonable way. In a similar validation task, con- ducted for the existing dialogue-type datasets (de- scribed in the Initial approach section), the annota- tors agreed that only 28% of the dialogues resem- bled conversations from a messenger app. Cleaning data. After preparing the dataset, we conducted a process of cleaning it in a semi- automatic way. Beforehand, we specified a for- mat for written dialogues with summaries: a colon should separate an author of utterance from its content, each utterance is expected to be in a sep- arate line. Therefore, we could easily find all de- viations from the agreed structure – some of them could be automatically fixed (e.g. when instead of a colon, someone used a semicolon right af- ter the interlocutor’s name at the beginning of an utterance), others were passed for verification to linguists. We also tried to correct typos in inter- locutors’ names (if one person has several utter- ances, it happens that, before one of them, there is a typo in his/her name) – we used the Levenshtein distance to find very similar names (possibly with typos e.g. ’George’ and ’Goerge’) in a single con- versation, and those cases with very similar names were passed to linguists for verification. Description. The created dataset is made of 16369 conversations distributed uniformly into 4 groups based on the number of utterances in con- versations: 3-6, 7-12, 13-18 and 19-30. Each ut- terance contains the name of the speaker. Most conversations consist of dialogues between two in- terlocutors (about 75% of all conversations), the rest is between three or more people. Table 1 presents the size of the dataset split used in our experiments. The example of a dialogue from this corpus is shown in Table 2. Dialogue Blair: Remember we are seeing the wedding planner after work Chuck: Sure, where are we meeting her? Blair: At Nonna Rita’s Chuck: Can I order their seafood tagliatelle or are we just having coffee with her? I’ve been dreaming about it since we went there last month Blair: Haha sure why not Chuck: Well we both remmber the spaghetti pomodoro disaster from our last meeting with Diane Blair: Omg hahaha it was all over her white blouse Chuck: :D Blair: :P Summary Blair and Chuck are going to meet the wedding planner after work at Nonna Rita’s. The tagliatelle served at Nonna Rita’s are very good. Table 2: Example of a dialogue from the collected cor- pus # 3 Dialogues baselines The baseline commonly used in the news summa- rization task is Lead-3 (See et al., 2017), which takes three leading sentences of the document as the summary. The underlying assumption is that the beginning of the article contains the most R-L 29.42 29.91 30.07 26.13 28.10 27.97 29.92 29.91 29.55 26.72 27.59 27.71 R-2 8.68 8.93 9.53 6.57 7.96 8.12 10.27 10.35 10.21 9.69 10.23 10.28 n R-1 31.40 3 31.87 4 32.02 5 28.04 3 30.08 4 29.91 5 32.46 3 32.19 4 31.61 5 28.31 10 29.36 20 29.61 30 Model LEAD MIDDLE LONGEST LONGER -THAN MOST-ACTIVE -PERSON n/a 26.54 8.55 24.57 Table 3: Baselines for the dialogues summarization Inspired by the Lead-n significant information. model, we propose a few different simple models: • MIDDLE-n, which takes n utterances from the middle of the dialogue, • LONGEST-n, treating only n longest utter- ances in order of length as a summary, • LONGER-THAN-n, taking only utterances longer than n characters in order of length (if there is no such long utterance in the di- alogue, takes the longest one), • MOST-ACTIVE-PERSON, which treats all utterances of the most active person in the di- alogue as a summary. Results of the evaluation of the above models are reported in Table 3. There is no obvious baseline for the task of dialogues summarization. We ex- pected rather low results for Lead-3, as the begin- nings of the conversations usually contain greet- ings, not the main part of the discourse. How- ever, it seems that in our dataset greetings are fre- quently combined with question-asking or infor- mation passing (sometimes they are even omit- ted) and such a baseline works even better than the MIDDLE baseline (taking utterances from the middle of a dialogue). Nevertheless, the best di- alogue baseline turns out to be the LONGEST-3 model. # 4 Experimental setup This section contains a description of setting used in the experiments carried out. # 4.1 Data preparation In order to build a dialogue summarization model, we adopt the following strategies: (1) each can- didate architecture is trained and evaluated on the dialogue dataset; (2) each architecture is trained on the train set of CNN/Daily Mail joined together with the train set of the dialogue data, and evalu- ated on the dialogue test set. In addition, we prepare a version of dialogue data, in which utterances are separated with a spe- cial token called the separator (artificially added token e.g. ’<EOU>’ for models using word em- beddings, ’|’ for models using subword embed- dings). In all our experiments, news and dialogues are truncated to 400 tokens, and summaries – to 100 tokens. The maximum length of generated summaries was not limited. • Fast Abs RL Enhanced. The additional variant of the Fast Abs RL model with slightly changed utterances i.e. to each utterance, at the end, after artificial separator, we add names of all other interlocutors. The reason for that is that Fast Abs RL requires text to be split into sentences (as it selects sentences and then paraphrase each of them). For dia- logues, we divide text into utterances (which is a natural unit in conversations), so some- times, a single utterance may contain more than one sentence. Taking into account how this model works, it may happen that it se- lects an utterance of a single person (each ut- terance starts with the name of the author of the utterance) and has no information about other interlocutors (if names of other inter- locutors do not appear in selected utterances), so it may have no chance to use the right peo- ple’s names in generated summaries. # 4.2 Models We carry out experiments with the following sum- marization models (for all architectures we set the beam size for beam search decoding to 5): • Pointer generator network (See et al., In the case of Pointer Generator, 2017). we use a default configuration3, changing only the minimum length of the generated summary from 35 (used in news) to 15 (used in dialogues). • LightConv and DynamicConv (Wu et al., The implementation is available 2019). in fairseq7 (Ott et al., 2019). We train lightweight convolution models in two man- ners: (1) learning token representations from scratch; in this case we apply BPE tokeniza- tion with the vocabulary of 30K types, using fastBPE implementation8 (Sennrich et al., 2015); (2) initializing token embeddings with pre-trained language model representations; as a language model we choose GPT-2 small (Radford et al., 2019). • Transformer (Vaswani et al., 2017). The model is trained using OpenNMT library4. We use the same parameters for training both on news and on dialogues5, changing only the minimum length of the generated summary – 35 for news and 15 for dialogues. • Fast Abs RL (Chen and Bansal, 2018). It is trained using its default parameters6. For di- alogues, we change the convolutional word- level sentence encoder (used in extractor part) to only use kernel with size equal 3 in- It is caused by the fact stead of 3-5 range. that some of utterances are very short and the default setting is unable to handle that. # 4.3 Evaluation metrics the standard We reporting the ROUGE metric F1 for ROUGE-1, scores ROUGE-2 and ROUGE-L following previous works (Chen and Bansal, 2018; See et al., 2017). We obtain scores using the py-rouge package9. # 5 Results The results for the news summarization task are shown in Table 4 and for the dialogue summariza- tion – in Table 5. In both domains, the best mod- els’ ROUGE-1 exceeds 39, ROUGE-2 – 17 and ROUGE-L – 36. Note that the strong baseline for # 3https://github.com/abisee/pointer-generator 4https://github.com/OpenNMT/OpenNMT-py 5http://opennmt.net/OpenNMT-py/Summarization.html 6https://github.com/ChenRocks/fast_abs_rl 7https://github.com/pytorch/fairseq 8https://github.com/glample/fastBPE 9https://pypi.org/project/py-rouge/ news (Lead-3) is outperformed in all three met- rics only by one model. In the case of dialogues, all tested models perform better than the baseline (LONGEST-3). In general, the Transformer-based architec- tures benefit from training on the joint dataset: news+dialogues, even though the news and the di- alogue documents have very different structures. Interestingly, this does not seem to be the case for the Pointer Generator or Fast Abs RL model. The inclusion of a separation token between di- alogue utterances is advantageous for most models – presumably because it improves the discourse structure. The improvement is most visible when training is performed on the joint dataset. Having compared two variants of the Fast Abs RL model – with original utterances and with en- hanced ones (see Section 4.2), we conclude that enhancing utterances with information about the other interlocutors helps achieve higher ROUGE values. The largest improvement of the model perfor- mance is observed for LightConv and Dynamic- Conv models when they are complemented with pretrained embeddings from the language model GPT-2, trained on enormous corpora. is also worth noting that some models (Pointer Generator, Fast Abs RL), trained only on the dialogues corpus (which has 16k dialogues), reach similar level (or better) in terms of ROUGE metrics than models trained on the CNN/DM news dataset (which has more than 300k arti- cles). Adding pretrained embeddings and train- ing on the joined dataset helps in achieving signifi- cantly higher values of ROUGE for dialogues than the best models achieve on the CNN/DM news dataset. the best per- forming model is DynamicConv with GPT-2 em- beddings, trained on joined news and dialogue data with an utterance separation token. # 6 Linguistic verification of summaries ROUGE is a standard way of evaluating the qual- ity of machine generated summaries by compar- ing them with reference ones. The metric based on n-gram overlapping, however, may not be very informative for abstractive summarization, where in producing high- paraphrasing is a keypoint quality sentences. To quantify this conjecture, we manually evaluated summaries generated by the R-1 40.24 38.72 40.99 38.72 39.44 39.46 R-2 17.44 16.67 17.72 16.89 17.20 17.33 Model Lead-3 baseline Pointer Generator Fast Abs RL Transformer LightConv DynamicConv LightConv R-L 34.90 35.59 38.30 35.74 36.20 36.29 + GPT2 emb 39.52 17.31 36.15 DynamicConv + GPT2 emb 39.94 17.56 36.51 Table 4: Model evaluation on the news corpus test set models for 150 news and 100 dialogues. We asked two linguists to mark the quality of every sum- mary on the scale of −1, 0, 1, where −1 means that a summarization is poor, extracts irrelevant information or does not make sense at all, 1 – it is understandable and gives a brief overview of the text, and 0 stands for a summarization that extracts only a part of relevant information, or makes some mistakes in the produced summary. We noticed a few annotations (7 for news and 4 for dialogues) with opposite marks (i.e. one an- notator judgement was −1, whereas the second one was 1) and decided to have them annotated once again by another annotator who had to re- solve conflicts. For the rest, we calculated the lin- ear weighted Cohen’s kappa coefficient (McHugh, 2012) between annotators’ scores. For news ex- amples, we obtained agreement on the level of 0.371 and for dialogues – 0.506. The annotators’ agreement is higher on dialogues than on news, probably because of structures of those data – arti- cles are often long and it is difficult to decide what the key-point of the text is; dialogues, on the con- trary, are rather short and focused mainly on one topic. For manually evaluated samples, we calculated ROUGE metrics and the mean of two human rat- ings; the prepared statistics is presented in Ta- ble 6. As we can see, models generating dialogue summaries can obtain high ROUGE results, but their outputs are marked as poor by human anno- tators. Our conclusion is that the ROUGE met- ric corresponds with the quality of generated sum- maries for news much better than for dialogues, confirmed by Pearson’s correlation between hu- man evaluation and the ROUGE metric, shown in Table 7. Model Train data Separator | R-1 R-2 R-L LONGEST-3 baseline 32.46 10.27 29.92 Pointer Generator dialogues no 38.55 14.14 34.85 Pointer Generator dialogues yes 40.08 15.28 36.63 Fast Abs RL dialogues no 40.96 17.18 39.05 Fast Abs RL Enhanced dialogues no 41.95 18.06 39.23 Transformer dialogues no 36.62 11.18 33.06 Transformer dialogues yes 37.27 10.76 32.73 LightConv dialogues no 33.19 11.14 30.34 DynamicConv dialogues no 33.79 11.19 30.41 DynamicConv dialogues yes 33.69 10.88 30.93 LightConv + GPT-2 emb. dialogues no 41.81 16.34 37.63 DynamicConv + GPT-2 emb. | dialogues no 41.79 16.44 37.54 DynamicConv + GPT-2 emb. | dialogues yes 41.54 16.29 37.07 Pointer Generator news + dialogues no 35.04 13.25 32.42 Pointer Generator news + dialogues yes 37.27 14.42 34.36 Fast Abs RL news + dialogues no 41.03 16.93 39.05 Fast Abs RL Enhanced news + dialogues no 41.87 17.47 39.53 Transformer news + dialogues no 41.91 18.25 38.77 Transformer news + dialogues yes 42.37 18.44 39.27 LightConv news + dialogues no 40.29 17.28 36.81 DynamicConv news + dialogues no 40.66 17.41 37.20 DynamicConv news + dialogues yes 41.07 17.11 37.27 LightConv + GPT-2 emb. news + dialogues no 44.47 19.75 40.07 DynamicConv + GPT-2 emb. | news + dialogues no 44.69 20.28 40.76 DynamicConv + GPT-2 emb. | news + dialogues yes 45.41 20.65 41.45 Table 5: Model evaluation on the dialogues corpus test set R-2 16.55 18.28 14.81 19.94 19.28 16.59 R-1 39.76 42.33 37.19 43.53 42.16 39.79 #examples mean median 0.18 0.33 0.03 -0.503 -0.55 -0.63 100 50 50 150 50 50 overall Fast Abs RL DynamicConv overall Fast Abs RL Fast Abs RL Enhanced DynamicConv 0.5 0.5 0.25 -0.5 -0.75 -1.0 48.63 -0.5 50 -0.33 23.95 + GPT-2 emb. R-L 36.23 38.82 33.64 40.66 40.37 37.05 44.57 Table 6: Statistics of human evaluation of summaries’ quality and ROUGE evaluation of those summaries # 7 Difficulties in dialogue summarization In a structured text, such as a news article, the in- formation flow is very clear. However, in a dia- logue, which contains discussions (e.g. when peo- ple try to agree on a date of a meeting), questions (one person asks about something and the answer may appear a few utterances later) and greetings, most important pieces of information are scattered across the utterances of different speakers. What is more, articles are written in the third-person point of view, but in a chat everyone talks about them- selves, using a variety of pronouns, which fur- ther complicates the structure. Additionally, peo- ple talking on messengers often are in a hurry, so they shorten words, use the slang phrases (e.g. ’u r gr8’ means ’you are great’) and make typos. These phenomena increase the difficulty of performing dialogue summarization. Table 8 and 9 show a few selected dialogues, ROUGE-1 corr p-value NEWS 0.47 DIALOGUES 0.32 ROUGE-L corr p-value 0.48 0.32 ROUGE-2 corr p-value 0.44 0.30 1e-6 7.7e-5 1e-6 8.1e-5 6e-6 1.84e-4 Table 7: Pearson’s correlations between human judgement and ROUGE metric together with summaries produced by the best tested models: them separately. This leads to the narrowing of the context and loosing important pieces of informa- tion. • DynamicConv + GPT-2 embeddings with a separator (trained on news + dialogues), • DynamicConv + GPT-2 embeddings (trained on news + dialogues), • Fast Abs RL (trained on dialogues), • Fast Abs RL Enhanced (trained on dia- logues), • Transformer (trained on news + dialogues). One can easily notice problematic issues. Firstly, the models frequently have difficulties in associating names with actions, often repeating the same name, e.g., for Dialogue 1 in Table 8, Fast Abs RL generates the following summary: ’lilly and lilly are going to eat salmon’. To help the model deal with names, the utterances are en- hanced by adding information about the other in- terlocutors – Fast Abs RL enhanced variant de- scribed in Section 4.2. In this case, after enhance- ment, the model generates a summary containing both interlocutors’ names: ’lily and gabriel are going to pasta...’. Sometimes models correctly choose speakers’ names when generating a sum- mary, but make a mistake in deciding who per- forms the action (the subject) and who receives the action (the object), e.g. for Dialogue 4 Dynamic- Conv + GPT-2 emb. w/o sep. model generates the summary ’randolph will buy some earplugs for maya’, while the correct form is ’maya will buy some earplugs for randolph’. A closely related problem is capturing the con- text and extracting information about the arrange- ments after the discussion. For instance, for Di- alogue 4, the Fast Abs RL model draws a wrong conclusion from the agreed arrangement. This is- sue is quite frequently visible in summaries gen- erated by Fast Abs RL, which may be the conse- quence of the way it is constructed; it first chooses important utterances, and then summarizes each of One more aspect of summary generation is de- ciding which information in the dialogue content is important. For instance, for Dialogue 3 Dy- namicConv + GPT-2 emb. with sep. generates a correct summary, but focuses on a piece of infor- mation different than the one included in the ref- erence summary. In contrast, some other models – like Fast Abs RL enhanced – select both of the pieces of information appearing in the discussion. On the other hand, when summarizing Dialogue 5, the models seem to focus too much on the phrase ’it’s the best place’, intuitively not the most impor- tant one to summarize. # 8 Discussion This paper is a step towards abstractive summa- rization of dialogues by (1) introducing a new dataset, created for this task, (2) comparison with news summarization by the means of automated (ROUGE) and human evaluation. Most of the tools and the metrics measuring the quality of text summarization have been developed for a single-speaker document, such as news; as such, they are not necessarily the best choice for conversations with several speakers. We test a few general-purpose summarization models. In terms of human evaluation, the re- sults of dialogues summarization are worse than the results of news summarization. This is con- nected with the fact that the dialogue structure is more complex – information is spread in multi- ple utterances, discussions, questions, more typos and slang words appear there, posing new chal- lenges for summarization. On the other hand, dia- logues are divided into utterances, and for each ut- terance its author is assigned. We demonstrate in experiments that the models benefit from the intro- duction of separators, which mark utterances for each person. This suggests that dedicated models having some architectural changes, taking into ac- count the assignation of a person to an utterance in Dialogue 1 1. lilly: sorry, i’m gonna be late 2. lilly: don’t wait for me and order the food 3. gabriel: no problem, shall we also order something for you? 4. gabriel: so that you get it as soon as you get to us? 5. lilly: good idea 6. lilly: pasta with salmon and basil is always very tasty here REF: lilly will be late. gabriel will order pasta with salmon and basil for her. Dialogue 2 1. randolph: honey 2. randolph: are you still in the pharmacy? 3. maya: yes 4. randolph: buy me some earplugs please 5. maya: how many pairs? 6. randolph: 4 or 5 packs 7. maya: i’ll get you 5 8. randolph: thanks darling REF: maya will buy 5 packs of earplugs for randolph at the pharmacy. L3: 6, 3, 4 [38/17/38] DS: lilly and gabriel are going to order pasta with salmon and basil [62/42/62] D: lilly and gabriel are going to order pasta with salmon and basil [62/42/62] F: lilly will be late . she will order the food . lilly F: maya is in the pharmacy . maya will get 5 . and lilly are going to eat salmon and basil [55/39/55] FE: lilly will be late . lilly and gabriel are going to pasta with salmon and basil is always tasty . [63/47/63] T: lilly will order the food as soon as she gets to gabriel [31/17/23] L3: 2, 4, 8 [36/8/36] DS: randolph and maya are going to buy some earplugs for randolph. [43/19/43] D: randolph will buy some earplugs for maya. [63/24/42] [48/21/48] FE: randolph is in the pharmacy . randolph will buy some earplugs for randolph . maya will get 5 . [64/38/64] T: randolph will buy some earplugs for randolph . maya will get 5 pairs . [58/36/42] Table 8: Examples of dialogues (Part 1). REF – reference summary, L3 – LONGEST-3 baseline, DS – Dynamic- Conv + GPT-2 emb. with sep., D – DynamicConv + GPT-2 emb., F – Fast Abs RL, FE – Fast Abs RL Enhanced, T – Transformer. For L3, three longest utterances are listed. Rounded ROUGE values [R-1/R-2/R-L] are given in square brackets. a systematic manner, could improve the quality of dialogue summarization. We show that the most popular summarization metric ROUGE does not reflect the quality of a summary. Looking at the ROUGE scores, one concludes that the dialogue summarization models perform better than the ones for news summariza- tion. In fact, this hypothesis is not true – we per- formed an independent, manual analysis of sum- maries and we demonstrated that high ROUGE results, obtained for automatically-generated di- alogue summaries, correspond with lower eval- uation marks given by human annotators. An interesting example of the misleading behavior of the ROUGE metrics is presented in Table 9 for Dialogue 4, where a wrong summary – ’paul and cindy don’t like red roses.’ – obtained all ROUGE values higher than a correct summary – ’paul asks cindy what color flowers should buy.’. Despite lower ROUGE values, news summaries were scored higher by human evaluators. We con- clude that when measuring the quality of model- the ROUGE metrics are generated summaries, more indicative for news than for dialogues, and a new metric should be designed to measure the quality of abstractive dialogue summaries. # 9 Conclusions In our paper we have studied the challenges of ab- stractive dialogue summarization. We have ad- dressed a major factor that prevents researchers from engaging into this problem: the lack of a proper dataset. To the best of our knowledge, this is the first attempt to create a comprehen- sive resource of this type which can be used in future research. The next step could be creating an even more challenging dataset with longer dia- logues that not only cover one topic, but span over numerous different ones. Dialogue 3 1. ashleigh: looks like we’re going to the cinema!! 2. ashleigh: <file_gif> 3. peter: you got the job?? 4. ashleigh: i got hte job! :d 5. peter: <file_gif> 6. ashleigh: <file_gif> Dialogue 4 1. paul: what color flowers should i get 2. cindy: any just not yellow 3. paul: ok, pink? 4. cindy: no maybe red 5. paul: just tell me what color and what type ok? 6. cindy: ugh, red roses! REF: paul will buy red roses following cindy’s advice. REF: ashleigh got the job. L3: 1, 4, 3 [33/18/33] DS: ashleigh and peter are going to the cinema. [33/0/33] D: ashleigh got hte job. [75/33/75] L3: 5, 1, 2 [13/0/13] DS: paul and cindy don’t like red roses. [47/13/35] D: paul asks cindy what color flowers should buy. [35/0/24] F: cindy is going to buy red roses [50/29/38] FE: cindy is buying red roses . cindy will buy red . [56/38/44] T: cindy does n’t know what color should get. cindy does not know what to do [8/0/8] F: ashleigh and ashleigh are going to the cinema. peter got the job . [50/29/50] FE: ashley and peter are going to the cinema together . ashleigh got the job . [47/40/47] T: ashleigh got the job at the cinema . peter and ashleigh are going there . [47/40/47] Dialogue 5 1. eve: where are we meeting? 2. charlie: at the entrance 3. nicole: yes, it’s the best place. we would’t find each other inside, it’ll be too crowded 4. eve: ok! REF: eve, charlie and nicole are meeting at the entrance. L3: 3, 1, 2 [43/11/43] DS: eve, charlie and nicole are meeting at the entrance. [100/100/100] D: eve, charlie and nicole are meeting at the entrance. [100/100/100] F: charlie is at the entrance . it ’s the best place . [42/24/42] FE: charlie is at the entrance . nicole and charlie are going to find each other inside . [58/18/42] T: eve and nicole are meeting at the entrance . it ’s the best place to meet . [67/55/67] Table 9: Examples of dialogues (Part 2). REF – reference summary, L3 – LONGEST-3 baseline, DS – Dynamic- Conv + GPT-2 emb. with sep., D – DynamicConv + GPT-2 emb., F – Fast Abs RL, FE – Fast Abs RL Enhanced, T – Transformer. For L3, three longest utterances are listed. Rounded ROUGE values [R-1/R-2/R-L] are given in square brackets. As shown, summarization of dialogues is much more challenging than of news. In order to per- form well, it may require designing dedicated tools, but also new, non-standard measures to cap- ture the quality of abstractive dialogue summaries in a relevant way. We hope to tackle these issues in future work. # Acknowledgments We would like to express our sincere thanks to Tu- nia Błachno, Oliwia Ebebenge, Monika J˛edras and Małgorzata Krawentek for their huge contribution to the corpus collection – without their ideas, man- agement of the linguistic task and verification of examples we would not be able to create this pa- per. We are also grateful for the reviewers’ helpful comments and suggestions. # References Siddhartha Banerjee, Prasenjit Mitra, and Kazunari Sugiyama. 2015. Abstractive meeting summariza- tion using dependency graph fusion. In Proceedings of the 24th International Conference on World Wide Web, pages 5–6. Yen-Chun Chen and Mohit Bansal. 2018. Fast abstrac- tive summarization with reinforce-selected sentence rewriting. In Proceedings of the 56th Annual Meet- ing of the Association for Computational Linguis- tics, pages 675–686. Sumit Chopra, Michael Auli, and Alexander M. Rush. 2016. Abstractive sentence summarization with at- tentive recurrent neural networks. In Proceedings of the 2016 Conference of the North American Chap- ter of the Association for Computational Linguistics: Human Language Technologies, pages 93–â ˘A ¸S98. Prakhar Ganesh and Saket Dingliwal. 2019. Abstrac- tive summarization of spoken and written conversa- tion. arXiv:1902.01615. Sebastian Gehrmann, Yuntian Deng, and Alexander Rush. 2018. Bottom-up abstractive summarization. In Proceedings of the 2018 Conference on Empiri- cal Methods in Natural Language Processing, pages 4098–4109. Chih-Wen Goo and Yun-Nung Chen. 2018. Abstrac- tive dialogue summarization with sentence-gated modeling optimized by dialogue acts. 2018 IEEE Spoken Language Technology Workshop (SLT), pages 735–742. Karl M. Hermann, Tomà ˛as Kociská, Edward Grefen- stette, Lasse Espeholt, Will Kay, Mustafa Suleyman, and Phil Blunsom. 2015. Teaching machines to read and comprehend. CoRR, abs/1506.03340. Urvashi Khandelwal, Kevin Clark, Dan Jurafsky, and Lukasz Kaiser. 2019. Sample efficient text sum- marization using a single pre-trained transformer. CoRR, abs/1905.08836. Chin-Yew Lin. 2004. ROUGE: A package for auto- matic evaluation of summaries. In Text Summariza- tion Branches Out, pages 74–81, Barcelona, Spain. Association for Computational Linguistics. I. McCowan, J. Carletta, W. Kraaij, S. Ashby, S. Bour- ban, M. Flynn, M. Guillemot, T. Hain, J. Kadlec, V. Karaiskos, M. Kronenthal, G. Lathoud, M. Lin- coln, A. Lisowska, W. Post, Dennis Reidsma, and P. Wellner. 2005. The ami meeting corpus. In Pro- ceedings of Measuring Behavior 2005, 5th Interna- tional Conference on Methods and Techniques in Be- havioral Research, pages 137–140. the kappa statistic. Biochemia medica, 22(3):276–282. Yashar Mehdad, Giuseppe Carenini, and Raymond T. Ng. 2014. Abstractive summarization of spoken and written conversations based on phrasal queries. In Proceedings of the 52nd Annual Meeting of the As- sociation for Computational Linguistics, volume 1, pages 1220–1230. Amita Misra, Pranav Anand, Jean Fox Tree, and Mar- ilyn Walker. 2015. Using summarization to dis- cover argument facets in online idealogical dialog. In The North American Chapter of the Association for Computational Linguistics (NAACL). Ramesh Nallapati, Bowen Zhou, Cicero Nogueira dos Santos, Caglar Gulcehre, and Bing Xiang. 2016. Abstractive text summarization using sequence-to- sequence rnns and beyond. In Computational Natu- ral Language Learning. Nikola Nikolov, Michael Pfeiffer, and Richard Hahn- loser. 2018. Data-driven summarization of scien- tific articles. In Proceedings of the Eleventh Interna- tional Conference on Language Resources and Eval- uation (LREC 2018). Myle Ott, Sergey Edunov, Alexei Baevski, Angela Fan, Sam Gross, Nathan Ng, David Grangier, and fairseq: A fast, extensible Michael Auli. 2019. In Proceedings of toolkit for sequence modeling. the 2019 Conference of the North American Chap- ter of the Association for Computational Linguistics (Demonstrations), pages 48–53. Alec Radford, Jeff Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. Alexander M. Rush, Sumit Chopra, and Jason Weston. 2015. A neural attention model for abstractive sen- In Proceedings of the 2015 tence summarization. Conference on Empirical Methods in Natural Lan- guage Processing, pages 379–389. Abigail See, Peter J. Liu, and Christopher D. Manning. 2017. Get to the point: Summarization with pointer- generator networks. In Proceedings of the 55th An- nual Meeting of the Association for Computational Linguistics, volume 1, pages 1073–1083. Rico Sennrich, Barry Haddow, and Alexandra Birch. 2015. Neural machine translation of rare words with subword units. CoRR, abs/1508.07909. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Pro- cessing Systems 30, pages 5998–6008. Felix Wu, Angela Fan, Alexei Baevski, Yann Dauphin, and Michael Auli. 2019. Pay less attention with lightweight and dynamic convolutions. In Interna- tional Conference on Learning Representations. Jianjun Xu, and Ji Wang. 2019. Pretraining-based natural language generation for text summarization. CoRR, abs/1902.09243.
Title: Top-KAST: Top-K Always Sparse Training: Summary: Sparse neural networks are becoming increasingly important as the field seeks to improve the performance of existing models by scaling them up, while simultaneously trying to reduce power consumption and computational footprint. Unfortunately, most existing methods for inducing performant sparse models still entail the instantiation of dense parameters, or dense gradients in the backward-pass, during training. For very large models this requirement can be prohibitive. In this work we propose Top-KAST, a method that preserves constant sparsity throughout training (in both the forward and backward-passes). We demonstrate the efficacy of our approach by showing that it performs comparably to or better than previous works when training models on the established ImageNet benchmark, whilst fully maintaining sparsity. In addition to our ImageNet results, we also demonstrate our approach in the domain of language modeling where the current best performing architectures tend to have tens of billions of parameters and scaling up does not yet seem to have saturated performance. Sparse versions of these architectures can be run with significantly fewer resources, making them more widely accessible and applicable. Furthermore, in addition to being effective, our approach is straightforward and can easily be implemented in a wide range of existing machine learning frameworks with only a few additional lines of code. We therefore hope that our contribution will help enable the broader community to explore the potential held by massive models, without incurring massive computational cost. # Top-KAST: Top-K Always Sparse Training Siddhant M. Jayakumar DeepMind University College London Razvan Pascanu DeepMind University College London Jack W. Rae DeepMind Simon Osindero DeepMind Erich Elsen DeepMind # Abstract Sparse neural networks are becoming increasingly important as the field seeks to im- prove the performance of existing models by scaling them up, while simultaneously trying to reduce power consumption and computational footprint. Unfortunately, most existing methods for inducing performant sparse models still entail the in- stantiation of dense parameters, or dense gradients in the backward-pass, during training. For very large models this requirement can be prohibitive. In this work we propose Top-KAST, a method that preserves constant sparsity throughout training (in both the forward and backward-passes). We demonstrate the efficacy of our approach by showing that it performs comparably to or better than previous works when training models on the established ImageNet benchmark, whilst fully maintaining sparsity. In addition to our ImageNet results, we also demonstrate our approach in the domain of language modeling where the current best performing architectures tend to have tens of billions of parameters and scaling up does not yet seem to have saturated performance. Sparse versions of these architectures can be run with significantly fewer resources, making them more widely accessible and applicable. Furthermore, in addition to being effective, our approach is straightforward and can easily be implemented in a wide range of existing machine learning frameworks with only a few additional lines of code. We therefore hope that our contribution will help enable the broader community to explore the potential held by massive models, without incurring massive computational cost. # Introduction The Lottery Ticket Hypothesis [9] has spurred interest in training sparse neural networks [44], as it highlights a prior exciting result – that only a small subset of weights of a converged model are sufficient to represent the learnt function to high accuracy [14, 40, 29, 17, 36]. Perhaps even more exciting is the finding of Kalchbrenner et al. [17] that large sparse models outperform smaller dense models for a fixed parameter and floating point operation (FLOP) budget. However, while encouraging, the primary method of finding such sparse subsets involves training a dense model. While there is a plethora of works proposing increasingly efficient ways to prune dense networks for sparse inference (dense-to-sparse training) [45, 27, 5], the field has only more recently begun to look at approaches that start training at the desired sparsity (sparse-to-sparse training) [26, 3, 28, 7]. Additionally, a high performance and scalable sparse-to-sparse approach would considerably benefit the democratisation of deep learning, as state-of-the-art models are ever increasing in size [34, 18, 39]. This increasingly leads to situations wherein state-of-the-art models require large clusters to train 34th Conference on Neural Information Processing Systems (NeurIPS 2020), Vancouver, Canada. Y Cc A f ™, B | | See | | | | LI aa <= _ vw x Va MO Figure 1: A diagramatic illustration of Top-KAST. While initialised with an effectively random mask, Top-KAST explores different permutations by updating an exploration set of weights and choosing the ones with greatest magnitude. which most researchers would have limited access to. The large compute footprints and energy consumption of training such models also raises important environmental, moral and economic concerns [11, 33, 37]. State-of-the-art text-to-speech (TTS) [17, 1] and automatic speech recognition (ASR) [15, 31] are other domains that rely heavily on sparsity. Here sparse networks are used for efficient inference on embedded devices as well as to reduce latency. Further, enabling sparse-training could improve models’ ability to personalize to different users, and maintain privacy on device [43, 23]. Sparse training requires both appropriate algorithms and software/hardware to take advantage of sparse operations. Whilst much of the focus in neural network training hardware has centred on accelerating dense linear algebra operations, there is already sparsity support in modern hardware [30] with more in the development pipeline [16]. Thus, a scalable and performant sparse-to-sparse method promises to unlock large potential benefits to neural network training — in terms of model scaling, reduced energy consumption and effective inference. The simplest and most scalable of these methods is to simply pick a random static sparse pattern at initialisation and train with this. Approaches such as Sparse Evolutionary Training (SET) [26] or Dynamic Reparameterization [28] improve on this by modifying their sparsity masks based on random evolution, but still lag behind corresponding dense-to-sparse methods. More recently, RigL [8] is able to match, or supersede the performance of dense-to-sparse methods. It does this by updating sparsity masks by using occasional gradient information. While theoretically entirely sparse, it is difficult to achieve RigL’s theoretical bounds and avoid full dense materialization in common deep learning frameworks. In this paper we aim to address some of these issues and propose a fully parameter-sparse training approach called Top-KAST. Our technique is scalable because it never requires doing a forward pass with dense parameters, nor calculating a dense gradient. It is also easy to implement within existing frameworks. Briefly, our method consists of selecting a subset of parameters A ⊂ Θ that correspond to the top-K parameters by parameter-magnitude for each training step, and applying gradients to a larger parameter subset B ⊂ Θ (where B ⊃ A.) To avoid the network fixating on a sub-optimal sparse subset, we introduce an auxiliary exploration loss to encourage the mask to adapt during training. We find we are able to get state-of-the-art language modelling performance for small models, when training a Transformer-XL model using Top-KAST on the character-level task: enwik8 [24]. For image modelling, Top-KAST outperforms existing sparse-to-sparse training approaches, such as Sparse Evolutionary Training (SET) [26] and matches Rigging the Lottery (RigL) [7] on ImageNet across a range of floating-point operations (FLOPs) budgets. # 2 Method: Top-KAST # The key desiderata for a sparse training method, is that it should: 1. Produce a network of desired weight sparsity Sf inal after training is finished. 2. Have minimal compute and memory overheads relative to training a fixed (i.e. static) topology sparse model. 2 Dense-to-sparse training methods such as magnitude pruning, Dynamic Neural Wirings (DNW) [42] and Soft Weight Threshold Reparameterization (STR) [20] satisfy the first criterion but not the second. Existing sparse to sparse methods satisfy the second constraint in different ways. SET and its derivatives occasionally prune unpromising connections and add new ones at random to maintain the same sparsity throughout training. RigL occasionally prunes unpromising connections and adds new ones based on the locations of the largest gradients from one mini-batch. We propose an alternate solution that still satisfies the second criterion and achieves high accuracy for a given number of training FLOPs while being easier to integrate into existing frameworks. # 2.1 Sparse Forward Pass We consider a generic neural network parameterised by function f with parameters θt at some training step t and input x. The output from the forward pass is y = f (θt, x). And during learning the parameters would be updated as θt+1 = θt − η∇θtL(y, x), where L is the loss function. Our aim is to to maintain a network weight sparsity of S ∈ [0, 1] throughout training — where S represents the proportion of weights that are zero (D = 1 − S is the corresponding density proportion of the network). To do so, at each point in time we consider αt – a parameterisation that retains a subset of weights from θt 0, and replaces the rest with zeros. We have: of ifie At a= {ft ifi 0 otherwise with At used to define a sparse subset of parameter indices that we consider to be “active” (i.e. non-zero) at time t. Membership of At is restricted to the top D-proportion of weights (from θt) by magnitude – that is: At = {i|θt i ∈ TopK(θt, D)} In practice, we perform this top-K operation per layer instead of on the flattened set of param- eters1. One rationale for selecting weights according to their magnitude is that it is an effective but inexpensive estimate of which parameters contribute the most to defining the behaviour of the densely-parameterized function f (θ, x). Ideally we would like f (α, x) to be the best approximation of f (θ, x) using α of fixed sparsity-proportion S. To obtain insight into our approximation, we can examine the Taylor series expansion for f (α, x) around θ, where G is the gradient vector and H is the Hessian matrix: f (α, x) ≈ f (θ, x) + GT (α − θ) + 1 2 (α − θ)T H(α − θ) + ... While being able to calculate higher-order derivatives would provide more accurate sensitivity information [21], it is computationally intractable to do so for very large modern networks. However, as every term in the error scales with powers of (α − θ), without any information about the higher order derivatives, minimizing the norm of (α − θ) – which corresponds to our selection process – seems the best choice. During learning we use αt in both for the forward-pass and in the backward-pass – hence only incurring the inference and back-propagation compute costs of a sparse model. However, αt is best thought of as a “temporary view” of the dense parameterisation, θt. That is, the updates will be applied to θ rather than α and αt will be reconstructed periodically from θ by the same deterministic procedure of picking largest (by magnitude) D-proportion of weights. # 2.2 Sparse Backward Pass The gradient of the loss with respect to a sparse αt parameterisation need not result in a sparse gradient vector; indeed the gradient would typically be expected to be fully dense. This is because the gradients with respect to the 0 entries of αt need not themselves be zero. This unfortunately would break our key desideratum (2). To avoid evaluating dense gradients we take inspiration from 1Either choice is valid and leads to the same number of parameters. Global pruning often increases the FLOP requirements by preferring parameters in earlier layers which have more reuse. It can also suffer from convergence issues at high sparsities due to differing scales in different layers leading to entire layers being pruned. 3 coordinate descent and compute the gradient for a coordinate block composed of parameters with indices from the set Bt, where: Bt = {i|θt i ∈ TopK(θt, D + M )} By definition, B is a superset of A and contains the indices corresponding to the non-zero entries of α as well as an additional set of indices corresponding to the next largest M -proportion of entries (by magnitude) of the dense parameterisation, θ. Updating the largest (D + M )-proportion of weights makes it more likely that this will lead to permutations in the top D-proportion weights that are active, and hence allows the learning process to more effectively explore different masks. We refer to this effective sparsity of (1 − D − M ) units as our backward sparsity. Computing the gradient with respect to a subset of coordinates of θ implies that the gradient we are computing is sparse, and throughout the forward pass and backward pass we do not need to instantiate a dense vector of the size of θ.The final update has the following form2: Anu = —7VotLly,x,0"); ifie B Lo otherwise At initialisation, A will consist of a random subset of weight-indices from the freshly initialised θ0. As learning progresses, due to the updates on B coming both from the primary loss and the auxiliary regularisation term (described in detail in the following section) this set will change and evolve the weights and topology most useful for the desired function approximation. We postulate learning as going through two stages (and this postulation seems to be observed in practice): • In the first exploratory stage, at each iteration we select a different active set A, and its corresponding α, and perform one update step on θ using gradients obtained from the loss on f (α, x) and the regularizer. • In the second refinement stage, the active set A effectively becomes fixed, as we settle on a stable pattern of non-zero weights which then undergo fine-tuning to their optimal values. In the first stage, the updates on the “additional” coordinates in the set B \ A allows exploration by changing the set of weights that will end up in the active set A (and thus used in α) on the next iteration. In the second stage, these “additional” updates will end up being increasingly less impactful and eventually will be effectively ignored, as they will not alter A and hence will not be reflected in α for either the forward or backward passes. The exploratory stage of picking different subsets of parameters from θ sets makes our approach very different from simply having a fixed random sparsity pattern imposed on the model. # 2.3 Exploration Regularisation Loss The method outlined above may lead to a rich-get-richer phenomenon: with only the randomly selected weights at initialization being used if others receive insufficient weight updates for their norm to exceed the critical threshold. This problem may be particularly pronounced at high levels of sparsity, and to combat it we propose a heuristic inspired by the principle of optimism in face of uncertainty, widely used in reinforcement learning (RL) [4]. Concretely, we penalise the magnitude of the weights in set B, while those that are neither used nor currently being updated (set C) are not penalized at all. The net effect of this is to reduce the magnitude of the active weights, making it more likely that on the next iteration the algorithm considers new items for the membership of both set A and B — similar to how in RL, optimistic exploration adds bias to favour the selection of actions that have not thus far been chosen often. We also posit that for high sparsity settings there is a teetering effect between weights in B \ A and A that are very close in magnitude, leading to a slow down in learning. We therefore propose to penalise B \ A more than A to increase the critical strength of updates needed for units from B \ A to turn on and to stabilise the mask. We heuristically choose the scale to be inversely proportional to D, as this effect is more important for D < 1. 2Our approach is not a strictly valid coordinate descent method on either α or θ. 4 We express this penalty as an L2 regularisation, with a similar split of units as above3. Specifically: LossR(αt i) = |θt i| if i ∈ At |θt i | D 0 if i ∈ Bt \ At else # Implementation of Top-KAST As described above, the compute and memory requirements for Top-KAST in the forward and backward passes scale with the forward and backward sparsities, respectively. One possible concern is the additional cost of performing a Top-K operation in the forward pass every iteration. While the FLOPs required for this are much fewer than those needed by the actual training — this could necessitate fitting the dense model in memory. One way to alleviate this is to simply compute the the Top-K entries in parallel on CPU, thus avoiding the need to fit the model on the actual training hardware. The CPU could maintain the parameters in an appropriate data structure, such as a heap that would minimise the cost of updates. Lastly, we show in the sections below that the mask slowly stabilises and in fact we do not even need to perform this operation every step. In appendix C we show that we can get comparable results even if we perform this only every 100 steps which significantly reduces communication requirements and extra overheads. # 3 Related Work Methods that require dense weight or gradient information at training time but produce a sparse network at the end of training are now numerous and include: L0 regularization [5], variational dropout [27], discovering neural wirings [42], soft weight threshold reparameterization [20]. Mag- nitude Pruning is simple and effective [10] and we use it throughout as a baseline representative of this class of training methods. Such methods do not allow us to train larger sparse models than the biggest dense model we could train (in fact it is usually smaller due to overheads). Sparse training of neural networks first happened through evolutionary means. Throughout the 1990s there was a flurry a research on the topic of Topology and Weight Evolving Artificial Neural Networks (TWEANNs) exemplified by [35]. While the networks were sparse during the evolution, this was not the focus of the research and the advantages of the sparseness in terms of enabling size and efficiency were mostly ignored. There has also been some recent work on using evolutionary methods to evolve sparse topologies [22]. Deep Rewiring [3] was the first work to consider sparse training of weight-sparse neural networks within the framework of gradient descent. It restricts weights to have a fixed sign, and sets weights to zero when their sign would flip. Additionally, it introduces a random walk in parameter space and can be thought of a constrained Monte Carlo sampling procedure over both the weights and the network connectivity. Despite theoretical convergence proofs, its practical performance seems to lag behind later, less well founded work [28]. This was followed by Sparse Evolutionary Training [26] which uses weight magnitudes to drop weights and introduces new connections at random, drawn from the original initialisation distribution. It is both simpler and more effective than Deep Rewiring. Our method, Top-KAST modifies the units based on gradient information instead which we find is more performant than random additions. Dynamic Reparameterization [28] introduces a method for moving a parameter budget between different layers. This allows the network to better put parameter capacity where it is most effective. However, this ignores a FLOP constraint - the amount of FLOPs required to evaluate the network can change (usually upwards) because of these modifications. Lastly, Rigging the Lottery (RigL) [7] is a recent and highly performant sparse-to-sparse method that matches or surpasses the performance of pruning-based methods. It uses infrequent full gradient calculations to decide which parameters to ‘wake-up’. As it only requires knowing the location of the highest values of the gradients, its theoretical cost is proportional to the network sparsity, though this bound is hard to achieve in practice in current DL frameworks. We also compare Top-KAST to 3The gradient of the regularization term follows the same sparsity pattern as the gradient of the primary loss. 5 TopkAST at 80% Sparsity Imagenet Performance at 1x Training Extreme Sparsity Dense nR Method Dense Ric (— 8 == TopKAST (98%) sey ee Biot 2 — Topkast (99%) Pruning Eos ro 7 == Rigl (98%) er ge 77 igh 199%) ‘sral.Dence NIP. Rik <o6 74 Train Step Multiplier orws iti 4 /o p Multip Forward Sparsities « Bea + —10 — os e < — 20 —os Ser 62 “ Ci — 50 — 095 Top-1 Accuracy Top-1 Accuracy 32 Small-Dense °° Fraction FLOPS for Training / Dense °° “Gackward Sparsiies °° Fraction FLOPS for Training / Dense Figure 2: (a) FLOPS needed to train various sparse models as a fraction of those for a dense model. The FLOPS for Top-KAST vary as a function of the backward sparsity and the length of the training run. (b) Comparing methods on the basis of their backward sparsity. (c) Top-KAST and RigL compared at sparsities of 98% and 99%. RigL in this paper and find we are able to perform comparably while alleviating the aforementioned implementation issues. # 4 Experiments: ImageNet Our aim in the section below is to demonstrate the efficacy of our method at enabling sparse training of models across different modalities (vision and language), model types (convolutions and attention) and different sparsity regimes. We start by demonstrating the efficacy of our method on the ImageNet dataset for image classification, where we train a sparse ResNet-50 as in previous works [7, 10]. This is a commonly used benchmark for sparsity methods, albeit often used in different regimes. We provide full details of model and hyper-parameters in the appendix B. We first compare methods in the commonly used regime of fixed inference sparsity with first and last layers dense. As Top-KAST allows practitioners to choose their own level of backward and forward sparsity, we run Top-KAST for different levels of each, as well for multiples of the default training runs. We summarise this in Figure 2 above, showing the spectrum of performance versus FLOPS used (increases with decreasing backward sparsity and increasing training time), for a fixed forward sparsity of 80%. We also report results for a variety of standard and state-of-art methods. We find (Figure 2 a and b) that Top-KAST is comparable (at constant FLOPS) to dense methods like pruning, while advantageously staying completely sparse throughout. Top-KAST also outperforms always-sparse methods like SET and Static random sparsity patterns. We further report results for sparsity levels 90% and 95% in 2(b) and results for relaxing the assumption of first and last layers dense, in appendix B. Comparing RigL and Top-KAST Fig 2 also shows that the most performant prior sparse-to-sparse method is RigL and we see that Top-KAST performs comparably on a per-FLOP basis. RigL’s update of its sparsity pattern requires occasionally calculating (a top-k over) dense gradients and in Fig 2 (b), we can see that when compared on the basis of average backward sparsity instead, Top-KAST requires slightly higher densities to match RigL’s performance. However, while in theory RigL only needs the highest values of this dense gradient, it would require re-writing the gradient calculation for many primitives in existing DL frameworks to achieve this. Additionally, we note that RigL has many hyperparameters that might need tuning: when to start and finish updating the mask, how often to update, the initial drop fraction and the schedule by which this is annealed. On the other hand, Top-KAST requires no custom gradient calculations, and the only hyperparameter is the size of bucket B, and thus is easier to implement, to use, and is readily scalable. We expand on these implementation details in appendix section C. We also find in Fig 2 (c) that Top-KAST surpasses RigL at higher levels of sparsity (98% and 99%). Top-KAST’s ability to choose slightly higher backward sparsities also means that at the cost of a little extra compute we are able to greatly increase performance. # 4.1 Ablation studies # Selection of B \ A. 6 We first consider the question of exploration in the backward pass and the method for selecting set B. We defined this set as those units used in the forward A plus the next-highest set of units by magnitude. We can instead consider whether it would not be better to randomly sample these extra units. Intuitively we might explore more of the space and in expectation, allow gradient to pass through all units. We see in table 1 that this method is far better for sparsity of 90% but performs far worse for higher levels of sparsity, validating our choice. It is to be expected that this choice becomes more important in very sparse settings, where it would take many iterations to cover relevant weights if they are not directly targeted. Also, randomly picking additional weights means that the mask also changes more through training, whereas we expect the top-k to stay more constant, thus reducing the potential cost of the sampling procedure. Method Sparsity Forward Sparsity Backward Top 1 Acc Top-KAST Top-KAST (Random) 0.9 0.9 0.8 0.8 73.03 74.76 Top-KAST Top-KAST (Random) 0.95 0.95 0.9 0.9 70.42 68.48 Top-KAST (t = 0) Top-KAST (t = 5000) Top-KAST (t = 16000) Top-KAST (t = 32000) 0.9 0.9 0.9 0.9 0.0 0.0 0.0 0.0 68.26 72.05 74.14 74.65 Table 1: Ablation Experiments. Analysing the learning dynamics We can further test our hypothesis that our regularisation, com- bined with the learning dynamics, divides learning into an exploration phase, wherein an optimal mask is discovered, and a refinement phase. To do so, we take a standard training run of 32000 steps and artificially stop the gradient updates to the ‘extra’ units not active in the forward pass (B \ A). We do so at different points of training (marked t in Table 1) — start of training (t = 0), t = 5000, or halfway through. We find that removing all exploration units entirely (t = 0) is very harmful for performance, but training for just 5000 steps with these considerably boosts performance. At t = 16000 we have recovered most of the benefits of our method. This provides evidence that for the latter half of training, the gradients fine-tune performance on the learnt mask which stays more or less constant. Analysing the mask dynamics We can further analyse how the mask changes through time. We take a standard training run as above with forward sparsity of 80% and backward sparsity of 50%. We first measure the difference in the sparsity masks m at pairs of points 5, 000 steps apart in training — i.e. (mt−mt+5000)2 — the fraction of units that change (m = 1 if the weight is active, else m = 0). This is summarised in figure 3 where we show the percentage change in masks across time (we plot min, mean and max across layers). We find that the mask indeed stabilises over time. We can further assess what units that are in set C or the reservoir — units used in neither the forward nor backward passes at initialisation — ever turn on. We find that only about 5% of these units are ever used and most of this change occurs at the start of training. This provides more evidence for the exploration and learning dynamics that motivate our design choices. Change in Top-KAST Masks for 80% Sparsity Change in Top-KAST Masks Ese aso Top-KAST on enwik8 a & MetricAcross Layes|| © Metric Across Layers Forward Sparsity g x, . in aaas Forward Spa aad é*r S. — Mesn 5 os % . == Max § 1100 i= ES (ek el = © \ 1 1075 £15 & é FA a2 © 050 eg. $ \ F) Es 21 \ im 1.025 —— o oa) 7 1.000 ‘Dense ° €o _S--_-_S © 5000 10000 15000 20000 25000 30000 9 S000 10000 15000 20000 25000 30000 00 OF ckwatd sparsity 08 Steps of Training Steps of Training jackward Sparsity Figure 3: (a) shows that the mask gradually stabilises over time. (b) further, the number of units in set C that make it to the active set A is relatively small and also tends to 0. 7 # 5 Experiments: Language Modeling One class of models which have benefited hugely from a greater number of training parameters is language models, notably using the Transformer architecture [41] [32]. Language models predict the probability of strings of text, typically by tokenizing the text into a sequence of integers xo, ... , x; (e.g. characters or words) and then decomposing the joint probability p(xo,..., 21) of this sequence into a product of conditional probabilities p(xo) []/_, p(wila<i). Language model performance has been observed to follow a power-law of improvement when the data and model parameters are increased [18]. One challenge large parameter sets bring, is an increased strain on memory bandwidth to store the parameters. Approaches which can train and evaluate to comparable performance using less parameters can facilitate eventual training of larger models. We try Top-KAST to train language models on two commonly-benchmarked datasets: Enwik8 [24] which is a character-level benchmark derived from the Hutter Prize and WikiText-103 which is a word- level language model benchmark. We use a long-range Transformer variant, the Transformer-XL [6]; training hyper-parameters are displayed in Supplementary Section[A] Model Params BPC Transformer-XL [6] 277M 0.99 Stacked LSTM [12] Hypernetworks [13] mLSTM [19] Transformer-XL [6] All-Attention Transf. [38] Top-KAST (80%, 0%) Top-KAST (80%, 80%) Top-KAST (90%, 60%) 21.3M 1.67 1.34 27M 1.24 46M 1.06 44M 1.01 39M 1.00 55M 55M 1.02 27.7M 1.03 Fwd Bwd Params Perplexity 0% 0% 0% 0% 285M 94M 18.3 21.5 57M 80% 0% 80% 60% 57M 90% 80% 28.5M 95% 90% 14.3M 19.8 21.3 25.1 32.2 Table 2: Enwik8: test BPC of small models. On Enwik8, the baseline 24-layer dense Transformer-XL obtains 0.99 bits-per-character (BPC). We apply Top-KAST to training this model and vary the forward and backward sparsity rates as shown in Figure 3 (c). We find that we can obtain results comparable to the dense model all the way up to 80% sparsity. When comparing to previously published models that were trained and evaluated at a modest parameter count (under 60M parameters) in Table 2 we see that our Transformer-XL + Top-KAST achieves state-of-the-art performance. We also compare to magnitude pruning for a smaller Transformer model in appendix A. On WikiText-103 our baseline 16-layer Transformer-XL obtains 18.3 test perplexity. When trained with Top-KAST, we see in Table 3 that we can achieve 80% sparsity with minimal performance degradation, and performance begins to drift beyond the 90% sparsity range. Most importantly, the sparse model is significantly better than the even the smaller dense model with 3× as many parameters. # 6 Conclusion In this work, we considered the question of effectively and efficiently training sparse neural networks. Performant sparse networks promise to democratise research with their low-resource usage, provide savings on compute and memory and also allow the proportional scaling up of model sizes. Prior works have shown the efficacy of pruning dense neural networks to highly sparse equivalents that are able to retain most of their original performance. Motivated by these successes, more recent works have attempted to maintain fully sparse networks throughout training. While a lot of progress has been made, most of these still involve the calculation of some dense weights or gradients, or involve operations that cannot be efficiently implemented with today’s tools. Building on this, we introduced a novel method, Top-KAST that stays fully sparse in the both the backward and forward passes and is able to be implemented easily with modern neural network packages. Our method involves keeping around only the highest weights by magnitude in the forward pass and an extra set 8 of exploration weights in the backward. Practitioners can choose their own values for both sparsities, based on the resource budget available. We further introduced a novel form of regularisation to encourage exploration in weight space. Coupled with this loss, Top-KAST achieves comparable performance to existing dense-to-sparse methods on ImageNet while remaining sparse, and exceeding the performance of several sparse-to-sparse methods. We further demonstrated the efficacy of our method on language modeling, the first such method to successfully sparsify Transformers in this context. We’re also able to achieve state-of-art results for small models, with 1.00 bpc at 55M parameters (versus a baseline of 0.99 at 277M parameters). While these are encouraging findings, more work is required to fully integrate Top-KAST with sparse hardware and the appropriate sparse kernels. We hope practioners and researchers alike find our method useful for reducing computational requirements, and to build on for even more powerful methods of sparsification. # Acknowledgements We’d like to thank Jacob Menick, Karen Simonyan, Tim Harley and Malcolm Reynolds for their helpful feedback throughout the project. We’d also like to thank Utku Evci for their help with running baselines for the ImageNet experiments. # Broader Impact Our work proposes a new method to train sparse neural networks that allows them to remain sparse throughout training – thereby enabling a practitioner to increase the model size that can be trained on a given piece of hardware. (This would also impact deployment too, in the case of on-device or real- time learning.) As we note in our introduction this scale-enabling should benefit the democratisation of deep learning since state-of-the-art models are ever increasing in size. Furthermore, there are beneficial impacts to be expected by reducing the computational footprint and energy consumption for training neural networks, as well as the higher-order impacts achieved if our work promotes the adoption of sparse networks more broadly – thereby also reducing the deployment/inference costs. While we do not expect any direct negative consequences from this work, the proposed method is general and widely applicable. We believe that the benefits offered by advances in machine learning net outweigh (by a significant margin) the potential risks and negative consequences. However, the technology as a whole is not purely good or benign. As one suggestion for future research building on our contribution, we would encourage colleagues who extend or apply our work to help us assess whether the inductive biases promoted by our sparsification methods have lead to any differential sensitivity to class imbalances or other aspects of the underlying data, relative to dense counterpart approaches for a given application. Since such issues could exacerbate problems related to algorithmic bias. # References [1] A highly efficient real-time text-to-speech system deployed on cpus. URL https://ai.facebook.com/ blog/a-highly-efficient-real-time-text-to-speech-system-deployed-on-cpus/. [2] Alexei Baevski and Michael Auli. Adaptive input representations for neural language modeling. In International Conference on Learning Representations, 2019. URL https://openreview.net/forum? id=ByxZX20qFQ. [3] Guillaume Bellec, David Kappel, Wolfgang Maass, and Robert A. Legenstein. Deep rewiring: Training very sparse deep networks. In International Conference on Learning Representations, 2018. [4] Ronen I. Brafman and Moshe Tennenholtz. R-max - a general polynomial time algorithm for near-optimal reinforcement learning. J. Mach. Learn. Res., 3(null):213–231, March 2003. ISSN 1532-4435. doi: 10.1162/153244303765208377. URL https://doi.org/10.1162/153244303765208377. [5] Diederik P. Kingma Christos Louizos, Max Welling. Learning sparse neural networks through l0 regular- ization. In International Conference on Learning Representations, 2018. [6] Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V Le, and Ruslan Salakhutdi- arXiv preprint nov. Transformer-xl: Attentive language models beyond a fixed-length context. arXiv:1901.02860, 2019. 9 [7] Utku Evci, Trevor Gale, Jacob Menick, Pablo Samuel Castro, and Erich Elsen. Rigging the lottery: Making all tickets winners, 2019. [8] Utku Evci, Fabian Pedregosa, Aidan N. Gomez, and Erich Elsen. The difficulty of training sparse neural networks. ArXiv, 2019. URL http://arxiv.org/abs/1906.10732. [9] Jonathan Frankle and Michael Carbin. The lottery ticket hypothesis: Finding sparse, trainable neural networks. In 7th International Conference on Learning Representations, ICLR 2019, New Orleans, LA, USA, May 6-9, 2019, 2019. URL https://openreview.net/forum?id=rJl-b3RcF7. [10] Trevor Gale, Erich Elsen, and Sara Hooker. The state of sparsity in deep neural networks. CoRR, abs/1902.09574, 2019. URL http://arxiv.org/abs/1902.09574. [11] Eva García-Martín, Crefeda Faviola Rodrigues, Graham Riley, and Håkan Grahn. Estimation of energy consumption in machine learning. Journal of Parallel and Distributed Computing, 134:75 – 88, 2019. ISSN 0743-7315. doi: https://doi.org/10.1016/j.jpdc.2019.07.007. URL http://www.sciencedirect. com/science/article/pii/S0743731518308773. [12] Alex Graves. Generating sequences with recurrent neural networks. arXiv preprint arXiv:1308.0850, 2013. [13] David Ha, Andrew Dai, and Quoc V Le. Hypernetworks. arXiv preprint arXiv:1609.09106, 2016. [14] Song Han, Jeff Pool, John Tran, and William Dally. Learning both weights and connections for efficient neural network. In Advances in neural information processing systems, 2015. [15] Y. He, T. N. Sainath, R. Prabhavalkar, I. McGraw, R. Alvarez, D. Zhao, D. Rybach, A. Kannan, Y. Wu, R. Pang, Q. Liang, D. Bhatia, Y. Shangguan, B. Li, G. Pundak, K. C. Sim, T. Bagby, S. Chang, K. Rao, and A. Gruenstein. Streaming end-to-end speech recognition for mobile devices. In ICASSP 2019 - 2019 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), pages 6381–6385, 2019. [16] Norman P Jouppi, Cliff Young, Nishant Patil, David Patterson, Gaurav Agrawal, Raminder Bajwa, Sarah Bates, Suresh Bhatia, Nan Boden, Al Borchers, et al. In-datacenter performance analysis of a tensor processing unit. In Proceedings of the 44th Annual International Symposium on Computer Architecture, pages 1–12, 2017. [17] Nal Kalchbrenner, Erich Elsen, Karen Simonyan, Seb Noury, Norman Casagrande, Edward Lockhart, Florian Stimberg, Aaron Oord, Sander Dieleman, and Koray Kavukcuoglu. Efficient neural audio synthesis. In International Conference on Machine Learning (ICML), 2018. [18] 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, 2020. [19] Ben Krause, Liang Lu, Iain Murray, and Steve Renals. Multiplicative lstm for sequence modelling. arXiv preprint arXiv:1609.07959, 2016. [20] Aditya Kusupati, Vivek Ramanujan, Raghav Somani, Mitchell Wortsman, Prateek Jain, Sham Kakade, and Ali Farhadi. Soft threshold weight reparameterization for learnable sparsity, 2020. [21] Yann LeCun, John S. Denker, and Sara A. Solla. Optimal Brain Damage. In Advances in Neural Information Processing Systems, 1990. [22] Karel Lenc, Erich Elsen, Tom Schaul, and Karen Simonyan. Non-differentiable supervised learning with evolution strategies and hybrid methods. CoRR, abs/1906.03139, 2019. URL http://arxiv.org/abs/ 1906.03139. [23] J. Lin, W. Yu, N. Zhang, X. Yang, H. Zhang, and W. Zhao. A survey on internet of things: Architecture, enabling technologies, security and privacy, and applications. IEEE Internet of Things Journal, 4(5): 1125–1142, 2017. [24] Matt Mahoney. Large text compression benchmark. URL: http://www. mattmahoney. net/text/text. html, 2011. [25] Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher. Pointer sentinel mixture models. arXiv preprint arXiv:1609.07843, 2016. [26] Decebal Constantin Mocanu, Elena Mocanu, Peter Stone, Phuong H Nguyen, Madeleine Gibescu, and Antonio Liotta. Scalable training of artificial neural networks with adaptive sparse connectivity inspired by network science. Nature Communications, 2018. 10 [27] Dmitry Molchanov, Arsenii Ashukha, and Dmitry P. Vetrov. Variational Dropout Sparsifies Deep Neural Networks. In Proceedings of the 34th International Conference on Machine Learning, ICML 2017, Sydney, NSW, Australia, 6-11 August 2017, pages 2498–2507, 2017. [28] Hesham Mostafa and Xin Wang. Parameter efficient training of deep convolutional neural networks by dynamic sparse reparameterization. In Proceedings of the 36th International Conference on Machine Learning, ICML 2019, 9-15 June 2019, Long Beach, California, USA, pages 4646–4655, 2019. URL http://proceedings.mlr.press/v97/mostafa19a.html. [29] Sharan Narang, Greg Diamos, Shubho Sengupta, and Erich Elsen. Exploring sparsity in recurrent neural networks. In 5th International Conference on Learning Representations, ICLR 2017, Toulon, France, April 24-26, 2017, Conference Track Proceedings, 2017. URL https://openreview.net/forum?id= BylSPv9gx. [30] NVIDIA. Nvidia a100 tensor core gpu architecture, 2020. URL https://www.nvidia.com/content/ dam/en-zz/Solutions/Data-Center/nvidia-ampere-architecture-whitepaper.pdf. [31] Ruoming Pang, Tara Sainath, Rohit Prabhavalkar, Suyog Gupta, Yonghui Wu, Shuyuan Zhang, and Chung- Cheng Chiu. Compression of end-to-end models. In Proc. Interspeech 2018, pages 27–31, 2018. doi: 10.21437/Interspeech.2018-1025. URL http://dx.doi.org/10.21437/Interspeech.2018-1025. [32] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. OpenAI Blog, 1(8):9, 2019. [33] Roy Schwartz, Jesse Dodge, Noah A. Smith, and Oren Etzioni. Green AI. arXiv e-prints, art. arXiv:1907.10597, Jul 2019. [34] Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. Megatron-lm: Training multi-billion parameter language models using model parallelism, 2019. [35] Kenneth O. Stanley and Risto Miikkulainen. Evolving neural networks through augmenting topologies. Evol. Comput., 10(2):99–127, June 2002. ISSN 1063-6560. doi: 10.1162/106365602320169811. URL https://doi.org/10.1162/106365602320169811. [36] Nikko Ström. Sparse Connection and Pruning in Large Dynamic Artificial Neural Networks. In EU- ROSPEECH, 1997. [37] Emma Strubell, Ananya Ganesh, and Andrew McCallum. Energy and policy considerations for deep learning in nlp. In ACL, 2019. [38] Sainbayar Sukhbaatar, Edouard Grave, Guillaume Lample, Herve Jegou, and Armand Joulin. Augmenting self-attention with persistent memory. arXiv preprint arXiv:1907.01470, 2019. [39] Mingxing Tan and Quoc Le. EfficientNet: Rethinking model scaling for convolutional neural networks. 97:6105–6114, 09–15 Jun 2019. URL http://proceedings.mlr.press/v97/tan19a.html. [40] Georg Thimm and Emile Fiesler. Evaluating pruning methods. In National Chiao-Tung University, page 2, 1995. [41] 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, pages 5998–6008, 2017. [42] Mitchell Wortsman, Ali Farhadi, and Mohammad Rastegari. Discovering neural wirings. In H. Wallach, H. Larochelle, A. Beygelzimer, F. dÁlché Buc, E. Fox, and R. Garnett, editors, Advances in Neural Information Processing Systems 32, pages 2684–2694. Curran Associates, Inc., 2019. URL http:// papers.nips.cc/paper/8536-discovering-neural-wirings.pdf. [43] J. Zhang, B. Chen, Y. Zhao, X. Cheng, and F. Hu. Data security and privacy-preserving in edge computing paradigm: Survey and open issues. IEEE Access, 6:18209–18237, 2018. [44] Hattie Zhou, Janice Lan, Rosanne Liu, and Jason Yosinski. Deconstructing Lottery Tickets: Zeros, Signs, and the Supermask. ArXiv, 2019. [45] Michael Zhu and Suyog Gupta. To Prune, or Not to Prune: Exploring the Efficacy of Pruning for Model Compression. In International Conference on Learning Representations Workshop, 2018. 11 # Supplementary # A Language Modeling We train our Transformer-XL models with a very similar setup to Dai et al. [6]. The dense model hyper- parameters are listed in Table 4. We train with a learning rate warmup for 4000 steps from 1e-7 up to a value of 2e-4 and then apply a cosine decay. For WikiText-103 and enwik8 our dense model uses the same specification as the large Transformer-XL in Dai et al. [6], which has 285M parameters4. Enwik8 WikiText-103 num layers dmodel df f dembed tie input/output embeddings num heads dropout learning rate grad clip by global norm window size train mem size eval mem size num params 24 1024 3072 512 true 8 0.05-0.2 2e-4 0.25 768 2304 5000 69M 18 1024 4096 adaptive: [2] tie head only: [2] 16 0.05 - 0.2 2e-4 0.25 512 768 2000 285M Table 4: Transformer-XL baseline hyper-parameters. We further compare to a magnitude pruning baseline on enwik8. We found we were unable to implement this with the large model due to the additional memory requirements. Instead we compare Top-KAST and pruning on a smaller version of the Transformer-XL model of 69M parameters. This has identical training and hyper-parameters to below with the exception of dmodel = 512, df f = 1536 and numheads = 8. We summarise the results below. We find that pruning slightly outperforms Top-KAST when Top-KAST is allowed a dense backward (albeit the forward pass is also sparse). However, Top-KAST is competitive even in the regime of sparse backward passes. Fwd Bwd Params Pruning BPC Top-KAST BPC 0% 0% 69M 1.00 1.00 80% 0% 80% 60% 90% 0% 90% 80% 95% 0% 95% 90% 14M 14M 7M 7M 1.4M 1.4M 1.02 - 1.06 - 1.13 - 1.03 1.05 1.08 1.10 1.14 1.17 Table 5: enwik8: test perplexity for the smaller transformer model. # B ImageNet For all ImageNet experiments we use a ResNet-50 set up as in prior work [10]. We use a batch size of 4096 and train for 32000 steps. We use use a learning rate of 1.6 (with a linear ramp up for 5 epochs) followed by learning rate drops by factors of 0.1 at 30, 70 and 90 epochs. For Top-KAST we use a weight decay of 1e − 4, and train for a range of backward and forward sparsity rates. For our experiments we keep the first and last layers dense as in previous works [10, 7]. We also relax the assumption and show below the performance if all layers are sparsified. 4The original publication erroneously listed 255M parameters, however it has been clarified as 285M with the authors. 12 All Layers Sparsified (1x Training) fa ra g 7: < Forward Sparsities a71 N rf — 08 (5) £70 — 0915) ==) 0.8 (D) 69 == 0.90) 68 0.0 0.2 04 0.6 08 10 Backward Sparsities # C Implementation of RigL and Top-KAST In the sections above we compared briefly the implementations of RigL and Top-KAST and argued the relative ease of implementing Top-KAST because of some of the practical constraints a theoretically sparse implementation of RigL faces. We first detail how RigL might actually be implemented and the difficulties that would be encountered. RigL occasionally requires calculating the Top-K values and locations of the full dense gradient with respect the parameters for every layer. The usual framework encapsulation is that all the gradients are computed and then sent to the optimiser. Doing the Top-K in the optimiser has the advantage of not needing modify the gradient calculations, but the large downside of meaning that the dense gradient would need to be materialised. This means the Top-K must happen inside the gradient calculation. The type returned by the gradient calculation must be consistent, so it must always return both gradient values and locations and it must accept as arguments locations and a step count. If the step count indicates a Top-K over a dense gradient is to be performed, then input locations are ignored and the output locations contain updated locations. Otherwise, the input locations are used and simply copied to the output. Inside the actual gradient calculation, it must ‘chunk’ the calculation of the dense gradient so as maintain a bound on the memory required. Assuming a data parallel regime, after each chunk is calculated locally, it must then be all-reduced. Then on each replica the running Top-K values are concatenated with the gradient chunk and a new running Top-K is calculated from this list. This process must proceed completely serially to maintain the memory bounds. The serialisation introduces some perhaps non-trivial overheads, but most problematic is that no gradient calculations currently work like this. Every gradient calculation would need to re-written to do the appropriate chunking, this is both a high burden as this code involve rewriting a great deal of code. And it also introduces its own performance ramifications. Common libraries and/or data formats, especially for convolutions, might not support strides that would be necessary to compute arbitrary output shapes. If they do, it might come with negative performance implications. Lastly, we show results for an implementation of Top-KAST that only requires calculating the Top-K every N steps, where N = 100 (as opposed to N = 1, which corresponds to performing this every iteration). Such an implementation only requires occasional communication of the indices and weights and the Top-K operation can be calculated in parallel on CPU as it does not require any data or forward passes. The accelerator need only know the actual sparse weights and can be implemented entirely sparsely. We run Top-KAST for a variety of sparsity fractions and report the results below: Fwd Bwd N = 1 N = 100 80% 50% 75.03 90% 80% 73.03 95% 90% 70.42 75.14 73.18 70.38 Table 6: Top-KAST at different frequencies of Top-K # D Pseudocode In general Top-KAST can be implemented by modifying the parameters used in the forward pass and applying a gradient with respect to only some of the weighs in the backward pass. Below we demonstrate how this could be implemented with existing dense kernels and explicit masking of the weights. For a truly sparse implementation, custom sparse kernels would be required. 13 Algorithm 1 TopKAST // First perform a Top-K dense_params = initialise() fwd_params = TopK(dense_params, X%) bwd_params = TopK(dense_params, Y%) just_bwd_set = set(bwd_params) - set(fwd_params) ... // Output with just the TopK params output = model(fwd_params, input) loss = loss_fn(output) // Exploration L2 Loss loss += l2(fwd_params) + l2(just_bwd_set) / (X/100) ... // Update only the bwd params bwd_params = bwd_params - grad(loss, bwd_params) 14
Title: Overcoming Exploration in Reinforcement Learning with Demonstrations: Summary: Exploration in environments with sparse rewards has been a persistent problem in reinforcement learning (RL). Many tasks are natural to specify with a sparse reward, and manually shaping a reward function can result in suboptimal performance. However, finding a non-zero reward is exponentially more difficult with increasing task horizon or action dimensionality. This puts many real-world tasks out of practical reach of RL methods. In this work, we use demonstrations to overcome the exploration problem and successfully learn to perform long-horizon, multi-step robotics tasks with continuous control such as stacking blocks with a robot arm. Our method, which builds on top of Deep Deterministic Policy Gradients and Hindsight Experience Replay, provides an order of magnitude of speedup over RL on simulated robotics tasks. It is simple to implement and makes only the additional assumption that we can collect a small set of demonstrations. Furthermore, our method is able to solve tasks not solvable by either RL or behavior cloning alone, and often ends up outperforming the demonstrator policy. # Overcoming Exploration in Reinforcement Learning with Demonstrations Ashvin Nair12, Bob McGrew1, Marcin Andrychowicz1, Wojciech Zaremba1, Pieter Abbeel12 Abstract— Exploration in environments with sparse rewards has been a persistent problem in reinforcement learning (RL). Many tasks are natural to specify with a sparse reward, and manually shaping a reward function can result in suboptimal performance. However, finding a non-zero reward is exponen- tially more difficult with increasing task horizon or action dimensionality. This puts many real-world tasks out of practical reach of RL methods. In this work, we use demonstrations to overcome the exploration problem and successfully learn to perform long-horizon, multi-step robotics tasks with continuous control such as stacking blocks with a robot arm. Our method, which builds on top of Deep Deterministic Policy Gradients and Hindsight Experience Replay, provides an order of magnitude of speedup over RL on simulated robotics tasks. It is simple to implement and makes only the additional assumption that we can collect a small set of demonstrations. Furthermore, our method is able to solve tasks not solvable by either RL or behavior cloning alone, and often ends up outperforming the demonstrator policy. # I. INTRODUCTION RL has found significant success in decision making for solving games, so what makes it more challenging to apply in robotics? A key difference is the difficulty of exploration, which comes from the choice of reward function and compli- cated environment dynamics. In games, the reward function is usually given and can be directly optimized. In robotics, we often desire behavior to achieve some binary objective (e.g., move an object to a desired location or achieve a certain state of the system) which naturally induces a sparse reward. Sparse reward functions are easier to specify and recent work suggests that learning with a sparse reward results in learned policies that perform the desired objective instead of getting stuck in local optima [1], [2]. However, exploration in an environment with sparse reward is difficult since with random exploration, the agent rarely sees a reward signal. The difficulty posed by a sparse reward is exacerbated by the complicated environment dynamics in robotics. For example, system dynamics around contacts are difficult to model and induce a sensitivity in the system to small errors. Many robotics tasks also require executing multiple steps successfully over a long horizon, involve high dimensional control, and require generalization to varying task instances. These conditions further result in a situation where the agent so rarely sees a reward initially that it is not able to learn at all. All of the above means that random exploration is not a tenable solution. Instead, in this work we show that we can use demonstrations as a guide for our exploration. To test our method, we solve the problem of stacking several blocks at a given location from a random initial state. Stacking blocks has been studied before in the literature [3], [4] and exhibits many of the difficulties mentioned: long horizons, contacts, and requires generalizing to each instance of the task. We limit ourselves to 100 human demonstrations collected via teleoperation in virtual reality. Using these demonstrations, we are able to solve a complex robotics task in simulation that is beyond the capability of both reinforcement learning and imitation learning. The primary contribution of this paper is to show that demonstrations can be used with reinforcement learning to solve complex tasks where exploration is difficult. We introduce a simple auxiliary objective on demonstrations, a method of annealing away the effect of the demonstrations when the learned policy is better than the demonstrations, and a method of resetting from demonstration states that significantly improves and speeds up training policies. By effectively incorporating demonstrations into RL, we short- circuit the random exploration phase of RL and reach nonzero rewards and a reasonable policy early on in training. Finally, we extensively evaluate our method against other commonly used methods, such as initialization with learning from demonstrations and fine-tuning with RL, and show that our method significantly outperforms them. # II. RELATED WORK Learning methods for decision making problems such as robotics largely divide into two classes: imitation learning and reinforcement learning (RL). In imitation learning (also called learning from demonstrations) the agent receives be- havior examples from an expert and attempts to solve a task by copying the expert’s behavior. In RL, an agent attempts to maximize expected reward through interaction with the environment. Our work combines aspects of both to solve complex tasks. Imitation Learning: Perhaps the most common form of imitation learning is behavior cloning (BC), which learns a policy through supervised learning on demonstration state- action pairs. BC has seen success in autonomous driving [5], [6], quadcopter navigation [7], locomotion [8], [9]. BC struggles outside the manifold of demonstration data. Dataset Aggregation (DAGGER) augments the dataset by interleaving the learned and expert policy to address this problem of accumulating errors [10]. However, DAGGER is difficult to use in practice as it requires access to an expert during all of training, instead of just a set of demonstrations. 1 OpenAI, 2 University of California, Berkeley. Fig. 1: We present a method using reinforcement learning to solve the task of block stacking shown above. The robot starts with 6 blocks labelled A through F on a table in random positions and a target position for each block. The task is to move each block to its target position. The targets are marked in the above visualization with red spheres which do not interact with the environment. These targets are placed in order on top of block A so that the robot forms a tower of blocks. This is a complex, multi-step task where the agent needs to learn to successfully manage multiple contacts to succeed. Frames from rollouts of the learned policy are shown. A video of our experiments can be found at: http://ashvin.me/demoddpg-website Fundamentally, BC approaches are limited because they do not take into account the task or environment. Inverse reinforcement learning (IRL) [11] is another form of imita- tion learning where a reward function is inferred from the demonstrations. Among other tasks, IRL has been applied to navigation [12], autonomous helicopter flight [13], and manipulation [14]. Since our work assumes knowledge of a reward function, we omit comparisons to IRL approaches. Reinforcement Learning: Reinforcement learning meth- ods have been harder to apply in robotics, but are heavily investigated because of the autonomy they could enable. Through RL, robots have learned to play table tennis [15], swing up a cartpole, and balance a unicycle [16]. A renewal of interest in RL cascaded from success in games [17], [18], especially because of the ability of RL with large function approximators (ie. deep RL) to learn control from raw pixels. Robotics has been more challenging in general but there has been significant progress. Deep RL has been applied to manipulation tasks [19], grasping [20], [21], opening a door [22], and locomotion [23], [24], [25]. However, results have been attained predominantly in simulation per high sample complexity, typically caused by exploration challenges. learning forward models naturally have trouble modelling the sharply discontinuous dynamics of contacts; although they can learn to place a block, it is a much harder problem to grasp the block in the first place. One-shot Imitation [4] learns to stack blocks in a way that generalizes to new target configurations, but uses more than 100,000 demonstrations to train the system. A heavily shaped reward can be used to learn to stack a Lego block on another with RL [30]. In contrast, our method can succeed from fully sparse rewards and handle stacking several blocks. Combining RL and Imitation Learning: Previous work has combined reinforcement learning with demonstrations. Demonstrations have been used to accelerate learning on classical tasks such as cart-pole swing-up and balance [31]. This work initialized policies and (in model-based methods) initialized forward models with demonstrations. Initializing policies from demonstrations for RL has been used for learning to hit a baseball [32] and for underactuated swing- up [33]. Beyond initialization, we show how to extract more knowledge from demonstrations by using them effectively throughout the entire training process. Robotic Block Stacking: Block stacking has been studied from the early days of AI and robotics as a task that encapsulates many difficulties of more complicated tasks we want to solve, including multi-step planning and complex contacts. SHRDLU [26] was one of the pioneering works, but studied block arrangements only in terms of logic and natural language understanding. More recent work on task and motion planning considers both logical and physical aspects of the task [27], [28], [29], but requires domain- specific engineering. In this work we study how an agent the need of domain-specific can learn this task without engineering. One RL method, PILCO [16] has been applied to a simple version of stacking blocks where the task is to place a block on a tower [3]. Methods such as PILCO based on to two recent approaches — Deep Q-Learning From Demonstrations (DQfD) [34] and DDPG From Demonstrations (DDPGfD) [2] which combine demonstrations with reinforcement learning. DQfD improves learning speed on Atari, including a margin loss which encourages the expert actions to have higher Q-values than all other actions. This loss can make improving upon the demonstrator policy impossible which is not the case for our method. Prior work has previously explored improving beyond the demonstrator policy in simple environments by introducing slack variables [35], but our method uses a learned value to actively inform the improvement. DDPGfD solves simple robotics tasks akin to peg insertion using DDPG with demonstrations in the replay buffer. In contrast to this prior work, the tasks we consider exhibit additional difficulties that are of key interest in robotics: multi-step behaviours, and generalization to varying goal states. While previous work focuses on speeding up already solvable tasks, we show that we can extend the state of the art in RL with demonstrations by introducing new methods to incorporate demonstrations. # III. BACKGROUND A. Reinforcement Learning We consider the standard Markov Decision Process frame- work for picking optimal actions to maximize rewards over discrete timesteps in an environment EL. We assume that the environment is fully observable. At every timestep t, an agent is in a state 2, takes an action a;, receives a reward r;, and E evolves to state x;41. In reinforcement learning, the agent must learn a policy a, = m(x,) to maximize expected returns. We denote the return by R; = ve, 79 r;, where T is the horizon that the agent optimizes over and 7¥ is a discount factor for future rewards. The agent’s objective is to maximize expected return from the start distribution J = Ep,.s:~B,a:~[Ro]- A variety of reinforcement learning algorithms have been developed to solve this problem. Many involve constructing an estimate of the expected return from a given state after taking an action: Qπ(st, at) = Eri,si∼E,ai∼π[Rt|st, at] (1) = Ert,st+1∼E[rt + γ Eat+1∼π[Qπ(st+1, at+1)]] (2) We call Qπ the action-value function. Equation 2 is a recursive version of equation 1, and is known as the Bell- man equation. The Bellman equation allows for methods to estimate Q that resemble dynamic programming. # B. DDPG Our method combines demonstrations with one such method: Deep Deterministic Policy Gradients (DDPG) [23]. DDPG is an off-policy model-free reinforcement learning algorithm for continuous control which can utilize large function approximators such as neural networks. DDPG is an actor-critic method, which bridges the gap between policy gradient methods and value approximation methods for RL. At a high level, DDPG learns an action-value function (critic) by minimizing the Bellman error, while simultaneously learning a policy (actor) by directly maxi- mizing the estimated action-value function with respect to the parameters of the policy. Concretely, DDPG maintains an actor function π(s) with parameters θπ, a critic function Q(s, a) with parameters θQ, and a replay buffer R as a set of tuples (st, at, rt, st+1) for each transition experienced. DDPG alternates between running the policy to collect experience and updating the parameters. Training rollouts are collected with extra noise for exploration: at = π(s) + N , where N is a noise process. During each training step, DDPG samples a minibatch consisting of N tuples from R to update the actor and critic networks. DDPG minimizes the following loss L w.r.t. θQ to update the critic: yi = ri + γQ(si+1, π(si+1)) (3) 1 L=5 diy = Q(si, ai|9Q))” (4) The actor parameters θπ are updated using the policy gradient: 1 Vo,J = id DS VaQ(s, a|9Q)|s=s;,a=n(s) V0, 7(5|Ox) Si (5) (5) To stabilize learning, the Q value in equation 3 is usually computed using a separate network (called the target net- work) whose weights are an exponential average over time of the critic network. This results in smoother target values. Note that DDPG is a natural fit for using demonstra- tions. Since DDPG can be trained off-policy, we can use demonstration data as off-policy training data. We also take advantage of the action-value function Q(s, a) learned by DDPG to better use demonstrations. C. Multi-Goal RL Instead of the standard RL setting, we train agents with parametrized goals, which lead to more general policies [36] and have recently been shown to make learning with sparse rewards easier [1]. Goals describe the task we expect in our case the agent they specify the desired positions of all objects. We sample the goal g at he beginning of every episode. The function approximators, here π and Q, take the current goal as an additional input. D. Hindsight Experience Replay (HER) To handle varying task instances and parametrized goals, we use Hindsight Experience Replay (HER) [1]. The key insight of HER is that even in failed rollouts where no reward was obtained, the agent can transform them into successful ones by assuming that a state it saw in the rollout was the actual goal. HER can be used with any off-policy RL algorithm assuming that for every state we can find a goal corresponding to this state (i.e. a goal which leads to a positive reward in this state). For every episode the agent experiences, we store it in the replay buffer twice: once with the original goal pursued in the episode and once with the goal corresponding to the final state achieved in the episode, as if the agent intended on reaching this state from the very beginning. # IV. METHOD Our method combines DDPG and demonstrations in sev- eral ways to maximally use demonstrations to improve learning. We describe our method below and evaluate these ideas in our experiments. A. Demonstration Buffer First, we maintain a second replay buffer RD where we store our demonstration data in the same format as R. In each minibatch, we draw an extra ND examples from RD to use as off-policy replay data for the update step. These examples are included in both the actor and critic update. This idea has been introduced in [2]. B. Behavior Cloning Loss Second, we introduce a new loss computed only on the demonstration examples for training the actor. Np Lec = > |r(si i=l Or) — ail” (6) This loss is a standard loss in imitation learning, but we show that using it as an auxiliary loss for RL improves learning significantly. The gradient applied to the actor parameters θπ is: λ1∇θπ J − λ2∇θπ LBC (7) (Note that we maximize J and minimize LBC.) Using this loss directly prevents the learned policy from improving significantly beyond the demonstration policy, as the actor is always tied back to the demonstrations. Next, we show how to account for suboptimal demonstrations using the learned action-value function. # C. Q-Filter We account for the possibility that demonstrations can be suboptimal by applying the behavior cloning loss only to states where the critic Q(s, a) determines that the demon- strator action is better than the actor action: Np Lac => |r (si|9e) = ail” Necea)>Q(s,.m(s)) 8) i=1 The gradient applied to the actor parameters is as in equation 7. We label this method using the behavior cloning loss and Q-filter “Ours” in the following experiments. D. Resets to demonstration states To overcome the problem of sparse rewards in very long horizon tasks, we reset some training episodes using states and goals from demonstration episodes. Restarts from within demonstrations expose the agent to higher reward states dur- ing training. This method makes the additional assumption that we can restart episodes from a given state, as is true in simulation. To reset to a demonstration state, we first sample a demonstration D = (x0, u0, x1, u1, ...xN , uN ) from the set of demonstrations. We then uniformly sample a state xi from D. As in HER, we use the final state achieved in the demonstration as the goal. We roll out the trajectory with the given initial state and goal for the usual number of timesteps. At evaluation time, we do not use this procedure. We label our method with the behavior cloning loss, Q- filter, and resets from demonstration states as “Ours, Resets” in the following experiments. # V. EXPERIMENTAL SETUP # A. Environments We evaluate our method on several simulated MuJoCo [37] environments. In all experiments, we use a simulated 7-DOF Fetch Robotics arm with parallel grippers to manipulate one or more objects placed on a table in front of the robot. The agent receives the positions of the relevant objects on the table as its observations. The control for the agent is continuous and 4-dimensional: 3 dimensions that specify the desired end-effector position1 and 1 dimension that specifies the desired distance between the robot fingers. The agent is controlled at 50Hz frequency. We collect demonstrations in a virtual reality environment. The demonstrator sees a rendering of the same observations as the agent, and records actions through a HTC Vive interface at the same frequency as the agent. We have the option to accept or reject a demonstration; we only accept demonstrations we judge to be mostly correct. The demonstrations are not optimal. The most extreme example is the “sliding” task, where only 7 of the 100 demonstrations are successful, but the agent still sees rewards for these demonstrations with HER. # B. Training Details To train our models, we use Adam [38] as the optimizer with learning rate 10−3. We use N = 1024, ND = 128, λ1 = 10−3, λ2 = 1.0/ND. The discount factor γ is 0.98. We use 100 demonstrations to initialize RD. The function approxi- mators π and Q are deep neural networks with ReLU activa- tions and L2 regularization with the coefficient 5×10−3. The final activation function for π is tanh, and the output value is scaled to the range of each action dimension. To explore during training, we sample random actions uniformly within the action space with probability 0.1 at every step, and the noise process N is uniform over ±10% of the maximum value of each action dimension. Task-specific information, including network architectures, are provided in the next section. C. Overview of Experiments We perform three sets of experiments. In Sec. VI, we provide a comparison to previous work. In Sec. VII we solve block stacking, a difficult multi-step task with complex contacts that the baselines struggle to solve. In Sec. VIII we do ablations of our own method to show the effect of individual components. VI. COMPARISON WITH PRIOR WORK A. Tasks We first show the results of our method on the simulated tasks presented in the Hindsight Experience Replay paper [1]. We apply our method to three tasks: 1) Pushing. A block placed randomly on the table must be moved to a target location on the table by the robot (fingers are blocked to avoid grasping). 2) Sliding. A puck placed randomly on the table must be moved to a given target location. The target is outside the robot’s reach so it must apply enough force that the puck reaches the target and stops due to friction. 3) Pick-and-place. A block placed randomly on the table must be moved to a target location in the air. Note 1In the 10cm x 10cm x 10cm cube around the current gripper position ae Pushing — ours — HER — 8c Success Rate _ Sliding re Pick and Place Success Rate am T om 10m Timesteps am fae “ow om 20m “Timesteps om imesteps am 10M Fig. 2: Baseline comparisons on tasks from [1]. Frames from the learned policy are shown above each task. Our method significantly outperforms the baselines. On the right plot, the HER baseline always fails. that the original paper used a form of initializing from favorable states to solve this task. We omit this for our experiment but discuss and evaluate the initialization idea in an ablation. the block through demonstrations. Providing demonstrations does not require expert knowledge of the learning system, which makes it a more compelling way to provide prior information. As in the prior work, we use a fully sparse reward for this task. The agent is penalized if the object is not at its goal position: 0, −1, otherwise if ||xi − gi|| < δ rt = (9) where the threshold δ is 5cm. # B. Results Fig. 2 compares our method to HER without demonstra- tions and behavior cloning. Our method is significantly faster at learning these tasks than HER, and achieves significantly better policies than behavior cloning does. Measuring the number of timesteps to get to convergence, we exhibit a 4x speedup over HER in pushing, a 2x speedup over HER in sliding, and our method solves the pick-and-place task while HER baseline cannot solve it at all. # VII. MULTI-STEP EXPERIMENTS A. Block Stacking Task To show that our method can solve more complex tasks with longer horizon and sparser reward, we study the task of block stacking in a simulated environment as shown in Fig. 1 with the same physical properties as the previous experiments. Our experiments show that our approach can solve the task in full and learn a policy to stack 6 blocks with demonstrations and RL. To measure and communicate various properties of our method, we also show experiments on stacking fewer blocks, a subset of the full task. We initialize the task with blocks at 6 random locations x1...x6. We also provide 6 goal locations g1...g6. To form a tower of blocks, we let g1 = x1 and gi = gi−1 + (0, 0, 5cm) for i ∈ 2, 3, 4, 5. The pick-and-place task showcases the shortcoming of RL in sparse reward settings, even with HER. In pick-and-place, the key action is to grasp the block. If the robot could manage to grasp it a small fraction of the time, HER discovers how to achieve goals in the air and reinforces the grasping behavior. However, grasping the block with random actions is extremely unlikely. Our method pushes the policy towards demonstration actions, which are more likely to succeed. In the HER paper, HER solves the pick-and-place task by initializing half of the rollouts with the gripper grasping the block. With this addition, pick-and-place becomes the easiest of the three tasks tested. This initialization is similar in spirit to our initialization idea, but takes advantage of the fact that pick-and-place with any goal can be solved starting from a block grasped at a certain location. This is not always true (for example, if there are multiple objects to be moved) and finding such a keyframe for other tasks would be dif- ficult, requiring some engineering and sacrificing autonomy. Instead, our method guides the exploration towards grasping By stacking N blocks, we mean N blocks reach their target locations. Since the target locations are always on top of x1, we start with the first block already in position. So stacking N blocks involves N −1 pick-and-place actions. To solve stacking N , we allow the agent 50 ∗ (N − 1) timesteps. This means that to stack 6 blocks, the robot executes 250 actions or 5 seconds. We recorded 100 demonstrations to stack 6 blocks, and use subsets of these demonstrations as demonstrations for stacking fewer blocks. The demonstrations are not perfect; they include occasionally dropping blocks, but our method can handle suboptimal demonstrations. We still rejected more than half the demonstrations and excluded them from the demonstration data because we knocked down the tower of blocks when releasing a block. # B. Rewards Two different reward functions are used. To test the performance of our method under fully sparse reward, we Task Stack 2, Sparse Stack 3, Sparse Stack 4, Sparse Stack 4, Step Stack 5, Step Stack 6, Step Ours 99% 99% 1% 91% 49% 4% BC+ Ours, Resets HER 97% 65% 0% 65% 1% 89% - 54% 0% 73% - 50% - 32% BC HER 1% - 0% - - 0% - 0% - - Fig. 3: Comparison of our method against baselines. The value reported is the median of the best performance (success rate) of all randomly seeded runs of each method. reward the agent only if all blocks are at their goal positions: rt = min i 1||xi−gi||<δ (10) The threshold δ is the size of a block, 5cm. Throughout the paper we call this the “sparse” reward. To enable solving the longer horizon tasks of stacking 4 or more blocks, we use the “step” reward : rt = −1 + 1||xi−gi||<δ i (11) Note the step reward is still very sparse; the robot only sees the reward change when it moves a block into its target location. We subtract 1 only to make the reward more interpretable, as in the initial state the first block is already at its target. Regardless of the reward type, an episode is considered successful for computing success rate if all blocks are at their goal position in their final state. C. Network architectures We use a 4 layer networks with 256 hidden units per layer for π and Q for the HER tasks and stacking 3 or fewer blocks. For stacking 4 blocks or more, we use an attention mechanism [39] for the actor and a larger network. The attention mechanism uses a 3 layer network with 128 hidden units per layer to query the states and goals with one shared head. Once a state and goal is extracted, we use a 5 layer network with 256 hidden units per layer after the attention mechanism. Attention speeds up training slightly but does not change training outcomes. D. Baselines to baselines on stacking 2 to 6 blocks. 2 Ours: Refers to our method as described in section IV-C. Ours, Resets: Refers to our method as described in section IV-C with resets from demonstration states (Sec. IV-D). BC: This method uses behavior cloning to learn a policy. Given the set of demonstration transitions RD, we train the 2Because of computational constraints, we were limited to 5 random seeds per method for stacking 3 blocks, 2 random seeds per method for stacking 4 and 5 blocks, and 1 random seed per method for stacking 6 blocks. Although we are careful to draw conclusions from few random seeds, the results are consistent with our collective experience training these models. We report the median of the random seeds everywhere applicable. Stack 3, Sparse Reward Ours Ours, Resets No Q-Filter No BC No HER Success Rate 300M 350M 400M Fig. 4: Ablation results on stacking 3 blocks with a fully sparse reward. We run each method 5 times with random seeds. The bold line shows the median of the 5 runs while each training run is plotted in a lighter color. Note “No HER” is always at 0% success rate. Our method without resets learns faster than the ablations. Our method with resets initially learns faster but converges to a worse success rate. policy π by supervised learning. Behavior cloning requires much less computation than RL. For a fairer comparison, we performed a large hyperparameter sweep over various networks sizes, attention hyperparameters, and learning rates and report the success rate achieved by the best policy found. HER: This method is exactly the one described in Hindsight Experience Replay [1], using HER and DDPG. BC+HER: This method first initializes a policy (actor) with BC, then finetunes the policy with RL as described above. # E. Results We are able to learn much longer horizon tasks than the other methods, as shown in Fig. 3. The stacking task is extremely difficult using HER without demonstrations because the chance of grasping an object using random actions is close to 0. Initializing a policy with demonstrations and then running RL also fails since the actor updates depend on a reasonable critic and although the actor is pretrained, the critic is not. The pretrained actor weights are therefore destroyed in the very first epoch, and the result is no better than BC alone. We attempted variants of this method where initially the critic was trained from replay data. However, this also fails without seeing on-policy data. The results with sparse rewards are very encouraging. We are able to stack 3 blocks with a fully sparse reward without resetting to the states from demonstrations, and 4 blocks with a fully sparse reward if we use resetting. With resets from demonstration states and the step reward, we are able to learn a policy to stack 6 blocks. # VIII. ABLATION EXPERIMENTS In this section we perform a series of ablation experiments to measure the importance of various components of our method. We evaluate our method on stacking 3 to 6 blocks. We perform the following ablations on the best performing We perform the following ablations on the best performing of our models on each task: of our models on each task: No BC Loss: This method does not apply the behavior cloning gradient during training. It still has access to demon- strations through the demonstration replay buffer. _ Stack 4, Step Reward Ours Ours, Resets, 06-— Ours — Ours, Resets 05. — No Q-Filter Rate Success Rate Reward J a 5 (OM 100M 200M 300M 400M 500M OOM 700M sooM om soo Timesteps Stack 5, Step Reward Stack 6, Step Reward — ours — Ours, Resets 0.00 ul led om 500m 000m 150m 2000 000 500m om 500m 000m 1500m 2000 Timesteps Timesteps Fig. 5: Ablation results on longer horizon tasks with a step reward. The upper row shows the success rate while the lower row shows the average reward at the final step of each episode obtained by different algorithms. For stacking 4 and 5 blocks, we use 2 random seeds per method. The median of the runs is shown in bold and each training run is plotted in a lighter color. Note that for stacking 4 blocks, the “No BC” method is always at 0% success rate. As the number of blocks increases, resets from demonstrations becomes more important to learn the task. No Q-Filter: This method uses standard behavioral cloning loss instead of the loss from equation Eq. 8, which means that the actor tries to mimic the demonstrator’s behaviour regardless of the critic. No HER: Hindsight Experience Replay is not used. A. Behavior Cloning Loss by Q-value gives a natural way to anneal the effect of the demonstrations as it automatically disables the BC loss when a better action is found. However, it gives mixed results on the longer horizon tasks. One explanation is that in the step reward case, learning relies less on the demonstrations because the reward signal is stronger. Therefore, the training is less affected by suboptimal demonstrations. Without the behavior cloning loss, the method is signifi- cantly worse in every task we try. Fig. 4 shows the training curve for learning to stack 3 blocks with a fully sparse reward. Without the behavior cloning loss, the system is about 2x slower to learn. On longer horizon tasks, we do not achieve any success without this loss. To see why, consider the training curves for stacking 4 blocks shown in Fig. 5. The “No BC” policy learns to stack only one additional block. Without the behavior cloning loss, the agent only has access to the demonstrations through the demonstration replay buffer. This allows it to view high- reward states and incentivizes the agent to stack more blocks, but there is a stronger disincentive: stacking the tower higher is risky and could result in lower reward if the agent knocks over a block that is already correctly placed. Because of this risk, which is fundamentally just another instance of the agent finding a local optimum in a shaped reward, the agent learns the safer behavior of pausing after achieving a certain reward. Explicitly weighting behavior cloning steps into gradient updates forces the policy to continue the task. C. Resets From Demonstrations We find that initializing rollouts from within demonstra- tion states greatly helps to learn to stack 5 and 6 blocks but hurts training with fewer blocks, as shown in Fig. 5. Note that even where resets from demonstration states helps the final success rate, learning takes off faster when this technique is not used. However, since stacking the tower higher is risky, the agent learns the safer behavior of stopping after achieving a certain reward. Resetting from demonstration states alleviates this problem because the agent regularly experiences higher rewards. This method changes the sampled state distribution, bi- asing it towards later states. It also inflates the Q values unrealistically. Therefore, on tasks where the RL algorithm does not get stuck in solving a subset of the full problem, it could hurt performance. # IX. DISCUSSION AND FUTURE WORK # B. Q-Filter The Q-Filter is effective in accelerating learning and achieving optimal performance. Fig. 4 shows that the method without filtering is slower to learn. One issue with the behavior cloning loss is that if the demonstrations are sub- optimal, the learned policy will also be suboptimal. Filtering We present a system to utilize demonstrations along with reinforcement learning to solve complicated multi-step tasks. We believe this can accelerate learning of many tasks, especially those with sparse rewards or other difficulties in exploration. Our method is very general, and can be applied on any continuous control task where a success criterion can be specified and demonstrations obtained. An exciting future direction is to train policies directly on a physical robot. Fig. 2 shows that learning the pick-and- place task takes about 1 million timesteps, which is about 6 hours of real world interaction time. This can realistically be trained on a physical robot, short-cutting the simulation- reality gap entirely. Many automation tasks found in factories and warehouses are similar to pick-and-place but without the variation in initial and goal states, so the samples required could be much lower. With our method, no expert needs to be in the loop to train these systems: demonstrations can be collected by users without knowledge about machine learning or robotics and rewards could be directly obtained from human feedback. A major limitation of this work is sample efficiency on solving harder tasks. While we could not solve these tasks with other learning methods, our method requires a large amount of experience which is impractical outside of simulation. To run these tasks on physical robots, the sample efficiency will have to improved considerably. We also require demonstrations which are not easy to collect for all tasks. If demonstrations are not available but the environment can be reset to arbitrary states, one way to learn goal-reaching but avoid using demonstrations is to reuse successful rollouts as in [40]. Finally, our method of resets from demonstration states requires the ability to reset to arbitrary states. Although we can solve many long-horizon tasks without this ability, it is very effective for the hardest tasks. Resetting from demon- stration rollouts resembles curriculum learning: we solve a hard task by first solving easier tasks. If the environment does not afford setting arbitrary states, then other curriculum methods will have to be used. X. ACKNOWLEDGEMENTS We thank Vikash Kumar and Aravind Rajeswaran for valu- able discussions. We thank Sergey Levine, Chelsea Finn, and Carlos Florensa for feedback on initial versions of this paper. Finally, we thank OpenAI for providing a supportive research environment. # REFERENCES [1] M. Andrychowicz et al., “Hindsight experience replay,” in Advances in neural information processing systems, 2017. [2] M. Veˇcer´ık et al., “Leveraging Demonstrations for Deep Reinforce- ment Learning on Robotics Problems with Sparse Rewards,” arXiv preprint arxiv:1707.08817, 2017. [3] M. P. Deisenroth, C. E. Rasmussen, and D. Fox, “Learning to Control a Low-Cost Manipulator using Data-Efficient Reinforcement Learning,” Robotics: Science and Systems, vol. VII, pp. 57–64, 2011. [4] Y. Duan et al., “One-shot imitation learning,” in NIPS, 2017. [5] D. A. Pomerleau, “Alvinn: An autonomous land vehicle in a neural network,” NIPS, pp. 305–313, 1989. [6] M. Bojarski et al., “End to End Learning for Self-Driving Cars,” arXiv preprint arXiv:1604.07316, 2016. [7] A. Giusti et al., “A Machine Learning Approach to Visual Perception of Forest Trails for Mobile Robots,” in IEEE Robotics and Automation Letters., 2015, pp. 2377–3766. [8] J. Nakanishi et al., “Learning from demonstration and adaptation of biped locomotion,” in Robotics and Autonomous Systems, vol. 47, no. 2-3, 2004, pp. 79–91. [9] M. Kalakrishnan et al., “Learning Locomotion over Rough Terrain using Terrain Templates,” in The 2009 IEEE/RSJ International Con- ference on Intelligent Robots and Systems, 2009. [10] S. Ross, G. J. Gordon, and J. A. Bagnell, “A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning,” in Proceedings of the 14th International Conference on Artificial Intelligence and Statistics (AISTATS), 2011. [11] A. Ng and S. Russell, “Algorithms for Inverse Reinforcement Learn- ing,” International Conference on Machine Learning (ICML), 2000. [12] B. D. Ziebart et al., “Maximum Entropy Inverse Reinforcement Learning.” in AAAI Conference on Artificial Intelligence, 2008, pp. 1433–1438. [13] P. Abbeel and A. Y. Ng, “Apprenticeship learning via inverse rein- forcement learning,” in ICML, 2004, p. 1. [14] C. Finn, S. Levine, and P. Abbeel, “Guided Cost Learning: Deep Inverse Optimal Control via Policy Optimization,” in ICML, 2016. [15] J. Peters, K. M¨ulling, and Y. Alt¨un, “Relative Entropy Policy Search,” Artificial Intelligence, pp. 1607–1612, 2010. [16] M. P. Deisenroth and C. E. Rasmussen, “Pilco: A model-based and data-efficient approach to policy search,” in ICML, 2011, pp. 465–472. [17] V. Mnih et al., “Human-level control through deep reinforcement learning,” Nature, vol. 518, no. 7540, pp. 529–533, 2015. [18] D. Silver et al., “Mastering the game of Go with deep neural networks and tree search,” Nature, vol. 529, no. 7587, pp. 484–489, Jan 2016. [19] S. Levine et al., “End-to-end training of deep visuomotor policies,” CoRR, vol. abs/1504.00702, 2015. [20] L. Pinto and A. Gupta, “Supersizing self-supervision: Learning to grasp from 50k tries and 700 robot hours,” arXiv preprint arXiv:1509.06825, 2015. [21] S. Levine et al., “Learning hand-eye coordination for robotic grasping with deep learning and large-scale data collection,” arXiv preprint arXiv:1603.02199, 2016. [22] S. Gu et al., “Deep Reinforcement Learning for Robotic Ma- nipulation with Asynchronous Off-Policy Updates,” arXiv preprint arXiv:1610.00633, 2016. [23] T. P. Lillicrap et al., “Continuous control with deep reinforcement learning,” arXiv preprint arXiv:1509.02971, 2015. [24] V. Mnih et al., “Asynchronous methods for deep reinforcement learn- ing,” in ICML, 2016. [25] J. Schulman et al., “Trust region policy optimization,” in Proceedings of the twenty-first international conference on Machine learning, 2015. [26] T. Winograd, Understanding Natural Language. Academic Press, 1972. [27] L. P. Kaelbling and T. Lozano-Perez, “Hierarchical task and motion planning in the now,” IEEE International Conference on Robotics and Automation, pp. 1470–1477, 2011. [28] L. Kavraki et al., “Probabilistic roadmaps for path planning in high- dimensional configuration spaces,” IEEE transactions on Robotics and Automation, vol. 12, no. 4, pp. 566–580, 1996. [29] S. Srivastava et al., “Combined Task and Motion Planning Through an Extensible Planner-Independent Interface Layer,” in International Conference on Robotics and Automation, 2014. [30] I. Popov et al., “Data-efficient Deep Reinforcement Learning for Dexterous Manipulation,” arXiv preprint arXiv:1704.03073, 2017. [31] S. Schaal, “Robot learning from demonstration,” Advances in Neural Information Processing Systems, no. 9, pp. 1040–1046, 1997. [32] J. Peters and S. Schaal, “Reinforcement learning of motor skills with policy gradients,” Neural Networks, vol. 21, no. 4, pp. 682–697, 2008. [33] J. Kober and J. Peter, “Policy search for motor primitives in robotics,” in Advances in neural information processing systems, 2008. [34] T. Hester et al., “Learning from Demonstrations for Real World Reinforcement Learning,” arXiv preprint arxiv:1704.03732, 2017. [35] B. Kim et al., “Learning from Limited Demonstrations,” Neural Information Processing Systems., 2013. [36] T. Schaul et al., “Universal Value Function Approximators,” Proceed- ings of The 32nd International Conference on Machine Learning, pp. 1312–1320, 2015. [37] E. Todorov, T. Erez, and Y. Tassa, “MuJoCo: A physics engine for model-based control,” in The IEEE/RSJ International Conference on Intelligent Robots and Systems, 2012. [38] D. Kingma and J. Ba, “Adam: A method for stochastic optimization,” International Conference on Learning Representations (ICLR), 2015. [39] D. Bahdanau, K. Cho, and Y. Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate,” in ICLR, 2015. [40] C. Florensa et al., “Reverse Curriculum Generation for Reinforcement Learning,” in Conference on robot learning, 2017.
Title: Scaling Laws for Neural Language Models: Summary: We study empirical scaling laws for language model performance on the cross-entropy loss. The loss scales as a power-law with model size, dataset size, and the amount of compute used for training, with some trends spanning more than seven orders of magnitude. Other architectural details such as network width or depth have minimal effects within a wide range. Simple equations govern the dependence of overfitting on model/dataset size and the dependence of training speed on model size. These relationships allow us to determine the optimal allocation of a fixed compute budget. Larger models are significantly more sample-efficient, such that optimally compute-efficient training involves training very large models on a relatively modest amount of data and stopping significantly before convergence. # Scaling Laws for Neural Language Models Jared Kaplan ∗ Sam McCandlish∗ Johns Hopkins University, OpenAI OpenAI jaredk@jhu.edu sam@openai.com Tom Henighan Tom B. Brown Benjamin Chess Rewon Child OpenAI OpenAI OpenAI OpenAI henighan@openai.com tom@openai.com bchess@openai.com Scott Gray Alec Radford Jeffrey Wu Dario Amodei OpenAI OpenAI OpenAI OpenAI scott@openai.com alec@openai.com jeffwu@openai.com # Abstract We study empirical scaling laws for language model performance on the cross-entropy loss. The loss scales as a power-law with model size, dataset size, and the amount of compute used for training, with some trends spanning more than seven orders of magnitude. Other architectural details such as network width or depth have minimal effects within a wide range. Simple equations govern the dependence of overfitting on model/dataset size and the dependence of training speed on model size. These relationships allow us to determine the optimal allocation of a fixed compute budget. Larger models are significantly more sample- efficient, such that optimally compute-efficient training involves training very large models on a relatively modest amount of data and stopping significantly before convergence. # ∗Equal contribution. Contributions: Jared Kaplan and Sam McCandlish led the research. Tom Henighan contributed the LSTM ex- periments. Tom Brown, Rewon Child, and Scott Gray, and Alec Radford developed the optimized Transformer implementation. Jeff Wu, Benjamin Chess, and Alec Radford developed the text datasets. Dario Amodei provided guidance throughout the project. # Contents 1 Introduction 2 Background and Methods 3 Empirical Results and Basic Power Laws 4 Charting the Infinite Data Limit and Overfitting 5 Scaling Laws with Model Size and Training Time 6 Optimal Allocation of the Compute Budget 7 Related Work 8 Discussion Appendices A Summary of Power Laws B Empirical Model of Compute-Efficient Frontier C Caveats 2 6 7 10 12 14 18 18 20 20 20 22 D Supplemental Figures # 1 Introduction Language provides a natural domain for the study of artificial intelligence, as the vast majority of reason- ing tasks can be efficiently expressed and evaluated in language, and the world’s text provides a wealth of data for unsupervised learning via generative modeling. Deep learning has recently seen rapid progress in lan- guage modeling, with state of the art models [RNSS18, DCLT18, YDY+19, LOG+19, RSR+19] approaching human-level performance on many specific tasks [WPN+19], including the composition of coherent multi- paragraph prompted text samples [RWC+19]. One might expect language modeling performance to depend on model architecture, the size of neural models, the computing power used to train them, and the data available for this training process. In this work we will empirically investigate the dependence of language modeling loss on all of these factors, focusing on the Transformer architecture [VSP+17, LSP+18]. The high ceiling and low floor for performance on language tasks allows us to study trends over more than seven orders of magnitude in scale. Throughout we will observe precise power-law scalings for performance as a function of training time, con- text length, dataset size, model size, and compute budget. # 1.1 Summary Our key findings for Transformer language models are are as follows: 2Here we display predicted compute when using a sufficiently small batch size. See Figure 13 for comparison to the purely empirical data. 2 4.2 6 —— L=(D/5.4+1013)-9995 | 5.6 —— L=(N/8.8-1023)-9.976 3.9 48 - 4.0 a4 > F; 3.3 3.2 F 3 3.0 . 24 === L= (Cmin/2.3 - 108)~950 2 2.7 fo 10-7 10-8 10-3 10-1 108 108 10° 108 107 10° Compute Dataset Size Parameters PF-days, non-embedding tokens non-embedding Figure 1 Language modeling performance improves smoothly as we increase the model size, datasetset size, and amount of compute2 used for training. For optimal performance all three factors must be scaled up in tandem. Empirical performance has a power-law relationship with each individual factor when not bottlenecked by the other two. Performance depends strongly on scale, weakly on model shape: Model performance depends most strongly on scale, which consists of three factors: the number of model parameters N (excluding embed- dings), the size of the dataset D, and the amount of compute C used for training. Within reasonable limits, performance depends very weakly on other architectural hyperparameters such as depth vs. width. (Section 3) Smooth power laws: Performance has a power-law relationship with each of the three scale factors N, D, C when not bottlenecked by the other two, with trends spanning more than six orders of magnitude (see Figure 1). We observe no signs of deviation from these trends on the upper end, though performance must flatten out eventually before reaching zero loss. (Section 3) Universality of overfitting: Performance improves predictably as long as we scale up N and D in tandem, but enters a regime of diminishing returns if either N or D is held fixed while the other increases. The performance penalty depends predictably on the ratio N 0.74/D, meaning that every time we increase the model size 8x, we only need to increase the data by roughly 5x to avoid a penalty. (Section 4) Universality of training: Training curves follow predictable power-laws whose parameters are roughly independent of the model size. By extrapolating the early part of a training curve, we can roughly predict the loss that would be achieved if we trained for much longer. (Section 5) Transfer improves with test performance: When we evaluate models on text with a different distribution than they were trained on, the results are strongly correlated to those on the training validation set with a roughly constant offset in the loss – in other words, transfer to a different distribution incurs a constant penalty but otherwise improves roughly in line with performance on the training set. (Section 3.2.2) Sample efficiency: Large models are more sample-efficient than small models, reaching the same level of performance with fewer optimization steps (Figure 2) and using fewer data points (Figure 4). Convergence is inefficient: When working within a fixed compute budget C but without any other restric- tions on the model size N or available data D, we attain optimal performance by training very large models and stopping significantly short of convergence (see Figure 3). Maximally compute-efficient training would therefore be far more sample efficient than one might expect based on training small models to convergence, with data requirements growing very slowly as D ∼ C 0.27 with training compute. (Section 6) Optimal batch size: The ideal batch size for training these models is roughly a power of the loss only, and continues to be determinable by measuring the gradient noise scale [MKAT18]; it is roughly 1-2 million tokens at convergence for the largest models we can train. (Section 5.1) Taken together, these results show that language modeling performance improves smoothly and predictably as we appropriately scale up model size, data, and compute. We expect that larger language models will perform better and be more sample efficient than current models. 3 Larger models require fewer samples to reach the same performance Test Loss 10 The optimal model size grows smoothly with the loss target and compute budget: Is Line color indicates number of parameters 103 108 10° KN AN WO N Compute-efficient training stops far short of convergence 107 109 ton Tokens Processed 109 106 103 109 Compute (PF-days) Figure 2 We show a series of language model training runs, with models ranging in size from 103 to 109 parameters (excluding embeddings). g 108 Minimum serial steps 3 increases negligibly N : x g 10° io) 1S} & 104 Bat I 3 £ 102 3 = 10° 10-8 10-6 10-4 Data grow Optimal increases 10-2 10° Compute (PF-days) Figure 3 As more compute becomes available, we can choose how much to allocate towards training larger models, using larger batches, and training for more steps. We illustrate this for a billion-fold increase in compute. For optimally compute-efficient training, most of the increase should go towards increased model size. A relatively small increase in data is needed to avoid reuse. Of the increase in data, most can be used to increase parallelism through larger batch sizes, with only a very small increase in serial training time required. # 1.2 Summary of Scaling Laws The test loss of a Transformer trained to autoregressively model language can be predicted using a power-law when performance is limited by only either the number of non-embedding parameters N , the dataset size D, or the optimally allocated compute budget Cmin (see Figure 1): 1. For models with a limited number of parameters, trained to convergence on sufficiently large datasets: L(N ) = (Nc/N )αN ; αN ∼ 0.076, Nc ∼ 8.8 × 1013 (non-embedding parameters) 2. For large models trained with a limited dataset with early stopping: L(D) = (Dc/D)αD ; αD ∼ 0.095, Dc ∼ 5.4 × 1013 (tokens) 3. When training with a limited amount of compute, a sufficiently large dataset, an optimally-sized model, and a sufficiently small batch size (making optimal3 use of compute): L(Cinin) = (C®™/Crnin) am ~ 0.050, Cm™ ~ 3.1 x 108 (PF-days) (1.3) 3We also observe an empirical power-law trend with the training compute C (Figure 1) while training at fixed batch size, but it is the trend with Cmin that should be used to make predictions. They are related by equation (5.5). 4 # requirements relatively slowly # model size very quickly (1.1) (1.2) 2 4 Loss vs Model Size and Training Steps 3 ed 108 & g EI wre it 2 z 108 § & 104 105 Estimated Sinin Loss vs Model and Dataset Size Loss vs Model Size and Training Steps 45 4.0 Params 108 © 708M © 302M ges oom e 3M 3.0 © 25M © 393.2K 108 2.5 107 108 10° 1010 104 105 Tokens in Dataset Estimated Sinin Figure 4 Left: The early-stopped test loss L(N, D) varies predictably with the dataset size D and model size N according to Equation (1.5). Right: After an initial transient period, learning curves for all model sizes N can be fit with Equation (1.6), which is parameterized in terms of Smin, the number of steps when training at large batch size (details in Section 5.1). These relations hold across eight orders of magnitude in Cmin, six orders of magnitude in N , and over two orders of magnitude in D. They depend very weakly on model shape and other Transformer hyperparameters (depth, width, number of self-attention heads), with specific numerical values associated with the Webtext2 training set [RWC+19]. The power laws αN, αD, αmin specify the degree of performance improvement C expected as we scale up N , D, or Cmin; for example, doubling the number of parameters yields a loss that is smaller by a factor 2−αN = 0.95. The precise numerical values of Nc, C min , and Dc depend on the c vocabulary size and tokenization and hence do not have a fundamental meaning. The critical batch size, which determines the speed/efficiency tradeoff for data parallelism ([MKAT18]), also roughly obeys a power law in L: Bcrit (L) = B∗ L1/αB , B∗ ∼ 2 · 108 tokens, αB ∼ 0.21 (1.4) Equation (1.1) and (1.2) together suggest that as we increase the model size, we should increase the dataset αN αD ∼ N 0.74. In fact, we find that there is a single equation combining size sublinearly according to D ∝ N (1.1) and (1.2) that governs the simultaneous dependence on N and D and governs the degree of overfitting: L(N,D)= (3) "+3 (1.5) with fits pictured on the left in figure 4. We conjecture that this functional form may also parameterize the trained log-likelihood for other generative modeling tasks. When training a given model for a finite number of parameter update steps S in the infinite data limit, after an initial transient period, the learning curves can be accurately fit by (see the right of figure|4p N. an Ye os L(N,S) = (*) + (ss) ” # an where Sc ≈ 2.1 × 103 and αS ≈ 0.76, and Smin(S) is the minimum possible number of optimization steps (parameter updates) estimated using Equation (5.4). When training within a fixed compute budget C, but with no other constraints, Equation (1.6) leads to the prediction that the optimal model size N , optimal batch size B, optimal number of steps S, and dataset size D should grow as N ∝ C αmin C /αN , B ∝ C αmin C /αB , S ∝ C αmin C /αS , D = B · S (1.7) # with # αmin (1.8) which closely matches the empirically optimal results N ∝ C 0.73 min . As the computational budget C increases, it should be spent primarily on larger models, without dramatic increases in training time or dataset size (see Figure 3). This also implies that as models grow larger, they become increasingly sample efficient. In practice, researchers typically train smaller models for longer than would 5 be maximally compute-efficient because of hardware constraints. Optimal performance depends on total compute as a power law (see Equation (1.3)). We provide some basic theoretical motivation for Equation (1.5), an analysis of learning curve fits and their implications for training time, and a breakdown of our results per token. We also make some brief compar- isons to LSTMs and recurrent Transformers [DGV+18]. # 1.3 Notation We use the following notation: • L – the cross entropy loss in nats. Typically it will be averaged over the tokens in a context, but in some cases we report the loss for specific tokens within the context. N – the number of model parameters, excluding all vocabulary and positional embeddings • C ≈ 6N BS – an estimate of the total non-embedding training compute, where B is the batch size, and S is the number of training steps (ie parameter updates). We quote numerical values in PF-days, where one PF-day = 1015 × 24 × 3600 = 8.64 × 1019 floating point operations. D – the dataset size in tokens • Bcrit – the critical batch size [MKAT18], defined and discussed in Section 5.1. Training at the critical batch size provides a roughly optimal compromise between time and compute efficiency. • Cmin – an estimate of the minimum amount of non-embedding compute to reach a given value of the loss. This is the training compute that would be used if the model were trained at a batch size much less than the critical batch size. • Smin – an estimate of the minimal number of training steps needed to reach a given value of the loss. This is also the number of training steps that would be used if the model were trained at a batch size much greater than the critical batch size. • αX – power-law exponents for the scaling of the loss as L(X) ∝ 1/X αX where X can be any of N, D, C, S, B, C min. # 2 Background and Methods We train language models on WebText2, an extended version of the WebText [RWC+19] dataset, tokenized using byte-pair encoding [SHB15] with a vocabulary size nvocab = 50257. We optimize the autoregres- sive log-likelihood (i.e. cross-entropy loss) averaged over a 1024-token context, which is also our principal performance metric. We record the loss on the WebText2 test distribution and on a selection of other text distributions. We primarily train decoder-only [LSP+18, RNSS18] Transformer [VSP+17] models, though we also train LSTM models and Universal Transformers [DGV+18] for comparison. # 2.1 Parameter and Compute Scaling of Transformers We parameterize the Transformer architecture using hyperparameters nlayer (number of layers), dmodel (di- mension of the residual stream), dff (dimension of the intermediate feed-forward layer), dattn (dimension of the attention output), and nheads (number of attention heads per layer). We include nctx tokens in the input context, with nctx = 1024 except where otherwise noted. We use N to denote the model size, which we define as the number of non-embedding parameters N ≈ 2dmodelnlayer (2dattn + dff ) = 12nlayerd2 model with the standard dattn = dff /4 = dmodel (2.1) where we have excluded biases and other sub-leading terms. Our models also have nvocabdmodel parameters in an embedding matrix, and use nctxdmodel parameters for positional embeddings, but we do not include these when discussing the ‘model size’ N ; we will see that this produces significantly cleaner scaling laws. Evaluating a forward pass of the Transformer involves roughly Cforward ≈ 2N + 2nlayernctxdmodel add-multiply operations, where the factor of two comes from the multiply-accumulate operation used in matrix multiplication. A more detailed per-operation parameter and compute count is included in Table 1. 6 Operation Parameters FLOPs per Token Embed (nvocab + nctx) dmodel 4dmodel Attention: QKV nlayerdmodel3dattn 2nlayerdmodel3dattn Attention: Mask — 2nlayernctxdattn Attention: Project nlayerdattndmodel 2nlayerdattndembd Feedforward nlayer2dmodeldff 2nlayer2dmodeldff De-embed — 2dmodelnvocab Total (Non-Embedding) N = 2dmodelnlayer (2dattn + dff ) Cforward = 2N + 2nlayernctxdattn Table 1 Parameter counts and compute (forward pass) estimates for a Transformer model. Sub-leading terms such as nonlinearities, biases, and layer normalization are omitted. For contexts and models with dyodel > Netx/12, the context-dependent computational cost per token is a relatively small fraction of the total compute. Since we primarily study models where dmode1 > Netx/12, we do not include context-dependent terms in our training compute estimate. Accounting for the backwards pass (approximately twice the compute as the forwards pass), we then define the estimated non-embedding compute as C' © 6N floating point operators per training token. # 2.2 Training Procedures Unless otherwise noted, we train models with the Adam optimizer [KB14] for a fixed 2.5 × 105 steps with a batch size of 512 sequences of 1024 tokens. Due to memory constraints, our largest models (more than 1B parameters) were trained with Adafactor [SS18]. We experimented with a variety of learning rates and schedules, as discussed in Appendix D.6. We found that results at convergence were largely independent of learning rate schedule. Unless otherwise noted, all training runs included in our data used a learning rate schedule with a 3000 step linear warmup followed by a cosine decay to zero. # 2.3 Datasets We train our models on an extended version of the WebText dataset described in [RWC+19]. The original WebText dataset was a web scrape of outbound links from Reddit through December 2017 which received at least 3 karma. In the second version, WebText2, we added outbound Reddit links from the period of January to October 2018, also with a minimum of 3 karma. The karma threshold served as a heuristic for whether people found the link interesting or useful. The text of the new links was extracted with the Newspaper3k python library. In total, the dataset consists of 20.3M documents containing 96 GB of text and 1.62 × 1010 words (as defined by wc). We then apply the reversible tokenizer described in [RWC+19], which yields 2.29 × 1010 tokens. We reserve 6.6 × 108 of these tokens for use as a test set, and we also test on similarly- prepared samples of Books Corpus [ZKZ+15], Common Crawl [Fou], English Wikipedia, and a collection of publicly-available Internet Books. # 3 Empirical Results and Basic Power Laws To characterize language model scaling we train a wide variety of models, varying a number of factors including: • Model size (ranging in size from 768 to 1.5 billion non-embedding parameters) • Dataset size (ranging from 22 million to 23 billion tokens) Shape (including depth, width, attention heads, and feed-forward dimension) Context length (1024 for most runs, though we also experiment with shorter contexts) • Batch size (219 for most runs, but we also vary it to measure the critical batch size) 7 So Mead =8 —*— 50M Params =F dmogei = 256 8% | © Omose/Mneaa = 64 —— 274M Params dade! = 512 —— 1.5B Params = dinagei = 1024 Awide range of architectures achieve similar performance 1 22% additional compute compensates for 1% loss increase ee 10° 10! 10° 10? 103 10" 10? Feed-Forward Ratio (dit / model) Attention Head Dimension (dmoce! / Nhead) 50M Parameters 25M Parameters Loss Increase Aspect Ratio (dmodel / Niayer) Figure 5 Performance depends very mildly on model shape when the total number of non-embedding parameters N is held fixed. The loss varies only a few percent over a wide range of shapes. Small differences in parameter counts are compensated for by using the fit to L(N ) as a baseline. Aspect ratio in particular can vary by a factor of 40 while only slightly impacting performance; an (nlayer, dmodel) = (6, 4288) reaches a loss within 3% of the (48, 1600) model used in [RWC+19]. 7 “Re : 6 6 5 5 2 2 — OL a4 ayer a4 2 —— 1 Layer 2 —— 1 Layer & —— 2 Layers & —— 2 Layers 3) —— 3 Layers 3} —— 3 Layers —— 6 Layers —— 6 Layers —— >6 Layers —— >6 Layers 2 2 5 108 107 108 10° 108 104 105 108 107 108 10° Parameters (with embedding) Parameters (non-embedding) Figure 6 Left: When we include embedding parameters, performance appears to depend strongly on the number of layers in addition to the number of parameters. Right: When we exclude embedding parameters, the performance of models with different depths converge to a single trend. Only models with fewer than 2 layers or with extreme depth-to-width ratios deviate significantly from the trend. In this section we will display data along with empirically-motivated fits, deferring theoretical analysis to later sections. # 3.1 Approximate Transformer Shape and Hyperparameter Independence Transformer performance depends very weakly on the shape parameters nlayer, nheads, and dff when we hold the total non-embedding parameter count N fixed. To establish these results we trained models with fixed size while varying a single hyperparameter. This was simplest for the case of nheads. When varying nlayer, we simultaneously varied dmodel while keeping N ≈ 12nlayerd2 model fixed. Similarly, to vary dff at fixed model size we also simultaneously varied the dmodel parameter, as required by the parameter counts in Table 1. Independence of nlayers would follow if deeper Transformers effectively behave as ensembles of shallower models, as has been suggested for ResNets [VWB16]. The results are shown in Figure 5. # 3.2 Performance with Non-Embedding Parameter Count N In Figure 6 we display the performance of a wide variety of models, ranging from small models with shape (nlayer, dmodel) = (2, 128) through billion-parameter models, ranging in shape from (6, 4288) through (207, 768). Here we have trained to near convergence on the full WebText2 dataset and observe no over- fitting (except possibly for the very largest models). As shown in Figure 1, we find a steady trend with non-embedding parameter count N , which can be fit to the first term of Equation (1.5), so that L(N) = (%)° (3.1) 8 # Test Transformers asymptotically outperform LSTMs due to improved use of long contexts LSTM plateaus after <100 tokens Transformer improves through the whole context Figure 7 To observe these trends it is crucial to study performance as a function of N ; if we instead use the total parameter count (including the embedding parameters) the trend is somewhat obscured (see Figure 6). This suggests that the embedding matrix can be made smaller without impacting performance, as has been seen in recent work [LCG+19]. Although these models have been trained on the WebText2 dataset, their test loss on a variety of other datasets is also a power-law in N with nearly identical power, as shown in Figure 8. # 3.2.1 Comparing to LSTMs and Universal Transformers In Figure 7 we compare LSTM and Transformer performance as a function of non-embedding parameter count N . The LSTMs were trained with the same dataset and context length. We see from these figures that the LSTMs perform as well as Transformers for tokens appearing early in the context, but cannot match the Transformer performance for later tokens. We present power-law relationships between performance and context position Appendix D.5, where increasingly large powers for larger models suggest improved ability to quickly recognize patterns. We also compare the performance of standard Transformers to recurrent Transformers [DGV+18] in Figure 17 in the appendix. These models re-use parameters, and so perform slightly better as a function of N , at the cost of additional compute per-parameter. # 3.2.2 Generalization Among Data Distributions We have also tested our models on a set of additional text data distributions. The test loss on these datasets as a function of model size is shown in Figure 8; in all cases the models were trained only on the WebText2 dataset. We see that the loss on these other data distributions improves smoothly with model size, in direct parallel with the improvement on WebText2. We find that generalization depends almost exclusively on the in-distribution validation loss, and does not depend on the duration of training or proximity to convergence. We also observe no dependence on model depth (see Appendix D.8). # 3.3 Performance with Dataset Size and Compute We display empirical trends for the test loss as a function of dataset size D (in tokens) and training compute C in Figure 1. For the trend with D we trained a model with (nlayer, nembd) = (36, 1280) on fixed subsets of the WebText2 dataset. We stopped training once the test loss ceased to decrease. We see that the resulting test losses can be fit with simple power-law D.\°? L(D) = (— 3.2 (r= (2) (2) in the dataset size. The data and fit appear in Figure 1. The total amount of non-embedding compute used during training can be estimated as C = 6N BS, where B is the batch size, S is the number of parameter updates, and the factor of 6 accounts for the forward and backward passes. Thus for a given value of C we can scan over all models with various N to find the model 9 7 5.0 = —e WebText2 (Test) ¢ wSy, ee ==» Books during training 6 —e— Internet Books 94.5 ae TS ~~~ Wikipedia during training —* Books 3 She @ Books at convergence 5 -e— Wikipedia ‘8 4.0 Rae © Wikipedia at convergence —e— Common Crawl a “Sey, 2 = A35 weg a7 FS ‘ 5 3.0 * 3 8 B25 4 10# = 105 108 = 107 108 =~ 109 5.0 45 4.0 3.5 3.0 2.5 Parameters (non-embedding) Test Loss on Training Distribution a g ° 44 E & Figure 8 Left: Generalization performance to other data distributions improves smoothly with model size, with only a small and very slowly growing offset from the WebText2 training distribution. Right: Gener- alization performance depends only on training distribution performance, and not on the phase of training. We compare generalization of converged models (points) to that of a single large model (dashed curves) as it trains. with the best performance on step S = C 6BS . Note that in these results the batch size B remains fixed for all models, which means that these empirical results are not truly optimal. We will account for this in later sections using an adjusted Cmin to produce cleaner trends. The result appears as the heavy black line on the left-hand plot in Figure 1. It can be fit with C.\% L(C) = | = 3.3 ©=($) G3) The figure also includes images of individual learning curves to clarify when individual models are optimal. We will study the optimal allocation of compute more closely later on. The data strongly suggests that sample efficiency improves with model size, and we also illustrate this directly in Figure 19 in the appendix. # 4 Charting the Infinite Data Limit and Overfitting In Section 3 we found a number of basic scaling laws for language modeling performance. Here we will study the performance of a model of size N trained on a dataset with D tokens while varying N and D simultaneously. We will empirically demonstrate that the optimally trained test loss accords with the scaling law of Equation (1.5). This provides guidance on how much data we would need to train models of increasing size while keeping overfitting under control. # 4.1 Proposed L(N, D) Equation We have chosen the parameterization (1.5) (repeated here for convenience): us.py=|(%)" +2 an using three principles: 1. Changes in vocabulary size or tokenization are expected to rescale the loss by an overall factor. The parameterization of L(N, D) (and all models of the loss) must naturally allow for such a rescaling. 2. Fixing D and sending N → ∞, the overall loss should approach L(D). Conversely, fixing N and sending D → ∞ the loss must approach L(N ). 3. L(N, D) should be analytic at D = ∞, so that it has a series expansion in 1/D with integer powers. Theoretical support for this principle is significantly weaker than for the first two. Our choice of L(N, D) satisfies the first requirement because we can rescale Nc, Dc with changes in the vocabulary. This also implies that the values of Nc, Dc have no fundamental meaning. 10 Data Size Bottleneck Overfitting 0.5 45 Data Size 0.4 Data 4.0 © 2M a © 2M © 43M \ ° 43M 935 © 86M gos © 86M ° 172M U e © 344M 02 © 3.0 © 688M a © © 148 a © 143 © 22.08 0.1 © 2.5 ; ; 0.0 10° 107 108 10° 10-4 10-3 10-2 10-1 Params (non-embed) Ne!) 2 3 3 & Figure 9 The early-stopped test loss L(N, D) depends predictably on the dataset size D and model size N according to Equation (1.5). Left: For large D, performance is a straight power law in N . For a smaller fixed D, performance stops improving as N increases and the model begins to overfit. (The reverse is also true, αN αD /D, as predicted in see Figure 4.) Right: The extent of overfitting depends predominantly on the ratio N equation (4.3). The line is our fit to that equation. Since we stop training early when the test loss ceases to improve and optimize all models in the same way, we expect that larger models should always perform better than smaller models. But with fixed finite D, we also do not expect any model to be capable of approaching the best possible loss (ie the entropy of text). Similarly, a model with fixed size will be capacity-limited. These considerations motivate our second principle. Note that knowledge of L(N ) at infinite D and L(D) at infinite N fully determines all the parameters in L(N, D). The third principle is more speculative. There is a simple and general reason one might expect overfitting to scale ∝ 1/D at very large D. Overfitting should be related to the variance or the signal-to-noise ratio of the dataset [AS17], and this scales as 1/D. This expectation should hold for any smooth loss function, since we expect to be able to expand the loss about the D → ∞ limit. However, this argument assumes that 1/D corrections dominate over other sources of variance, such as the finite batch size and other limits on the efficacy of optimization. Without empirical confirmation, we would not be very confident of its applicability. Our third principle explains the asymmetry between the roles of N and D in Equation (1.5). Very similar symmetric expressions4 are possible, but they would not have a 1/D expansion with integer powers, and would require the introduction of an additional parameter. In any case, we will see that our equation for L(N, D) fits the data well, which is the most important justifi- cation for our L(N, D) ansatz. # 4.2 Results We regularize all our models with 10% dropout, and by tracking test loss and stopping once it is no longer decreasing. The results are displayed in Figure 9, including a fit to the four parameters αN , αD, Nc, Dc in Equation (1.5): Parameter αN αD Nc Dc Value 0.076 0.103 6.4 × 1013 1.8 × 1013 Table 2 Fits to L(N, D) We obtain an excellent fit, with the exception of the runs where the dataset has been reduced by a factor of 1024, to about 2 × 107 tokens. With such a small dataset, an epoch consists of only 40 parameter updates. Perhaps such a tiny dataset represents a different regime for language modeling, as overfitting happens very early in training (see Figure 16). Also note that the parameters differ very slightly from those obtained in Section 3, as here we are fitting the full L(N, D) rather than just L(N, ∞) or L(∞, D). To chart the borderlands of the infinite data limit, we can directly study the extent of overfitting. For all but the largest models, we see no sign of overfitting when training with the full 22B token WebText2 dataset, so we can take it as representative of D = ∞. Thus we can compare finite D to the infinite data limit by For example, one might have used L(N, D) = [(42)°% + (22)°?] e but this does not have a 1/D expansion. 11 # Size 172M 344M 688M 22.08 Critical Batch Size vs. Performance on - a ™ 108 ° & g w 105 a = : Bios ee —e— Empirical Bait, N= 3M Z —s— Empirical Berit, N= 85M £ a= Bert = 2.1 x 108 tokens -L~48 a Noise Scale Measurement © 103 10! 6x 10° 4x10° 3x10° WebText2 Train Loss Figure 10 The critical batch size Bcrit follows a power law in the loss as performance increase, and does not depend directly on the model size. We find that the critical batch size approximately doubles for every 13% decrease in loss. Bcrit is measured empirically from the data shown in Figure 18, but it is also roughly predicted by the gradient noise scale, as in [MKAT18]. defining δL(N, D) ≡ L(N, D) L(N, ∞) − 1 (4.2) and studying it as a function of N, D. In fact, we see empirically that δL depends only a specific combination of N and D, as shown in Figure 16. This follows from the scaling law of Equation (1.5), which implies ay ap N\s> D. 6L (: + (x) 2) -1 (4.3) Note that at large D this formula also has a series expansion in powers of 1/D. We estimate that the variation in the loss with different random seeds is roughly 0.02, which means that to avoid overfitting when training to within that threshold of convergence we require D2 (5x 10°) N°” (4.4) With this relation, models smaller than 109 parameters can be trained with minimal overfitting on the 22B token WebText2 dataset, but our largest models will encounter some mild overfitting. More generally, this relation shows that dataset size may grow sub-linearly in model size while avoiding overfitting. Note however that this does not typically represent maximally compute-efficient training. We should also emphasize that we have not optimized regularization (eg the dropout probability) while varying dataset and model size. # 5 Scaling Laws with Model Size and Training Time In this section we will demonstrate that a simple scaling law provides a good description for the loss as a function of model size N and training time. First we will explain how to use the results of [MKAT18] to define a universal training step Smin, which accounts for the fact that most of our models have not been trained at an optimal batch size. Then we will demonstrate that we can fit the model size and training time dependence of the loss using Equation (1.6). Later we will use these results to predict the optimal allocation of training compute between model size and training time, and then confirm that prediction. # 5.1 Adjustment for Training at Bcrit(L) A simple empirical theory for the batch size dependence of training was developed in [MKAT18] (see also [SLA+18, ZLN+19]). It was argued that there is a critical batch size Bcrit for training; for B up to Bcrit the batch size can be increased with very minimal degradation in compute-efficiency, whereas for B > Bcrit increases in B result in diminishing returns. It was also argued that the gradient noise scale provides a simple 12 prediction for B,,;,, and that neither depends directly on model size except through the value of the loss that has been attained. These results can be used to predict how training time and compute will vary with the batch size. To utilize both training time and compute as effectively as possible, it is best to train with a batch size B + Beit. Training at B >> Bit minimizes the number of training steps, while B < Beri, minimizes the use of compute. More specifically, it was demonstrated that for a wide variety of neural network tasks, the number of training steps S and the number of data examples processed E = BS satisfy the simple relation Ss E (= 7 1) (a. 7 1) GO» when training to any fixed value of the loss L. Here Smin is the minimum number of steps necessary to reach L, while Emin is the minimum number of data examples that must be processed. We demonstrate the relation (5.1) for Transformers in Figure 18 in the appendix. This relation defines the critical batch size Emin Smin Bcrit(L) ≡ (5.2) which is a function of the target value of the loss. Training at the critical batch size makes a roughly optimal time/compute tradeoff, requiring 2Smin training steps and processing E = 2Emin data examples. In Figure 10 we have plotted the critical batch size and gradient noise scale5 as a function of training loss for two different models. We see that Bcrit(L) is independent of model size, and only depends on the loss L. So the predictions of [MKAT18] continue to hold for Transformer language models. The critical batch size can be fit with a power-law in the loss Bcrit(L) ≈ B∗ L1/αB (5.3) where B∗ ≈ 2 × 108 and αB ≈ 0.21. We have chosen this parameterization for Bcrit(L) because as the loss approaches its minimum value Lmin, the gradient noise scale is expected to diverge, and we expect Bcrit to track this noise scale. We do not know Lmin, as we see no sign that our models are approaching it, but Lmin > 0 since the entropy of natural language is non-zero. Since apparently Lmin is much smaller than the values of L we have achieved, we used a parameterization where Bcrit diverges as L → 0. We will use B.,it(L) to estimate the relation between the number of training steps S' while training at batch size B = 2!9 tokens and the number of training steps while training at B >> B.,i,. This is simply Ss Sinin(S) = T+ Ban(L)/B (minimum steps, at B >> Berit) (5.4) for any given target value L for the loss. This also defines a critical value of the compute needed to train to L with a model of size N if we were to train at B < Beyi,(L). This is Cc Cwnin(C) = 1+ B/Bai(L) (minimum compute, at B < Beit) (5.5) where C = 6N BS estimates the (non-embedding) compute used at batch size B. # 5.2 Results for L(N, Smin) and Performance with Model Size and Compute Now we will use Smin defined in Equation (5.4) to obtain a simple and universal fit for the dependence of the loss on model size and training time in the infinite data limit. We will fit the stable, Adam-optimized training runs using Equation (1.6), repeated here for convenience: an a as L(N, Simin) = (*) + (= ) (5.6) for the loss. We include all training steps after the warmup period of the learning rate schedule, and find a fit to the data with the parameters: 5Although the critical batch size roughly matches the gradient noise scale, we are using a direct measurements of Bcrit from Figures 18 and 10 for all our later analyses. 13 Performance vs Compute Budget 8 7 10° 6 10-1 ge g -2 Sy w?B % ay 10- é 3 10-4 10-5 2 5 104 106 108 Parameters (non-embedding) Performance vs Steps 105 g g a % FA é 104 5 108 107 108 109 Parameters (non-embedding) Performance vs Compute Budget Performance vs Steps 8 7 10° 6 105 10-1 ge g g -2 w?B g ay % 10- é 3 10-4 104 10-5 2 5 5 104 106 108 108 107 108 109 Parameters (non-embedding) Parameters (non-embedding) Figure 11 When we hold either total compute or number of training steps fixed, performance follows L(N, S) from Equation (5.6). Each value of compute budget has an associated optimal model size that maximizes performance. Mediocre fits at small S are unsurprising, as the power-law equation for the learning curves breaks down very early in training. Parameter αN αS Nc Sc Value 0.077 0.76 6.5 × 1013 2.1 × 103 # Table 3 Fits to L(N, S) With these parameters, we obtain the learning curve fits in Figure 4. Though the fits are imperfect, we believe they are quite compelling given the simplicity of Equation (5.6). The data and fits can be visualized in a different and more interesting way, as shown in Figure 11. There we study the test loss as a function of model size while fixing either the total non-embedding compute C used in training, or the number of steps S. For the fits we use Equation (5.5) and (5.4) along with the parameters above and Equation (5.6). The power-law dependence of the loss on Smin reflects the interplay of optimizer dynamics and the loss landscape. Since the fits are best late in training, when the loss may be approximately quadratic, the power- law should provide information about the spectrum of the Hessian of the loss. Its universality suggests that the Hessian eigenvalue density is roughly independent of model size. # 5.3 Lower Bound on Early Stopping Step The results for L(N, Smin) can be used to derive a lower-bound (and rough estimate) of the step at which early stopping should occur when training is data limited. It is motivated by the idea that finite and infinite D learning curves for a given model will be very similar until we reach Smin ≈ Sstop. Thus overfitting should be proportional to the correction from simply ending training at Sstop. This will underestimate Sstop, because in reality the test loss will decrease more slowly when we have a finite D, and therefore we will require more training steps to reach the optimal test loss at finite D. This line of reasoning leads to the inequality Se [L(N, D) — L(N, co)]'/“S (5.7) Sstop(N, D) where L(N, oo) is the converged loss, evaluated with infinite available data. This inequality and its com- parison to the empirical data is displayed in Figure [T6]in the appendix. In that figure, the values of Sstop and L(N, D) are empirical (though Sstop is adjusted to mimic training at B > Bei), while L(N, 00) is computed from the fit to L(V, D) evaluated at D = ov. # 6 Optimal Allocation of the Compute Budget We displayed the empirical trend of performance as a function of the computation used during training in the top-right of Figure 1. However, this result involved training at a fixed batch size B, whereas we know 14 10! » fo) Smaller models require more steps to train, while larger models require fewer w uw we o Models between 0.6x and 2.2x the optimal size can be trained with a 20% larger compute budget 10° N o Excess Steps (S/Serricient) Excess Compute (C/Cesticient) N or 15 Our framework does not ~~~ an 1.0 capture early training dynamics ‘| 10° 10! 10° 10! Deviation from Optimal Model (N/Netricient) Deviation from Optimal Model (N/Negficient) Figure 12 Left: Given a fixed compute budget, a particular model size is optimal, though somewhat larger or smaller models can be trained with minimal additional compute. Right: Models larger than the compute- efficient size require fewer steps to train, allowing for potentially faster training if sufficient additional paral- lelism is possible. Note that this equation should not be trusted for very large models, as it is only valid in the power-law region of the learning curve, after initial transient effects. ~ -=-= L= (Cmin/2.3 108) -0.05° === L= (C/2.0-107)-°57 Test Loss 2 F 1o-8 10-6 10-4 10-2 10° Compute (PF-days), non-embedding Figure 13 When adjusting performance to simulate training far below the critical batch size, we find a somewhat altered power law for L(Cmin) when compared with the fully empirical results. The conspicuous lump at 10−5 PF-days marks the transition from 1-layer to 2-layer networks; we exclude 1-layer networks in the power-law fits. It is the L(Cmin) trend that we expect to provide a reliable extrapolation for larger compute. that in fact we could train more efficiently6 by training at the batch size Bcrit discussed in Section 5.1. Large and small values of the loss could have been achieved with fewer samples or fewer steps, respectively, and correcting for this inefficiency by standardizing to the critical batch size results in cleaner and more predictable trends. In this section we will adjust for this oversight. More importantly, we will use the results of Section 5 to determine the optimal allocation of compute between model size N and the quantity of data processed during training, namely 2BcritSmin. We will determine this allocation both empirically and theoretically, by using the equation for L(N, Smin), and we will demonstrate that these methods agree. # 6.1 Optimal Performance and Allocations Let us first study the loss as a function of the optimally allocated compute from Equation (5.5). The result is plotted in Figure 13, along with a power-law fit. We see that as compared to the compute plot of Figure 1, the new fit with Cmin is somewhat improved. Given L(Cmin), it is natural to ask for the optimal model size N (Cmin) that provides the minimal loss with a given quantity of training compute. The optimal model size is shown in Figure 14. We observe that N (Cmin) 6One might ask why we did not simply train at Bcrit in the first place. The reason is that it depends not only on the model but also on the target value of the loss we wish to achieve, and so is a moving target. 15 —e— Smin (adjusted) 150004 ~--- Spin = (5.4 +103) C293 —e— S (fixed-batch) =--- N=(1.3-10°) «C873 min ~--- N=(1,6-109) C88 min 107 eB R| oI Zo ® | ) ae o 8 ete 2.10000 = 105 ne a g an £ ow “| z a a 5000 3 103 a £ - a - * “ 0 10-7 10-5 10-8 10-1 10-7 10-5 10-3 10-1 Compute (PF-days), non-embedding Compute (PF-days), excluding embeddings Figure 14 Left: Each value of the compute budget Cmin has an associated optimal model size N . Optimal model size grows very rapidly with Cmin, increasing by 5x for each 10x increase in compute. The number of data examples processed makes up the remainder of the increase, growing relatively modestly by only 2x. Right: The batch-adjusted number of optimization steps also grows very slowly, if at all, meaning that most of the growth in data examples processed can be used for increased batch sizes. can be fit very well with a power-law N (Cmin) ∝ (Cmin)0.73. (6.1) In Figure 12, we show the effect of training models of sub-optimal sizes (see Appendix B.4). By definition Cmin ≡ 6N BcritS, and so we can use N (Cmin) to extract further results. In particular, since prior fits show B ∝ L−4.8 and L ∝ C −0.05 min . This leads us to conclude that the optimal number of steps will only grow very slowly with compute, as Smin ∝ (Cmin)0.03, (6.2) matching the empirical results in Figure 14. In fact the measured exponent is sufficiently small that our results may even be consistent with an exponent of zero. Thus we conclude that as we scale up language modeling with an optimal allocation of computation, we should predominantly increase the model size N , while simultaneously scaling up the batch size via B ∝ Bcrit with negligible increase in the number of serial steps. Since compute-efficient training uses relatively few optimization steps, additional work on speeding up early training dynamics may be warranted. # 6.2 Predictions from L(N, Smin) The results for L(Cmin) and the allocations can be predicted from the L(N, Smin) equation obtained in Section 5. Given our equation for L(N, Smin), we can substitute Smin = Cmin 6N B and then find the minimum of the loss as a function of N , while fixing the training compute. We carry out this procedure in detail in Appendix B, where we also provide some additional predictions. For the loss as a function of training compute, we predict that U(Cnin) = (F ) (63) Crnin where αmin C ≡ 1 1/αS + 1/αB + 1/αN ≈ 0.054 (6.4) in excellent agreement with the exponent of Figure 13. We also predict that N (Cmin) ∝ (Cmin)αmin C /αN ≈ (Cmin)0.71 (6.5) which also matches the scaling of Figure 14 to within a few percent. Our scaling laws provide a predictive framework for the performance of language modeling. 16 Poa uw =-=- L(Cmin) ~ — L(D(C)) Pe 2 a oO Test Loss w i) The intersection point is sensitive to | the precise power-law parameters 10-8 10-5 10-? 10! 10+ 107 Compute (PF-days), non-embedding 1.5 Figure 15 Far beyond the model sizes we study empirically, we find a contradiction between our equations for L(Cmin) and L(D) due to the slow growth of data needed for compute-efficient training. The intersection marks the point before which we expect our predictions to break down. The location of this point is highly sensitive to the precise exponents from our power-law fits. # 6.3 Contradictions and a Conjecture We observe no signs of deviation from straight power-law trends at large values of compute, data, or model size. Our trends must eventually level off, though, since natural language has non-zero entropy. Indeed, the trends for compute-efficient training described in this section already contain an apparent contra- diction. At scales several orders of magnitude above those documented here, the performance predicted by the L(Cmin) scaling law decreases below what should be possible given the slow growth in training data with compute. This implies that our scaling laws must break down before this point, but we conjecture that the intersection point has a deeper meaning: it provides an estimate of the point at which Transformer language models reach maximal performance. Since the amount of data used by compute-efficient training grows slowly with the compute budget, the performance predicted by L(Cmin) eventually hits a lower bound set by the L(D) power law (see Figure 15). Let us work this out in more detail. To keep overfitting under control, the results of Section 4 imply that we should scale the dataset size as D ∝ N 0.74 ∝ C 0.54 min (6.6) where we have used the compute-efficient N (Cmin) from Figure 14. Let us compare this to the data requirements of compute-efficient training. If we train at the critical batch size (i.e. C = 2Cmin) and never re-use data during training, we find that data usage grows with compute as — _2Cnin 6N(Cmin) D(Cwnin) & (4 x 101° tokens) (C\inin/PF-Day)°?6 (6.7) This is the maximum rate at which the dataset size can productively grow with compute, since it means that we are only training for a single epoch. But it grows the dataset much more slowly than in Equation (6.6). It appears to imply that compute-efficient training will eventually run into a problem with overfitting, even if the training process never re-uses any data! According to Figure 1, we expect that when we are bottlenecked by the dataset size (ie by overfitting), the loss should scale as L(D) ∝ D−0.095. This implies that the loss would scale with compute as L(D(Cmin)) ∝ C −0.03 once we are data-limited. Once again, we have a contradiction, as this will eventually intersect with min our prediction for L(Cmin) from Figure 13, where we found a scaling L(Cmin) ∝ C −0.050 The intersection point of L(D(Cmin)) and L(Cmin) occurs at # min C ∗ ∼ 104 PF-Days N ∗ ∼ 1012 parameters, D∗ ∼ 1012 tokens, L∗ ∼ 1.7 nats/token though the numerical values are highly uncertain, varying by an order or magnitude in either direction de- pending on the precise values of the exponents from the power-law fits. The most obvious interpretation is that our scaling laws break down at or before we reach this point, which is still many orders of magnitude away in both compute and model size. 17 (6.8) One might also conjecture that this intersection point has a deeper meaning. If we cannot increase the model size beyond N ∗ without qualitatively different data requirements, perhaps this means that once we reach C ∗ min and N ∗, we have extracted all of the reliable information available in natural language data. In this interpretation, L∗ would provide a rough estimate for the entropy-per-token7 of natural language. In this scenario, we would expect the loss trend to level off at or before L∗. We can guess at the functional form of L(Cmin) as it levels off by considering a version of our training dataset with added noise. For example, we could append a random string of tokens to each context shown to the model to artificially boost the loss by a constant additive factor. Then, the distance from the noise floor L − Lnoise would be a more meaningful performance metric, with even a small decrease in this distance potentially representing a significant boost in qualitative performance. Since the artificial noise would affect all of our trends equally, the critical point of 6.8 would not change (aside from the absolute value of L∗), and may be meaningful even if it occurs after the leveling off. # 7 Related Work Power laws can arise from a wide variety of sources [THK18]. Power-law scalings with model and dataset size in density estimation [Was06] and in random forest models [Bia12] may be connected with our results. These models suggest that power-law exponents may have a very rough interpretation as the inverse of the number of relevant features in the data. Some early [BB01, Goo01] work found power-law scalings between performance and dataset size. More recent work [HNA+17, HAD19] also investigated scaling between model size and data size; their work is perhaps the closest to ours in the literature8. Note, however, that [HNA+17] found super-linear scaling of dataset size with model size, whereas we find a sub-linear scaling. There are some parallels between our findings on optimal allocation of compute and [Kom19], including power-law learning curves. EfficientNets [TL19] also appear to obey an approximate power-law relation between accuracy and model size. Very recent work [RRBS19b] studies scaling with both dataset size and model size for a variety of datasets, and fits an ansatz similar to ours. EfficientNet [TL19] advocates scaling depth and width exponentially (with different coefficients) for optimal performance of image models, resulting in a power-law scaling of width as a function of depth. We find that for language models this power should be roughly one when scaling up (as width/depth should remain fixed). But more importantly, we find that the precise architectural hyperparameters are unimportant compared to the overall scale of the language model. In [VWB16] it was argued that deep models can function as ensembles of shallower models, which could potentially explain this finding. Earlier work [ZK16] has compared width and depth, and found that wide ResNets can outperform deep ResNets on image classification. Some studies fix computation per data example, which tends to scale in proportion to the number of model parameters, whereas we investigate scaling with both model size and the quantity of training computation. Various works [AS17, BHMM18] have investigated generalization in highly overparameterized models, find- ing a “jamming transition” [GJS+19] when the model size reaches the dataset size (this may require training many orders of magnitude beyond typical practice, and in particular does not use early stopping). We do not observe such a transition, and find that the necessary training data scales sublinearly in the model size. Expansions in the model size, particularly at large width [JGH18, LXS+19], may provide a useful framework for thinking about some of our scaling relations. Our results on optimization, such as the shape of learning curves, can likely be explained using a noisy quadratic model, which can provide quite accurate predictions [ZLN+19] in realistic settings. Making this connection quantitative will require a characterization of the Hessian spectrum [Pap18, GKX19, GARD18]. # 8 Discussion We have observed consistent scalings of language model log-likelihood loss with non-embedding parameter count N , dataset size D, and optimized training computation Cmin, as encapsulated in Equations (1.5) and (1.6). Conversely, we find very weak dependence on many architectural and optimization hyperparameters. Since scalings with N, D, Cmin are power-laws, there are diminishing returns with increasing scale. 7Defining words using the wc utility, the WebText2 dataset has 1.4 tokens per word and 4.3 characters per token. 8After this work was completed, [RRBS19a] also appeared, which makes similar predictions for the dependence of loss on both model and dataset size. 18 We were able to precisely model the dependence of the loss on N and D, and alternatively on N and S, when these parameters are varied simultaneously. We used these relations to derive the compute scaling, magnitude of overfitting, early stopping step, and data requirements when training large language models. So our scaling relations go beyond mere observation to provide a predictive framework. One might interpret these relations as analogues of the ideal gas law, which relates the macroscopic properties of a gas in a universal way, independent of most of the details of its microscopic consituents. It is natural to conjecture that the scaling relations will apply to other generative modeling tasks with a maximum likelihood loss, and perhaps in other settings as well. To this purpose, it will be interesting to test these relations on other domains, such as images, audio, and video models, and perhaps also for random network distillation. At this point we do not know which of our results depend on the structure of natural language data, and which are universal. It would also be exciting to find a theoretical framework from which the scaling relations can be derived: a ‘statistical mechanics’ underlying the ‘thermodynamics’ we have observed. Such a theory might make it possible to derive other more precise predictions, and provide a systematic understanding of the limitations of the scaling laws. In the domain of natural language, it will be important to investigate whether continued improvement on the loss translates into improvement on relevant language tasks. Smooth quantitative change can mask major qualitative improvements: “more is different”. For example, the smooth aggregate growth of the economy provides no indication of the specific technological developments that underwrite it. Similarly, the smooth improvements in language model loss may hide seemingly qualitative changes in capability. Our results strongly suggest that larger models will continue to perform better, and will also be much more sample efficient than has been previously appreciated. Big models may be more important than big data. In this context, further investigation into model parallelism is warranted. Deep models can be trained using pipelining [HCC+18], which splits parameters depth-wise between devices, but eventually requires increased batch sizes as more devices are used. Wide networks on the other hand are more amenable to parallelization [SCP+18], since large layers can be split between multiple workers with less serial dependency. Sparsity [CGRS19, GRK17] or branching (e.g. [KSH12]) may allow for even faster training of large networks through increased model parallelism. And using methods like [WRH17, WYL19], which grow networks as they train, it might be possible to remain on the compute-efficient frontier for an entire training run. # Acknowledgements We would like to thank Shan Carter, Paul Christiano, Jack Clark, Ajeya Cotra, Ethan Dyer, Jason Eisner, Danny Hernandez, Jacob Hilton, Brice Menard, Chris Olah, and Ilya Sutskever for discussions and for feed- back on drafts of this work. 19 # Appendices # A Summary of Power Laws For easier reference, we provide a summary below of the key trends described throughout the paper. Parameters | Data | Compute | Batch Size | Equation N 0° oo Fixed L(N) = (N./N)°* oo D_ | Early Stop Fixed L(D) =(D,./D)°” Optimal oo Cc Fixed L(C) = (C./C)°° (naive) Nopt Dopt | Cmin | BK Berit | L(Cmin) = (C™™/Cmnin) “© an ~D N D | Early Stop | Fixed =| L(N,D)= () SD + 5] N 0° S' steps B L(N,S)= (42 ON (===) ° Table 4 The empirical fitted values for these trends are: Power Law Scale (tokenization-dependent) Nc = 8.8 × 1013 params (non-embed) Dc = 5.4 × 1013 tokens Cc = 1.6 × 107 PF-days αN = 0.076 αD = 0.095 αC = 0.057 C = 0.050 C min αmin αB = 0.21 c = 3.1 × 108 PF-days B∗ = 2.1 × 108 tokens Sc = 2.1 × 103 steps αS = 0.76 # Table 5 The optimal parameters for compute efficient training are given by: Compute-Efficient Value Power Law | Scale Nopt = Ne» CP* pn = 0.73 | Ne =1.3- 10° params ‘min B< Bein = Goze = BeChR, | pp =0.24 | B. = 2.0- 10° tokens min Smin = Se + CPS, (lower bound) | pg = 0.03 S. = 5.4+ 10° steps Dopt = De» CRP, (1 epoch) Pp =0.27 | De =2-10!° tokens Table 6 # B Empirical Model of Compute-Efficient Frontier Throughout this appendix all values of C, S, and αC are adjusted for training at the critical batch size Bcrit. We have left off the ‘adj’ label to avoid cluttering the notation. # B.1 Defining Equations The power-law fit to the learning curves implies a simple prescription for compute-efficient training. In this appendix, we will derive the optimal performance, model size, and number of training steps as a function of 20 the compute budget. We start with the Equation (1.6), repeated here for convenience: bovsy=(%)"+ (8) 6. Here, S represents the number of parameter updates when training at the critical batch size [MKAT18], which was defined in Equation (5.2)9: B (L) = B∗ L1/αB . (B.2) We would like to determine optimal training parameters for a fixed compute budget, so we replace S = C/ (6N B (L)), where C is the number of FLOPs used in the training run: Ne an . N as L(N,C) () t (08.5.2) . (B.3) Now, we set On L| c= 0 to find the condition for optimality: Now, we set On L| c= 0 to find the condition for optimality: _ ab. ~ ON'e an (Ne an ag N as N OL t BS 1-—5— N () N (0 8 ae) ° TAN 'c an Ne an N as 5B. B4 a () C s, amc) (B4) =⇒ Equation (B.3) and (B.4) together determine the compute-efficient frontier. # B.2 Efficient Training Now we assemble the implications of (B.3) and (B.4). First, note that inserting (B.4) into (B.3) yields L (Neff (C) , C) = 1 + αN αS L (Neff , ∞) , (B.5) which implies that for compute-efficient training, we should train to a fixed percentage αN ≈ 10% above αS the converged loss. Next, let’s determine how the optimal loss depends on the compute budget. Eliminating N yields a power-law dependence of performance on compute: C.\% L(C) =| > B.6 @)=($) 6.6) where we defined αC = 1/ (1/αS + 1/αB + 1/αN ) ≈ 0.052 (B.7) V/as+1/an _\ las C. = 6N.B.S. (1 + ox) (2) ; (BS) as an Similarly, we can eliminate L to find N (C): N(C) C\ee/en ay \ Vex — {= 14— B. Ne (=) + as (B) and αN αS 9There is a slight ambiguity here: we can imagine training either at a constant batch size B (Ltarget), or we could instead train at a variable batch size ˜B (L), where ˜B is the instantaneous critical batch size (as opposed to B, which is the averaged version). These two prescriptions result in the same number of steps, so we can ignore this subtlety (see [MKAT18]). 21 (B.4) # B.3 Comparison to Inefficient Typically, researchers train models until they appear to be close to convergence. In this section, we compare the efficient training procedure described above to this more typical setup. We define a the convergence factor f as the percent deviation from the converged loss: L (N, C) = (1 + f ) L (N, ∞) . (B.11) For compute-efficient training we have f = an/ags * 10% from the previous section, but researchers typically use a much smaller value. Here, we choose f’ = 2% as an estimate. For a fixed value of the loss, we predict: Ny l+f 1/an af 2. B.12 ¥ (; + a 7 (B.12) # l+f (; + a 1+4 f 1+ ji Ny Sp Np Sp l/as 1+4 # i Sp = ≈ 0.13 (B.13) Cr _ Ny Sp = = 0.35 B.14 Cr Np Sp ° ane So that compute-efficient training uses 7.7x fewer parameter updates, 2.7x more parameters, and 65% less compute to reach the same loss. # B.4 Suboptimal Model Sizes We can solve A.1 to find an expression for the amount of compute needed to reach a given value of the loss L with a model of size N : any —l/ag C(N,L) (0.5. 2757) (z (=) ) . (B.15) Using A.6 and A.9, we can eliminate L in favor of Neff (L), the model size which reaches L most efficiently. From there, we find an expression for the excess compute needed as a consequence of using a suboptimal model size: αS αN The result is shown in Figure X. Models between 0.6x and 2.2x the optimal size can be used with only a 20% increase in compute budget. Using a smaller model is useful when accounting for the cost inference. A larger model can be trained the the same level of performance in fewer steps, allowing for more parallelism and faster training if sufficient harware is available (see Figure Y): S(N, Nes) } _ os (1 (“yyy B17 S (Nes, Ne) " an N , (B.17) A 2.2x larger model requires 45% fewer steps at a cost of 20% more training compute. Note that this equation should not be trusted for very large models, as it is only valid in the power-law region of the learning curve after initial transient effects. # C Caveats In this section we list some potential caveats to our analysis. • At present we do not have a solid theoretical understanding for any of our proposed scaling laws. The scaling relations with model size and compute are especially mysterious. It may be possible to understand scaling at very large D holding model size fixed [AS17], and also the shape of learning curves late in training, by modeling the loss with a noisy quadratic. But the scaling with D at very large model size still remains mysterious. Without a theory or a systematic understanding of the corrections to our scaling laws, it’s difficult to determine in what circumstances they can be trusted. 22 — Test Loss 101° 5 ---- Train Loss g ad g 9 4 10° 4 a 7a 3 2 108 § a 2 103 104 105 Step — Test Loss 101° Early Stopping Step 5 ---- Train Loss ee ° . Data Size 108 ata Se 4 10° ° aM 4 g © 86M 12M 104 o ou 3 © seam 108 © 148 10? |. _ ; _ 2 io) enmeneerts) 103 104 105 Sc x [L(N, D) —L(N, 2)]-¥%s Step Figure 16 Left: We characterize the step on which early stopping occurs, as a function of the extent of overfitting. The red line indicates a lower bound for early stopping that is derived in Section 5.3. Right: We display train and test loss for a series of 300M parameter models trained on different sized dataset sub- samples. The test loss typically follows that of a run done with unrestricted data until diverging. Note that the degree of overfitting (as compared to the infinite data limit) is significantly overestimated by Ltest − Ltrain (denoted by a black bar for each run). • We are not especially confident in the prediction of Bcrit(L) for values of the loss far outside the range we have explored. Changes in Bcrit could have a significant impact on trade-offs between data parallelism and the number of serial training steps required, which would have a major impact on training time. • We did not thoroughly investigate the small data regime, and our fits for L(N, D) were poor for the smallest values of D (where an epoch corresponded to only 40 steps). Furthermore, we did not experiment with regularization and data augmentation. Improvements in these could alter our results, quantitatively or qualitatively. e We used the estimated training compute C' + 6N BS, which did not include contributions propor- tional to netx (see Section So our scalings with compute may be confounded in practice in the regime of very large nctx, specifically where netx 2 12dmodel- • We tuned learning rates, and we experimented with learning rate schedules. But we may have neglected to tune some hyperparameter (e.g. intialization scale or momentum) that have an important effect on scaling. • The optimal choice of learning rate is sensitive to the target loss. When training close to convergence, it may be necessary to use a smaller learning rate to avoid divergences. But when conducting a short training run (eg due to compute limitations), it may be possible to use a larger learning rate. We did not experiment with higher learning rates for training runs that did not proceed to convergence. # D Supplemental Figures # D.1 Early Stopping and Test vs Train In section 5.3 we described the result shown in Figure 16, which provides a prediction for a lower bound on the early stopping step. We also show the train and test loss for a given model size when training on different sized datasets. # D.2 Universal Transformers We compare the performance of standard Transformers to recurrent Transformers [DGV+18] in Figure 17. These models re-use parameters, and so perform slightly better as a function of N , but slightly worse as a function of compute C. We include several different different possibilities for parameter re-use. # D.3 Batch Size We measure the critical batch size using the data displayed in figure 18. This made it possible to estimate Bcrit(L) in figure 10. 23 as} 45} s —e— 2x Reuse —e— 4x Reuse 4.0 4.0 ~*~ 8x Reuse a 8 - Non-recurrent Models 93.5 83.5 B B & 3.0, 2x Reuse & 3.0 —e— 4x Reuse ~*~ 8x Reuse 2.5] ---- Non-recurrent Models . 2.5 S 105 10° 107 108 109 105 10° 107 108 109 Parameters, including reuse (non-embedding) Parameters (non-embedding) Figure 17 We compare recurrent Transformers [DGV+18], which re-use parameters, to standard Trans- formers. Recurrent Transformers perform slightly better when comparing models with equal parameter count, but slightly worse when accounting for reuse and comparing per FLOP. Batch Size Scan - 3M Params tot 10 1910 a 8 § 10° g £ & 108 6 2 4 § 107 Be z 4 108 Batch Size Scan - 85M Params 10 3 101° 2 8 8 g 10 4 & 10 6 3 § & é 10° 4 Batch Size Scan - 3M Params Batch Size Scan - 85M Params tot 10 10 1910 3 101° 8 2 8 10° g 8 Sf 10 4 108 6 2 & 10 6 $4 107 Be § & 4 é 10° 4 108 Figure 18 These figures demonstrate fits to Equation (5.1) for a large number of values of the loss L, and for two different Transformer model sizes. These fits were used to measure Bcrit(L) for Figure 10. # D.4 Sample Efficiency vs Model Size It is easy to see from figure 2 that larger models train faster, and are therefore more sample efficient. We provide another way of looking at this phenomenon in figure 19, which shows when different models reach various fixed values of the loss. 55 zie 5.0 € a 45 é a 2 108 404 q 357 & ¢ 30 J 163 S———— 25 105 107 108 Parameters (non-embedding) aon 5.5 £ ~~ 5.0 w @ 1910 45 e s 4.0 a & 10 3.5 EI 3.0 2 108 eee & _ 25 105 107 108 Parameters (non-embedding) 55 aon 5.5 zie 5.0 £ ~~ 5.0 € w a 45 @ 1910 45 é e a 2 108 404 s 4.0 q 357 & 10 3.5 & EI ¢ 30 3.0 J 163 S———— 2 108 eee 25 & _ 25 105 107 108 105 107 108 Parameters (non-embedding) Parameters (non-embedding) Figure 19 The number of minimum serial steps needed to reach any fixed value of the test loss decreases precipitously with model size. Sample efficiency (show here for training far below the critical batch size) improves greatly as well, improving by a factor of almost 100 when comparing the smallest possible model to a very large one. 24 Per-token Loss (774M Params) 103 10 4» g 102 § 8 SI =I 4 4 oa a 2 6 S ad F 101 8 a 4 2 - 10° 101 103 105 Step Per-token Loss (774M Params) 103 8 woe 4,043.2: TO 10 a7 3.444,.0- TO a 2.944.5-TO58 Fa} § 27449:728 10°S 4» g 102 26 24 os o 8 7 <-- 2445.1-T #3 & Wo. 23454.728 § 4 u oa a5 3s 2 6 oS 107% i 3 F 101 4 3 S 4 s 2 i 3 108 2 - 10° 10° 10? 102 103 101 103 105 Token Index Step 8 woe 4,043.2: TO a7 3.444,.0- TO a 2.944.5-TO58 Fa} § 27449:728 10°S 26 24 os o 7 <-- 2445.1-T & Wo. 23454.728 § u a5 3s oS 107% i 3 4 3 S s 2 i 3 108 10° 10? 102 103 Token Index Figure 20 This figure provides information about the performance per token as a function of model size and training time. Left: Loss per token as a function of its position T in the 1024-token context. Loss scales predictably as a power-law in T . Right: Test loss per token as a function of training step. —— Token 1/1024 —— Token 2/1024 —— Token 4/1024 —— Token 8/1024 —s— Token 16/1024 —*— Token 64/1024 —s— Token 256/1024 =~ Token 1024/1024 Token 1/8 Token 2/8 Token 4/8 -=- Token 8/8 Test Loss 3.0 104 10° 10° 10” 108 10° Parameters (excl. embedding) Figure 21 In addition to the averaged loss, individual tokens within the 1024-token context also improve smoothly as model size increases. Training runs with shorter context nctx = 8 (dashed lines) perform better on early tokens, since they can allocate all of their capacity to them. # D.5 Context Dependence The trends for loss as a function of model size are displayed for different tokens in the context in Figure 21. We see that models trained on nctx = 1024 show steady improvement with model size on all but the first token. Fixing model size, it appears that the loss scales as a power-law as a function of position T in the context, see Figure 20. This may be a consequence of underlying power-law correlations in language [EP94, ACDE12, LT16], or a more general feature of the model architecture and optimization. It provides some suggestion for the potential benefits (or lack thereof) from training on larger contexts. Not only do larger models converge to better performance at T = 1024, but they also improve more quickly at early tokens, suggesting that larger models are more efficient at detecting patterns with less contextual information. In the right-hand plot we show how per-token performance varies for a fixed model as a function of the training step. The model begins by learning short-range information, and only learns longer-range correlations later in training. We have also included models trained with a tiny context nctx = 8 in order to compare with our longer context models. Even modestly sized models trained on nctx = 8 can dominate our largest nctx = 1024 models on very early tokens. This also suggests that further improvements should be possible with much larger models trained on large contexts. # D.6 Learning Rate Schedules and Error Analysis We experimented with a variety of learning rates and schedules. A host of schedules and resulting test performances for a small language model are plotted in Figure 22. We conclude that the choice of learning rate schedule is mostly irrelevant, as long as the total summed learning rate is sufficiently large, and the schedule includes a warmup period and a final decay to near-vanishing learning rate. Variations among 25 3.90 . 3.85, . 3 ° 3 . Ey 2 a © oe ° g 8 oe oe 5 a 3.75, eo’ ov "we e . g coe ° ee ° eo. 2? 3.70 ° i 3.65 0 50000 100000 150000 200000 250000 50 100 150 200 250 Step LR Summed Over Steps 4 # fi Figure 22 We test a variety of learning rate schedules including cosine decay, linear decay, as well as other faster/slower decays schedules on a 3 million parameter model, shown on the left. For these experiments we do not decay to zero, since we find that this tends to give a fixed improvement close to the end of training. We find that, as long as the learning rate is not too small and does not decay too quickly, performance does not depend strongly on learning rate. Run-to-run variation is at the level of 0.05 in the loss, so averaging multiple runs is necessary to validate performance changes smaller than this level. a6 13)-0.076 e —— L=(N/8.8-10+*) a —— L= —0.25log(N/7.1-1012) i) BS S i=] 8 4 4 Ff 43 B i) & 2 10 10° 108 107 108 109 Parameters (non-embedding) Figure 23 The trend for performance as a function of parameter count, L(N ), is fit better by a power law than by other functions such as a logarithm at a qualitative level. schedules appear to be statistical noise, and provide a rough gauge for the scale of variation between different training runs. Experiments on larger models suggest that the variation in the final test loss between different random seeds is roughly constant in magnitude for different model sizes. We found that larger models require a smaller learning rate to prevent divergence, while smaller models can tolerate a larger learning rate. To implement this, the following rule of thumb was used for most runs: LR(N ) ≈ 0.003239 + −0.0001395 log(N ) We expect that this formula could be improved. There may be a dependence on network width, likely set by the initialization scale. The formula also breaks down for N > 1010 parameters. Nevertheless, we found that it works sufficiently well for the models we considered. # D.7 Fit Details and Power Law Quality We experimented with a number of functional forms for the fits to L(N ), L(C), and L(D); the power-law fits were qualitatively much more accurate than other functions such as logarithms (see Figure 23). For L(C), we do not include small models with only 1 layer in the fit, as the transition from 1 to 2 layers causes a noticable lump in the data. For L(N ) we also do not include very small models with only 1 layer in the fit, and we exclude the largest models that have not trained fully to convergence. Fit parameters change marginally if we do include them, and the trend extrapolates well in both directions regardless. # D.8 Generalization and Architecture In figure 24 we show that generalization to other data distributions does not depend on network depth when we hold the total parameter count fixed. It seems to depend only on the performance on the training distribution. 26 (D.1) 2.8 a 27 —® Wikipedia S —®- Books 4 2.6 —e- Internet Books a —e Common Crawl 25 Se —e— WebText2 (Train) —e- WebText2 (Test) a Se 2.3 See 10" 10? Depth Figure 24 We show evaluations on a series of datasets for models with approximately 1.5 Billion param- eters. We observe no effect of depth on generalization; generalization performance depends primarily on training distribution performance. The 12-layer model overfit the Internet Books dataset and we show the early-stopped performance; we have not seen this surprising result in other experiments. # List of Figures 1 Summary of simple power laws. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Illustration of sample efficiency and compute efficiency. . . . . . . . . . . . . . . . . . . . . 3 How to scale up model size, batch size, and serial steps . . . . . . . . . . . . . . . . . . . . 4 Performance when varying model and data size, or model and training steps, simultaneously 5 Weak dependence of performance on hyperparameter tuning . . . . . . . . . . . . . . . . . 6 Comparison of performance trend when including or excluding embeddings . . . . . . . . . 7 LSTM and Transformer performance comparison . . . . . . . . . . . . . . . . . . . . . . . 8 Generalization to other test datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Universality of overfitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Critical batch size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Performance versus compute budget or number of parameter updates . . . . . . . . . . . . . 12 Training on suboptimal models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Comparison between empirical and adjusted compute trends . . . . . . . . . . . . . . . . . 14 Optimal model size and serial number of steps versus compute budget . . . . . . . . . . . . 15 Contradiction between compute and data trends . . . . . . . . . . . . . . . . . . . . . . . . 16 Early stopping lower bound and training curves for overfit models . . . . . . . . . . . . . . 17 Universal transformers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Batch size scans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Another look at sample efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Power-law dependence of performance on position in context . . . . . . . . . . . . . . . . . 21 Performance at different context positions versus model size . . . . . . . . . . . . . . . . . 22 Learning rate schedule scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Comparison of Power-Law and Logarithmic Fits . . . . . . . . . . . . . . . . . . . . . . . 24 Generalization versus depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 4 5 8 8 9 10 11 12 14 15 15 16 17 23 24 24 24 25 25 26 26 27 27 # List of Tables 1 Parameter and compute counts for Transformer . . . . . . . . . . . . . . . . . . . . . . . . 2 Fits to L(N, D) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Fits to L(N, S) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Key trend equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Key parameters to trend fits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Trends for compute-efficient training . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 11 14 20 20 20 # References [ACDE12] Eduardo G Altmann, Giampaolo Cristadoro, and Mirko Degli Esposti. On the origin of long- range correlations in texts. Proceedings of the National Academy of Sciences, 109(29):11582– 11587, 2012. 25 Madhu S. Advani and Andrew M. Saxe. High-dimensional dynamics of generalization error in neural networks. arXiv, 2017, 1710.03667. 11, 18, 22 Michele Banko and Eric Brill. Scaling to very very large corpora for natural language disam- biguation. In Proceedings of the 39th annual meeting on association for computational linguis- tics, pages 26–33. Association for Computational Linguistics, 2001. 18 [BHMM18] Mikhail Belkin, Daniel Hsu, Siyuan Ma, and Soumik Mandal. Reconciling modern machine learning and the bias-variance trade-off. arXiv, 2018, 1812.11118. 18 GÊrard Biau. Analysis of a random forests model. Journal of Machine Learning Research, 13(Apr):1063–1095, 2012. 18 [CGRS19] Rewon Child, Scott Gray, Alec Radford, and Ilya Sutskever. Generating long sequences with sparse transformers. CoRR, abs/1904.10509, 2019, 1904.10509. URL http://arxiv.org/ abs/1904.10509. 19 Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. Bert: Pre-training of deep bidirectional transformers for language understanding, 2018, arXiv:1810.04805. 2 [DGV+18] Mostafa Dehghani, Stephan Gouws, Oriol Vinyals, Jakob Uszkoreit, and Lukasz Kaiser. Uni- versal transformers. CoRR, abs/1807.03819, 2018, 1807.03819. URL http://arxiv.org/ abs/1807.03819. 6, 9, 23, 24 Werner Ebeling and Thorsten Pöschel. Entropy and long-range correlations in literary english. EPL (Europhysics Letters), 26(4):241, 1994. 25 The Common Crawl Foundation. Common crawl. URL http://commoncrawl.org. 7 [GARD18] Guy Gur-Ari, Daniel A. Roberts, and Ethan Dyer. Gradient descent happens in a tiny subspace. 2018, arXiv:1812.04754. 18 [GJS+19] Mario Geiger, Arthur Jacot, Stefano Spigler, Franck Gabriel, Levent Sagun, Stéphane d’Ascoli, Giulio Biroli, Clément Hongler, and Matthieu Wyart. Scaling description of generalization with number of parameters in deep learning. arXiv, 2019, 1901.01608. 18 Behrooz Ghorbani, Shankar Krishnan, and Ying Xiao. An investigation into neural net op- timization via hessian eigenvalue density. CoRR, abs/1901.10159, 2019, 1901.10159. URL http://arxiv.org/abs/1901.10159. 18 Joshua Goodman. A bit of progress in language modeling. CoRR, cs.CL/0108005, 2001. URL http://arxiv.org/abs/cs.CL/0108005. 18 Scott Gray, Alec Radford, and Diederik P Kingma. Gpu kernels for block-sparse weights. ope- nai.com, 2017. 19 Joel Hestness, Newsha Ardalani, and Gregory Diamos. Beyond human-level accuracy: Compu- tational challenges in deep learning. In Proceedings of the 24th Symposium on Principles and Practice of Parallel Programming, PPoPP ’19, pages 1–14, New York, NY, USA, 2019. ACM. doi:10.1145/3293883.3295710. 18 28 [HCC+18] Yanping Huang, Yonglong Cheng, Dehao Chen, HyoukJoong Lee, Jiquan Ngiam, Quoc V. Le, and Zhifeng Chen. Gpipe: Efficient training of giant neural networks using pipeline parallelism. CoRR, abs/1811.06965, 2018, 1811.06965. URL http://arxiv.org/abs/1811.06965. 19 [HNA+17] Joel Hestness, Sharan Narang, Newsha Ardalani, Gregory Diamos, Heewoo Jun, Hassan Kia- ninejad, Md. Mostofa Ali Patwary, Yang Yang, and Yanqi Zhou. Deep learning scaling is pre- dictable, empirically, 2017, 1712.00409. 18 Arthur Jacot, Franck Gabriel, and Clément Hongler. Neural tangent kernel: Convergence and generalization in neural networks. In Advances in neural information processing systems, pages 8571–8580, 2018. 18 Diederik P. Kingma and Jimmy Ba. Adam: A method for stochastic optimization, 2014, 1412.6980. 7 Aran Komatsuzaki. One epoch is all you need, 2019, arXiv:1906.06669. 18 Imagenet classification with deep Alex Krizhevsky, Ilya Sutskever, and Geoffrey E. Hinton. convolutional neural networks. In Proceedings of the 25th International Conference on Neural Information Processing Systems - Volume 1, NIPS’12, pages 1097–1105, USA, 2012. Curran Associates Inc. URL http://dl.acm.org/citation.cfm?id=2999134.2999257. 19 [LCG+19] Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu Soricut. Albert: A lite bert for self-supervised learning of language representations, 2019, 1909.11942. 9 [LOG+19] Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. Roberta: A robustly optimized BERT pretrain- ing approach. CoRR, abs/1907.11692, 2019, 1907.11692. URL http://arxiv.org/abs/ 1907.11692. 2 # [LSPt 18] [LT 16] Peter J. Liu, Mohammad Saleh, Etienne Pot, Ben Goodrich, Ryan Sepassi, Lukasz Kaiser, and Noam Shazeer. Generating wikipedia by summarizing long sequences. arXiv:1801.10198 [cs], 2018, 1801.10198. URL http://arxiv.org/abs/1801.10198. 2, 6 Henry W Lin and Max Tegmark. Criticality in formal languages and statistical physics. arXiv preprint arXiv:1606.06737, 2016. 25 Jaehoon Lee, Lechao Xiao, Samuel S. Schoenholz, Yasaman Bahri, Roman Novak, Jascha Sohl- Dickstein, and Jeffrey Pennington. Wide neural networks of any depth evolve as linear models under gradient descent, 2019, arXiv:1902.06720. 18 [MKAT18] Sam McCandlish, Jared Kaplan, Dario Amodei, and OpenAI Dota Team. An empirical model of large-batch training, 2018, arXiv:1812.06162. 3, 5, 6, 12, 13, 21 Vardan Papyan. The full spectrum of deep net hessians at scale: Dynamics with sample size. CoRR, abs/1811.07062, 2018, 1811.07062. URL http://arxiv.org/abs/1811.07062. 18 Improving language understanding by generative pre-training. URL https://s3-us-west-2. amazonaws. com/openai- assets/research-covers/languageunsupervised/language understanding paper. pdf, 2018. 2, 6 [RRBS19a] Jonathan S. Rosenfeld, Amir Rosenfeld, Yonatan Belinkov, and Nir Shavit. A constructive prediction of the generalization error across scales, 2019, 1909.12673. 18 [RRBS19b] Jonathan S. Rosenfeld, Amir Rosenfeld, Yonatan Belinkov, and Nir Shavit. A constructive prediction of the generalization error across scales, 2019, arXiv:1909.12673. 18 [RSR+19] 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, 2019, arXiv:1910.10683. 2 [RWC+19] Alec Radford, Jeff Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. openai.com, 2019. 2, 5, 6, 7, 8 [SCP+18] Noam Shazeer, Youlong Cheng, Niki Parmar, Dustin Tran, Ashish Vaswani, Penporn Koanan- takool, Peter Hawkins, HyoukJoong Lee, Mingsheng Hong, Cliff Young, Ryan Sepassi, and Blake Hechtman. Mesh-tensorflow: Deep learning for supercomputers, 2018, 1811.02084. 19 Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. CoRR, 2015, 1508.07909. 6 29 [SS18] [THK18] [TL19] [VSP+17] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Ł ukasz Kaiser, and Illia Polosukhin. Attention is all you need. In I. Guyon, U. V. Luxburg, S. Bengio, H. Wallach, R. Fergus, S. Vishwanathan, and R. Garnett, editors, Advances in Neural Information Processing Systems 30, pages 5998–6008. Curran Associates, Inc., 2017. URL http://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf. 2, 6 [VWB16] Andreas Veit, Michael Wilber, and Serge Belongie. Residual networks behave like ensembles [Was06] of relatively shallow networks, 2016, arXiv:1605.06431. 8, 18 Larry Wasserman. All of nonparametric statistics. Springer Science & Business Media, 2006. 18 [WPN+19] 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, 2019, 1905.00537. 2 [WRH17] Yu-Xiong Wang, Deva Ramanan, and Martial Hebert. Growing a brain: Fine-tuning by in- creasing model capacity. 2017 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), Jul 2017. doi:10.1109/cvpr.2017.323. 19 [WYL19] Wei Wen, Feng Yan, and Hai Li. Autogrow: Automatic layer growing in deep convolutional networks, 2019, 1906.02909. 19 [YDY+19] Zhilin Yang, Zihang Dai, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, and Quoc V. Xlnet: Generalized autoregressive pretraining for language understanding, 2019, Le. arXiv:1906.08237. 2 Sergey Zagoruyko and Nikos Komodakis. Wide residual networks. Procedings of the British Machine Vision Conference 2016, 2016. doi:10.5244/c.30.87. 18 [ZK16] [ZKZ+15] Yukun Zhu, Ryan Kiros, Rich Zemel, Ruslan Salakhutdinov, Raquel Urtasun, Antonio Tor- ralba, and Sanja Fidler. Aligning books and movies: Towards story-like visual explanations by watching movies and reading books. 2015 IEEE International Conference on Computer Vision (ICCV), Dec 2015. doi:10.1109/iccv.2015.11. 7 [ZLN+19] Guodong Zhang, Lala Li, Zachary Nado, James Martens, Sushant Sachdeva, George E. Dahl, Christopher J. Shallue, and Roger B. Grosse. Which algorithmic choices matter at which batch sizes? insights from a noisy quadratic model. CoRR, abs/1907.04164, 2019, 1907.04164. URL http://arxiv.org/abs/1907.04164. 12, 18 30
Title: GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers: Summary: Generative Pre-trained Transformer models, known as GPT or OPT, set themselves apart through breakthrough performance across complex language modelling tasks, but also by their extremely high computational and storage costs. Specifically, due to their massive size, even inference for large, highly-accurate GPT models may require multiple performant GPUs, which limits the usability of such models. While there is emerging work on relieving this pressure via model compression, the applicability and performance of existing compression techniques is limited by the scale and complexity of GPT models. In this paper, we address this challenge, and propose GPTQ, a new one-shot weight quantization method based on approximate second-order information, that is both highly-accurate and highly-efficient. Specifically, GPTQ can quantize GPT models with 175 billion parameters in approximately four GPU hours, reducing the bitwidth down to 3 or 4 bits per weight, with negligible accuracy degradation relative to the uncompressed baseline. Our method more than doubles the compression gains relative to previously-proposed one-shot quantization methods, preserving accuracy, allowing us for the first time to execute an 175 billion-parameter model inside a single GPU for generative inference. Moreover, we also show that our method can still provide reasonable accuracy in the extreme quantization regime, in which weights are quantized to 2-bit or even ternary quantization levels. We show experimentally that these improvements can be leveraged for end-to-end inference speedups over FP16, of around 3.25x when using high-end GPUs (NVIDIA A100) and 4.5x when using more cost-effective ones (NVIDIA A6000). The implementation is available at https://github.com/IST-DASLab/gptq. at ICLR 2023 GPTQ: ACCURATE POST-TRAINING QUANTIZATION FOR GENERATIVE PRE-TRAINED TRANSFORMERS Saleh Ashkboos ETH Zurich Torsten Hoefler ETH Zurich Dan Alistarh IST Austria & NeuralMagic # ABSTRACT Generative Pre-trained Transformer models, known as GPT or OPT, set them- selves apart through breakthrough performance across complex language mod- elling tasks, but also by their extremely high computational and storage costs. Specifically, due to their massive size, even inference for large, highly-accurate GPT models may require multiple performant GPUs, which limits the usability of such models. While there is emerging work on relieving this pressure via model compression, the applicability and performance of existing compression techniques is limited by the scale and complexity of GPT models. In this paper, we address this challenge, and propose GPTQ, a new one-shot weight quantiza- tion method based on approximate second-order information, that is both highly- accurate and highly-efficient. Specifically, GPTQ can quantize GPT models with 175 billion parameters in approximately four GPU hours, reducing the bitwidth down to 3 or 4 bits per weight, with negligible accuracy degradation relative to the uncompressed baseline. Our method more than doubles the compression gains rel- ative to previously-proposed one-shot quantization methods, preserving accuracy, allowing us for the first time to execute an 175 billion-parameter model inside a single GPU for generative inference. Moreover, we also show that our method can still provide reasonable accuracy in the extreme quantization regime, in which weights are quantized to 2-bit or even ternary quantization levels. We show ex- perimentally that these improvements can be leveraged for end-to-end inference speedups over FP16, of around 3.25x when using high-end GPUs (NVIDIA A100) and 4.5x when using more cost-effective ones (NVIDIA A6000). The implemen- tation is available at https://github.com/IST-DASLab/gptq. # INTRODUCTION Pre-trained generative models from the Transformer (Vaswani et al., 2017) family, commonly known as GPT or OPT (Radford et al., 2019; Brown et al., 2020; Zhang et al., 2022), have shown break- through performance for complex language modelling tasks, leading to massive academic and prac- tical interest. One major obstacle to their usability is computational and storage cost, which ranks among the highest for known models. For instance, the best-performing model variants, e.g. GPT3- 175B, have in the order of 175 billion parameters and require tens-to-hundreds of GPU years to train (Zhang et al., 2022). Even the simpler task of inferencing over a pre-trained model, which is our focus in this paper, is highly challenging: for instance, the parameters of GPT3-175B occupy 326GB (counting in multiples of 1024) of memory when stored in a compact float16 format. This exceeds the capacity of even the highest-end single GPUs, and thus inference must be performed using more complex and expensive setups, such as multi-GPU deployments. Although a standard approach to eliminating these overheads is model compression, e.g. (Hoefler et al., 2021; Gholami et al., 2021), surprisingly little is known about compressing such models for inference. One reason is that more complex methods for low-bitwidth quantization or model prun- ing usually require model retraining, which is extremely expensive for billion-parameter models. Alternatively, post-training methods (Nagel et al., 2020; Wang et al., 2020; Hubara et al., 2020; Nahshan et al., 2021), which compress the model in one shot, without retraining, would be very appealing. Unfortunately, the more accurate variants of such methods (Li et al., 2021; Hubara et al., 2021; Frantar et al., 2022) are complex and challenging to scale to billions of parameters (Yao et al., ∗Corresponding author: elias.frantar@ist.ac.at 1 Published as a conference paper at ICLR 2023 2022). To date, only basic variants of round-to-nearest quantization (Yao et al., 2022; Dettmers et al., 2022) have been applied at the scale of GPT-175B; while this works well for low compression targets, e.g., 8-bit weights, they fail to preserve accuracy at higher rates. It therefore remains open whether one-shot post-training quantization to higher compression rates is generally-feasible. 50 OPT Model Family BLOOM Model Family Ld : t 3 4 : n 45 A : 2 60 . : t 110): a, £4 : S71 gy“ Y 50 nN Fd . Fd E35 : € z z = 30 = 40 ry 4 3bit RTN 5 5 4 3bit GPTQ Bes B30 FP16 Ay Ay 220 e G > 2 20 “157 m= 4bit RTN * ro} = aoiecpTQ: UTR af © FPI6 0 EES SSS SS 5 107? 10° 107 107 10° 107 10? #params in billions #params in billions Figure 1: Quantizing OPT models to 4 and BLOOM models to 3 bit precision, comparing GPTQ with the FP16 baseline and round-to-nearest (RTN) (Yao et al., 2022; Dettmers et al., 2022). Contribution. In this paper, we present a new post-training quantization method, called GPTQ,1 which is efficient enough to execute on models with hundreds of billions of parameters in at most a few hours, and precise enough to compress such models to 3 or 4 bits per parameter without significant loss of accuracy. For illustration, GPTQ can quantize the largest publicly-available mod- els, OPT-175B and BLOOM-176B, in approximately four GPU hours, with minimal increase in perplexity, known to be a very stringent accuracy metric. Further, we show that our model can also provide robust results in the extreme quantization regime, in which models are quantized to 2 bits per component, or even ternary values. On the practical side, we develop an execution harness which allows us to execute the resulting compressed models efficiently for generative tasks. Specifically, we are able to run the compressed OPT-175B model for the first time on a single NVIDIA A100 GPU, or using only two more cost-effective NVIDIA A6000 GPUs. We also implement bespoke GPU kernels which are able to leverage compression for faster memory loading, resulting in speedups of ≈ 3.25× when using A100 GPUs, and 4.5× when using A6000 GPUs. To our knowledge, we are the first to show that extremely accurate language models with hundreds of billions of parameters can be quantized to 3-4 bits/component: prior post-training methods only remain accurate at 8 bits (Yao et al., 2022; Dettmers et al., 2022), while prior training-based tech- niques have only tackled models that are smaller by one to two orders of magnitude (Wu et al., 2022). This high degree of compression may appear natural, as these networks are overparametrized; yet, as we discuss in our detailed analysis of results, compression induces non-trivial tradeoffs between the accuracy of the language modeling (perplexity), bit-width, and the size of the original model. We hope that our work will stimulate further research in this area, and can be a further step towards making these models available to a wider audience. In terms of limitations, our method currently does not provide speedups for the actual multiplications, due to the lack of hardware support for mixed-precision operands (e.g. FP16 x INT4) on mainstream architectures. Moreover, our current results do not include activation quantization, as they are not a significant bottleneck in our target scenarios; however, this can be supported using orthogonal techniques (Yao et al., 2022). # 2 RELATED WORK Quantization methods fall broadly into two categories: quantization during training, and post- training methods. The former quantize models during typically extensive retraining and/or fine- tuning, using some approximate differentiation mechanism for the rounding operation (Gholami et al., 2021; Nagel et al., 2021). By contrast, post-training (“one-shot”) methods quantize a pre- 1This merges the name of the OPT model family with the abbreviation for post-training quantization (PTQ). 2 Published as a conference paper at ICLR 2023 trained model using modest resources, typically a few thousand data samples and a few hours of computation. Post-training approaches are particularly interesting for massive models, for which full model training or even finetuning can be expensive. We focus on this scenario here. Post-training Quantization. Most post-training methods have focused on vision models. Usually, accurate methods operate by quantizing either individual layers, or small blocks of consecutive layers. (See Section 3 for more details.) The AdaRound method (Nagel et al., 2020) computes a data-dependent rounding by annealing a penalty term, which encourages weights to move towards grid points corresponding to quantization levels. BitSplit (Wang et al., 2020) constructs quantized values bit-by-bit using a squared error objective on the residual error, while AdaQuant (Hubara et al., 2021) performs direct optimization based on straight-through estimates. BRECQ (Li et al., 2021) introduces Fisher information into the objective, and optimizes layers within a single residual block jointly. Finally, Optimal Brain Quantization (OBQ) (Frantar et al., 2022) generalizes the classic Optimal Brain Surgeon (OBS) second-order weight pruning framework (Hassibi et al., 1993; Singh & Alistarh, 2020; Frantar et al., 2021) to apply to quantization. OBQ quantizes weights one-by-one, in order of quantization error, always adjusting the remaining weights. While these approaches can produce good results for models up to ≈ 100 million parameters in a few GPU hours, scaling them to networks orders of magnitude larger is challenging. Large-model Quantization. With the recent open-source releases of language models like BLOOM (Laurenc¸on et al., 2022) or OPT-175B (Zhang et al., 2022), researchers have started to develop affordable methods for compressing such giant networks for inference. While all exist- ing works—ZeroQuant (Yao et al., 2022), LLM.int8() (Dettmers et al., 2022), and nuQmm (Park et al., 2022)— carefully select quantization granularity, e.g., vector-wise, they ultimately just round weights to the nearest (RTN) quantization level, in order to maintain acceptable runtimes for very large models. ZeroQuant further proposes layer-wise knowledge distillation, similar to AdaQuant, but the largest model it can apply this approach to has only 1.3 billion parameters. At this scale, ZeroQuant already takes ≈ 3 hours of compute; GPTQ quantizes models 100× larger in ≈ 4 hours. LLM.int8() observes that activation outliers in a few feature dimensions break the quantization of larger models, and proposes to fix this problem by keeping those dimensions in higher preci- sion. Lastly, nuQmm develops efficient GPU kernels for a specific binary-coding based quantization scheme. Relative to this line of work, we show that a significantly more complex and accurate quantizer can be implemented efficiently at large model scale. Specifically, GPTQ more than doubles the amount of compression relative to these prior techniques, at similar accuracy. # 3 BACKGROUND Layer-Wise Quantization. At a high level, our method follows the structure of state-of-the-art post-training quantization methods (Nagel et al., 2020; Wang et al., 2020; Hubara et al., 2021; Fran- tar et al., 2022), by performing quantization layer-by-layer, solving a corresponding reconstruction problem for each layer. Concretely, let Wz, be the weights corresponding to a linear layer @ and let X_, denote the layer input corresponding to a small set of m data points running through the network. Then, the objective is to find a matrix of quantized weights W which minimizes the squared error, relative to the full precision layer output. Formally, this can be restated as argming, || WX — WX ||}. (1) Further, similar to (Nagel et al., 2020; Li et al., 2021; Frantar et al., 2022), we assume that the quantization grid for W is fixed before the process, and that individual weights can move freely as in (Hubara et al., 2021; Frantar et al., 2022). Optimal Brain Quantization. Our approach builds on the recently-proposed Optimal Brain Quanization (OBQ) method (Frantar et al., 2022) for solving the layer-wise quantization problem defined above, to which we perform a series of major modifications, which allow it to scale to large language models, providing more than three orders of magnitude computational speedup. To aid understanding, we first briefly summarize the original OBQ method. The OBQ method starts from the observation that Equation (1) can be written as the sum of the squared errors, over each row of W. Then, OBQ handles each row w independently, quantizing one weight at a time while always updating all not-yet-quantized weights, in order to compensate for the error incurred by quantizing a single weight. Since the corresponding objective is a quadratic, 3 Published as a conference paper at ICLR 2023 whose Hessian is Hp = 2X pX}, where F' denotes the set of remaining full-precision weights, the greedy-optimal weight to quantize next, which we denote by w,, and the corresponding optimal update of all weights in F’, denoted by dp, are given by the following formulas, where quant(w) rounds w to the nearest value on the quantization grid: wq = argminwq (quant(wq) − wq)2 [H−1 F ]qq , δF = − wq − quant(wq) [H−1 F ]qq · (H−1 F ):,q. (2) OBQ quantizes weights iteratively using these two equations, until all the weights of w are quan- tized. This is done efficiently, avoiding expensive full recomputations of H~!, by removing the gth row and column of H, which is necessary after quantizing wg, directly in the inverse via one step of Gaussian elimination. Namely, the updated inverse is given by the formula _ 1 _ 1 [Haq H-} = (H' H./H,!) )) —P This method comes with a vectorized implementation, handling multiple rows of W in parallel. Eventually, the algorithm can achieve reasonable runtimes on medium-sized models: for instance, it can fully quantize the ResNet-50 model (25M parameters) in ≈ 1 hour on a single GPU, which is roughly in line with other post-training methods achieving state-of-the-art accuracy (Frantar et al., 2022). However, the fact that OBQ’s runtime for a drow × dcol matrix W has cubic input dependency O(drow · d3 col) means that applying it to models with billions of parameters is extremely expensive. # 4 THE GPTQ ALGORITHM Step 1: Arbitrary Order Insight. As explained in the previous section, OBQ quantizes weights in greedy order, i.e. it always picks the weight which currently incurs the least additional quantization error. Interestingly, we find that, while this quite natural strategy does indeed seem to perform very well, its improvement over quantizing the weights in arbitrary order is generally small, in particular on large, heavily-parametrized layers. Most likely, this is because the slightly lower number of quantized weights with large individual error is balanced out by those weights being quantized towards the end of the process, when only few other unquantized weights that can be adjusted for compensation remain. As we will now discuss, this insight that any fixed order may perform well, especially on large models, has interesting ramifications. The original OBQ method quantizes rows of W independently, in a specific order defined by the corresponding errors. By contrast, we will aim to quantize the weights of all rows in the same order, and will show that this typically yields results with a final squared error that is simi- lar to the original solutions. As a consequence, the set of unquantized weights F and similarly H−1 F is always the same for all rows (see Fig- ure 2 for an illustration). In more detail, the lat- ter is due to the fact that HF depends only on the layer inputs XF , which are the same for all rows, and not on any weights. Therefore, we have to perform the update of H−1 F given by Equation (3) only dcol times, once per column, rather than drow·dcol times, once per weight. This reduces the overall runtime from O(drow · d3 col) col, d3 to O(max {drow · d2 col}), i.e., by a factor of min {drow, dcol}. For larger models, this differ- ence consists of several orders of magnitude. However, before this algorithm can actually be applied to very large models in practice, two ad- ditional major problems need to be addressed. # Inverse Layer Hessian / (Cholesky Form) ; Unquantized weights [Ty wartzesweiants TT hat are updated Weight Matrix Block block i quantized recursively computed initially column-by-column Figure 2: GPTQ quantization procedure. Blocks of consecutive columns (bolded) are quantized at a given step, using the inverse Hessian informa- tion stored in the Cholesky decomposition, and the remaining weights (blue) are updated at the end of the step. The quantization procedure is applied recursively inside each block: the white middle column is currently being quantized. Step 2: Lazy Batch-Updates. First, a direct implementation of the scheme described previously will not be fast in practice, because the algorithm has a relatively low compute-to-memory-access ratio. For example, Equation (3) needs to update all elements of a potentially huge matrix using just a 4 Published as a conference paper at ICLR 2023 few FLOPs for each entry. Such operations cannot properly utilize the massive compute capabilities of modern GPUs, and will be bottlenecked by the significantly lower memory bandwidth. Fortunately, this problem can be resolved by the following observation: The final rounding decisions for column i are only affected by updates performed on this very column, and so updates to later columns are irrelevant at this point in the process. This makes it possible to “lazily batch” updates together, thus achieving much better GPU utilization. Concretely, we apply the algorithm to B = 128 columns at a time, keeping updates contained to those columns and the corresponding B × B block of H−1 (see also Figure 2). Only once a block has been fully processed, we perform global updates of the entire H−1 and W matrices using the multi-weight versions of Equations (2) and (3) given below, with Q denoting a set of indices, and H−1 −Q denoting the inverse matrix with the corresponding rows and columns removed: δF = −(wQ − quant(wQ))([H−1 F ):,Q, (4) | (Hz")..2; -1qzq-1 H−1 H−1 − H−1 :,Q([H−1]QQ)−1H−1 −Q = . Q,: −Q (5) Although this strategy does not reduce the theoretical amount of compute, it effectively addresses the memory-throughput bottleneck. This provides an order of magnitude speedup for very large models in practice, making it a critical component of our algorithm. Step 3: Cholesky Reformulation. The final technical issue we have to address is given by numeri- cal inaccuracies, which can become a major problem at the scale of existing models, especially when combined with the block updates discussed in the previous step. Specifically, it can occur that the matrix H−1 F becomes indefinite, which we notice can cause the algorithm to aggressively update the remaining weights in incorrect directions, resulting in an arbitrarily-bad quantization of the corre- sponding layer. In practice, we observed that the probability of this happening increases with model size: concretely, it almost certainly occurs for at least a few layers on models that are larger than a few billion parameters. The main issue appears to be the repeated applications of Equation (5), which accumulate various numerical errors, especially through the additional matrix inversion. For smaller models, applying dampening, that is adding a small constant λ (we always choose 1% of the average diagonal value) to the diagonal elements of H appears to be sufficient to avoid numerical issues. However, larger models require a more robust and general approach. To address this, we begin by noting that the only information required from H−1 , where Fq denotes Fq the set of unquantized weights when quantizing weight q, is row q, or more precisely, the elements in this row starting with the diagonal. The consequence is that we could precompute all of these rows using a more numerically-stable method without any significant increase in memory consumption. Indeed, the row removal via (3) for our symmetric H−1 essentially corresponds to taking a Cholesky decomposition, except for the minor difference that the latter divides row q by ([H−1 ]qq)1/2. Hence, Fq we can leverage state-of-the-art Cholesky kernels to compute all information we will need from H−1 upfront. In combination with mild dampening, the resulting method is robust enough to execute on huge models without issues. As a bonus, using a well-optimized Cholesky kernel also yields further speedup. We detail all small changes necessary for the Cholesky version of the algorithm next. The Full Algorithm. Finally, we present the full pseudocode for GPTQ in Algorithm 1, including the optimizations discussed above. Algorithm 1 Quantize W given inverse Hessian H~! = (2X X' + AI)~1 and blocksize B. Q & Dag, x deo // quantized output E+ 04,.%B // block quantization errors H™! © Cholesky(H~')* // Hessian inverse information fori = 0, B,2B,... do for j =i,...,i+B-—1do Q.,; <— quant(W. ;) // quantize column E.j-1 — (W,; — Q.,;) / [Hi // quantization error W. 5:43) — W.5:44B) — E.j-i- 1; ewe // update weights in block end for W.(i4B): — W. +B), —E- Byii.a) itn): // update all remaining weights end for 5 Published as a conference paper at ICLR 2023 # 5 EXPERIMENTAL VALIDATION Overview. We begin our experiments by validating the accuracy of GPTQ relative to other accurate- but-expensive quantizers, on smaller models, for which these methods provide reasonable runtimes. Next, we examine GPTQ’s runtime scaling for very large models. Then, we present 3- and 4-bit quantization results for the entire BLOOM and OPT model families, evaluated via perplexity on challenging language generation tasks. In addition, we show that our method is also stable for 2-bit quantization when the granularity is reduced to small blocks of consecutive weights. To complement this perplexity analysis, we also evaluate the resulting quantized models on a series of standard zero- shot tasks. Finally, we focus on the two largest (and interesting) openly-available models, Bloom- 176B and OPT-175B, where we perform a detailed evaluation on several tasks. For these models, we also present practical improvements, namely reducing the number of GPUs required for inference as well as end-to-end speedups for generative tasks. Setup. We implemented GPTQ in PyTorch (Paszke et al., 2019) and worked with the HuggingFace integrations of the BLOOM (Laurenc¸on et al., 2022) and OPT (Zhang et al., 2022) model families. We quantized all models (including the 175 billion parameter variants) using a single NVIDIA A100 GPU with 80GB of memory. Our entire GPTQ calibration data consists of 128 random 2048 token segments from the C4 dataset (Raffel et al., 2020), i.e., excerpts from randomly crawled websites, which represents generic text data. We emphasize that this means that GPTQ does not see any task-specific data, and our results thus remain actually “zero-shot”. We perform standard uniform per-row asymmetric quantization on the min-max grid, similar to Dettmers et al. (2022). Additional evaluation details can be found in Appendix A.2.1. To ensure that the entire compression procedure can be performed with significantly less GPU mem- ory than what would be required to run the full precision model, some care must be taken. Specif- ically, we always load one Transformer block, consisting of 6 layers, at a time into GPU memory and then accumulate the layer-Hessians and perform quantization. Finally, the current block inputs are sent through the fully quantized block again to produce the new inputs for the quantization of the next block. Hence, the quantization process operates not on the layer inputs in the full precision model but on the actual layer inputs in the already partially quantized one. We find that this brings noticeable improvements at negligible extra cost. Baselines. Our primary baseline, denoted by RTN, consists of rounding all weights to the nearest quantized value on exactly the same asymmetric per-row grid that is also used for GPTQ, meaning that it corresponds precisely to the state-of-the-art weight quantization of LLM.int8(). This is cur- rently the method of choice in all works on quantization of very large language models (Dettmers et al., 2022; Yao et al., 2022; Park et al., 2022): its runtime scales well to networks with many bil- lions of parameters, as it simply performs direct rounding. As we will also discuss further, more accurate methods, such as AdaRound (Nagel et al., 2020) or BRECQ (Li et al., 2021), are currently too slow for models with many billions of parameters, the main focus of this work. Nevertheless, we also show that GPTQ is competitive with such methods for small models, while scaling to huge ones like OPT-175B as well. Quantizing Small Models. As a first ablation study, we compare GPTQ’s performance relative to state-of-the-art post-training quantization (PTQ) methods, on ResNet18 and ResNet50, which are standard PTQ benchmarks, in the same setup as (Frantar et al., 2022). As can be seen in Table 1, GPTQ performs on par at 4-bit, and slightly worse than the most accurate methods at 3-bit. At the same time, it significantly outperforms AdaQuant, the fastest amongst prior PTQ methods. Further, we compare against the full greedy OBQ method on two smaller language models: BERT-base (De- vlin et al., 2019) and OPT-125M. The results are shown in Appendix Table 8. At 4 bits, both methods perform similarly, and for 3 bits, GPTQ surprisingly performs slightly better. We suspect that this is because some of the additional heuristics used by OBQ, such as early outlier rounding, might require careful adjustments for optimal performance on non-vision models. Overall, GPTQ appears to be competitive with state-of-the-art post-training methods for smaller models, while taking only < 1 minute rather than ≈ 1 hour. This enables scaling to much larger models. Runtime. Next we measure the full model quantization time (on a single NVIDIA A100 GPU) via GPTQ; the results are shown in Table 2. As can be seen, GPTQ quantizes 1-3 billion parameter models in a matter of minutes and 175B ones in a few hours. For reference, the straight-through based method ZeroQuant-LKD (Yao et al., 2022) reports a 3 hour runtime (on the same hardware) for a 1.3B model, which would linearly extrapolate to several hundred hours (a few weeks) for 175B 6 Published as a conference paper at ICLR 2023 Method RN18 – 69.76 % RN50 – 76.13% 4bit 3bit 4bit 3bit AdaRound AdaQuant BRECQ OBQ 69.34 68.12 69.37 69.56 68.37 59.21 68.47 68.69 75.84 74.68 75.88 75.72 75.14 64.98 75.32 75.24 GPTQ 69.37 67.88 75.71 74.87 OPT 13B 30B 66B 175B Runtime 20.9m 44.9m 1.6h 4.2h BLOOM 1.7B 3B 7.1B 176B Runtime 2.9m 5.2m 10.0m 3.8h Table 1: Comparison with state-of-the-art post-training methods for vision models. Table 2: GPTQ runtime for full quantization of the 4 largest OPT and BLOOM models. models. Adaptive rounding-based methods typically employ a lot more SGD steps and would thus be even more expensive (Nagel et al., 2020; Li et al., 2021). Language Generation. We begin our large-scale study by compressing the entire OPT and BLOOM model families to 3- and 4-bit. We then evaluate those models on several language tasks including WikiText2 (Merity et al., 2016) (see Figure 1 as well as Tables 3 and 4), Penn Treebank (PTB) (Mar- cus et al., 1994) and C4 (Raffel et al., 2020) (both in Appendix A.3). We focus on these perplexity- based tasks, as they are known to be particularly sensitive to model quantization (Yao et al., 2022). On OPT models, GPTQ clearly outperforms RTN, by significant margins. For example, GPTQ loses only 0.03 perplexity at 4-bit on the 175B model, while RTN drops 2.2 points, performing worse than the 10× smaller full-precision 13B model. At 3-bit, RTN collapses completely, while GPTQ can still maintain reasonable perplexity, in particular for larger models. BLOOM shows a similar pattern: the gaps between methods are however usually a bit smaller, indicating that this model family might be easier to quantize. One interesting trend (see also Figure 1) is that larger models generally (with the exception of OPT-66B2) appear easier to quantize. This is good news for practical applications, as these are the cases where compression is also the most necessary. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B 30B 66B 175B full 16 27.65 22.00 14.63 12.47 10.86 10.13 9.56 9.34 8.34 RTN GPTQ 4 4 37.28 31.12 25.94 24.24 48.17 15.47 16.92 12.87 12.10 11.39 11.32 10.31 10.98 9.63 110 9.55 10.54 8.37 RTN GPTQ 3 3 1.3e3 53.85 64.57 33.79 1.3e4 20.97 1.6e4 16.88 5.8e3 14.86 3.4e3 11.61 1.6e3 10.27 6.1e3 14.16 7.3e3 8.68 Table 3: OPT perplexity results on WikiText2. BLOOM Bits 560M 1.1B 1.7B 3B 7.1B 176B full 16 22.42 17.69 15.39 13.48 11.37 8.11 RTN GPTQ 4 4 25.90 24.03 22.00 19.05 16.97 16.48 14.76 14.20 12.10 11.73 8.37 8.21 RTN GPTQ 3 3 57.08 32.31 50.19 25.08 63.59 21.11 39.36 17.40 17.38 13.47 571 8.64 Table 4: BLOOM perplexity results for WikiText2. 175 Billion Parameter Models. We now examine BLOOM-176B and OPT-175B, the largest dense openly-available models. Table 5 summarizes results across Wikitext-2, PTB, C4. We observe that, at 4 bits, GPTQ models reach only ≤ 0.25 lower perplexity than the full-precision versions, with a large gap to RTN results on OPT-175B. At 3-bit, RTN collapses, while GPTQ is still able to maintain good performance on most tasks, losing only 0.3 − 0.6 points for more than 5× compression. We note that GPTQ’s accuracy can be further improved via finer-granularity grouping (Park et al., 2022): group-size 1024 (≈ 0.02 extra bits) improves perplexities by about 0.2 on average and group-size 128 (≈ 0.15 extra bits) by another 0.1, which is only 0.1 − 0.3 off from the uncompressed accuracy. 2Upon closer inspection of the OPT-66B model, it appears that this is correlated with the fact that this trained model has a significant fraction of dead units in the early layers, which may make it harder to compress. 7 Published as a conference paper at ICLR 2023 We note that grouping interacts very well with GPTQ, as the group parameters can be determined during the quantization process of each layer, always using the most current updated weights. Method Bits Wiki2 OPT-175B PTB C4 LAMB. ↑ Wiki2 BLOOM-176B PTB C4 LAMB. ↑ Baseline 16 8.34 12.01 10.13 75.59 8.11 14.59 11.71 67.40 RTN GPTQ 4 4 10.54 8.37 14.22 12.26 11.61 10.28 71.34 76.80 8.37 8.21 15.00 14.75 12.04 11.81 66.70 67.71 RTN GPTQ 3 3 7.3e3 8.68 8.0e3 12.68 4.6e3 10.67 0 76.19 571. 8.64 107. 15.57 598. 12.27 0.17 65.10 GPTQ GPTQ 3/g1024 3/g128 8.45 8.45 12.48 12.37 10.47 10.36 77.39 76.42 8.35 8.26 15.01 14.89 11.98 11.85 67.47 67.86 Table 5: Results summary for OPT-175B and BLOOM-176B. “g1024” and “g128” denote results with groupings of size 1024 and 128, respectively. Practical Speedups. Finally, we study practical applications. As an interesting use-case, we focus on the OPT-175B model: quantized to 3 bits, this model takes approximately 63GB of memory, including the embeddings and the output layer, which are kept in full FP16 precision. Additionally, storing the complete history of keys and values for all layers, a common optimization for generation tasks, consumes another ≈ 9GB for the maximum of 2048 tokens. Hence, we can actually fit the entire quantized model into a single 80GB A100 GPU, which can be executed by dynamically dequantizing layers as they are required during inference (the model would not fully fit using 4 bits). For reference, standard FP16 execution requires 5x80GB GPUs, and the state-of-the-art 8bit LLM.int8() quantizer (Dettmers et al., 2022) requires 3 such GPUs. Next, we consider language generation, one of the most appealing applications of these models, with the goal of latency reduction. Unlike LLM.int8(), which reduces memory costs but has the same runtime as the FP16 baseline, we show that our quantized models can achieve significant speedups for this application. For language generation, the model processes and outputs one token at-a-time, which for OPT-175B can easily take a few 100s of milliseconds per token. Increasing the speed at which the user receives generated results is challenging, as compute is dominated by matrix-vector products. Unlike matrix-matrix products, these are primarily limited by memory bandwidth. We address this problem by developing a quantized-matrix full-precision-vector product kernel which performs a matrix vector product by dynamically dequantizing weights when needed. Most notably, this does not require any activation quantization. While dequantization consumes extra compute, the kernel has to access a lot less memory, leading to significant speedups, as shown in Table 6. We note that almost all of the speedup is due to our kernels, as communication costs are negligible in our standard HuggingFace-accelerate-like setting (see Appendix A.2.2 for details). GPU FP16 3bit Speedup GPU reduction A6000 – 48GB 589ms 230ms A100 – 80GB 130ms 71ms 4.53× 3.24× 8 → 2 5 → 1 Table 6: Average per-token latency (batch size 1) when generating sequences of length 128. For example, using our kernels, the 3-bit OPT-175B model obtained via GPTQ running on a single A100 is about 3.25× faster than the FP16 version (running on 5 GPUs) in terms of average time per token. More accessible GPUs, such as the NVIDIA A6000, have much lower memory bandwidth, so this strategy is even more effective: executing the 3-bit OPT-175B model on 2x A6000 GPUs reduces latency from 589 milliseconds for FP16 inference (on 8 GPUs) to 130 milliseconds, a 4.5× latency reduction. Zero-Shot Tasks. While our focus is on language generation, we also evaluate the performance of quantized models on some popular zero-shot tasks, namely LAMBADA (Paperno et al., 2016), ARC (Easy and Challenge) (Boratko et al., 2018) and PIQA (Tata & Patel, 2003). Figure 3 visualizes model performance on LAMBADA (and see also “Lamb.” results in Table 5). We observe similar behavior as before: the outliers are that 1) quantization appears “easier” across the whole spectrum of models at 4-bit, where even RTN performs relatively well, and 2) at 3-bit, RTN breaks down, while GPTQ still provides good accuracy. We provide additional results in Appendix A.4. 8 Published as a conference paper at ICLR 2023 © FP16 = 4bit GPTQ = 4bit RTN & = 3bit GPTQ 4 3bit RTN 0.8 OPT Family BLOOM Family << § Z 0.6 = s < 0.4 5 > z g $0.2 F g ¢ 10" 10° 10° 10? 10° 10? 102 #params in billions #params in billions Figure 3: The accuracy of OPT and BLOOM models post-GPTQ, measured on LAMBADA. Additional Tricks. While our experiments so far have focused exclusively on vanilla row-wise quantization, we want to emphasize that GPTQ is compatible with essentially any choice of quanti- zation grid. For example, it is easily combined with standard grouping (Alistarh et al., 2017; Park et al., 2022), i.e. applying independent quantization to groups of g consecutive weights. As shown in the last rows of Table 5, this can bring noticeable extra accuracy for the largest models at 3-bit. Fur- ther, as visualized in Figure 4, it significantly reduces the accuracy losses for medium sized models at 4-bit precision. Model FP16 g128 g64 g32 3-bit OPT-175B BLOOM 8.34 8.11 9.58 9.55 9.18 9.17 8.94 8.83 8.68 8.64 Table 7: 2-bit GPTQ quantization results with varying group-sizes; perplexity on WikiText2. Figure 4: GPTQ at 4-bit with different group-sizes on medium sized OPT models. Extreme Quantization. Lastly, grouping also makes it possible to achieve reasonable performance for extreme quantization, to around 2-bits per component on average. Table 7 shows results on WikiText2 when quantizing the biggest models to 2-bit with varying group-sizes. At ≈ 2.2 bit (group-size 128; using FP16 scale and 2-bit zero point per group) the perplexity increase is already less than 1.5 points, while dropping to 0.6 - 0.7 at ≈ 2.6 bit (group-size 32), which is only slightly worse than vanilla 3-bit and might be interesting for practical kernel implementations. Further, if we reduce group size to 8, we can apply ternary (-1, 0, +1) quantization, which achieves 9.20 WikiText2 PPL on OPT-175B, a less than 1 point drop. While this leads to worse compression on average relative to the 2-bit numbers above, this pattern could be efficiently implemented on custom hardware such as FPGAs. In summary, these results are an encouraging first step towards pushing highly-accurate one-shot compression of very large language models, even lower than 3 bits per value on average. # 6 SUMMARY AND LIMITATIONS We have presented GPTQ, an approximate second-order method for quantizing truly large language models. GPTQ can accurately compress some of the largest publicly-available models down to 3 and 4 bits, which leads to significant usability improvements, and to end-to-end speedups, at low accuracy loss. We hope that our method will make these models accessible to more researchers and practitioners. At the same time, we emphasize some significant limitations: On the technical side, our method obtains speedups from reduced memory movement, and does not lead to computational reductions. In addition, our study focuses on generative tasks, and does not consider activation quantization. These are natural directions for future work, and we believe this can be achieved with carefully-designed GPU kernels and existing techniques (Yao et al., 2022; Wu et al., 2022). 9 Published as a conference paper at ICLR 2023 # ACKNOWLEDGMENTS Elias Frantar and Dan Alistarh gratefully acknowledge funding from the European Research Coun- cil (ERC) under the European Union’s Horizon 2020 programme (grant agreement No. 805223 ScaleML), as well as experimental support from Eldar Kurtic, and from the IST Austria IT de- partment, in particular Stefano Elefante, Andrei Hornoiu, and Alois Schloegl. The work of Saleh Ashkboos and Torsten Hoefler was supported by the PASC DaCeMI project, received EuroHPC-JU funding under grant MAELSTROM, No. 955513. We thank the Swiss National Supercomputing Center (CSCS) for supporting us with compute infrastructure. # 7 ETHICS STATEMENT Our work introduces a general method for compressing large language models (LLMs) via quan- tization, with little-to-no accuracy loss in terms of standard accuracy metrics such as perplexity. Our method is task-agnostic, as it only uses a tiny amount of randomly-chosen data for calibration. We therefore do not foresee any significant ethical implications arising directly from the technical details of our method. However, one possible consideration is that our study focused on “leading accuracy” metrics that are standard in the literature, such as perplexity, which is essentially standard in the literature (Dettmers et al., 2022; Yao et al., 2022). We believe a thorough study of the impact of compression upon secondary measures, and in particular bias effects (Bender et al., 2021) is war- ranted, and may be rendered easier through our work. At the same time, our work makes inference on extremely large language models more accessible, for better or for worse. We believe that, in time, such tools will become much easier to use and deploy, making the need to understand their power and limitations even more stringent. # 8 REPRODUCIBILITY STATEMENT In the Supplementary Materials, we provide code to reproduce all experiments in this paper. More specifically, this includes: • Compressing all models from the OPT and BLOOM model families to 2/3/4 bits. • Evaluating perplexity of the quantized models. • Our 3-bit CUDA kernel together with compressed inference benchmarking features. • Code for the ZeroShot experiments. A README file providing sample commands and information on how to run all scripts. # REFERENCES Dan Alistarh, Demjan Grubic, Jerry Li, Ryota Tomioka, and Milan Vojnovic. QSGD: Randomized quantization for communication-efficient stochastic gradient descent. In Conference on Neural Information Processing Systems (NeurIPS), 2017. Emily M Bender, Timnit Gebru, Angelina McMillan-Major, and Shmargaret Shmitchell. On the dangers of stochastic parrots: Can language models be too big? In 2021 ACM Conference on Fairness, Accountability, and Transparency, 2021. Michael Boratko, Harshit Padigela, Divyendra Mikkilineni, Pritish Yuvraj, Rajarshi Das, Andrew McCallum, Maria Chang, Achille Fokoue-Nkoutche, Pavan Kapanipathi, Nicholas Mattei, et al. A systematic classification of knowledge, reasoning, and context within the ARC dataset. arXiv preprint arXiv:1806.00358, 2018. 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. In Conference on Neural Information Processing Systems (NeurIPS), 2020. Tri Dao, Daniel Y Fu, Stefano Ermon, Atri Rudra, and Christopher R´e. FlashAttention: Fast and memory-efficient exact attention with io-awareness. arXiv preprint arXiv:2205.14135, 2022. 10 Published as a conference paper at ICLR 2023 Tim Dettmers, Mike Lewis, Younes Belkada, and Luke Zettlemoyer. LLM.int8(): 8-bit matrix multiplication for transformers at scale. arXiv preprint arXiv:2208.07339, 2022. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training of deep bidirectional transformers for language understanding. In North American Chapter of the Associ- ation for Computational Linguistics (NAACL), 2019. Elias Frantar, Eldar Kurtic, and Dan Alistarh. M-FAC: Efficient matrix-free approximations of second-order information. In Conference on Neural Information Processing Systems (NeurIPS), 2021. Elias Frantar, Sidak Pal Singh, and Dan Alistarh. Optimal Brain Compression: A framework for ac- curate post-training quantization and pruning. arXiv preprint arXiv:2208.11580, 2022. Accepted to NeurIPS 2022, to appear. Amir Gholami, Sehoon Kim, Zhen Dong, Zhewei Yao, Michael W Mahoney, and Kurt Keutzer. arXiv preprint A survey of quantization methods for efficient neural network inference. arXiv:2103.13630, 2021. Babak Hassibi, David G Stork, and Gregory J Wolff. Optimal brain surgeon and general network pruning. In IEEE International Conference on Neural Networks, 1993. Torsten Hoefler, Dan Alistarh, Tal Ben-Nun, Nikoli Dryden, and Alexandra Peste. Sparsity in deep learning: Pruning and growth for efficient inference and training in neural networks. arXiv preprint arXiv:2102.00554, 2021. Improving post training neural quantization: Layer-wise calibration and integer programming. arXiv preprint arXiv:2006.10518, 2020. Itay Hubara, Yury Nahshan, Yair Hanani, Ron Banner, and Daniel Soudry. Accurate post train- ing quantization with small calibration sets. In International Conference on Machine Learning (ICML), 2021. Hugo Laurenc¸on, Lucile Saulnier, Thomas Wang, Christopher Akiki, Albert Villanova del Moral, Teven Le Scao, Leandro Von Werra, Chenghao Mou, Eduardo Gonz´alez Ponferrada, Huu Nguyen, et al. The BigScience corpus: A 1.6 TB composite multilingual dataset. 2022. Yuhang Li, Ruihao Gong, Xu Tan, Yang Yang, Peng Hu, Qi Zhang, Fengwei Yu, Wei Wang, and In Shi Gu. BRECQ: Pushing the limit of post-training quantization by block reconstruction. International Conference on Learning Representations (ICLR), 2021. Mitch Marcus, Grace Kim, Mary Ann Marcinkiewicz, Robert MacIntyre, Ann Bies, Mark Ferguson, Karen Katz, and Britta Schasberger. The penn treebank: Annotating predicate argument structure. In Human Language Technology: Proceedings of a Workshop held at Plainsboro, New Jersey, March 8-11, 1994, 1994. Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher. Pointer sentinel mixture models. arXiv preprint arXiv:1609.07843, 2016. Markus Nagel, Rana Ali Amjad, Mart Van Baalen, Christos Louizos, and Tijmen Blankevoort. Up or down? Adaptive rounding for post-training quantization. In International Conference on Machine Learning (ICML), 2020. Markus Nagel, Marios Fournarakis, Rana Ali Amjad, Yelysei Bondarenko, Mart van Baalen, arXiv preprint and Tijmen Blankevoort. A white paper on neural network quantization. arXiv:2106.08295, 2021. Yury Nahshan, Brian Chmiel, Chaim Baskin, Evgenii Zheltonozhskii, Ron Banner, Alex M Bron- stein, and Avi Mendelson. Loss aware post-training quantization. Machine Learning, 110(11): 3245–3262, 2021. Denis Paperno, Germ´an Kruszewski, Angeliki Lazaridou, Quan Ngoc Pham, Raffaella Bernardi, Sandro Pezzelle, Marco Baroni, Gemma Boleda, and Raquel Fern´andez. The LAMBADA dataset: Word prediction requiring a broad discourse context. arXiv preprint arXiv:1606.06031, 2016. 11 Published as a conference paper at ICLR 2023 Gunho Park, Baeseong Park, Se Jung Kwon, Byeongwook Kim, Youngjoo Lee, and Dongsoo Lee. nuQmm: Quantized matmul for efficient inference of large-scale generative language models. arXiv preprint arXiv:2206.09557, 2022. Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, et al. Pytorch: An imperative style, high- In Conference on Neural Information Processing Systems performance deep learning library. (NeurIPS), 2019. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9, 2019. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter Liu. Exploring the limits of transfer learning with a unified text-to-text transformer. Journal of Machine Learning Research, 21(140):1–67, 2020. Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, and Percy Liang. SQuAD: 100,000+ questions for machine comprehension of text. In Conference on Empirical Methods in Natural Language Processing (EMNLP), 2016. Sidak Pal Singh and Dan Alistarh. WoodFisher: Efficient second-order approximation for neural network compression. In Conference on Neural Information Processing Systems (NeurIPS), 2020. Sandeep Tata and Jignesh M Patel. PiQA: An algebra for querying protein data sets. In International Conference on Scientific and Statistical Database Management, 2003. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, In Conference on Neural In- Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. formation Processing Systems (NeurIPS), 2017. Peisong Wang, Qiang Chen, Xiangyu He, and Jian Cheng. Towards accurate post-training network quantization via bit-split and stitching. In International Conference on Machine Learning (ICML), 2020. Xiaoxia Wu, Zhewei Yao, Minjia Zhang, Conglong Li, and Yuxiong He. Extreme compression for pre-trained transformers made simple and efficient. arXiv preprint arXiv:2206.01859, 2022. Zhewei Yao, Reza Yazdani Aminabadi, Minjia Zhang, Xiaoxia Wu, Conglong Li, and Yuxiong He. ZeroQuant: Efficient and affordable post-training quantization for large-scale transformers. arXiv preprint arXiv:2206.01861, 2022. Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen, Christo- pher Dewan, Mona Diab, Xian Li, Xi Victoria Lin, et al. OPT: Open pre-trained transformer language models. arXiv preprint arXiv:2205.01068, 2022. Lianmin Zheng, Zhuohan Li, Hao Zhang, Yonghao Zhuang, Zhifeng Chen, Yanping Huang, Yida Wang, Yuanzhong Xu, Danyang Zhuo, Joseph E Gonzalez, et al. Alpa: Automating inter-and intra-operator parallelism for distributed deep learning. arXiv preprint arXiv:2201.12023, 2022. 12 Published as a conference paper at ICLR 2023 A APPENDIX A.1 ADDITIONAL COMPARISON WITH OBQ We now provide an additional comparison between GPTQ and OBQ on BERT-base/SQuAD Ra- jpurkar et al. (2016) and OPT-125M/WikiText2, which is one of the largest models to which OBQ can be reasonably applied. Method BERT-base 88.53 F1 ↑ 3bit 4bit OPT-125M 27.66 PPL ↓ 3bit 4bit OBQ GPTQ 88.23 88.18 85.29 86.02 32.52 31.12 69.32 53.85 Table 8: Comparison of GPTQ relative to OBQ on BERT-base/SQuAD and OPT-125M/WikiText2. A.2 EXPERIMENT DETAILS This section provides additional details about our experiment setup, in particular regarding the model evaluation and the setup of our timing experiments. # A.2.1 EVALUATION For language generation experiments, we calculate the perplexity, in standard fashion like Radford et al. (2019), as follows: First, the entire validation set is concatenated using two linebreaks as separators and encoded using the default HuggingFace tokenizer of each model. Next, the sequence is split into non-overlapping segments of width 2048, the full context size of our models. These are sent through the model to collect the log-probabilities corresponding to the next token each. Their exponentiated average is the final perplexity we report. For zero-shot tasks we follow the EleutherAI evaluation harness3 in terms of data preprocessing and final score calculation. We note that we evaluate all individual samples separately and thus do not apply any padding. # A.2.2 TIMING EXPERIMENT SETUP Our timing experiments are performed following the standard HuggingFace/accelerate4 setup also used by the recent work LLM.int8() (Dettmers et al., 2022). In this setting, the model is split by distributing chunks of consecutive layers across GPUs. Importantly, in this setup the communication costs are minimal, < 5% of the total runtime even when working with 8 GPUs. This means almost all of the reported speedups are due to our quantized-matrix full-precision vector product kernels. We emphasize that the only difference between the FP16 baseline and our quantized models are the kernels used to perform the underlying matrix-vector products. This means all overheads due to HuggingFace, attention or non-quantized operations like residuals or LayerNorms are exactly the same. Consequently, our quantized models should benefit from more advanced distribution strategies (Zheng et al., 2022) or more efficient attention kernels (Dao et al., 2022) just as much as our baseline. In general, our kernels target generative inference in the low batch-size setting (for simplicity, we consider only batchsize 1) where the underlying (close to) matrix-vector products are memory- bound. For non-generative and large-batch applications, operations may be compute- rather than memory-bound and our kernels thus not directly applicable. Instead, one could simply decompress the matrix before performing the corresponding matrix-matrix calculations: this takes < 1.5ms on an A100 and < 3ms on an A6000 compared to 76ms/365ms for the subsequent OPT-175B FC2 layer computation with batchsize 16×1024 tokens. Hence, for such applications our methods significantly reduce the required number of GPUs at very little computational overhead. This is similar to recent work (Dettmers et al., 2022), but we achieve a 2.5× higher compression rate. 3https://github.com/EleutherAI/lm-evaluation-harness 4https://huggingface.co/docs/accelerate/index 13 Published as a conference paper at ICLR 2023 A.3 ADDITIONAL LANGUAGE GENERATION RESULTS Tables 9, 10, 11 and 12 show additional results for language generation tasks. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B 30B 66B full 16 38.99 31.08 20.29 17.97 15.77 14.52 14.04 13.36 RTN GPTQ 4 4 53.89 45.17 36.79 34.52 57.30 21.85 31.05 19.14 18.84 16.56 16.51 14.94 15.40 14.26 225.66 13.81 RTN GPTQ 3 3 1.4e3 73.19 88.04 47.08 1.3e4 32.10 1.4e4 24.81 5.7e3 21.88 2.8e3 16.68 1.2e3 15.36 5.0e3 28.12 175B 12.01 14.22 12.26 8.0e3 12.86 Table 9: OPT perplexity results on PTB. BLOOM Bits 560M 1.1B 1.7B 3B 7.1B 176B full 16 43.69 57.96 30.00 25.34 20.83 14.59 RTN GPTQ 4 4 51.10 46.97 66.85 62.47 33.58 31.84 27.68 26.49 22.42 21.67 15.00 14.75 RTN GPTQ 3 3 126. 70.35 185. 87.04 106. 46.11 66.78 34.02 35.04 26.14 107. 15.57 Table 10: BLOOM perplexity results for PTB. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B 30B 66B full 16 26.56 22.59 16.07 14.34 12.71 12.06 11.44 10.99 RTN GPTQ 4 4 33.91 29.22 26.21 24.63 24.51 16.97 18.43 15.00 14.36 13.18 13.36 12.26 13.46 11.57 309. 11.23 RTN GPTQ 3 3 834 42.41 55.49 31.33 5.2e3 21.63 1.1e4 18.17 5.3e3 17.14 3.1e3 13.34 1.4e3 12.23 3.5e3 14.59 175B 10.13 11.61 10.28 4.6e3 10.67 Table 11: OPT perplexity results on C4. We note that the calibration data used by GPTQ is sampled from the C4 training set, this task is thus not fully zero-shot. BLOOM Bits 560M 1.1B 1.7B 3B 7.1B 176B full 16 26.60 22.05 19.49 17.49 15.20 11.71 RTN GPTQ 4 4 29.89 28.00 24.44 23.25 21.26 20.55 18.76 18.10 16.06 15.60 12.04 11.81 RTN GPTQ 3 3 67.49 35.78 60.71 28.83 113. 25.34 80.49 21.25 22.59 17.67 598. 12.27 Table 12: BLOOM perplexity results for C4. We note that the calibration data used by GPTQ is sampled from the C4 training set, this task is thus not fully zero-shot. 14 Published as a conference paper at ICLR 2023 A.4 ADDITIONAL ZEROSHOT RESULTS This section contains additional results for zero-shot tasks. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B full 16 39.16 46.67 58.80 64.82 68.72 70.23 RTN GPTQ 4 4 18.34 34.74 40.62 48.38 36.31 56.45 59.27 62.97 64.66 66.37 67.38 69.12 RTN GPTQ 3 3 0.10 13.93 27.36 32.31 0.00 37.26 0.00 52.26 0.00 54.98 0.06 64.18 30B 72.39 70.48 72.40 1.46 69.69 66B 74.93 13.08 74.50 2.00 57.02 175B 75.59 71.34 76.80 0.00 76.19 Table 13: OPT accuracy on LAMBADA. BLOOM Bits 560M 1.1B 1.7B 3B full 16 34.06 42.85 46.71 52.12 RTN GPTQ 4 4 26.00 31.75 39.06 39.80 41.92 46.28 45.84 51.41 RTN GPTQ 3 3 9.10 21.31 15.95 28.70 15.02 33.65 24.55 43.12 7.1B 57.79 50.48 54.65 29.90 47.41 176B 67.40 66.70 67.71 0.17 65.10 # Table 14: BLOOM accuracy on LAMBADA. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B full 16 62.02 64.74 72.36 74.81 76.39 76.88 RTN GPTQ 4 4 61.43 61.26 63.44 63.71 67.63 70.73 73.72 73.99 76.44 76.28 76.01 76.61 RTN GPTQ 3 3 56.09 59.25 60.61 61.32 52.77 68.34 51.90 71.38 50.49 73.29 52.99 75.24 30B 78.18 77.26 79.00 56.37 77.58 66B 79.76 60.07 79.33 50.87 71.27 175B 81.07 78.23 81.00 51.25 80.03 Table 15: OPT accuracy on PIQA. BLOOM Bits 560M 1.1B 1.7B 3B full 16 65.07 67.14 69.97 70.51 RTN GPTQ 4 4 63.11 64.31 65.29 66.05 67.74 68.77 69.86 69.42 RTN GPTQ 3 3 58.60 61.62 60.80 62.62 60.88 65.18 66.28 68.34 7.1B 73.72 72.69 72.96 69.70 70.95 176B 79.16 79.00 79.00 53.32 77.70 Table 16: BLOOM accuracy on PIQA. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B full 16 39.69 40.36 50.93 54.34 60.14 61.83 RTN GPTQ 4 4 36.32 39.02 38.55 37.92 49.20 59.97 52.90 53.11 57.68 59.72 61.31 61.32 RTN GPTQ 3 3 30.43 36.15 36.07 36.91 27.97 46.17 26.05 48.19 25.04 53.41 30.60 56.82 30B 65.40 61.11 65.11 34.22 59.72 66B 67.26 40.66 65.35 25.84 52.44 175B 71.04 63.93 68.69 26.77 65.36 Table 17: OPT accuracy on ARC-easy. 15 Published as a conference paper at ICLR 2023 BLOOM Bits 560M 1.1B 1.7B 3B full 16 41.71 45.41 48.11 53.24 RTN GPTQ 4 4 39.40 40.24 42.51 44.49 44.70 44.49 51.35 52.82 RTN GPTQ 3 3 45.44 39.14 46.87 41.79 37.58 42.85 45.08 46.63 7.1B 57.37 56.14 56.14 48.61 51.56 176B 67.47 66.33 67.42 28.87 62.84 # Table 18: BLOOM accuracy on ARC-easy. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B full 16 22.87 24.06 29.44 31.31 34.56 35.75 RTN GPTQ 4 4 22.44 22.95 23.81 24.83 24.91 28.24 29.18 30.12 32.59 33.70 35.24 34.90 RTN GPTQ 3 3 21.76 22.53 22.18 25.09 23.55 27.65 25.43 27.82 25.85 31.91 23.81 33.02 30B 38.14 35.41 37.80 19.97 35.84 66B 40.02 22.87 39.16 25.77 31.66 175B 43.94 37.71 42.75 23.81 41.04 Table 19: OPT accuracy on ARC-challenge. BLOOM Bits 560M 1.1B 1.7B 3B full 16 24.15 25.68 26.79 30.55 RTN GPTQ 4 4 23.89 23.46 23.34 25.51 26.45 25.94 29.52 28.92 RTN GPTQ 3 3 21.67 23.21 22.86 24.06 23.29 24.91 27.13 28.58 7.1B 33.45 32.17 32.25 31.31 30.97 176B 44.97 43.17 44.20 24.74 40.70 Table 20: BLOOM accuracy on ARC-challenge. OPT Bits 125M 350M 1.3B 2.7B 6.7B 13B full 16 59.96 63.21 70.78 71.74 74.60 76.64 RTN GPTQ 4 4 60.02 59.58 63.08 63.46 59.13 69.64 70.78 70.46 73.65 73.90 74.47 76.19 RTN GPTQ 3 3 49.65 57.03 56.78 60.15 47.61 65.25 46.98 68.43 48.12 70.97 49.20 73.07 30B 77.28 75.37 77.08 49.84 75.68 66B 77.34 51.24 77.15 48.19 71.23 175B 79.82 78.04 80.08 46.47 78.04 Table 21: OPT accuracy on StoryCloze. BLOOM Bits 560M 1.1B 1.7B 3B full 16 61.94 63.27 65.44 67.79 RTN GPTQ 4 4 60.15 61.17 60.66 62.32 62.95 64.48 67.09 67.22 RTN GPTQ 3 3 54.87 57.80 56.08 59.77 55.79 61.81 59.83 63.97 7.1B 71.99 70.72 71.36 66.20 69.26 176B 76.89 76.00 76.32 48.50 75.37 # Table 22: BLOOM accuracy on StoryCloze. 16
Title: Zero-shot Generation of Coherent Storybook from Plain Text Story using Diffusion Models: Summary: Recent advancements in large scale text-to-image models have opened new possibilities for guiding the creation of images through human-devised natural language. However, while prior literature has primarily focused on the generation of individual images, it is essential to consider the capability of these models to ensure coherency within a sequence of images to fulfill the demands of real-world applications such as storytelling. To address this, here we present a novel neural pipeline for generating a coherent storybook from the plain text of a story. Specifically, we leverage a combination of a pre-trained Large Language Model and a text-guided Latent Diffusion Model to generate coherent images. While previous story synthesis frameworks typically require a large-scale text-to-image model trained on expensive image-caption pairs to maintain the coherency, we employ simple textual inversion techniques along with detector-based semantic image editing which allows zero-shot generation of the coherent storybook. Experimental results show that our proposed method outperforms state-of-the-art image editing baselines. # Zero-shot Generation of Coherent Storybook from Plain Text Story using Diffusion Models # Hyeonho Jeong Department of Software, Sungkyunkwan University drake6751@g.skku.edu # Gihyun Kwon Department of Bio and Brain Engineering, KAIST cyclomon@kaist.ac.kr # Jong Chul Ye Kim Jaechul Graduate School of AI, KAIST jong.ye@kaist.ac.kr g > r ie A ‘ There was a boy named who was so lazy, tree in their yard was full of he couldn't even bother to fruits, change his clothes. Ne ' - i ky oS There was a girl named who was so lazy, she couldn't even bother to change her clothes. One day, she saw that the of fruits. One day, he'saw that the apple He wanted to eat some apples So he lay down underneath the but he was too lazy to climb the tree and take the fruits. She wanted to eat some apples So she lay down underneath apple tree in their yard was full but she was too lazy to climb the tree and take the fruits. ge |e s . | waited and waited until he tree and waited for the fruits _ was very hungry but the apples to fall off. never fell. ac | & waited and waited until she was very hungry but the apples never fell. the tree and waited for the fruits to fall of f. Figure 1. Zero-shot generation example of a coherent storybook with the main character, Brad (top) and Hanna (bottom), using plain text story from ‘The Lazy John’. All the generation processes are performed using large language models (LLM) and latent diffusion models without additional training data. # Abstract Recent advancements in large scale text-to-image mod- els have opened new possibilities for guiding the creation of images through human-devised natural language. However, while prior literature has primarily focused on the gener- ation of individual images, it is essential to consider the capability of these models to ensure coherency within a se- quence of images to fulfill the demands of real-world appli- cations such as storytelling. To address this, here we present a novel neural pipeline for generating a coherent storybook from the plain text of a story. Specifically, we leverage a combination of a pre-trained Large Language Model and a text-guided Latent Diffusion Model to generate coherent images. While previous story synthesis frameworks typi- cally require a large-scale text-to-image model trained on expensive image-caption pairs to maintain the coherency, we employ simple textual inversion techniques along with detector-based semantic image editing which allows zero- shot generation of the coherent storybook. Experimental 1 results show that our proposed method outperforms state- of-the-art image editing baselines. # 1. Introduction The progress in image synthesis using large-scale text- to-image models has garnered significant attention due to their unprecedented synthetic capacity. Text-guided image synthesis methods such as VQGAN-CLIP [7] and CLIP- guided Diffusion [6], utilize the superior performance of text-to-image alignment in the CLIP [35] latent spaces. Parti [54], Make-a-scene [12], and DALL-E 1 [39] have employed large auto-regressive architectures, while Ima- gen [43], DALL-E 2 [38], and Stable Diffusion [42] have utilized diffusion-based architectures. MUSE [5] employs a masked transformer architecture and learns to predict masked tokens using the embeddings projected from Large Language Models (LLM) and image tokens. The over- whelming performance of these models has sparked ongo- ing research efforts to harness their power for image editing. While prior frameworks have mainly focused on the gen- eration of individual, high-quality images, real-world appli- cations place an equal emphasis on coherency within a se- ries of generated images. For example, in the context of an AI-generated storybook, it is crucial for the main character to maintain a consistent appearance throughout the book. Therefore, we address the challenge of not only locally edit- ing an image, but also applying these techniques to a practi- cal real-world application: the generation of a training-free storybook that maintains the coherency of the main charac- ter. One prior attempt at this is Long Stable Diffusion [58], which generates a book (both plot and corresponding il- lustrations) using a combination of LLM and text-image models. However, their use of a LLM is limited to gen- erating illustration ideas, which can lead to irrelevant im- ages if directly used as text conditioning or require sig- nificant manual modification of prompts. Another pio- neering work in the field of story synthesis is StoryGAN [24], a conditional GAN [29] trained to generate visual se- quences corresponding to text descriptions of a story. Sub- sequently, StoryDALL-E [28] proposed the adaptation of pre-trained text-to-image transformers to generate visual se- quences that continue a given text-based story, introduc- ing a new task of story continuation. More recently, Pan et al. [32] proposed history-aware Auto-Regressive Latent Diffusion Models that leverage diffusion models for story synthesis, utilizing a history-aware conditioning network to encode past caption-image pairs. While previous works have made important strides in story synthesis by utilizing datasets of specific domains [55] for training, generalizing their methods to other domains or stories often requires ex- pensive image-caption pairs and additional training. 2 To address these issues, here we introduce a neural pipeline for the zero-shot generation of coherent story- books without additional training data. Specifically, our method starts with a simple, yet powerful prompt generation pipeline that takes as input the plain text of existing stories. Furthermore, we ensure that the main character maintains a consistent appearance throughout the book by utilizing our proposed semantic image editing method that injects the de- sired identity into the facial regions, which play a crucial role in distinguishing a character’s identity. Our experimen- tal results demonstrate the effectiveness of our approach in comparison to state-of-the-art semantic image editing base- lines. In summary, the contributions of our work are as follows: • We propose a novel prompt generation pipeline, in which LLMs understand the context and generate prompt inputs for text-to-image models, replacing the need for human-devised natural language prompts. • We propose our semantic image editing method and demonstrate its effectiveness against other baselines in terms of smooth editing, coherency maintenance across independent images, and preservation of back- ground regions. • Our method allows for fine-grained control over the degree of semantic change by adjusting the number of cycles. # 2. Related Works Large Language Models and Prompt Engineering. Large Language Models (LLMs) [4, 10, 36, 37] have gained significant attention in recent years due to their capability to create human-like text and accomplish a wide range of natural language processing (NLP) tasks accurately. Re- cent works demonstrated that LLMs can perform both few- shot [4] and zero-shot [22] reasoning tasks with high accu- racy, generalizing well to both common and rare examples. This is achieved by conditioning the models on a few exam- ples or task instructions, a method commonly referred to as ”prompting” [25]. While most of the research in prompt en- gineering has focused on text generation in NLP [41,45,60], relatively little exploration has been conducted on prompt- ing text generation frameworks in visual tasks, e.g. text-to- image generation. Various guidelines [26,31,51] for design- ing prompts have been suggested through empirical analy- sis of the relationship between prompt components and the resulting visual effects. The studies employed extensive ex- perimentation, utilizing a variety of prompt modifiers on the generation model to gain a deeper understanding of the fac- tors that influence the generated images. Diffusion Models. Diffusion models [46] are trained to learn the underlying data distribution by gradually denois- ing a variable sampled from Gaussian distribution. In par- ticular, this is equivalent to learning the reverse process of the Markov Chain of fixed length T . In a forward diffusion process q(xt|xt−1), noised sampled from Gaussian distri- bution is added to a ground truth image x0 at every time step t: (xt |t1—-1) = N (a3 V1 — Bexe-1, Gi) = Tater) 1 qd) q(xr|xo) : where (3, decides the step size which gradually increases. Let a; := 1 — 8; and a; := Ti, a;. Then we can sample x, ina single step: √ √ x = Vayxo + V1 = are (2) where ¢ is a noise sampled from N’(0,7). DDPM [18] learns to predict the noise component of x; and generate a marginally denoised x;_; from 2, by maximizing the varia- tional lower bound to minimize the negative log-likelihood of po (xo). A function eg is parameterized by a UNet-shaped model to reverse the forward step and mean jug(xz,t) is learned in the reverse process: po(te—-1|2e) = N(ae-1; Hoa, t), 071), where 1 1- (3) fo(a,t) = Jal - Fale) The training objective of the diffusion model is then: 2 Lom = Exo e~N(0,1),t I —€& (v apt + V1 — Gier,t) | (4) Denoising Diffusion Implicit Models (DDIM) [47] pro- posed a method for accelerating the sampling process of diffusion models by replacing the Markov forward process used in DDPM with a non-Markovian process. DDIM for- mulates a Markov chain that reverses a non-Markovian per- turbation process. This chain is fully deterministic when the variance of the reverse noise α2 t is set to zero. DDIM method is formulated using the following Markov chain: T q(a1,...,¢7|%0) = [La Lp |p 1; x0) el N (1-13 fie (21, £0); 07D) do(tt-1|t, 0) = where √ Exo Le (Le, Li Vat-1%9 + \/1-a& —o? fie (@t, = t—1%0 t-1 t TS (6) Text-to-Image Generation and Semantic Image Edit- ing. The field of text-guided synthesis has seen a sig- nificant amount of progress in recent years, with various methods proposed to address the challenge of generating images from natural language descriptions. Early works [29, 40, 52, 56, 57] in this field were based on Generative Adversarial Networks (GAN) [15]. (3) A widely adopted approach is the use of auxiliary mod- els such as CLIP [35] to guide the optimization of pre- trained generators towards the objective of minimizing text- to-image similarity scores [6, 7]. Additionally, other works have exploited the use of CLIP in conjunction with gen- erative models for various tasks such as image manipula- tion [20, 33], domain adaptation [14], style transfer [23], and even object segmentation [27,50]. Recently, large-scale text-to-image models demonstrated impressive image gen- eration performance [5, 12, 38, 39, 42, 43, 54]. These models have sparked research efforts using diffusion models [46] for text-driven image generation and editing. In regard to image editing, previous works such as Blended Diffu- sion [3], Blended Latent Diffusion [2], and Paint by Ex- ample [53] have addressed the issue of background preser- vation through user-provided masks. Another approach demonstrated the ability to edit synthesized images using text prompts as editing guidance [17]. DALL-E 2 [38] also proved its impressive capability in text-guided image edit- ing, commonly referred to as ‘inpainting’. However, when generating images from these models, the identity of a sub- ject is not sustained among images. This is because the diffusion-based generators only use text as a guidance and changing the context in the prompt also alters the appear- ance. 2 # 3. Method In this section, we detail our neural pipeline for generat- ing a training-free storybook that maintains the coherence of the main character. Specifically, for a given plain text of a story, our algorithm automatically generates matched images and storybook that maintains the coherence of the main character. The overall process of our method can be summarized as follows: 1. Generate prompts by providing instruction to LLM along with the text of a story. (5) 2. Utilize a Diffusion-based Text-to-Image model to gen- erate initial images from the set of prepared prompts. 3. Apply Face Restoration on the initial images. 4. Find the textual embedding of a specific identity by Textual Inversion learning. 5. Use the obtained textual embedding to perform Itera- tive Coherent Identity Injection on enhanced images. 3 (a) LLM Pipeline (b) Text-to-Image Generation Results ” an #1 The idea of the herd of elephants made the little prince laugh #11 “Who are you?’ the litle prince asked to the fox, “You are very pretty to look at Describe = | each scene #1 The tle prince laughing, surrounded by a herd of elephants #11 The lite prince with a curious ‘expression, looking up at the fox Summarize each noun phrase #1 Little prince laughing with elephants #11 Little prince curiously looking at a fox Add Ln facial descriptions #1 Little prince, symmetrical face, laughing with elephants #1 Little prince, highly detailed face, looking ata fox Figure 2. (b) Text-to- (a) Overall prompt generation process. Image generation results on the corresponding text sets: it can be observed that the generated images in the lower rows more effec- tively depict the semantics of the corresponding texts. # 3.1. Prompt Generation Prior literature has primarily leveraged text-to-image models for generating a wide range of images with human- devised text prompts. Instead, this article proposes an ap- proach where we utilize prompts generated by a LLM when given the plain text of a story. Our pipeline, as outlined in Figure 2 (a), is able to generate a series of prompts corre- sponding to each scene of a story. Let us utilize ‘The Little Prince’ [8] as a case study for our corresponding prompts generation pipeline. The pro- cess begins by providing the LLM with the instruction to ”Describe each scene” along with the sentences of the story. One example input-output pair for this step would be ”The idea of the herd of elephants made the little prince laugh” and ”The little prince laughing, surrounded by a herd of elephants”. The LLM expresses its creativity through this step, with the strength of creativity being controlled by the temperature parameter T . However, text-to-image synthesis models often struggle to effectively handle the complexity of the outputs generated from the ”Describe each scene” in- struction. As demonstrated in Figure 2 (b), the amount of information contained in these outputs exceeds the capacity of text-to-image models. To address this issue, we employ a summarization step in which we provide the LLM with the ”Summarize each noun phrase” instruction and the outputs obtained from the previous step. An example of the output generated in this step, given the previous output ”The little prince laughing, surrounded by a herd of elephants,” is ”The little prince laughing with elephants.” To further enhance the quality of the generated images, we employ additional processing of the prompts by the LLM, through the use of magic words already popular to 4 practitioners. These magic words, such as ‘highly detailed’ and ‘insanely intricate’ are known to be effective in adding detailed properties to images. Additionally, when the main subject of the prompt is a person, we also utilize descrip- tions of facial features, such as ‘symmetrical face’ and ‘beautiful eyes’ to enhance the realism of the generated im- ages. This is accomplished through the use of simple in- structions given to the LLM, specifically, ”If the main sub- ject of the prompt is a person, add facial descriptions such as ‘symmetrical face’ or ‘beautiful eyes’, where the LLM expresses its creativity again. In order to generate images in a specific style, we em- ploy the use of style modifiers. In this work, we specif- ically target the style of a storybook. Examples of uti- lized style modifiers that achieved the storybook aesthetic include: 1. Modifiers that include children’s book illustra- tors such as ”illustrated by Quentin Blake” 2. Modifiers that indicate a specific type of book such as ”1950s adventure book character illustration” 3. Modifiers that include artists with desired artistic style such as ”watercolor by Carl Lars- son” or ”painting by Jean-Baptiste Monge”. This step of in- corporating style modifiers allows for increased scalability as it enables the generation of an infinite number of varia- tions of the storybook by simply altering the style modifiers used, according to the demands of users. Visual effects of mentioned modifiers are illustrated in Figure 4. “shepherd boy with mischievous smile” Blake" ‘"bustrated by Quentin + "1950s adventure book + “painting by Jean. character station” + watercolor by Carl Bapiste Monge" Larsson" Figure 4. Text-to-image generation with different storybook style modifiers. # 3.2. Iterative Coherent Identity Injection Initial Image Generation using Latent Diffusion Mod- els. We utilize a text-conditioned Latent Diffusion model (LDM) [42] to generate initial images from a set of prepared prompts. Unlike traditional diffusion models that operate in the pixel space, LDM utilizes the latent space, using a pre- trained autoencoder (VAE [21] or VQ-VAE [1, 48]). An encoder E maps image x ∈ RH×W ×3 to latent representa- tions z = E(x), z ∈ Rh×w×c, while a decoder D maps the latents back to images ˜x = D(z) = D(E(x)). Our trained perceptual compression models, the autoencoder consisting of E and D, enable access to low-dimensional latent space where high-frequency, indiscernible details are ignored. A diffusion model is additionally trained to generate represen- tations within this learned latent space, while conditioned on texts, and initial images. Note that the text condition and Va Pixel Space \ Latent Space Pixel Space M s mg Textual Inversion _ i os n Target I Conditioning ad Zinit 27 ap 2 Input Image ent 5 Output Image a N times ye Figure 3. Iterative Coherent Identity Injection procedure. the initial image are the two important control knobs that will be used for the iterative coherent identity injection de- scribed later. Based on image-conditioning pairs, the model tries to precisely eliminate the noise added to a latent repre- sentation of an image x via: the LDM loss is defined as: Ss, = arg min E.~8(0),ye~N(O,1)st [Ile — €9 (a1, t, 70(S))|l] (8) where parameters of €g and T¢ are frozen. Lupo ‘= E.ng(2),ye~N (0,1), [le — €9 (2; t,ra(u))I3| , 7) where ¢ is the time step, z; is the noisy version of initial latent on time t, € is the sampled noise, €g is a conditional denoising autoencoder, and T¢ is a encoder that projects in- put y to a conditioning vector T9(y). €9 and 79 are jointly optimized to minimize the loss. Iterative Coherent Identity Injection. Given an initial image x generated by Latent Diffusion Model (LDM) using the prompt P, we employ a face restoration model [49, 59] on x to obtain an enhanced image xen to elevate the qual- ity of the initial images before proceeding to the next step of Iterative Coherent Identity Injection. This is an important step as it addresses the issue of mutated facial features in the generated images, and also helps to reduce the domain gap between the generated images and the target textual embed- ding which we obtain from Textual Inversion [13] of real- photo domain images. Subsequently, we utilize a Face De- tector [9] to extract the bounding box of the facial region in the image. This bounding box is used to generate a binary mask Mf that marks the region of the face in the image. To incorporate a target identity, we edit the prompt P to obtain P∗ by replacing the original subject in P with a placeholder string S∗ of the target identity, for example re- placing ”the little prince” in the original prompt with ”S∗”. To find a designated placeholder string S∗ which represents the desired target identity given a few images (or a single image) of the target identity, the textual inversion technique proposed by Gal et al. [13] is used to find the target embed- ding vector v∗ in the embedding space of text encoder τθ, where v∗ = τθ(S∗). The optimization goal of minimizing The objective is then to generate an altered image iy, where the facial region te, © My is consistent to the iden- tity encoded in S,, while preserving the background (non- facial) region of the source image. The overall N cycles of identity injection process is guided by Px and Mr, ie., LDM performs textual embedding guidance denoising in the latent space of a Variational Autoencoder (VAE) consist- ing of an encoder € and a decoder D. We denote the facial area as ‘face’ (f) and to the complementary non-facial area as ‘non-face’ (nf). The enhanced input x,,, first moves to the latent space using the VAE Encoder zinit ~ E(en). As the width and the height of latent representations are down- sampled from the input image pixel space, we downsample the facial mask mrp = downsample(Mr) as well. With the downsampled facial mask m,, we extract ground truth latent representation of non-face region Zp¢ by zinit O(1—mer). As the denoising step progresses, the non-facial region of the intermediate representation z; will repeatedly be replaced with the extracted zy,. More specifically, we do the following process for N cy- cles: We noise the initial latent z;ni, to the noise level T. Replace the non-facial region of noised sample zr with the corresponding region of Zy¢ as Zp + zp ©me_e st Zn¢ . The resulting z/, becomes the input of the denoising process. Then after each denoising step, which is conditioned by the edited prompt P,, we obtain the less noisy sample z;—1. Preserve the facial region of z;_; but replace the comple- mentary region with z,, as 24 — %-1 © me + Mn. The resultant z;_, becomes the input of the next denoising step. Once the denoising process terminates, instead of being de- coded back to pixel space, the resulting denoised sample z/ becomes the input of the next cycle, which eliminates the inefficiency of going back and forth between latent space and pixel space. After N cycles are carried out, we get 5 the output image by decoding it from the latent space to the pixel space. The overall procedure is outlined in Algorithm 1 and illustrated in Figure 3. Algorithm 1 Iterative Coherent Identity Injection: given a Latent Diffusion Model (noise(z, T ), denoise(z, P, t)) along with VAE encoder E and decoder D Input: enhanced image xen, modified prompt P∗, down- sampled facial mask in latent space mf , the number of cycles N , diffusion steps T Output: image ˆxN that has the appearance of the target identity contained in S∗, while keeping the background of xen unchanged Zinit © E(Xen) Zant © Zinit © (1 — mp) for n = 1,2,...,N do zr ~ noise(Zinit, T') ap — 2p © me + 2ne fort = 7T,T —1,...,1 do z-1 ~ denoise(z}, P., t) 1 — 4-1 © me + Zag end for Zinit — 2% end for En = D(x) Return 7 # 4. Experiment # 4.1. Implementation Details We first provide details on the implementation choices of our proposed method. For the story-to-prompts compo- nent, we employed the GPT-3 model [4], specifically the ”text-davinci-003” variant, as well as the ChatGPT lan- guage model. For the text-to-image synthesis component, we adopted the Stable Diffusion model(v1.5) [42], a pub- licly available text-to-image latent diffusion model trained on LAION-5B [44] and its default settings. We utilized CodeFormer [59] for face restoration and RetinaFace face detector [9] to accurately detect and align faces in the gen- erated images. # 4.2. Experiment Settings The experiments were conducted on a GPU of Quadro RTX 6000. We employed the DDIM scheduler [47] for sampling the latent space of the Stable Diffusion model [42]. In the initial image generation phase, we used 100 reverse diffusion steps, with scale guidance [19] between 7.5 and 10. A fidelity weight of 0.5 was used during face restoration [59]. For one cycle of coherent identity in- jection, we used about 50 forward and reverse diffusion 6 steps. The number of coherent identity injection cycles var- ied between 1 and 8. The generated images had a resolu- tion of 512x512 and the latent representations were of size 4x64x64. Lastly, the story ‘The Lazy John’ presented in Figure 1 is from an article presented in [16], ‘The Boy Who Cried Wolf’ in Figure 5 is from [34], and ‘The Little Prince’ in Figure 12 is from [8]. # 4.3. Qualitative Results Figure 1 illustrates examples of our zero-shot genera- tion of the storybook with two different identities, which clearly demonstrates that our method can control and main- tain the coherency of the stories that are generated without any training data. In Figure 5, we present a qualitative evaluation of our proposed method in comparison to state-of-the-art semantic image editing baselines. To demonstrate the effectiveness of our pipeline, we first show initial images generated by our pipeline, which includes prompt generation, initial text- to-image generation, and face restoration. We then compare our method with a range of baselines, including text-guided methods such as CLIP-guided Diffusion [6] and Stable Dif- fusion Img2img [42], DALL-E2 Inpainting [38], Blended Latent Diffusion [2] and an image-guided method such as Paint by Example [53]. The ‘Source’ images show that our pipeline successfully synthesizes images corresponding to the plot of the story. The comparison results show that our method outperforms the baselines in terms of coherency preservation and background region preservation. Further comparisons on additional stories are presented in Figure 11 and Figure 12. # 4.4. Quantitative Results We created three questionnaires for a total of four sto- ries, with each questionnaire designed to assess different aspects of the generated images. The first questionnaire, la- beled as Correspondence, assessed the level of correspon- dence between the plot of the text and the generated image pairs. The second questionnaire, labeled as Coherency, as- sessed the coherency of the main characters across images within a story. Lastly, the third questionnaire, labeled as Smoothness, assessed how smooth and seamless the transi- tion was between the foreground and background in the im- ages. To evaluate detailed opinions, we employed a custom- made opinion scoring system. The results of this study on 76 random people are summarized in Table 1 in the form of mean scores for each of the questionnaires. Overall, our method achieved the highest scores in all aspects, indicating the effectiveness of our proposed pipeline. # 4.5. Ablation Study To validate the optimality of our approach, we performed ablation studies. First, we compare the generative perfor- Brad Pitt ‘Shepherd Sit Stable DALL-E 2 Blended boy — & CLIP-guided Diffusion Mask Latent Paint by Ui Source Diffu: Img2img Inpainting Diffusion Example #1 There was once a shepherd boy who liked to play tricks. at #2 One day, while he was watching over the herd, the boy decided to play a trick and cried “wolf! wolfl”. #3 The people who heard rushed over to help him. #4 But they were disappointed when they saw that there was no wolf and the boy was laughing at them #5 The next day, he did it again and people rushed to his aid only to be disappointed once again. #6 On the third day, the boy saw a wolf devouring one of his sheep and cried for help. #7 But the people who heard him thought this is just another of the boy's pranks so no one came to help him. #8 That day, the boy lost some of his sheep to the wolf. Figure 5. Comparison with semantic image editing baselines. Our method effectively maintains the identity of a character across multiple images while preserving the background of the source images. Note that our method consistently preserves the emotional expressions from the source images, unlike other methods. mance on varying numbers of cycles. The results are pre- sented in Figure 6, which illustrates that as the number of in- jection cycles increases, the source identity gradually fades away while the target identity becomes more discernible. It demonstrates the ability of the proposed method to pro- vide delicate control over the amount of editing applied to an image. The edited results in the first and the third columns demonstrate that our method is also robust to oc- clusions. Additionally, a comparison with a method using only Textual Inversion is presented in Figure 7. It shows that 7 Methods Correspondence Coherence Smoothness CLIP-guided Diffusion 2.96 2.16 2.55 Stable Diffusion 2.68 2.64 2.87 DALL-E2 2.75 2.44 2.96 Blended Latent Diffusion 2.42 2.36 2.71 Paint by Example 2.32 2.24 2.20 Ours 4.06 3.84 4.23 Table 1. User study results on various semantic image editing models. Our model outperforms baselines in the user study. our method is more effective in preserving the background, while the transition between foreground and background appears more seamless. Further results are presented in Fig- ure 10. Figure 6. Generation results of our method with a different number of cycles: As the number increases, the injected target identity becomes more apparent in the output image. # 5. Conclusion In this paper, we presented a new approach for zero-shot storybook synthesis. Our pipeline utilized Large Language Models to generate text-based conditioning, which can re- place human-crafted natural language prompts and guide image synthesis models. We then developed an iterative identity injection step, using a textual embedding and a face 8 < Ss § > 3 3 4 6 ec Textual Inversion Figure 7. Comparison with Textual Inversion method [13]: Tex- tual embedding guided image synthesis fails to preserve the back- ground of the source images. detector to guide the generation process of Latent Diffu- sion Models in terms of semantic changes and background preservation. Our experimental results demonstrated that our proposed framework outperforms both text- and image- guided semantic image editing baselines in terms of co- herency preservation and background preservation. # References [1] Eirikur Agustsson, Fabian Mentzer, Michael Tschannen, Lukas Cavigelli, Radu Timofte, Luca Benini, and Luc V Gool. Soft-to-hard vector quantization for end-to-end learn- ing compressible representations. Advances in neural infor- mation processing systems, 30, 2017. 4 [2] Omri Avrahami, Ohad Fried, and Dani Lischinski. Blended latent diffusion. arXiv preprint arXiv:2206.02779, 2022. 3, 6, 11 [3] Omri Avrahami, Dani Lischinski, and Ohad Fried. Blended diffusion for text-driven editing of natural images. In Pro- ceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 18208–18218, 2022. 3 [4] Tom Brown, Benjamin Mann, Nick Ryder, Melanie Sub- biah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakan- tan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Lan- guage models are few-shot learners. Advances in neural in- formation processing systems, 33:1877–1901, 2020. 2, 6, 11 [5] Huiwen Chang, Han Zhang, Jarred Barber, AJ Maschinot, Jose Lezama, Lu Jiang, Ming-Hsuan Yang, Kevin Mur- phy, William T Freeman, Michael Rubinstein, et al. Muse: Text-to-image generation via masked generative transform- ers. arXiv preprint arXiv:2301.00704, 2023. 2, 3 [6] Katherine Crowson. Clip-guided diffusion. 2022. 2, 3, 6, 11 [7] Katherine Crowson, Stella Biderman, Daniel Kornis, Dashiell Stander, Eric Hallahan, Louis Castricato, and Ed- ward Raff. Vqgan-clip: Open domain image generation and editing with natural language guidance. In European Con- ference on Computer Vision, pages 88–105. Springer, 2022. 2, 3 [8] Antoine de Saint-Exup´ery. The Little Prince: And Letter to a Hostage. Penguin UK, 2021. 4, 6 [9] Jiankang Deng, Jia Guo, Evangelos Ververas, Irene Kot- sia, and Stefanos Zafeiriou. Retinaface: Single-shot multi- In Proceedings of level face localisation in the wild. the IEEE/CVF conference on computer vision and pattern recognition, pages 5203–5212, 2020. 5, 6, 11 [10] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Pre-training of deep bidirectional arXiv preprint Toutanova. transformers for language understanding. arXiv:1810.04805, 2018. 2 Bert: [11] Ohad Fried, Jennifer Jacobs, Adam Finkelstein, and Ma- neesh Agrawala. Editing self-image. Communications of the Acm, 63(3):70–79, 2020. 12 [12] Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv Taigman. Make-a-scene: Scene- based text-to-image generation with human priors. arXiv preprint arXiv:2203.13131, 2022. 2, 3 [13] Rinon Gal, Yuval Alaluf, Yuval Atzmon, Or Patash- nik, 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. 5, 8, 11 [14] Rinon Gal, Or Patashnik, Haggai Maron, Amit H Bermano, Gal Chechik, and Daniel Cohen-Or. Stylegan-nada: Clip- guided domain adaptation of image generators. ACM Trans- actions on Graphics (TOG), 41(4):1–13, 2022. 3 [15] Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, and Yoshua Bengio. Generative adversarial networks. Commu- nications of the ACM, 63(11):139–144, 2020. 3 [16] Vijay Gupta. 10 lines short stories with moral for kids in english, 2021. 6 [17] Amir Hertz, Ron Mokady, Jay Tenenbaum, Kfir Aberman, Yael Pritch, and Daniel Cohen-Or. Prompt-to-prompt im- arXiv preprint age editing with cross attention control. arXiv:2208.01626, 2022. 3 [18] Jonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising diffu- sion probabilistic models. Advances in Neural Information Processing Systems, 33:6840–6851, 2020. 3 [19] Jonathan Ho and Tim Salimans. Classifier-free diffusion guidance. arXiv preprint arXiv:2207.12598, 2022. 6 9 [20] Gwanghyun Kim and Jong Chul Ye. Diffusionclip: Text- guided image manipulation using diffusion models. 2021. 3 [21] Diederik P Kingma and Max Welling. Auto-encoding varia- tional bayes. arXiv preprint arXiv:1312.6114, 2013. 4 [22] Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa. Large language models are zero-shot reasoners. arXiv preprint arXiv:2205.11916, 2022. 2 [23] Gihyun Kwon and Jong Chul Ye. Clipstyler: Image style In Proceedings of transfer with a single text condition. the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 18062–18071, 2022. 3 [24] Yitong Li, Zhe Gan, Yelong Shen, Jingjing Liu, Yu Cheng, Yuexin Wu, Lawrence Carin, David Carlson, and Jianfeng Gao. Storygan: A sequential conditional gan for story vi- In Proceedings of the IEEE/CVF Conference sualization. on Computer Vision and Pattern Recognition, pages 6329– 6338, 2019. 2 [25] Pengfei Liu, Weizhe Yuan, Jinlan Fu, Zhengbao Jiang, Hi- roaki Hayashi, and Graham Neubig. Pre-train, prompt, and predict: A systematic survey of prompting methods in nat- ural language processing. arXiv preprint arXiv:2107.13586, 2021. 2 [26] Vivian Liu and Lydia B Chilton. Design guidelines for prompt engineering text-to-image generative models. In CHI Conference on Human Factors in Computing Systems, pages 1–23, 2022. 2 Image segmenta- In Proceedings of tion using text and image prompts. the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 7086–7096, 2022. 3 [28] Adyasha Maharana, Darryl Hannan, and Mohit Bansal. Storydall-e: Adapting pretrained text-to-image transformers for story continuation. In European Conference on Computer Vision, pages 70–87. Springer, 2022. 2 [29] Mehdi Mirza and Simon Osindero. Conditional generative adversarial nets. arXiv preprint arXiv:1411.1784, 2014. 2, 3 [30] P Mishkin, L Ahmad, M Brundage, G Krueger, and G Sastry. Dall· e 2 preview-risks and limitations. Noudettu, 28:2022, 2022. 12 [31] Jonas Oppenlaender. A taxonomy of prompt modifiers for text-to-image generation. arXiv preprint arXiv:2204.13988, 2022. 2 [32] Xichen Pan, Pengda Qin, Yuhong Li, Hui Xue, and Wenhu Chen. Synthesizing coherent story with auto-regressive la- arXiv preprint arXiv:2211.10950, tent diffusion models. 2022. 2 [33] Or Patashnik, Zongze Wu, Eli Shechtman, Daniel Cohen-Or, and Dani Lischinski. Styleclip: Text-driven manipulation of In Proceedings of the IEEE/CVF Inter- stylegan imagery. national Conference on Computer Vision, pages 2085–2094, 2021. 3 [34] Judy Ponio. 10 lines short stories with moral lessons for kids, 2021. 6 [35] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learn- ing transferable visual models from natural language super- vision. In International Conference on Machine Learning, pages 8748–8763. PMLR, 2021. 2, 3 [36] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. Language models are unsu- pervised multitask learners. OpenAI blog, 1(8):9, 2019. 2 [37] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Pe- ter J Liu, et al. Exploring the limits of transfer learning with a unified text-to-text transformer. J. Mach. Learn. Res., 21(140):1–67, 2020. 2 [38] Aditya Ramesh, Prafulla Dhariwal, Alex Nichol, Casey Chu, and Mark Chen. Hierarchical text-conditional image gen- eration with clip latents. arXiv preprint arXiv:2204.06125, 2022. 2, 3, 6, 11 [39] Aditya Ramesh, Mikhail Pavlov, Gabriel Goh, Scott Gray, Chelsea Voss, Alec Radford, Mark Chen, and Ilya Sutskever. Zero-shot text-to-image generation. In International Confer- ence on Machine Learning, pages 8821–8831. PMLR, 2021. 2, 3 [40] Scott Reed, Zeynep Akata, Xinchen Yan, Lajanugen Lo- geswaran, Bernt Schiele, and Honglak Lee. Generative ad- versarial text to image synthesis. In International conference on machine learning, pages 1060–1069. PMLR, 2016. 3 [41] Laria Reynolds and Kyle McDonell. Prompt programming for large language models: Beyond the few-shot paradigm. In Extended Abstracts of the 2021 CHI Conference on Hu- man Factors in Computing Systems, pages 1–7, 2021. 2 [42] Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Bj¨orn Ommer. High-resolution image In Proceedings of synthesis with latent diffusion models. the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 10684–10695, 2022. 2, 3, 4, 6, 11 [43] 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. 2, 3 [44] Christoph Schuhmann, Romain Beaumont, Richard Vencu, Cade Gordon, Ross Wightman, Mehdi Cherti, Theo Coombes, Aarush Katta, Clayton Mullis, Mitchell Worts- man, et al. Laion-5b: An open large-scale dataset for training next generation image-text models. arXiv preprint arXiv:2210.08402, 2022. 6, 12 [45] Taylor Shin, Yasaman Razeghi, Robert L Logan IV, Eric Wallace, and Sameer Singh. Autoprompt: Eliciting knowl- edge from language models with automatically generated prompts. arXiv preprint arXiv:2010.15980, 2020. 2 [46] Jascha Sohl-Dickstein, Eric Weiss, Niru Maheswaranathan, and Surya Ganguli. Deep unsupervised learning using In International Confer- nonequilibrium thermodynamics. ence on Machine Learning, pages 2256–2265. PMLR, 2015. 2, 3 [47] Jiaming Song, Chenlin Meng, Denoising diffusion implicit models. arXiv:2010.02502, 2020. 3, 6 and Stefano Ermon. arXiv preprint 10 [48] Aaron Van Den Oord, Oriol Vinyals, et al. Neural discrete representation learning. Advances in neural information pro- cessing systems, 30, 2017. 4 [49] Xintao Wang, Yu Li, Honglun Zhang, and Ying Shan. To- wards real-world blind face restoration with generative fa- In Proceedings of the IEEE/CVF Conference cial prior. on Computer Vision and Pattern Recognition, pages 9168– 9178, 2021. 5 [50] Zhaoqing Wang, Yu Lu, Qiang Li, Xunqiang Tao, Yandong Guo, Mingming Gong, and Tongliang Liu. Cris: Clip- In Proceedings of driven referring image segmentation. the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 11686–11695, 2022. 3 [51] Sam Witteveen and Martin Andrews. prompt engineering in diffusion models. arXiv:2211.15462, 2022. 2 [52] Tao Xu, Pengchuan Zhang, Qiuyuan Huang, Han Zhang, Zhe Gan, Xiaolei Huang, and Xiaodong He. Attngan: Fine- grained text to image generation with attentional generative adversarial networks. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 1316– 1324, 2018. 3 [53] Binxin Yang, Shuyang Gu, Bo Zhang, Ting Zhang, Xuejin Chen, Xiaoyan Sun, Dong Chen, and Fang Wen. Paint by example: Exemplar-based image editing with diffusion mod- els. arXiv preprint arXiv:2211.13227, 2022. 3, 6, 11 [54] Jiahui Yu, Yuanzhong Xu, Jing Yu Koh, Thang Luong, Gun- jan Baid, Zirui Wang, Vijay Vasudevan, Alexander Ku, Yin- fei Yang, Burcu Karagol Ayan, et al. Scaling autoregres- sive models for content-rich text-to-image generation. arXiv preprint arXiv:2206.10789, 2022. 2, 3 [55] Gangyan Zeng, Zhaohui Li, and Yuan Zhang. Pororogan: an improved story visualization model on pororo-sv dataset. In Proceedings of the 2019 3rd International Conference on Computer Science and Artificial Intelligence, pages 155– 159, 2019. 2 [56] Han Zhang, Tao Xu, Hongsheng Li, Shaoting Zhang, Xiao- gang Wang, Xiaolei Huang, and Dimitris N Metaxas. Stack- gan: Text to photo-realistic image synthesis with stacked generative adversarial networks. In Proceedings of the IEEE international conference on computer vision, pages 5907– 5915, 2017. 3 [57] Han Zhang, Tao Xu, Hongsheng Li, Shaoting Zhang, Xiao- gang Wang, Xiaolei Huang, and Dimitris N Metaxas. Stack- gan++: Realistic image synthesis with stacked generative ad- IEEE transactions on pattern analysis versarial networks. and machine intelligence, 41(8):1947–1962, 2018. 3 [58] Sharon Zhou. Long stable diffusion. 2022. 2 [59] Shangchen Zhou, Kelvin CK Chan, Chongyi Li, and Towards robust blind face restora- arXiv preprint Chen Change Loy. tion with codebook lookup transformer. arXiv:2206.11253, 2022. 5, 6, 11 [60] Yongchao Zhou, Andrei Ioan Muresanu, Ziwen Han, Keiran Paster, Silviu Pitis, Harris Chan, and Jimmy Ba. Large language models are human-level prompt engineers. arXiv preprint arXiv:2211.01910, 2022. 2 # A. Implementation Details In our proposed method, we utilized a large language model, specifically the GPT-3 model [4] with the ”text- davinci-003” version, in conjunction with the ChatGPT lan- guage model, to generate prompts for the text-to-image component. Our experiments revealed that both models produce comparable results. During the story-to-prompts process, the GPT-3 model was configured with a ‘Temper- ature’ of 0.5 and a ‘Top P’ parameter of 1. An example instruction set used in our implementation was ”Prompts to generate painting that best describes each scene of a story.” followed by ”Summarize each noun phrase.” and lastly, ”If the main subject of the prompt is categorized as a human, add facial descriptions on the subject such as symmetrical face’,emerald eyes’.” For the initial text-to-image synthesis component, we utilized the official codebase of the Stable Diffusion model 1 [42] with its default hyperparameter settings and the ac- cording model checkpoints from Hugging Face 2. We used Textual Inversion method [13] to find the target textual em- bedding, referencing both the official codebase 3 and an un- official codebase 4 by nicolai256. Additionally, we applied the face restoration step on the initially generated images by using the Codeformer Face Restoration model 5 [59], where ‘Fidelity’ parameter was set to 0.5. To precisely detect and align facial parts in the generated images, we employed the RetinaFace Face Detector model 6 [9]. Details of the Iter- ative Coherent Identity Injection method are explained in Section 4.2 of the main paper. # B. Experimental Details of Baselines In our experiments, we compared our method to sev- eral state-of-the-art baselines, including CLIP-guided Dif- fusion [6], Stable Diffusion [42], DALL-E 2 [38], Blended Latent Diffusion [2], and Paint by Example [53]. We uti- lized the official codebase of the works 7 8 9 and according demo web sites 10 11 if provided. For DALL-E 2, we uti- 1https://github.com/CompVis/stable-diffusion 2https : / / huggingface . co / runwayml / stable - diffusion-v1-5 # 3https://github.com/rinongal/textual_inversion 4https://github.com/nicolai256/Stable- textual- inversion_win 5https://github.com/sczhou/CodeFormer,https:// huggingface.co/spaces/sczhou/CodeFormer 6https://github.com/biubug6/Pytorch_Retinaface 7https : / / github . com / afiaka87 / clip - guided - diffusion 8https : / / github . com / omriav / blended - latent - diffusion 9https : / / github . com / Fantasy - Studio / Paint - by - Example 10https://huggingface.co/spaces/EleutherAI/clip- guided-diffusion 11https://huggingface.co/spaces/Fantasy- Studio/ Paint-by-Example 11 lized the paid inpainting demo 12 by OpenAI as we could not access the trained model freely. In particular, for the ex- periment with the CLIP-guided Diffusion model, we con- figured the model with the following hyperparameter set- tings: ‘skip timesteps’:30, ‘clip guidance scale’:1600, ‘tv scale’:150, ‘range scale’:50, ‘initial scale’: 1000. This de- viated from the default settings reported in the CLIP Guided Diffusion code repository, as the default settings resulted in poor image quality. Additionally, for the methods that are guided by user-provided masks (DALL-E 2, Blended La- tent Diffusion, Paint by Example), we manually generated the masks as illustrated in Figure 8. / Input Image Mask Input Figure 8. Example of manual masking applied to an input image. # C. User Study Details In order to evaluate the performance of our proposed method, a user study was conducted. A total of 76 par- ticipants were recruited, with a diverse age range of the 20s and 30s. The study was conducted using a Google Form, in which participants were asked to provide scores for im- ages generated by our method and several state-of-the-art methods. The evaluation was conducted in a blind manner, in which participants were not informed of which method was used to generate the images. Three questions were asked for each of the four stories, with each story featur- ing variations of 6 different image editing methods (1 ours + 5 baselines). In total, 72 questions were asked. The first question assessed the Correspondence of the gener- ated story set, with the following instruction used: ”Your task is to evaluate the correspondence between the plot and images, which refers to how well the images depict the corresponding plot.” The second question assessed the Co- herency of the generated story set, with the following in- struction used: ”Your task is to evaluate the coherency of appearance, which refers to how consistent the appearance of the main character is across the images.” The third ques- tion assessed the Smoothness of the generated story set, with the following instruction used: ”Your task is to evalu- ate the smoothness of the images, which refers to how well the facial regions blend seamlessly with the background re- gions.” A 5-point Likert scale was used for each aspect, with a minimum score of 1 and a maximum score of 5. The op- # 12https://openai.com/dall-e-2/ tions provided were: 1- Very Bad, 2- Bad, 3- Medium, 4- Good, 5-Very Good. # D. Limitations In our work, we employed a publicly available text- guided Latent Diffusion Model, Stable Diffusion, as the backbone of our proposed method. However, due to its in- herent limitations, not all text conditioning methods gener- ated optimal images, particularly in cases where images of people were involved. For example, images with mutated facial or body features were generated in some instances. To address this limitation, we incorporated the step of ‘Add fa- cial descriptions’ in our prompt generation pipeline, which partially mitigated this issue. However, it is important to note that the imperfect nature of Stable Diffusion may still lead to suboptimal results in some cases. # E. Social Impact The use of Text-Image models and generative image editing techniques poses several ethical challenges. These models have the potential to be used for malicious purposes, such as creating misleading or fake images, and can have negative societal impacts [11]. Our work is built on such models and is also susceptible to these issues. Additionally, the models were trained on a dataset of images collected from the web [44], which may contain inappropriate con- tent and biases. As a result, the models may inherit these biases [30] and generate inappropriate images. To mitigate these risks, we will release our code under a license that promotes ethical and legal use, similar to the license used for the Stable Diffusion model. # F. Additional Results # F.1. Face Restoration Target Without Face Restoration With Face Restoration Figure 9. Results of our method with and without face restoration. 12 # F.2. Different Number of Cycles Taget Source Cycle 1 oye? oye 4 cycles Figure 10. Generation results of our proposed method with differ- ent number of cycles # F.3. Additional Story Synthesis Results CLIP-quided Diffusion | ge 23 Ee 3 Figure 11. Our method applied to the story ‘The Lazy John’ Little A Stable DALL-E 2 Blended Prince — = CLIP-guided Diffusion Mask Latent Paint by Source Ours Diffusion Img2img Inpainting Diffusion Example 7 oe ss EBRD oe 7 ae #1 “Who are you?" asked the little prince, and added, "You are very pretty to look at." #2 “Lam a fox," the fox said. #3 "Come and play with me," proposed the little prince. "lam so. unhappy.” #4 "| cannot play with you," the fox said. "I am not tamed.” #5 “Ah! Please excuse me," said the little prince. #6 But, after some thought, he added: “What does that mean-'tame'?" Figure 12. Our method applied to the story ‘The Little Prince’ 13
Title: Adaptive Quantization for Deep Neural Network: Summary: In recent years Deep Neural Networks (DNNs) have been rapidly developed in various applications, together with increasingly complex architectures. The performance gain of these DNNs generally comes with high computational costs and large memory consumption, which may not be affordable for mobile platforms. Deep model quantization can be used for reducing the computation and memory costs of DNNs, and deploying complex DNNs on mobile equipment. In this work, we propose an optimization framework for deep model quantization. First, we propose a measurement to estimate the effect of parameter quantization errors in individual layers on the overall model prediction accuracy. Then, we propose an optimization process based on this measurement for finding optimal quantization bit-width for each layer. This is the first work that theoretically analyse the relationship between parameter quantization errors of individual layers and model accuracy. Our new quantization algorithm outperforms previous quantization optimization methods, and achieves 20-40% higher compression rate compared to equal bit-width quantization at the same model prediction accuracy. # Adaptive Quantization for Deep Neural Network Yiren Zhou1, Seyed-Mohsen Moosavi-Dezfooli2, Ngai-Man Cheung1, Pascal Frossard2 1Singapore University of Technology and Design (SUTD) 2 ´Ecole Polytechnique F´ed´erale de Lausanne (EPFL) yiren zhou@mymail.sutd.edu.sg, ngaiman cheung@sutd.edu.sg {seyed.moosavi, pascal.frossard}@epfl.ch # Abstract In recent years Deep Neural Networks (DNNs) have been rapidly developed in various applications, together with in- creasingly complex architectures. The performance gain of these DNNs generally comes with high computational costs and large memory consumption, which may not be affordable for mobile platforms. Deep model quantization can be used for reducing the computation and memory costs of DNNs, and deploying complex DNNs on mobile equipment. In this work, we propose an optimization framework for deep model quantization. First, we propose a measurement to estimate the effect of parameter quantization errors in individual layers on the overall model prediction accuracy. Then, we propose an optimization process based on this measurement for finding optimal quantization bit-width for each layer. This is the first work that theoretically analyse the relationship between pa- rameter quantization errors of individual layers and model accuracy. Our new quantization algorithm outperforms previ- ous quantization optimization methods, and achieves 20-40% higher compression rate compared to equal bit-width quanti- zation at the same model prediction accuracy. Introduction Deep neural networks (DNNs) have achieved significant success in various machine learning applications, includ- ing image classification (Krizhevsky, Sutskever, and Hinton 2012; Simonyan and Zisserman 2014; Szegedy et al. 2015), image retrieval (Hoang et al. 2017; Do, Doan, and Cheung 2016), and natural language processing (Deng, Hinton, and Kingsbury 2013). These achievements come with increasing computational and memory cost, as the neural networks are becoming deeper (He et al. 2016), and contain more filters per single layer (Zeiler and Fergus 2014). While the DNNs are powerful for various tasks, the in- creasing computational and memory costs make it difficult to apply on mobile platforms, considering the limited stor- age space, computation power, energy supply of mobile de- vices (Han, Mao, and Dally 2015), and the real-time pro- cessing requirements of mobile applications. There is clearly a need to reduce the computational resource requirements of DNN models so that they can be deployed on mobile de- vices (Zhou et al. 2016). In order to reduce the resource requirement of DNN mod- els, one approach relies on model pruning. By pruning some parameters in the model (Han, Mao, and Dally 2015), or skipping some operations during the evaluation (Figurnov et al. 2016), the storage space and/or the computational cost of DNN models can be reduced. Another approach consists in parameter quantization (Han, Mao, and Dally 2015). By applying quantization on model parameters, these parame- ters can be stored and computed under lower bit-width. The model size can be reduced, and the computation becomes more efficient under hardware support (Han et al. 2016). It is worth noting that model pruning and parameter quantiza- tion can be applied at the same time, without interfering with each other (Han, Mao, and Dally 2015); we can apply both approaches to achieve higher compression rates. Many deep model compression works have also con- sidered using parameter quantization (Gupta et al. 2015; Han, Mao, and Dally 2015; Wu et al. 2016) together with other compression techniques, and achieve good results. However, these works usually assign the same bit-width for quantization in the different layers of the deep network. In DNN models, the layers have different structures, which lead to the different properties related to quantization. By applying the same quantization bit-width for all layers, the results could be sub-optimal. It is however possible to as- sign different bit-width for different layers to achieve opti- mal quantization result (Hwang and Sung 2014). In this work, we propose an accurate and efficient method to find the optimal bit-width for coefficient quan- tization on each DNN layer. Inspired by the analysis in (Fawzi, Moosavi-Dezfooli, and Frossard 2016), we pro- pose a method to measure the effect of parameter quantiza- tion errors in individual layers on the overall model predic- tion accuracy. Then, by combining the effect caused by all layers, the optimal bit-width is decided for each layer. By this method we avoid the exhaustive search for optimal bit- width on each layer, and make the quantization process more efficient. We apply this method to quantize different models that have been pre-trained on ImageNet dataset and achieve good quantization results on all models. Our method con- stantly outperforms recent state-of-the-art, i.e., the SQNR- based method (Lin, Talathi, and Annapureddy 2016) on dif- ferent models, and achieves 20-40% higher compression rate compared to equal bit-width quantization. Furthermore, we give a theoretical analysis on how the quantization on layers affects DNN accuracy. To the best of our knowledge, this is the first work that theoretically analyses the relationship be- tween coefficient quantization effect of individual layers and DNN accuracy. 1 Related works Parameter quantization has been widely used for DNN model compression (Gupta et al. 2015; Han, Mao, and Dally 2015; Wu et al. 2016). The work in (Gupta et al. 2015) limits the bit-width of DNN models for both training and testing, and stochastic rounding scheme is proposed for quantiza- tion to improve the model training performance under low bit-width. The authors in (Han, Mao, and Dally 2015) use k- means to train the quantization centroids, and use these cen- troids to quantize the parameters. The authors in (Wu et al. 2016) separate the parameter vectors into sub-vectors, and find sub-codebook of each sub-vectors for quantization. In these works, all (or a majority of) layers are quantized with the same bit-width. However, as the layers in DNN have var- ious structures, these layers may have different properties with respect to quantization. It is possible to achieve better compression result by optimizing quantization bit-width for each layer. Previous works have been done for optimizing quanti- zation bit-width for DNN models (Hwang and Sung 2014; Anwar, Hwang, and Sung 2015; Lin, Talathi, and Anna- pureddy 2016; Sun, Lin, and Wang 2016). The authors in (Hwang and Sung 2014) propose an exhaustive search approach to find optimal bit-width for a fully-connected net- work. In (Sun, Lin, and Wang 2016), the authors first use exhaustive search to find optimal bit-width for uniform or non-uniform quantization; then two schemes are proposed to reduce the memory consumption during model testing. The exhaustive search approach only works for a relatively small network with few layers, while it is not practical for deep networks. As the number of layers increases, the complex- ity of exhaustive search increases exponentially. The authors in (Anwar, Hwang, and Sung 2015) use mean square quan- tization error (MSQE) (L2 error) on layer weights to mea- sure the sensitivity of DNN layers to quantization, and man- ually set the quantization bit-width for each layer. The work in (Lin, Talathi, and Annapureddy 2016) use the signal-to- quantization-noise ratio (SQNR) on layer weights to mea- sure the effect of quantization error in each layer. These MSQE and SQNR are good metrics for measuring the quan- tization loss on model weights. However, there is no theo- retical analysis to show how these measurements relate to the accuracy of the DNN model, but only empirical results are shown. The MSQE-based approach in (Anwar, Hwang, and Sung 2015) minimizes the L2 error on quantized weight, indicating that the L2 error in different layer has the equal effect on the model accuracy. Similarly, in (Lin, Talathi, and Annapureddy 2016), the authors maximize the overall SQNR, and suggest that quantization on different layers has equal contribution to the overall SQNR, thus has equal ef- fect on model accuracy. Both works ignore that the various structure and position of different layers may lead to dif- ferent robustness on quantization, and thus render the two approaches suboptimal. In this work, we follow the analysis in (Fawzi, Moosavi- Dezfooli, and Frossard 2016), and propose a method to mea- sure the effect of quantization error in each DNN layers. Different from (Anwar, Hwang, and Sung 2015; Lin, Ta- lathi, and Annapureddy 2016), which use empirical results to show the relationship between the measurement and DNN accuracy, we conduct a theoretical analysis to show how our proposed method relates to the model accuracy. Further- more, we show that our bit-width optimization method is more general than the method in (Lin, Talathi, and Anna- pureddy 2016), which makes our optimization more accu- rate. There are also works (Hinton, Vinyals, and Dean 2015; Romero et al. 2014) that use knowledge distillation to train a smaller network using original complex models. It is also possible to combine our quantization framework with knowledge distillation to achieve yet better compression re- sults. Measuring the effect of quantization noise In this section, we analyse the effect of quantization on the accuracy of a DNN model. Parameter quantization can result in quantization noise that would affect the performance of the model. Previous works have been done for analyzing the effect of input noise on the DNN model (Fawzi, Moosavi- Dezfooli, and Frossard 2016); here we use this idea to anal- yse the effect of noise in intermediate feature maps in the DNN model. Quantization optimization The goal of our paper is to find a way to achieve optimal quantization result to compress a DNN model. After the quantization, under controlled accuracy penalty, we would like the model size to be as small as possible. Suppose that we have a DNN F with N layers. Each layer i has s; param- eters, and we apply b; bit-width quantization in the parame- ters of layer i to obtain a quantized model F’. Our optimiza- tion objective is: N mind 5°; () s.t. acez — accF < Nace, where accy is the accuracy of the model F, and Aace is the maximum accuracy degradation. Note that it re- quires enormous computation to calculate the accuracy of the model for all quantization cases. To solve the problem more efficiently, we propose a method to estimate the value of the performance penalty given by accr — accr’. Quantization noise Value quantization is a simple yet effective way to compress a model (Han, Mao, and Dally 2015). Here we evaluate the effect of using value quantization on model parameters. Assume that conducting quantization on a value is equiv- alent to adding noise to the value: wq = w + rw (2) Here w is the original value, w ∈ W , with W the set of weights in a layer. Then, wq is the quantized value, and rw is the quantization noise. Assume that we use a uniform quan- tizer, and that the stepsize of the quantized interval is fixed. Following the uniform quantization analysis in (You 2010), if we consider rw = (rw,1, · · · , rw,NW ) as the quantization noise on all weights in W , we have the expectation of ||rw||2 2 as E(||rw||2 w · e−α·b, (3) # E(\[w||3) = eminsemas) , NW is the number of weights in W , and α = ln(4) (You 2010). Detailed analysis can be found in Supplementary Material. Eq. (3) indicates that every time we reduce the bit-width by 1 bit, E(||rw||2 2) will increase by 4 times. This is equivalent to the quantiza- tion efficiency of 6dB/bit in (Gray and Neuhoff 2006). # Measurement for quantization noise input image DNN last feature vector probability m4 FF softmax Bi Figure 1: Simple DNN model architecture. From weight domain to feature domain Eq. (3) shows the quantization noise in the weight domain; here we show how the noise on weight domain can link to the noise in the feature domain. A simplified DNN classifier architecture is shown in Fig. 1. Here we define Wi as the weights of layer i in the DNN model F. And Z is the last feature map (vector) of the DNN model F. As we quantize Wi, the quantization noise is rWi, and there would be a resulting noise rZi on the last feature map Z. Here we define rZi as the noise on last feature map Z that is caused by the quantization only on a single layer i. 2 is proportional to the value of 2, similar to Eq. (3), the expectation of resulting noise As the value of ||rZi ||2 ||rWi||2 on rZi is: E(||rZi||2 2) = pi · e−α·bi (4) This is proved in later sections, empirical results are shown in Fig. 4. The effect of quantization noise Similarly to the analysis in (Pang, Du, and Zhu 2017), we can see that the softmax classifier has a linear decision boundary in the last feature vectors Z (Pang, Du, and Zhu 2017) in Fig. 1. The analy- sis can be found in the Supplementary Material. Then we apply the result of (Fawzi, Moosavi-Dezfooli, and Frossard 2016) to bound the robustness of the classifier with respect to manipulation of weights in different layers. We define r∗ to be the adversarial noise, which represents the minimum noise to cause misclassification. For a certain input vector z = (z1, · · · , zL), where L is the number of element in z, the ||r∗||2 is the distance from the datapoint to the decision boundary, which is a fixed value. We define a sorted vector of z as zsorted = (z(1), · · · , z(L)), where the max value is z(1), and second max value is z(2). The result for softmax classifier (or max classifier) can be expressed as: max(z) = z(1), which is picking up the maximum value in the vectorz. As adversarial noise is the minimum noise that can change the result of a classifier, we can get the adver- sarial noise for softmax classifier max(z) as r∗ = ( z(2)−z(1) , 0, · · · , 0), then the norm square of ad- 2 2 = (z(1) − z(2))2/2. versarial noise ||r∗||2 Here we define rZ as the noise that we directly add on last feature map Z. We can consider rZ as the collective effect of all rZi that caused by the quantization on all layers i ∈ {1, · · · , N }, where N is the number of layers. As mentioned in (Fawzi, Moosavi-Dezfooli, and Frossard 2016), if we apply random noise ||rz/||3 rather than adversar- ial noise ||r*||2 on the input vector z for a softmax classifier maz(z), it requires higher norm for random noise ||rz/||3 to causes prediction error with same probability, compared to adversarial noise ||r*||2. The following result shows the relationship between the random noise ||rz||3 and adversarial noise ||r*||2, under soft- max classifier with a number of classes equal to d: Lemma 1. Let 7(5) = 5+41In(1/6). The following inequal- ities hold between the norm square of random noise | z\| @ay- =e and adversarial noise 2 Ind x1) — 22))? 24 (o)iiraig > Gore (5) with probability exceeding 1 − 2δ. The proof of Lemma 1 can be found in the Supplemen- tary Material. The lemma states that if the norm of random noise is o , it does not change the classifier decision with high probability. Based on Lemma 1, we can rewrite our optimization prob- lem. Assume that we have a model F with accuracy accF . After adding random noise rZ on the last feature map Z, the model accuracy drops by ∆acc. If we have θ(∆acc) = d γ( ∆acc 2accF ) ln d , (6) we have the relation between accuracy degradation and noise rZ as: acer — accz < Mace > (za) = 2)” M 2 \Irz IIs < O(Aace) The detailed analysis can be found in the Supplementary Material. Eq. (7) shows the bound of noise on last feature map Z. However, adding quantization noise to different lay- ers may have different effect on model accuracy. Suppose we have model ¥ for quantization. By adding noise rw, on weights of layer i, we induce the noise rz, on last fea- ture map Z. By quantizing earlier layers, the noise needs to pass through more layers to get rz,, which results in a low rank noise rz,. For example, when quantizing the first layer, is results inrz, = (e1,--- ,ea,0,--- ,0), and rank(rz,) = d' < d. When quantizing the last layer, it re- sults inrz, = (e1,-++ ,éa), and rank(rz,,) = d. In order to let rz, have equivalent effect on model accuracy as rz,, ||rz, ||z should be larger than ||rz, ||». By considering the different effects of rZi caused by quantization in different layers, we rewrite Eq. (7) in a more precise form: acez — accez = Agec > (z() — 2)” (8) 3 . [3 = ti(Aace) Irz, Here ti(∆acc) is the robustness parameter of layer i under accuracy degradation ∆acc. Eq. (8) shows a precise relationship between rZi and ∆acc. If we add quantization noise to layer i of model F, and get noise rZi on last feature map Z, then the model ac- curacy decreases by ∆acc. We consider the layer i in model F as yi = Fi(yi−1), where yi is the feature map after layer i. Here we consider that the noise ryi would transfer through layers under almost linear transformation (to be discussed in later sections). If we add random noise in the weights of layer i, we have the rank of the resulting noise rZi on last feature map Z given as: N rank(rz,) = rank(] | Fi) < min{rank(F;)} (9) i Based on Eq. (9), we have: rank(rZ1) ≤ · · · ≤ rank(rZi) ≤ · · · ≤ rank(rZN ) (10) Eq. (10) suggests that the noise on earlier layers of DNN needs to pass through more layers to affect the last feature map Z, the noise rZi on Z would have lower rank, resulting in a lower value of ti(∆acc). From Eq. (8), we can see in particular that when Ir2l3 _ (rz, IB ay ti(Aace) ti (Aace)’ the quantization on layer i and j have same effect on model accuracy. Based on Eq. (11), Ie good measurement for estimating the accuracy degradation caused by quantization noise, regardless of which layer to quantize. Consider x € D as the input in dataset D, we have the corresponding feature vector z = G(x, W) in the last fea- ture map Z. By quantizing layer i in model F, we get noise r,, on z. We define the accuracy measurement on layer i as: can be a Poy oxo Ira ll3) |g. {13 mM; ‘ ti(Aace) 2 (12) ti(Aace) The way to calculate ti(∆acc) is given by: oy Deep Ilrell3 a DLs SE ay s.t. accez — accz = Nace meany, ti(Aace) MEANy* The detailed method to calculate ti(∆acc) will be dis- cussed in the experiment section. Note that, based on the optimization result in Eq. (22), the selected value of ∆acc does not matter for the optimization result, as long as the the value of ti(∆acc) tj (∆acc) is almost independent w.r.t. ∆acc, which is true according to Fig. 3. So choosing different value of ∆acc does not change the optimization result. In later sections, we use ti instead of ti(∆acc) for simplicity. From Eq. (12), based on the linearity and additivity of the proposed estimation method (shown in later sections), the measurement of the effect of quantization error in all the layers of the DNN model is shown in Eq. (20). After we define the accuracy measurement for each layer of model, based on Eq. (8), we can then rewrite the opti- mization in Eq. (1) as N min 5b; i=1 N s.t. Ma = Yom <C, i=l (14) where mall is the accuracy measurement for all layers, and C is a constant related to model accuracy degradation ∆acc, with higher C indicating higher ∆acc. Linearity of the measurements In this section we will show that the DNN model are locally linear to the quantization noise measurement ||ry/||2, under the assumption that the quantization noise is much smaller than the original value: ||r||2 < ||w||2. That is, if a quan- tization noise ||ryy, ||2 on layer i leads to ||rz,||2 on last fea- ture vector Z, then we have a quantization noise a - ||ry,||2 on layer 7 leads to a - ||rz,||2 on last feature vector Z. For linear layers like convolutional layers and fully con- nected layers in the DNN model, the linearity for noise is obvious. Here we mainly focus on the non-linear layers in the DNN model, such as ReLU and Max-pooling layers. ReLU layers The ReLU layers is widely used to provide nonlinear activation for DNN. Given the input a ∈ A to a ReLU layer, the output value z ∈ Z is calculated as: a, ifa>0 0, ifa<=0 z= ReLU(a) = { (15) From Eq. (15) we can see that the ReLU layer is linear to noise in most cases. The non-linearity happens only when the noise rw crossing the zero point, which has small proba- bility when the noise is sufficiently small. Max-pooling layers Max-pooling is a nonlinear down- sampling layer that reduces the input dimension and controls overfitting. We can consider that max-pooling acts as a max filter to the feature maps. Similarly to the ReLU layer, which can be described as z = ReLU (a) = max(0, a), the max-pooling layer can be describes as z = maxpool({ai}) = max({ai}), where i = 1, · · · , P , with P the kernel size for max-pooling. The linearity for noise holds when the noises are sufficiently small and do not alter the order for {ai}. Other layers For other non-linear layers like Sigmoid and PReLU, the linearity for small noises still holds under the assumptions that the function is smooth along most input ranges, and the noise has very low probability to cross the non-linear region. Based on the linearity assumption, as we model the quan- tization noise on weight as Eq. (3), the resulting noise on last feature vector Z can be modeled as: ||rZi||2 2 = pi · e−α·bi (16) # Additivity of the measurements Noise on single multiplication Pairwise multiplication is a basic operation in the convolutional layers and fully con- nected layers of DNN. Given one value in the input a ∈ A, one value in the weight matrix w ∈ W , we have the pair- wise multiplication as a · w. If we consider noise in both input a ∈ A and w ∈ W , we have noised value aq ∈ Aq and wq ∈ Wq, and finally aq · wq = (a + ra) · (w + rw). Noise on one layer Given a convolutional layer input A with size M × N × C, conv kernel K with size Mk × Nk × C × D, and stride size s, we have the output feature map Z with size (M/s)×(N/s)×D. Here M and N are the height and width of input, C is the number of channels of input. Mk and Nk are the height and width of the conv kernel, D is the depth of output feature map. The analysis on fully connected layers will be similar to the analysis on convolutional layers. It can be considered as a special case of convolutional layers when M , N , Mk, and Nk are equal to 1. For a single value zp,q,d ∈ Z, the noise term of zp,q,d can be expressed as: My-Nu-C Ven qd y (Gi + Twig Fla: Wid +a: Twig) +7 ba i=l My-Nu-C Ss (Qi Twig + Ta; * Wid) i=l v (17) (17) The calculation details can be found in Supplementary Material. Note that the term r,, can be ignored under the assumption that w and b have same bit-width quantization. The term rg, -T», , can be ignored under the assumption that |Irall2 <lal|2 and ||rw|l2 << |lwl2. From Eq. (17) we can see that: 1) adding noise to input feature maps and weights separately and independently, is equivalent to adding noise to both input feature maps and weights; 2) regarding the output feature map z ∈ Z, adding noise to the input feature maps and weights and doing layer operation (pairwise product), is equivalent to adding the noise directly to the output feature map. We will use these two properties in later sections. (a) (b) (c) Tw, i r r juantized xX) Z input ae intermediate conv 2 output feature map ReLU feature map ReLU feature map A on x Pooling Zz Pooling rw, quantized Yz, input conv 1 intermediate conv 2 output feature map ReLU feature map at feature map A Pooling x P z ‘ooling rw, rw, quantized Tx, quantized TZ; input conv 1 intermediate conv 2 output a map ReLU fostl map ReLU ia map Pooling Pooling Figure 2: Effect of adding noise to multiple layers. Adding noise to multiple layers Fig. 2 shows a 2-layer module inside a DNN model. Given input feature map A, after the first conv layer, an intermediate feature map X is generated, then after the second conv layer, output feature map Z is generated. Fig. 2(a) and 2(b) show the effect of noise on layer 1 and 2, respectively. And Fig. 2(c) shows the effect of noise on both layer | and 2. By analysing the additivity of ||rz||?, we have: ||rz3||2 2 . = ||rz1 ||2 2 + ||rz2||2 2 (18) Detailed analysis can be found in Supplementary Mate- rial. Eq. (18) holds under the assumption that rz1 and rz2 are independent. This is reasonable in our case, as rz1 and rz2 are caused by rW1 and rW2 which are two independent quantization noises. This independence between rz1 and rz2 is also important for our proposed estimation method. We can extend Eq. (18) to the situation of N layers: 3 (19) N IIr2||5 = Ss |lr2, i=1 If we consider the linearity and additivity of the proposed measurement, from Eq. (12) and Eq. (19), as well as the in- dependence of the measurement among different layers, we have the measurement of the effect of quantization errors in all layers in DNN model: Nw N N r mat = ym = yo Mall 20) i=1 i=l o Eq. (20) suggests that the noise effect of adding noise to each layer separately and independently, is equivalent to the effect of adding noise to all layers simultaneously. We use Eq. (12) as the measurement for noise effect on layer i, and the effect of adding noise to all layers can be predicted using Eq. (20). Layer-wise bit-width optimization In this section we show the approach for optimizing the layer-wise bit-width quantization to achieve an optimal com- pression ratio under certain accuracy loss. Following the discussion from the optimization problem in Eq. (14), our goal is to constraint Eq. (20) to be a small value while minimizing the model size. Adaptive quantization on multiple layers Based on Eq. (16) and (20), the optimization Eq. (14) can be expressed as: N min 5b; i=1 N Di (21) s.t. Sen odi ig » 7 e <C i=l # s.t. The optimal value of Eq. (21) can be reached when: p1 · e−α·b1 t1 · s1 = p2 · e−α·b2 t2 · s2 = · · · = pN · e−α·bN tN · sN (22) The detailed analysis can be found in Supplementary Ma- terial. Optimal bit-width for each layer From Eq. (22) we can directly find the optimal bit-width for each layer using the following procedure: • Calculate ti (Eq. (13)): — First, calculate the mean value of adversarial noise for (a)=2@))" xeED 2 : the dataset: mean, = ral > the dataset: meanr∗ = 1 |D| – Then, fix ∆acc value. For example, ∆acc = 10%. Note that the selection of ∆acc value does not affect the op- timization result. – For each layer i, change the amount of noise rWi added in weight Wi, until the accuracy degradation equals to ∆acc. Then, record the mean value of noise rzi on the last feature map Z: meanrzi x∈D ||rzi||2 2. meanrzi – The value ti can be calculated as: ti(∆acc) = meanr∗ . – The details for the calculation of ti can be found in - The details for the calculation of t; can be found in Fig. 3. # Fig. 3. • Calculate pi: – First, for each layer i, fix bi value. For example, use bi = 10. – Then, record the mean value of noise rzi on the last = 1 |D| – The value pi can be calculated using Eq. = ||rZi||2 2 = pi · e−α·bi . (16): # meanrzi • Calculate bi: – Fix the bitwidth for first layer b1, for example, b1 = 10. Then bitwidth for layer i can be calculated using the Eq. (22): p1·e−α·b1 The detailed algorithm about the above procedure can be found in Supplementary Material. Note that, by select- ing different b1, we achieve different quantization result. A lower value of b1 results in higher compression rate, as well as higher accuracy degradation. Comparison with SQNR-based approach Based on the SQNR-based approach (Lin, Talathi, and An- napureddy 2016), the optimal bit-width is reached when: e−α·b1 s1 = e−α·b2 s2 = · · · = e−α·bN sN (23) The proof can be found in Supplementary Material. Note that compared with our result in Eq. (22), the parameters pi and ti are missing. This is consistent with the assumption of the SQNR-based approach, where two layers having the same bit-width for quantization would have the same SQNR value; hence the effects on accuracy are equal. This makes the SQNR-based approach a special case of our approach, when all layers in the DNN model have the equal effect on model accuracy under the same bit-width. Experimental results In this section we show empirical results that validate our assumptions in previous sections, and evaluate the proposed bit-width optimization approach. All codes are implemented using MatConvNet (Vedaldi and Lenc 2015). All experiments are conducted using a Dell workstation with E5-2630 CPU and Titan X Pascal GPU. Empirical results about measurements To validate the effectiveness of the proposed accuracy esti- mation method, we conduct several experiments. These ex- periments validate the relationship between the estimated accuracy, the linearity of the measurement, and the additiv- ity of the measurement. Here we use Alexnet (Krizhevsky, Sutskever, and Hin- ton 2012), VGG-16 (Simonyan and Zisserman 2014), GoogleNet (Szegedy et al. 2015), and Resnet (He et al. 2016) as the model for quantization. Each layer of the model is quantized separately using uniform quantization, but possibly with different bit-width. The quantized model is then tested on the validation set of Imagenet (Krizhevsky, Sutskever, and Hinton 2012), which contains 50000 images in 1000 classes. Calculate ti As Eq. (12) is proposed to measure the ro- bustness of each layer, we conduct an experiment to find ti value. We use Alexnet as an example. First, we calculate the adversarial noise for Alexnet on the last feature vector Z. The calculation is based on Eq. (13). The mean value of ||r∗||2 2 for Alexnet is meanr∗ = 5.33. The distribution of ||r∗||2 2 for Alexnet on Imagenet valida- tion set can be found in Supplementary Material. 2 value, the value of ti is calculated based on Fig. 3(a) and Eq. (13). We set the accuracy degra- dation to be roughly half of original accuracy (57%), which is 28%. Based on the values in Fig. 3(a), t1 to t6 are equal to 5.2 × 102, t7 = 1.3 × 103, and t8 = 2.0 × 103. (a) (b) Alexnet 06. s “layer 1 eS layer 2 > “layer 3 04 layer 4 Fl layer 5 8 layer 6 ~02 “layer 7 3 layer 8 2 0 10° 2 Illa VGG-16 08 g 0.6 3 g 304 8 8 30.2 8 aes g Bat 0 10° 2 Illa Figure 3: The relationship between different ||rZi||2 model accuracy. Here we show the example for Alexnet of how to calcu- late the ¢; value. Note that for other networks like VGG- 16, GoogleNet, and Resnet, we also observe that only the t; value for the last 1 or 2 layers are obviously different than the other t; values. During our calculation, we can thus focus on the ¢; values for the last several layers. Further- more, in Fig. 3(a), we find the ||rz||? — accuracy relation- ship for different amounts of noise, which requires a lot of calculations. In real cases, we use binary search to find ap- propriate points under the same accuracy degradation. This makes the process to calculate t; fast and efficient. Typically, for a deep model with N layers, and dataset with |D| size, we require O(r N|D|) forward passes to calculate accuracy. Here 7 is the trial times over one layer. We can reduce it to O(rN"|D|)(with N’ << N) by only calculating t; values for the last N’ layers. In our experiments, the calculation of ti is the most time- consuming part of our algorithm. We use around 15 mins to calculate the ti value for Alexnet (30 sec for forward pass on the whole dataset), and around 6 hours to calculate the ti value for Resnet-50 (2 min for forward pass on the whole dataset). This time can be reduced if we only calculate ti values for the last few layers. Linearity of measurements Fig. 4 shows the relation- ship between the norm square of noise on quantized weight ||rWi||2 2 on different layers. When the quantiza- tion noise on weight is small, we can observe linear relation- ships. While it is interesting to see that, when the quantiza- tion noise is large, the curve does not follow exact linearity, and curves for earlier layers are not as linear as later lay- ers. One possible explanation is that earlier layers in a DNN 408 Alexnet uN layer =r 10° ite » ayer 3 slayer 4 slayer 5 layer 6 ayer 108 ies 10°? 10° 2 Mylo (a) 108 VGG-16 anal as 10° a 10° 10° 10° 2 Me ylte (b) # Figure 4: The relationship between ||rWi||2 2 and ||rZi||2 2. model are affected by more non-linear layers, such as ReLU and Max-pooling layers. When the noise is large enough to reach the non-linear part of the layer functions (i.e. the zero point of the ReLU function), the curves become non-linear. It is worth noting that, when the non-linearity in most lay- ers happens, the accuracy of the model is already heavily affected (become near zero). So this non-linearity would not affect our quantization optimization process. Additivity of measurements Fig. 5 shows the relation- ship between SH |l'z,\|3 when we quantize each layer sep- arately, and the value ||rz||3 when we quantize all layers to- gether. We can see that when the quantization noise is small, the result closely follows our analysis that ||rz||3 = ||1rz, ||3; it validates the additivity of ||rz||3. When the quantization noise is large, the additivity of ||rz||3 is not accurate. This result fits our assumption in Eq. (17), where the additivity holds under the condition ||ryy,||2 < ||Wi||2 for all layer i in the DNN model. When the noise is too high and we ob- serve the inaccuracy of additivity, the model accuracy is al- ready heavily degraded (near zero). Hence it does not affect the quantization optimization process which rather works in low noise regime. Optimal bit-width for models After the validation of the proposed measurement, we con- duct experiments to show the results on adaptive quanti- zation. Here we use Alexnet (Krizhevsky, Sutskever, and Hinton 2012), VGG-16 (Simonyan and Zisserman 2014), GoogleNet (Szegedy et al. 2015), and Resnet-50 (He et al. 2016) to test our bit-width optimization approach. Similarly to the last experiments, the validation set of Imagenet is used. As the SQNR-based method (Lin, Talathi, and Anna- Alexnet 10° ay ww 10° 10° 10° sum of IIe Ie (a) (b) VGG-16 10° oc ww = 499 10° 10° sum of IIe Ie Figure 5: The value of }> N ||rz, ||3 when quantize each layer separately, compare to ||rz||3 when quantize all layers si- multaneously. pureddy 2016) only works for convolutional layers, here we keep the fully connected layers with 16 bits . Fig. 6 shows the quantization results using our method, SQNR-based method (Lin, Talathi, and Annapureddy 2016), and equal bit-width quantization. The equal bit-width quan- tization means that the number of quantization intervals in all layers are the same. For all three methods, we use uni- form quantization for each layer. We can see that for all networks, our proposed method outperforms SQNR-based method, and achieves smaller model size for the same accu- racy degradation. It is interesting to see that the SQNR-based method does not obviously outperform equal quantization on the Resnet-50 model. One possible reason is that Resnet- 50 contains 1 × 1 convolutional layers in its ”bottleneck” structure, which is similar to fully connected layers. As the authors claim in (Lin, Talathi, and Annapureddy 2016), the SQNR-based method does not work for fully connected lay- ers. Note that our method generates more datapoints on the figure, because the optimal bit-width for different layers may contain different decimals. And by rounding the optimal bit- width in different ways, we can generate more bit-width combinations than the SQNR-based methods. The results for quantization on all layers are shown in Supplementary Material. For Alexnet and VGG-16 model, our method achieves 30 − 40% smaller model size with the same accuracy degradation, while for GoogleNet and Resnet-50, our method achieves 15 − 20% smaller model size with the same accuracy degradation. These results in- dicate that our proposed quantization method works better for models with more diverse layer size and structures, like Quantization on Alexnet + Equal bitwidth ~e- SQNR-based optimization == our method Top-1 error rate (%) ° ® 10 20 30 40 Model size (Mbits) (a) 07 Quantization on VGG-16 . 4 \. equal bitwiath g \ -e- SQNR-based optimization 506 4 2 \ g i 505 *\ o an 0.4 ° 2 0.3 — 60 80 100 120 Model size (Mbits) (b) (c) 08 Quantization on GoogleNet “ \ [Equal bitwiath Zo7 i -2- SQNR-based optimization ~~ \ = our method 2 £06 ig 505 s 0.4 C0. 0.3 20 30 40 50 Model size (Mbits) 05 Quantization on Resnet-50 . + Equal bitwidth Jo.45 1\ -°- SQNR-based optimization Ss iH B04 H Loss | 2 i a 03 i 2 0.25 100 120 140 160 180 200 220 Model size (Mbits) (d) Figure 6: Model size after quantization, v.s. accuracy. To compare with SQNR-based method (Lin, Talathi, and An- napureddy 2016), only convolutional layers are quantized. Alexnet and VGG. # Conclusions Parameter quantization is an important process to reduce the computation and memory costs of DNNs, and to deploy complex DNNs on mobile equipments. In this work, we pro- pose an efficient approach to optimize layer-wise bit-width for parameter quantization. We propose a method that relates quantization to model accuracy, and theoretically analyses this method. We show that the proposed approach is more general and accurate than previous quantization optimiza- tion approaches. Experimental results show that our method outperforms previous works, and achieves 20 − 40% higher compression rate than SQNR-based methods and equal bit- width quantization. For future works, we will consider com- bining our method with fine-tuning and other model com- pression methods to achieve better model compression re- sults. References Anwar, S.; Hwang, K.; and Sung, W. 2015. Fixed point optimization of deep convolutional neural networks for ob- ject recognition. In 2015 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), 1131– 1135. Deng, L.; Hinton, G.; and Kingsbury, B. 2013. New types of deep neural network learning for speech recognition and related applications: An overview. In Acoustics, Speech and Signal Processing (ICASSP), 2013 IEEE International Con- ference on, 8599–8603. Do, T.-T.; Doan, A.-D.; and Cheung, N.-M. 2016. Learning to hash with binary deep neural network. In European Con- ference on Computer Vision (ECCV), 219–234. Springer. Fawzi, A.; Moosavi-Dezfooli, S.-M.; and Frossard, P. 2016. Robustness of classifiers: from adversarial to random noise. In Advances in Neural Information Processing Systems (NIPS). 1632–1640. Figurnov, M.; Ibraimova, A.; Vetrov, D. P.; and Kohli, P. 2016. Perforatedcnns: Acceleration through elimination of redundant convolutions. In Advances in Neural Information Processing Systems (NIPS), 947–955. Gray, R. M., and Neuhoff, D. L. tion. 44(6):2325–2383. Gupta, S.; Agrawal, A.; Gopalakrishnan, K.; and Narayanan, P. 2015. Deep learning with limited numerical precision. In Proceedings of the 32nd International Conference on Ma- chine Learning (ICML), 1737–1746. Han, S.; Liu, X.; Mao, H.; Pu, J.; Pedram, A.; Horowitz, M. A.; and Dally, W. J. 2016. Eie: efficient inference en- gine on compressed deep neural network. In Proceedings of the IEEE International Symposium on Computer Architec- ture (ISCA), 243–254. 2015. Deep com- Han, S.; Mao, H.; and Dally, W. J. pression: Compressing deep neural networks with pruning, trained quantization and huffman coding. arXiv preprint arXiv:1510.00149. He, K.; Zhang, X.; Ren, S.; and Sun, J. 2016. Deep resid- In Proceedings of the ual learning for image recognition. IEEE conference on computer vision and pattern recogni- tion (CVPR), 770–778. Hinton, G.; Vinyals, O.; and Dean, J. ing the knowledge in a neural network. arXiv:1503.02531. Hoang, T.; Do, T.-T.; Tan, D.-K. L.; and Cheung, N.-M. 2017. Selective deep convolutional features for image re- trieval. arXiv preprint arXiv:1707.00809. Hwang, K., and Sung, W. 2014. Fixed-point feedforward deep neural network design using weights+ 1, 0, and- 1. In 2014 IEEE Workshop on Signal Processing Systems (SiPS), 1–6. Krizhevsky, A.; Sutskever, I.; and Hinton, G. E. 2012. Imagenet classification with deep convolutional neural net- works. In Advances in neural information processing sys- tems (NIPS), 1097–1105. Lin, D.; Talathi, S.; and Annapureddy, S. 2016. Fixed point quantization of deep convolutional networks. In Inter- national Conference on Machine Learning (ICML), 2849– 2858. Pang, T.; Du, C.; and Zhu, J. 2017. Robust deep learning via reverse cross-entropy training and thresholding test. arXiv preprint arXiv:1706.00633. Romero, A.; Ballas, N.; Kahou, S. E.; Chassang, A.; Gatta, C.; and Bengio, Y. 2014. Fitnets: Hints for thin deep nets. arXiv preprint arXiv:1412.6550. Simonyan, K., and Zisserman, A. 2014. Very deep convo- lutional networks for large-scale image recognition. CoRR abs/1409.1556. Sun, F.; Lin, J.; and Wang, Z. 2016. Intra-layer nonuni- form quantization of convolutional neural network. In 2016 8th International Conference on Wireless Communications & Signal Processing (WCSP), 1–5. Szegedy, C.; Liu, W.; Jia, Y.; Sermanet, P.; Reed, S.; Anguelov, D.; Erhan, D.; Vanhoucke, V.; and Rabinovich, In Proceed- A. 2015. Going deeper with convolutions. ings of the IEEE conference on computer vision and pattern recognition (CVPR), 1–9. Vedaldi, A., and Lenc, K. 2015. Matconvnet – convolutional neural networks for matlab. In Proceeding of the ACM Int. Conf. on Multimedia. Wu, J.; Leng, C.; Wang, Y.; Hu, Q.; and Cheng, J. 2016. Quantized convolutional neural networks for mobile de- vices. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 4820–4828. You, Y. 2010. Audio Coding: Theory and Applications. Springer Science & Business Media. Zeiler, M. D., and Fergus, R. 2014. Visualizing and under- In European conference standing convolutional networks. on computer vision (ECCV), 818–833. Springer. Zhou, Y.; Do, T. T.; Zheng, H.; Cheung, N. M.; and Fang, L. 2016. Computation and memory efficient image segmenta- tion. IEEE Transactions on Circuits and Systems for Video Technology (TCSVT) PP(99):1–1. # Supplementary Material: Adaptive Quantization for Deep Neural Network Yiren Zhou1, Seyed-Mohsen Moosavi-Dezfooli2, Ngai-Man Cheung1, Pascal Frossard2 1Singapore University of Technology and Design (SUTD) 2 ´Ecole Polytechnique F´ed´erale de Lausanne (EPFL) yiren zhou@mymail.sutd.edu.sg, ngaiman cheung@sutd.edu.sg {seyed.moosavi, pascal.frossard}@epfl.ch # Measuring the effect of quantization noise Quantization noise Assume that conducting quantization on a value is equiva- lent to adding noise to the value: (2 revisited) Here w is the original value, w ∈ W , W is all weights in a layer. wq is the quantized value, and rw is the quantization noise. Assume we use a uniform quantizer, that the stepsize of the quantized interval is fixed. Then the quantization noise rw follows a uniform distribution in range (− B 2 ), where B is the quantized interval. Based on this, rw has zero mean, and the variance of the noise var(rw) = B2 12 . Then we have E(r2 w) = var(rw) + E(rw)2 = B2 12 . Follow the uniform quantization analysis in (You 2010), given weights w ∈ W in a layer, w ∈ (wmin, wmax). If we quantize the weights by b bits, the total number of inter- val would be M = 2b, and quantization interval would be wmin−wmax . If we consider rw = (rw,1, · · · , rw,NW ) as the 2b quantization noise on all weights in W , The expectation of noise square: Nw E( wll3) = 30 EC) = Nw (Wmin = Cmax)” 12 47h u —a-b =pi,-e A DNN classifier can be expressed as a mapping func- tion F(X, W ) : Rd → RL, where X ∈ Rd is the input variable, W is the parameters, and L denotes the number of classes. From Fig. 1, here we divide the DNN into two parts. In the first part, we have a mapping function G(X,W) : #4 > &", which maps input variables X € #¢ into the feature vectors Z € #* for the last layer of DNN. In the second part, we have the softmax function softmaz(z) : #” > R* as softmaa(z;)) = exp(%)/ i, eap(x), i € [L], where [L] := 1,..., L. The final classification result can be calculated by picking the maximum value of the softmax value: argmaxi sof tmax(zi), i ∈ [L]. Note that this is equiv- alent to picking the maximum value for feature vector z: argmaxi zi, i ∈ [L]. So we can see that the softmax clas- sifier has a linear decision boundary in the feature vectors Z (Pang, Du, and Zhu 2017). # Proof of Lemma 1 Lemma 1. Let 7(5) = 5+41In(1/6). The following inequal- ities hold between the norm square of random noise | z| 2 and adversarial noise Gaya) 2 Ind 2 (O)licib > (zq) _ 22))” 2 (5) (3 revisited) with probability exceeding 1 − 2δ. (wmin−wmax)2 , NW is the number of 12 weights in W , and α = ln(4). Eq. (3) indicates that every time we reduce the bit-width by 1 bit, E(r2 w) will increase by 4 times. This is equivalent to the quantization efficiency of 6dB/bit mentioned in (Lin, Talathi, and Annapureddy 2016). Proof. Based on Theorem 1 in (Fawzi, Moosavi-Dezfooli, and Frossard 2016), for an L-class classifier, the norm of a random noise to fool the classifier can be bounded from below by # The property of softmax classifier input image DNN last feature vector probability X a softmax . input image DNN last feature vector probability X a softmax . dlr" ||3 < B(5)IIrzll2, (24) with a probability exceeding 1 — 2(L + 1)6’, where 8(0’) = 1 + 2\/In(1/6’) + 21In(1/0’). For the softmax layer, L = d —1, therefore one can write P (dljr*||3 < B(6’)|rz]3) >1—2d5’. (25) P (dljr*||3 < B(6’)|rz]3) >1—2d5’. (25) Figure 1: Simple DNN model architecture. Furthermore, ||r*||3_ = (z(1) — 2(2))?/2, where 2(;) is i” largest element of z. Put 6’ = 6/d, hence Similar to the analysis in (Pang, Du, and Zhu 2017), we analyse the property of softmax classifier. P (dir*|[z < B(6/d)\|rzl|z) > 1-26. (26) 10 From the other hand, B(5/d) = 1+ 2y/in(d/6) + 2In(a/5) >1+4In(d/6) (27) > Ind(5 + 4In(1/5)) = (6) Ind. # Therefore, diy P (Sil diy igs . , P (Sil Bs »(6)lt2I3) > P (djr*3 < 6(6/a)\rzl3) > 1-26, (28) which concludes the proof. Relationship between accuracy and noise The original quantization optimization problem: N min 55° b; i=1 1 revisited) s.t. acez — acce < Nace Lemma | states that if the norm of random noise is 0 ((ea — 22))/d/In d), it does not change the classifier decision with high probability. In particular, from Lemma 1 (Eq. (28) in specific), the probability of misclassification can be expressed as: d__ (za) —%2))”) P(|irz [3 < ——— 8)" *) (5) nd 2 <8 29) Eq. (29) suggest that as we limit the noise to be less (z(1)−z(2))2 2 d γ(δ) ln d than should be less than 2δ. , the probability of misclassification Based on Lemma 1 and Eq. (29), we formulate the re- lationship between the noise and model accuracy. Assume that we have a model F with accuracy accF . After adding random noise rZ on the last feature map Z, the model accu- racy drops ∆acc. If we assume that the accuracy degradation is caused by the noise rZ, we can see that the δ value in Eq. (29) is closely related to ∆acc: 2δ ∼ ∆acc accF ⇒γ(δ) ∼ γ( ∆acc 2accF ) (30) If we have: θ(∆acc) = d γ( ∆acc 2accF ) ln d (6 revisited) From Eq. (29), we have: 9 (za) - 202)? <5~ ace 31 P(|lrz||5 < O(Aace) 5 )<20 acer GD Eq. (31) indicates that by limiting noise rz to be less than θ(∆acc) (z(1)−z(2))2 , we can approximately assume that model accuracy drops less than ∆acc. As γ(δ) is strictly decreasing, we can see that θ(∆acc) is strictly increasing w.r.t. ∆acc. So as the model has higher accuracy degrada- tion ∆acc, the noise limitation also increase. Based on Eq. (31), we have the relation between accuracy degradation and noise rZ as: acez — acc# < Nace > (za) _ 22)" (7 revisited) Ir2ll3 <0 Accc) PS Calculation of noise on convolutional layer Given a convolutional layer input A with size M × N × C, conv kernel K with size Mk × Nk × C × D, and stride size s, we have the output feature map Z with size (M/s) × (N/s) × D. Here M and N are the height and width of input, C is the number of channel of input. Mk and Nk are the height and width of conv kernel, D is the depth of output feature map. The analysis on fully connected layers will be similar to the analysis on convolutional layers. It can be considered as a special case of convolutional layers when M , N , Mk, and Nk are equal to 1. Based on the definition of convolutional operation, for a single value z ∈ Z, the value is calculated as: M,e Nz C Zp,q,d = y y y Amy +p-s,nz-tq-s,c* Wmy,nz,c,d + ba mr=lng=1 c=1 My? = Ss aj Wia + ba i=l (32) where w is the weight, and b is the bias. p ∈ {1, ..., M/s} and q ∈ {1, ..., N/s}. As we consider noise on both input feature maps and weights, the Eq. (32) will become: My-Nu-C 2p,qd = ( y aj: Wid + ba) i=l My-Nu-C +( SO Gir twga tha: Wid + 0a; *Twia) +74) i=l (33) Then the noise term of zp,q,d can be expressed as: My-Ny-C Vipqd = y (Gi Twig + Ta; * Wid + 1a; *Twia) +7 i=1 My-Ny-C ~ (Qi * Tw; + Ta; * Wid) i=1 (17 revisited) (33) Note that the term rp, can be ignored under the assump- tion that w and b have same bit-width quantization. The term Tq; * Tw;,, can be ignored under the assumption that IIrall2 < lalla and ||rw|l2< |lwl2. # Additivity of ||rz||3 rw, quantized rx, Tz, input conv 1 intermediate conv 2 output feature map pe feature map ReLU + feature map a x Pooling z Pooling (a) (b) (c) Tw, quantized Yz, input conv 1 intermediate conv 2 output feature map ReLU feature map feature map A Pooling x sbi z Pooling rw, Tw, quantized rx, quantized rz, input conv intermediate cony 2 output feature m feature may feat we map RelU ature map ReLU feature map Pooling Pooling Figure 2: Effect of adding noise to multiple layers. Fig. 2 shows a 2-layer module inside a DNN model. Given input feature map A, after the first conv layer, an intermedi- ate feature map X is generated, then after the second conv layer, output feature map Z is generated. In Fig. 2(a), the weight of the first conv layer W1 is quan- tized, result in the quantization noise rW1 on weight W1, then the noise passes to feature map X with noise rX1 , and feature map Z with rZ1. In Fig. 2(b), the weight of the second conv layer W2 is quantized, result in the quantization noise rW2 on weight W2, then the noise passes to feature map Z with rZ2. In Fig. 2(c), we quantize the weight of both layer W1 and W2, with quantization noise rW1 and rW2, the noise passes to Z with noise rZ3 . Based on the discussion in previous section, rZ3 ≈ rZ1 + rZ2 . Given a particular z ∈ Z, we have z = (z1, · · · , zL), where z ∈ RL. Then rz1 = (rz1,1, · · · , rz1,L), rz2 = (rz2,1, · · · , rz2,L), and rz3 ≈ (rz1,1 + rz2,1, · · · , rz1,L + rz2,L). ||rz3||2 2 can be cal- culated as: L | Pz 113 = Ss ra 1 (Tayi + T2n,i)” 2 Ms i=l L 9 L 9 L (18 revisited) = Ss raat Ss Toi t 2° Ss Pai Vaayi i=l i=l i=l L = |fresl3 + [tao + 2° SO tera Pen. i=l = |Ir2, II3 + [Ize I3 The last equality holds under the assumption that rz1 and rz2 are independent. Which is reasonable in our case, as rz1 and rz2 are caused by rW1 and rW2 which are two indepen- dent quantization noise. # Layer-wise bit-width optimization Solving the optimization problem Consider the optimization problem: (21 revisited) # s.t. The form can be written as a dual problem: (34) Ss sib; =C" i=l We convert this to Lagrange function: N Tabs ASO si - bi (35) i=l Using KKT conditions, we have that the optimal value can be reached when: p1 · e−α·b1 t1 · s1 = p2 · e−α·b2 t2 · s2 = · · · = pN · e−α·bN tN · sN (22 revisited) Algorithm to calculate optimal bit-width The algorithms to calculate ti, pi, and bi Alg. 1, 2, and 3, respectively. is shown # in Algorithm 1 Calculate t; 1: procedure CAL_T Input: Dataset D; label £; accuracy degradation Agee; model F; model before softmax: G; weights W; € W in layer 7; 1 (2a)-2@))*. meany» — [Dy xed Oe, acez Fens. Output: tj,i = {1,--- ,N} 2 for layer i = 1 > Ndo 3 ry, =U(-0.5, 0.5) 4 k = kmin = 10~°, kmax = 10° 5: while acc¢ — accz # Agec do 6: if accz — acc# < Agee then kmin < k 7: elsekinax << k 8 k = Viimin max 9 rw, —k-ty, 10: acep, — PPM ew Jae 11: rz, = G(x, Wi) — G(x, Wi + rw,) t : 12: = py Uxe |IFall3 ~~ “meany« return ¢;,7 = (1, +N} Algorithm 2 Calculate p; 1: procedure CAL_P Input: Dataset D; a = In(4); model before softmax: G; weights W; € W in layer 7; quantization bit-width b; for layer i. Output: piri = {1,---,N} 2 for layer i = 1 > Ndo 3: Wig = quantize(W;, b;) 4: rz, = G(x, Wi) — G(x, Wig) 5: Meany, = PT Vxep en 3 6 meaner, Di = a return p;,i = {1,--- ,N} Algorithm 3 Calculate bi 1: procedure CAL B Input: Parameter ti, pi, i = {1, · · · , N }; α = ln(4); size si of layer i; quantization bit-width b1 for layer 1. Output: bi, i = {2, · · · , N } for layer i = 2 → N do 2: 3: α · ln( pi·t1·s1 p1·ti·si return bi, i = {2, · · · , N } bi = b1 + 1 ) Comparison with SQNR-based approach From our work, the optimal quantization bit-width for each layer is reached when Eq. (22) is fulfilled. From the paper we have that ||rZi||2 2 = pi · e−α·bi is the noise norm on last feature map Z when we apply bi-bit quan- tization on layer i, si is the size of layer i, and ti is the ro- bustness parameter for layer i. Now we focus on the optimization result for SQNR- based method (Lin, Talathi, and Annapureddy 2016). For the SQNR-based method, the optimal quantization bit-width is achieved when βi − βj = 10log(ρj/ρi) κ , (36) where βi is the bit-width for layer i, ρi is the number of parameter in layer i. κ is the quantization efficiency, which corresponds to the α parameter in our work. If we rewrite Eq. (36) using our notation, the optimization result for SQNR-based method becomes b, — 0, = Mlaatss/s) Qe I / a a Sj => —b; — —b; = log( 19% ~ 9?) = log) emi ig. (37) efi ~ en fab en 908s => = Sj 8; Let a = a’/10, we have the optimization result for SQNR-based method as e−α·b1 s1 = e−α·b2 s2 = · · · = e−α·bN sN (23 revisited) Note that compared with our result in Eq. (22), the pa- rameters pi and ti are missing. This is consistent with the assumption of the SQNR-based approach, that if two layers have the same bit-width for quantization, they would have the same SQNR value, thus the affection on accuracy are equal. This makes the SQNR-based approach a special case of our approach, when all layers in the DNN model have the equal affection on model accuracy under the same bit-width. Experimental results Fig. 8 shows the quantization results using our method, compared to equal quantization. For Alexnet and VGG-16 model, our method achieves 40% less model size with same accuracy degradation, while for GoogleNet and Resnet-50, our method achieves 15 − 20% less model size with same accuracy degradation. These results indicates that our pro- posed quantization method works better for models with more diverse layer-wise size and structures, like Alexnet and VGG. Figure 7: Histogram of ||r∗||2 validation set. 2 value for Alexnet on Imagenet Quantization on Alexnet o @ Equal bitwidth -*- our method ° = Top-1 error rate (%) ° a 200 300 400 500 600 Model size (Mbits) (a) Quantization on VGG-16 ° = + Equal bitwidth -*- our method = cy Top-1 error rate (%) ° a 0.4 0.3 400 600 800 1000 Model size (Mbits) (b) OO Quantization on GoogleNet . { Equal bitwidth So7 our method 2 £06 i O05 3 ce 0.4 0.3 20 30 40 50 Model size (Mbits) (c) OG Quantization on Resnet-50 Equal bitwidth -*- our method Top-1 error rate (%) 100 120 140 160 180 200 Model size (Mbits) (d) Figure 8: Model size after quantization, v.s. model accuracy. All layers are quantized.
Title: Demonstrate-Search-Predict: Composing retrieval and language models for knowledge-intensive NLP: Summary: Retrieval-augmented in-context learning has emerged as a powerful approach for addressing knowledge-intensive tasks using frozen language models (LM) and retrieval models (RM). Existing work has combined these in simple "retrieve-then-read" pipelines in which the RM retrieves passages that are inserted into the LM prompt. To begin to fully realize the potential of frozen LMs and RMs, we propose Demonstrate-Search-Predict (DSP), a framework that relies on passing natural language texts in sophisticated pipelines between an LM and an RM. DSP can express high-level programs that bootstrap pipeline-aware demonstrations, search for relevant passages, and generate grounded predictions, systematically breaking down problems into small transformations that the LM and RM can handle more reliably. We have written novel DSP programs for answering questions in open-domain, multi-hop, and conversational settings, establishing in early evaluations new state-of-the-art in-context learning results and delivering 37-120%, 8-39%, and 80-290% relative gains against the vanilla LM (GPT-3.5), a standard retrieve-then-read pipeline, and a contemporaneous self-ask pipeline, respectively. We release DSP at https://github.com/stanfordnlp/dsp # DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models for knowledge-intensive NLP Omar Khattab 1 Keshav Santhanam 1 Xiang Lisa Li 1 David Hall 1 Percy Liang 1 Christopher Potts 1 Matei Zaharia 1 # Abstract learning has Retrieval-augmented in-context emerged as a powerful approach for addressing knowledge-intensive tasks using frozen language models (LM) and retrieval models (RM). Exist- ing work has combined these in simple “retrieve- then-read” pipelines in which the RM retrieves passages that are inserted into the LM prompt. To begin to fully realize the potential of frozen LMs and RMs, we propose DEMONSTRATE– SEARCH–PREDICT (DSP), a framework that re- lies on passing natural language texts in sophisti- cated pipelines between an LM and an RM. DSP can express high-level programs that bootstrap pipeline-aware demonstrations, search for rele- vant passages, and generate grounded predictions, systematically breaking down problems into small transformations that the LM and RM can handle more reliably. We have written novel DSP pro- grams for answering questions in open-domain, multi-hop, and conversational settings, establish- ing in early evaluations new state-of-the-art in- context learning results and delivering 37–120%, 8–39%, and 80–290% relative gains against the vanilla LM (GPT-3.5), a standard retrieve-then- read pipeline, and a contemporaneous self-ask pipeline, respectively. We release DSP at https: //github.com/stanfordnlp/dsp. ( How many storeys are in the castle David Gregory inherited? } X Hallucinates VanillaLM LW: Castle Gregory has three storeys. sha a fictitious castle Retrieve- RM: “St. Gregory Hotel is a nine-floor boutique hotel in D.C. then-Read & Retrieves a : St. Gregory nine ; 4 ne Liv: St, Gregory Hotel has nine storeys ee building LM: ‘Which castle did David Gregory inherit? | RM: ‘David Gregory inherited Kinnairdy Castle in 1664 Vv Multi-Hop Lm: “How many storyes does Kinnairdy Castle have? DSP Program — RM: “Kinnairdy Castie is a tower house, having five storeys. Liv: Kinnairdy Castle has five storeys. Figure 1. A comparison between three systems based on GPT- 3.5 (text-davinci-002). On its own, the LM often makes false assertions. An increasingly popular retrieve-then-read pipeline fails when simple search can’t find an answer. In contrast, a task- aware DSP program successfully decomposes the problem and produces a correct response. Texts edited for presentation. with relevant information from a large corpus (Lazaridou et al., 2022; Press et al., 2022; Khot et al., 2022). Recent work has shown such retrieval-augmented in-context learning to be effective in simple “retrieve-then-read” pipelines: a query is fed to the RM and the retrieved pas- sages become part of a prompt that provides context for the LM to use in its response. In this work, we argue that the fact that both LMs and RMs consume (and generate or retrieve) natural language texts creates an opportunity for much more sophisticated interactions between them. Fully realizing this would be transformative: frozen LMs and RMs could serve as infrastructure across tasks, enabling ML- and domain-experts alike to rapidly build grounded AI systems at a high level of abstraction and with lower deployment overheads and annotation costs. # 1. Introduction In-context learning adapts a frozen language model (LM) to tasks by conditioning the LM on a textual prompt including task instructions and a few demonstrating examples (Mc- Cann et al., 2018; Radford et al., 2019; Brown et al., 2020). For knowledge-intensive tasks such as question answering, fact checking, and information-seeking dialogue, retrieval models (RM) are increasingly used to augment prompts 1Stanford University. Correspondence to: Omar Khattab <okhattab@cs.stanford.edu>. Figure 1 begins to illustrate the power of retrieval- augmented in-context learning, but also the limitations of “retrieve-then-read” (Lazaridou et al., 2022; Izacard et al., 2022). Our query is “How many storeys are in the castle David Gregory inherited?” When prompted to answer this, GPT-3.5 (text-davinci-002; Ouyang et al. 2022) makes up a fictitious castle with incorrect attributes, highlighting the common observation that knowledge stored in LM pa- rameters is often unreliable (Shuster et al., 2021; Ishii et al., 2022). Introducing an RM component helps, as the LM can ground its responses in retrieved passages, but a rigid Preprint. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models “How many storeys are in the castle David Gregory inherited?” ¥ @ How many storeys are in... @ How many storeys are in the castle... @ ie a _ How many storeys are in the... Hop1 hich castle did David Gregory inherit? Psgl David Gregory inherited Kinnairdy Castle... Hop2 How many storeys are in Kinnairdy Castle? Psg2__Kinnairdy Castle [..] having five storeys... 3 Predict @ How many storeys does the... P| F if ° 2s | + x : Example } 1 Demonstrate H det rate (x: Example) => Exam i 2 Search x. = annotate (x.train, m 1 « J (oc: Example) => generate (h pt (a: Example) + retrieve (x 4 (a) generat d = predict (a) if d.pred == d.answer: return d »_ template) (x) .pred retrieve(x.hop2, k=1) [0] Pred Five storeys | + “Five storeys” Figure 2. A toy example of a DSP program for multi-hop question answering. Given an input question and a 2-shot training set, the DEMONSTRATE stage programmatically annotates intermediate transformations on the training examples using a form of weak supervision. Learning from a resulting demonstration, the SEARCH stage decomposes the complex input question and retrieves supporting information over two retrieval hops. Finally, the PREDICT stage uses the demonstration and retrieved passages to answer the question. retrieve-then-read strategy fails because the RM cannot find passages that directly answer the question. We introduce the DEMONSTRATE–SEARCH–PREDICT (DSP) framework for in-context learning, which relies en- tirely on passing natural language text (and scores) be- tween a frozen RM and LM. DSP introduces a num- ber of composable functions that bootstrap training exam- ples (DEMONSTRATE), gather information from a knowl- edge corpus (SEARCH), and generate grounded outputs (PREDICT), using them to systematically unify techniques from the retrieval-augmented NLP and the in-context learn- ing literatures (Lee et al., 2019; Khattab et al., 2021a; Anan- tha et al., 2020; Gao et al., 2022; Izacard et al., 2022; Dohan et al., 2022; Zelikman et al., 2022; Zhang et al., 2022). We use DSP to suggest powerful strategies for knowledge- intensive tasks with compositions of these techniques. This reveals new conceptual possibilities for in-context learning in general (§2), and it allows us to present rich programs that set new state-of-the-art results (§3). stage uses labeled question–answer pairs to implement a form of weak supervision that programmatically annotates the transformations invoked within SEARCH and PREDICT. We evaluate several DSP programs on answering questions in open-domain, multi-hop, and conversational settings. In them, we implement novel and reusable transformations such as bootstrapping annotations for all of our pipelines with weak supervision (§2.3), reliably rewriting questions to resolve conversational dependencies and iteratively decom- pose complex queries with summarization of intermediate hops (§2.4), and generating grounded responses from mul- tiple passages with self-consistency (§2.5). We report pre- liminary results on Open-SQuAD, HotPotQA, and QReCC using the frozen LM GPT-3.5 and RM ColBERTv2 (Khat- tab & Zaharia, 2020; Santhanam et al., 2022b) with no fine-tuning. Our DSP programs deliver 37–120%, 8–39%, and 80–290% relative gains against corresponding vanilla LMs, a standard retrieve-then-read pipeline, and a contem- poraneous self-ask pipeline (Press et al., 2022), respectively. Future versions of this report will include additional test tasks and LM choices. Figure 1 shows the path that a DSP program might take to arrive at an answer, and Figure 2 illustrates how a deliberate program achieves this. Instead of asking the LM to answer this complex question, the program’s SEARCH stage uses the LM to generate a query “Which castle did David Gregory inherit?” The RM retrieves a passage saying Gregory inher- ited the Kinnairdy Castle. After a second search “hop” finds the castle’s number of storeys, the PREDICT stage queries the LM with these passages to answer the original question. Although this program implements behaviors such as query generation, it requires no hand-labeled examples of these intermediate transformations (i.e., of the queries and pas- sages of both retrieval hops). Instead, the DEMONSTRATE In summary, this work makes the following contributions. First, we argue that simple task-agnostic pipelines for in- context learning should give way to deliberate, task-aware strategies. Second, we show that this shift need not be a burden: with DSP, such strategies can be easily expressed as short programs using composable operators. Third, this composability spawns powerful capacities, like automati- cally annotating demonstrations for complex pipelines from end-task labels. Fourth, for three knowledge-intensive tasks, we implement rich programs that establish state-of-the-art results for in-context learning. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models # 2. DEMONSTRATE–SEARCH–PREDICT # 2.2. Datatypes and Control Flow We now introduce the DSP framework and show its expres- sive power by suggesting a number of strategies in which the LM and RM can come together to tackle complex prob- lems effectively. We show in §3 that such strategies out- perform existing in-context learning methods. We begin by discussing the LM and RM foundation modules on which DSP is built (§2.1) and then the datatypes and control flow within DSP (§2.2). Subsequently, we discuss each of the three inference stages: DEMONSTRATE (§2.3), SEARCH (§2.4), and PREDICT (§2.5). # 2.1. Pretrained Modules: LM and RM We have implemented the DSP framework in Python. The present section introduces the core data types and compos- able functions provided by the framework. We use illustra- tive code snippets to ground the examples, and to convey the power that comes from being able to express complex interactions between the LM and RM in simple programs. The Example Datatype To conduct a task, a DSP pro- gram manipulates one or more instances of the Example datatype. An Example behaves like a Python dictionary with multiple fields. The program is typically provided with a few training examples. The code snippet below illustrates this for multi-hop question answering. A DSP program defines the communication between the language model LM and the retrieval model RM. Language Model We invoke a frozen language model LM to conditionally generate (or score) text. For each invocation, the program prepares a prompt that adapts the LM to a specific function (e.g., answering questions or generating queries). A prompt often includes instructions, a few demonstrations of the desired behavior, and an input query to be answered. As in Figure 2, the LM generates not only: (i) the final answer to the input question (in the PREDICT stage), but also (ii) intermediate “hop” queries to find useful information for the input question (SEARCH) as well as (iii) exemplar queries that illustrate how to produce queries for questions in the training set (DEMONSTRATE). This systematic use of the LM is a hallmark of DSP programs. Retrieval Model DSP programs also invoke a frozen re- trieval model RM to retrieve the top-k most “relevant” text sequences for a given query. The RM can index a massive set of pre-defined passages for scalable search, and those passages can be updated without changing the retrieval parameters. The RM accepts free-form textual inputs and specializes in estimating the relevance (or similarity) of a text sequence to a query. 1 from dsp import Example 2 3 train = [ Example ( question =" When was the discoverer of Palomar 4 born ? " , answer =" 1889 ") , 4 Example ( question =" In which city did Akeem Ellis play in 2017? " , answer = " Ellesmere Port ") ] This snippet contains two labeled examples, each with a multi-hop question (e.g., “In which city did Akeem Ellis play in 2017?”) and its short answer (“Ellesmere Port”). Arbitrary keys and values are allowed within an Example, though typical values are strings or lists of strings. In this task, we are unlikely to find an individual passage that provides the answer to any question. For example, the first training example can probably be resolved only by first answering the question of who discovered Palomar (“Edwin Hubble”) and then addressing the question of Hubble’s birth date using different evidence passages. We typically assume that the human-labeled training data do not include labels for intermediate transformations (e.g., queries for individual hops) that would be useful for following these steps, and so it is the job of the DSP program to discover these strategies via in-context learning. A DSP Program The following code snippet is a com- plete program for resolving multi-hop questions like those in Figure 1, with help from train examples like those above. As in Figure 2, the RM is responsible for retrieving (i) passages for each query generated by the LM (during the SEARCH stage), but also (ii) passages that are used within demonstrations (DEMONSTRATE). In the latter case, the RM’s contributions are less about providing directly rel- evant information to the input question and more about helping the LM adapt to the domain and task. 1 def multihop_program ( question : str ) -> str : 2 3 4 5 6 7 8 multihop_program (" How many storeys does the castle x = Example ( question = question , train = train ) x = multihop_demonstrate (x) x = multihop_search ( x) x = multihop_predict (x ) return x. answer David Gregory inherited have ?" ) 9 # => " five storeys " Though not utilized in this example, the RM is also used in DSP for functions like retrieving “nearest-neighbor” demon- strations from task training data (DEMONSTRATE) and se- lecting well-grounded generated sequences from the LM (PREDICT). The program takes the input (here, a question) and outputs the system output (its short answer). It starts by creating an Example for the input question and assigning the train field to the training set from the previous snippet. Programs DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models invoke and compose DSP primitives (i.e., built-in functions) to build the DEMONSTRATE, SEARCH, and PREDICT trans- formations that define the program. Transformations A transformation is a function that takes an Example as input and returns an Example, pop- ulating new fields (or modifying existing fields) in it. This program invokes three developer-defined transformations, namely, multihop_demonstrate, multihop_search, and multihop_predict. Transformations may themselves in- voke other transformations, and they act analogously to layers in standard deep neural network (DNN) program- ming frameworks such as PyTorch, except that they pass text data instead of tensors between each other and do not involve backpropagation. of training examples. Whenever fn returns an example (rather than None), annotate caches the intermediate pre- dictions (i.e., the generated queries and retrieved passages). These predictions serve as successful demonstrations for the pipeline transformations. In simple uses, fn may attempt to answer the example “zero-shot” one or more times. This is typically done by invoking the SEARCH and PREDICT stages of the program. When an answer is produced, if fn assesses it as correct, it returns a populated example in which the intermediate predictions are present. Case Study The snippet below defines the func- tion multihop_demonstrate, called in Line 3 of multihop_program, and illustrates the usage of annotate. We categorize transformations according to their behavior (or purpose) under one of the DEMONSTRATE, SEARCH, and PREDICT stages. That said, DSP does not impose this categorization and allows us to define functions that may blend these stages. We will discuss each of the three stages next. 1 from dsp import sample , annotate 2 3 def attempt_example (d: Example ): 4 5 6 7 8 9 def multihop_demonstrate (x: Example ): 10 11 d = d. copy ( demos =[]) d = multihop_search ( d) d = multihop_predict (d ) return d if d. pred == d. answer else None demos = annotate (x. train , attempt_example ) return Example (x , demos = demos ) # 2.3. DEMONSTRATE It is known that including examples of the desired behavior from the LM in its prompt typically leads to better perfor- mance (Brown et al., 2020). In DSP, a demonstration is a training example that has been prepared to illustrate specific desired behaviors from the LM. A DEMONSTRATE transfor- mation takes as input x of type Example and prepares a list of demonstrations in x.demos, typically by selecting a sub- set of the training examples in x.train and bootstrapping new fields in them. In Line 10, multihop_demonstrate invokes annotate, which bootstraps missing fields in training examples by caching annotations from attempt_example. The transfor- mation attempt_example takes a training example d and attempts to answer it in a zero-shot fashion: it creates a copy of d with no demonstrations (Line 4; i.e., zero-shot) and invokes the multi-hop search and predict pipeline (Lines 5 and 6). Each transformation returns an updated version of d with additional fields populated. If the pipeline answers correctly (Line 7), the updated d is returned. Bootstrapping Demonstrations Examples in the train- ing set typically consist of the input text and the target output of the task. The DEMONSTRATE stage can aug- ment a training example by programmatically bootstrapping annotations for intermediate transformations. In our run- ning “multi-hop” example, the demonstrations illustrate three LM-based transformations: (i) how to break down the input question in order to gather information for answer- ing it (i.e., first-hop retrieval), (ii) how to use information gathered in an earlier “hop” to ask follow-up questions, and (iii) how to use the information gathered to answer complex questions. 1 Examples = list [ Example ] 2 Transformation = Callable [[ Example ], 3 4 5 annotate ( train : Examples , fn : Transformation ) 6 Akin to a specialized map, the annotate primitive accepts a user-defined transformation fn and applies it over a list Figure 2 illustrates this behavior. DEMONSTRATE trans- forms a training question–answer pair to a fully-populated demonstration, including fields such as hop1 and hop2 (i.e., queries for multi-hop search) as well as psg1 and psg2. When the LM is later invoked to conduct a transformation, say, generating a “second-hop” query during SEARCH, the psg1 field serves as context and the hop2 field serves as a label for this particular training example. Discussion This simple case study illustrates the power of composition in the DSP abstraction. Because the pipeline is a well-defined program in which transformations com- municate by passing text attached to Examples, a simple map-and-filter strategy can leverage the LM and RM to bootstrap annotations for a full pipeline from end-task la- bels. This is an extensible strategy, but even in its simplest form it generalizes the approaches explored recently by Ze- likman et al. (2022), Wei et al. (2022), Zhang et al. (2022), and Huang et al. (2022) in which an LM self-generates chain-of-thought rationales for an individual prompt. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models By bootstrapping pipelines, DEMONSTRATE makes it easy to explore complex strategies in SEARCH and PREDICT without writing examples for every transformation. This includes strategies that are challenging to explore without custom annotations in traditional retrieval-augmented NLP. For instance, Khattab et al. (2021a) introduces a pipeline for multi-hop reasoning that is trained with weak supervi- sion, extending work by Lee et al. (2019) and Khattab et al. (2021b). In it, the target 3 or 4 passages that need to re- trieved must be labeled but the system discovers the best order of “hops” automatically. In contrast, DSP allows us to build complex pipelines with- out labels for intermediate steps, because we can compose programs out of small transformations. If LM and RM can accurately process such transformations “zero-shot” (i.e., without demonstrations) on at least one or two examples, these examples can be discovered with end-task labels and used as demonstrations. would select n subsets of k = 5 examples each, and return the set with which a transformation evaluate performs best on the remaining 95 examples. Compositions & Extensions By manipulating demon- strations and higher-order transformations, these simple selection and bootstrapping primitives can be combined to conduct larger novel strategies. If the training set is very large (e.g., |train| = 100, 000), we can conduct knn to find the nearest k = 16 examples and only annotate these, arriving at a system that learns incrementally in real-time. If the training set is moderately large (e.g., |train| = 1000), we can conduct crossval and cache the performance of all prompts it evaluates on each training example. At test time, we can use knn to find k = 50 similar examples to the test input and select the prompt that performs best on these k examples, producing an adaptive system that is informed by the quality of its pipeline on different types of examples. To draw on our earlier analogy with DNN frameworks like PyTorch, DEMONSTRATE aims to replace the function of backpropagation in extensible ways by simulating the be- havior of the program (corresponding to a “forward” pass) and programmatically learning from errors. In doing this with frozen models and with only end-task labels, DEMON- STRATE introduces a high degree of modularity. In partic- ular, without hand-labeling intermediate transformations, developers may swap the training domain, update the train- ing examples, or modify the program’s strategy, and use annotate to automatically populate all of the intermediate fields for demonstrations. Selecting Demonstrations It is not always possible to fit all of the training examples in the context window of the LM. DSP provides three primitives for selecting a subset of training examples, namely, sample, knn, and crossval. # 2.4. SEARCH The SEARCH stage gathers passages to support transforma- tions conducted by the LM. We assume a large knowledge corpus—e.g., a snippet of Web, Wikipedia, or arXiv—that is divided into text passages. Providing passages to the LM facilitates factual responses, enables updating the knowl- edge store without retraining, and presents a transparency contract: when in doubt, users can check whether the system has faithfully used a reliable source in making a prediction. In the simplest scenarios, SEARCH can directly query the RM, requesting the top-k passages (from a pre-defined in- dex) that match an input question. This baseline instantia- tion of SEARCH simulates retrieval in most open-domain question answering systems, which implement a “retrieve- then-read” pipeline, like Lee et al. (2019), Khattab et al. (2021b), Lazaridou et al. (2022), and many others. 1 sample ( train : Examples , k: int ) 2 3 4 knn ( train : Examples , cast : Callable [[ Example ], str ]) -> fn ( example : Example , k: int ) # currying 5 -> Examples 6 7 8 crossval ( train : Examples , n: int , k: int ) -> fn ( evaluate : Transformation ) 9 -> Examples 10 As a baseline choice, k demonstrations can be randomly sampled from train using the sample primitive, an ap- proach used by Brown et al. (2020) and much subsequent work. We can also leverage the RM’s representations and se- lect from the training set the k nearest neighbors to the input text, a strategy explored by Liu et al. (2021). Another strat- egy is to apply cross-validation to select among a number of sampled sets of demonstrations (Perez et al., 2021). For ex- ample, given |train| = 100 training examples, crossval 1 from dsp import retrieve 2 3 def simple_search (x): 4 5 passages = retrieve ( query =x. question , k =2) return passages SEARCH Strategies In many scenarios, the complexity of the task demands more sophisticated SEARCH strategies that empower the RM to find relevant passages. Our run- ning example (Figure 2) is one such scenario, in which we suspect examples are likely to require multi-hop reasoning in particular. Other settings, for instance, pose conversa- tional challenges, in which the information need expressed by a user can only be resolved by taking into account pre- vious turns in the conversation, or demand more extensive planning (Zhong et al., 2022). In the retrieval-augmented NLP literature, multi-hop search (Xiong et al., 2020; Khattab et al., 2021a) and con- DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models versational search (Del Tredici et al., 2021; Raposo et al., 2022) pipelines have received much attention. These sys- tems are typically fine-tuned with many hand-labeled query “rewrites” (Anantha et al., 2020), “decompositions” (Geva et al., 2021; Min et al., 2019), or target hops (Yang et al., 2018; Jiang et al., 2020). Supported with automatic anno- tations from DEMONSTRATE, the SEARCH stage allows us to simulate many such strategies and many others in terms of passing queries, passages, and demonstrations between the RM and LM. More importantly, SEARCH facilitates our vision of advanced strategies in which the LM and RM co- operate to incrementally plan a research path for which the RM gathers information and the LM identifies next steps. As shown, the LM is instructed to read the context re- trieved in earlier hops and a complex question. It is then prompted to write: (i) a summary of the supplied con- text and (ii) a search query that gathers information for answering that question. The generated text will be ex- tracted and assigned to the summary and query variables in (multihop_search_v2; Line 7). On Line 10, we terminate the hops if the query is “N/A”. Otherwise, Line 12 retrieves k = 5 passages using the query and Line 13 assigns the context for the subsequent hop (or for PREDICT), setting that to include the summary of all previous hops as well as the passages retrieved in the final hop so far. Case Study Let us build on our running multi-hop exam- ple as a case study. We can define multihop_search_v2 (Line 4 in our core program), a slightly more advanced ver- sion of the SEARCH transformation from Figure 2. This transformation simulates the iterative retrieval component of fine-tuned retrieval-augmented systems like IRRR (Qi et al., 2020), which reads a retrieved passage in every hop and generates a search query (or a termination condition to stop hopping), and Baleen (Khattab et al., 2021a), which summarizes the information from many passages in each hop for inclusion in subsequent hops. 1 from dsp import generate 2 3 def multihop_search_v2 (x , max_hops =3) : 4 5 6 7 8 9 10 11 12 13 14 15 x. hops = [] for hop in range ( max_hops ): summary , query = generate ( hop_template )(x) x. hops . append (( summary , query )) if query == 'N/A ': break passages = retrieve ( query , k =5) x. context = [ summary ] + passages return x Comparison with self-ask It may be instructive to con- trast this multi-hop DSP program with the recent “self- ask” (Press et al., 2022) prompting technique, which we compare against in §3. Self-ask can be thought of as a sim- ple instantiation of DSP’s SEARCH stage. In it, the LM asks one or more “follow-up questions”, which are intercepted and sent to a search engine. The search engine’s answers are concatenated into the prompt and are used to answer the question. This is essentially a simplified simulation of IRRR (Qi et al., 2020). As a general framework, DSP can express ideas like self-ask and many other, more sophisticated pipelines as we discuss in the present section. More importantly, DSP offers a num- ber of intrinsic advantages that lead to large empirical gains: 80%–290% over self-ask. For instance, DSP programs are deeply modular, which among other things means that DSP programs will annotate and construct their own demonstra- tions. Thus, they can be developed without labeling any of the intermediate transformations (e.g., the queries gener- ated). In addition, the LM prompts constructed by DSP get automatically updated to align with the training data and re- trieval corpus provided. In contrast, approaches like self-ask rely on a hand-written prompt with hard-coded examples. In multihop_search_v2, Line 7 calls the generate prim- itive, which invokes the LM to produce a query for each retrieval hop. The LM is conditioned on a prompt that is prepared using the hop_template template. (We discuss prompt templates and the generate primitive in §2.5.) Here, this template may be designed to generate a prompt that has the following format (e.g., for the second hop). 1 My task is to write a simple query that gathers information for answering a complex question . I write N/A if the context contains all information required . 2 3 { Task demonstrations from x. demos , if any } 4 5 Context : {x. context } 6 Question : {x. question } 7 Summary : Let 's summarize the above context . __ { summary } __ 8 Search Query : __ { query } __ Moreover, DSP assigns the control flow to an explicit pro- gram and facilitates design patterns that invoke the LM (or RM) to conduct small transformations. This allows us to build steps that are dedicated to generating one or more re- trieval queries, summarizing multiple passages per hop, and answering questions. These steps are individually simpler than the self-ask prompt, yet our multi-hop DSP program deliberately composes them to build richer pipelines that are thus more reliable. In contrast, self-ask delegates the con- trol flow to the LM completions, maintaining state within the prompt itself and intercepting follow-up questions to conduct search. We find that this paradigm leads to a “self- distraction” problem (§3.5) that DSP programs avoid. Fusing Retrieval Results For improved recall and robust- ness, we can also fuse the retrieval across multiple gen- erated queries. Fusion has a long history in information DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models retrieval (Fox & Shaw, 1994; Xue & Croft, 2013; Kur- land & Culpepper, 2018) and sequentially processing multi- ple queries was explored recently by Gao et al. (2022) for retroactively attributing text generated by LMs to citations. Inspired by these, we include a fused_retrieval primitive to DSP to offer a versatile mechanism for interacting with frozen retrievers. It accepts an optional fusion function that maps multiple retrieval lists into one. By default, DSP uses a variant of CombSUM (Fox & Shaw, 1994), assigning each passage the sum of its probabilities across retrieval lists. 1 Template # template : an object that can produce prompts and parse completions 2 3 generate ( template : Template ) 4 5 -> fn ( example : Example ) -> Completions extracted preds and scores # object with keys to access 6 7 rank ( query : str , passages : List [ str ]) 8 -> List [ float ] passage texts and scores # object with keys to access To illustrate, the modification below generates n = 10 queries for the transformation multihop_search_v2. A Template is an object that can produce prompts, that is, map an Example to a string, and extract fields out of com- pletions. For instance, we can map an example x that has a question and retrieved passages to the following prompt: c = generate ( hop_template , n =10) (x) passages = fused_retrieval (c. queries , k =5) summary = c. summaries [0] # highest - scoring summary Compositions & Extensions To illustrate a simple com- position, we can equip a chatbot with the capacity for con- versational multi-hop search by combining a query rewriting step, which produces a query that encompasses all of the relevant conversational context, with the multi-hop transfor- mation, as follows. # 1 def conversational_multihop_search (x): 2 3 # x. question = generate ( conv_rewriting_template ) (x ) return multihop_search_v2 (x) 1 My task is to answer questions using Web documents . 2 3 { Task demonstrations from x. demos , if any } 4 5 Context : {x . passage } 6 Question : {x . question } 7 Rationale : Let 's think step by step . __ { rationale } __ 8 Answer : __ { answer } __ As this illustrates, the LM will be asked to generate a chain- of-thought rationale (CoT; Wei et al. 2022; Kojima et al. 2022) and an answer, and the generated text will be ex- tracted back into the rationale and answer keys of each completion. Similar approaches can be used for correcting spelling mis- takes or implementing pseudo-relevance feedback (Cao et al., 2008; Wang et al., 2022a), in which retrieved passages are used to inform a better search query, though this has not been attempted with pretrained LMs to our knowledge. Each invocation to the LM can sample multiple candidate predictions. Selecting a “best” prediction is the subject of much work on decoding (Wiher et al., 2022; Li et al., 2022), but a frozen and general-purpose LM may not support cus- tom modifications to decoding. Within these constraints, we present several high-level strategies for selecting predictions and aggregating information in DSP via the LM and RM. # 2.5. PREDICT The PREDICT stage generates the system output using demonstrations (e.g., in x.demos) and passages (e.g., in x.context). PREDICT tackles the challenges of reliably solving the downstream task, which integrates much of the work on in-context learning in general. Within DSP, it also has the more specialized function of systematically aggre- gating information across a large number of demonstrations, passages, and candidate predictions. Selecting Predictions Among multiple candidates, we can simply extract the most popular prediction. When a CoT is used to arrive at the answer, this is the self-consistency method of Wang et al. (2022c), which seeks to identify predictions at which multiple distinct rationales arrive. 1 from dsp import generate , majority 2 3 def multihop_predict (x): 4 5 candidates = generate ( template_qa ) (x ) return x. copy ( answer = majority ( candidates ). answer ) Generating Candidates Generally, PREDICT has to pro- duce one or more candidate predictions for the end-task. To this end, the basic primitive in PREDICT is generate, which accepts a Template and (via currying) an Example and queries the LM to produce one or more completions, as explored earlier in §2.4. A corresponding primitive that uses the RM in this stage is rank, which accepts a query and one or more passages and returns their relevance scores. DSP generalizes this in two ways. First, we can sample multiple “pipelines of transformations” (PoT) within the pro- gram, rather than locally with “chains of thought” (CoT) in one transformation. These chains may even invoke different paths in the program, as illustrated below. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models 1 from dsp import branch 2 3 def pipeline (x): 4 5 6 def PoT_program ( question : str ) -> str : 7 8 9 10 11 return multihop_predict ( multihop_search_v2 (x)) x = Example ( question = question , train = train ) x = multihop_demonstrate (x) candidates = branch ( pipeline , n =5 , t =0.7) (x) return x. copy ( answer = majority ( candidates ). answer ) To deal with a larger number of demonstrations or passages, we can branch in parallel to process individual subsets of the passages or demonstrations and then aggregate the individual answers using one of the scoring methods pre- sented earlier. Indeed, Lewis et al. (2020) and Lazaridou et al. (2022) have explored marginalization as a way to com- bine scores across passages and Le et al. (2022) ensemble prompts across demonstrations, which can be expressed in this way. In the snippet above, Line 10 invokes the primitive branch which samples n different PoTs with a high temperature (e.g., t = 0.7) and accumulates their intermediate and In this example, our pipeline invokes final predictions. multihop_search_v2 (§2.4), which applies a variable num- ber of retrieval hops depending on the questions generated, before doing PREDICT. That is, PoT_program potentially invokes multiple distinct paths in the program (i.e., with dif- ferent multi-hop queries and number of hops in each) across branches. It then selects the majority answer overall. An alternative aggregation strategy is to accumulate informa- tion across passages sequentially, rather than independently. This is effectively how our multi-hop approach works (§2.4). Such a strategy has also been employed recently by Gao et al. (2022) for retroactively attributing text generated by LMs to citations. They generate many queries but instead of fusion (§2.4), they run their pipeline on each query and use its outputs to alter the input to subsequent queries.1 # 3. Evaluation DSP generalizes self-consistency in a second way. When sampling our CoTs or PoTs provides multiple candidates, we can select the top-k (e.g., top-4) predictions and then compare them directly. For instance, we may prompt the LM to compare these choices as MCQ candidates, a trans- formation for which DEMONSTRATE can automatically pre- pare exemplars. This effectively simulates the LM recursion of Levine et al. (2022), though unlike their approach it does not require a large training set or updating any (prompt- tuning) weights. One such implementation is illustrated in openqa_predict below. 1 def openqa_predict (x): 2 3 4 5 6 7 8 9 10 preds = generate ( template_qa , n =20) (x). answers x. choices = most_common ( preds , k =4) queries = [f"{x. question } {c}" for c in x. choices ] x. passages = fused_retrieval ( queries ) x. answer = generate ( TemplateMCQ )(x). answer return x As an alternative comparison approach, we can invoke the RM via rank to find the prediction that is most grounded in a retrieved contexts (i.e., most similar to the concatenation of the retrieved passages) or, given an RM that can score completions (Krishna et al., 2022), simply the prediction that has the highest score given the prompt. We now consider how to implement DSP programs for three diverse knowledge-intensive NLP tasks: open-domain ques- tion answering (QA), multi-hop QA, and conversational QA. All of these tasks are “open-domain”, in the sense that sys- tems are given a short question or participate in a multi-turn conversation without being granted access to context that answers these questions. We build and evaluate intuitive compositions of the func- tions explored in §2 for each task. We show that, despite low development effort, the resulting DSP programs exhibit strong quality and deliver considerable empirical gains over vanilla in-context learning and a standard retrieve-then-read pipeline with in-context learning. # 3.1. Evaluation Methodology In this report, we consider one development dataset for each of the tasks we consider, namely, the open-domain version of SQuAD (Rajpurkar et al., 2016; Lee et al., 2019), the multi-hop HotPotQA (Yang et al., 2018) dataset in the open- domain “fullwiki” setting, and the conversational question answering QReCC (Anantha et al., 2020; Vakulenko et al., 2022) dataset, which we used for developing the DSP ab- stractions. We report the validation set accuracy on all three datasets and discuss them in detail §3.5. Aggregating Information When only a few demonstra- tions or passages are selected, we can simply concate- nate them all into the prompt. For instance, GPT-3.5 text-davinci-002 has a context window of 4097 tokens, which we find to be reasonably large for accommodating several (e.g., 3–5) demonstrations, which individually in- clude their own passages and rationales. Unless otherwise stated, systems are given access to 16- shot training examples, that is, each DSP program can use (up to) 16 questions—or conversations, where applicable— randomly sampled from the respective training set. We 1Though most of the functionality in this section is imple- mented, the primitives branch, knn, and crossval are currently work-in-progress. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models subsample the validation and test sets to 1000 questions (or 400 conversations, where applicable) and report average quality across five seeds where each seed fixes a single k- shot training set of examples. To control the language model API spending budget, each seed processes one fifth of the evaluation examples (e.g., 200 questions per seed, for a total of 1000 unique questions). test datasets (e.g., Open- We also dedicate held-out NaturalQuestions; Kwiatkowski et al. 2019) and test tasks (e.g., claim verification, as in FEVER; Thorne et al. 2018) that we only use for evaluating pre-defined DSP programs rather than development. We will include these results in a future version of this report. # 3.2. Pretrained Modules Retrieve-then-Read The “retrieve-then-read” baselines use the RM to support each example with a potentially rele- vant passage before submitting the prompt to the LM. This emulates the pipelines used by state-of-the-art open-domain question answering systems (Khattab et al., 2021b; Izacard & Grave, 2020; Hofstätter et al., 2022). In conversational QA, we concatenate the first turn and the final question, an approach that we found to perform much better than simply using the final turn. For multi-hop QA, we retrieve and concatenate two passages per question. 1 def retrieve_then_read_QA ( question : str ) -> str : 2 3 4 5 6 7 RM We use ColBERTv2 (Santhanam et al., 2022b), a state-of-the-art retriever based on late interaction (Khattab & Zaharia, 2020). We choose ColBERTv2 for its highly effective zero-shot search quality and efficient search (San- thanam et al., 2022a). However, our DSP programs are agnostic to how the retriever represents examples or scores passages, so essentially any retriever can be used. In addition, by making retrieval a first-class construct, DSP allows us to change or update the search index over time. We simulate this in our experiments by aligning each of our datasets with the nearest Wikipedia corpus among the Dec 2016 Wikipedia dump from Chen et al. 2017, the Nov 2017 Wikipedia “abstracts” dump from Yang et al. 2018, and the Dec 2018 Wikipedia dump from Karpukhin et al. 2020. Self-ask We also compare against self-ask (Press et al., 2022), a contemporaneous pipeline that can be thought of as a specific instantiation of DSP’s SEARCH stage followed by a simple PREDICT step. For direct comparison with our methods, we modify the self-ask control flow to query the same ColBERTv2 index used in our DSP experiments instead of Google Search. We evaluate two configurations of self-ask. The first uses the original self-ask prompt template, which contains four hand-written demonstrations. In the second configuration, we modify the prompt template to apply a number of changes that we find are empirically useful for HotPotQA.2 # 3.4. Proposed DSP Programs LM We use the GPT-3.5 (text-davinci-002; Brown et al. 2020; Ouyang et al. 2022) language model. Unless otherwise stated, we use greedy decoding when generating n = 1 prediction. We sample with temperature t = 0.7 when n > 1, like related work (Wang et al., 2022c). We build on transformations presented in §2. Our programs for all three tasks have the following structure, illustrated for open-domain QA. # 3.3. Baselines Vanilla LM The vanilla LM baselines represent the few- shot in-context learning paradigm used by Brown et al. (2020). The open-domain QA and multi-hop QA base- lines randomly sample 16 demonstrations (i.e., all of the examples available to each program in our evaluation) from the training set and do not augment these demonstrations with evidence. Similarly, the conversational QA baseline samples four conversations. The vanilla baselines do not search for passages relevant to the input query. 1 def vanilla_LM_QA ( question : str ) -> str : 2 3 4 demos = sample ( train , k =16) x = Example ( question = question , demos = demos ) return generate ( qa_template )(x). pred 1 def openqa_program ( question : str ) -> str : 2 3 4 5 6 The exception is that the conversational QA program, 2In particular: (i) use ColBERTv2-style passages in the hand- crafted demonstrations of self-ask (i.e., instead of the original Google-style snippets), (ii) concatenate 16-shot training examples from the task (i.e., question–answer pairs) as a prefix of the prompt, (iii) ask the model to generate a short intermediate answer per retrieval step, and (iv) explicitly ask the model to generate a follow- up “search query” at each step. We found the final item to be important because self-ask’s default prompt often produces follow- up questions that are not self-contained (e.g., “what is the name of the national park?”, which is not an informative search query). We also fix the casing in the prompt to be consistent. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models Table 1. Development results comparing a task-aware DSP program against baseline vanilla LM and retrieve-then-read LM as well as recent and contemporaneous in-context learning approaches with and without retrieval. All of our runs use GPT-3.5 and our retrieval-based rows use ColBERTv2. The results marked with ¶ are collected from related work as of mid-December 2022, and attributed to their individual sources in the main text. As we discuss in the main text, the marked results are not generally apples-to-apples comparisons, since they span a variety of evaluation settings. Nonetheless, we report them here as qualitative reference points. Open-SQuAD EM F1 HotPotQA F1 EM QReCC F1 nF1 Vanilla LM No-retrieval LM SoTA 16.2 20.2¶ 25.6 – 28.3 33.8¶ 36.4 44.6¶ 29.8 – 18.4 – Retrieve-then-Read Self-ask w/ ColBERTv2 Search + Refined Prompt Retrieval-augmented LM SoTA 33.8 9.3 9.0 34.0¶ 46.1 17.2 15.7 – 36.9 25.2 28.6 35.1¶ 46.1 33.2 37.3 – 31.6 – – – 22.2 – – – Task-aware DSP Program 36.6 49.0 51.4 62.9 35.0 25.3 convqa_program, accepts turns (i.e., a list of strings, rep- resenting the conversational history) instead of a single question. Unless otherwise stated, our programs default to greedy decoding during the DEMONSTRATE stage. each hop and QA), it concatenates the summaries of all previous hops (i.e., hop 1 onwards) and a total of k = 5 passages divided between the hops (i.e., five passages from the first hop or two passages from the first and three from the second). For SEARCH, our open-domain QA program uses the ques- tion directly for retrieving k = 7 passages and concate- nates these passages into our QA prompt with CoT. For PREDICT, it generates n = 20 reasoning chains and uses self-consistency (SC; Wang et al. 2022c) to select its final prediction. For DEMONSTRATE, our open-domain QA pro- gram uses the following approach, slightly simplified for presentation. In it, the parameter k = 3 passed to annotate requests annotating only three demonstrations, which will then be used in the prompts. 1 def openqa_demonstrate (x: Example ) -> Example : 2 3 4 5 demos = sample (x. train , k =16) def openqa_attempt (d: Example ) -> Example : d. demos = all_but ( demos , d) # all ( raw ) examples different from d 6 7 8 d = openqa_search (d , k =2) if not passage_match (d): return None # skip examples where search fails 9 10 11 d = openqa_predict (d , sc = False ) if not answer_match (d): return None # skip examples where predict fails 12 13 14 15 16 return d x. demos = annotate ( demos , openqa_attempt , k =3) return x For conversational QA, we use a simple PREDICT which generates a response with greedy decoding, conditioned on all of the previous turns of the conversation and five retrieved passages. For SEARCH, our conversational QA pipeline generates n = 10 re-written queries (and also uses the simple query as the retrieve-and-read baseline; §3.3) and fuses them as in §2.4. We implement DEMONSTRATE simi- lar to openqa_demonstrate, but sample only four examples (i.e., four conversational turns; instead of 16 questions as in open-domain QA) for demonstrating the task for the higher- order transformation convqa_attempt, which is passed to annotate (not shown for brevity). 1 def convqa_attempt (d: Example ) -> Example : 2 d. demos = all_but ( demos , d) examples that don 't intersect with the conversation of d # all ( raw ) 3 4 5 d = convqa_search (d , k =2) if max ( precision (d . answer , p) for p in d. passages ) < .8: return None where search fails # skip examples 6 7 8 d = convqa_predict (d , n =20) if max ( F1 (c. pred , d. answer ) for c in d. candidates ) < .75: return None # skip examples where predict fails out of n =20 attempts 9 10 return d Our multi-hop program adopts a very similar approach for DEMONSTRATE and PREDICT. For SEARCH, it uses the approach described in §2.4, with the following adjustments. It uses result fusion across n = 10 queries per hop and, among the n predictions, uses the summary corresponding to the largest average log-probability. It uses a fixed number of hops for HotPotQA, i.e., two hops. In each prompt (i.e., # 3.5. Development Datasets & Results Open-SQuAD We conduct the open-domain version of SQuAD over the Wikipedia 2016 corpus from Chen et al. (2017), as processed by Khattab et al. (2021b). We use the DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models same train/validation/test splits as in Karpukhin et al. (2020) and Khattab et al. (2021b). Table 1 reports the answer EM and F1. The task-aware DSP program achieves 36.6% EM, outperforming the vanilla LM baseline by 126% EM relative gains. This indicates the im- portance of grounding the LM’s predictions in retrieval, and it shows that state-of-the-art retrievers like ColBERTv2 have the capacity to do so off-the-shelf. The proposed DSP pro- gram also achieves relative gains of 8% in EM and 6% in F1 over the retrieve-then-read pipeline, highlighting that non- trivial gains are possible by aggregating information across several retrieved passages as we do with self-consistency. the training set into 90%/10% train/validation splits. In the training (and thus validation) split, we keep only examples marked as “hard” in the original dataset, which matches the designation of the official validation and test sets. We report the final answer EM and F1 in Table 1. On HotPotQA, the task-aware DSP program outperforms the baselines and existing work by very wide margins, exceed- ing the vanilla LM, the retrieve-then-read baseline, and the self-ask pipeline by 82%, 39%, and 80%, respectively, in EM. This highlights the effectiveness of building up more sophisticated programs that coordinate the LM and RM for the SEARCH step. These in-context learning results are competitive with a number of popular fine-tuned systems. For instance, on the Open-SQuAD test set, DPR achieves 29.8% EM, well below our 16-shot DSP program. On the Open-SQuAD dev set, the powerful Fusion-in-Decoder (Izacard & Grave, 2020) “base” approach achieves approximately 36% (i.e., very similar quality to our system) when invoked with five retrieved passages. Nonetheless, with the default setting of reading 100 passages, their system reaches 48% EM in this evaluation. This may indicate that similar gains are possible for our DSP program if the PREDICT stage is made to aggregate information across many more passages. These results may be pegged against the evaluation on Hot- PotQA in a number of concurrent papers. We first compare with non-retrieval approaches, though our comparisons must be tentative due to variation in evaluation methodologies. Si et al. (2022) achieve 25.2% EM with CoT prompting. With a “recite-and-answer” technique for PaLM-62B (Chowdh- ery et al., 2022), Sun et al. (2022) achieve 26.5% EM. Wang et al. (2022b) achieve 33.8% EM and 44.6 F1 when apply- ing a self-consistency prompt for PaLM-540B. Next, we compare with a contemporaneous retrieval-based approach: Yao et al. (2022) achieve 35.1% EM using a system capable of searching using a Wikipedia API. All of these approaches trail our task-aware DSP program, which achieves 51.4% EM, by large margins. For comparison, we also evaluate the self-ask pipeline, which achieves 9.3% EM, suggesting that its fixed pipeline is ineffective outside its default multi-hop setting. Study- ing a few examples of its errors reveals that it often de- composes questions in tangential ways and answers these questions instead. We refer to this behavior of the LMas “self-distraction”, and we believe it adds evidence in favor of our design decisions in DSP. To illustrate self-distraction, when self-ask is prompted with “When does The Kidnap- ping of Edgardo Mortara take place?”, it asks “What is The Kidnapping of Edgardo Mortara“ and then asks when it was published, a tangential question. Thus, self-ask answers “1997”, instead of the time The Kidnapping of Edgardo Mortara takes place (1858). For reference, Table 1 also reports (as No-retrieval LM SoTA) the concurrent in-context learning results from Si et al. (2022) using code-davinci-002, who achieve 20.2% EM without retrieval and 34.0% EM with retrieval, albeit on a different sample and split of the SQuAD data. Overall, their approaches are very similar to the baselines we im- plement (vanilla LM and retrieve-then-read), though their retrieval-augmented approach retrieves (and concatenates into the prompt) 10 passages from a Wikipedia dump. QReCC We use QReCC (Anantha et al., 2020) in an open- domain setting over Wikipedia 2018. QReCC does not have an official development set, so we sub-divide the training set into 90%/10% train/validation splits. For the first ques- tion in every conversation, we use the rewritten question as the original question often assumes access to a ground- truth document. We also filter low-quality examples from QReCC.3 We conduct the QReCC conversations in an auto-regressive manner. At turn t > 1 of a particular conversation, the system sees its own responses (i.e., not the ground truth responses) to previous turns of the conversation. We report the novel-F1 metric (nF1; Paranjape et al. 2022), which computes the F1 overlap between the system response and the ground truth while discounting common stopwords and terms present in the question (or earlier questions). The results are shown in Table 1, and follow the same general pattern as SQuAD and HotPotQA. HotPotQA We use the open-domain “fullwiki” setting of HotPotQA using its official Wikipedia 2017 “abstracts” corpus. The HotPotQA test set is hidden, so we reserve the official validation set for our testing. We sub-divide 3We remove conversations that have one or more empty ground- truth answers and conversations that have only one or two ques- tions. We also find many conversations that include “what other interesting facts are in this article?”, which conflict with the open- domain formulation and have no well-defined answer. Hence, we remove any conversation that includes the keywords “other inter- esting” or “else”, which we found to be markers of low quality. DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models # 4. Conclusion prompts (at @goodside on Twitter). For a long time, the dominant paradigm for building models in AI has centered around multiplication of tensor repre- sentations, and in the deep learning era this has given rise to highly modular (layer-wise) designs that allow for fast development and wide exploration. However, these design paradigms require extensive domain expertise, and even experts face substantial challenges when it comes to com- bining different pretrained components into larger systems. The promise of in-context learning is that we can build com- plex systems from pretrained components using only natural language as the medium for giving systems instructions and, as we argue for, allowing components to communicate with each other. In this new paradigm, the building blocks are pretrained models and the core operations are natural lan- guage instructions and operations on natural language texts. If we can realize this potential, then we can broaden partici- pation in AI system development, rapidly prototype systems for new domains, and maximize the value of specialized pretrained components. # References Anantha, R., Vakulenko, S., Tu, Z., Longpre, S., Pulman, S., and Chappidi, S. Open-domain question answering goes conversational via question rewriting. arXiv preprint arXiv:2010.04898, 2020. Brown, T., Mann, B., Ryder, N., Subbiah, M., Kaplan, J. D., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., et al. Language models are few-shot learners. Advances in neural information processing systems, 33: 1877–1901, 2020. Cao, G., Nie, J.-Y., Gao, J., and Robertson, S. Selecting good expansion terms for pseudo-relevance feedback. In Proceedings of the 31st annual international ACM SIGIR conference on Research and development in information retrieval, pp. 243–250, 2008. In the current paper, we introduced the DEMONSTRATE– SEARCH–PREDICT (DSP) framework for retrieval aug- mented in-context learning. DSP consists of a number of simple, composable functions for implementing in-context learning systems as deliberate programs—instead of end- task prompts—for solving knowledge intensive tasks. We implemented DSP as a Python library and used it to write programs for Open-SQuAD, HotPotQA, and QReCC. These programs deliver substantial gains over previous in-context learning approaches. However, beyond any particular per- formance number, we argue that the central contribution of DSP is in helping to reveal a very large space of conceptual possibilities for in-context learning in general. # Acknowledgements We thank Ashwin Paranjape, Amir Ziai, and Rick Battle for valuable discussions and feedback. This work was partially supported by IBM as a founding member of the Stanford Institute for Human-Centered Artificial Intelligence (HAI). This research was supported in part by affiliate members and other supporters of the Stanford DAWN project—Ant Fi- nancial, Facebook, Google, and VMware—as well as Cisco, SAP, and the NSF under CAREER grant CNS-1651570. Any opinions, findings, and conclusions or recommenda- tions expressed in this material are those of the authors and do not necessarily reflect the views of the National Science Foundation. We thank Giuseppe Attanasio for his public LATEX GitHub-style Python code formatting gist.4 We also thank Riley Goodside for his public tips on formatting LM Chen, D., Fisch, A., Weston, J., and Bordes, A. Reading Wikipedia to answer open-domain questions. In Proceed- ings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 1870–1879, Vancouver, Canada, 2017. Association for Computational Linguistics. doi: 10.18653/v1/P17-1171. URL https://aclanthology.org/P17-1171. Chowdhery, A., Narang, S., Devlin, J., Bosma, M., Mishra, G., Roberts, A., Barham, P., Chung, H. W., Sutton, C., Gehrmann, S., et al. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311, 2022. Del Tredici, M., Barlacchi, G., Shen, X., Cheng, W., and de Gispert, A. Question rewriting for open-domain con- versational qa: Best practices and limitations. In Pro- ceedings of the 30th ACM International Conference on Information & Knowledge Management, pp. 2974–2978, 2021. Dohan, D., Xu, W., Lewkowycz, A., Austin, J., Bieber, D., Lopes, R. G., Wu, Y., Michalewski, H., Saurous, R. A., Sohl-Dickstein, J., et al. Language model cascades. arXiv preprint arXiv:2207.10342, 2022. Fox, E. A. and Shaw, J. A. Combination of multiple searches. NIST special publication SP, 243, 1994. Gao, L., Dai, Z., Pasupat, P., Chen, A., Chaganty, A. T., Fan, Y., Zhao, V. Y., Lao, N., Lee, H., Juan, D.-C., et al. At- tributed text generation via post-hoc research and revision. arXiv preprint arXiv:2210.08726, 2022. 4https://gist.github.com/g8a9/ 07c2be12ae02cfad4aa430d77dc940cb Geva, M., Khashabi, D., Segal, E., Khot, T., Roth, D., and Berant, J. Did aristotle use a laptop? a question answering DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models benchmark with implicit reasoning strategies. Transac- tions of the Association for Computational Linguistics, 9: 346–361, 2021. Khattab, O., Potts, C., and Zaharia, M. Relevance-guided supervision for openqa with ColBERT. Transactions of the Association for Computational Linguistics, 9:929– 944, 2021b. Hofstätter, S., Chen, J., Raman, K., and Zamani, H. Fid- light: Efficient and effective retrieval-augmented text generation. arXiv preprint arXiv:2209.14290, 2022. Huang, J., Gu, S. S., Hou, L., Wu, Y., Wang, X., Yu, H., and Han, J. Large language models can self-improve. arXiv preprint arXiv:2210.11610, 2022. Ishii, Y., Madotto, A., and Fung, P. Survey of hallucination in natural language generation. ACM Comput. Surv, 1(1), 2022. Izacard, G. and Grave, E. Leveraging passage retrieval with generative models for open domain question answering. arXiv preprint arXiv:2007.01282, 2020. Izacard, G., Lewis, P., Lomeli, M., Hosseini, L., Petroni, F., Schick, T., Dwivedi-Yu, J., Joulin, A., Riedel, S., and Grave, E. Few-shot learning with retrieval augmented lan- guage models. arXiv preprint arXiv:2208.03299, 2022. Jiang, Y., Bordia, S., Zhong, Z., Dognin, C., Singh, M., and Bansal, M. HoVer: A dataset for many-hop fact In Findings of the extraction and claim verification. Association for Computational Linguistics: EMNLP 2020, pp. 3441–3460, Online, 2020. Association for Computational Linguistics. doi: 10.18653/v1/2020. findings-emnlp.309. URL https://aclanthology. org/2020.findings-emnlp.309. Karpukhin, V., Oguz, B., Min, S., Lewis, P., Wu, L., Edunov, S., Chen, D., and Yih, W.-t. Dense passage retrieval In Proceedings for open-domain question answering. of the 2020 Conference on Empirical Methods in Nat- ural Language Processing (EMNLP), pp. 6769–6781, Online, 2020. Association for Computational Linguis- tics. doi: 10.18653/v1/2020.emnlp-main.550. URL https://aclanthology.org/2020.emnlp-main.550. Khattab, O. and Zaharia, M. Colbert: Efficient and effective passage search via contextualized late interaction over BERT. In Huang, J., Chang, Y., Cheng, X., Kamps, J., Murdock, V., Wen, J., and Liu, Y. (eds.), Proceedings of the 43rd International ACM SIGIR conference on re- search and development in Information Retrieval, SIGIR 2020, Virtual Event, China, July 25-30, 2020, pp. 39– 48. ACM, 2020. doi: 10.1145/3397271.3401075. URL https://doi.org/10.1145/3397271.3401075. Khot, T., Trivedi, H., Finlayson, M., Fu, Y., Richardson, K., Clark, P., and Sabharwal, A. Decomposed prompting: A modular approach for solving complex tasks. arXiv preprint arXiv:2210.02406, 2022. Kojima, T., Gu, S. S., Reid, M., Matsuo, Y., and Iwasawa, Y. Large language models are zero-shot reasoners. arXiv preprint arXiv:2205.11916, 2022. Krishna, K., Chang, Y., Wieting, J., and Iyyer, M. Rankgen: Improving text generation with large ranking models. arXiv preprint arXiv:2205.09726, 2022. Kurland, O. and Culpepper, J. S. Fusion in information retrieval: Sigir 2018 half-day tutorial. In The 41st Inter- national ACM SIGIR Conference on Research & Devel- opment in Information Retrieval, pp. 1383–1386, 2018. Kwiatkowski, T., Palomaki, J., Redfield, O., Collins, M., Parikh, A., Alberti, C., Epstein, D., Polosukhin, I., Devlin, J., Lee, K., Toutanova, K., Jones, L., Kelcey, M., Chang, M.-W., Dai, A. M., Uszkoreit, J., Le, Q., and Petrov, S. Natural questions: A benchmark for question answering research. Transactions of the Association for Computa- tional Linguistics, 7:452–466, 2019. doi: 10.1162/tacl_a_ 00276. URL https://aclanthology.org/Q19-1026. Lazaridou, A., Gribovskaya, E., Stokowiec, W., and Grig- orev, N. Internet-augmented language models through few-shot prompting for open-domain question answering. arXiv preprint arXiv:2203.05115, 2022. Le, N. T., Bai, F., and Ritter, A. Few-shot anaphora reso- lution in scientific protocols via mixtures of in-context experts. arXiv preprint arXiv:2210.03690, 2022. Lee, K., Chang, M.-W., and Toutanova, K. Latent re- trieval for weakly supervised open domain question an- swering. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pp. 6086– 6096, Florence, Italy, 2019. Association for Computa- tional Linguistics. doi: 10.18653/v1/P19-1612. URL https://aclanthology.org/P19-1612. Levine, Y., Dalmedigos, I., Ram, O., Zeldes, Y., Jan- nai, D., Muhlgay, D., Osin, Y., Lieber, O., Lenz, B., Shalev-Shwartz, S., et al. Standing on the shoul- ders of giant frozen language models. arXiv preprint arXiv:2204.10019, 2022. Khattab, O., Potts, C., and Zaharia, M. Baleen: Robust Multi-Hop Reasoning at Scale via Condensed Retrieval. In Thirty-Fifth Conference on Neural Information Pro- cessing Systems, 2021a. Lewis, P. S. H., Perez, E., Piktus, A., Petroni, F., Karpukhin, V., Goyal, N., Küttler, H., Lewis, M., Yih, W., Rock- täschel, T., Riedel, S., and Kiela, D. Retrieval-Augmented DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models Generation for Knowledge-Intensive NLP Tasks. In Larochelle, H., Ranzato, M., Hadsell, R., Balcan, M., and Lin, H. (eds.), Advances in Neural Information Processing Systems 33: Annual Conference on Neural Information Processing Systems 2020, NeurIPS 2020, December 6-12, 2020, virtual, 2020. URL https: //proceedings.neurips.cc/paper/2020/hash/ 6b493230205f780e1bc26945df7481e5-Abstract. html. Li, X. L., Holtzman, A., Fried, D., Liang, P., Eisner, J., Hashimoto, T., Zettlemoyer, L., and Lewis, M. Con- trastive decoding: Open-ended text generation as opti- mization. arXiv preprint arXiv:2210.15097, 2022. Liu, J., Shen, D., Zhang, Y., Dolan, B., Carin, L., and Chen, W. What makes good in-context examples for gpt-3? arXiv preprint arXiv:2101.06804, 2021. McCann, B., Keskar, N. S., Xiong, C., and Socher, R. The natural language decathlon: Multitask learning as question answering. arXiv:1806.08730, 2018. URL https://arxiv.org/abs/1806.08730. Min, S., Zhong, V., Zettlemoyer, L., and Hajishirzi, H. Multi-hop reading comprehension through ques- arXiv preprint tion decomposition and rescoring. arXiv:1906.02916, 2019. Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., Sutskever, I., et al. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9, 2019. Rajpurkar, P., Zhang, J., Lopyrev, K., and Liang, P. SQuAD: 100,000+ questions for machine comprehension of text. In Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing, pp. 2383– 2392, Austin, Texas, 2016. Association for Computa- tional Linguistics. doi: 10.18653/v1/D16-1264. URL https://aclanthology.org/D16-1264. Raposo, G., Ribeiro, R., Martins, B., and Coheur, L. Ques- tion rewriting? assessing its importance for conversa- tional question answering. In European Conference on Information Retrieval, pp. 199–206. Springer, 2022. Santhanam, K., Khattab, O., Potts, C., and Zaharia, M. PLAID: An Efficient Engine for Late Interaction Re- trieval. arXiv preprint arXiv:2205.09707, 2022a. Santhanam, K., Khattab, O., Saad-Falcon, J., Potts, C., and Zaharia, M. ColBERTv2: Effective and efficient retrieval via lightweight late interaction. In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 3715–3734, Seattle, United States, July 2022b. Association for Computational Lin- guistics. doi: 10.18653/v1/2022.naacl-main.272. URL https://aclanthology.org/2022.naacl-main.272. Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C. L., Mishkin, P., Zhang, C., Agarwal, S., Slama, K., Ray, A., et al. Training language models to fol- low instructions with human feedback. arXiv preprint arXiv:2203.02155, 2022. Shuster, K., Poff, S., Chen, M., Kiela, D., and Weston, J. Retrieval augmentation reduces hallucination in conver- sation. arXiv preprint arXiv:2104.07567, 2021. Paranjape, A., Khattab, O., Potts, C., Zaharia, M., and Manning, C. D. Hindsight: Posterior-guided Training of Retrievers for Improved Open-ended Generation. In International Conference on Learning Representations, 2022. URL https://openreview.net/forum?id=Vr_ BTpw3wz. Si, C., Gan, Z., Yang, Z., Wang, S., Wang, J., Boyd-Graber, J., and Wang, L. Prompting gpt-3 to be reliable. arXiv preprint arXiv:2210.09150, 2022. Sun, Z., Wang, X., Tay, Y., Yang, Y., and Zhou, D. Recitation-augmented language models. arXiv preprint arXiv:2210.01296, 2022. Perez, E., Kiela, D., and Cho, K. True few-shot learning with language models. Advances in Neural Information Processing Systems, 34:11054–11070, 2021. Press, O., Zhang, M., Min, S., Schmidt, L., Smith, N. A., and Lewis, M. Measuring and narrowing the com- positionality gap in language models. arXiv preprint arXiv:2210.03350, 2022. Thorne, J., Vlachos, A., Christodoulopoulos, C., and Mit- tal, A. FEVER: a large-scale dataset for fact extrac- tion and VERification. In Proceedings of the 2018 Con- ference of the North American Chapter of the Associa- tion for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers), pp. 809–819, New Orleans, Louisiana, 2018. Association for Compu- tational Linguistics. doi: 10.18653/v1/N18-1074. URL https://aclanthology.org/N18-1074. Qi, P., Lee, H., Sido, O., Manning, C. D., et al. Retrieve, rerank, read, then iterate: Answering open-domain ques- tions of arbitrary complexity from text. arXiv preprint arXiv:2010.12527, 2020. URL https://arxiv.org/ abs/2010.12527. Vakulenko, S., Kiesel, J., and Fröbe, M. SCAI-QReCC shared task on conversational question answering. In Pro- ceedings of the Thirteenth Language Resources and Eval- uation Conference, pp. 4913–4922, Marseille, France, DEMONSTRATE–SEARCH–PREDICT: Composing retrieval and language models June 2022. European Language Resources Association. URL https://aclanthology.org/2022.lrec-1.525. Wang, X., Macdonald, C., Tonellotto, N., and Ounis, I. Colbert-prf: Semantic pseudo-relevance feedback for dense passage and document retrieval. ACM Transac- tions on the Web, 2022a. Wang, X., Wei, J., Schuurmans, D., Le, Q., Chi, E., and Zhou, D. Rationale-augmented ensembles in language models. arXiv preprint arXiv:2207.00747, 2022b. Wang, X., Wei, J., Schuurmans, D., Le, Q., Chi, E., and Zhou, D. Self-consistency improves chain of thought reasoning in language models. arXiv preprint arXiv:2203.11171, 2022c. Wei, J., Wang, X., Schuurmans, D., Bosma, M., Chi, E., Le, Q., and Zhou, D. Chain of thought prompting elic- its reasoning in large language models. arXiv preprint arXiv:2201.11903, 2022. Wiher, G., Meister, C., and Cotterell, R. On decoding arXiv preprint strategies for neural text generators. arXiv:2203.15721, 2022. Xiong, W., Li, X. L., Iyer, S., Du, J., Lewis, P., Wang, W. Y., Mehdad, Y., Yih, W.-t., Riedel, S., Kiela, D., et al. Answering complex open-domain questions with multi- hop dense retrieval. arXiv preprint arXiv:2009.12756, 2020. URL https://arxiv.org/abs/2009.12756. Xue, X. and Croft, W. B. Modeling reformulation using query distributions. ACM Transactions on Information Systems (TOIS), 31(2):1–34, 2013. Yang, Z., Qi, P., Zhang, S., Bengio, Y., Cohen, W. W., Salakhutdinov, R., and Manning, C. D. Hotpotqa: A dataset for diverse, explainable multi-hop question an- swering. arXiv preprint arXiv:1809.09600, 2018. Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K., and Cao, Y. React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629, 2022. Zelikman, E., Wu, Y., and Goodman, N. D. Star: Boot- arXiv preprint strapping reasoning with reasoning. arXiv:2203.14465, 2022. Zhang, Z., Zhang, A., Li, M., and Smola, A. Automatic chain of thought prompting in large language models. arXiv preprint arXiv:2210.03493, 2022. Zhong, V., Shi, W., Yih, W.-t., and Zettlemoyer, L. Romqa: A benchmark for robust, multi-evidence, multi-answer question answering. arXiv preprint arXiv:2210.14353, 2022.
Title: Contrastive Learning of Medical Visual Representations from Paired Images and Text: Summary: Learning visual representations of medical images (e.g., X-rays) is core to medical image understanding but its progress has been held back by the scarcity of human annotations. Existing work commonly relies on fine-tuning weights transferred from ImageNet pretraining, which is suboptimal due to drastically different image characteristics, or rule-based label extraction from the textual report data paired with medical images, which is inaccurate and hard to generalize. Meanwhile, several recent studies show exciting results from unsupervised contrastive learning from natural images, but we find these methods help little on medical images because of their high inter-class similarity. We propose ConVIRT, an alternative unsupervised strategy to learn medical visual representations by exploiting naturally occurring paired descriptive text. Our new method of pretraining medical image encoders with the paired text data via a bidirectional contrastive objective between the two modalities is domain-agnostic, and requires no additional expert input. We test ConVIRT by transferring our pretrained weights to 4 medical image classification tasks and 2 zero-shot retrieval tasks, and show that it leads to image representations that considerably outperform strong baselines in most settings. Notably, in all 4 classification tasks, our method requires only 10\% as much labeled training data as an ImageNet initialized counterpart to achieve better or comparable performance, demonstrating superior data efficiency. Research 182:1–24, 2022 Machine Learning for Healthcare # Contrastive Learning of Medical Visual Representations from Paired Images and Text # Yuhao Zhang∗ Biomedical Informatics Training Program, Stanford University yuhao@cs.stanford.edu # Hang Jiang∗ Symbolic Systems Program, Stanford University hjian42@stanford.edu # Yasuhide Miura† Computer Science Department, Stanford University ysmiura@stanford.edu # Christopher D. Manning Computer Science and Linguistics Departments, Stanford University manning@stanford.edu # Curtis P. Langlotz Department of Radiology, Stanford University langlotz@stanford.edu Abstract Learning visual representations of medical images (e.g., X-rays) is core to medical image understanding but its progress has been held back by the scarcity of human annotations. Existing work commonly relies on fine-tuning weights transferred from ImageNet pretrain- ing, which is suboptimal due to drastically different image characteristics, or rule-based label extraction from the textual report data paired with medical images, which is inaccu- rate and hard to generalize. Meanwhile, several recent studies show exciting results from unsupervised contrastive learning from natural images, but we find these methods help little on medical images because of their high inter-class similarity. We propose ConVIRT, an alternative unsupervised strategy to learn medical visual representations by exploiting naturally occurring paired descriptive text. Our new method of pretraining medical image encoders with the paired text data via a bidirectional contrastive objective between the two modalities is domain-agnostic, and requires no additional expert input. We test Con- VIRT by transferring our pretrained weights to 4 medical image classification tasks and 2 zero-shot retrieval tasks, and show that it leads to image representations that consid- erably outperform strong baselines in most settings. Notably, in all 4 classification tasks, our method requires only 10% as much labeled training data as an ImageNet initialized counterpart to achieve better or comparable performance, demonstrating superior data efficiency. ∗ The first two authors contributed equally. YZ is now affliated with AWS AI Labs, while the work was done before his current affiliation. HJ is now affliated with Massachusetts Institute of Technology. † YM is now affiliated with FUJIFILM Corporation. © 2022 Y. Zhang, H. Jiang, Y. Miura, C.D. Manning & C.P. Langlotz. OF MEDICAL VISUAL REPRESENTATIONS FROM PAIRED IMAGES AND has the potential to transform healthcare and has seen rapid learning (Gulshan et al., 2016; Esteva et al., 2017; De Fauw et al., 2018b). Yet, with expert-level performance achieved only in some some circumstances, medical image understanding remains a difficult dependent on subtle visual distinctions in overall similar images. by the extreme scarcity of annotated data. Severe cardiomegaly Radiograph shows is noted in the image pleural effusion in with enlarged... the right... Contrastive Learning of Medical Visual Representations from Paired Images and Text # 1. Introduction Medical image understanding has the potential to transform healthcare and has seen rapid progress with deep learning (Gulshan et al., 2016; Esteva et al., 2017; De Fauw et al., 2018; Rajpurkar et al., 2018b). Yet, with expert-level performance achieved only in some specialties and under some circumstances, medical image understanding remains a difficult task, with classifications dependent on subtle visual distinctions in overall similar images. This is further exacerbated by the extreme scarcity of annotated data. Figure 1: Two example chest X-ray images with different abnormality categories, along with sentences from their paired textual report and example views indicative of their char- acteristics. Existing work has followed two general approaches to obtain annotations for medical imaging tasks. The first approach has been using high-quality annotations created by med- ical experts (Abr`amoff et al., 2016; Gulshan et al., 2016; Shih et al., 2019; Wang and Wong, 2020). However, the high cost of this approach has resulted in datasets that are mostly orders of magnitude smaller than natural image datasets such as ImageNet (Russakovsky et al., 2015). To remedy this, existing work has relied heavily on transferring model weights from ImageNet pretraining (Wang et al., 2017; Esteva et al., 2017; Irvin et al., 2019). This approach is suboptimal because, as shown in Figure 1, medical image understanding often requires representations of very fine-grained visual features that are drastically different from those required for identifying objects in natural images. As a result, Raghu et al. (2019) found that ImageNet pretraining often provides little to no benefit compared to simple random initialization. A second popular approach is to use expert-crafted rules to extract labels from the textual reports accompanying the images. This approach has led to datasets of larger scale, since the text data paired with medical images are often produced naturally by medical experts in their routine workflow and abundant in a typical hospital’s IT systems. Nevertheless, this rule-based label extraction approach has two key limitations: 1) the rules are often inaccurate and limited to a few categories (Wang et al., 2017), leading to very inefficient use of the textual report data; 2) these rules are often domain-specific and sensitive to the style of the text, making cross-domain and cross-institution generalization difficult (Irvin et al., 2019). 2 # Contrastive Learning of Medical Visual Representations from Paired Images and Text In efforts to make more efficient use of unlabeled image data, several recent studies have shown promising results from contrastive representation learning from natural images (Chen et al., 2020a; He et al., 2020; Grill et al., 2020). However, as we will show, applying these image view–based contrastive methods to medical images provides only marginal benefits compared to ImageNet pretraining, a result mostly due to the high inter-class similarity of the medical images as in Figure 1. In this work, we introduce a new method to improve visual representation learning on medical images by combining the benefits of both learning from abundant textual data and unsupervised statistical approaches. We present Contrastive VIsual Representation Learning from Text (ConVIRT), a framework for learning visual representations by exploit- ing the naturally occurring pairing of images and textual data. ConVIRT improves visual representations by maximizing the agreement between true image-text pairs versus random pairs via a bidirectional contrastive objective between the image and text modalities. We apply ConVIRT to the pretraining of medical image encoders, and show that it leads to higher-quality in-domain image representations that capture the subtlety of visual features required for medical image understanding tasks. Compared to existing methods, ConVIRT has the advantages of utilizing the paired text data in a way agnostic to the medical specialty and requiring no additional expert input. This allows us to evaluate ConVIRT by transferring our pretrained encoder weights to 4 different medical image classification tasks covering 2 medical specialties. We find that the resulting models outperform all baseline initialization approaches, including the widely used ImageNet pretraining and strong baselines that also utilize the paired text data. It further improves upon popular image-only unsupervised learning methods such as SimCLR (Chen et al., 2020a) and MoCo v2 (Chen et al., 2020b). Most notably, in all 4 classification tasks, ConVIRT requires only 10% as much labeled training data as an ImageNet initialized counterpart to achieve better or comparable performance. We further evaluate ConVIRT on two new zero-shot retrieval tasks, an image-image and a text-image retrieval task, and also find it superior to all baselines. Since its original release in 2020, ConVIRT has directly inspired subsequent studies such as the CLIP framework (Radford et al., 2021) and the ALIGN model (Jia et al., 2021), which showed that direct adaptations of ConVIRT-style pretraining at much larger scales lead to state-of-the-art general visual recognition capabilities. To facilitate future research, we make our model and the collected retrieval datasets1 publicly available. # 1.1. Generalizable Insights about Machine Learning in the Context of Healthcare Healthcare data is usually scarce and costly to annotate compared to data in the general domain. As a result, machine learning models built with a single modality of healthcare data often face the generalization challenge due to small sample sizes of training data. Meanwhile, healthcare data is often naturally paired with multimodal clinical features, including text descriptions or patient metadata, which can be exploited to reduce the cost of building reliable machine learning models. Our method, ConVIRT, demonstrates an application of this idea to learning robust medical image encoders by reusing descriptive 1. https://github.com/yuhaozhang/convirt 3 # Contrastive Learning of Medical Visual Representations from Paired Images and Text text naturally produced by experts via a cross-modality learning framework. We show that this simple method can greatly benefit downstream predictive tasks with reduced annotation cost. Since the release of our work, similar image-text pretraining strategies have been used to improve more downstream healthcare tasks including image regeneration (Wang et al., 2021), medical visual question answering (Eslami et al., 2021) and clinical risk prediction (Zang and Wang, 2021), etc. Moreover, a similar idea can be extended to include other modalities of healthcare data, including multiomics data (Han et al., 2021) or patient metadata (Vu et al., 2021), for more robust and cost-effective machine learning applications in the healthcare domain. # 2. Related Work Our work is most relevant to work on medical image classification, which we have discussed in Section 1, and textual report generation from medical images (Wang et al., 2018; Jing et al., 2018; Liu et al., 2019; Miura et al., 2021). A dominant approach for initializing medical image encoders in relevant studies has been using encoder weights pretrained on ImageNet, despite the drastic difference in image characteristics (Raghu et al., 2019). Instead, we propose an alternative in-domain pretraining strategy for medical imaging and compare different pretraining approaches that also use the paired medical reports. Our work is inspired by the recent line of work on image view-based contrastive learning (H´enaff et al., 2020; Chen et al., 2020a; He et al., 2020; Grill et al., 2020; Sowrirajan et al., 2021; Azizi et al., 2021), but fundamentally differs from existing studies by exploiting contrastive learning using the text modality. As we show in Section 6, the added semantics from the text data makes contrastive learning more effective in learning high-quality representations of medical images. To our knowledge, our work represents the first systematic attempt in this direction. Another line of work related to ours is visual-linguistic representation learning (Lu et al., 2019; Tan and Bansal, 2019; Su et al., 2020). Among existing studies, Ilharco et al. (2021) and Gupta et al. (2020) explored cross-modality contrastive objectives related to ours, but for the purpose of probing visual-linguistic models and learning phrase grounding, respec- tively. Our work differs from most work in visual-linguistic pretraining in several crucial ways: 1) existing work in visual-linguistic learning focused on learning visual representations from paired text via a binary contrastive prediction task, whereas we contribute by showing the superior performance of the new cross-modality NCE objectives in improving visual representations; 2) existing work has primarily relied on object representations extracted from image segmentation models in their preprocessing steps, making them less applicable to medical image understanding tasks where anatomical segmentations are extremely hard to obtain; 3) while existing work has run evaluation primarily on visual-linguistic tasks such as visual question answering, we instead focus on evaluation with classification and retrieval tasks which are at the center of medical image understanding research. Several concurrent papers have studied the problem of learning visual representations from text data (Sariyildiz et al., 2020; Desai and Johnson, 2021) on general-domain image problems. Most notably, since the original release of our work, ConVIRT has been applied at larger scales in several general visual recognition studies, including the CLIP model (Radford et al., 2021), which uses a simplified version of the ConVIRT approach, and the 4 # Contrastive Learning of Medical Visual Representations from Paired Images and Text ALIGN model by Jia et al. (2021). These successful applications have confirmed that ConVIRT is a promising strategy for learning visual representations from human-written descriptive text, and that it has the potential to further advance the state of the art for visual recognition tasks. There are also subsequent studies which mainly focused on medical-domain image prob- lems. To the best of our knowledge, ConVIRT was the first work that leverages text-image contrastive loss for pretraining medical visual representations and was followed by numer- ous papers (Heiliger et al., 2022) that apply multimodal contrastive learning to the medical imaging domain. Wang et al. (2021) demonstrated the feasibility of such a pretraining strat- egy across mixed data inputs (image-only, text-only, image-text pairs) in three chest X-ray applications (i.e., classification, retrieval, and image regeneration). M¨uller et al. (2021) proposed a similar method, LoVT, for localized medical imaging tasks. Huang et al. (2021) adapted our method and further proposed GloRIA to contrast image sub-regions and words in the paired report. Liao et al. (2021) trained image and text encoders by encouraging the resulting representations to exhibit high local mutual information. Eslami et al. (2021) proposed PubMedCLIP to better adapt CLIP to the Medical Visual Question Answering (MedVQA) task. Zang and Wang (2021) applied a similar contrastive learning framework to clinical risk prediction based on longitudinal electronic health records. Han et al. (2021) extended ConVIRT to use radiomics features and contrastive learning for pneumonia de- tection, and Vu et al. (2021) selected positive pairs coming from views of possibly different images through the use of patient metadata. # 3. Methods # 3.1. Task Definition We start by defining our representation learning setting. We assume paired input (xv, xu) where xv represents one or a group of images, and xu represents a text sequence which de- scribes the imaging information in xv. Our goal is to learn a parameterized image encoder function fv, which maps an image to a fixed-dimensional vector. We are then interested in transferring the learned image encoder function fv into downstream tasks, such as classifi- cation or image retrieval. In this work, we model the encoder function fv as a convolutional neural network (CNN). We note that paired image-text data (xv, xu) naturally exists for many medical domains. Medical experts such as radiologists produce textual descriptions of images as part of their routine workflow, some of which are also made publicly available (Demner-Fushman et al., 2016; Johnson et al., 2019). # 3.2. Contrastive Visual Representation Learning from Text An overview of our method, ConVIRT, for learning fv is shown in Figure 2. At a high level, our method converts each input image xv and text xu into d-dimensional vector representa- tions v and u respectively, following a similar processing pipeline. For each input image xv, our method starts by drawing a random view ˜xv from xv with a sampled transformation function tv ∼ T , where T represents a family of stochastic image transformation functions described later. Next, the encoder function fv transforms ˜xv into a fixed-dimensional vector 5 CONTRASTIVE LEARNING OF MEDICAL VISUAL REPRESENTATIONS FROM PAIRED IMAGES AND TEXT Image Encoder Heart size is enlarged... E tu Xu Clear consolidation at... | ——> Xy No abnormality seen ... # Contrastive Learning of Medical Visual Representations from Paired Images and Text Figure 2: Overview of our ConVIRT framework. The blue and green shades represent the image and text encoding pipelines, respectively. Our method relies on maximizing the agreement between the true image-text representation pairs with bidirectional losses 0@7 and >”), hv, followed by a non-linear projection gv which further transforms hv into vector v: v = gv(fv(˜xv)), (1) where v ∈ Rd. Similarly, for each text input xu, we obtain a span ˜xu from it following a sampling function tu, and then a text representation u with: u = gu(fu(˜xu)), where fu is a text encoder, gu a projection, and u ∈ Rd. The projection functions gv and gu project representations for both modalities from their encoder space to the same d-dimensional space for contrastive learning. At training time, we sample a minibatch of N input pairs (xv, xu) from training data, and calculate their representation pairs (v, u). We use (vi, ui) to denote the i-th pair. The training objective of ConVIRT involves two loss functions. The first loss function is an image-to-text contrastive loss for the i-th pair: per) lo exp((vi, ui) /T) ; ‘ SSN exp((vi, ua)/7)’ °) where (v;,u;) represents the cosine similarity, ie., (v,u) = v'u/||v||llull; and 7 € R* represents a temperature parameter. This loss takes the same form as the InfoNCE loss (Oord et al., 2018), and minimizing it leads to encoders that maximally preserve the mutual information between the true pairs under the representation functions. Intuitively, it is the log loss of an N-way classifier that tries to predict (v;, u;) as the true pair. Note that unlike previous work which use a contrastive loss between inputs of the same modality (Chen et al., 2020a; He et al., 2020), our image-to-text contrastive loss is asymmetric for each input modality. We therefore define a similar text-to-image contrastive loss as: per) lo exp((ui, vi) /T) ; ‘ SSN exp((us, va)/7) ®) 6 # Contrastive Learning of Medical Visual Representations from Paired Images and Text Our final training loss is then computed as a weighted combination of the two losses averaged over all positive image-text pairs in each minibatch: 1 a vou usu c= (ar ea ae”), (4) where λ ∈ [0, 1] is a scalar weight. # 3.3. Realization We note that our ConVIRT framework defined above is agnostic to the specific choice of image and text encoders, transformations and projection functions. Following previous work (Chen et al., 2020a), we model gv and gu as separate learnable single-hidden-layer neural networks, i.e., gv(·) = W(2)σ(W(1)(·)) where σ is a ReLU non-linearity, and similarly for gu. For the image encoder fv, we use the ResNet50 architecture (He et al., 2016) for all experiments, as it is the architecture of choice for much medical imaging work and is shown to achieve competitive performance. For the text encoder fu, we use a BERT encoder (Devlin et al., 2019) followed by a max-pooling layer over all output vectors. We initialize our encoder with the ClinicalBERT weights (Alsentzer et al., 2019) pretrained on the MIMIC clinical notes, which achieved state-of-the-art performance on a suite of clinical NLP tasks. At training time we allow the encoder to adapt to our contrastive task by freezing the embeddings and the first 6 transformer layers of this BERT encoder and fine-tuning the last 6 layers. For the image transformation family T where tv is sampled from, we use sequential applications of five random transformations: cropping, horizontal flipping, affine transfor- mation, color jittering and Gaussian blur. Different from recent work on contrastive visual learning (Chen et al., 2020a,b), we only apply brightness and contrast adjustments in color jittering, due to the monochrome nature of the medical images. For the text transformation function tu, we apply a simple uniform sampling of a sentence from the input document xu (i.e., ˜xu is a randomly sampled sentence from xu for each minibatch). We did not use a more aggressive transformation mainly because sampling at the sentence level helps preserve the semantic meaning of the sampled spans. An alternative method to using the sampled view ˜xv from xv as input to the encoder is to directly use xv or to fuse all images for each study in the case of multiple available xv instances (e.g., images from multiple angles). We empirically found in our preliminary experiments that using sampled view ˜xv leads to better pretraining results. We conjecture that we can treat the use of ˜xv as a way of data augmentation for the visual modality, which helped increase the effective amount of unique image-text pairs that the model sees at pretraining time, leading to better performance. # 4. Experiments We now introduce the paired datasets that we used for contrastive pretraining, the down- stream tasks and datasets for evaluation, and the baseline methods that we compare against. 7 Contrastive Learning of Medical Visual Representations from Paired Images and Text # 4.1. Data for Pretraining We evaluate ConVIRT by pretraining two separate image encoders using two separate image-text datasets (see Appendix A for full pretraining details): • Chest image encoder: We use version 2 of the public MIMIC-CXR database (Johnson et al., 2019), which is a collection of chest radiograph images paired with their textual reports, and since its release has become a standard resource for studying multi-modal modeling of medical images. After preprocessing, this dataset contains a total of about 217k image-text pairs, with each pair containing an average of 1.7 images and 6.0 sen- tences. • Bone image encoder: We obtain a collection of musculoskeletal (i.e., bone) image-text pairs from the Rhode Island Hospital system. Following chest, musculoskeletal images constitute the second most common type of radiograph images in a typical hospital. This dataset contains a total of 48k image-text pairs, with each pair containing an average of 2.5 images and 8.0 sentences. # 4.2. Evaluation Tasks & Data We evaluate our pretrained image encoders on three medical imaging tasks: image classifi- cation, zero-shot image-image retrieval and zero-shot text-image retrieval. Image Classification. We evaluate our pretrained image encoders on four representative medical image classification tasks: 1) RSNA Pneumonia Detection (Wang et al., 2017; Shih et al., 2019), which involves binary classification of a chest radiograph image into ei- ther a pneumonia or a normal category; 2) CheXpert image classification (Irvin et al., 2019), which involves multi-label binary classification of a chest image for five individual la- bels, i.e., atelectasis, cardiomegaly, consolidation, edema and pleural effusion; 3) COVIDx (Wang and Wong, 2020), which involves multi-class chest image classification into three cat- egories (COVID19, non-COVID pneumonia or normal ); and 4) MURA bony abnormality detection (Rajpurkar et al., 2018a), which involves binary classification of a musculoskeletal image into abnormal or normal. We report test accuracy for COVIDx given its balanced test set, and report the standard area under the receiver operating characteristic curve (AUC) metric for other tasks. Following previous work (H´enaff et al., 2020; Chen et al., 2020a; He et al., 2020), for all tasks, we evaluate each pretrained image encoder under two settings: a linear classifica- tion setting, where the pretrained CNN weights are frozen and only a linear classification head is trained for the task; and a fine-tuning setting, where both the CNN weights and the linear head are fine-tuned. The two settings complement each other for evaluation pur- poses: while the linear setting directly evaluates the quality of the extracted image features with the pretrained CNN, the fine-tuning setting more closely resembles how the pretrained CNN weights are used in practical applications. To further compare the data efficiency of different pretraining methods, for each set- ting we evaluate the image encoders with 1%, 10% and all training data, respectively (except for the COVIDx task where we omit the 1% setting due to the scarcity of training data). To control the variance in results, for all settings and models, we report average 8 Contrastive Learning of Medical Visual Representations from Paired Images and Text results over 5 independent training runs. We include further dataset and training details in Appendix B. Zero-shot Image-image Retrieval. This evaluation is similar to the conventional content- based image retrieval setting in which we search for images of a particular category using a representative query image. For evaluation, a group of query images and a larger collection of candidate images, each with a categorical label, are given to a pretrained CNN encoder. We encode each query and candidate image with this encoder, and then for each query, rank all candidates by their cosine similarities to the query in descending order. Since a widely-used annotated benchmark for this setting is not available, we create our own dataset by re-using existing annotations in the CheXpert dataset (Irvin et al., 2019) and additional expert annotations from a board-certified radiologist. The resulting dataset covers 8 differ- ent chest abnormality categories, each with 10 expert-annotated query and 200 candidate images. We include the detailed collection and annotation procedure in Appendix C, and refer to this dataset as CheXpert 8×200 Retrieval Dataset. We focus our evaluation on retrieval precision, and evaluate our models with Precision@k metrics where k = 5, 10, 100. Zero-shot Text-image Retrieval. This setting is similar to the image-image retrieval setting, but instead of using query images, we retrieve images of a particular category with textual queries. For this purpose, we ask a radiologist to write 5 diverse and representative textual descriptions for each of the 8 abnormality categories for the same CheXpert 8x200 candidate images (see Appendix D for details). At test time, for each query we encode its text with the learned text encoder fu and then retrieve from candidate images in a similar way. This evaluation not only evaluates the quality of the learned image representations, but also the alignment between the text representations and the image representations. We again use Precision@k metrics where k = 5, 10, 100. # 4.3. Baseline Methods We compare ConVIRT against the following standard or competitive initialization methods: • Random Init.: For all tasks we initialize the ResNet50 with its default random initial- ization. • ImageNet Init.: We use CNN weights pretrained on ImageNet (Russakovsky et al., 2015), which remains a dominant initialization approach for medical imaging work (Raghu et al., 2019). • Caption-LSTM: We further pretrain the ImageNet-initialized CNN weights with an image captioning task using the standard CNN-LSTM with attention model (Xu et al., 2015). We train the model to decode the paired medical report text from the encoded image representations. Compared to the random or ImageNet initializations, this is an “in-domain” initialization baseline which uses the paired text data for representation learning. • Caption-Transformer: We use a CNN-Transformer-based captioning model (Cornia et al., 2020) for caption-based pretraining, which recently achieves state-of-the-art results on the COCO image captioning benchmark (Lin et al., 2014). 9 Contrastive Learning of Medical Visual Representations from Paired Images and Text • Contrastive-Binary-Loss: This baseline differs from ConVIRT by contrasting the paired image and text representations with a binary classification head, as is widely done in visual-linguistic pretraining work (Tan and Bansal, 2019; Su et al., 2020). For each input pair, we first project encoder outputs hv and hu into the same dimension with linear layers, concatenate them, and use a MLP network to predict a binary probability of whether the input is a real or a “fake” pair, which we train with a binary cross-entropy loss. During training, for each (xv, xu) pair in the training set, we construct a “fake” pair by replacing xu with a randomly sampled one from the dataset. We expect that the binary classification task requires the encoder to learn reasonable representations of the input images, and therefore is a stronger in-domain initialization baseline. For fair comparison, for all baselines that require paired image-text data, we use the same datasets as in our contrastive pretraining. For the captioning-based methods, we always use the model checkpoints that achieve the best CIDEr score (Vedantam et al., 2015) on a held-out validation set. # 5. Results # 5.1. Classification Tasks Linear Classification. We present all linear classification results for the four tasks in Table 1(a). We find that compared to random initialization, ImageNet initialization provides markedly better representations, despite pretrained on a very different domain of images; in- domain image initialization methods that use paired image-text data further improve over ImageNet initialization in almost all settings. Among the in-domain initialization methods, our proposed ConVIRT pretraining achieves the best overall results in all settings. Notably, we find on three out of the four tasks, with only 1% training data ConVIRT is able to achieve classification results better than the default ImageNet initialization with 100% training data, highlighting the high quality of the learned representations from ConVIRT. Fine-tuning. We show the fine-tuning evaluation results in Table 1(b). Similar to the linear setting, we find that: 1) ImageNet initialization is again better than random initial- ization with smaller margins; 2) all in-domain initialization methods are better than the popular ImageNet initialization in most settings; and 3) our proposed ConVIRT pretraining again achieves the best overall results in 10 out of the 11 settings, with the exception of the CheXpert dataset with all training data used, where the result of ConVIRT is similar to that of the Caption-Transformer result. Most notably, on all datasets, with only 10% labeled training data ConVIRT achieves classification results that are better or close to the ImageNet initialization with 100% training data results. We also notice that our conclusion of using ImageNet versus random initialization is different from (Raghu et al., 2019): while they showed comparable results from the two strategies, we find that using ImageNet initialization is still superior than random initial- ization in most results, justifying its popularity. Upon closer examination, we conjecture that this is likely due to under-optimization of their models: while our ResNet50 with ran- dom initialization achieves an average AUC of 85.8 on the CheXpert dataset, their ResNet50 model only achieved 83.5 AUC on the same evaluation set. 10 # Contrastive Learning of Medical Visual Representations from Paired Images and Text # (a) Linear classification Method 1% RSNA (AUC) 10% all CheXpert (AUC) all 10% 1% COVIDx (Accu.) 10% all MURA (AUC) 10% 1% General initialization methods Random Init. ImageNet Init. 55.0 82.8 67.3 85.4 72.3 86.9 58.2 75.7 63.7 79.7 66.2 81.0 69.2 83.7 73.5 88.6 50.9 63.8 56.8 74.1 In-domain initialization methods 84.8 Caption-Transformer 89.8 Caption-LSTM 88.9 Contrastive-Binary-Loss 90.7 ConVIRT (Ours) 87.5 90.8 90.5 91.7 89.5 91.3 90.8 92.1 77.2 85.2 84.5 85.9 82.6 85.3 85.6 86.8 83.9 86.2 85.8 87.3 80.0 84.5 80.5 85.9 89.0 91.7 90.8 91.7 66.5 75.2 76.8 81.2 76.3 81.5 81.7 85.1 all 62.0 79.0 81.8 84.1 85.3 87.6 Method 1% RSNA (AUC) 10% all CheXpert (AUC) all 10% 1% COVIDx (Accu.) 10% all MURA (AUC) 10% 1% General initialization methods Random Init. ImageNet Init. 71.9 83.1 82.2 87.3 88.5 90.8 70.4 80.1 81.1 84.8 85.8 87.6 75.4 84.4 87.7 90.3 56.8 72.1 61.6 81.8 In-domain initialization methods 86.3 Caption-Transformer 87.2 Caption-LSTM 87.7 Contrastive-Binary-Loss ConVIRT (Ours) 88.8 89.2 88.0 89.9 91.5 92.1 91.0 91.2 92.7 81.5 83.5 86.2 87.0 86.4 85.8 86.1 88.1 88.2 87.8 87.7 88.1 88.3 83.8 89.5 90.3 92.3 90.8 90.5 92.4 75.2 78.7 80.6 81.3 83.2 83.3 84.0 86.5 all 79.1 87.0 87.6 87.8 88.4 89.0 Table 1: Results for the medical image classification tasks: (a) linear classification; (b) fine-tuning setting. All results are averaged over 5 independent models. Best results for each setting are in boldface. COVIDx 1% setting is omitted due to the scarcity of labels in COVIDx. # 5.2. Retrieval Tasks We present the zero-shot image-image and text-image retrieval results in Table 2. For the image-image retrieval setting, we present additional results from fine-tuning our pretrained model on all CheXpert training data, and use them as “upper bounds” of the results ob- tained from the use of supervised labels. We find that: 1) using ImageNet weights in a zero-shot image retrieval setting is only better than random guess by small margins; 2) all in-domain pretrained CNN weights achieve much better retrieval performance than Image- Net weights; and 3) our proposed ConVIRT pretraining achieves the best overall retrieval results on all metrics. While Contrastive-Binary-Loss performs notably better than other baselines in image-image retrieval, its text-image retrieval results are far from ConVIRT pretraining. We conjecture that the lack of an explicit similarity-based loss function in the Contrastive-Binary-Loss baseline results in misaligned representations in the image and text space, leading to poor results in text-image retrieval. To understand how well ConVIRT pretraining helps separate images from different ab- normality categories in its encoding space, in Figure 3 we present t-SNE plots (Maaten and Hinton, 2008) of candidate images in the CheXpert 8x200 dataset for five selected categories, from the ImageNet pretrained CNN encoder and the ConVIRT pretrained encoder. It is worth noting that clustering images in our setting is much more challenging than that in 11 # Contrastive Learning of Medical Visual Representations from Paired Images and Text Method Image-Image Retrieval Prec@10 Prec@5 Prec@50 Text-Image Retrieval Prec@10 Prec@5 Prec@50 Random ImageNet 12.5 14.8 12.5 14.4 12.5 15.0 12.5 – 12.5 – 12.5 – In-domain initialization methods Caption-Transformer Caption-LSTM Contrastive-Binary-Loss ConVIRT (Ours) 29.8 34.8 38.8 45.0 28.0 32.9 36.6 42.9 23.0 28.1 29.7 35.7 – – 15.5 60.0 – – 14.5 57.5 – – 13.7 48.8 Fine-tuned ConVIRT + CheXpert Supervised 56.8 56.3 48.9 – – – Table 2: Zero-shot image-image and text-image retrieval results on the CheXpert 8×200 datasets. Random shows results from a random guess; ConVIRT + CheXpert Supervised shows results from further fine-tuning the pretrained weights with supervised training data. Text-image retrieval results are not obtained for some methods due to the lack of text encoders. (a) ImageNet Pretraining (b) ConVIRT Pretraining Figure 3: t-SNE visualizations of encoded image representations from different pretraining methods. the general object classification setting due to the high inter-class similarity of the medical images. Nevertheless we find that ConVIRT pretraining achieves a better clustering of the images in the t-SNE plots. # 6. Analysis and Discussion Comparisons to Image-only Contrastive Learning. ConVIRT shows superior results against baselines in evaluation, but an important question remains as to how it compares against existing image-only contrastive learning methods. We study this by running two popular such methods, SimCLR (Chen et al., 2020a) and MoCo v2 (Chen et al., 2020b), on the same collection of images that we used in our pretraining. We present the results in Table 3 and include training details in Appendix E. We find that compared to ImageNet initialization, both contrastive methods lead to marginal to moderate improvements on the 12 # Contrastive Learning of Medical Visual Representations from Paired Images and Text Method RSNA CheXpert (Linear, 1%) (Linear, 1%) ImageNet 82.8 75.7 14.4 SimCLR (Chen et al., 2020a) MoCo v2 (Chen et al., 2020b) 86.3 86.6 77.4 81.3 17.6 20.6 ConVIRT 90.7 85.9 42.9 Table 3: Comparisons of ConVIRT to image-only contrastive learning. For RSNA and CheXpert we show the AUC under linear classification with 1% training data. ImageNet SimCLR MoCo v2 ConVIRT Original _ ae ES ie ae —_ pee age ae *e f <4 Edema i al Pleural Effusion : , Figure 4: Saliency maps on sampled images for 4 abnormality categories in the CheXpert dataset. For each image we present maps for ImageNet, SimCLR, MoCo v2 and our Con- VIRT initializations. Ground truth regions that are indicative of the abnormalities are shown as red boxes in the original images on the right, and are seen to most closely match the regions found by ConVIRT. classification and retrieval tasks. However, our training strategy substantially outperforms both methods on all tasks, demonstrating its effective use of information from the paired text data. This efficient use of data is critical to the healthcare domain because medical data are often limited in size but come with paired text data and even user metadata. 13 # Contrastive Learning of Medical Visual Representations from Paired Images and Text 45 60 2.8 90.5 2.6 90 35 50 2.4 89.5 25 40 0 100 200 −2.8 −2.6 −2.4 −2.8 −2.6 −2.4 −2.8 −2.6 −2.4 (a) Pretraining Loss (b) RSNA Linear (1%, AUC) (c) Image-image (P@10) (d) Text-image (P@10) Figure 5: (a) shows pretraining validation loss at different epochs; (b)-(d) shows correlation between the pretraining loss and the performance of three end tasks. For (a) the x-axis shows the training epoch number, and for (b)-(d) the x-axis shows the negative value of the pretraining loss (i.e., −L) on a held-out validation set. To understand the representational difference that has led to this difference in per- formance, for all four initialization methods, we visualize in Figure 4 the saliency maps (Simonyan et al., 2014) corresponding to the correct class on sampled images from the CheXpert dataset. Models for all initialization methods are trained with 1% CheXpert training data under the linear classification setting (with pretrained CNN weights frozen). We find that ImageNet pretraining has led to models that focus on trivial visual features that are mostly irrelevant to the task, and that the model with ConVIRT pretrained weights has focused on much more relevant areas than those with SimCLR and MoCo v2 pretrain- ing, suggesting more effective representation learning. For example, for atelectasis, while the ConVIRT model has correctly focused on the bottom of the lung regions, the SimCLR model has much more scattered focus and the MoCo model has incorrectly focused on the heart region. Correlation Between Contrastive Loss and End Task Performance. To under- stand the relation between a model’s performance on the ConVIRT pretraining task and its performance on the downstream tasks, we ran an analysis where for every 5 epochs during the pretraining, we transferred the pretrained checkpoint to the downstream tasks and evaluate its performance. The pretraining was run for a total of 200 epochs, and 40 points were obtained with varying validation loss and end task results. Figure 5 presents the results of the models’ validation loss on the pretraining task, and its achieved perfor- mance on the RSNA 1% data linear evaluation and the two retrieval tasks. For all three tasks, we find a clear positive correlation between the pretraining performance and the end task performance. This corroborates that by learning with the ConVIRT objectives, the image encoder learns gradually improved representations for the end tasks, and suggests that further improvement on the pretraining task may have positive impact on the end task performance. Hyperparameter Analysis. We run experiments to study the impact of hyperparame- ters, and have the following observations. First of all, similar to previous work on image-only contrastive learning (Chen et al., 2020a; He et al., 2020), the pretraining results are most 14 # Contrastive Learning of Medical Visual Representations from Paired Images and Text Settings RSNA Linear (1%, AUC) Image-Image (Prec@10) Text-Image (Prec@10) ConVIRT (default) 90.7 42.9 57.5 τ = 0.01 τ = 1 90.7 89.6 40.5 25.0 21.0 31.0 bs = 16 bs = 128 90.3 90.3 40.0 39.3 55.8 50.3 linear proj. 90.6 40.8 55.8 Table 4: Evaluation results with different hyperparameters, for the RSNA 1% data linear evaluation, image-image retrieval and text-image retrieval tasks. bs represents batch size and linear proj. represents using linear projection layers for gv and gu. Our default model uses τ = 0.1, bs = 32 and non-linear projections. sensitive to the choice of the temperature value τ . As shown in Table 4, using a temperature much lower than the ideal value (τ = 0.01) hurts the retrieval results, and a temperature much larger (τ = 1) notably hurts the performance on all tasks. Second, unlike previous work, changing batch size does not lead to substantial change in the classification results. At last, replacing the non-linear projection heads in gv and gu with linear layers hurts the retrieval results moderately, suggesting worse representations. However, this is again not reflected notably in the RSNA classification results. Limitations. This work mainly focuses on comparing ConVIRT against conventional ImageNet initialization, image captioning-based initialization, and image-only contrastive learning approaches including SimCLR and MoCo to demonstrate the data efficiency and effectiveness of image-text pretraining. We did not compare our method against relevant subsequent studies that extended ConVIRT, such as LoVT (M¨uller et al., 2021) or GloRIA (Huang et al., 2021), mainly because such comparisons are included in these studies. # 7. Conclusion We presented ConVIRT, an unsupervised method for learning medical visual representa- tions from paired descriptive text. Our method relies on contrasting the image repre- sentations with the paired descriptive text via a bidirectional objective between the two modalities. On 4 medical image classification tasks and 2 image retrieval tasks, ConVIRT outperformed other strong in-domain initialization methods, and led to representations with notably higher quality. Compared to ImageNet pretraining, ConVIRT is able to achieve the same level of classification accuracy with an order of magnitude less labeled data. This is especially critical for the healthcare domain where data sparsity is an important issue, and the innovative cross-modality pretraining in ConVIRT is extensible to consider other modalities of data in this domain. We thus hope that ConVIRT continues inspiring future work that makes more efficient use of multi-modal data for medical image understanding. 15 Contrastive Learning of Medical Visual Representations from Paired Images and Text # References Michael David Abr`amoff, Yiyue Lou, Ali Erginay, Warren Clarida, Ryan Amelon, James C Folk, and Meindert Niemeijer. Improved automated detection of diabetic retinopathy on a publicly available dataset through integration of deep learning. Investigative Ophthal- mology & Visual Science, 57(13):5200–5206, 2016. Emily Alsentzer, John Murphy, William Boag, Wei-Hung Weng, Di Jindi, Tristan Naumann, and Matthew McDermott. Publicly available clinical BERT embeddings. In Proceedings of the 2nd Clinical Natural Language Processing Workshop, 2019. Shekoofeh Azizi, Basil Mustafa, Fiona Ryan, Zachary Beaver, Jan Freyberg, Jonathan Deaton, Aaron Loh, Alan Karthikesalingam, Simon Kornblith, Ting Chen, et al. Big self- supervised models advance medical image classification. In Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), 2021. Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton. A simple frame- work for contrastive learning of visual representations. In International Conference on Machine Learning (ICML), 2020a. Xinlei Chen, Haoqi Fan, Ross Girshick, and Kaiming He. Improved baselines with momen- tum contrastive learning. arXiv preprint arXiv:2003.04297, 2020b. Marcella Cornia, Matteo Stefanini, Lorenzo Baraldi, and Rita Cucchiara. Meshed-memory Transformer for image captioning. In Proceedings of the IEEE/CVF Conference on Com- puter Vision and Pattern Recognition (CVPR), 2020. Jeffrey De Fauw, Joseph R Ledsam, Bernardino Romera-Paredes, Stanislav Nikolov, Nenad Tomasev, Sam Blackwell, Harry Askham, Xavier Glorot, Brendan O’Donoghue, Daniel Visentin, et al. Clinically applicable deep learning for diagnosis and referral in retinal disease. Nature Medicine, 24(9):1342–1350, 2018. Dina Demner-Fushman, Marc D Kohli, Marc B Rosenman, Sonya E Shooshan, Laritza Rodriguez, Sameer Antani, George R Thoma, and Clement J McDonald. Preparing a collection of radiology examinations for distribution and retrieval. Journal of the Amer- ican Medical Informatics Association, 23(2):304–310, 2016. Karan Desai and Justin Johnson. VirTex: Learning visual representations from textual annotations. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2021. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training In Proceedings of the of deep bidirectional transformers for language understanding. 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (NAACL-HLT), 2019. Sedigheh Eslami, Gerard de Melo, and Christoph Meinel. Does CLIP benefit visual question answering in the medical domain as much as it does in the general domain? arXiv preprint arXiv:2112.13906, 2021. 16 Contrastive Learning of Medical Visual Representations from Paired Images and Text Andre Esteva, Brett Kuprel, Roberto A Novoa, Justin Ko, Susan M Swetter, Helen M Blau, and Sebastian Thrun. Dermatologist-level classification of skin cancer with deep neural networks. Nature, 542(7639):115–118, 2017. Jean-Bastien Grill, Florian Strub, Florent Altch´e, Corentin Tallec, Pierre Richemond, Elena Buchatskaya, Carl Doersch, Bernardo Avila Pires, Zhaohan Guo, Mohammad Ghesh- laghi Azar, Bilal Piot, Koray Kavukcuoglu, Remi Munos, and Michal Valko. Bootstrap In Advances in Neural your own latent: A new approach to self-supervised learning. Information Processing Systems, 2020. Varun Gulshan, Lily Peng, Marc Coram, Martin C Stumpe, Derek Wu, Arunacha- lam Narayanaswamy, Subhashini Venugopalan, Kasumi Widner, Tom Madams, Jorge Cuadros, et al. Development and validation of a deep learning algorithm for detection of diabetic retinopathy in retinal fundus photographs. JAMA, 316(22):2402–2410, 2016. Tanmay Gupta, Arash Vahdat, Gal Chechik, Xiaodong Yang, Jan Kautz, and Derek Hoiem. Contrastive learning for weakly supervised phrase grounding. In Proceedings of the 16th European Conference on Computer Vision (ECCV), 2020. Yan Han, Chongyan Chen, Ahmed Tewfik, Ying Ding, and Yifan Peng. Pneumonia detec- tion on chest x-ray using radiomic features and contrastive learning. In 2021 IEEE 18th International Symposium on Biomedical Imaging (ISBI). IEEE, 2021. Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for In Proceedings of the IEEE Conference on Computer Vision and image recognition. Pattern Recognition (CVPR), 2016. Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, and Ross Girshick. Momentum contrast for unsupervised visual representation learning. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2020. Lars Heiliger, Anjany Sekuboyina, Bjoern Menze, Jan Egger, and Jens Kleesiek. Beyond medical imaging: A review of multimodal deep learning in radiology. TechRxiv preprint, 2022. Olivier J H´enaff, Aravind Srinivas, Jeffrey De Fauw, Ali Razavi, Carl Doersch, SM Eslami, and Aaron van den Oord. Data-efficient image recognition with contrastive predictive coding. In International Conference on Machine Learning (ICML), 2020. Shih-Cheng Huang, Liyue Shen, Matthew P Lungren, and Serena Yeung. GLoRIA: A mul- timodal global-local representation learning framework for label-efficient medical image In Proceedings of the IEEE/CVF International Conference on Computer recognition. Vision (ICCV), 2021. Gabriel Ilharco, Rowan Zellers, Ali Farhadi, and Hannaneh Hajishirzi. Probing contextual language models for common ground with visual representations. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (NAACL-HLT), 2021. 17 Contrastive Learning of Medical Visual Representations from Paired Images and Text Jeremy Irvin, Pranav Rajpurkar, Michael Ko, Yifan Yu, Silviana Ciurea-Ilcus, Chris Chute, Henrik Marklund, Behzad Haghgoo, Robyn Ball, Katie Shpanskaya, et al. CheXpert: In A large chest radiograph dataset with uncertainty labels and expert comparison. Proceedings of the AAAI Conference on Artificial Intelligence, 2019. Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc Le, Yun- Hsuan Sung, Zhen Li, and Tom Duerig. Scaling up visual and vision-language repre- sentation learning with noisy text supervision. In Proceedings of the 38th International Conference on Machine Learning, 2021. Baoyu Jing, Pengtao Xie, and Eric Xing. On the automatic generation of medical imaging reports. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (ACL), 2018. Alistair EW Johnson, Tom J Pollard, Seth J Berkowitz, Nathaniel R Greenbaum, Matthew P Lungren, Chih-ying Deng, Roger G Mark, and Steven Horng. MIMIC-CXR, a de-identified publicly available database of chest radiographs with free-text reports. Scientific Data, 6, 2019. Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In The 2015 International Conference for Learning Representations, 2015. Ruizhi Liao, Daniel Moyer, Miriam Cha, Keegan Quigley, Seth Berkowitz, Steven Horng, Polina Golland, and William M Wells. Multimodal representation learning via maxi- In International Conference on Medical Image mization of local mutual information. Computing and Computer-Assisted Intervention, 2021. Tsung-Yi Lin, Michael Maire, Serge Belongie, James Hays, Pietro Perona, Deva Ramanan, Piotr Doll´ar, and C Lawrence Zitnick. Microsoft COCO: Common objects in context. In European Conference on Computer Vision (ECCV), 2014. Guanxiong Liu, Tzu-Ming Harry Hsu, Matthew McDermott, Willie Boag, Wei-Hung Weng, Peter Szolovits, and Marzyeh Ghassemi. Clinically accurate chest X-ray report generation. In Machine Learning for Healthcare Conference, 2019. Jiasen Lu, Dhruv Batra, Devi Parikh, and Stefan Lee. ViLBERT: Pretraining task-agnostic visiolinguistic representations for vision-and-language tasks. In Advances in Neural In- formation Processing Systems, 2019. Laurens van der Maaten and Geoffrey Hinton. Visualizing data using t-SNE. Journal of Machine Learning Research, 9(Nov):2579–2605, 2008. Christopher D. Manning, Mihai Surdeanu, John Bauer, Jenny Finkel, Steven J. Bethard, and David McClosky. The Stanford CoreNLP natural language processing toolkit. In Association for Computational Linguistics (ACL) System Demonstrations, 2014. Yasuhide Miura, Yuhao Zhang, Curtis P. Langlotz, and Dan Jurafsky. Improving factual completeness and consistency of image-to-text radiology report generation. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies (NAACL-HLT), 2021. 18 Contrastive Learning of Medical Visual Representations from Paired Images and Text Philip M¨uller, Georgios Kaissis, Congyu Zou, and Daniel R¨uckert. Joint learning of localized representations from medical images and reports. arXiv preprint arXiv:2112.02889, 2021. Aaron van den Oord, Yazhe Li, and Oriol Vinyals. Representation learning with contrastive predictive coding. arXiv preprint arXiv:1807.03748, 2018. Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual models from natural language supervision. In International Conference on Machine Learning, 2021. Maithra Raghu, Chiyuan Zhang, Jon Kleinberg, and Samy Bengio. Transfusion: Under- standing transfer learning for medical imaging. In Advances in Neural Information Pro- cessing Systems, 2019. Pranav Rajpurkar, Jeremy Irvin, Aarti Bagul, Daisy Ding, Tony Duan, Hershel Mehta, Brandon Yang, Kaylie Zhu, Dillon Laird, Robyn L Ball, et al. MURA: Large dataset for abnormality detection in musculoskeletal radiographs. In 1st Conference on Medical Imaging with Deep Learning (MIDL), 2018a. Pranav Rajpurkar, Jeremy Irvin, Robyn L Ball, Kaylie Zhu, Brandon Yang, Hershel Mehta, Tony Duan, Daisy Ding, Aarti Bagul, Curtis P Langlotz, et al. Deep learning for chest ra- diograph diagnosis: A retrospective comparison of the CheXNeXt algorithm to practicing radiologists. PLoS Medicine, 15(11):e1002686, 2018b. Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhi- heng Huang, Andrej Karpathy, Aditya Khosla, Michael Bernstein, et al. ImageNet large International Journal of Computer Vision, 115(3): scale visual recognition challenge. 211–252, 2015. Mert Bulent Sariyildiz, Julien Perez, and Diane Larlus. Learning visual representations with caption annotations. In Proceedings of the 16th European Conference on Computer Vision (ECCV), 2020. George Shih, Carol C Wu, Safwan S Halabi, Marc D Kohli, Luciano M Prevedello, Tessa S Cook, Arjun Sharma, Judith K Amorosa, Veronica Arteaga, Maya Galperin-Aizenberg, et al. Augmenting the National Institutes of Health chest radiograph dataset with expert annotations of possible pneumonia. Radiology: Artificial Intelligence, 1(1):e180041, 2019. Karen Simonyan, Andrea Vedaldi, and Andrew Zisserman. Deep inside convolutional net- works: Visualising image classification models and saliency maps. In ICLR Workshop, 2014. Hari Sowrirajan, Jingbo Yang, Andrew Y Ng, and Pranav Rajpurkar. MoCo pretraining improves representation and transferability of chest X-ray models. In Medical Imaging with Deep Learning, pages 728–744. PMLR, 2021. Weijie Su, Xizhou Zhu, Yue Cao, Bin Li, Lewei Lu, Furu Wei, and Jifeng Dai. VL-BERT: Pre-training of generic visual-linguistic representations. In International Conference on Learning Representations (ICLR), 2020. 19 Contrastive Learning of Medical Visual Representations from Paired Images and Text Hao Tan and Mohit Bansal. LXMERT: Learning cross-modality encoder representations from transformers. In Proceedings of the 2019 Conference on Empirical Methods in Natu- ral Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), 2019. Ramakrishna Vedantam, C Lawrence Zitnick, and Devi Parikh. CIDEr: Consensus-based image description evaluation. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2015. Yen Nhi Truong Vu, Richard Wang, Niranjan Balachandar, Can Liu, Andrew Y Ng, and Pranav Rajpurkar. MedAug: Contrastive learning leveraging patient metadata improves representations for chest x-ray interpretation. In Machine Learning for Healthcare Con- ference, 2021. Linda Wang and Alexander Wong. COVID-Net: A tailored deep convolutional neural network design for detection of COVID-19 cases from chest X-ray images. arXiv preprint arXiv:2003.09871, 2020. Xiaosong Wang, Yifan Peng, Le Lu, Zhiyong Lu, Mohammadhadi Bagheri, and Ronald M Summers. ChestX-ray8: Hospital-scale chest X-ray database and benchmarks on weakly- supervised classification and localization of common thorax diseases. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017. Xiaosong Wang, Yifan Peng, Le Lu, Zhiyong Lu, and Ronald M Summers. TieNet: Text- image embedding network for common thorax disease classification and reporting in chest X-rays. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recog- nition (CVPR), 2018. Xiaosong Wang, Ziyue Xu, Leo Tam, Dong Yang, and Daguang Xu. Self-supervised image- text pre-training with mixed data in chest x-rays. arXiv preprint arXiv:2103.16022, 2021. Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Clement Delangue, An- thony Moi, Pierric Cistac, Tim Rault, Remi Louf, Morgan Funtowicz, Joe Davison, Sam Shleifer, Patrick von Platen, Clara Ma, Yacine Jernite, Julien Plu, Canwen Xu, Teven Le Scao, Sylvain Gugger, Mariama Drame, Quentin Lhoest, and Alexander Rush. Transformers: State-of-the-art natural language processing. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP): System Demonstrations, 2020. Kelvin Xu, Jimmy Ba, Ryan Kiros, Kyunghyun Cho, Aaron Courville, Ruslan Salakhudinov, Rich Zemel, and Yoshua Bengio. Show, attend and tell: Neural image caption generation with visual attention. In International Conference on Machine Learning (ICML), 2015. Chengxi Zang and Fei Wang. Scehr: Supervised contrastive learning for clinical risk pre- diction using electronic health records. arXiv preprint arXiv:2110.04943, 2021. 20 Contrastive Learning of Medical Visual Representations from Paired Images and Text # Appendix A. Model Implementation and Pretraining Details Dataset Preprocessing. For the MIMIC-CXR chest radiograph dataset, we use the publicly available JPG version of it.2 For both the MIMIC-CXR chest dataset and the Rhode Island Hospital bone image datasets, we resize the image files to have a size of 256 on the larger side. For the textual radiology report data, we first tokenize all reports with the default English tokenizer in version 4.0.0 of the CoreNLP library (Manning et al., 2014). Next, we keep only the Findings and Impression sections and remove all other sections. We remove all image-text pairings from the dataset where the text section is empty or has less than 3 tokens. This preprocessing procedure gives us about 217k total image-text pairs for pretraining our chest image encoder and 48k total pairs for pretraining our bone image encoder. Image and Text Encoders. For the image encoder, we use the standard ResNet50 implementation provided by the torchvision library. For the text encoder, we use the BERT base encoder offered by the Transformers library (Wolf et al., 2020) and initialize it with the ClinicalBERT model (Alsentzer et al., 2019) pretrained on the MIMIC clinical notes. We also experimented with training a specialized BERT encoder on a large collection of radiology notes but found that it made no substantial difference in the pretraining results. At pretraining time we freeze the embeddings and the first 6 layers of this BERT encoder, and only fine-tune the last 6 layers for our contrastive task. Other Hyperparameters. For contrastive learning, we use projection layers with an output dimension d = 512, a temperature value τ = 0.1, a loss weight λ = 0.75. These hyperparameter settings are obtained by comparing the linear evaluation validation scores on the RSNA image classification task with the pretrained ResNet50 weights. For the image transformation family T , we adopt the implementations offered by the torchvision library.3 We apply random cropping with a ratio sampled from [0.6, 1.0]; horizontal flipping with p = 0.5; affine transformation with a degree sampled from [−20, 20], max horizontal and vertical translation fractions of 0.1, and a scaling factor sampled from [0.95, 1.05]; color jittering with brightness and contrast adjustment ratios sampled from [0.6, 1.4]; and Gaussian blur with σ ∈ [0.1, 3.0]. All images are resized to 224×224 after the transformation tv is applied. Limited by computational resources, we arrive at these image transformation parameters via preliminary experiments rather than a systematic search. Pretraining Details. At pretraining time, for each dataset, we randomly sample 5k image-text pairs to form a held-out validation set. We we use the Adam optimizer (Kingma and Ba, 2015) with an initial learning rate of 1e-4 and weight decay of 1e-6. We initialize the image encoder with ImageNet pretrained weights at the beginning of pretraining, and use a fixed batch size of 32. We calculate the validation loss every 5000 steps, and if the validation loss does not decrease after 5 straight evaluation runs, we anneal the learning rate by a factor of 0.5. We stop pretraining after 200 evaluation runs, and save the model checkpoint that achieves the lowest validation loss. For efficiency, we employ mixed-precision training, and for reference, the whole pretraining run on the MIMIC-CXR dataset took about 3 days on a single Titan RTX GPU card. 2. https://physionet.org/content/mimic-cxr-jpg/2.0.0/ 3. https://github.com/pytorch/vision 21 Contrastive Learning of Medical Visual Representations from Paired Images and Text # Appendix B. Image Classification Experiments We prepared and used the 4 image classification datasets following the procedures below: 1. RSNA Pneumonia Detection (Wang et al., 2017; Shih et al., 2019): we used the orig- inal version of this dataset available at its Kaggle page,4 which contains 25184/1500/3000 annotated images in its training/validation/test sets, respectively. 2. CheXpert image classification (Irvin et al., 2019): we downloaded the original version of this dataset from its official website.5 Since the original expert-labeled test set of this dataset is hidden and not included as part of the release, we instead followed Raghu et al. (2019) and used the original expert-labeled validation set as our test set, and randomly sampled 5000 images from the original training set for validation purpose. The resulting dataset contains 218414/5000/234 images in each split. 3. COVIDx image classification (Wang and Wong, 2020): we prepared this dataset fol- lowing the scripts provided by its authors.6 We used the version 4 of this dataset, the latest version at the time of this work. We additionally randomly sampled 300 images from the training set for validation, resulting in a dataset with 13598/300/300 images in each split. 4. MURA bony abnormality detection (Rajpurkar et al., 2018a): we downloaded the orig- inal version of this dataset from its website.7 Similar to the CheXpert dataset, we again used the original validation set as our test set, and randomly sampled 10% images from the training set for validation, resulting in a dataset with 33078/3730/3197 images in each split. Different from the other 3 datasets, the MURA dataset uses patient-level evaluation, meaning that the prediction results from different images of the same patient needs to be aggregated to produce a final prediction for the patient, which is then scored against the gold patient label. We therefore followed Rajpurkar et al. (2018a) and at test time aggregated result for a patient by averaging the predicted probabilities from multiple images. Classification Model Training Details. For all models that require ImageNet pre- trained initialization, we use the pretrained weights from torchvision, which achieves an ImageNet top-5 error rate of 7.13%. For all datasets, we first zero-pad the input image to be square, and then resize it to be 224×224. For training, we use the Adam optimizer with an initial learning rate of 1e-3 for the COVIDx task and 1e-4 for the other three tasks. We additionally apply a weight decay of 1e-6 and a dropout before the last classification layer with p = 0.2 in all tasks. All classification models are trained with a batch size of 64. In the fine-tuning evaluation setting, we first “warmup” the classification head by freezing the CNN weights and only training the classification head with a learning rate of 1e-3 for 200 steps, after which we unfreeze the CNN weights and fine-tune the entire network together. Validation score is obtained after each epoch of training and we anneal the learning rate 4. https://www.kaggle.com/c/rsna-pneumonia-detection-challenge 5. https://stanfordmlgroup.github.io/competitions/chexpert/ 6. https://github.com/lindawangg/COVID-Net 7. https://stanfordmlgroup.github.io/competitions/mura/ 22 Contrastive Learning of Medical Visual Representations from Paired Images and Text by a factor of 0.5 if the validation score is not improved after 3 epochs. The training is stopped after no validation improvement is observed for 10 straight epochs, at which point the model checkpoint with the highest validation score is evaluated on the test set. Image Category Example Textual Query Atelectasis Cardiomegaly Edema Fracture Pleural Effusion The pleural space is partially filled with fluid. Pneumonia Pneumothorax No Finding Platelike opacity likely represents atelectasis. The cardiac silhouette is enlarged. The presence of hazy opacity suggests interstitial pulmonary edema. A cortical step off indicates the presence of a fracture. Table 5: Example textual queries for each of the 8 categories in the text-image retrieval task. # Appendix C. Image-image Retrieval Dataset Collection We create the CheXpert 8x200 Retrieval Dataset with 8 different abnormality categories commonly found in Chest radiograph images, including atelectasis, cardiomegaly, edema, fracture, pleural effusion, pneumonia, pneumothorax and a special no finding category indi- cating that no obvious abnormality is found in the image. We create the dataset by reusing existing rule-labeled annotations in the CheXpert dataset (Irvin et al., 2019) and additional expert annotations. To create the candidate images for a category label @, we go through all images in the CheXpert training set, and keep an image as a candidate image if only its label for @ is positive and all other categories negative. We only include images with this “exclusive positivity” as candidate images, mainly to avoid confounding results between categories in retrieval evaluation. To create the query images for a category @, we again first pre-select 50 exclusively positive images for this category in the CheXpert training set (with all candidate images excluded). Next, we ask a board-certified radiologist to examine each of the 50 images, and exclude images that: 1) might indicate additional abnormalities other than /, 2) have uncommon color or contrast distortions in the image, or 3) are not well posed during the capture of the image. This procedure is mainly to avoid including query images that have uncommon features and may therefore bias the retrieval evaluation results. At the end, we aggregate the annotation results from the radiologist and keep 10 query images for each abnormality category. # Appendix D. Text-image Retrieval Dataset Collection For the text-image retrieval dataset, we first reuse all candidate images from the CheXpert 8×200 image-image retrieval dataset described above, with 200 images for each of 8 cate- 23 Contrastive Learning of Medical Visual Representations from Paired Images and Text gories. To create the textual queries for each abnormality category, we ask a board-certified radiologist to write at least 5 different sentences that he will use to describe this abnormal- ity in radiology reporting. We additionally set the following requirements: 1) the sentences must describe the category with no ambiguity and must not include other categories; 2) the sentences must be diverse from each other; and 3) the sentences should not include very specific anatomic locations or rare clinical observations. At the end, we aggregate the results and keep 5 textual queries for each abnormality category. For reference, we present example textual queries in Table 5. # Appendix E. Experiments on Image-Only Contrastive Learning Methods We run experiments with two popular image-only contrastive visual representation learning methods: SimCLR (Chen et al., 2020a) and MoCo v2 (Chen et al., 2020b). For a fair comparison, in both experiments we use the exact same set of images from the MIMIC- CXR dataset that we use in the pretraining of our method and the baselines. Our settings for each method are: • SimCLR: We use the open PyTorch implementation available at https://github.com/ sthalles/SimCLR. For image encoder we use ResNet50. We use cosine similarity in the loss function, set the temperature value to 0.1 and set the output dimension to 128. We use the default image augmentation functions in the paper except for the color jittering transformation where we set the saturation and hue adjustment to 0 due to the monochrome nature of our medical images. For training, we use the Adam optimizer with an initial learning rate of 3e-4 and weight decay of 1e-4. We set batch size to 128 and run training on a single GPU card for 100 epochs, as we find that increasing the batch size or number of epochs does not lead to improved results. We use the default settings for all other parameters. • MoCo v2: We use the authors’ PyTorch implementation available at https://github. com/facebookresearch/moco. For image encoder we use ResNet50. We follow the de- fault MoCo v2 setting and use a temperature value of 0.07 and an output dimension of 128. Similarly, we adopt the default image augmentation functions except for the color jittering transformation where we set the saturation and hue adjustment to 0. For train- ing, we use the SGD optimizer with a learning rate of 0.0075 and weight decay of 1e-4. We use a batch size of 64 and a queue size of 4096, and run parallel training on two GPU cards for 100 epochs, as we find that further increasing the batch size or number of epochs does not lead to improved results. During training, we anneal the learning rate by a factor of 0.1 at the 60th and 80th epochs. 24
Title: Improving Code Generation by Training with Natural Language Feedback: Summary: The potential for pre-trained large language models (LLMs) to use natural language feedback at inference time has been an exciting recent development. We build upon this observation by formalizing an algorithm for learning from natural language feedback at training time instead, which we call Imitation learning from Language Feedback (ILF). ILF requires only a small amount of human-written feedback during training and does not require the same feedback at test time, making it both user-friendly and sample-efficient. We further show that ILF can be seen as a form of minimizing the KL divergence to the ground truth distribution and demonstrate a proof-of-concept on a neural program synthesis task. We use ILF to improve a Codegen-Mono 6.1B model's pass@1 rate by 38% relative (and 10% absolute) on the Mostly Basic Python Problems (MBPP) benchmark, outperforming both fine-tuning on MBPP and fine-tuning on repaired programs written by humans. Overall, our results suggest that learning from human-written natural language feedback is both more effective and sample-efficient than training exclusively on demonstrations for improving an LLM's performance on code generation tasks. # Improving Code Generation by Training with Natural Language Feedback # Angelica Chen 1 J´er´emy Scheurer 1 2 Tomasz Korbak 1 2 3 Jon Ander Campos 1 4 Jun Shern Chan 1 2 Samuel R. Bowman 1 Kyunghyun Cho 1 5 6 Ethan Perez 1 2 7 Abstract The potential for pre-trained large language mod- els (LLMs) to use natural language feedback at inference time has been an exciting recent devel- opment. We build upon this observation by for- malizing an algorithm for learning from natural language feedback at training time instead, which we call Imitation learning from Language Feed- back (ILF). ILF requires only a small amount of human-written feedback during training and does not require the same feedback at test time, mak- ing it both user-friendly and sample-efficient. We further show that ILF can be seen as a form of min- imizing the KL divergence to the ground truth dis- tribution and demonstrate a proof-of-concept on a neural program synthesis task. We use ILF to im- prove a CODEGEN-MONO 6.1B model’s pass@1 rate by 38% relative (and 10% absolute) on the Mostly Basic Python Problems (MBPP) bench- mark, outperforming both fine-tuning on MBPP and fine-tuning on repaired programs written by humans. Overall, our results suggest that learn- ing from human-written natural language feed- back is both more effective and sample-efficient than training exclusively on demonstrations for improving an LLM’s performance on code gener- ation tasks. Incorrect program generated by 774 Failed unit tests ‘def sum_every other (1st): “Return the sum of every other element of lst, starting with index 0.""" return sum(1st) Natural language feedback provided by human "The code is wrong because it attempts to sum every element instead of every other one. Fix it by slicing 1st using increment 2 before taking the sum." squawauyal uo Oy aun}-aul4 Refinement generated by 7’Refine using the feedback and original program Passed unit ‘tests lef sum_every other (1st): “Return the sum of every other element of lst, starting with index 0.""" return sum(1st[::2]) # 1. Introduction Figure 1. An overview of imitation learning from language feed- back (ILF) for code generation. Given an initial LLM πθ, we sample programs from πθ that do not pass unit tests (indicated by the red X). Human annotators write natural language feedback for the incorrect program and a model πRefine generates a refinement - i.e. an improved version of the original program that incorpo- rates the feedback and passes the unit tests (indicated by the green checkmark). Finally, we fine-tune πθ on the refinements. An important task for the field of software engineering is program synthesis, the automatic generation of computer programs from an input specification (e.g. a natural lan- guage task description or a set of input-output examples) (Manna & Waldinger, 1971). Effective program synthesis can not only improve the efficiency of software developers (Ziegler et al., 2022), but also increase the accessibility of 3University of Sus- sex 4HiTZ Center, University of the Basque Country UP- V/EHU 5Genentech 6CIFAR LMB 7Anthropic. Correspondence to: Angelica Chen <angelica.chen@nyu.edu>, Ethan Perez <ethan@anthropic.com>. writing code in general. Recently, pre-trained large language models (LLMs) have demonstrated impressive success on program synthesis (Chen et al., 2021; Li et al., 2022; Austin et al., 2021; Nijkamp et al., 2022; Xu et al., 2022, inter alia) but still struggle to consistently generate correct code, even with large-scale pre-training (Chen et al., 2021). We hypothesize that these failures can be largely attributed to modern LLM pre-training set-ups. For instance, code pre- training datasets consist mostly of unfiltered code scraped Improving Code Generation by Training with Natural Language Feedback from the Internet, which contains a significant number of security vulnerabilities (Kang et al., 2022) and bugs (Chen et al., 2021). This training signal also consists exclusively of offline demonstrations, without any signal from trial- and-error or interactive guidance that penalizes the model’s buggy outputs. As such, we hypothesize that supervising LLMs with explicit human-written feedback on the model’s own outputs can be more effective at training models to produce functionally correct code. In particular, an intuitive and rich form of feedback to pro- vide to LLMs is natural language feedback. We argue that LLMs are naturally able to incorporate written feedback, which has been shown to significantly improve a code gen- eration model’s pass rates when the feedback is provided at test time (Nijkamp et al., 2022; Austin et al., 2021). In our work, we build upon this observation by exploring the use of natural language feedback during the training process itself, rather than just during inference. We conjecture that such feedback provides expressive and targeted informa- tion about a code generation model’s current failings in a sample-efficient manner. More broadly, this approach also represents a weak version of scalable oversight (Bowman et al., 2022), in that model overseers can improve a model merely by evaluating its outputs, without manually gener- ating new demonstrations, in a way that takes advantage of the capabilities that are being supervised. We demonstrate a proof of concept of ILF for code genera- tion by showing that it improves a CODEGEN-MONO 6.1B model’s pass@1 rate on the Mostly Basic Python Problems (MBPP) benchmark (Odena et al., 2021) by 38% relative (10% absolute) over its zero-shot performance. It also out- performs fine-tuning on the MBPP-provided code by 64% (14% absolute, see Section 3.2). We further find that the refinements generated during ILF do indeed leverage the human-written feedback (Section 3.1) – when the feedback is unhelpful or irrelevant, we observe steep drops in code correctness. The quality of the feedback is also crucial – LLM-generated feedback yields far lower final pass rates than human-written feedback (Section 3.3). Despite the success of our approach, we still observe concrete limita- tions – for instance, πRefine is less effective at incorporating feedback when the feedback addresses multiple bugs (Sec- tion 3.5), which suggests headroom for future work or more capable LLMs to base πRefine on. Overall, our results – as well as our additional results on text summarization, us- ing a similar technique in Scheurer et al. (2023) – suggest that human-written feedback is a powerful, information-rich form of supervision for LLMs. # 2. Method # 2.1. Preliminaries To train LLMs with language feedback, we propose an al- gorithm called Imitation learning from Language Feedback (ILF; Algorithm 1), which extends the work of Scheurer et al. (2022), who study the impact of learning from lan- guage feedback on text summarization models. Scheurer et al. (2022) improves a summarization model by training the base model on improved summaries generated from the model’s original summaries and human-written feedback. Our work builds upon Scheurer et al. (2022) in a number of ways: (1) by formalizing the algorithm and generalizing it into a form that can be applied to any task (our ILF algorithm in Section 2.2), (2) by detailing how the reward function can be adapted for code generation, and (3) by demonstrat- ing a proof-of-concept of ILF for code generation.1 ILF improves the correctness of programs generated by a base- line code generation model πθ by training a separate model πRefine to use language feedback to repair the incorrect πθ- generated programs. (We refer to the repaired programs as refinements.) We then improve πθ by fine-tuning it on the πRefine-generated refinements that pass unit tests, yielding a final improved model πθ∗ . This procedure may be run iteratively to continue improving the model, which we show can be seen as minimizing the expected KL divergence from a target ground truth distribution (Section 2). Here, we formally describe the problem we aim to tackle, before introducing our algorithm. Suppose we start with vo- cabulary V and a pre-trained language model πθ parameter- ized by θ. πθ : V ∗ → [0, 1] is a probability distribution over sequences of tokens x ∈ V ∗, where V ∗ is the Kleene closure of V. We also have a dataset of tasks D = {(t, u)}. A task (t, u) consists of a task description t ∈ T (e.g. “Write a function that computes the prime factorization of an input in- teger.”) and a suite u = UNITTESTS(t) ∈ U of unit tests as- sociated with task t. Finally, let EVAL : V ∗×T → {0, 1} be a unit test verification function that indicates whether a pro- gram x ∼ πθ(· | t) passes all the unit tests in UNITTESTS(t): 1, EVAL(x, t) := if x passes test suite UNITTESTS(t), 0, otherwise (1) We also define a fine-tuning function FINETUNE(πθ, D) that applies a gradient-based optimization algorithm to πθ using the associated loss objective calculated over dataset D. # 2.2. Imitation Learning From Language Feedback 1We open-source our code and annotated data at https:// github.com/nyu-mll/ILF-for-code-generation. Our goal is to sample a diverse set of high-quality programs x1 ∼ πθ(·|t) for any given task t sampled from the task distribution p(t). We do so by fitting an auto-regressive LLM πθ to approximate a ground truth distribution π∗ t (x1) that assigns a probability to x1 that is proportional to its Improving Code Generation by Training with Natural Language Feedback Algorithm 1 Imitation learning from natural language feedback for code generation. 1: Input: Dataset D, initial LLM πθ, unit test verification function EVAL, LLM πRefine : V ∗ → [0, 1] trained to incorporate feedback into code 2: C & {(x0,t, u) | xo ~ 7, (-|t), EVAL(xo, t) = 0, (t, u) € D} » Cannotatea — {(xo, ft) | (wo, t,u) € Ch 4. BR {(t,21) ~ TRefine( | t,o, f) | EVAL(21,t) = 1, (20, ft) © Cannotatea } incorporate feedback f into xo. 5: 79« < FINETUNE(7¢9, R) > Humans write feedback f for a € C. D TRefine generates refinements x that # 5: πθ∗ ← FINETUNE(πθ, R) quality, as measured by a reward function R. Fitting πθ to approximate π∗ t can be seen as minimizing the expected KL divergence from π∗ t to πθ over the task distribution p(t): min θ E t∼p(t) [KL(π∗ t , πθ(· | t))] (2) where π∗ t (x1) ∝ exp (βR(x1, t)) (3) the feedback and passes the test suite (i.e. EVAL(x1, t) = 1), and (iv) assigning higher weight to x1. Let We can formalize this procedure as follows. πψ(x1|t, x0, f ) be a distribution over programs x1 that improve x0 by incorporating the feedback f and pF (f | t, x0, EVAL(x0, t) = 0) be the distribution of pieces of feedback f for incorrect program x0 and task t. We can then define our proposal distribution as: In this work we use the unit test verification function EVAL directly as our reward function R, but R can also be a function of any number of other signals, such as stack traces or compiler outputs. Minimizing the objective in Equation 2 is equivalent to supervised learning, i.e. minimizing the cross-entropy loss: qt(x1) = x0,f πθ(x0|t) × δ0 (EVAL(x0, t) | x0, t)) × pF (f |t, x0, EVAL(x0, t) = 0) × πψ(x1|t, x0, f ) × δ1(EVAL(x1, t) | t, x1), (7) where L(θ) = − E t∼p(t) [Lθ(t)] , (4) Lo(t) = So mF (a1) log mo(21 It). (5) where δ0 and δ1 are the Dirac delta distributions centered at 0 and 1, respectively. Then this proposal distribution is guaranteed to place higher probability mass on higher- quality programs (in terms of unit test pass rate) than πθ since the term δ1(EVAL(x1, t) | t, x1) equals 0 for incorrect programs x1. Rather than computing this loss over the exponentially large space of all possible x1’s, we instead use Monte-Carlo sam- pling over a small set of x1’s drawn from π∗ t . However, this is still intractable because we cannot sample directly from π∗ t . Instead, we approximate π∗ t using importance sampling with a proposal distribution qt(x1): 21) Lo(t) = Sl) log 79 (21|t) (6) We approximate sampling from q by considering each of the terms in Equation 7 in order: πθ(x0|t) × sample δ0 (EVAL(x0, t) | x0, t)) sampling from πθ. In other words, we sample programs x0 from πθ for task t and only keep those that fail the test suite (i.e. EVAL(x0, t) = 0; step 2 of Algorithm 1). which assigns higher weights to higher quality programs x1. # 2.3. Proposal Distribution q Intuitively, we aim to design qt to be as close as possible to π∗ t , which we accomplish by incorporating pieces of natural language feedback f that give information about how to transform a low-reward program x0 into a higher- reward program x1. This can be achieved by (i) identifying a program x0 ∼ πθ(·|t) that does not currently pass the test suite (i.e. EVAL(x0, t) = 0), (ii) asking for natural language feedback f about bugs in x0, (iii) using f to transform the original program x0 into a refinement x1 that incorporates from pF (f |t, x0, EVAL(x0, t) = 0) by having humans annotate programs x0 (paired with their corresponding task descriptions t and test suites u) with natural language feedback (step 3 of Algorithm 1). 3. We approximate sampling from πψ(x1|t, x0, f ) by sampling from πRefine, a model capable of generating refinements given the task description, original pro- grams, and human-written feedback. 4. Finally, the term δ1(EVAL(x1, t) | t, x1) corresponds to another filter: we only keep refined programs x1 that pass the test suite. Improving Code Generation by Training with Natural Language Feedback Next, we consider more concrete details of how this sam- pling is accomplished. Training πRefine ILF assumes the availability of feedback but not necessarily of the repaired code/refinements, for a va- riety of reasons. We assume that program synthesis may be a task for which writing high-level natural language feedback is often less laborious than performing program repair. Al- though writing feedback involves identifying at a high level what is wrong with the program and how it should be fixed, program repair may involve the additional steps of refactor- ing, looking through documentation, and testing. Moreover, past work (Austin et al., 2021; Nijkamp et al., 2022) has in- dicated that certain large LLMs can proficiently incorporate the feedback at inference time, assuming access to accurate and high-quality feedback. As such, ILF assumes access to some model πRefine that is capable of producing a refinement given the original program and feedback. ate any correct completions. This split is first used to evaluate the correctness of refinements generated by πRefine. Then, the correct refinements in this split are used to train πθ to obtain πθ∗ (step 5 in Algorithm 1). • MBPPTest: These are tasks with IDs in the range 11- 110 that we use to evaluate the final performance of πθ∗ . Unlike the previous two splits, we use all tasks in this split, rather than only the tasks for which CODEGEN- MONO 6.1B did not originally generate correct pro- grams for. This allows us to better compare the baseline performance of πθ with that of πθ∗ . We use this modified split so that a larger portion of the dataset can be used to train the final model πθ∗ , whereas smaller portions are allocated for training πRefine and eval- uating πθ∗ . We do not make use of the prompt split (IDs 1-10). πRefine can take a variety of forms, but we fine-tune a pre- trained CODEGEN-MONO 6.1B model as our πRefine. We create a training dataset for πRefine by further annotating a subset of Cannotated with refinements x1 that repair incor- rect programs x0 by incorporating feedback f , such that EVAL(x1, t) = 1 for (x0, f, t) ∈ Cannotated. Further details of our dataset and annotation procedure are in Section 3. Models Throughout this paper, we use a pre-trained CODEGEN-MONO 6.1B model (Nijkamp et al., 2022) as our πθ. It is pre-trained sequentially on THEPILE (Gao et al., 2020), BIGQUERY (Nijkamp et al., 2022), and BIGPYTHON (Nijkamp et al., 2022). We selected this model because it is open-source, can be fine-tuned on a single 4 × 100 A100 (80 GB) node, and demonstrated pass@k scores comparable to CODEX-12B (Chen et al., 2021; Nijkamp et al., 2022). # 3. Experiments and Results Having described our high-level approach, we now explain the experimental setup we use to test ILF. Dataset We train and evaluate our models on the Mostly Basic Python Problems (MBPP) dataset (Odena et al., 2021). MBPP contains 974 Python programming tasks designed to be solvable by entry-level coders. Each task contains a natural language task description t (e.g., “Write a function to return the prime factorization of the input.”), a gold solution, and a suite u of three unit tests. Since the task descriptions are sometimes ambiguous, we include one unit test in the task description. The addition of the unit test helps to specify the input and output format of each task. We hold out the remaining unit tests for the evaluation of our generated programs. To implement our algorithm, we independently fine-tune two separate instances of CODEGEN-MONO 6.1B to cre- ate πRefine and the final model πθ∗ . We train πRefine using pairs of incorrect programs and human-written feedback as inputs, with human-written refinements as targets (using the format in Figure 2). In contrast, we train πθ∗ using natural language task descriptions from MBPP as the inputs and πRefine-generated refinements as the targets. Further training details are in Appendix A.1. Evaluation We evaluate all code generations in this paper using the pass@k metric introduced in Kulal et al. (2019). It estimates the rate for which ≥1 of k model samples passes all the unit tests. We use the empirical estimate of this quantity from Chen et al. (2021), an unbiased estimator given by: MBPP includes a designated prompt/training/validation/test split of the dataset, but we re-split the dataset into the fol- lowing splits: 1- Ce) 7 (8) (x) | pass@k = Eras • MBPPRefine: These are tasks with IDs in the range 111-310 for which CODEGEN-MONO 6.1B did not generate any correct completions. This split is used to train πRefine. • MBPPTrain: These are tasks with IDs in the range 311- 974 for which CODEGEN-MONO 6.1B did not gener- for n total programs (where n ≥ k) and c correct programs for the given task. Human Annotation We hire annotators via Surge AI2 to write both natural language feedback and refinements for 2www.surgehq.ai Improving Code Generation by Training with Natural Language Feedback Prompt Expected completion OLD CODE: Write a python function to find the sum of the three lowest positive numbers from a given list of numbers. >>> Example: sum_three_smallest_nums([10,20,30, 0,60,7]) = 37 def sum_three_smallest_nums (1st) : ist.sort() return sum(ist[:3]) FEEDBACK: This code finds the sum of the smallest 3 numbers, not the smallest 3 positive numbers. It needs to disregard negatives and 0. REFINEMENT: Write a python function to find the sum of the three lowest positive numbers from a given list of numbers. >>> Example: sum_three_smallest_nums([10,20,30, 40,50,60,7]) = 37 def sum_three_smallest_nums (1st) : ist = [x for x in lst if x > 0] ist.sort() return sum(lst[:3]) Figure 2. An example of a zero-shot LLM prompt for repairing incorrect code based on human-written feedback. incorrect programs generated by CODEGEN-MONO 6.1B. For each task that CODEGEN-MONO 6.1B generated no correct programs for, we ask the workers to first select one of the incorrect programs to write feedback and refinement for. We specify that the workers should select a sample that seems relatively easy to correct (i.e. could be minimally corrected to pass the unit tests). Then, they are asked to write feedback that describes what is wrong with the current code and how to fix it. For the refinement, they are asked to copy over the original code and make the minimum number of edits necessary to incorporate the feedback and pass all the unit tests. The full set of worker instructions can be found in Appendix A.2. our method. For instance, this allows us to compare fine- tuning on πRefine-generated refinements with fine-tuning on human-written refinements. When scaled to other pairs of model and task, ILF requires new feedback annotations, but it is possible that using ILF on one dataset will improve the model’s abilities on another dataset for a similar task. We leave analyses of scaling ILF across different tasks and models to future work. Table 1. Initial zero-shot CODEGEN-MONO 6.1B performance on the entire MBPP dataset. “1+ Correct” refers to the percentage of tasks for which CODEGEN-MONO 6.1B generated at least one program that passed all unit tests. We keep all annotations for which the refinement passes all the feed- tests in the task’s test suite, back is correct (as manually verified by the authors), and the Levenshtein edit distance between the refine- ment and the original program is less than 50% of max(len(refinement), len(original program)). The final dataset consists of 195 triples of (incorrect program, human- written feedback, human-written refinement). On average, workers are paid $23 per annotated sample and take 27 min- utes/sample, with a 10th percentile of 4 minutes and a 90th percentile of 43 minutes. Metric Zero-Shot CODEGEN-MONO 6.1B Pass@1 Pass@10 1+ Correct 31% 63% 67% Table 2. Evaluations of 1-shot refinements generated by CODEGEN-MONO 6.1B (before ILF) given either related or unrelated text feedback in the prompt. Feedback is provided only for tasks on which CODEGEN-MONO 6.1B previously did not output any correct programs. Although the ILF algorithm only requires the collection of human-written feedback for the tasks in MBPPTrain (as- suming access to some πRefine that is already fine-tuned or can generate refinements via few-shot prompting), we col- lect both human-written feedback and refinement for all splits of the data so that we can conduct further analyses of Prompt Type Code + feedback Code + unrelated feedback CODEGEN-MONO 6.1B Pass@10 ↑ Pass@1 ↑ 2.0% 0.4% 13.8% 4.0% Improving Code Generation by Training with Natural Language Feedback # 3.1. CODEGEN-MONO 6.1B Incorporates Feedback We first verify that our baseline model can use feedback to repair incorrect code, a pre-requisite for ILF to work. We evaluate CODEGEN-MONO 6.1B’s ability to generate refinements given pairs of (incorrect code, natural language feedback), both in a few-shot manner and after fine-tuning. Feedback is only required for tasks for which πθ is initially unable to produce a correct response, so we first evaluate CODEGEN-MONO 6.1B zero-shot on all of MBPP, gener- ating 30 programs per task with temperature 0.8. Table 1 shows the resulting pass rates. There were 321 tasks for which zero-shot CODEGEN-MONO 6.1B yielded no cor- rect samples (from Table 1: (100% − 67%) × 974 tasks ≈ 321). We then annotate one incorrect program per task with both feedback and refinement, as described in Section 3. Few-Shot Feedback Incorporation We use the human feedback annotations to create few-shot feedback prompts, formatted as in Figure 2. We evaluate CODEGEN-MONO 6.1B’s ability to produce refinements that incorporate the feedback and pass the unit tests. However, producing a re- finement that passes the unit tests does not guarantee that the feedback has been incorporated; there can be multi- ple solutions to a programming task, including ones that are functional but completely different and not using the feedback to improve upon the original code. Alternatively, the model may already be able to repair programs without feedback. Thus, we also evaluate the pass rate after shuf- fling the feedback samples in the dataset, to evaluate if the model’s ability to repair code degrades when presented with unrelated feedback. The results are shown in Table 2. CODEGEN-MONO 6.1B’s ability to incorporate relevant feedback on this particular set of program is low, with pass@10 reaching only 13.8%. However, the gap in accuracy between CODEGEN-MONO 6.1B-generated refinements on relevant versus irrelevant feedback is significant, with pass@10 decreasing by 71% (relative; 13.8% → 4.0%), indicating that the model is in- deed using the feedback. Training πRefine Next, we examine whether we can im- prove our ability to repair programs given feedback by fine-tuning a separate model specifically to perform this task. Our training examples consist of triples of incorrect program, human-written feedback, and human-written re- finement. We train the model to maximize the likelihood of the refinement given the program and feedback. The incorrect programs were generated by CODEGEN-MONO 6.1B zero-shot on MBPP tasks, and the feedback and re- finements were written by human annotators, as discussed in Section 3. We only included tasks for which none of CODEGEN-MONO 6.1B’s generated programs were cor- rect, yielding 44 tasks in the training dataset (forming the split MBPPRefine) and 128 tasks in the evaluation dataset (forming the split MBPPTrain). We asked human annotators to write refinements of the original code that incorporated their own previously written feedback, passed the unit tests, and made only minimal edits to the code (see Section 3). The format of the training data also matched the few-shot prompt format (Figure 2) but without the in-context exam- ples of refinements. We denote this model as πRefine, as described in Section 2.3. Table 3. Pass rates of πRefine-generated refinements versus zero- shot CODEGEN-MONO 6.1B programs for tasks in MBPPTrain. Metric πRefine Zero-shot CODEGEN-MONO 6.1B Pass@1 Pass@10 1+ correct 19% 47% 61% 0% 0% 0% Table 3 shows the pass rates for πRefine on the evaluation dataset, which were produced by sampling 30 refinements per task with temperature 0.8. Fine-tuning significantly improves CODEGEN-MONO 6.1B’s ability to incorporate feedback compared to 1-shot refinement, increasing pass rates more than three-fold (2→19% pass@1, 13.8→47% pass@10, from Tables 2 and 3). Furthermore, 61% of tasks had at least one correct refinement. This is particularly significant when considering the fact that we selected only tasks for which a non-finetuned CODEGEN-MONO 6.1B model did not originally output any correct programs for (the rightmost column in Table 3). For the 61% of valida- tion tasks that πRefine generated a correct refinement for, we randomly selected one such correct program for each task to form the training dataset for our final model πθ∗ , yielding a final training dataset of 78 examples. # 3.2. ILF Yields Pass Rates Higher Than Fine-Tuning on Gold Data or Human-Written Programs Alone Given that our refinements improve over the initial pro- grams, we now fine-tune on the refinements to improve our code generation model. As discussed earlier, we use the correct refinements (as evaluated by the unit tests) that πRefine generated for its evaluation dataset as the training dataset for πθ∗ . Since πθ∗ is meant to generate code from a natural language task description (rather than to incorpo- rate feedback into a refinement), the inputs of our training dataset are the MBPP prompts and the targets are the 78 πRefine-generated refinements described in the previous sec- tion. We also compare the performance of π∗ θ against that of CODEGEN-MONO 6.1B evaluated in a zero-shot manner, CODEGEN-MONO 6.1B fine-tuned on the gold programs from the MBPP dataset, and CODEGEN-MONO 6.1B fine- tuned on our human-written refinements. For all fine-tuning experiments, we train on programs corresponding to the Improving Code Generation by Training with Natural Language Feedback Table 4. Final performance of πθ∗ on MBPPTest, compared to other ablations and baselines. All results are calculated using 30 output samples with temperature 0.8. All the methods are built on the CODEGEN-MONO 6.1B model. Method Feedback Source Fine-Tuning Data Pass Rates of πθ∗ Pass@1 Pass@10 ILF Humans πRefine Refinements 36% 68% Ablations 1-shot InstructGPT 2-shot InstructGPT 1-shot InstructGPT Refinements 2-shot InstructGPT Refinements 19% 25% 55% 59% Gold Standards - - MBPP Gold Human Refinements 22% 33% 63% 68% Baseline (zero-shot) - - 26% 59% same set of task IDs as the ones used in πθ∗ ’s training dataset. Additionally, we evaluate the impact of ablating the hu- man annotations in our algorithm by using an LLM in place of humans to generate the feedback and refinements (replacing steps 3 and 4 in Algorithm 1). For the LLM, we use GPT-3.5 fine-tuned with Feedback Made Easy (FeedME; text-davinci-002 on the OpenAI API)3. We refer to this model as InstructGPT, which is the se- ries of OpenAI models that FeedME belongs to (OpenAI, 2022). We use InstructGPT to generate both the feedback and refinements on the original programs. We then fine- tune CODEGEN-MONO 6.1B on the model-generated re- finements. Training data source 50 mmm MBPP gold programs MM Mrefine refinements 40 lam Human-written refinements 530 it iS) 20 10 | 0 | WW als 0 | = . 10° 10? 10? 103 104 Perplexity The results of our ILF algorithm compared to the baselines and ablations are shown in Table 4. ILF yields the high- est pass@1 and pass@10 rates, despite how few samples of feedback and refinements we use. The pass@1 rate in particular shows a significant increase in improvement over the zero-shot baseline, representing a 10% absolute increase (38% relative increase). Pass@1 improvements are espe- cially helpful for assisting with software engineering, where it is more helpful to suggest a single correct completion rather than 10 possible completions for the user to select from. Compared to the gold standards, ILF outperforms both fine- tuning on MBPP gold programs and human-written refine- ments on the pass@1 metric, yielding 14% absolute (64% relative) and 3% absolute (9% relative) increases in pass@1 rates, respectively. However, training on human-written re- finements yielded comparable pass@10 rates as ILF, which is unsurprising since πRefine was trained on human-written refinements. When human-written feedback and πRefine- generated refinements are ablated (the “Ablations” section of Table 4), ILF also outperforms training on both 1-shot and 2-shot InstructGPT-generated refinements by 17% and 11% absolute (89% and 44% relative), respectively. Figure 3. Histogram of the perplexities of the various training data sources, as measured using a pre-trained CODEGEN-MONO 6.1B model. Analysis of Training Data Sources However, we also note the surprising fact that merely training on a small sample of the MBPP gold programs did not make a sig- nificant difference in accuracy over zero-shot inference. We speculate that the gold programs from the MBPP dataset may be somewhat out-of-distribution for CODEGEN-MONO 6.1B. To test this hypothesis, we computed the perplexity of the MBPP gold programs, the πRefine-generated refine- ments, and the human-written refinements using the pre- trained CODEGEN-MONO 6.1B model. The results are shown in Figure 3. While the distributions of all three data sources look similar, the MBPP dataset contains more high-perplexity programs (i.e. programs with perplexity ≥ 102) than either the πRefine-generated refinements or the human-written refinements. As a result, it is likely easier for CODEGEN-MONO 6.1B to learn from the latter two datasets, since they are closer to CODEGEN-MONO 6.1B’s original distribution while still being functionally correct. 3Details at beta.openai.com/docs/model-index-for-researchers Furthermore, ILF is particularly useful for settings where large amounts of gold code are not available. In this setting, ILF can be thought of as a method of not only generating Improving Code Generation by Training with Natural Language Feedback Pass@1 Pass@10 x Rd 35% 65% 32% 60% 30% 28% 55% 25% 50% 22% 150 Number of tasks w/ feedback 50 100 200 150 Number of tasks w/ feedback 200 50 100 % tasks with at least one passed completion 75% CodeGen-Mono 6.18 trained on 1-shot InstructGPT refinements CodeGen-Mono 6.1B trained on 2-shot InstructGPT refinements CodeGen-Mono 6.18 trained on * Tref-generated refinements 0-shot CodeGen-Mono 6.1B 70% 65% 60% 55% 50 100 150 Number of tasks w/ feedback 200 Figure 4. Training dataset size versus CODEGEN-MONO 6.1B pass rates on MBPP tasks 11-111 after fine-tuning on InstructGPT- generated refinements, versus the performance of πθ∗ (the model produced by our approach). X marks the performance of πθ∗ , whereas the solid lines plot the performance of CODEGEN-MONO 6.1B after fine-tuning on correct refinements generated by InstructGPT, using feedback also generated by InstructGPT. The dashed line indicates the zero-shot pass rate of a pre-trained CODEGEN-MONO 6.1B model. more training data, but training data that is closer to the model’s original outputs in data representation space and that specifically repairs the kinds of bugs that the original model generates. As a result, fine-tuning the model on πRefine-generated refinements does not require adjusting the weights as much as fine-tuning the model on the MBPP gold programs would, even though both training datasets contain the same number of functionally correct programs. in quality, we expect that this gap between human- and model-written feedback will increasingly narrow. Table 5. The proportion of the feedback that addressed each type of bug, for feedback sourced from humans and InstructGPT. Each sample of feedback can be tagged with multiple categories, so the quantities in each column do not necessarily add up to 100%. # 3.3. Scaling Up Model Feedback Does Not Offer the Same Benefits As Human Feedback Since high quality human feedback can be expensive to col- lect, we also evaluated how much model feedback might yield the same benefit as our sample of human-written feed- back. To do so, we randomly select k tasks from the set of MBPP tasks for which CODEGEN-MONO 6.1B did not originally output a correct answer, and prompt Instruct- GPT to generate both the feedback and the refinement. We then evaluate the refinements for correctness and train CODEGEN-MONO 6.1B on the correct refinements. We use k ∈ {50, 100, 200} and generate 30 output samples at tem- perature 0.8 for all stages of the experiment. We are limited to these k values due to the small number of tasks we have in MBPPTrain, but future work may investigate scaling up these experiments by using larger datasets or automatically generating new tasks and unit tests for the training dataset. Further training details are listed in Appendix A.1. The results are shown in Figure 4. Although increasing the quantity of InstructGPT-generated feedback offers mod- est improvements in pass rates, these improvements do not yield pass rates as high as those of πθ∗ , even though πθ∗ uses only a total of 122 pieces of feedback throughout its training process (44 for training πRefine and 78 for generat- ing refinements to train πθ∗ on). However, as pre-trained large language models continue to improve dramatically Feedback Category % of Feedback Human InstructGPT Logic Formatting Missing step Algebra Recursion Regex Function semantics Dynamic programming Extra step No feedback needed Unrelated 30% 36% 10% 10% 4% 6% 2% 2% 0% 0% 0% 46% 14% 6% 8% 14% 6% 4% 0% 12% 14% 8% Table 6. Descriptive statistics for the human- versus InstructGPT- generated feedback. The * indicates that the metric was computed on the random sample of 50 that we manually inspected, whereas the other metrics are computed from the full dataset. Source of Feedback Human InstructGPT Avg. num. of bugs addressed* Avg. num. of words 1.8 68.9 ± 48.2 1.1 24.2 ± 28.6 Improving Code Generation by Training with Natural Language Feedback 80% a fo) x 40% Pass rate of refinement 20% 0% 1 2 3 4 5 Number of bugs addressed in feedback Figure 5. The number of bugs addressed in the feedback versus the pass rate of πRefine’s refinements. # 4. Related Work LLMs for Program Synthesis Our work builds on a large body of literature that explores the use of pre-trained LLMs for neural program synthesis. Many general purpose LLMs, although not pre-trained specifically for code gener- ation, have demonstrated impressive proficiency at solving code challenges since they are pre-trained on large corpora of text such as THE PILE (Gao et al., 2020) that contain a small percentage of code content (Austin et al., 2021; Wang & Komatsuzaki, 2021; Black et al., 2022; Nijkamp et al., 2022). Yet other recent LLMs for program synthesis are trained on solely source code files (Wang et al., 2021; Zan et al., 2022; Li et al., 2022; Xu et al., 2022), or on both text and source code documents – sometimes either in suc- cession (Chen et al., 2021; Nijkamp et al., 2022; Bai et al., 2022a), in a mixed corpus (Workshop et al., 2022), or on mixed natural language-programming language documents (Feng et al., 2020). # 3.4. Human Feedback Is More Informative Than InstructGPT Feedback To better understand why human feedback produced greater improvements in pass rate than InstructGPT feedback, we randomly selected 50 samples of feedback for each source (i.e. human or InstructGPT) and annotated the number and types of bugs that each feedback sample addressed. The results are shown in Tables 5 and 6. We observed that In- structGPT often gave no feedback (e.g. “The code is correct” or “Great job!”), provided feedback that was irrelevant or incorrect, or restated the task description instead of address- ing what should be repaired about the code. Despite this, InstructGPT’s refinements were often correct even if the feedback itself wasn’t. Human-written feedback addressed more bugs on average and never gave irrelevant feedback. We provide further examples of the differences between human and InstructGPT feedback in Appendix A.3. # 3.5. πRefine Struggles To Incorporate Feedback Addressing Many Bugs Lastly, we explored whether the number of bugs addressed in the feedback affected πRefine’s ability to repair the orig- inal code sample. The results are shown in Figure 5. The greater the number of bugs addressed, the lower the aver- age pass rate of πRefine’s refinements. This suggests that a promising direction for future work might consist of auto- matically decomposing the feedback into multiple steps and having πRefine incorporate the feedback one step at a time. Indeed, Nijkamp et al. (2022) show that the CODEGEN models are often more effective at following instructions when the instructions are given across multiple turns, and recent Chain-of-Thought work (Wei et al., 2022) illustrates a similar prompting technique. Learning from Human Feedback Our algorithm is in- spired by a number of past works that have trained models to learn from feedback. A common technique is reinforce- ment learning from human feedback (RLHF Ziegler et al., 2019; Stiennon et al., 2020; Ouyang et al., 2022), which trains models to satisfy human preferences. However, our algorithm is closer to works that use natural language feed- back, rather than comparisons between different choices. Elgohary et al. (2020); Austin et al. (2021); Nijkamp et al. (2022) all demonstrate that code LLM performance gener- ally improves when prompted with natural language feed- back, though Nijkamp et al. (2022) observes that the feed- back is more effective when it is given one step at a time. Our work differs from these in that ILF learns from the feedback at training time, not at inference time. Bai et al. (2022a) also uses natural language feedback dur- ing the training process, but as part of an RLHF algorithm instead where the feedback is used to solicit different re- sponses from the digital assistant, the responses are ranked by crowdworkers, and the rankings are used to train the preference model. However, they note that this form of learning from natural language feedback does not measur- ably improve their code generation model more than simply prompting. Outside of program synthesis, we show in our other work (Scheurer et al., 2023) that ILF is also effective for text summarization. In addition to re-formulating the reward function R(·) for summarization, Scheurer et al. (2023) addi- tionally demonstrates that an instruction-finetuned LLM can evaluate its own outputs and select the best one. Similar to our results on code generation, Scheurer et al. (2023) shows that ILF outperforms all supervised fine-tuning baselines on text summarization. This aligns with numerous other works Improving Code Generation by Training with Natural Language Feedback that have explored supervision via natural language in other ways, such as via explanations (Camburu et al., 2018; Hase & Bansal, 2021; Pruthi et al., 2021; Lampinen et al., 2022, inter alia) and as part of RL systems (Fidler et al., 2017; Luketina et al., 2019; Lin et al., 2020, inter alia). # 5. Conclusion We have shown that ILF can significantly improve the qual- ity of a code generation model, even with just a small sample of human-written feedback and refinements. This approach is theoretically justified as minimizing the expected KL di- vergence between πθ and a target ground-truth distribution, where we acquire signal from the latter via human-written natural language feedback. This approach is also appealing because it is not model- specific (in the sense that ILF can be used with any type of base model πθ, assuming the existence of a sufficiently capable LLM to act as πRefine), and can be conducted in multiple rounds to continuously improve the model. Fur- thermore, it is notable that our approach generates training data that is not only correct, but targets the specific kinds of bugs that the model is likely to output. In essence, it provides an online training signal that is missing from the offline pre-training set-up of modern LLMs. Our approach is also remarkably sample-efficient, yielding 38% and 64% relative increases in pass@1 rate over the zero-shot baseline and fine-tuning on MBPP data, despite fine-tuning on only 78 examples. Seraphina Nix, Quintin Pope, Kay Kozaronek, Peter Hase, Talia Ringer, Asa Cooper Stickland, Jacob Pfau, David Lind- ner, Lennart Heim, Kath Lumpante, and Pablo Morena for helpful discussions and feedback about the design and im- plementation of this work. We are additionally thankful to Scott Heiner and Edwin Chen for extensive help with setting up our human annotation workflow and interface. EP thanks the National Science Foundation and Open Philanthropy for fellowship support. JAC is supported by a doctoral grant from the Spanish MECD. AC, SB, and KC are supported by National Science Foundation Awards 1922658 and 2046556. Any opinions, findings, and conclusions or recommenda- tions expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Sci- ence Foundation. KC is additionally supported by 42dot, Hyundai Motor Company (under the project Uncertainty in Neural Sequence Modeling) and the Samsung Advanced Institute of Technology (under the project Next Genera- tion Deep Learning: From Pattern Recognition to AI). This project has also benefited from financial support to SB by Eric and Wendy Schmidt (made by recommendation of the Schmidt Futures program), Open Philanthropy, and Apple. We also thank the NYU High-Performance Computing Cen- ter for in-kind support and OpenAI for providing access to and credits for their models via the API Academic Access Program. # References Our work opens up multiple avenues for promising future work. For instance, ILF can be applied iteratively over the course of multiple rounds whenever new information arrives (e.g. new Python syntax) or new bugs are discovered. As the pace of progress of modern LLM research continues to accelerate, it may soon be feasible to partially or fully automate the generation of natural language feedback (sim- ilar to ‘RL from AI feedback’ (RLAIF; Bai et al., 2022b) and our experiments in Section 3.3), greatly reducing both the time and cost necessary for collecting feedback. This direction of work is also particularly appealing because the learning signal is process-based rather than outcome- based, which has been shown to mitigate reward hacking and improve the correctness of intermediate reasoning steps (Uesato et al., 2022). Although further work is required to extend our method, ILF represents an exciting step forward in training LLMs with feedback that is rich, interactive, and sample-efficient. # Acknowledgements We are grateful to Nitarshan Rajkumar, Jason Phang, Nat McAleese, Geoffrey Irving, Jeff Wu, Jan Leike, Cathy Yeh, William Saunders, Jonathan Ward, Daniel Ziegler, Austin, J., Odena, A., Nye, M. I., Bosma, M., Michalewski, H., Dohan, D., Jiang, E., Cai, C. J., Terry, M., Le, Q. V., and Sutton, C. Program synthesis with large language models, 2021. URL https://arxiv.org/abs/ 2108.07732. Bai, Y., Jones, A., Ndousse, K., Askell, A., Chen, A., Das- Sarma, N., Drain, D., Fort, S., Ganguli, D., Henighan, T. J., Joseph, N., Kadavath, S., Kernion, J., Conerly, T., El-Showk, S., Elhage, N., Hatfield-Dodds, Z., Hernandez, D., Hume, T., Johnston, S., Kravec, S., Lovitt, L., Nanda, N., Olsson, C., Amodei, D., Brown, T. B., Clark, J., Mc- Candlish, S., Olah, C., Mann, B., and Kaplan, J. Train- ing a helpful and harmless assistant with reinforcement learning from human feedback. ArXiv, abs/2204.05862, 2022a. Bai, Y., Kadavath, S., Kundu, S., Askell, A., Kernion, J., Jones, A., Chen, A., Goldie, A., Mirhoseini, A., McKin- non, C., Chen, C., Olsson, C., Olah, C., Hernandez, D., Drain, D., Ganguli, D., Li, D., Tran-Johnson, E., Perez, E., Kerr, J., Mueller, J., Ladish, J., Landau, J., Ndousse, K., Lukosuite, K., Lovitt, L., Sellitto, M., Elhage, N., Schiefer, N., Mercado, N., DasSarma, N., Lasenby, R., Larson, R., Ringer, S., Johnston, S., Kravec, S., Showk, S. E., Fort, S., Lanham, T., Telleen-Lawton, T., Conerly, Improving Code Generation by Training with Natural Language Feedback T., Henighan, T., Hume, T., Bowman, S. R., Hatfield- Dodds, Z., Mann, B., Amodei, D., Joseph, N., McCan- dlish, S., Brown, T., and Kaplan, J. Constitutional ai: Harmlessness from ai feedback, 2022b. Black, S., Biderman, S., Hallahan, E., Anthony, Q., Gao, L., Golding, L., He, H., Leahy, C., McDonell, K., Phang, J., Pieler, M., Prashanth, U. S., Purohit, S., Reynolds, L., Tow, J., Wang, B., and Weinbach, S. GPT-NeoX-20B: An open-source autoregressive language model. In Pro- ceedings of the ACL Workshop on Challenges & Perspec- tives in Creating Large Language Models, 2022. URL https://arxiv.org/abs/2204.06745. 187. URL https://aclanthology.org/2020. acl-main.187. Feng, Z., Guo, D., Tang, D., Duan, N., Feng, X., Gong, M., Shou, L., Qin, B., Liu, T., Jiang, D., and Zhou, M. CodeBERT: A pre-trained model for programming and natural languages. In Findings of the Association for Com- putational Linguistics: EMNLP 2020, pp. 1536–1547, Online, November 2020. Association for Computational doi: 10.18653/v1/2020.findings-emnlp. Linguistics. 139. URL https://aclanthology.org/2020. findings-emnlp.139. Bowman, S. R., Hyun, J., Perez, E., Chen, E., Pettit, C., Heiner, S., Lukoˇsi¯ut˙e, K., Askell, A., Jones, A., Chen, A., Goldie, A., Mirhoseini, A., McKinnon, C., Olah, C., Amodei, D., Amodei, D., Drain, D., Li, D., Tran-Johnson, E., Kernion, J., Kerr, J., Mueller, J., Ladish, J., Landau, J., Ndousse, K., Lovitt, L., Elhage, N., Schiefer, N., Joseph, N., Mercado, N., DasSarma, N., Larson, R., McCandlish, S., Kundu, S., Johnston, S., Kravec, S., Showk, S. E., Fort, S., Telleen-Lawton, T., Brown, T., Henighan, T., Hume, T., Bai, Y., Hatfield-Dodds, Z., Mann, B., and Kaplan, J. Measuring progress on scalable oversight for large language models. ArXiv, abs/2211.03540, 2022. Camburu, O.-M., Rockt¨aschel, T., Lukasiewicz, T., and Blunsom, P. e-snli: Natural language inference with natural language explanations. Advances in Neural In- formation Processing Systems, 31, 2018. URL https: //arxiv.org/pdf/1812.01193.pdf. Fidler, S. et al. Teaching machines to describe images with natural language feedback. Advances in Neural Information Processing Systems, 30, 2017. Gao, L., Biderman, S., Black, S., Golding, L., Hoppe, T., Foster, C., Phang, J., He, H., Thite, A., Nabeshima, N., Presser, S., and Leahy, C. The Pile: An 800gb dataset of diverse text for language modeling. arXiv preprint arXiv:2101.00027, 2020. Hase, P. and Bansal, M. When can models learn from a formal framework for understand- explanations? arXiv preprint ing the roles of explanation data. arXiv:2102.02201, 2021. URL https://arxiv. org/pdf/2102.02201.pdf. Kang, S., Yoon, J., and Yoo, S. Large language models are few-shot testers: Exploring llm-based general bug re- production, 2022. URL https://arxiv.org/abs/ 2209.11515. Chen, M., Tworek, J., Jun, H., Yuan, Q., de Oliveira Pinto, H. P., Kaplan, J., Edwards, H., Burda, Y., Joseph, N., Brockman, G., Ray, A., Puri, R., Krueger, G., Petrov, M., Khlaaf, H., Sastry, G., Mishkin, P., Chan, B., Gray, S., Ryder, N., Pavlov, M., Power, A., Kaiser, L., Bavar- ian, M., Winter, C., Tillet, P., Such, F. P., Cummings, D., Plappert, M., Chantzis, F., Barnes, E., Herbert- Voss, A., Guss, W. H., Nichol, A., Paino, A., Tezak, N., Tang, J., Babuschkin, I., Balaji, S., Jain, S., Saun- ders, W., Hesse, C., Carr, A. N., Leike, J., Achiam, J., Misra, V., Morikawa, E., Radford, A., Knight, M., Brundage, M., Murati, M., Mayer, K., Welinder, P., Mc- Grew, B., Amodei, D., McCandlish, S., Sutskever, I., and Zaremba, W. Evaluating large language models trained on code, 2021. URL https://arxiv.org/abs/ 2107.03374. Kulal, S., Pasupat, P., Chandra, K., Lee, M., Padon, O., Aiken, A., and Liang, P. S. Spoc: Search-based In Wallach, H., Larochelle, pseudocode to code. H., Beygelzimer, A., d'Alch´e-Buc, F., Fox, E., and Garnett, R. (eds.), Advances in Neural Information Processing Systems, volume 32. Curran Associates, Inc., 2019. URL https://proceedings.neurips. cc/paper_files/paper/2019/file/ 7298332f04ac004a0ca44cc69ecf6f6b-Paper. pdf. Lampinen, A. K., Dasgupta, I., Chan, S. C., Matthewson, K., Tessler, M. H., Creswell, A., McClelland, J. L., Wang, J. X., and Hill, F. Can language models learn from ex- planations in context? arXiv preprint arXiv:2204.02329, 2022. Elgohary, A., Hosseini, S., and Hassan Awadallah, A. Speak to your parser: Interactive text-to-SQL with natural lan- guage feedback. In Proceedings of the 58th Annual Meet- ing of the Association for Computational Linguistics, pp. 2065–2077, Online, July 2020. Association for Compu- tational Linguistics. doi: 10.18653/v1/2020.acl-main. Lhoest, Q., Villanova del Moral, A., Jernite, Y., Thakur, A., von Platen, P., Patil, S., Chaumond, J., Drame, M., Plu, J., Tunstall, L., Davison, J., ˇSaˇsko, M., Chhablani, G., Malik, B., Brandeis, S., Le Scao, T., Sanh, V., Xu, C., Patry, N., McMillan-Major, A., Schmid, P., Gugger, S., Delangue, C., Matussi`ere, T., Debut, L., Bekman, S., Improving Code Generation by Training with Natural Language Feedback Cistac, P., Goehringer, T., Mustar, V., Lagunas, F., Rush, A., and Wolf, T. Datasets: A community library for natural language processing. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing: System Demonstrations, pp. 175–184, Online and Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics. URL https: //aclanthology.org/2021.emnlp-demo.21. Schulman, J., Hilton, J., Kelton, F., Miller, L., Simens, M., Askell, A., Welinder, P., Christiano, P., Leike, J., and Lowe, R. Training language models to follow instruc- tions with human feedback. In Oh, A. H., Agarwal, A., Belgrave, D., and Cho, K. (eds.), Advances in Neural Information Processing Systems, 2022. URL https: //openreview.net/forum?id=TG8KACxEON. Li, Y., Choi, D., Chung, J., Kushman, N., Schrit- twieser, J., Leblond, R., Eccles, T., Keeling, J., Gi- meno, F., Lago, A. D., Hubert, T., Choy, P., de Mas- son d’Autume, C., Babuschkin, I., Chen, X., Huang, P.-S., Welbl, J., Gowal, S., Cherepanov, A., Mol- loy, J., Mankowitz, D. J., Robson, E. S., Kohli, P., de Freitas, N., Kavukcuoglu, K., and Vinyals, O. Competition-level code generation with alphacode. Sci- ence, 378(6624):1092–1097, 2022. doi: 10.1126/ science.abq1158. URL https://www.science. org/doi/abs/10.1126/science.abq1158. Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J., Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga, L., Desmaison, A., Kopf, A., Yang, E., DeVito, Z., Raison, M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L., Bai, J., and Chintala, S. PyTorch: An Imperative Style, High-Performance Deep Learning Library. In Advances in Neural Information Processing Systems 32, 2019. Pruthi, D., Bansal, R., Dhingra, B., Soares, L. B., Collins, M., Lipton, Z. C., Neubig, G., and Cohen, W. W. Evalu- ating Explanations: How much do explanations from the teacher aid students?, 2021. Lin, J., Ma, Z., Gomez, R., Nakamura, K., He, B., and Li, G. A review on interactive reinforcement learning from human social feedback. IEEE Access, 8:120757–120765, 2020. doi: 10.1109/ACCESS.2020.3006254. Scheurer, J., Campos, J. A., Chan, J. S., Chen, A., Cho, K., and Perez, E. Training language models with lan- guage feedback. ACL Workshop on Learning with Natural Language Supervision, 2022. URL https://arxiv. org/abs/2204.14146. Luketina, J., Nardelli, N., Farquhar, G., Foerster, J., An- dreas, J., Grefenstette, E., Whiteson, S., and Rockt¨aschel, T. A survey of reinforcement learning informed by nat- ural language. In Proceedings of the Twenty-Eighth In- ternational Joint Conference on Artificial Intelligence, IJCAI-19, pp. 6309–6317. International Joint Confer- ences on Artificial Intelligence Organization, 7 2019. doi: 10.24963/ijcai.2019/880. URL https://doi.org/ 10.24963/ijcai.2019/880. Manna, Z. and Waldinger, R. J. Toward automatic program synthesis. Commun. ACM, 14(3):151–165, mar 1971. ISSN 0001-0782. doi: 10.1145/362566.362568. URL https://doi.org/10.1145/362566.362568. Nijkamp, E., Pang, B., Hayashi, H., Tu, L., Wang, H., Zhou, Y., Savarese, S., and Xiong, C. Codegen: An open large language model for code with multi-turn program synthe- sis. arXiv preprint, 2022. Odena, A., Sutton, C., Dohan, D. M., Jiang, E., Michalewski, H., Austin, J., Bosma, M. P., Nye, M., Terry, M., and Le, Q. V. Program synthesis with large language models. In n/a, pp. n/a, n/a, 2021. n/a. OpenAI. Model index for researchers, 2022. URL https://platform.openai.com/docs/ model-index-for-researchers. Scheurer, J., Campos, J. A., Korbak, T., Chan, J. S., Chen, A., Cho, K., and Perez, E. Training language models with language feedback at scale. Preprint, 2023. https://drive.google.com/file/ URL d/1tryv10CABT_FOF9Sn2OaWvfwqXF6iIec/ view?usp=share_link. Stiennon, N., Ouyang, L., Wu, J., Ziegler, D., Lowe, R., Voss, C., Radford, A., Amodei, D., and Christiano, P. F. Learning to summarize with human feedback. In Larochelle, H., Ranzato, M., Hadsell, R., Balcan, M., and Lin, H. (eds.), Advances in Neural Information Pro- cessing Systems, volume 33, pp. 3008–3021. Curran As- sociates, Inc., 2020. URL https://proceedings. neurips.cc/paper/2020/file/ 1f89885d556929e98d3ef9b86448f951-Paper. pdf. Uesato, J., Kushman, N., Kumar, R., Song, F., Siegel, N., Wang, L., Creswell, A., Irving, G., and Higgins, I. Solv- ing math word problems with process- and outcome- based feedback, 2022. Wang, B. and Komatsuzaki, A. GPT-J-6B: A Parameter Autoregressive Language https://github.com/kingoflolz/ 6 Billion Model. mesh-transformer-jax, May 2021. Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C., Mishkin, P., Zhang, C., Agarwal, S., Slama, K., Gray, A., Wang, Y., Wang, W., Joty, S., and Hoi, S. C. Codet5: Identifier-aware unified pre-trained encoder-decoder mod- els for code understanding and generation. In Proceedings Improving Code Generation by Training with Natural Language Feedback of the 2021 Conference on Empirical Methods in Natural Language Processing, EMNLP 2021, 2021. Wei, J., Wang, X., Schuurmans, D., Bosma, M., brian ichter, Xia, F., Chi, E. H., Le, Q. V., and Zhou, D. Chain of thought prompting elicits reasoning in large language models. In Oh, A. H., Agarwal, A., Belgrave, D., and Cho, K. (eds.), Advances in Neural Information Processing Systems, 2022. URL https://openreview.net/ forum?id=_VjQlMeSB_J. Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue, C., Moi, A., Cistac, P., Rault, T., Louf, R., Funtowicz, M., Davison, J., Shleifer, S., von Platen, P., Ma, C., Jer- nite, Y., Plu, J., Xu, C., Scao, T. L., Gugger, S., Drame, M., Lhoest, Q., and Rush, A. M. Transformers: State- of-the-art natural language processing. In Proceedings of the 2020 Conference on Empirical Methods in Natu- ral Language Processing: System Demonstrations, pp. 38–45, Online, October 2020. Association for Compu- tational Linguistics. URL https://www.aclweb. org/anthology/2020.emnlp-demos.6. Workshop, B., :, Scao, T. L., Fan, A., Akiki, C., Pavlick, E., Ili´c, S., Hesslow, D., Castagn´e, R., Luccioni, A. S., Yvon, F., Gall´e, M., Tow, J., Rush, A. M., Biderman, S., Webson, A., Ammanamanchi, P. S., Wang, T., Sagot, B., Muennighoff, N., del Moral, A. V., Ruwase, O., Baw- den, R., Bekman, S., McMillan-Major, A., Beltagy, I., Nguyen, H., Saulnier, L., Tan, S., Suarez, P. O., Sanh, V., Laurenc¸on, H., Jernite, Y., Launay, J., Mitchell, M., Raffel, C., Gokaslan, A., Simhi, A., Soroa, A., Aji, A. F., Alfassy, A., Rogers, A., Nitzav, A. K., Xu, C., Mou, C., Emezue, C., Klamm, C., Leong, C., van Strien, D., Adelani, D. I., Radev, D., Ponferrada, E. G., Lev- kovizh, E., Kim, E., Natan, E. B., De Toni, F., Dupont, G., Kruszewski, G., Pistilli, G., Elsahar, H., Benyam- ina, H., Tran, H., Yu, I., Abdulmumin, I., Johnson, I., Gonzalez-Dios, I., de la Rosa, J., Chim, J., Dodge, J., Zhu, J., Chang, J., Frohberg, J., Tobing, J., Bhattacharjee, J., Almubarak, K., Chen, K., Lo, K., Von Werra, L., We- ber, L., Phan, L., allal, L. B., Tanguy, L., Dey, M., Mu˜noz, M. R., Masoud, M., Grandury, M., ˇSaˇsko, M., Huang, M., Coavoux, M., Singh, M., Jiang, M. T.-J., Vu, M. C., Jauhar, M. A., Ghaleb, M., Subramani, N., Kassner, N., Khamis, N., Nguyen, O., Espejel, O., de Gibert, O., Ville- gas, P., Henderson, P., Colombo, P., Amuok, P., Lhoest, Q., Harliman, R., Bommasani, R., L´opez, R. L., Ribeiro, R., Osei, S., Pyysalo, S., Nagel, S., Bose, S., Muhammad, S. H., Sharma, S., Longpre, S., Nikpoor, S., Silberberg, S., Pai, S., Zink, S., Torrent, T. T., Schick, T., Thrush, T., Danchev, V., Nikoulina, V., Laippala, V., Lepercq, V., Prabhu, V., Alyafeai, Z., Talat, Z., Raja, A., Heinzer- ling, B., Si, C., Tas¸ar, D. E., Salesky, E., Mielke, S. J., Lee, W. Y., Sharma, A., Santilli, A., Chaffin, A., Stiegler, A., Datta, D., Szczechla, E., Chhablani, G., Wang, H., Pandey, H., Strobelt, H., Fries, J. A., Rozen, J., Gao, L., Sutawika, L., Bari, M. S., Al-shaibani, M. S., Manica, M., Nayak, N., Teehan, R., Albanie, S., Shen, S., Ben-David, S., Bach, S. H., Kim, T., Bers, T., Fevry, T., Neeraj, T., Thakker, U., Raunak, V., Tang, X., Yong, Z.-X., Sun, Z., Brody, S., Uri, Y., Tojarieh, H., Roberts, A., Chung, H. W., Tae, J., Phang, J., Press, O., Li, C., Narayanan, D., Bourfoune, H., Casper, J., Rasley, J., Ryabinin, M., Mishra, M., Zhang, M., Shoeybi, M., Peyrounette, M., Patry, N., Tazi, N., Sanseviero, O., von Platen, P., Cor- nette, P., Lavall´ee, P. F., Lacroix, R., Rajbhandari, S., Gandhi, S., Smith, S., Requena, S., Patil, S., Dettmers, T., Baruwa, A., Singh, A., Cheveleva, A., Ligozat, A.-L., Subramonian, A., N´ev´eol, A., Lovering, C., Garrette, D., Tunuguntla, D., Reiter, E., Taktasheva, E., Voloshina, E., Bogdanov, E., Winata, G. I., Schoelkopf, H., Kalo, J.-C., Novikova, J., Forde, J. Z., Clive, J., Kasai, J., Kawamura, K., Hazan, L., Carpuat, M., Clinciu, M., Kim, N., Cheng, N., Serikov, O., Antverg, O., van der Wal, O., Zhang, R., Zhang, R., Gehrmann, S., Mirkin, S., Pais, S., Shav- rina, T., Scialom, T., Yun, T., Limisiewicz, T., Rieser, V., Protasov, V., Mikhailov, V., Pruksachatkun, Y., Belinkov, Y., Bamberger, Z., Kasner, Z., Rueda, A., Pestana, A., Feizpour, A., Khan, A., Faranak, A., Santos, A., Hevia, A., Unldreaj, A., Aghagol, A., Abdollahi, A., Tammour, A., HajiHosseini, A., Behroozi, B., Ajibade, B., Saxena, B., Ferrandis, C. M., Contractor, D., Lansky, D., David, D., Kiela, D., Nguyen, D. A., Tan, E., Baylor, E., Ozoani, E., Mirza, F., Ononiwu, F., Rezanejad, H., Jones, H., Bhattacharya, I., Solaiman, I., Sedenko, I., Nejadgholi, I., Passmore, J., Seltzer, J., Sanz, J. B., Dutra, L., Samagaio, M., Elbadri, M., Mieskes, M., Gerchick, M., Akinlolu, M., McKenna, M., Qiu, M., Ghauri, M., Burynok, M., Abrar, N., Rajani, N., Elkott, N., Fahmy, N., Samuel, O., An, R., Kromann, R., Hao, R., Alizadeh, S., Shub- ber, S., Wang, S., Roy, S., Viguier, S., Le, T., Oyebade, T., Le, T., Yang, Y., Nguyen, Z., Kashyap, A. R., Palas- ciano, A., Callahan, A., Shukla, A., Miranda-Escalada, A., Singh, A., Beilharz, B., Wang, B., Brito, C., Zhou, C., Jain, C., Xu, C., Fourrier, C., Peri˜n´an, D. L., Molano, D., Yu, D., Manjavacas, E., Barth, F., Fuhrimann, F., Al- tay, G., Bayrak, G., Burns, G., Vrabec, H. U., Bello, I., Dash, I., Kang, J., Giorgi, J., Golde, J., Posada, J. D., Sivaraman, K. R., Bulchandani, L., Liu, L., Shinzato, L., de Bykhovetz, M. H., Takeuchi, M., P`amies, M., Castillo, M. A., Nezhurina, M., S¨anger, M., Samwald, M., Cullan, M., Weinberg, M., De Wolf, M., Mihaljcic, M., Liu, M., Freidank, M., Kang, M., Seelam, N., Dahlberg, N., Broad, N. M., Muellner, N., Fung, P., Haller, P., Chandrasekhar, R., Eisenberg, R., Martin, R., Canalli, R., Su, R., Su, R., Cahyawijaya, S., Garda, S., Deshmukh, S. S., Mishra, S., Kiblawi, S., Ott, S., Sang-aroonsiri, S., Kumar, S., Schweter, S., Bharati, S., Laud, T., Gigant, T., Kainuma, Improving Code Generation by Training with Natural Language Feedback T., Kusa, W., Labrak, Y., Bajaj, Y. S., Venkatraman, Y., Xu, Y., Xu, Y., Xu, Y., Tan, Z., Xie, Z., Ye, Z., Bras, M., Belkada, Y., and Wolf, T. Bloom: A 176b-parameter open-access multilingual language model, 2022. URL https://arxiv.org/abs/2211.05100. Xu, F. F., Alon, U., Neubig, G., and Hellendoorn, V. J. A systematic evaluation of large language models of code. In Proceedings of the 6th ACM SIGPLAN Inter- national Symposium on Machine Programming, MAPS 2022, pp. 1–10, New York, NY, USA, 2022. Associa- tion for Computing Machinery. ISBN 9781450392730. doi: 10.1145/3520312.3534862. URL https://doi. org/10.1145/3520312.3534862. Zan, D., Chen, B., Yang, D., Lin, Z., Kim, M., Guan, B., Wang, Y., Chen, W., and Lou, J.-G. CERT: Continual pre- training on sketches for library-oriented code generation. In The 2022 International Joint Conference on Artificial Intelligence, 2022. Ziegler, A., Kalliamvakou, E., Li, X. A., Rice, A., Rifkin, D., Simister, S., Sittampalam, G., and Aftandilian, E. Productivity assessment of neural code completion. In Proceedings of the 6th ACM SIGPLAN International Symposium on Machine Programming, MAPS 2022, pp. 21–29, New York, NY, USA, 2022. Association for Com- ISBN 9781450392730. doi: 10. puting Machinery. 1145/3520312.3534864. URL https://doi.org/ 10.1145/3520312.3534864. Ziegler, D. M., Stiennon, N., Wu, J., Brown, T. B., Rad- ford, A., Amodei, D., Christiano, P., and Irving, G. Fine-tuning language models from human preferences. arXiv preprint arXiv:1909.08593, 2019. URL https: //arxiv.org/abs/1909.08593. Improving Code Generation by Training with Natural Language Feedback # A. Appendix # A.1. Training Details For the experiments in Section 3.2, we run a hyperparameter sweep for all methods except for ILF. The hyperparameter value ranges that we sweep include learning rate ∈ {1.0−6, 5.0−6, 1.0−5}, batch size ∈ {32, 64, 128}, and number of epochs ∈ {1, 2, 5}. The tasks for the training and validation datasets are from MBPPTrain and MBPPRefine, respectively, while the programs are sourced from the method (e.g. InstructGPT, MBPP, human-written, or zero-shot CODEGEN-MONO 6.1B). For ILF, we use the best hyperparameters obtained for the sweep over MBPP programs instead of sweeping over ILF-generated programs, since the tasks in MBPPRefine are already used to train πRefine. All pass rates reported in Table 4 are obtained by evaluating each method on MBPPTest using the best hyperparameters found during the sweep on MBPPRefine. For the experiments in Section 3.3, we separately tune hyperparameters for each size of dataset. As in our other experiments, we train and validate using the tasks from MBPPTrain and MBPPRefine, respectively, coupled with the refinements generated by InstructGPT that pass the unit test suites. We sweep the same hyperparameter value ranges as the experiments in the previous section (i.e. learning rate ∈ {1.0−6, 5.0−6, 1.0−5}, batch size ∈ {32, 64, 128}, and number of epochs ∈ {1, 2, 5}). We implement all experimental pipelines with the HuggingFace transformers (v4.12.5) (Wolf et al., 2020), Huggingface datasets (v2.7.1) (Lhoest et al., 2021), and Pytorch (v1.11) (Paszke et al., 2019) libraries. Improving Code Generation by Training with Natural Language Feedback # A.2. Annotator Instructions NL Feedback for Code Generation Given a natural language description of a Python programming challenge and its accompanying unit tests, you will be shown 10 sample model-generated Python solutions that do not pass the tests. Please do the following: 1) Select one model-generated code sample that seems relatively easy to correct (such that it can be minimally corrected to pass the unit tests). If no such code sample exists (ie every code sample would require extensive correction, select the corresponding option and move on to the next task. 2) Write ~1-4 sentences of natural language feedback for the code sample that does two things: (a) describes what is wrong with the code sample, and (b) how it can be fixed. You can use individual variable or method names, but please do not include entire lines of code. Try to describe the necessary logic using mostly natural language, not Python expressions. Below are some examples of good versus bad feedback: Good: "The current code is wrong because it returns items using the heappop method in the hq module, which gets the smallest items even though the task description actually asks for the largest items. Instead, the code should use the nlargest function in hq to get the largest n integers." Bad (because it only describes what to change, and not what was originally wrong with the code): “The code should use the nlargest function in hq to get the largest n integers.” Bad (because it gives the actual code needed to fix the function, instead of describing the desired fix using words only): "The current code is wrong because it returns items using the heappop method in the hq module, which gets the smallest items even though the task description actually asks for the largest items. Instead, the function should return [hq.heappop(nums) for i in range(n)]." 3) Write a refinement for the code that consists of copying the original model sample and making minimal edits to the code such that it correctly solves the challenge and can pass all the unit tests. Here is an example. We only show a couple of model samples here for brevity, but in practice you will be shown up to 10 model samples per task. Figure 6. An example of the instructions given to Surge annotators. Improving Code Generation by Training with Natural Language Feedback # A.3. Examples of Human Versus InstructGPT Feedback Table 7: Examples of natural language feedback written by humans versus InstructGPT for incorrect programs generated by CODEGEN-MONO 61.B. Incorrect program generated by CODEGEN- MONO 6.1B Human feedback # InstructGPT feedback """ Write a function to assign frequency to each tuple in the given tuple list. >>> Example: assign_freq([(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)] ) = ’[(6, 5, 8, 3), (2, 7, 2), (9, 1)]’ """ from collections import Counter def assign_freq(test_list): """ >>> assign_freq([(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)] ) = ’[(6, 5, 8, 3), (2, 7, 2), (9, 1)]’ """ counter = Counter(x for x in test_list) res = [] for key, val in counter.items(): temp = (key, val) res.append( temp) return str(res) “The only issue with this code is that it does not dereference the key. When you set temp = (key, val), the key is an entire tuple instead of the values in the tuple. Thus, you need the asterisks to get the values” _ “The function works as in- tended.” """ Write a function to get the angle of a complex number. >>> Example: angle_complex(0,1 j)=1.5707963267948966 """ “Only one thing is wrong in the code that complex method can take the complex number as ar- gument example complex(a+b) not like complex(a,b) we have to replace, by + and the code is fine.” “The code should use the atan2 function to get the angle of a complex number.” import cmath def angle_complex(a,b): return cmath.phase( complex(a,b)) Improving Code Generation by Training with Natural Language Feedback Table 7: Continued from previous page Incorrect program generated by CODEGEN- MONO 6.1B Human feedback # InstructGPT feedback """ Write a function to count the same pair in three given lists. >>> Example: count_samepair ([1,2,3,4,5,6,7,8], [2,2,3,1,2,6,7,9], [2,1,3,1,2,6,7,9])=3 """ def count_samepair(list1,list2 ,list3): count = 0 for i in range(len(list1)) : for j in range(len( list2)): if list1[i]==list2 [j] and list2[j]==list3[i ]: count+=1 return count “One extra for loop for list2 is causing the issue, it finds more matching elements be- tween list1,2,3. The possible solution for the code is to re- move the unnecessary for loop of list2 iteration, and check all the lists same index element at the time, and return the count of this element.” “The code above is very ineffi- cient. It is checking every pos- sible combination of pairs of elements in the three lists. It would be much more efficient to use a set to keep track of the pairs that have already been seen.” """ Write a function to find number of lists present in the given tuple. >>> Example: find_lists(([1, 2, 3, 4], [5, 6, 7, 8])) = 2 """ def find_lists(Input): result = 0 for x in Input: if isinstance(x, list) : result += 1 return result “The code works for tuples of more than one list, but not in case of one single list. Python goes one level down and reads the elements when given a single list and does I not see an instance of list. would just check for the case of ‘type(Input) == list’ and turn the input into a 1-sized list of lists in this case.” “The function find lists needs to return the number of lists present in the given tuple, not the number of items in the tu- ple.” Improving Code Generation by Training with Natural Language Feedback Table 7: Continued from previous page Incorrect program generated by CODEGEN- MONO 6.1B Human feedback InstructGPT feedback """ Write a function to calculate magic square. >>> Example: magic_square_test ([[7, 12, 1, 14], [2, 13, 8, 11], [16, 3, 10, 5], [9, 6, 15, 4]])=True """ def magic_square_test( my_matrix): """ >>> magic_square_test([[7, 12, 1, 14], [2, 13, 8, 11], [16, 3, 10, 5], [9, 6, 15, 4]])=True """ def is_square(x): return x==x*x def is_magic_square( my_matrix): sides=[] for i in range(len( my_matrix)): sides.append(sum( my_matrix[i])) if not is_square(sum( sides)): return False sides=[] for i in range(len( my_matrix)): sides.append(sum([ my_matrix[i][j] for j in range(len(my_matrix))])) if not is_square(sum( sides)): return False diagonals=[] for i in range(len( my_matrix)): diagonals.append( my_matrix[i][i]) if not is_square(sum( diagonals)): return False diagonals=[] for i in range(len( my_matrix)): diagonals.append( my_matrix[i][len(my_matrix )-1-i]) if not is_square(sum( “The logic behind checking whether rows, columns, and diagonals is a magic number or not is not correct, the code checks if the sum of squares of itself in the is square method is Instead of checking wrong. all the sums of rows, columns, and diagonals at every point, the logic should be like sav- ing all the sums for rows, columns, and diagonals in one array(sides) and then checking if there are all same values present in this array because for magic square test all the sums should be equal.” function “The magic square test should return whether my matrix is a magic square.” # diagonals)): # return False # return True # return is_magic_square( my_matrix) Improving Code Generation by Training with Natural Language Feedback Table 7: Continued from previous page Incorrect program generated by CODEGEN- MONO 6.1B Human feedback InstructGPT feedback """ Write a python function to count characters at same position in a given string (lower and uppercase characters) as in english alphabet. >>> Example: count_char_position(" xbcefg") = 2 """ def count_char_position(str1): counter = 0 for i in range(0, len(str1 )): if str1[i] == str1[i]. upper(): counter += 1 # return counter “a) The first thing that the code sample gets incorrect is that it increments the counter when each character in the string is an upper case character. The prompt is asking for how many characters in str1 have the same numerical position as their re- spective alphabetic counterpart and the code does not check for this at all. b) The way to fix it would be to create a sepa- rate j variable that keeps track of the ordinal value that cor- responds with the alphabetic character that we would expect to be compared to the respec- tive character in str1. j and i would increment at the same time so that the code is both iterating through the alphabet AND iterating through str1 si- multaneously. The other fix would be to automatically con- vert str1 to lowercase so that we don’t have to worry about checking the ordinal codes of both the lowercase and upper- case versions of the same al- phabetic character.” # “Great job!”
Title: An In-depth Survey of Large Language Model-based Artificial Intelligence Agents: Summary: Due to the powerful capabilities demonstrated by large language model (LLM), there has been a recent surge in efforts to integrate them with AI agents to enhance their performance. In this paper, we have explored the core differences and characteristics between LLM-based AI agents and traditional AI agents. Specifically, we first compare the fundamental characteristics of these two types of agents, clarifying the significant advantages of LLM-based agents in handling natural language, knowledge storage, and reasoning capabilities. Subsequently, we conducted an in-depth analysis of the key components of AI agents, including planning, memory, and tool use. Particularly, for the crucial component of memory, this paper introduced an innovative classification scheme, not only departing from traditional classification methods but also providing a fresh perspective on the design of an AI agent's memory system. We firmly believe that in-depth research and understanding of these core components will lay a solid foundation for the future advancement of AI agent technology. At the end of the paper, we provide directional suggestions for further research in this field, with the hope of offering valuable insights to scholars and researchers in the field. # An In-depth Survey of Large Language Model-based Artificial Intelligence Agents Pengyu Zhao∗, Zijian Jin∗, Ning Cheng Beijing Jiaotong University, New York University, zj2076@nyu.edu {pengyuzhao, ningcheng}@bjtu.edu.cn Abstract Due to the powerful capabilities demonstrated by large language model (LLM), there has been a recent surge in efforts to integrate them with AI agents to enhance their performance. In this paper, we have explored the core differences and characteristics between LLM-based AI agents and traditional AI agents. Specifically, we first compare the fundamental characteristics of these two types of agents, clarifying the significant advantages of LLM-based agents in handling natural language, knowledge storage, and reasoning capabilities. Subsequently, we conducted an in-depth analysis of the key components of AI agents, including planning, memory, and tool use. Particularly, for the crucial component of memory, this paper introduced an innovative classification scheme, not only departing from traditional classification methods but also providing a fresh perspective on the design of an AI agent’s memory system. We firmly believe that in-depth research and understanding of these core components will lay a solid foundation for the future advancement of AI agent technology. At the end of the paper, we provide directional suggestions for further research in this field, with the hope of offering valuable insights to scholars and researchers in the field. Keywords: AI agents, Survey, Large language model # 1. Introduction The notion of intelligent agents can trace its roots back to the research of the mid to late 20th century. Pioneering contributions in this realm encompass Hewitt’s Actor model (Hewitt et al., 1973) and Minsky’s innovative conceptualization in the ’So- ciety of Mind’ (Minsky, 1988) which still trigger some new ideas recently eg: ”Mindstorms in Nat- ural Language-Based Societies of Mind” (Zhuge and et al., 2023).In the 1990s, Russell introduced the framework for intelligent and rational agents (Russell and Norvig, 2010), which has since be- come a foundational theory in this field. The ad- vent of deep neural networks post-2012 marked a significant shift in the AI landscape. Leveraging the power of backpropagation (Rumelhart et al., 1986) for training deep models, researchers be- gan to explore more sophisticated agent behaviors, transcending beyond traditional rule-based meth- ods. Among the emergent methodologies, Rein- forcement Learning (RL) stood out as a paradigm where agents learn optimal behavior through inter- actions with the environment and receiving feed- back in the form of rewards or penalties. In 2013, DeepMind (Mnih et al., 2013) used RL to play the Atair Game and win humans’ performance which indicates that AI Agents are available to outper- form human capabilities in specific areas. The in- corporation of neural networks into RL, often re- ferred to as Deep Reinforcement Learning (DRL) (Li, 2017), allowed for the tackling of previously in- | tractable problems, bridging the gap between high- dimensional input spaces and complex decision- making processes (Arulkumaran et al., 2017). De- spite the promising advancements offered by DRL, certain challenges persist. Chief among these is the issue of generalization. Many reinforcement learn- ing agents, especially those trained in simulated environments, struggle to transfer their learned be- havior to new or slightly altered scenarios, often termed as domain adaptation (Arndt et al., 2020). Training these agents can also be computationally intensive, often requiring vast amounts of inter- actions to achieve satisfactory performance. Fur- thermore, Reinforcement learning training strug- gles with convergence and the design of reward functions can be challenging, particularly in real- world scenarios, and can be a daunting and often unfeasible task. This hampers the rapid develop- ment and deployment of RL-based agents in di- verse environments. In 2020, OpenAI released GPT3 (Brown et al., 2020) with 175 billion parameters, making it the largest publicly available language model at the time. These models, characterized by their im- mense size and capacity, have shown exceptional prowess in generalization across a myriad of tasks. The ability of LLMs to understand and gener- ate language allows them to act as a foundational model for a wide range of applications (Huang and Chang, 2022). Their inherent generalization capabilities make them ideal candidates to serve as base models for universal agents. By harness- # ∗Equal contribution. ing the vast knowledge embedded within LLMs, researchers are now exploring hybrid models, in- tegrating the strengths of reinforcement learning with the generalization capacities of LLMs (Hu et al., 2023). This symbiotic combination promises to pave the way for more robust, adaptable, and efficient intelligent agents in the future. In order to assist readers in quickly understanding the research history of AI agents and to further in- spire research in AI agents, in this paper, we offer a comprehensive and systematic review of AI agents based on the components1 and applications. 2. LLM vs. Traditional Agents Traditional agents were designed specifically to ad- dress certain problems. They primarily relied on predetermined algorithms or rule sets, excelling in tasks they were built for. However, they often struggled with generalization and reasoning when confronted with tasks outside their initial scope. The introduction of Large Language Models (LLMs) has brought significant changes to AI agent design. These agents, trained on the exten- sive corpus, are not only proficient in understand- ing and generating natural language but also dis- play strong generalization abilities. This capability allows them to easily integrate with various tools, enhancing their versatility. On the other hand, the emergent abilities of Large Language Models (Wei et al., 2022a) shows that LLMs are also good at reasoning which can help them learn from fault behavior. Taking game exploration as an example, espe- cially in the Minecraft setting, the differences be- tween LLM-based agents like VOYAGER (Wang et al., 2023a) and traditional RL agents are ev- ident. LLM agents, with their rich pre-trained knowledge, have an advantage in decision-making strategies even without task-specific training. On the other hand, traditional RL agents often need to start from scratch in new environments, rely- ing heavily on interaction to learn. In this sce- nario, VOYAGER showcases better generalization and data efficiency. # 3. Components of AI Agents 3.1. Overview The LLM-powered AI agent system relies on LLM to function as its brain, which is supported by sev- eral crucial components that deploy various impor- tant functions. These functions, including plan- ning, memory, and tool use, have been studied in- dependently and thoughtfully in the past and have a well-established history. In this survey, we will 1The key components of AI agents were originally defined at https://lilianweng.github.io/posts/2023-06- 23-agent/ introduce the research history of each individual functional model, mainstream methods, combina- tion methods with the AI agent, and potential di- rections for the future. We hope that this historical information will serve as an inspiration for the fu- ture development of AI agents. It is worth noting that the integration of these three functional mod- els is still a relatively new concept. # 3.2. Planning The goal of planning is to design a series of ac- tions to facilitate state transitions and ultimately achieve the desired task. As shown in the left of Figure 1, this component, functioning as an in- dividual module, has been integrated in various applications, such as robot manipulations (Chen et al., 2021), robot navigation (Lo et al., 2018), and service robots (Li and Ding, 2023). And the existing works, such as methods using the planning domain description language (PDDL) (Aeronau- tiques et al., 1998; Fox and Long, 2003; Jiang et al., 2019) and hierarchical planning frameworks (Erol et al., 1994; Su´arez-Hern´andez et al., 2018; Guo et al., 2023), have greatly propelled the advance- ment of planning systems. Recently, with signif- icant successes achieved by LLMs in various do- mains, numerous studies have been exploring the utilization of LLMs to enhance the planning and execution capabilities of AI agents. Benefiting from the powerful inference capabilities of LLM, LLM-based AI agents can efficiently decompose complex tasks or instructions into a series of sub- tasks or simpler instructions (i.e., planning). For instance, as shown in the top right of Figure 1, the LLM-based agent decomposes the complex instruc- tion “Put the banana on the counter” into a se- ries of simpler instructions which are easier for the agent to accomplish. Further, taking actions solely based on the initial plan formulated by the agent without considering external environmental feed- back may limit the performance of the agent. For example, as shown in the bottom right of Figure 1, an agent creates a plan for the instruction “Put the bat on the bed”, and the first step in the initial planning is “Pick up the baseball bat”, which may fail to execute when there is no ’bat’ nearby. How- ever, if the agent can self-reflection based on the feedback, it can refine the first step to ”Walk to the side of the baseball bat”, and then progressively work towards achieving the goal. Therefore, dur- ing the execution process, reflecting on and analyz- ing past behaviors and feedback, and subsequently adjusting the plan, are equally pivotal for the suc- cessful execution of tasks by AI agents. Next, we will introduce relevant works that utilize LLM for task decomposition and self-reflection. Robot manipulations Robot navigation Applications Service robot LLM-based methods Feedback Plan domain 7 description language Representative Hierarichical planning works framework Planning Task decompo’ You can only pick up the baseball bat if you're next to it, but it's not currently beside you. Put the banana on the counter Step 1: Pick up the banana. Step 2: Go to the counter. Step 3: Put down the banana, Put a bat on the bed Step 1: Pick up the baseball bat. Refinement planning Step 1: Walk to the side of the baseball bat. Step 2: Pick up the baseball bat. Step 3: Walk to the bed. Step 4: Lean the bat on bed. Figure 1: Overview of the planning component of AI agent. Left introduces some applications and representative methods of planning. Right provides an example illustrating the working mechanism of an AI agent with task decomposition and self-reflection. # 3.2.1. Task Decomposition Task decomposition aims to decompose the com- plex task or instruction into a series of simpler sub- goals or sub-instructions for performing the task. For example, as shown in the top right of Fig- ure 1, given a task instruction ”Put the banana on the counter”, the agent will split it into three steps: 1. Pick up the banana. 2. Go to the counter. 3. Put down the banana. The exist- ing works mainly perform task decomposition by chain or tree of thought (Wei et al., 2022b; Ko- jima et al., 2022; Yao et al., 2023a) and PDDL with LLM (Liu et al., 2023a). Chain of thought can utilize a few examples or simple instructions to progressively guide LLM reasoning, in order to decompose complex tasks into a series of sim- pler tasks (Wei et al., 2022b; Zhang et al., 2022; Huang et al., 2022a; Wang et al., 2023b). Zhang et al. (Zhang et al., 2022) proposed a method for au- tomatically generating chain of thought samples. They first clustered the problems and then, for each cluster, selected representative questions to generate chain of thought samples in a zero-shot manner. Huang et al. (Huang et al., 2022a) uti- lized high-level tasks related to the given task and their decomposed planning steps as examples, and combined these examples with input information to construct prompts. Then, they employed LLM to predict the next steps of planning and added the generated steps to the original prompts, con- tinuing the prediction until the entire task was completed. Wang et al. (Wang et al., 2023b) pro- posed that by guiding LLM to first construct a series of plans and then progressively execute so- lutions, it can effectively alleviate the issue of in- termediate plans disappearing during the reason- ing process. Unlike linear thinking, the Tree of Thought (Long, 2023; Yao et al., 2023a) generates multiple branches of thoughts at each step to cre- ate a tree-like structure. Subsequently, searching on this tree of thought is conducted using meth- ods like breadth-first search or depth-first search. For evaluating each state, reasoning can be facili- tated using a ”value prompt” or assessment results can be generated through a voting mechanism. In addition, some research efforts consider combining LLM with PDDL for the purpose of planning tar- get problems (Xie et al., 2023; Liu et al., 2023a; Guan et al., 2023). For example, Liu et al. (Liu et al., 2023a) first conveyed the task description in the form of natural language to LLM for translat- ing to PDDL format by in-context learning, then they employed the classical planners to generate plans and converted them into natural language format by LLM again. 3.2.2. Self-Reflection During the process of interacting with the environ- ment, AI agents can enhance their planning ability by reflecting on past actions by receiving feedback. There are many works attempt to combine LLM- based agents with the self-reflection (Yao et al., 2022; Huang et al., 2022b; Shinn et al., 2023; Liu et al., 2023b; Sun et al., 2023; Singh et al., 2023; Yao et al., 2023b; Chen and Chang, 2023). For ex- ample, Yao et al. (Yao et al., 2022) integrated ac- tions with the chain of thought, leveraging thought to formulate planning that guides the agent’s exe- cution of acts. Simultaneously, interactive execu- tion of actions in the environment further enhances the agent’s planning ability. Shinn et al. (Shinn et al., 2023) introduced a framework named Reflex- ion, in which the approach first generates actions through the Actor module and evaluates them. Then utilizes the self-reflection module to gener- ate feedback and store it in memory. When errors occur, this method can infer the actions that led to the errors and correct them, thereby continuously enhancing the agent’s capabilities. Liu et al. (Liu et al., 2023b) first rated the various outputs of the model based on human feedback, then they used prompt templates to construct these ratings into natural language forms and combined them with the outputs for fine-tuning the model, thereby en- abling it to learn self-reflection. Singh et al. (Singh et al., 2023) utilize Pythonic program and annota- tions to generate planning, wherein assertion func- tions are used to obtain feedback from the envi- ronment. When assertions are false, error recovery can be performed. Sun et al. (Sun et al., 2023) proposed a model named AdaPlanner, which uti- lizes two refiners to optimize and refine plans. One of the refiners collects information from the envi- ronment after executing an action, which is then utilized for subsequent actions. The other one ad- justs the existing plan based on feedback obtained from the external environment when the executed action fails to achieve its intended outcome. Simi- larly, Yao et al (Yao et al., 2023b). first finetuned a small language model as a retrospective model to generate feedback for past failures, and then ap- pended this feedback to the actor prompt as input of the large LLM for preventing the recurrence of similar errors and predicting the next action. # 3.3. Memory Memory can help individuals integrate past learned knowledge and experience events with their cur- rent state, thereby assisting in making more appro- In general, human memory can priate decisions. be categorized into three primary types: sensory memory, short-term memory, and long-term mem- ory (Camina and G¨uell, 2017). Sensory memory is the collection of information through the senses of touch, hearing, vision, and other senses, and it has an extremely brief lifespan (Wan et al., 2020; Jung et al., 2019). Short-term memory refers to the pro- cess of handling information within a brief period, and it is typically carried out by working mem- ory (Hunter, 1957; Baddeley, 1983, 1997). In con- trast, long-term memory refers to memories that can be stored for an extended period, which en- compasses episodic memory and semantic memory. Episodic memory refers to the memory capacity for events that individuals have personally experi- enced, and it is often able to closely associate these events with contextual information (Tulving et al., 1972; Tulving, 1983). Semantic memory refers to the factual knowledge that individuals know, and this type of memory is unrelated to specific events and personal experiences (Tulving et al., 1972). Similarly, memory, as a key component of AI agents, can assist them in learning valuable knowl- edge from past information, thereby helping the agents perform tasks more effectively. To fully uti- lize the stored information in memory, some re- search has attempted to integrate AI agents with short-term memory (Kang et al., 2023; Peng et al., long-term memory (Vere and Bickmore, 2023), 1990; Kazemifard et al., 2014), and a combination of both (Nuxoll and Laird, 2007; Kim et al., 2023; Yao et al., 2023b; Shinn et al., 2023). In addition, since sensory memory can be regarded as the em- bedded representation of inputs such as text and images, similar to a sensory buffer, we consider sen- sory memory not to be part of the memory module of the AI agent. With the emergence of large lan- guage models (LLM), some works devoted to drive the development of AI agents using LLM. Consid- ering the characteristics of LLM, as shown in Fig- ure 2, we further redefine the concepts of memory types for AI agents and classify them into training memory, short-term memory, and long-term mem- ory. Training memory refers to the knowledge and facts that a model learns during the pre-training pro- cess, and this information is stored through model parameters. Existing research has shown that models can learn world knowledge (Rogers et al., 2021), relational knowledge (Petroni et al., 2019; Safavi and Koutra, 2021), common sense knowl- edge (Davison et al., 2019; Da et al., 2021; Bian et al., 2023), semantic knowledge (Tang et al., 2023), and syntactic knowledge (Chiang et al., 2020) during the pre-training phase. Therefore, by employing LLM for reasoning, the AI agent can implicitly recall this knowledge to enhance the model’s performance. Short-term memory refers to the temporary infor- mation that AI agents process during task execu- tion, such as the example information involved in the in-context learning process and the intermedi- ate results generated during LLM inference. Dur- ing the inference process, LLM temporarily stores and processes in-context information or intermedi- ate results, using them to improve the ability of the model. This is similar to human working memory, which temporarily holds and processes informa- tion in the short-term to support complex cognitive tasks (Gong et al.). Some works utilize in-context learning to improve the performance of LLM. They first combine some examples with input informa- tion to construct a prompt and then send this prompt to LLM to utilize short-term memory (Li et al., 2023b; Logeswaran et al., 2022; Omidvar and An, 2023). For example, Li et al. (Li et al., 2023b) pointed out that when provided with a con- text that is relevant to the task, it is important to ensure that its working memory is controlled by the context. Otherwise, the model should rely on the world knowledge obtained during the pre- Human's Memory Sensory Memory Short-term Memory Long-term Memory Episodic Memory Semantic Memory Intelligent Agent with LLM > Input Embedding The knowledge and facts that LLM learns during the pre-training process. Stored through model parameters. Short-term Memory Temporary information that LLM process during task execution . Long-term Memory ' 1 Stored in an external storage system | : Figure 2: Mapping Structure of Memory: Left illustrates memory categories in human memory, while the right depicts memory categories in AI agents, which have been redefined based on the characteristics of LLM. training phase. Logeswaran et al. (Logeswaran et al., 2022) first combined some examples with input instructions as a prompt, and then gener- ated multiple candidate sub-goal plans using LLM. Subsequently, they employed a re-rank model to se- lect the most suitable plan from these candidates. Some works prompt LLM to output its thinking process and results in the form of chain-of-thought, or to feed the intermediate results from LLM’s inference into LLM for further reasoning (Huang et al., 2022a; Akyurek et al., 2023; Chen et al., 2023b,a; Zhang et al., 2023a; Chen et al., 2023c). For example, Zhang et al. (Zhang et al., 2023a) first guided the model to generate a chain of thought by engaging it in multi-turn dialogues based on the given context. Subsequently, they combined the context with the generated chain of thought to form samples, which are then used to assist the model in reasoning and prediction under new con- textual situations. Akyurek et al. (Akyurek et al., 2023) proposed a multi-agent collaborative system that includes two LLMs. One LLM is responsible for generating answers based on the input content, while the other LLM generates a textual critique based on the input and output of the first LLM to assist in error correction. Long-term memory refers to the information stored in an external storage system, and when AI agents use this memory, they can retrieve information rel- evant to the current context from the external stor- age. The utilization of long-term memory can be information storage, in- divided into three steps: formation retrieval, and information updating. In- formation storage aims to store essential informa- tion from the interactions between the agent and its environment. For example, Shuster et al. (Shus- ter et al., 2022) first generated a summary of the last interaction. If the generated summary is ”no persona,” it is not stored; otherwise, the summary information is stored in long-term memory. Zhang et al. (Zhang et al., 2023b) utilized a tabular for- mat to store memory in the form of key-value pairs. In this format, the observations and states serve as the keys, and the actions and their corresponding Q-values are stored as values. Liang et al. (Liang et al., 2023a) stored the relevant information from the interactions between the agent and the environ- ment. The information from the last interaction is stored in the flash memory for quick retrieval. The rest of the information is stored in the action mem- ory as long-term memory. Information retrieval aims to retrieve information relevant to the cur- rent context from long-term memory to assist the agent in performing tasks. For example, Lee et al. (Lee et al., 2023) first clarified the input infor- mation, then they employed dense passage retriev- ers to select relevant information from long-term memory. Afterward, they combined the selected information with the input information and used methods like chain-of-thought or few-shot learning to choose the most relevant information for task execution. Zhang et al. (Zhang et al., 2023b) first computed the similarity between the received in- formation and the keys stored in the long-term memory, and then selected the top k records with the highest similarity to assist the LLM’s decision- making. Information updating aims to update the stored long-term memory. For example, Zhong et al. (Zhong et al., 2023) designed a forgetting mech- anism based on the Ebbinghaus forgetting curve to simulate the updating process of human long-term memory. 3.4. Tool Use Recent works have greatly propelled the devel- opment of LLMs, however, LLMs still fail to achieve satisfactory performance in certain sce- narios involving up-to-date information, computa- tional reasoning, and others. For example, when a user asks, ’Where is the global premiere of Op- penheimer?’, ChatGPT is unable to answer this question because the movie ’Oppenheimer’ is the latest information and is not included in the train- ing corpus of the LLM. To bridge these gaps, many efforts have been dedicated to integrating LLM with external tools Some works aim to to extend its capabilities. integrate LLM with specific tools such as web search (Nakano et al., 2021), translation (Thoppi- lan et al., 2022), calculators (Cobbe et al., 2021), and some plugins of ChatGPT2. Some other works consider teaching LLMs to choose suitable tools or combine various tools to accomplish tasks. For example, Karpas et al. (Karpas et al., 2022) imple- mented a system named MRKL, which mainly con- sists of a language model, an adapter, and multiple experts (e.g., model or tools), where the adapter is utilized to select the appropriate expert to assist the language model in processing input requests. Parisi et al. (Parisi et al., 2022) designed an iter- ative self-play algorithm to assist LM in learning how to utilize external APIs by fine-tuning LM. In self-play, they first fine-tuned LM with a few sam- ples and then utilized it to generate the tool in- put for invoking the tool API to generate results, followed by an LM to infer an answer. If the re- ferred answer is similar to the golden answer, the task input and predicted results (i.e., tool input, tool result, and predicted answer) are appended to the corpus sets for further fine-tuning and itera- tion in the next round. Patil et al. (Patil et al., 2023) first constructed a dataset with the format of instruct-API pairs, and then fine-tuned LLM based on the dataset for aiding LLM to employ tools with zero-shot and retriever-aware. Similarly, Schick et al. (Schick et al., 2023) fine-tuned the LLM on a dataset containing API calls to help the LLM learn the ability to invoke APIs. Paranjape et al. (Paranjape et al., 2023) first retrieved the related examples with the input task as a prompt and then employed the LLM to implement infer- 2https://openai.com/blog/chatgpt-plugins ence with chain reasoning. In this process, if the immediate step requires tools, the inference process is paused to execute the tools, and the output of the tools is inserted into the inference process. Li et al. (Li et al., 2023c) proposed the API bank to eval- uate the LLM’s ability to utilize tools and devised a tool-augmented LLM paradigm to alleviate the limitation of in-context length. Shen et al. (Shen et al., 2023) proposed a method to combine LLM with HuggingFace to enhance the performance of LLM. Specifically, the method first employs LLM to decompose complex tasks into a series of sub- tasks and then sequentially selects suitable models from HuggingFace to perform these sub-tasks. Lu et al. (Lu et al., 2023) designed a plug-and-play compositional reasoning method, which first plans the schedule of input tasks and then composes mul- tiple tools to execute sub-tasks for achieving the original task. Liang et al. (Liang et al., 2023b) first applied a multi-model foundation model to under- stand and plan the given instructions for selecting suitable APIs from the API platform, and then uti- lized an action executor to generate results based on the selected APIs. Besides, they also exploited the feedback of humans to optimize the ability of planning and choose APIs of LLM, and the docu- ment of API in API platform. Different from the above approaches, Cai et al. (Cai et al., 2023) first employed an LLM to generate tool for input task, and then utilized an LLM to perform task based on the generated tool. Specifically, for an incoming task, if the tool required by the task has been gen- erated, the tool will be invoked directly, otherwise, the LLM will first generates tool, and then uses it. # 4. Application AI Agent is not an emergent concept. As early as 1959, the world’s first complete artificial intelli- gence system, advice taker (McCarthy, 1959), was proposed. Subsequently, John McCarthy and oth- ers began to use the term Agent to describe the role that a computing program can play in a scene to achieve certain tasks in artificial intelligence. With reinforcement learning coming into promi- nence, the field of artificial intelligence has seen a number of notable AI agents based on reinforce- ment learning and gaming strategies, such as Al- phaGo (Silver et al., 2016), a Go agent launched by DeepMind in 2014. Similarly, OpenAI launched OpenAI Five (Berner and et al., 2019) for playing the game of Dota 2 in 2017 and DeepMind an- nounced AlphaStar (Vinyals et al., 2019) for play- ing StarCraft II. Recently, the emergence of Chat- GPT has made AI agents active once again. The LLM-based Agent also keeps emerging. In this pa- per, we focus on the latest LLM-based AI Agent applications and talk about the applications of AI Agent from seven aspects: chatbot, game, design, Category Application Description Chatbot Pi Inflection’s chatting AI agent known for its emotional companion- ship and high emotional intelligence Game Voyager (Wang et al., 2023a) The first LLM-powered embodied lifelong learning agent in Minecraft that continuously explores the world, acquires diverse skills, and makes novel discoveries without human intervention Coding GPT Engineer A AI coding agent that can generate an entire codebase based on a prompt Design Diagram An AI-powered and automatable design platform Research ChemCrow (Bran et al., 2023) Agent (Boiko et al., 2023) An LLM chemistry agent designed to accomplish tasks across or- ganic synthesis, drug discovery, and materials design An intelligent agent system that combines multiple large language models for autonomous design, planning, and execution of scien- tific experiments Collaboration DialOp (Lin et al., 2023a) MindOS MetaGPT Multi-GPT AI assistants collaborating with one or more humans via natural language to help them make complex decisions An engine creating autonomous AI agents for users’ professional tasks An multi-agent framework assigning different roles to GPTs to form a collaborative software entity for complex tasks An experimental multi-agent system where multiple “expertG- PTs” collaborate to perform a task and each has their own short and long-term memory and the ability to communicate with each other. Generative Agents (Park et al., 2023) Multiple AI agents for the interactive simulacra of human behavior General purpose Auto-GPT BabyAGI SuperAGI AgentGPT An AI agent chaining LLM “thoughts” together to autonomously achieve whatever goal users set An task-driven autonomous agent leveraging GPT-4 language model, Pinecone vector search, and the LangChain framework to perform a wide range of tasks across diverse domains A developer-centric open-source framework to build, manage and run useful Autonomous AI Agents A framework allow users to configure and deploy Autonomous AI agents rapidly Table 1: LLM-based AI Agent applications. research, coding, collaboration, and general pur- pose, as shown in Tab. 1. 4.1. Chatbot Pi3 is a typical LLM-based chatting AI agent re- leased by Inflection. Like ChatGPT4 and Claude5, users can talk directly with Pi, but Pi not only serves productivity needs such as searching or an- swering questions but also focuses on emotional companionship. Pi is known for its high emotional intelligence. Users can communicate with Pi as naturally as they would with a close friend. LLM-based agents are naturally used in code gen- eration. A very attractive coding agent is GPT Engineer6, which can generate an entire codebase according to a prompt. GPT Engineer even learns the developer’s coding style and lets the devel- oper finish the coding project in just a few min- utes. What makes GPT Engineer unique is that GPT Engineer asks many detailed questions to al- low developers to clarify missing details instead of accepting these requests unconditionally made by developers. 4.2. Game No other LLM-based gaming intelligence has recently received more attention than Voy- ager (Wang et al., 2023a). Voyager is an AI agent with access to GPT-4 (OpenAI, 2023). Voyager shows remarkable proficiency in playing the game of Minecraft and is able to utilize a learned skill library to solve new tasks from scratch without hu- man intervention, demonstrating strong in-context lifelong learning capabilities. 4.3. Coding Developers have always wanted to have a code generator to help improve programming efficiency. # 4.4. Design The idea of AI Agent has also been applied to de- sign. Diagram7 is a representative AI-powered and automatable design platform with many products, including Magician, Genius, Automator, and UI- AI, for designing high-quality charts and graphs. Taking Genius and UI-AI as examples. Genius is equivalent to a design assistant, helping to trans- form users’ ideas into designs. Users only need to provide a product description and Genius can create fully editable UI designs. In addition, Ge- nius can provide design suggestions to help improve productivity. UI-AI contains a series of user inter- face AI models made for designers that leverage the latest advancements in AI combined with creative # 3https://pi.ai/talk 4https://chat.openai.com 5https://www.anthropic.com/index/claude-2 6https://github.com/AntonOsika/gpt-engineer 7https://diagram.com/ prompting or multimodal prompts to generate de- sign assets. # 4.5. Research A number of AI agents for autonomous scientific research have emerged. ChemCrow (Bran et al., 2023) is an LLM chemistry agent designed to ac- complish various tasks such as organic synthesis, drug discovery, and materials design. It integrates 17 expert-designed chemistry tools and operates by prompting GPT-4 to provide specific instructions about the task and the format required. Specifi- cally, a set of tools is created by using a variety of chemistry-related packages and software. These tools and user prompts are provided to GPT-4 and GPT-4 determines its behavioral path before arriv- ing at the final answer through an automated, it- erative chain-of-thought process. Throughout the process, ChemCrow serves as an assistant to expert chemists while simultaneously lowering the entry barrier for non-experts by offering a simple inter- face to access accurate chemical knowledge. Agent (Boiko et al., 2023) is an exploration of emerging autonomous scientific research capabil- ities of large language models. It binds multiple LLMs together for autonomous design, planning, and execution of scientific experiments (eg., the synthesis experiment of ibuprofen and the cross- coupling experiment of Suzuki and Sonogashira reaction). Specifically, autonomous scientific re- search is accomplished through a series of tools for surfing the Web, reading documents, executing code, etc., and several LLMs for well-timed calls. # 4.6. Collaboration Collaboration is one of the most significant appli- cations of AI agents. Many researchers have al- ready started to develop the application by allow- ing different AI agents to collaborate with each other, such as AI lawyers, AI programmers, and AI finance to form a team to complete complex tasks together. DialOp (Lin et al., 2023a) de- scribes a simple collaborative morphology, in which AI assistants collaborate with one or more hu- mans via natural language to help them make com- plex decisions. The autonomous AI agents cur- rently created by MindOS8 are also used for sim- ple human-agent collaboration to assist users with professional tasks. Compared to DialOp and Min- dOS, MetaGPT9and Multi-GPT10 allow multiple agents can automatically divide up the work and collaborate with each other to accomplish a task, with MetaGPT focusing more on software industry tasks. # 8https://mindos.com/marketplace 9https://github.com/geekan/MetaGPT 10https://github.com/sidhq/Multi-GPT Additionally, Generative Agents (Park et al., 2023) are introduced to simulate human behavior. By ex- tending LLMs, complete records of the experiences of the generative agents are stored using natural language, and over time these memories are syn- thesized to form higher-level reflections that are dynamically retrieved to plan behavior. End-users can interact with a town of 25 generative agents using natural language. The architecture behind these generative agents is expected to be applied in collaborative scenarios. 4.7. General purpose In addition to specific applications, some AI agents are developed for general purposes. These AI agents generally perform a wide range of tasks across diverse domains and attempt to reach the goal by thinking of tasks to do, executing them, and learning from the results. Auto-GPT11 is one of the first examples of GPT-4 running fully autonomously. The feature of completing tasks autonomously without human intervention attracts people’s attention. Similar to Auto-GPT, BabyAGI12 is a task-driven autonomous AI agent. BabyAGI constructs a task list dedicated to achiev- ing the goal, derives further tasks based on the pre- vious results, and executes these tasks in order of priority until the overall goal is achieved. More- over, SuperAGI13 and AgentGPT14 support the building and deployment of autonomous AI agents, and have it embark on any goal imaginable. Al- though these AI agents are not so perfect and even have some deficiencies, their presentation is cer- tainly an important step towards artificial general intelligence. # 4.8. Vision-Language model-based agent application LLM has already demonstrated outstanding capa- in bilities in language-only scenarios. However, some application scenarios, agents need to deal with multi-modal information, especially vision- language modalities. In such cases, modeling only the language information may not achieve satisfactory performance. Recent work considers equipping agents with the Vision-language model (VLM) to handle multi-modal information. In this subsection, we introduce some latest VLM-based agent applications. Some works attempt to ap- ply VLM in the field of embodied AI and robotics that are based on visual and language modalities. For example, Khandelwal et al. (Khandelwal et al., 11https://github.com/Significant-Gravitas/ Auto-GPT 12https://github.com/yoheinakajima/babyagi 13https://github.com/TransformerOptimus/ SuperAGI 14https://github.com/reworkd/AgentGPT 2022) introduced CLIP (Radford et al., 2021) into Embodied Agents, and demonstrated that CLIP can effectively enhance the task performance of em- bodied AI. Driess et al. (Driess et al., 2023) com- bined ViT and PaLM to construct a multi-modal model named PaLM-E, which is applied in embod- ied reasoning. PaLM-E takes a multi-modal se- quence (i.e., text and image) as input and converts it into text and image embeddings. Specifically, the image embedding is generated by the ViT and a projector encode images. Then, the text and im- age embeddings serve as input to PaLM for infer- ring the decisions that the robot needs to execute. Finally, the decisions are transformed into actions by a low-level policy or planner. Some works fo- cus on the navigation task. For instance, Dorbala et al. (Dorbala et al., 2022) first used GPT-3 to break down navigation instructions into a series of sub-instructions. Then, at each time step, they utilized CLIP to select an image from the cur- rent panoramic view that corresponded to the sub- instructions, serving as the direction for the next navigation step. This process continued until the agent reached its target location. ZSON (Majum- dar et al., 2022) is an object-goal navigation agent designed to locate specific objects within an en- vironment. Besides, some works consider applied LVM in the field of multi-model conversational. For example, Video-ChatGPT (Maaz et al., 2023) is a video-based conversational agent fine-tuned us- ing video instruction data. It first employs the vi- sual encoder from CLIP to encode video frames into temporal and spatial features. Then, it uti- lizes a trainable adapter to map these features into the language space and combines them with query representations as inputs of LLM to generate re- sponses. Li et al.(Li et al., 2023a) introduce a conversational assistant for the biomedical field, named LLaVA-Med. It is continuously trained by LLaVA on multimodal biomedical datasets. # 5. Benchmarking Recently, LLM-based AI agents have attracted sig- nificant research interest. In order to evaluate the performance of the proposed agents, some works focus on designing more suitable benchmarks. For example, Valmeekam et al. (Valmeekam et al., 2023) focused on assessing the planning ability of LLMs, which is a key component of AI agents. Liu et al. (Liu et al., 2023d) designed a benchmark based on the WebShop and HotPotQA environ- ment. Their goal is to compare the performance of multiple agent architectures equipped with differ- ent LLMs. Li et al. (Li et al., 2023c) constructed a benchmark, named API Bank, to evaluate the ability of LLMs to use tools. Fan et al. (Fan et al., 2022) proposed a simulator based on Minecraft to assess the performance of open-ended embod- ied agent. Xu et al. (Xu et al., 2023) designed a benchmark, named GentBench, which consists of public and private sections, with the aim of com- prehensively evaluating the performance of agents. Specifically, GentBench includes a series of com- plex tasks that promote LLMs to employ exter- nal tools for addressing these challenges. Baner- jee (Banerjee et al., 2023) introduced an end-to- end benchmark that evaluates the performance of LLM-based chatbots by comparing generated answers with the gold answer. Lin et al. (Lin et al., 2023b) presented a task-based evaluation method, which assesses the capabilities of agents based on their task completion within the interac- tive environment. Liu et al. (Liu et al., 2023c) in- troduced a multi-dimensional benchmark, named AgentBench, which evaluates the performance of LLM across multiple environments. 6. Conclusion In this paper, we presented a comprehensive and systematic survey of the LLM-based agents. We first introduced the difference between agents based on LLM and traditional methods, then re- viewed the related works from the perspectives of components and application of AI agents. Fur- thermore, we have explored some pressing issues that require solutions and valuable research direc- tions. With the development of LLM, an increas- ing amount of research attention has been directed toward the field of AI agents, resulting in the emer- gence of numerous new technologies and methods. Through this review, we aim to assist readers in swiftly grasping the key information and applica- tions of AI agents, and also provide insights into future research directions. # 7. Bibliographical References Constructions Aeronautiques, Adele Howe, Craig Knoblock, ISI Drew McDermott, Ashwin Ram, Manuela Veloso, Daniel Weld, David Wilkins SRI, Anthony Barrett, Dave Christianson, et al. 1998. Pddl— the planning domain definition lan- guage. Technical Report, Tech. Rep. Afra Feyza Akyurek, Ekin Akyurek, Ashwin Kalyan, Peter Clark, Derry Tanti Wijaya, and Niket Tandon. 2023. RL4F: Generating natural language feedback with reinforcement learning for repairing model outputs. In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics, pages 7716–7733. Karol Arndt, Murtaza Hazara, Ali Ghadirzadeh, and Ville Kyrki. 2020. Meta reinforcement learn- ing for sim-to-real domain adaptation. In 2020 IEEE International Conference on Robotics and Automation (ICRA), pages 2725–2731. IEEE. Kai Arulkumaran, Marc Peter Deisenroth, Miles Brundage, and Anil Anthony Bharath. 2017. Deep reinforcement learning: A brief survey. IEEE Signal Processing Magazine, 34(6):26–38. Alan D Baddeley. 1997. Human memory: Theory and practice. psychology press. Alan David Baddeley. 1983. Working mem- ory. Philosophical Transactions of the Royal Society of London. B, Biological Sciences, 302(1110):311–324. Debarag Banerjee, Pooja Singh, Arjun Avad- hanam, and Saksham Srivastava. 2023. Bench- marking llm powered chatbots: Methods and metrics. arXiv preprint arXiv:2308.04624. Christopher Berner and Brockman et al. 2019. Dota 2 with large scale deep reinforcement learn- ing. arXiv preprint arXiv:1912.06680. Ning Bian, Xianpei Han, Le Sun, Hongyu Lin, Yao- jie Lu, and Ben He. 2023. Chatgpt is a knowl- edgeable but inexperienced solver: An investiga- tion of commonsense problem in large language models. arXiv preprint arXiv:2303.16421. Daniil A Boiko, Robert MacKnight, and Gabe Gomes. 2023. Emergent autonomous scientific research capabilities of large language models. arXiv preprint arXiv:2304.05332. Andres M Bran, Sam Cox, Andrew D White, and Philippe Schwaller. 2023. Chemcrow: Augment- ing large-language models with chemistry tools. arXiv preprint arXiv:2304.05376. Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sas- try, Amanda Askell, et al. 2020. Language mod- els are few-shot learners. Advances in neural in- formation processing systems, 33:1877–1901. Tianle Cai, Xuezhi Wang, Tengyu Ma, Xinyun Chen, and Denny Zhou. 2023. Large lan- guage models as tool makers. arXiv preprint arXiv:2305.17126. Eduardo Camina and Francisco G¨uell. 2017. The neuroanatomical, neurophysiological and psy- chological basis of memory: Current models and their origins. Frontiers in pharmacology, 8:438. Jingkai Chen, Brian C Williams, and Chuchu Fan. 2021. Optimal mixed discrete-continuous plan- In Proceedings ning for linear hybrid systems. of the 24th International Conference on Hybrid Systems: Computation and Control, pages 1–12. Jiuhai Chen, Lichang Chen, Heng Huang, and Tianyi Zhou. 2023a. When do you need chain-of- thought prompting for chatgpt? arXiv preprint arXiv:2304.03262. Liting Chen, Lu Wang, Hang Dong, Yali Du, Jie Yan, Fangkai Yang, Shuang Li, Pu Zhao, Si Qin, Saravan Rajmohan, et al. 2023b. Introspective tips: Large language model for in-context deci- sion making. arXiv preprint arXiv:2305.11598. Po-Lin Chen and Cheng-Shang Chang. 2023. Interact: Exploring the potentials of chat- gpt as a cooperative agent. arXiv preprint arXiv:2308.01552. Zhipeng Chen, Kun Zhou, Beichen Zhang, Zheng Gong, Wayne Xin Zhao, and Ji-Rong Wen. 2023c. Chatcot: Tool-augmented chain-of- thought reasoning on\chat-based large lan- guage models. arXiv preprint arXiv:2305.14323. Cheng-Han Chiang, Sung-Feng Huang, and Hung- Yi Lee. 2020. Pretrained language model em- bryology: The birth of albert. In Proceedings of the Conference on Empirical Methods in Natural Language Processing, pages 6813–6828. Karl Cobbe, Vineet Kosaraju, Mohammad Bavar- ian, Mark Chen, Heewoo Jun, Lukasz Kaiser, Matthias Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Nakano, et al. 2021. Training verifiers to solve math word problems. arXiv preprint arXiv:2110.14168. Jeff Da, Ronan Le Bras, Ximing Lu, Yejin Choi, and Antoine Bosselut. 2021. Analyzing common- sense emergence in few-shot knowledge models. arXiv preprint arXiv:2101.00297. Joe Davison, Joshua Feldman, and Alexander M Rush. 2019. Commonsense knowledge mining from pretrained models. In Proceedings of the conference on empirical methods in natural lan- guage processing and the 9th international joint conference on natural language processing, pages 1173–1178. Vishnu Sashank Dorbala, Gunnar Sigurdsson, Robinson Piramuthu, Jesse Thomason, and Gaurav S Sukhatme. 2022. Clip-nav: Using clip for zero-shot vision-and-language naviga- tion. arXiv preprint arXiv:2211.16649. Danny Driess, Fei Xia, Mehdi S. M. Sajjadi, Corey Lynch, Aakanksha Chowdhery, Brian Ichter, Ayzaan Wahid, Jonathan Tompson, Quan Vuong, Tianhe Yu, Wenlong Huang, Yev- gen Chebotar, Pierre Sermanet, Daniel Duck- worth, Sergey Levine, Vincent Vanhoucke, Karol Hausman, Marc Toussaint, Klaus Greff, Andy Zeng, Igor Mordatch, and Pete Florence. 2023. Palm-e: An embodied multimodal language model. In Proceedings of the International Con- ference on Machine Learning, pages 8469–8488. Kutluhan Erol, James Hendler, and Dana S Nau. 1994. Htn planning: complexity and expres- sivity. In Proceedings of the Twelfth AAAI National Conference on Artificial Intelligence, pages 1123–1128. Linxi Fan, Guanzhi Wang, Yunfan Jiang, Ajay Mandlekar, Yuncong Yang, Haoyi Zhu, An- drew Tang, De-An Huang, Yuke Zhu, and An- ima Anandkumar. 2022. Minedojo: Building open-ended embodied agents with internet-scale knowledge. Advances in Neural Information Processing Systems, 35:18343–18362. Maria Fox and Derek Long. 2003. Pddl2. 1: An extension to pddl for expressing temporal plan- ning domains. Journal of artificial intelligence research, 20:61–124. Dongyu Gong, Xingchen Wan, and Dingmin Wang. Working memory capacity of chatgpt: An empir- ical study. Lin Guan, Karthik Valmeekam, Sarath Sreedha- ran, and Subbarao Kambhampati. 2023. Lever- aging pre-trained large language models to con- struct and utilize world models for model-based task planning. arXiv preprint arXiv:2305.14909. Huihui Guo, Fan Wu, Yunchuan Qin, Ruihui Li, Keqin Li, and Kenli Li. 2023. Recent trends in task and motion planning for robotics: A survey. ACM Computing Surveys. Carl Hewitt, Peter Bishop, and Richard Steiger. 1973. A universal modular actor formalism for artificial intelligence. In Proceedings of the 3rd international joint conference on Artificial intel- ligence, pages 235–245. Bin Hu, Chenyang Zhao, Pu Zhang, Zihao Zhou, Yuanhang Yang, Zenglin Xu, and Bin Liu. 2023. Enabling efficient interaction between an algo- rithm agent and an llm: A reinforcement learn- ing approach. arXiv preprint arXiv:2306.03604. Jie Huang and Kevin Chen-Chuan Chang. 2022. Towards reasoning in large language models: A survey. arXiv preprint arXiv:2212.10403. Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. 2022a. Language mod- els as zero-shot planners: Extracting actionable knowledge for embodied agents. In International Conference on Machine Learning, pages 9118– 9147. Wenlong Huang, Fei Xia, Ted Xiao, Harris Chan, Jacky Liang, Pete Florence, Andy Zeng, Jonathan Tompson, Igor Mordatch, Yevgen Chebotar, et al. 2022b. Inner monologue: Em- bodied reasoning through planning with lan- guage models. arXiv preprint arXiv:2207.05608. Ian ML Hunter. 1957. Memory: Facts and fallacies. Yu-qian Jiang, Shi-qi Zhang, Piyush Khandel- wal, and Peter Stone. 2019. Task planning in robotics: an empirical comparison of pddl-and asp-based systems. Frontiers of Information Technology & Electronic Engineering, 20:363– 373. Yei Hwan Jung, Byeonghak Park, Jong Uk Kim, and Tae-il Kim. 2019. Bioinspired electronics for artificial sensory systems. Advanced Materials, 31(34):1803637. Jikun Kang, Romain Laroche, Xindi Yuan, Adam Trischler, Xue Liu, and Jie Fu. 2023. Think before you act: Decision transformers with internal working memory. arXiv preprint arXiv:2305.16338. Ehud Karpas, Omri Abend, Yonatan Belinkov, Barak Lenz, Opher Lieber, Nir Ratner, Yoav Shoham, Hofit Bata, Yoav Levine, Kevin Leyton-Brown, et al. 2022. Mrkl systems: A modular, neuro-symbolic architecture that com- bines large language models, external knowledge sources and discrete reasoning. arXiv preprint arXiv:2205.00445. Mohammad Kazemifard, Nasser Ghasem-Aghaee, Bryan L Koenig, and Tuncer I ¨Oren. 2014. An emotion understanding framework for intelligent agents based on episodic and semantic memo- ries. Autonomous agents and multi-agent sys- tems, 28:126–153. Apoorv Khandelwal, Luca Weihs, Roozbeh Mot- taghi, and Aniruddha Kembhavi. 2022. Sim- ple but effective: Clip embeddings for embodied ai. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 14829–14838. Taewoon Kim, Michael Cochez, Vincent Fran¸cois- Lavet, Mark Neerincx, and Piek Vossen. 2023. A machine with short-term, episodic, and semantic memory systems. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 37, pages 48–56. Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa. 2022. Large language models are zero-shot reasoners. Advances in neural information processing sys- tems, 35:22199–22213. Gibbeum Lee, Volker Hartmann, Jongho Park, Dimitris Papailiopoulos, and Kangwook Lee. 2023. Prompted llms as chatbot modules for long open-domain conversation. arXiv preprint arXiv:2305.04533. Chunyuan Li, Cliff Wong, Sheng Zhang, Naoto Usuyama, Haotian Liu, Jianwei Yang, Tristan Naumann, Hoifung Poon, and Jianfeng Gao. 2023a. Llava-med: Training a large language- and-vision assistant for biomedicine in one day. arXiv preprint arXiv:2306.00890. Daliang Li, Ankit Singh Rawat, Manzil Zaheer, Xin Wang, Michal Lukasik, Andreas Veit, Felix Yu, and Sanjiv Kumar. 2023b. Large language models with controllable working memory. In Findings of the Association for Computational Linguistics: ACL, pages 1774–1793. Haizhen Li and Xilun Ding. 2023. Adaptive and intelligent robot task planning for home service: A review. Engineering Applications of Artificial Intelligence, 117:105618. Minghao Li, Feifan Song, Bowen Yu, Haiyang Yu, Zhoujun Li, Fei Huang, and Yongbin Li. 2023c. Api-bank: A benchmark for tool-augmented llms. arXiv preprint arXiv:2304.08244. Yuxi Li. 2017. Deep reinforcement learning: An overview. arXiv preprint arXiv:1701.07274. Xinnian Liang, Bing Wang, Hui Huang, Shuangzhi Wu, Peihao Wu, Lu Lu, Zejun Ma, and Zhou- jun Li. 2023a. Unleashing infinite-length input capacity for large-scale language models with self-controlled memory system. arXiv preprint arXiv:2304.13343. Yaobo Liang, Chenfei Wu, Ting Song, Wenshan Wu, Yan Xia, Yu Liu, Yang Ou, Shuai Lu, Lei Ji, Shaoguang Mao, et al. 2023b. Taskmatrix. ai: Completing tasks by connecting foundation models with millions of apis. arXiv preprint arXiv:2303.16434. Jessy Lin, Nicholas Tomlin, Jacob Andreas, and Jason Eisner. 2023a. Decision-oriented dia- logue for human-ai collaboration. arXiv preprint arXiv:2305.20076. Jiaju Lin, Haoran Zhao, Aochi Zhang, Yiting Wu, Huqiuyue Ping, and Qin Chen. 2023b. Agentsims: An open-source sandbox for large arXiv preprint language model evaluation. arXiv:2308.04026. Bo Liu, Yuqian Jiang, Xiaohan Zhang, Qiang Liu, Shiqi Zhang, Joydeep Biswas, and Peter Stone. 2023a. Llm+ p: Empowering large language models with optimal planning proficiency. arXiv preprint arXiv:2304.11477. Hao Liu, Carmelo Sferrazza, and Pieter Abbeel. lan- Chain of hindsight arXiv preprint 2023b. guage models with feedback. arXiv:2302.02676, 3. aligns Xiao Liu, Hao Yu, Hanchen Zhang, Yifan Xu, Xu- anyu Lei, Hanyu Lai, Yu Gu, Hangliang Ding, Kaiwen Men, Kejuan Yang, et al. 2023c. Agent- bench: Evaluating llms as agents. arXiv preprint arXiv:2308.03688. Zhiwei Liu, Weiran Yao, Jianguo Zhang, Le Xue, Shelby Heinecke, Rithesh Murthy, Yihao Feng, Zeyuan Chen, Juan Carlos Niebles, Devansh Arpit, et al. 2023d. Bolaa: Benchmarking and orchestrating llm-augmented autonomous agents. arXiv preprint arXiv:2308.05960. Shih-Yun Lo, Shiqi Zhang, and Peter Stone. 2018. Petlon: planning efficiently for task- level-optimal navigation. In Proceedings of the 17th International Conference on Autonomous Agents and MultiAgent Systems, pages 220–228. Lajanugen Logeswaran, Yao Fu, Moontae Lee, and Few-shot subgoal plan- arXiv preprint Honglak Lee. 2022. ning with language models. arXiv:2205.14288. Jieyi Long. 2023. Large guided arXiv:2305.08291. tree-of-thought. language model preprint arXiv Pan Lu, Baolin Peng, Hao Cheng, Michel Gal- ley, Kai-Wei Chang, Ying Nian Wu, Song-Chun Zhu, and Jianfeng Gao. 2023. Chameleon: Plug- and-play compositional reasoning with large lan- guage models. arXiv preprint arXiv:2304.09842. Muhammad Maaz, Hanoona Rasheed, Salman Khan, and Fahad Shahbaz Khan. 2023. Video- chatgpt: Towards detailed video understanding via large vision and language models. arXiv preprint arXiv:2306.05424. Arjun Majumdar, Gunjan Aggarwal, Bhavika De- vnani, Judy Hoffman, and Dhruv Batra. 2022. Zson: Zero-shot object-goal navigation using multimodal goal embeddings. Advances in Neural Information Processing Systems, pages 32340–32352. J McCarthy. 1959. Programs with common sense. In Proc. Teddington Conference on the Mecha- nization of Thought Processes, 1959, pages 75– 91. Marvin L. Minsky. 1988. The Society of Mind. Si- mon & Schuster, New York. Volodymyr Mnih, Koray Kavukcuoglu, David Sil- ver, Alex Graves, Ioannis Antonoglou, Daan Wierstra, and Martin A. Riedmiller. 2013. Play- ing atari with deep reinforcement learning. CoRR, abs/1312.5602. Reiichiro Nakano, Jacob Hilton, Suchir Balaji, Jeff Wu, Long Ouyang, Christina Kim, Christopher Hesse, Shantanu Jain, Vineet Kosaraju, William Saunders, et al. 2021. Webgpt: Browser-assisted question-answering with human feedback. arXiv preprint arXiv:2112.09332. Andrew M Nuxoll and John E Laird. 2007. Extend- ing cognitive architecture with episodic memory. In Proceedings of the 22nd national conference on Artificial intelligence-Volume 2, pages 1560– 1565. Amin Omidvar and Aijun An. 2023. Empowering conversational agents using semantic in-context learning. In Proceedings of the 18th Workshop on Innovative Use of NLP for Building Educational Applications (BEA 2023), pages 766–771. OpenAI. 2023. Gpt-4 technical report. Bhargavi Paranjape, Scott Lundberg, Sameer Singh, Hannaneh Hajishirzi, Luke Zettlemoyer, and Marco Tulio Ribeiro. 2023. Art: Automatic multi-step reasoning and tool-use for large lan- guage models. arXiv preprint arXiv:2303.09014. Aaron Parisi, Yao Zhao, and Noah Fiedel. 2022. Talm: Tool augmented language models. arXiv preprint arXiv:2205.12255. Joon Sung Park, Joseph C O’Brien, Carrie J Cai, Meredith Ringel Morris, Percy Liang, and Michael S Bernstein. 2023. Generative agents: Interactive simulacra of human behavior. arXiv preprint arXiv:2304.03442. Shishir G Patil, Tianjun Zhang, Xin Wang, and Joseph E Gonzalez. 2023. Gorilla: Large lan- guage model connected with massive apis. arXiv preprint arXiv:2305.15334. Baolin Peng, Michel Galley, Pengcheng He, Hao Cheng, Yujia Xie, Yu Hu, Qiuyuan Huang, Lars Liden, Zhou Yu, Weizhu Chen, et al. 2023. Check your facts and try again: Improv- ing large language models with external knowl- edge and automated feedback. arXiv preprint arXiv:2302.12813. Fabio Petroni, Tim Rockt¨aschel, Sebastian Riedel, Patrick Lewis, Anton Bakhtin, Yuxiang Wu, and Alexander Miller. 2019. Language models as knowledge bases? In Proceedings of the Confer- ence on Empirical Methods in Natural Language Processing and the 9th International Joint Con- ference on Natural Language Processing, pages 2463–2473. Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agar- wal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, and Ilya Sutskever. 2021. Learning transferable visual In models from natural language supervision. Proceedings of the 38th International Conference on Machine Learning, pages 8748–8763. and Anna A primer in bertology: Rumshisky. 2021. What we know about how bert works. Trans- actions of the Association for Computational Linguistics, 8:842–866. David E Rumelhart, Geoffrey E Hinton, and Ronald J Williams. 1986. Learning represen- tations by back-propagating errors. nature, 323(6088):533–536. Stuart Russell and Peter Norvig. 2010. Artifi- cial Intelligence: A Modern Approach, 3 edition. Prentice Hall. Tara Safavi and Danai Koutra. 2021. Relational world knowledge representation in contextual language models: A review. arXiv preprint arXiv:2104.05837. Timo Schick, Jane Dwivedi-Yu, Roberto Dess`ı, Roberta Raileanu, Maria Lomeli, Luke Zettle- moyer, Nicola Cancedda, and Thomas Scialom. 2023. Language models can teach themselves to use tools. arXiv preprint arXiv:2302.04761. Yongliang Shen, Kaitao Song, Xu Tan, Dong- sheng Li, Weiming Lu, and Yueting Zhuang. 2023. Hugginggpt: Solving ai tasks with chat- gpt and its friends in huggingface. arXiv preprint arXiv:2303.17580. Noah Shinn, Beck Labash, and Ashwin Gopinath. 2023. Reflexion: an autonomous agent with dy- namic memory and self-reflection. arXiv preprint arXiv:2303.11366. Kurt Shuster, Jing Xu, Mojtaba Komeili, Da Ju, Eric Michael Smith, Stephen Roller, Megan Ung, Moya Chen, Kushal Arora, Joshua Lane, et al. 2022. Blenderbot 3: a deployed conversational agent that continually learns to responsibly en- gage. arXiv preprint arXiv:2208.03188. David Silver, Aja Huang, Chris J Maddison, Arthur Guez, Laurent Sifre, George Van Den Driessche, Julian Schrittwieser, Ioannis Antonoglou, Veda Panneershelvam, Marc Lanc- tot, et al. 2016. Mastering the game of go with deep neural networks and tree search. nature, 529(7587):484–489. Ishika Singh, Valts Blukis, Arsalan Mousavian, Ankit Goyal, Danfei Xu, Jonathan Tremblay, Di- eter Fox, Jesse Thomason, and Animesh Garg. 2023. Progprompt: Generating situated robot task plans using large language models. In Pro- ceedings of IEEE International Conference on Robotics and Automation, pages 11523–11530. Alejandro Su´arez-Hern´andez, Guillem Aleny`a, and Interleaving hierarchical Carme Torras. 2018. task planning and motion constraint testing for dual-arm manipulation. In 2018 IEEE/RSJ In- ternational Conference on Intelligent Robots and Systems, pages 4061–4066. Haotian Sun, Yuchen Zhuang, Lingkai Kong, Bo Dai, and Chao Zhang. 2023. Adaplanner: Adaptive planning from feedback with language models. arXiv preprint arXiv:2305.16653. Chao Tang, Dehao Huang, Wenqi Ge, Weiyu Liu, and Hong Zhang. 2023. Graspgpt: Leverag- ing semantic knowledge from a large language model for task-oriented grasping. arXiv preprint arXiv:2307.13204. Romal Thoppilan, Daniel De Freitas, Jamie Hall, Noam Shazeer, Apoorv Kulshreshtha, Heng-Tze Cheng, Alicia Jin, Taylor Bos, Leslie Baker, Yu Du, et al. 2022. Lamda: Language mod- els for dialog applications. arXiv preprint arXiv:2201.08239. Endel Tulving. 1983. Elements of episodic memory. Endel Tulving et al. 1972. Episodic and semantic memory. Organization of memory, 1(381-403):1. Karthik Valmeekam, Sarath Sreedharan, Matthew Marquez, Alberto Olmo, and Subbarao Kamb- hampati. 2023. On the planning abilities of large language models (a critical investigation with a proposed benchmark). arXiv preprint arXiv:2302.06706. Steven Vere and Timothy Bickmore. 1990. A basic agent. Computational intelligence, 6(1):41–60. Oriol Vinyals, Igor Babuschkin, Wojciech M Czar- necki, Micha¨el Mathieu, Andrew Dudzik, Jun- young Chung, David H Choi, Richard Pow- ell, Timo Ewalds, Petko Georgiev, et al. in starcraft ii us- 2019. Grandmaster level ing multi-agent reinforcement learning. Nature, 575(7782):350–354. Changjin Wan, Pingqiang Cai, Ming Wang, Yan Qian, Wei Huang, and Xiaodong Chen. 2020. Artificial sensory memory. Advanced Materials, 32(15):1902434. Guanzhi Wang, Yuqi Xie, Yunfan Jiang, Ajay Mandlekar, Chaowei Xiao, Yuke Zhu, Linxi Fan, and Anima Anandkumar. 2023a. Voyager: An open-ended embodied agent with large language models. arXiv preprint arXiv:2305.16291. Lei Wang, Wanyu Xu, Yihuai Lan, Zhiqiang Hu, Yunshi Lan, Roy Ka-Wei Lee, and Ee-Peng Lim. 2023b. Plan-and-solve prompting: Improving zero-shot chain-of-thought reasoning by large language models. In Proceedings of the 61st An- nual Meeting of the Association for Computa- tional, pages 2609–2634. Jason Wei, Yi Tay, Rishi Bommasani, Colin Raf- fel, Barret Zoph, Sebastian Borgeaud, Dani Yo- gatama, Maarten Bosma, Denny Zhou, Don- ald Metzler, et al. 2022a. Emergent abili- ties of large language models. arXiv preprint arXiv:2206.07682. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny Zhou, et al. 2022b. Chain-of-thought prompting elicits reasoning in large language models. Advances in Neural Information Pro- cessing Systems, 35:24824–24837. Yaqi Xie, Chen Yu, Tongyao Zhu, Jinbin Bai, Trans- to planning goals arXiv preprint Binfeng Xu, Xukun Liu, Hua Shen, Zeyu Han, Yuhan Li, Murong Yue, Zhiyuan Peng, Yuchen Liu, Ziyu Yao, and Dongkuan Xu. Gentopia: A collaborative platform 2023. for arXiv preprint arXiv:2308.04030. Shunyu Yao, Dian Yu, Jeffrey Zhao, Izhak Shafran, Thomas L Griffiths, Yuan Cao, and Karthik Narasimhan. 2023a. Tree of thoughts: Deliber- ate problem solving with large language models. arXiv preprint arXiv:2305.10601. Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. 2022. React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629. Weiran Yao, Shelby Heinecke, Juan Carlos Niebles, Zhiwei Liu, Yihao Feng, Le Xue, Rithesh Murthy, Zeyuan Chen, Jianguo Zhang, Devansh Arpit, et al. 2023b. Retroformer: Retrospective large language agents with policy gradient opti- mization. arXiv preprint arXiv:2308.02151. Bowen Zhang, Xianghua Fu, Daijun Ding, Hu Huang, Yangyang Li, and Liwen Jing. 2023a. Investigating chain-of-thought with chatgpt for stance detection on social media. arXiv preprint arXiv:2304.03087. Danyang Zhang, Lu Chen, Situo Zhang, Hong- shen Xu, Zihan Zhao, and Kai Yu. 2023b. is semi-parametric re- Large language model inforcement learning agent. arXiv preprint arXiv:2306.07929. Zhuosheng Zhang, Aston Zhang, Mu Li, and Alex Smola. 2022. Automatic chain of thought prompting in large language models. In Proceed- ings of the Eleventh International Conference on Learning Representations. Wanjun Zhong, Lianghong Guo, Qiqi Gao, and Yanlin Wang. 2023. Memorybank: Enhancing large language models with long-term memory. arXiv preprint arXiv:2305.10250. Mingchen Zhuge and Haozhe Liu et al. 2023. Mind- language-based societies of storms in natural mind.
Title: AssistGPT: A General Multi-modal Assistant that can Plan, Execute, Inspect, and Learn: Summary: Recent research on Large Language Models (LLMs) has led to remarkable advancements in general NLP AI assistants. Some studies have further explored the use of LLMs for planning and invoking models or APIs to address more general multi-modal user queries. Despite this progress, complex visual-based tasks still remain challenging due to the diverse nature of visual tasks. This diversity is reflected in two aspects: 1) Reasoning paths. For many real-life applications, it is hard to accurately decompose a query simply by examining the query itself. Planning based on the specific visual content and the results of each step is usually required. 2) Flexible inputs and intermediate results. Input forms could be flexible for in-the-wild cases, and involves not only a single image or video but a mixture of videos and images, e.g., a user-view image with some reference videos. Besides, a complex reasoning process will also generate diverse multimodal intermediate results, e.g., video narrations, segmented video clips, etc. To address such general cases, we propose a multi-modal AI assistant, AssistGPT, with an interleaved code and language reasoning approach called Plan, Execute, Inspect, and Learn (PEIL) to integrate LLMs with various tools. Specifically, the Planner is capable of using natural language to plan which tool in Executor should do next based on the current reasoning progress. Inspector is an efficient memory manager to assist the Planner to feed proper visual information into a specific tool. Finally, since the entire reasoning process is complex and flexible, a Learner is designed to enable the model to autonomously explore and discover the optimal solution. We conducted experiments on A-OKVQA and NExT-QA benchmarks, achieving state-of-the-art results. Moreover, showcases demonstrate the ability of our system to handle questions far more complex than those found in the benchmarks. # AssistGPT: A General Multi-modal Assistant that can Plan, Execute, Inspect, and Learn # Difei Gao, Lei Ji, Luowei Zhou, Kevin Qinghong Lin, Joya Chen, Zihan Fan, Mike Zheng Shou∗ Show Lab, National University of Singapore, https://showlab.github.io/assistgpt/ # Abstract Recent research on Large Language Models (LLMs) has led to remarkable ad- vancements in general NLP AI assistants. Some studies have further explored the use of LLMs for planning and invoking models or APIs to address more general multi-modal user queries. Despite this progress, complex visual-based tasks still remain challenging due to the diverse nature of visual tasks. This diversity is reflected in two aspects: 1) Reasoning paths. For many real-life applications, it is hard to accurately decompose a query simply by examining the query itself. Planning based on the specific visual content and the results of each step is usually required. 2) Flexible inputs and intermediate results. Input forms could be flexible for in-the-wild cases, and involves not only a single image or video but a mixture of videos and images, e.g., a user-view image with some reference videos. Besides, a complex reasoning process will also generate diverse multimodal intermediate results, e.g., video narrations, segmented video clips, etc. To address such general cases, we propose a multi-modal AI assistant, AssistGPT, with an interleaved code and language reasoning approach called Plan, Execute, Inspect, and Learn (PEIL) to integrate LLMs with various tools. Specifically, the Planner is capable of using natural language to plan which tool in Executor should do next based on the current reasoning progress. Inspector is an efficient memory manager to assist the Planner to feed proper visual information into a specific tool. Finally, since the entire reasoning process is complex and flexible, a Learner is designed to enable the model to autonomously explore and discover the optimal solution. We conducted experiments on A-OKVQA and NExT-QA benchmarks, achieving state-of-the-art results. Moreover, showcases demonstrate the ability of our system to handle questions far more complex than those found in the benchmarks. # 1 Introduction Large language models (LLMs) [1–4], especially ChatGPT [5], have made remarkable progress in recent months, significantly advancing the field of developing AI assistants. Despite these advances, a single LLM serving as an AI assistant still exhibits inherent limitations in certain abilities, such as understanding visual environments and comprehending complex tasks, which restrict their utility in real-world applications. To address these shortcomings, a promising solution is to explore the integration and collaboration of multiple domain experts e.g., pretrained models or APIs, to tackle complex tasks. Numerous efforts have been made in this direction. Some works [6–8] utilize language as a bridge and transform the visual input into pure texts using foundational visual models, such as captioner [9–11], object detectors [12–14], and OCR models [15, 16]. Subsequently, the extracted texts are fed into LLMs for reasoning tasks like question-answering. Nonetheless, as for complex ∗Corresponding author. © Question: | am trying to add Midjourney Answer: Right-click on © to my own server. | have clicked the the “Midjourney Bot" User ‘show member icon’, what should | do in AssistGPT the next step? Show it on my provided screenshot. er )— @ a 627 seconds video, .., Midjourney Beginner Tutorial LLM —, plans what tool an image, .., the chat window with a painting on it touse r (executor) ~ e Thought: Locate the video clip regarding adding Midjourney to one's personal server. Run the selected tool hb Object Detection Observation: the target clip is from 3:58 - 04:15 . . (| visual-2: 2 17 seconds video, .., target clip for query “When was the video . @ video narration i G subtitle Grounding Thought: Infer what is the next step after selecting the ‘show member’ icon? OFA Region Grounding cr} OCR Detection = ASR Generate brief summary of Observation:the region is found visual inputs and visual-3: an image, .., target region for query "mid-journey bot" intermediate results 8 8 8: query j y ———— 1 rs Thought: I know the final answer. >) Final Answer: (Right-click on the "mid-journey bot", visual[3]) Check the reasoning path to (retry or save successful tries ) (@ itis successful try, save the whole reasoning process as an in-context example Figure 1: In-the-wild example of AssistGPT. AssistGPT can reason in an interleaved language and code format. Given a query input and visual inputs, AssistGPT plans the problem-solving path in language, using structured code to call upon various powerful tools. The Inspector, part of the system, can manage visual inputs and intermediate results, assisting the Planner to invoke tools. Meanwhile, the Learner can assess the reasoning process and collect in-context examples. visual scenarios such as a long-form video with complicated scene switching, as shown in Fig. 1, the generated texts may go well beyond the query requirements. This can lead to an abundance of superfluous information while crucial details relevant to the query may be omitted. Some other concurrent works propose decomposing user queries into subtasks and plan to sequentially call external models or APIs to answer them. Currently, there are two branches of methods. The first one is language-based planning [17–20]. For instance, HuggingGPT and Chameleon [17, 19] propose using an LLM as a controller, managing and organizing the cooperation of expert models. Another branch of work is code-based planning [21–23]. ViperGPT [21] proposes to use Codex to write the Python code to call visual-related APIs for handling multi-modal tasks. These approaches allow for invoking the models only when necessary, which allows models to only output useful information and optimize the use of computation resources. Despite this progress, addressing high-level queries is still challenging. Specifically, current questions in existing benchmarks usually directly imply how to plan the reasoning. For example, for questions like "What is the red object used for?", no matter what the image is, the reasoning steps are relatively fixed, i.e., recognize the red object, then figure out its function. However, for more complex questions, there could be diverse reason paths. For example, for question “How much black pepper should I use for 700g beef?” in Fig. 2, the variations in the presentation of relevant information, whether it’s in the form of subtitles, actions, text within videos, or a combination of these, can result in distinct reasoning paths. Therefore, as shown in Fig. 2, once a reason-only approach makes a mistake, it becomes difficult for it to self-correct. Similar approaches are already proposed in the NLP field, such as ReAct [24] and ToolFormer [25]. However, there is a unique challenge in multimodal tasks: How to handle non-textual intermediate 2 Inputs |. Question: How much black pepper should | use for 700g beef? Reason-only with Language Thought: I need to see if the video gives specific measurements for using black pepper on beef. Acton: Subtitle Ground Action Input: black pepper for beef Thought: I need to infer the amount of black pepper for 700g beef based on the information from the video. Acton: Subtitle Reason Action Input: how much black pepper should I use for 700g beef? Risk: the subtitles may not provide relevant context. Reason-only with Code Parse Question: code: Code Execution: Risk: When introducing the measurements, beef and pepper may not be appeared together. ReAct with PEIL Visual-@: 2 197 seconds video, user provided, sparse subtitle, How to Cook Perfect Beef Stir Fry Every Time use Subtitle Ground Module to Thought: Observation: Clip Not Found. Thought: I need to know more information. . Observation: ... 3-6: a person cutting a piece of beef on a cutting board. some texts on the frame (Beef 350 g Taste) .. Thought: I need to infer how much black pepper should I use for 700g beef Observation: 1 tsp Figure 2: Comparison of PEIL and two mainstream reasoning methods in multi-modal tasks. result? For ReAct and ToolFormer, the outputs of external models can be directly fed into the Planner and passed to subsequent models. While the intermediate results obtained in multimodal tasks usually are cropped regions for the image grounding module, and segmented video clips for the temporal location module, as shown in Fig. 1. In complex cases, it is hard for Planner to manage which information should be fed into the next module. In this paper, we propose a multi-modal AI Assistant system, named AssistGPT (The design of our model’s icon is inspired by the HAL 9000 from the movie “A Space Odyssey”, a fictional artificial intelligence character), with interleaved language and code reasoning method, inheriting the advantages of flexible reasoning in ReAct and robust tool invocation in Program-based planning. Specifically, our system consists of four parts, Planner, Executor, Inspector, and Learner. We show how our system works in Fig. 1. Similar to ReAct, the Planner thinks about what needs to be done next based on the current reasoning progress and invoking external models. What sets our method apart is the use of formatted code to invoke external models. The Executor wraps external tools into a uniform input and output format, allowing the tool to be invoked with structural commands. Simultaneously, we have also proposed an Inspector, which manages visual inputs and intermediate results during the reasoning process. It provides the Planner with summaries and metadata of all currently available visual materials. The combination of the Inspector and the Executor allows the model to efficiently implement complex reasoning. Moreover, it is challenging for the model to ensure correct reasoning in a zero-shot scenario. The Planner might output invalid code or unreasonable paths. To enable the system to continuously improve, we proposed the Learner, which checks whether the prediction process is reasonable or judges the correctness of the predicted results based on annotations. It allows the system to try multiple times and record successful examples as in-context examples. The current version of AssistGPT integrates 10+ tools for different functions, including image detection, captioning, region grounding, temporal grounding, OCR Module, object enumeration, speech-to-text, etc. By combining these functionalities, AssistGPT can accomplish a wide range of multi-modal tasks which are still hard for existing systems. In summary, our contributions are as follows: 1) We constructed a general multimodal AI assistant that can accomplish diverse visual-related tasks with the cooperation of multiple models. 2) We propose a new compositional reasoning method that reasons over in an interleaved language and code manner. A simple learning mechanism is also proposed to improve the AssistGPT’s ability in planning. 3) We showcase AssistGPT’s capabilities not only the benchmark results but also some realistic applications for processing complex images and long-form videos, understanding high-level queries, and handling flexible inputs. # 2 Related Work Multi-modal Systems. Prior to the advent of LLM, remarkable works were done to design multi- modal models for one or several specific tasks, such as focusing on visual appearance [26–31], visual- related knowledge [32–37], action [38–40], ego-centric videos [41–44], instructional videos [45–47], scene text [48–51], etc. They have achieved commendable results in specific tasks, however, their 3 generalizability is relatively limited, making it challenging to address more complex and diverse questions in real-world scenarios. Recently, two types of strategies are proposed for developing a general multi-modal system. One is pre-training LLM to support visual features as conditional inputs. The representative models are GPT- 4 [52], PaLM-E [53], BLIP-2 [54], and Mini-GPT4 [55]. Despite these methods being capable of directly processing multi-modal input, they still exhibit limitations in addressing advanced functional needs, such as image spatial grounding, long-form video grounding, and audio comprehension. Additionally, the computational cost of scaling these models can be extremely high. The alternative strategy aims to combine multiple models or APIs to accomplish complex multi-modal reasoning. For instance, models like the Socratic model [6] and Visual ChatGPT [8] achieve this by connecting ChatGPT with image generation models. HuggingGPT [17] combines a variety of Huggingface models with LLMs. ViperGPT [21] employs Codex [56] to call visual APIs via Python programming. Our AssistGPT falls into the second category by combining and invoking various modules for multi-modal reasoning, but we propose a new framework PEIL for integrating external tools and models. Compositional Reasoning. Compositional reasoning methods in the field of visual question an- swering usually decompose questions into several subtasks, each addressed by a specific module. This kind of method offers strong interpretability due to its modular structure and the clear division of responsibilities among the individual components. This idea was initially put forward by [57]. Subsequently, [58, 59] introduced an end-to-end variant based on LSTM and CNN. Traditional com- positional reasoning methods are limited by language models’ parsing capabilities, often requiring ground-truth question decomposition or reinforcement learning for optimal module usage. With the advent of LLMs, question decomposition can be accomplished remarkably well in a zero- shot manner. Chain-of-thought prompts [60], Toolformer [25], and ReAct [24] enable models to plan how to solve an NLP problem. HuggingGPT [17] and ViperGPT [21] are multi-modal systems that use LLM to parse a question into a series of reasoning steps. However, for complex queries, the model needs to determine the subsequent steps based on not only questions but also visual inputs or feedback from previously executed modules. MMReAct [61] introduced the idea of ReAct to a multi-modal system to overcome it, while it is still under development and hasn’t demonstrated its effectiveness on the benchmark. Previous methods reason over either language reasoning or code, and as stated in the introduction, both have certain shortcomings. Our work first proposes an interleaved language and code reasoning manner which can better handle general queries and complex visual inputs. Learning Schemes for Modular System. Early modular models primarily employed end-to-end Reinforcement Learning (RL) to train each module’s planning and acting from scratch. While this approach is practical for lightweight models, RL can introduce substantial overhead for systems where each module is an LLM. Toolformer [25] proposes a self-supervised technique that optimizes planning requiring only a handful of demonstrations for each API. Specifically, Toolformer attempts various APIs to find successful examples and then fine-tunes the model. In contrast, we propose a straightforward mechanism in the multi-modal field, which can guide the system to retry and preserve the successful explorations as in-context examples. # 3 AssistGPT Overview. AssistGPT is a general multi-modal AI assistant system that can dynamically engage various tools in an interleaved language and code manner. Specifically, given a general language query and reference images or videos as inputs, the goal of AssistGPT is to generate the desired answer. As shown in Fig. 3, AssistGPT is achieved by cooperation with four core modules: (a) Planner, (b) Executor, (c) Inspector, and (d) Learner. The Planner § 3.1 aims to control the whole reasoning process, with the Executor § 3.2 supplying valuable feedback to Planner by executing external tools. The Inspector § 3.3 manages the input and intermediate results and assists the Planner in feeding proper content to the Executor. The Learner § 3.4 is capable of assessing the system performance and record successful explorations as in-context examples. In the following sections, we will go through each module in detail. 4 @ Planner @ Executor @ Inspector Si 7 {Cesstietnase (ore ate) eee eet vee Ansa th lloing esto ss best os Your : BIB) user [ool Set illustration] Validation a Text Detection Modul: Used for detect the text “ieee [In-Context Example] ss Question:... Thought: .. Acton: .. Observation no ves | | "deer D User (&)—»{ input Query: When was the video .. ? 2. Module Execution: Image/Keyframe Captioner _ & Images @ execu Inspector ‘Summary of Input Videos and Images: Error Message Grounding eed Mecca oe meer i weit 4079 seins dad enerion; | QO Yoone i <module> only Coasduoned Lola S tatesvideoss =| OFA GM Get .. "pe veo | ‘Thought: | need to find input. duration av (or: ee J Srey et Executor Observation: Output of a tool ARES ‘Crop image / Segment Video Inspector ‘Summary: visual-1: a 17 seconds video, .. p nage / Sem [.. repeat above N times until getting final answer] ‘Thought: | know the final answer [User (2)—Final Answer: ‘Summary of Metadata: visual-1: a 17 seconds video, segmented video from visual-0, dense subtitle, target clip for query "When was the video 2. In-Context Memory Bank: Save as in-context example for better planning and module prompts Summary: visual-0, a 48.27 seconds video, sparse subtitle, user provided video, a toy "(train on the floor if success evaluate Figure 3: Diagrammatic illustration of AssistGPT system. It consists of four core modules: @ Planner: control the whole reasoning process; ® Executor: execute external tool and return feedback to Planner; ® Inspector: manage the input and intermediate outcomes; ® Learner: assess the system performance and record successful trials as in-context examples. # 3.1 Planner The @ Planner employs a highly intelligent LLM i.e., GPT-4 [52] as the central brain to control the global reasoning planning. It begins the planning process by taking inputs from three types of in- formation: an Instruction Prompt consisting of the [Tool Set Illustration] and [In-Context Example], Input Query , and the Summary of Visual Inputs created by @ Inspector. Then it generates the appropriate output for the next step, which consist of two parts: Thought: a language phrase indicates what should be done next. While it doesn’t affect the module or API call directly, it aids the LLM planning procedure. Action: a structural string obeys the pre-defined template provided in the instructions. It specifies which external tool to call and what arguments to input, e.g., After each time © Executor call to an external tool, the tool returns outputs in the form of natural language, which we refer to as Observation. If the tool generates an intermediate outcome, e.g., a segmented video, our @ Inspector will store it and generate a Summary for it. Both the Observation and Summary will be fed to the @ Planner to guide the planning of the next step. The following sections will introduce more details of Action, Observation , and Summary . Currently, we integrate 13 functional tools in AssistGPT to power multi-modal assistance, as shown in Tab. 1. These modules can be mainly categorized into three types: • Descriptor: To effectively comprehend and utilize the data derived from intricate multimodal environments e.g., image, video, audio, and text, we employ a variety of fundamental models as basic descriptors for perception. These models, including (a) Image Caption, (b) Video Narration, (c) Object Detection, (d) Text Detection, and (e) ASR Translation, enable us to extract enough information from diverse source, thus enhancing our understanding of the multimodal sceanrio. 2The successful trials recorded by Learner, will be introduced later. 5 Table 1: Module used in AssistGPT. A module may have different models, separated by a slash (/). Module Usage Core Model Input Output Module Usage Core Model Input Output T, I BLIP series [9–11] (a) Image Caption BLIP series [9–11] T, V (b) Video Narration G. Dino [64] / GLIP [13] T, I (c) Object Detection (d) Text Detection Google OCR (e) ASR Translation Whisper [65] (f) Region Ground OFA [66] I A T, I T T T T T T, I Program + SSA [62, 63] T, I (h) Text Ground (i) Subtitle Ground GPT [5] (j) Knowledge Reason GPT [5] GPT [5] (k) Narration Reason GPT [5] (l) Subtitle Reason Rule-based (m) Temporal Reason T, I T, Sub. T, V T T T, Nar. T T, Sub. T T, V T, V (g) Narration Ground GPT / CLIP [67] T, Nar. T, V I: Image, V: Video, T: Text, A: Audio, Nar.: Narration, Sub.: Subtitle • Locator: As the saying goes, a picture is worth a thousand words. Images or videos typically contain a wealth of information - objects, attributes, actions, events, and so on. However, the abundance of information can sometimes obstruct our problem-solving process. One crucial solution is to pinpoint the most crucial and valuable information from the rich sea of visual, textual, and audio data This part incorporates several modules such as the (f) Region Ground, (g) Narration Ground, (h) Text Ground, and (i) Subtitle Ground. • Reasoner: The initial two sets of tools primarily deal with collect and identify of data, whereas the third set focuses on reasoning, utilizing the extracted information and external knowledge. This part incorporates modules such as (j) Knowledge Reason, (k) Narration Reason, (l) Subtitle reason, and (m) Temporal Reason modules. These modules primarily utilize LLM at their core by taking different types of information and prompts as inputs or a simple program. # 3.2 Executor The ® Executor takes the code generated by the @ Planner as input, then call a module to produce the output by carrying out three steps to obtain the final result. These steps include validation check, module execution, and post-processing, as shown in Fig. 3. ¢ Validation Check: Even powerful LLM like GPT-4 can sometimes generate illegal code. For example, an image caption module accept a long video as input. We have designed a legality check for each module to determine whether the code is executable. Moreover, if code includes errors, we do not interrupt the entire reasoning process. Instead, we return an error message as the output code to the @ Planner, allowing it to optimize the planning process in real-time. ¢ Module Execution: We standard various modules or APIs into a unified interface using the code-style template i.e., [Module_Name] (<text_query>, <visual_index>). Each module is designed to accept multiple text queries and visual data (images or videos) as input. In each standarded module, we provide instructions on its function and the requirements of the argument, which is used for [Tool Set Illustration] in @ Planner. Additionally, for the sake of simplicity and accuracy in Planning, the generated code is simplified. Later, a simple rule-based function will map it to the executable codes and then execute it to obtain the final result. ¢ Post-processing: For all modules, the generated results will be translated into a language format to inform the @ Planner about the outcome, as the Observation part illustrated above. For instance, for the Narration Ground module, the model will return whether it has found the relevant segment. If so, output the start and end times of the segment. Additionally, many Ground-related modules will send their segmented video or cropped image region to the subsequent visual outcome manager i.e., ® Inspector. # 3.3 Inspector The objective of the ® Inspector is to manage the visual inputs provided by the user and the intermediary results produced by our system to assist the @ Planner in deciding which source should be directed to which module. Specifically, the @ Inspector records the metadata of each visual element, which includes its type (image or video), source (provided by the user or generated by the system), and a brief description of the content (obtained from the caption model, or the title of an online video). For videos, there is some additional metadata, such as the duration of the video, whether it contains audio and subtitles. The © Inspector monitors the inputs from the user and the outputs from the ® Executor. As soon as a new visual element is received, it appends the metadata, noted as Summary in the above, to the reasoning history of the @ Planner. With the cooperation of 6 the @ Planner, ® Executor, and ® Inspector, our system can generate answers to difficult queries with complex visual inputs. # 3.4 Learner Despite the robot generalization capabilities of LLMs, they can still easily encounter errors when dealing with multi-modal type queries. Thus, it is essential for an AI assistant to have self-valuate mechanism. To achieve this goal, we hope that the model can self-check the reasonableness of its output. On the other hand, when ground truth is available, we intend to gather successful prediction instances as in-context examples. Specifically, AssistGPT will repeatedly attempt to provide the answer when the response is not satisfactory until either passes the self-check, or correct answer is given (when ground truth is available) or a predefined maximum number of attempts is reached. © Learner includes an evaluator implemented by the LLM, which operates in two modes: self- assessment and ground-truth comparison. These modes are activated depending on the availability of ground truth, and we discuss the two of them separately. • Self-assessment mode is activated when there is no user feedback or ground truth available. It takes the reasoning trace and the results of each step as input, allowing GPT to assess whether the reasoning is complete, consistent, and adhere to the required format. • Ground-truth comparison mode is activated when annotators provide ground truth. In this mode, GPT evaluates whether the AssistGPT’s prediction is semantically consistent with the provided ground truth. Furthermore, ® Learner encourages to keep trying until it receives positive feedback or reachs the maximum number of attempts. After conducting N times explorations, several outcomes may arise: • No adjustments required: If the model delivers the correct answer on its initial attempt, this sug- gests that AssistGPT can well-solve the current question effectively. Therefore, no improvement is required. • Plan Revision: If the model produces the correct answer after making n attempts, where 1 < n ≤ N , this implies that there is room for improving the model’s planning capabilities. Therefore, we save the successful reasoning trace to [In-Context Memory Bank]. Consequently, when the model comes across a similar query in the future, it can use this as an in-context example. • Function Updates: If the model still fails to provide the correct answer even after N attempts, it is highly probable that the problem resides in a specific module or API rather than the planning process. It may necessitate incremental updates to the module. We will leave this for future work. # 4 Experiments # 4.1 Experimental Setting Datasets. Our system is evaluated on A-OKVQA [33] and NExT-QA [68] benchmarks designed to test comprehensive multimodal capabilities, including visual facts, commonsense, temporal sequences, causality, etc. A-OKVQA [33] is an innovative benchmark for knowledge-aware visual question answering with 25K questions that demand a high-level comprehension of commonsense and world knowledge. These questions in A-OKVQA go beyond the information contained in the image and cannot be answered solely by querying a knowledge base. Besides, the question is diverse, spanning a wide range of domains such as commonsense reasoning, visually-grounded, knowledge-based, and physical understanding. In our experiments, we assess the model performance under the in- context learning setting on the validation set, which consists of 1,145 questions. NExT-QA [68] is a benchmark for evaluating the AI system’s causal reasoning, temporal action reasoning, and rich object interactions in video question answering. NExT-QA has a total of 5,440 videos, with averaging 44 seconds in length, and approximately 52K manually annotated question-answer pairs. In our experiments, we assess the model performance under the in-context learning setting on the validation set, which consists of 4,996 questions. Implementation Details. In the following experiments, we use GPT-4 API provided by OpenAI [52] as Planner. In the A-OKVQA experiments, we set Caption Module as BLIP2 or InstructBLIP (abbreviated as Ins.BLIP), use the Gounding Dino for the Object Detection model, and Google 7 OCR for Text Detection. For the NExT-QA experiments, our Video Narration Module is based on InstructBLIP Vicuna-7B [11]. Our experiments are performed on 4 A5000 GPUs. # 4.2 Quantitative Results Table 2: Comparison of SOTAs on A-OKVQA dataset. D.A. and M.C. indicate direct answer and multi-choice. ICL: In-context Learning. ZS: Zero-shot inference. Table 3: Ablation study of our AssistGPT on A-OKVQA dataset. Ins.BLIP used here is the pre-trained version. Model D. A. M.C. LLM Model D.A. M.C. LXMERT [29] KRISP [36] GPV-2 [69] InstructBLIP Vicuna-7B [11] 30.7 33.7 48.6 64.0 51.4 51.9 60.3 75.7 - Ins.BLIP 13.4 . p u S Ins.BLIP + GPT-4 27.9 28.8 30.1 32.4 41.2 44.3 T Reason only P ReAct G PIE t s i s PEIL w. Self-Check s A PEIL w. GT-Check L PromptCap [70] C 56.3 42.6 44.3 AssistGPT (BLIP2 FlanT5XL [54]) AssistGPT (Ins.BLIP Vicuna-7B) I 53.8 55.2 65.9 68.2 72.4 74.2 74.7 73.2 73.7 74.7 Comparison with State-of-the-arts. From the results in Table 2, it can be seen that in the multi- choice track, our two versions of AssistGPT (i.e., with light-weight BLIP2 FlanT5XL and more powerful Ins.BLIP Vicuna-7B) achieve the best among all current methods on in-context learning setting. It’s worth noting that we use a pre-trained version of InstructBLIP, which performs at 53.3%, as shown in Table 3. When integrated into our system, it can enhance its performance to the level of fine-tuning model. For direct answer questions, while our performance on it may not match that of recently proposed models, it is still comparable to previous supervised SOTA, like GPV-2 [69]. Our performance on direct answers did not surpass previous methods. The main reason is that for open-ended questions, models relying on LLM tend to output complete phrases rather than a single word as the final answer, even when we prompt them to provide as concise an answer as possible. For instance, for a given question "What flag is represented on the wall?", AssistGPT outputted the answer, "United States flag", but the correct answer does not include the word "flag", therefore it’s deemed incorrect. This type of error is very common in AssistGPT. In the appendix, we show more examples to analyze the failure cases. Moreover, compared to the SOTA method, PromptCap [70], it specifically trained a caption model toward generating captions for A-OKVQA, which is also the reason for its good performance, while our system is more general. From the results in Table 4, AssistGPT achieved higher performance than recently proposed su- pervised methods, demonstrating the effectiveness of our approach. We can see that our model’s performance mainly shows a more promising improvement in Causal and Descriptive questions, mainly due to our model continuously obtaining detailed information related to the question from the videos. Moreover, our method does not perform well on temporal questions. The main reason for this is that there are relatively few open-world temporal grounding models available, and main- stream work still involves fine-tuning on closed-world datasets. Therefore, we have to use the image captioner InstructBLIP with GPT-4 to achieve temporal grounding. The effect is not as good as that of fine-tuned models but has a more generalization ability. Furthermore, its performance is also very close to recent concurrent work, ViperGPT [21]. The ViperGPT is a little bit superior to ours, possibly because it has designed a sophisticated rule-based method, iteratively checking whether objects appear in the frame to perform temporal grounding. Ablation Study. We have designed several variants of AssistGPT to test the effectiveness of our proposed method. The most basic baseline is InstructBLIP (note that all following models are using Vicuna-7B version), which is the main source of visual information in AssistGPT. Since InstructionBLIP cannot necessarily output the answer in the required format, we design a variant, InstructionBLIP+GPT-4 allows GPT-4 to further refine the output of InstructionBLIP. The Reason- only model directly plans all the steps the models need to run, similar to previous works [17]. The ReAct model is capable of executing language-based ReAct. However, without Inspector and Code- like invocation forms, a subsequent model can only accept the output of the previous model, which is similar to [61]. We also ablate the Learner, which has three versions, PIE (i.e., w/o. Learner), PEIL w. Self-Check and PEIL w. GT-Check. From the results in Table 3, we can see that the Reason-only model, which plans all the steps the models need to execute, showed a notable improvement in D.A. and M.C. This indicates that 8 Table 4: Comparison of our AssistGPT with SOTAs on NExT-QA dataset. Method Causal Temporal Descriptive All . p u S HGA VQA-T [71] ATP [72] VGT [73] MIST [74] 44.22 49.60 53.10 52.28 54.62 52.49 51.49 50.20 55.09 56.64 44.07 63.19 66.80 64.09 66.92 49.74 52.32 54.30 55.02 57.18 L ViperGPT [21] C AssistGPT I - 60.02 - 51.38 - 67.26 60.00 58.36 integrating multiple models can enhance model performance. The ReAct model, despite not having Inspector and Code-like invocation forms, showed a further improvement in both metrics, surpassing the Reason-only model. This suggests the effectiveness of ReAct manner. But involving our interleaved language and code, i.e., PIE, brings a more significant improvement on M.C. Finally, the two variants of PIE with partial ablations, PEIL w. Self-Check and PEIL w. GT-Check, scored the highest on both tracks, showing the effectiveness of the Learner. The Learner shows a more significant improvement on D.A. tracks because models on D.A. often fail to output extremely short answers as required by A-OKVQA. The Learner can mitigate it by collecting in-context examples. # 4.3 Qualitative Results Question’ : What kind of room is on the left of the yellow train? You must choose one ‘answer from: nursery room, bathroom, changing room, waiting room : an image, user-provided, a yellow and white pain pulling into a train station + Thought: The observation —+ Thought: Now that I have the _, Thought: Now that I have the contradicts the visual cropped image of the room, I ‘cropped image of the room, I description. I will try to can check its type. locate the room in the image. Thought: Check the visual Information about the room on the left of the yellow train. caption( C1) Observation: Observation: Train station Thought: of the given ‘options match the observation. Final Answer: of the given options match the room. There is no room on the yellow tra: ‘egion found visual-1: an image, cropped ... @ InstructBLIP: Describe the image in detail: The image depicts a busy train station, with several people standing on the platform waiting for their trains. There is a yellow and white train parked on one of the tracks, with passengers boarding and disembarking from the train. In the background, there are several ‘MiSiai'the question based on the above information of the image: Question: ... You must choose one answer from: ° GPT-4: The information provided about the image does not specify what kind of Thought: _T know the final answer. room is on the left of the yellow train. Thus, it's impossible to definitively Final Answer: waiting room answer this question based on the given detail. Thought: I need to infer way {does the baby stop for a while near the end of the video? Thought: Locate the final moment Thought: I need to know more in the video. information about the video. Action: stop for a while near the end a 81 seconds video, The answers for each yes, no, yes, no, Thought: I know the final answer. Final Answer: to look at the person filming provided video, a little girl riding a tricycle on a sidewalk Figure 4: Qualitative results on A-OKVQA (Question 1) and NExT-QA dataset (Question 2). In Fig. 4, we visualize some prediction cases from A-OKVQA (Question 1) and NExT-QA (Question 2). From both examples, it can be seen that AssistGPT can decompose the question into reasonable sub-tasks and then complete them step by step, ultimately obtaining the final answer. Moreover, due to the interleaved code and language reasoning method, the model can effectively invoke the necessary content as input. From the reasoning process of Question 1, we can also see AssistGPT’s self- correction ability. When the visual model output unsatisfactory results, AssistGPT can dynamically invoke other modules, like the ground module to reason over another path. In addition, for Question 9 1, the model’s first attempt did not yield effective results, and it will autonomously optimize the plan because it did not pass the self-check. In addition, we also present the result of the reason-only baseline. It first calls InstructBLIP to output a caption, then uses GPT-4 for inference. Since the information from the caption does not meet the requirements, resulting incorrect results. However, once the prediction fails, the model does not have a way to self-optimize. It’s worth mentioning that the most significant feature of our method is that it can solve more complex problems than those in the benchmark, as the example in Fig. 1. We show more in-the-wild examples in the Appendix. # 5 Conclusions and Limitations In this paper, we propose a novel multi-modal assistant system named AssistGPT that leverages an interleaved code and language reasoning approach, namely Plan, Execute, Inspect, and Learn (PEIL). This innovative system integrates LLM with various tools to address the challenges posed by complex visual-based tasks. Our experimental results on A-OKVQA and NExT-QA benchmarks demonstrate AssistGPT’s effectiveness. Furthermore, we showcase our system’s ability in handling diverse and intricate real-world scenarios. Our system also has some limitations. Our approach does not propose an end-to-end updating solution, which is crucial when the tools used make mistakes. Another limitation is that the planning process requires an extensive explanation of tools, resulting in a relatively large overhead, which could be improved by distilling a smaller size planner. # Appendix In the appendix, we provide additional details for the main paper: More discussion with existing modular systems in Sec. A • More details of AssistGPT in Sec. B. • More qualitative results of A-OKVQA in Sec. C. • More in-the-wild examples in Sec. D. # A Discussion with Existing LLM-driven Modular Systems Table 5: Comparison of existing LLM-driven modular systems. We compare existing methods from four dimensions: Task Focus, Reasoning Method, Source Management (how they manage input and intermediate results), and whether they have learning capabilities. The term "ReAct" in the table does not strictly refer to using the ReAct [24], but rather it denotes planning and executing concurrently. Task Focus Reasoning Source Management . Model Learning NLP Image Video Format ReAct Input format Method Toolformer [25] v x x lang. & prog. v text-only - v WebGPT [75] v x x program v test-only - v Visual ChatGPT [8] x v x language x multi. V. Filename x ViperGPT [21] x v v program x single V. Variable x VisProg [22] x v x program x single V. Variable x MM-ReAct [61] x v v language v multi V. Filename x Chameleon [19] v v x language x single V. Cache update x HuggingGPT [17] x v v language x multi V. Filename x AssistGPT (ours) x v v lang. & prog. v multi V. Inspector v In Table 5, we compare the existing LLM-driven modular systems with our AssistGPT from four perspectives: Task Focus. From the perspective of Task Focus, there are currently three works that can handle videos: Hugging GPT [17], MM-ReAct [61], and ViperGPT [21]. Hugging GPT and MM-ReAct merely demonstrate their capabilities in handling videos through a few simple examples (thus we mark them with orange checkmarks /). For instance, Hugging GPT exhibits its video generation feature, while MM-ReAct showcases its ability to perform tasks such as summarization and localization based 10 on subtitles. However, these methods have not been validated on any benchmark. ViperGPT can handle questions based on visual content. Compared to these works, AssistGPT is capable of dealing with more complex and general video question-answering tasks, including understanding subtitles, visual content, and OCR, and demonstrating long video comprehension capabilities. Reasoning. In terms of reasoning, existing Multi-modal models primarily adopt a reason-only style, that is, directly deriving the solution steps based on the question. This approach struggles with handling complex visual inputs, and when the intermediate results don’t meet expectations, the model also finds it hard to self-correct. MM-ReAct introduces the original ReAct for reasoning in Multi-modal tasks, but due to the original ReAct’s inadequacy in dealing with complex non-text intermediate results, its current planning scheme for addressing video-related issues is basically two steps: extracting all information from the video and then having an LLM answer the question. In contrast, this paper proposes a more general Plan, Execute, Inspect, and Learn (PEIL) reasoning scheme. In the case of complex videos, our interleaved language and code reasoning approach allows for flexible language planning for the next step, and structured code for invoking input and intermediate results, thereby facilitating the handling of complex questions and visual content. Source Management. Handling complex input and a large number of intermediate results is often crucial in complex reasoning processes. Current language-based reasoning methods mainly use filenames to label resources. Chameleon proposes an update mechanism with a cache that constantly updates the current reasoning results. Program-based reasoning, on the other hand, uses variables to store intermediate results. A deficiency of these methods is the inability of the language-based Planner to quickly comprehend the content of visual sources, which impedes the effective use of different sources to complete different subtasks. As a result, existing work struggles to handle flexible input and intermediate results. Even though some work supports multiple visual sources as input, they are more often batch-processed for similar tasks, with each source requiring similar operations. For instance, in HuggingGPT, the task of calculating the sum of the number of zebras in several images involves counting the number of zebras in each image. In contrast, our work introduces the Inspector, which records the metadata and summary of each visual source and provides it to the Planner for reasoning. This design can support complex input. For example, a user view image that describes the current user’s problem, and a reference video as a source of knowledge, AssistGPT can then use these two different types of sources to jointly answer the user’s question. Learning. Most multi-modal modular systems lack the capability for continuous optimization. This paper proposes a simple update mechanism that allows the model to self-check the reasonableness of its output and ultimately continues to collect in-context learning examples. # B More details of AssistGPT Table 6: Invoke Commands and Illustrations to the Modules in AssistGPT. Module Invoke Command Illustration (a) Image Caption (b) Video Narration (c) Object Detection (d) Text Detection (e) ASR Translation (f) Region Ground (g) Narration Ground (h) Text Ground (i) Subtitle Ground (j) Knowledge Reason (k) Narration Reason (l) Subtitle Reason (m) Temporal Reason caption(query, visual[i]) video_narration(query, visual[i]) object_detect(query, visual[i]) text_detect(None, visual[i]) asr(None, visual[i]) region_ground(query, visual[i]) narration_ground(query, visual[i]) text_ground(query, visual[i]) subtitle_ground(query, visual[i]) knowledge_reason(query, []) narration_reason(query, visual[i]) subtitle_reason(query, visual[i]) temporal_reason(query, visual[i]) In Table 6, we show the invoke commands and illustration of each module in AssistGPT. We provide more details of how each module is implemented. • Image Caption: The core model of this module is a text-conditioned captioning model, e.g., BLIP2 [54], InstructBLIP [11], similar to an open-ended Visual Question Answering model. 11 • Video Narration: As the general video captioning models are not yet mature, we currently use the image captioning model [54, 11] to accomplish this function. Specifically, we sample image frames (1/3 FPS for current implementation) and perform text-conditioned captioning on each frame. We employ text-conditioned captioning because, if we use dense captioning, the output text will be excessively abundant, making it difficult for subsequent models to utilize. The Video Narration feature can also optionally read the OCR content within the frames. The extracted OCR will be appended to the caption of each frame. • Object Detection: The main function of this module is to determine whether the image contains the objects mentioned in the query and to address counting-related questions. Thus, it contains an open-set object detection model, e.g., Grounding DINO [64], which can output the bounding boxes of relevant objects based on the query. We also let the module calculate the number of related objects. • Text Detection: This model is used to extract OCR from images, and the extracted text is returned to the Planner. We use Google OCR to achieve this purpose. ASR Translation: This model is used to convert audio from a video into text. We use Ope- nAI’s open-source ASR (Automatic Speech Recognition) model, Whisper [65], to accomplish this. The detected ASR organizes timestamps and text in a manner similar to subtitles. In the implementation, we automatically run this module as soon as we receive a video with audio. • Region Ground: The purpose of this module is to find a specific area of an image based on the query. We use the OFA-Large [66], which is fine-tuned on RefCOCO, to achieve it. Narration Ground: This model’s function is to find time segments related to the query based on the video’s narration. We propose two implementations: 1) We use GPT-4 [5], taking the video’s narration and query as prompts, to output the timestamps of the time segments. 2) Another solution is using CLIP [67] to do that. We can split the video into several segments, and calculate the similarity between the frame in each segment and query. The time stamps of the segment with the highest similarity will be outputted. In our preliminary experiments, the first solution showed better interpretability and generalization ability, so it was adopted in the benchmark evaluation. • Text Ground: The purpose of this model is to locate specific areas of an image that correspond to a certain text. This capability can guide users in identifying crucial information in complex, text- rich images, such as user interfaces. The query format is text[:object_name], wherein text signifies the text to be located, and object_name (which is optional) is used to locate the text on a specific object, for instance, "menu: button". Specifically, the model operates in two stages: 1) Based on the Optical Character Recognition (OCR) detection results, the model identifies areas of the image that match the text segment of the query. This is achieved by calculating the distance between the query and the OCR extracted, and when the edit distance is below a particular threshold, it is considered a match. 2) If more than one textual area is identified, we further refine the results based on the object’s name. We employ the Semantic Segment Anything (SSA) [63] to segment the image semantically, identifying regions that match the object’s name mentioned in the query. • Subtitle Ground: This model is similar to the narration grounding model, but it uses the video’s subtitles as input instead of the narration. Thus, we also use GPT-4 to achieve it. • Knowledge Reason: The purpose of this model is to enable the model to apply external knowl- edge to answer questions. We currently do not connect to the internet to retrieve knowledge, but use the knowledge that GPT-4 has itself learned. Specifically, this model enables GPT-4 to use its own knowledge to infer the answer based on the question and results of all previous reasoning steps. • Narration Reason: The aim of this module is to infer some information based on the visual content of the video. This module also uses GPT-4, taking the query and the input video’s narration as prompts, to infer the answer. • Subtitle Reason: The aim of this module is to infer some information based on the subtitle of the video. It is similar to Narration Reason, but takes the input video’s subtitle and query as prompts, to infer the answer. • Temporal Reason: This model is able to find a video clip based on some temporal relation words. The input to this module follows the following format: temporal_word: time stamps, e.g., after: 3 - 6. Temporal relation words include two types, one is absolute temporal relation words, such as in the middle/beginning/end of the video. The second type is relative temporal relation words, 12 such as before and after. For the first type of words, we divide the video into 5 segments and then output the time stamps of the corresponding segment according to the temporal_word. For the second type, we divide the video into 8 segments, and then, according to the input time stamps, we output the time stamps of the segment before or after it. The current hyperparameters, the division of video clips, are still preliminary. It would be much better to use the model to divide them semantically, and then perform temporal reasoning in the future. # C Qualitative Results in A-OKVQA In Figure 5, we showcase a successful instance along with several failure examples, illustrating the most frequent error patterns in A-OKVQA. As is evident, AssistGPT can produce highly interpretable answer processes. Moreover, even in cases where the questions are answered incorrectly, there are relatively reasonable explanations provided. In the following, we illustrate the common error patterns in detail: • Undesired output format: For Direct Answer questions, like Q2, the results of AssistGPT are the same as the correct answers in meaning, but the expression is different, which would be considered as incorrect under the existing metrics. • Fine-grained recognition: The recognition of fine-grained categories of some objects is still not well done by existing visual models, resulting in the incorrect final answer. For example, AssistGPT didn’t successfully recognize cough drops in Q3. Pose-to-text: Currently, there are very few models that can map the fine-grained pose or actions of people or animals to natural language. For example, capturing the upward jump action of the cat in Q4 is a challenge. AssistGPT currently does not incorporate a related model to grasp such information. Instead, it makes prediction based on the surrounding objects in relation to the cat. • Inconsistent reasoning: Despite AssistGPT having some self-error correction mechanisms, it occasionally exhibits inconsistencies in its reasoning process, which can lead to final inaccuracies. For instance, in Q5, the model initially identifies the orange vehicle as a truck, but in subsequent steps, it is referred to as a shuttle bus. Unfortunately, AssistGPT fails to detect this inconsistency and does not proceed to make necessary corrections. # D In-the-wild Prediction Examples We show some examples of AssistGPT handling in-the-wild scenarios in Figure 6 and Figure 7. From various in-the-wild examples, it’s clear that AssistGPT can adeptly handle a range of video types, be it dense, subtitled instructional videos (Q2, Q3), or those featuring rich, visual content with sporadic on-frame text (Q1, Q4, Q5). Impressively, when faced with high-level queries (Q2 and Q3), the model exhibits a capacity to strategically locate useful content, accurately identify the correct responses, and offer comprehensive, multimodal answers. A notable self-error correction capability is also evident during its reasoning process, as demonstrated in Q2. Here, the narration model was unable to generate meaningful narrations and, therefore, opted to utilize the subtitle to answer the question. Moreover, in Q5, we highlight that our model can effectively process multiple video inputs serving different functions. This includes a User view image and a couple of reference videos. It’s important to note that our model can accommodate any number of inputs. Consequently, with the incorporation of a YouTube video search function, the model could autonomously seek out several reference videos and then cross-reference them to discern the user’s intent. In summary, we want to emphasize that AssistGPT is a comprehensive multi-modal assistant system, capable of managing a wide array of real-world application queries that are far more complex and comprehensive than the samples provided in benchmarks. 13 Question1: What is the man in the gray suit on the left looking down to check? You must choose one answer from: phone, tablet, notebook, pager Thought: Check the visual + information about the man in the gray suit on the left. Action region_ground( -@: an image, user provided image, main content is two men in gray suits sitting at a table visual[°]) Observ: region found visual-1: an image, cropped image from visual- ®, main content is man in the gray suit on the left region Question2: Which number birthday is probably being celebrated? Thought: Check the visual > information about the birthday number in the image. Action an image, user provided image, main content is a teddy bear cake on a table text_detect( Figna, Troy, 30,afo Thought: Check the visual — information about the items on the desk in the image. Action svisual[?]} Question3: What item on the desk could help with a cold? You must choose one answer from: cough drops, syringe, pills, herbal tea caption( : an image, user provided image, main @ woman visual[]) content is reading a book in front of a laptop Observ: On the desk in the image, there is a laptop computer ‘a notebook, and a pen. Question4: What activity + does the cat appear most likely to do? You must choose one answer from: drink, jump, eat, sleep Thought: Check the visual information about the cat and its surroundings. Action: caption( visual-@: an image, user , visual[0]) provided image, main Observ: The cat is sitting on the floor in front of an open oven, staring up at the reflection of itself in the oven's glass door. There is also a bowl and a water bottle nearby. content is a cat sitting on the floor looking at an oven traffic Thought: Check what the man in the gray suit on the left is looking down to check. caption( 5 visual []) Observation: The man is looking down to check his cell phone. Thought: I know the final answer. Final Answer: phone Thought: I found the number 3@ in the image. It could be the birthday number Final Answer: 30 Ground truth [‘thirty’, ‘30th’, ‘thirty’, ‘thirty’, ‘thirty’, ‘30th’ ‘thirty’, ‘thirty’, ‘thirty’, ‘thirty’] Thought: of the given options are present in the image. I need to choose the best option based on common sense knowledge. Action: knowledge_reason( » []) Observation: herbal tea Thought: I know the final answer. Final Answer: herbal tea Thought: Determine the most likely activity the cat will do based on the objects around it. Action knowledge_reason( Thought: I know the final answer. Final Answer: drink QuestionS: What are the orange vehicles for? You must choose one answer from: police, shuttle, passengers, air (ae is visual-@: an image, user provided image, main two airplanes on a runway Thought: I need more information about the tow trucks to + determine their purpose. Check the choice one by one Action Thought: Check the visual information about the orange vehicles in the image. Actio ‘Observat The orange vehicles in the image are tow trucks. Observ: The answers for each question are: no, Yes, the orange vehicles are shuttle buses., No, Yes, the orange vehicles are for air traffic control Thought: I know the — Final answer. Final Answer: shuttle # Figure 5: Reasoning process of AssistGPT on A-OKVQA. The choice colored with green in the question indicates the ground truth. 14 Thought: I need to find the segment of Messi's second goal Action: video_narration( visual[>]) Observation: 9-12: he is celebrating with his team mates 12-15: he is kicking the ball into the goal 15-18: he is dribbling the ball Thought: Find the video segment that shows how to grip the racket when striking. Action: subtitle_ground( visual[°]) Observation: The target clip is from 32.16 to 42.8 in subtitle. visual-1: a 10.64 seconds video, dense subtitle, segmented video from visual-@ Talking about "How to grip the racket when striking” Thought: I know the final answer. of Messi's second goal. Action: video_ground( » visual[>]) Observation: the target clip is from 12-27 visual-1: a 15 seconds video, no meaningful subtitle, segmented from visual-@, ... Thought: Describe the video clip to provide the answer. Action: video_narration( » Visual[ ]) Observation: @-3: badminton court - how to play badminton 3-6: how to hit a badminton ball 6-9: how to play badminton visual-@: a 146.59 seconds video, no meaningful subtitle, user provided video, Every Lionel Messi Goal from the 2022 FIFA World Cup — Thought: Find the segment — Thought: Identify the country Messi scored his second goal against. Action: text_recognize( visual[>]) Observation: 63:27 ARG O O MEX WORLD'S BEST AIRLINE QATAR AIRWAYS QATAR AIRWAYS 16 Vorldcr FIFAR) WORLD'S BEST AIRLINI visual-@: a 279.08 seconds video, > Dense Subtitle, user provided video, Common Beginner Badminton Mistakes - Do And Don'ts 2 Thought: The narration doesn't provide enough information about gripping the racket. I need to watch the video more closely. Action: video_narration(" » visual[ ]) Observation: @-3: Describe how to grip the racket when striking 3-6: how to grip the racket when hitting the ball 6-9: Describe how to grip the racket when striking Question1: Which country was Messi's second goal scored against? Thought: Infer which country was Messi‘s second goal scored against. Action: knowledge_reason( » {)) Observation: Mexico Thought: I know the final answer. Final Answer: Mexico Question2: How to grip the racket when striking? And show me a video clip to illustrate it. Thought: The video narration still doesn't provide enough information about gripping the racket. I will try to find more information from the subtitles. Action: subtitle_reason( visual[|]) Observation: When striking, grip the racket with a forehand grip, which allows you to rotate the forearm and generate more power in your shots. This grip also enables you to get into a side-on position and bring your elbow back, giving you more control and deception with your overhead shots. | Final Answer: When striking, grip the racket with a forehand grip, which allows you to rotate the forearm and generate more power in your shots. This grip also enables you to get into a side-on position and bring your elbow back, giving you more control and deception with your overhead shots. To see a video clip illustrating this, please check the visual output. (visual[1]) # Figure 6: The reasoning process of AssistGPT when handling in-the-wild questions. 15 x visual-@: a 917.51 seconds video, Dense subtitle, user provided video, GoPro Hero 8 Black Best Tips and Tricks! visual-1: a 1783.08 seconds video, Dense subtitle, user provided video, GoPro Hero 10 Beginners Guide & Tutorial _ Getting Started Thought: First, I need to -—» Thought: The text understand what the recognition tool provided setting in the image is. the setting information, I will use the which is “Linear + Horizon text_detect tool to read Lock, Full 36@ rotation.” any visible settings or It appears to be a setting text in the image. or a feature of a device, Action: possibly the smartwatch in the image. .. I'll use the subtitle_ground tool on both videos to find a text_detect( visual[-]) Observation: segment that mentions this Linear + Horizon Lock, Full 360 setting. Action: rotation. Thought: I need to watch the video and narrate the content. subtitle_ground » visual[>]) Observation: Warning: Relevant clip didn’t found. > Thought: The first video doesn't contain the required information. I'll now try the same action with the second video. Action: subtitle_ground » visual[']) Observation: the target clip is from 18:02 - 18:44 visual-3: a 42 seconds video, segmented video from visual-1, dense subtitle, target clip for query "Linear + Horizon Lock, Full 360 rotation" Every Time PT J Action: video_narration( » visual[@]) Observation: 0-3: asian beef stir fry. Texts on the frame (Taste) 3-6: a chef is preparing a beef dish Texts on the frame (Beef 350 g Taste) 6-9: a person is cutting a piece of meat. Texts on the frame (Taste) 9-12: a person is cutting a piece of meat. Texts on the frame (e Taste) f . QuestionS: List all t : / PT ) Thought: I need to find the ingredients and their weights in the video. Action: video_narration( » Visual[@]) Observation: 0-3: asian beef stir fry. Texts on the frame (Taste) ... 84-87: garlic. Texts on the frame (Garlic 15 g Taste) ... 132-135: 1 cup of broccoli florets. Texts on the frame (Taste) ... > Question4: How to Cook Perfect Beef Stir Fry? visual-2: an image, user provided image, main content is a close up of a person holding a smart watch. —» Thought: The subtitle_ground tool found a clip from the second video that mentions "Linear + Horizon Lock, Full 360 rotation." This video segment should illustrate what these settings mean. Final Answer: (The meaning of the setting ‘Linear + Horizon Lock, Full 360 rotation’ is explained in the extracted video clip, visual[3]) visual-@: a 197.12 seconds video, no meaningful subtitle, user provided video, How to Cook Perfect Beef Stir Fry Thought: I have the narration of the video, now I can summarize the steps to cook perfect beef stir fry. Final Answer: To 1. Slice 350g of beef. cook perfect beef stir fry, follow these steps: 2. Cut 100g of carrots and 200g of broccoli. 3. Mince 15g of garlic. Heat a wok with cold oil to prevent sticking. 5. Cook the beef in the wok. Add the vegetables and cook them. Add 1 tsp of soy sauce and some water. 8. Mix water and cornstarch, then add it to the wok. 9. Add some lemon juice. 10. Serve the stir fry over cooked brown rice. he ingredients for the dish and their weights. Thought: I have found the ingredients and their weights in the video narration. Final Answer: The ingredients and their weights for the beef stir fry are: Beef 350g, Soy Sauce 1 1/2 tsp, Carrot 100g, Broccoli 200g, Garlic 15g, and Cooked Brown Rice. # Figure 7: The reasoning process of AssistGPT when handling in-the-wild questions. 16 # References [1] 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. [2] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. Language models are unsupervised multitask learners. OpenAI blog, page 9, 2019. [3] 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. NeurIPS, pages 1877–1901, 2020. [4] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timo- thé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. [5] OpenAI. Introducing chatgpt. OpenAI Blog, 09 2021. [6] Andy Zeng, Adrian Wong, Stefan Welker, Krzysztof Choromanski, Federico Tombari, Aveek Purohit, Michael Ryoo, Vikas Sindhwani, Johnny Lee, Vincent Vanhoucke, et al. So- cratic models: Composing zero-shot multimodal reasoning with language. arXiv preprint arXiv:2204.00598, 2022. [7] Zhenhailong Wang, Manling Li, Ruochen Xu, Luowei Zhou, Jie Lei, Xudong Lin, Shuohang Wang, Ziyi Yang, Chenguang Zhu, Derek Hoiem, et al. Language models with image descriptors are strong few-shot video-language learners. arXiv preprint arXiv:2205.10747, 2022. [8] Chenfei Wu, Shengming Yin, Weizhen Qi, Xiaodong Wang, Zecheng Tang, and Nan Duan. Visual chatgpt: Talking, drawing and editing with visual foundation models. arXiv preprint arXiv:2303.04671, 2023. [9] Junnan Li, Dongxu Li, Caiming Xiong, and Steven Hoi. Blip: Bootstrapping language-image pre-training for unified vision-language understanding and generation. In ICML, pages 12888– 12900, 2022. [10] Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi. Blip-2: Bootstrapping language- image pre-training with frozen image encoders and large language models. arXiv preprint arXiv:2301.12597, 2023. [11] Wenliang Dai, Junnan Li, Dongxu Li, Anthony Meng Huat Tiong, Junqi Zhao, Weisheng Instructblip: Towards general-purpose Wang, Boyang Li, Pascale Fung, and Steven Hoi. vision-language models with instruction tuning. arXiv preprint arXiv:2305.06500, 2023. [12] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to-end object detection with transformers. In ECCV, pages 213–229, 2020. [13] Liunian Harold Li, Pengchuan Zhang, Haotian Zhang, Jianwei Yang, Chunyuan Li, Yiwu Zhong, Lijuan Wang, Lu Yuan, Lei Zhang, Jenq-Neng Hwang, Kai-Wei Chang, and Jianfeng Gao. Grounded language-image pre-training. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), pages 10965–10975, June 2022. [14] Jialian Wu, Jianfeng Wang, Zhengyuan Yang, Zhe Gan, Zicheng Liu, Junsong Yuan, and Lijuan Wang. Grit: A generative region-to-text transformer for object understanding. arXiv preprint arXiv:2212.00280, 2022. [15] Jianfeng Wang, Zhengyuan Yang, Xiaowei Hu, Linjie Li, Kevin Lin, Zhe Gan, Zicheng Liu, Ce Liu, and Lijuan Wang. Git: A generative image-to-text transformer for vision and language. arXiv preprint arXiv:2205.14100, 2022. 17 [16] Xi Chen, Xiao Wang, Soravit Changpinyo, AJ Piergiovanni, Piotr Padlewski, Daniel Salz, Sebastian Goodman, Adam Grycner, Basil Mustafa, Lucas Beyer, Alexander Kolesnikov, Joan Puigcerver, Nan Ding, Keran Rong, Hassan Akbari, Gaurav Mishra, Linting Xue, Ashish Thapliyal, James Bradbury, Weicheng Kuo, Mojtaba Seyedhosseini, Chao Jia, Burcu Karagol Ayan, Carlos Riquelme, Andreas Steiner, Anelia Angelova, Xiaohua Zhai, Neil Houlsby, and Radu Soricut. Pali: A jointly-scaled multilingual language-image model, 2022. [17] Yongliang Shen, Kaitao Song, Xu Tan, Dongsheng Li, Weiming Lu, and Yueting Zhuang. Hugginggpt: Solving ai tasks with chatgpt and its friends in huggingface. arXiv preprint arXiv:2303.17580, 2023. [18] Yingqiang Ge, Wenyue Hua, Jianchao Ji, Juntao Tan, Shuyuan Xu, and Yongfeng Zhang. Openagi: When llm meets domain experts. arXiv preprint arXiv:2304.04370, 2023. [19] Pan Lu, Baolin Peng, Hao Cheng, Michel Galley, Kai-Wei Chang, Ying Nian Wu, Song-Chun Zhu, and Jianfeng Gao. Chameleon: Plug-and-play compositional reasoning with large language models. arXiv preprint arXiv:2304.09842, 2023. [20] KunChang Li, Yinan He, Yi Wang, Yizhuo Li, Wenhai Wang, Ping Luo, Yali Wang, Limin Wang, and Yu Qiao. Videochat: Chat-centric video understanding. arXiv preprint arXiv:2305.06355, 2023. [21] Dídac Surís, Sachit Menon, and Carl Vondrick. Vipergpt: Visual inference via python execution for reasoning. arXiv preprint arXiv:2303.08128, 2023. [22] Tanmay Gupta and Aniruddha Kembhavi. Visual programming: Compositional visual reasoning without training. arXiv preprint arXiv:2211.11559, 2022. [23] Yaobo Liang, Chenfei Wu, Ting Song, Wenshan Wu, Yan Xia, Yu Liu, Yang Ou, Shuai Lu, Lei Ji, Shaoguang Mao, Yun Wang, Linjun Shou, Ming Gong, and Nan Duan. Taskmatrix.ai: Completing tasks by connecting foundation models with millions of apis. arXiv preprint arXiv:2303.16434, 2023. [24] Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. React: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629, 2022. [25] Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Luke Zettle- moyer, Nicola Cancedda, and Thomas Scialom. Toolformer: Language models can teach themselves to use tools. arXiv preprint arXiv:2302.04761, 2023. [26] Stanislaw Antol, Aishwarya Agrawal, Jiasen Lu, Margaret Mitchell, Dhruv Batra, C Lawrence In Proceedings of the IEEE Zitnick, and Devi Parikh. Vqa: Visual question answering. international conference on computer vision, pages 2425–2433, 2015. [27] Peter Anderson, Xiaodong He, Chris Buehler, Damien Teney, Mark Johnson, Stephen Gould, and Lei Zhang. Bottom-up and top-down attention for image captioning and visual question answering. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 6077–6086, 2018. [28] Jiasen Lu, Dhruv Batra, Devi Parikh, and Stefan Lee. Vilbert: Pretraining task-agnostic visiolinguistic representations for vision-and-language tasks. Advances in neural information processing systems, 32, 2019. [29] Hao Tan and Mohit Bansal. Lxmert: Learning cross-modality encoder representations from transformers. arXiv preprint arXiv:1908.07490, 2019. [30] Difei Gao, Ruiping Wang, Shiguang Shan, and Xilin Chen. Learning to recognize visual concepts for visual question answering with structural label space. IEEE Journal of Selected Topics in Signal Processing, 14(3):494–505, 2020. [31] Difei Gao, Ruiping Wang, Shiguang Shan, and Xilin Chen. Visual textbook network: Watch carefully before answering visual questions. In BMVC, 2017. 18 [32] Kenneth Marino, Mohammad Rastegari, Ali Farhadi, and Roozbeh Mottaghi. Ok-vqa: A visual question answering benchmark requiring external knowledge. In Proceedings of the IEEE/cvf conference on computer vision and pattern recognition, pages 3195–3204, 2019. [33] Dustin Schwenk, Apoorv Khandelwal, Christopher Clark, Kenneth Marino, and Roozbeh Mottaghi. A-okvqa: A benchmark for visual question answering using world knowledge. arXiv, 2022. [34] Peng Wang, Qi Wu, Chunhua Shen, Anthony Dick, and Anton Van Den Hengel. Fvqa: Fact-based visual question answering. IEEE transactions on pattern analysis and machine intelligence, 40(10):2413–2427, 2017. [35] Liangke Gui, Borui Wang, Qiuyuan Huang, Alex Hauptmann, Yonatan Bisk, and Jianfeng Gao. Kat: A knowledge augmented transformer for vision-and-language. arXiv preprint arXiv:2112.08614, 2021. [36] Kenneth Marino, Xinlei Chen, Devi Parikh, Abhinav Gupta, and Marcus Rohrbach. Krisp: Integrating implicit and symbolic knowledge for open-domain knowledge-based vqa. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 14111–14121, 2021. [37] Difei Gao, Ruiping Wang, Shiguang Shan, and Xilin Chen. Cric: A vqa dataset for compositional reasoning on vision and commonsense. IEEE Transactions on Pattern Analysis and Machine Intelligence, 2022. [38] Max Bain, Arsha Nagrani, Gül Varol, and Andrew Zisserman. Frozen in time: A joint video and image encoder for end-to-end retrieval. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 1728–1738, 2021. [39] Jie Lei, Linjie Li, Luowei Zhou, Zhe Gan, Tamara L. Berg, Mohit Bansal, and Jingjing Liu. Less is more: Clipbert for video-and-language learning via sparse sampling. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), pages 7331–7341, June 2021. [40] Yuxuan Wang, Difei Gao, Licheng Yu, Weixian Lei, Matt Feiszli, and Mike Zheng Shou. In Geb+: A benchmark for generic event boundary captioning, grounding and retrieval. Computer Vision–ECCV 2022: 17th European Conference, Tel Aviv, Israel, October 23–27, 2022, Proceedings, Part XXXV, pages 709–725. Springer, 2022. [41] Kristen Grauman, Andrew Westbury, Eugene Byrne, Zachary Chavis, Antonino Furnari, Rohit Girdhar, Jackson Hamburger, Hao Jiang, Miao Liu, Xingyu Liu, et al. Ego4d: Around the world in 3,000 hours of egocentric video. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 18995–19012, 2022. [42] Kevin Qinghong Lin, Jinpeng Wang, Mattia Soldan, Michael Wray, Rui Yan, Eric Z XU, Difei Gao, Rong-Cheng Tu, Wenzhe Zhao, Weijie Kong, et al. Egocentric video-language pretraining. Advances in Neural Information Processing Systems, 35:7575–7586, 2022. [43] Difei Gao, Ruiping Wang, Ziyi Bai, and Xilin Chen. Env-qa: A video question answering benchmark for comprehensive understanding of dynamic environments. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 1675–1685, 2021. [44] Zhijian Hou, Wanjun Zhong, Lei Ji, Difei Gao, Kun Yan, Wing-Kwong Chan, Chong-Wah Ngo, Zheng Shou, and Nan Duan. Cone: An efficient coarse-to-fine alignment framework for long video temporal grounding. arXiv preprint arXiv:2209.10918, 2022. [45] Benita Wong, Joya Chen, You Wu, Stan Weixian Lei, Dongxing Mao, Difei Gao, and Mike Zheng Shou. Assistq: Affordance-centric question-driven task completion for egocentric assistant. In European Conference on Computer Vision, pages 485–501. Springer, 2022. [46] Weixian Lei, Difei Gao, Yuxuan Wang, Dongxing Mao, Zihan Liang, Lingmin Ran, and Mike Zheng Shou. Assistsr: Task-oriented video segment retrieval for personal ai assistant. In Findings of the Association for Computational Linguistics: EMNLP 2022, pages 319–338, 2022. 19 [47] Joya Chen, Difei Gao, Kevin Qinghong Lin, and Mike Zheng Shou. Affordance grounding from demonstration video to target image. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 6799–6808, 2023. [48] Ronghang Hu, Amanpreet Singh, Trevor Darrell, and Marcus Rohrbach. Iterative answer prediction with pointer-augmented multimodal transformers for textvqa. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 9992–10002, 2020. [49] Zhengyuan Yang, Yijuan Lu, Jianfeng Wang, Xi Yin, Dinei Florencio, Lijuan Wang, Cha Zhang, Lei Zhang, and Jiebo Luo. Tap: Text-aware pre-training for text-vqa and text-caption. In Proceedings of the IEEE/CVF conference on computer vision and pattern recognition, pages 8751–8761, 2021. [50] Difei Gao, Ke Li, Ruiping Wang, Shiguang Shan, and Xilin Chen. Multi-modal graph neu- ral network for joint reasoning on vision and scene text. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), June 2020. [51] Stan Weixian Lei, Difei Gao, Jay Zhangjie Wu, Yuxuan Wang, Wei Liu, Mengmi Zhang, and Mike Zheng Shou. Symbolic replay: Scene graph as prompt for continual learning on vqa task. arXiv preprint arXiv:2208.12037, 2022. [52] OpenAI. Gpt-4 technical report, 2023. [53] Danny Driess, Fei Xia, Mehdi SM Sajjadi, Corey Lynch, Aakanksha Chowdhery, Brian Ichter, Ayzaan Wahid, Jonathan Tompson, Quan Vuong, Tianhe Yu, et al. Palm-e: An embodied multimodal language model. arXiv preprint arXiv:2303.03378, 2023. [54] Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi. Blip-2: Bootstrapping language- image pre-training with frozen image encoders and large language models. arXiv preprint arXiv:2301.12597, 2023. [55] Deyao Zhu, Jun Chen, Xiaoqian Shen, xiang Li, and Mohamed Elhoseiny. Minigpt-4: Enhancing vision-language understanding with advanced large language models, 2023. [56] 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. [57] Jacob Andreas, Marcus Rohrbach, Trevor Darrell, and Dan Klein. Neural module networks. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 39–48, 2016. [58] Ronghang Hu, Jacob Andreas, Marcus Rohrbach, Trevor Darrell, and Kate Saenko. Learning to reason: End-to-end module networks for visual question answering. In Proceedings of the IEEE international conference on computer vision, pages 804–813, 2017. [59] Justin Johnson, Bharath Hariharan, Laurens Van Der Maaten, Judy Hoffman, Li Fei-Fei, C Lawrence Zitnick, and Ross Girshick. Inferring and executing programs for visual reasoning. In Proceedings of the IEEE international conference on computer vision, pages 2989–2998, 2017. [60] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Ed Chi, Quoc Le, and Denny Zhou. Chain of thought prompting elicits reasoning in large language models. arXiv preprint arXiv:2201.11903, 2022. [61] Zhengyuan Yang, Linjie Li, Jianfeng Wang, Kevin Lin, Ehsan Azarnasab, Faisal Ahmed, Zicheng Liu, Ce Liu, Michael Zeng, and Lijuan Wang. Mm-react: Prompting chatgpt for multimodal reasoning and action. arXiv preprint arXiv:2303.11381, 2023. [62] Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alexander C Berg, Wan-Yen Lo, et al. Segment anything. arXiv preprint arXiv:2304.02643, 2023. 20 [63] Jiaqi Chen, Zeyu Yang, and Li Zhang. Semantic segment anything. https://github.com/ fudan-zvg/Semantic-Segment-Anything, 2023. [64] Shilong Liu, Zhaoyang Zeng, Tianhe Ren, Feng Li, Hao Zhang, Jie Yang, Chunyuan Li, Jianwei Yang, Hang Su, Jun Zhu, et al. Grounding dino: Marrying dino with grounded pre-training for open-set object detection. arXiv preprint arXiv:2303.05499, 2023. [65] Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, and Ilya Sutskever. Robust speech recognition via large-scale weak supervision. arXiv preprint arXiv:2212.04356, 2022. [66] Peng Wang, An Yang, Rui Men, Junyang Lin, Shuai Bai, Zhikang Li, Jianxin Ma, Chang Zhou, Jingren Zhou, and Hongxia Yang. Ofa: Unifying architectures, tasks, and modalities through a simple sequence-to-sequence learning framework. CoRR, abs/2202.03052, 2022. [67] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual models from natural language supervision. In International Conference on Machine Learning, pages 8748–8763. PMLR, 2021. [68] Junbin Xiao, Xindi Shang, Angela Yao, and Tat-Seng Chua. Next-qa: Next phase of question- answering to explaining temporal actions. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 9777–9786, 2021. [69] Amita Kamath, Christopher Clark, Tanmay Gupta, Eric Kolve, Derek Hoiem, and Aniruddha In Kembhavi. Webly supervised concept expansion for general purpose vision models. Computer Vision–ECCV 2022: 17th European Conference, Tel Aviv, Israel, October 23–27, 2022, Proceedings, Part XXXVI, pages 662–681. Springer, 2022. [70] Yushi Hu, Hang Hua, Zhengyuan Yang, Weijia Shi, Noah A Smith, and Jiebo Luo. Promptcap: Prompt-guided task-aware image captioning. arXiv preprint arXiv:2211.09699, 2022. [71] Antoine Yang, Antoine Miech, Josef Sivic, Ivan Laptev, and Cordelia Schmid. Just ask: Learning to answer questions from millions of narrated videos. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 1686–1697, 2021. [72] Shyamal Buch, Cristóbal Eyzaguirre, Adrien Gaidon, Jiajun Wu, Li Fei-Fei, and Juan Carlos In Proceedings of the Niebles. Revisiting the" video" in video-language understanding. IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 2917–2927, 2022. [73] Junbin Xiao, Pan Zhou, Tat-Seng Chua, and Shuicheng Yan. Video graph transformer for video question answering. In European Conference on Computer Vision, pages 39–58. Springer, 2022. [74] Difei Gao, Luowei Zhou, Lei Ji, Linchao Zhu, Yi Yang, and Mike Zheng Shou. Mist: Multi- modal iterative spatial-temporal transformer for long-form video question answering. arXiv preprint arXiv:2212.09522, 2022. [75] Reiichiro Nakano, Jacob Hilton, Suchir Balaji, Jeff Wu, Long Ouyang, Christina Kim, Christo- pher Hesse, Shantanu Jain, Vineet Kosaraju, William Saunders, et al. Webgpt: Browser-assisted question-answering with human feedback. arXiv preprint arXiv:2112.09332, 2021. 21
Title: Don't Trust ChatGPT when Your Question is not in English: A Study of Multilingual Abilities and Types of LLMs: Summary: Large Language Models (LLMs) have demonstrated exceptional natural language understanding abilities and have excelled in a variety of natural language processing (NLP)tasks in recent years. Despite the fact that most LLMs are trained predominantly in English, multiple studies have demonstrated their comparative performance in many other languages. However, fundamental questions persist regarding how LLMs acquire their multi-lingual abilities and how performance varies across different languages. These inquiries are crucial for the study of LLMs since users and researchers often come from diverse language backgrounds, potentially influencing their utilization and interpretation of LLMs' results. In this work, we propose a systematic way of qualifying the performance disparities of LLMs under multilingual settings. We investigate the phenomenon of across-language generalizations in LLMs, wherein insufficient multi-lingual training data leads to advanced multi-lingual capabilities. To accomplish this, we employ a novel back-translation-based prompting method. The results show that GPT exhibits highly translating-like behaviour in multilingual settings. # Don’t Trust ChatGPT when your Question is not in English: A Study of Multilingual Abilities and Types of LLMs Xiang Zhang∗ Senyu Li∗ Bradley Hauer Ning Shi Grzegorz Kondrak Alberta Machine Intelligence Institute Department of Computing Science University of Alberta, Edmonton, Canada {xzhang23,senyu,bmhauer,ning.shi,gkondrak}@ualberta.ca # Abstract Large language models (LLMs) have demon- strated exceptional natural language under- standing abilities, and have excelled in a vari- ety of natural language processing (NLP) tasks. Despite the fact that most LLMs are trained pre- dominantly on English, multiple studies have demonstrated their capabilities in a variety of languages. However, fundamental questions persist regarding how LLMs acquire their mul- tilingual abilities and how performance varies across different languages. These inquiries are crucial for the study of LLMs since users and researchers often come from diverse language backgrounds, potentially influencing how they use LLMs and interpret their output. In this work, we propose a systematic way of qualita- tively and quantitatively evaluating the multilin- gual capabilities of LLMs. We investigate the phenomenon of cross-language generalization in LLMs, wherein limited multilingual training data leads to advanced multilingual capabilities. To accomplish this, we employ a novel prompt back-translation method. The results demon- strate that LLMs, such as GPT, can effectively transfer learned knowledge across different lan- guages, yielding relatively consistent results in translation-equivariant tasks, in which the cor- rect output does not depend on the language of the input. However, LLMs struggle to pro- vide accurate results in translation-variant tasks, which lack this property, requiring careful user judgment to evaluate the answers. # Introduction Type (a) Compound (b) Coordinate || (c) Subordinate Internal Concept couteau couteau couteau Fr Lexicon Figure 1: The three types of bilingualism. (LLMs), researchers have discovered many emer- gent properties (Wei et al., 2022a) in these models, and have used them for a variety of purposes (Wei et al., 2022b). However, the multilingual ability of these models has not been extensively studied. Previous research has shown that large language models, such as GPT, are capable of performing a wide variety of language tasks when the task is presented in English (Qin et al., 2023). However, investigations into the multilingual language abil- ities of these models have been limited. Shi et al. (2023) explore this topic by applying the models to multilingual datasets, and measuring performance differences across languages. However, they do not explore the underlying mechanisms of how LLMs perform different tasks, nor how this affects the results. Moreover, most LLMs (Brown et al., 2020; Touvron et al., 2023) are trained on datasets that are heavily skewed towards English, which leaves open the question of how multilingual abilities in such models are acquired. The study of bilingualism has long been a topic of interest among linguists (Yu et al., 2022; Hoffmann, 2014), as it provides insight into the mechanisms of language acquisition and processing. Furthermore, research on multilingualism has contributed to the development of more effective machine learning models, such as neural translation systems (Zou et al., 2013). With the rise of large language models In this study, we present a systematic approach to analyzing the multilingual capabilities of LLMs. To facilitate a comprehensive analysis, we pro- pose categorizing language-dependent abilities into three distinct categories which vary in the impact of language choice on the performance: Reasoning (least impact), Knowledge Access, and Articulation (most impact). We investigate a carefully selected set of tasks from these three categories by evalu- ∗∗Equal contribution. ating the multilingual abilities of an LLM using a novel prompting method which we call response back-translation (RBT). By comparing the gener- ated answers, we can both measure multilingual performance of the LLM, but also determine the type of multilinguality they exhibit. For example, we examine the capabilities of LLMs on pun detec- tion, a highly language-dependent task. The results of our experiments show that the pop- ular LLM “GPT”: (1) achieves higher performance when the task is presented in English; (2) achieves higher performance on tasks that can be translated without altering the correct output; and (3) exhibits a mixture of coordinate and subordinate bilingual- ism. Our main contributions1 are: • We present a first-of-its-kind quantitative and qualitative analysis of the multilingual abili- ties of LLMs. • We propose two novel task categorizations to facilitate the multilingual ability analysis. • Our work is the first to investigate LLMs with respect to a linguistic typology of bilingualism and multilingualism. # 2 Background Linguists categorize bilingual individuals into three groups: compound, coordinate, and subordinate bilinguals (D’Acierno, 1990). Figure 1 illus- trates this categorization, showing how individuals with different types of English-French bilingualism might internally represent the concept of “knife”. Compound bilingualism mostly emerges among individuals who learn two languages simultane- ously from birth. In this case, both languages are equally dominant and integrated, blurring any clear distinction between them and giving the impres- sion of a single unified language (Moradi, 2014). Compound bilingualism entails a shared mental representation of lexicons across both languages they acquire, and compound bilinguals are the most flexible in their use of multiple languages, exhibit- ing the ability to switch between languages without losing consistency in linguistic tasks (De Groot and Nas, 1991). In contrast, individuals exhibiting coordinate bilingualism maintain separate mental represen- tations for the lexicon of each language they 1Our data is publicly available at GitHub. learn. This separation leads to differences when tasks are performed under different language set- tings (Jakobovits, 1968). Finally, subordinate bilingualism is character- ized by a “translator” behaviour (Marcos, 1976). This type of bilingualism is characterized by a sin- gle lexicon representation that is linked to their dominant language (Lörscher, 2012). When per- forming tasks in languages other than their dom- inant one, subordinate bilinguals tend to rely on translating the task into their dominant language, formulating an answer in the dominant language, and then translating that answer back into the lan- guage of the task. As a result, subordinate bilin- guals may experience lower proficiency in com- municating and completing tasks in the second, subordinate language. Despite the demonstration in prior work of con- sistent multilingual performance in many large lan- guage models (Shi et al., 2023), it remains unclear how the multilingualism of LLMs should be cate- gorized. It is an open question whether the LLMs exhibit a representation of knowledge shared across both languages (compound), separate representa- tions for each language (coordinate), or whether they rely on a translation processes (subordinate). We develop an experimental framework aimed at using performance on various natural language pro- cessing tasks to determine how the multilingual abilities of LLMs relate to these categories. # 3 Categorizing Language-Dependent Tasks Language ability is a multifaceted concept en- compassing various tasks and aspects (Wei et al., 2022a). It is therefore difficult to assess a model’s capabilities with respect to a given language. To facilitate such assessment, researchers have often classified tasks into distinct categories (Khurana et al., 2023), such as parsing and summarization. However, the delineation of such categories often lacks systematic criteria, particularly in the context of multilingual analysis. In this section, we propose a novel approach to categorizing NLP tasks, which is better suited to analysis of multilingual abilities. The categoriza- tion is two dimensional: one dimension is based on the linguistic knowledge necessary to complete the task (Section 3.1), the other on how the task is impacted by the language in which it is presented (Section 3.2). Reasoning Knowledge Access Articulation What is the answer of 12 = 83? Explain what is a "finite state machine". (Can you write me a cover letter yr Prompt ? Response ———> 42h Prompt rot —> Se Response for SDE position? lam writing to express my keen interest in the position RAAT SST SDE BRZASRER (a5? RSE SRARMRASZ 1293S FSD? PRT AR ARKH. BR TAURI Figure 2: Three categories of NLP tasks. # 3.1 Categorization by Task Properties We classify NLP tasks into three distinct categories: Reasoning, Knowledge Access, and Articulation. This division is based on the extent to which per- formance on each task is influenced by the model’s capabilities with the language used. Figure 2 pro- vides an overview of this categorization. Reasoning The first category includes tasks that are minimally influenced by language, on which consistent performance is expected across lan- guages. Reasoning tasks involve logical and ra- tional thinking to solve problems based on avail- able information and logical principles. Examples include mathematical problem-solving (Lu et al., 2023), coding (Li et al., 2023), and common sense reasoning (Sap et al., 2020). These tasks can be performed using universal language elements, such as mathematical symbols, or rely on general life experience and common sense, which can be ac- quired without language. For example, answering the question “If I drop an apple, which direction will it go?” relies more on understanding gravity than on language-specific knowledge. Knowledge Access LLMs have the capability to function as knowledge bases (KBs) by storing knowledge extracted from training data (Heinzer- ling and Inui, 2021). Knowledge Access tasks de- pend on the ability to access this knowledge and formulate accurate responses based on it. While the underlying knowledge may not be language de- pendent, models may be less reliable in retrieving and utilizing knowledge learned in a language other than the one used to formulate the task. Examples of Knowledge Access tasks include factual knowl- edge checking (De Cao et al., 2021), knowledge- focused question answering (Wang, 2022), and named entity recognition (Malmasi et al., 2022). Articulation Much of everyday human conver- sation is highly language-dependent, as it involves the pragmatics and cultural nuances of the spo- ken language. For instance, writing a cover letter in English significantly differs from writing one in Japanese, due to the distinct social norms and conventions associated with those languages. The Articulation category includes tasks that are heavily influenced by the language choice, such as summa- rization (Nenkova and McKeown, 2012), dialogue generation (Ni et al., 2023), paraphrasing (Zhou and Bhat, 2021), and style writing (Jin et al., 2022). These tasks require an extensive understanding of not only language, but the associated culture, as they involve capturing and reproducing the appro- priate style, tone, and manner of expression specific to a given language. # 3.2 Categorization by Translatability The second dimension of our task classification scheme involves translatability. We introduce the concepts of Translation Equivariant (TE) and Trans- lation Variant (TV) tasks. A function is considered equivariant if it com- mutes with a symmetry transformation. That is, applying a transformation before or after comput- ing the function yields the same result. Formally , f (·) is said to be equivariant under g(·) if: ∀x ∈ D, g(f (x)) = f (g(x)) (1) where D represents the domain of both f and g. We denote translation as a transformation g that converts a given text in language A to an equiva- lent text in language B. In practice, g can be im- plemented by a machine translation system. We further use f to denote a function which solves a given task, given an instance of that task as in- put. A task is considered Translation Equivariant between languages A and B if the correct output can be obtained by translating the input, and then applying a method for solving the task, or by solv- ing the task, and then translating the output; in other words, if g(f (x)) = f (g(x)). Most of the tasks in the Reasoning and Knowledge Access cate- gories are regarded as Translation Equivariant since the correct output does not depend on the chosen language. Figure 3 shows an example where the answer to the question posed in English remains the same in Chinese, regardless of in which order the translation system and the question answering system are applied. A task which is not Translation Equivariant is Translation Variant. For such tasks, translating the input may change the correct output. TV tasks rely heavily on the language used, and include many tasks in the Articulation category. Representative TV tasks that we investigate in our experiments are letter writing and pun understanding. The former is subject to the conventions of the specific lan- guage and culture, while the latter involves word polysemy, which is often sensitive to translation. Figure 3 shows an example where a pun is present in the original English input, but not in the Span- ish translation, making the classification dependent upon the order in which translation is applied. # 4 Methods In this section, we present our approach to analyz- ing the multilingual ability of LLMs. Our methods involve prompt translation (PT) and response back- translation (RBT). They are designed to measure performance of an LLM, and its consistency across In our experiments, we apply these languages. methods to both TE and TV tasks, with the aim of determining the type of bilingualism (compound, coordinate, or subordinate) exhibited by an LLM. # 4.1 Prompt Translation Multilingual datasets are unvailable for many tasks. However, with state-of-the-art machine translation (MT) systems and LLMs, we can translate monolin- gual datasets for TE tasks to generate parallel mul- tilingual parallel data with minimal loss of infor- mation (Whitehouse et al., 2023; Shi et al., 2023). This is the key intuition behind prompt transla- tion (PT); an example is shown in Figure 4a, where an English multiple choice question, and its possi- ble answers, are translated to Chinese. The LLM is then prompted, and the response is given and eval- uated, in Chinese. Prompting in distinct languages is performed in independent LLM sessions. We measure the differences in multilingual task performance by comparing the answers given by the LLM in each language. Assuming that the LLM Translation Equivariant (TE) 1 |Una bicicleta no puede sostenerse por si sola ya que tiene dos llantas. g 1 |Abicycle can’t stand on its own 1 |since it's two-tired. Figure 3: A TE task (common sense reasoning) and a TV task (pun detection). Translation is denoted by g, and f is the solver function. successfully learns to solve a TE task in a language- independent way, the pairwise responses for each instance should be the same after the translation (re- gardless of whether it is correct or incorrect). This is because TE tasks, such as mathematical problem solving, do not depend on the language used to query the LLMs, as the solution does not depend on the language used to express the problem. # 4.2 Response Back-Translation One of the goals of our work is to understand what the consistency of LLM output across languages tells us about the model, and to determine the type of bilingualism an LLM exhibits. This is crucial for individuals who use LLMs for multilingual tasks, as it can impact the way task results are gener- ated, and affect the quality and consistency of the results. For example, a network exhibiting sub- ordinate bilingualism would produce output that appears to be the result of translation, rather than resembling text generated by a native speaker of the output language. To quantitatively measure how reasoning is per- formed, we propose a prompting method based on back-translation, as illustrated in Figure 4b. Simi- lar to prompt translation (Section 4.1), we begin by translating the instance to the target language, and prompting the LLM to produce a response in that language. After obtaining output from the LLM, regardless of the language, we further prompt the LLM to generate an explanation for its output (e.g., “Explain how you obtain this result”); and then trans- late the output of the LLM back to the original language. We then compare the explanation given En Prompt in One New Session (a) Prompt Translation (PT) Zh Prompt in One New Session y [Q: Where might you find a chair at an office? (Options: (A) stadium (B) kitchen (C) porch (D) cubicle (E) living room Translation Q: EDS ME aS? os ia: (A) PAP (B) EIS (C) (THB (0) HRI (E) BT. G* (0). XR Pairwise Comparison o. |G@ En Prompt in Same Session (b) Response Back-Translation (RBT) Zh Prompt in Same Session Translation Qui Can you explain why you chose this answer? >[0: ERA Fe SRS? os 'A: Because a cubicle is a small workspace that is typically found in an office setting. In such an aM A, LRT EARS, TERR ARLE, Blt, DART DORTTNTEL, EMDR, Bima G LSE MEREASEAL (FESS, lenvironment, people often have desks and chairs to work at, and these chairs are usually designed to be comfortable for long periods of sitting. (Q: JE¢RAUREAREDEARIES, (Q: Translate your answer into English.) oe ‘Therefore, it's most likely that you would find a (chair at an office in a cubicle where people sit land work on their computers or other tasks. lA: Because offices usually have cubicles or office partitions where employees work. Therefore, office chairs are Iypically located in these cubicles or offices for employees to sit and work comfortably. Chairs in these cubicles Sy [Pairwise ‘Comparison Nw lor offices are usually paired with office desks to provide a comfortable working environment for employees. Figure 4: An overview of our prompt translation and response back-translation methods. in the source language to the explanation back- translated from the target language. If the LLM is performing translation-based rea- soning, the reasoning process is conducted in one language and then translated into another. Since the internal reasoning of the LLM can be partially observed through the output explanation, back- translating such explanations into the source lan- guage allows us to compare the internal reasoning used to solve the problem in each language. High similarity of explanations should indicate homo- geneity in using the same internal reasoning pro- cess to perform the task in both languages. On the other hand, dissimilarity in the reasoning process across languages should be reflected in a lower explanation similarity. TE Task Vv Prompt Translation Same results No across all languages? Response Back-Translation TV Task | No Same reasoning T across all languages? Prompt Translation Compound Compound Yes Results change after translation? ~~ | Subordinate Coordinate | # Identifying Multilingual Types Figure 5: Flowchart for detecting multilingual types. In our investigation, we employ both Prompt Trans- lation (PT) and Response Back-Translation (RBT) to analyze how an LLM solves TE and TV tasks in different languages. As depicted in the first two steps in Figure 5, a compound LLM should exhibit consistent results on TE tasks with both methods. This is because a compound model performance does not depend on the language in which a ques- tion is presented. Conversely, subordinate and coor- dinate types of networks are expected to yield some- what different results on TE tasks. A coordinate model accesses distinct representations in different languages, which may result in different reasoning and answers. Finally, a subordinate model heavily depends on an internal translation process, which we expect to lead to some deterioration of output quality across languages. is expected to reason differently for each language, which may yield different outputs, whether correct or not. In contrast, a pure subordinate model is expected to reason only in the dominant language, producing relatively similar results in different lan- guages, regardless of whether the correct output is preserved after translation. # 5 Experiments We apply the methodology proposed in Section 4 to TE and TV tasks. As our LLM, we use Chat- GPT, via the official web application2, due to its availability. # 5.1 Datasets Testing on TV tasks provide additional informa- tion, which can be used to distinguish between coor- dinate and subordinate models. A coordinate LLM Reasoning We use 50 instances selected at ran- dom from each of two datasets: GSM8K (Cobbe 2https://chat.openai.com/ et al., 2021), which contains 7,500 training and 1,000 test problems, and CommonsenseQA (Tal- mor et al., 2019), which contains 12,247 questions. We used ChatGPT to translate these instances into French, Spanish, German, Japanese, and Chinese. GSM8K is a dataset of grade-school math prob- lems. Each problem consists of a question and a multiple-choice answer. CommonsenseQA is a question answering dataset for testing logic and common sense. Each instance consists of a ques- tion and five answer choices, only one of which is considered correct. Knowledge Access WebQuestions is a dataset of 6,642 question-answer pairs extracted from Free- base (Bordes et al., 2014). An example question is “Where is the Thames River located?” to which the correct answer is London. To simplify the evalua- tion, and avoid the issue of extracting answers from ChatGPT’s often verbose responses, we manually converted 50 randomly selected instances into the multiple-choice format used by CommonsenseQA. To create plausible incorrect answers (distractors), we randomly selected four incorrect candidate an- swers from sets of world city names3 and celebrity names4 (correct answers in this dataset are all ei- ther city names or celebrity names). This yielded a set of 50 multiple choice questions with five pos- sible answers each (one correct, four incorrect). We translated the English instances into five other languages via ChatGPT. Puns We randomly selected 80 positive and 80 negative instances each from the English, French, and Spanish instances in the JOKER@CLEF 2022 dataset (Ermakova et al., 2022). Each instance is annotated with a yes/no classification as to whether it contains a pun, and the pun location, if a pun is present. An example English instance is “As- tronauts work in a nice atmosphere” for which the pun location is the word atmosphere. We used ChatGPT to translate the French and Spanish in- stances into English, and the English instances into French, Spanish, German, Japanese, and Chinese. This yields 10 balanced sets of 160 instances each (three original and seven translated). Articulation To test the Articulation abilities of an LLM, we prompt the model to generate a cover letter for a job application, with randomized spec- ifications. For each prompt, we first generate the 3https://simplemaps.com/data/world-cities 4https://github.com/janester/mad_libs Task En Fr De Es Ja Zh 0.90 MR CSR 0.68 0.96 KA 0.80 0.58 0.96 0.78 0.52 0.94 0.80 0.54 0.94 0.82 0.48 0.80 0.78 0.52 0.68 Table 1: Accuracy for TE tasks: math reasoning (MR), commonsense reasoning (CSR), and knowledge access (KA). name and background of an individual, including information such as level of education, specialties, and hobbies. We then randomly select one well- known company to which cover letter is to be ad- dressed. Finally, we select a set of topics such as “What skills would you want to develop in this role?”. Each of these randomized prompts is then provided to the LLM. The output is then manually evaluated by a native speaker of the language of the prompt. We generate 50 prompts each in English and Chinese. An example is provided in Table 5 in the appendix. # 5.2 Metrics Since ChatGPT can give different answers to the same question, we present each multiple-choice question to ChatGPT five times, and use the most frequent output for evaluation. For comput- ing similarity between explanations, we use ap- pendix(Devlin et al., 2019). Specifically, we trans- late all non-English output to English via ChatGPT, and compute the cosine similarity of the BERT embeddings of the two explanations. # 5.3 Results on TE Tasks As shown in Table 1, the results on TE tasks in En- glish are on average much higher in English than in other languages. In math reasoning (MR), the least language-dependent task, the gap between English and other languages is over 10% on average. In common sense reasoning (CSR), the difference is over 15% on average. In knowledge access (KA), there is no substantial difference between English and other European languages, but accuracy on Japanese and Chinese is 16% and 28% lower, re- spectively. To confirm that the accuracy gap is not due to instance translation quality, we manu- ally compared all 50 Chinese MR questions with their original English counterparts, and found no translation errors. Taken together, these results provide strong evidence that GPT is better able to reason and retrieve knowledge given an English prompt, compared to prompting in other languages. In terms of multilinguality type, the evidence is against compound multilingualism in GPT (cf., Fig- ure 5), as a compound model would be expected to exhibit no substantial difference in performance across languages. We also analyzed the BERT similarity values between explanations in different languages (cf., Table 4 in the Appendix). In commonsense reason- ing, which relies on logic and conceptual distinc- tions, we observe that the average BERT similar- ity of German, Spanish, Japanese and Chinese to French is substantially lower than the correspond- ing average similarity to English (0.849 vs. 0.868), while French itself is substantially more similar to English than to German (0.871 vs 0.857). We interpret this as additional evidence of the GPT’s dependence on its strong English model. On the other hand, we observe no such trend in knowledge access questions. We hypothesize that since these problems are mostly about named en- tities, they tend to be more language-independent. Indeed, we observe higher performance on French, German, and Spanish, which use the Latin script, and therefore can represent named entities as En- glish does, compared to Japanese and Chinese, which use different orthographies. # 5.4 Cover Letters Cover letter writing is an example of a TV articula- tion task. We found that cover letters generated by ChatGPT with the same set of instructions in dif- ferent languages exhibit relatively high BERT simi- larity to their English versions, ranging from 0.818 Japanese to 0.865 for German. To provide some comparison, we also computed pairwise BERT sim- ilarities between English cover letters generated with the same prompts by ChatGPT and two other LLMs, Claude and Instant-Claude, which yielded the values of 0.618 and 0.643, respectively. This indicates that the letters generated in different lan- guages by ChatGPT are more similar to each other than the letters in English generated by different LLMs. Cover letters generated in languages other than English exhibit a written style which is closer to English than to the target language. For exam- ple, consider the cover letter shown in Table 5 in the Appendix. The expressions 阁下 “from what I have gathered” and 狂热的户外运动爱好者 “avid outdoor enthusiast” are very unnatural in Chinese, Chinese English Translation Frequency 诚挚地 致意 祝愿 此致敬礼 Salute (Proper Chinese Sign-off) Sincerely Regards Best Wishes 54.0% 38.4% 3.6% 0.8% No sign-off 3.2% Table 2: The frequency of different sign-offs in 250 different Chinese cover letters generated by ChatGPT. Language P-Acc L-Acc Es Es-En 0.488 0.507 0.697 0.714 Fr Fr-En 0.500 0.513 0.886 0.813 En En-Fr En-De En-Es En-Ja En-Zh 0.506 0.500 0.519 0.488 0.519 0.550 0.965 0.646 - 0.607 - 0.511 Table 3: Accuracy on pun detection (P-Acc) and loca- tion (L-Acc). X-Y means the puns were translated from language X to language Y before prompting. and appear characteristic of literal translations from English. The sign-off phrase 真诚的 “Sincerely” is similarly inappropriate in formal Chinese, although it is usual in English. Table 2 shows that less than 1% of the letters have a proper Chinese sign off. # 5.5 Results on Puns Table 3 shows the results on the translation-variant tasks of pun detection and location. The accuracy of pun detection is close to what we would ex- pect from a random baseline, as ChatGPT strongly favors positive pun classifications. The sole ex- ception is a slightly higher accuracy of 0.55 when English puns are translated into Chinese, due to a higher proportion of negative classifications. Since few conclusions can be drawn from the pun detection results, we conducted an evalua- tion of the pun location results in most datasets, which required manual extraction of the location information from ChatGPT’s explanations. The results are shown in Table 3. The pun location ac- curacy on the original English puns is very high at 96.5%, but drops dramatically when the sentences are translated into other languages. When French puns are translated to English, there is likewise a drop in performance, though it is much smaller than what is observed when English puns are trans- lated to French. However, the situation is different for Spanish puns, where the location accuracy in- creases slightly after the puns are translated into En- glish. This is surprising, as puns are often language- specific, and tend to disappear after translation. When the prompt is not in English, evidence suggests that ChatGPT relies, at least partly, on its English capabilities for semantic interpretation. Consider the homonymous English word bat which has two unrelated senses, translated by different words in Chinese: 蝙蝠 for the “animal” sense, and 球拍 for the “club” sense (Hauer and Kondrak, 2020). When the original English prompt is “What is the famous bat brand for baseball?”, ChatGPT appears unable to distinguish between these two translations of bat within a Chinese prompt. Al- though the choice of the Chinese translation of bat greatly affects the meaning of the question, it does not seem to impact ChatGPT’s response. How- ever, when we replace 蝙蝠 “animal bat” with 老虎 “tiger”, ChatGPT correctly responds that the ques- tion makes no sense. We interpret the inability of ChatGPT to differentiate between the two distinct Chinese translations of bat as strong evidence of subordinate bilingualism. # 5.6 Analysis of Results The results of our experiments provide evidence that GPT exhibits a substantial degree of subordi- nate multilingualism. Many of its responses are what we would expect from a system which trans- lates all input into English, formulates a response in English, and then translates this response into the input language. Since translation is an error- prone process, the resulting response accuracy is frequently lower than when the input is provided in English. We speculate that this behavior is an artifact of GPT being trained mostly on monolingual English texts. Consequently, GPT has developed a repre- sentation of knowledge and communication that is strongly biased towards English. We conclude that since GPT is not designed to take advantage of bilingual or multilingual corpora, it is unable to cre- ate a single multilingual conceptual representation analogous to compound multilingualism. Moreover, GPT has less training data for non- English languages, compared to its English training data. We postulate that this results in represen- tations for non-English languages that are much weaker than those GPT can create for English. This often leads to lower performance on even translation-equivariant tasks when the task is not presented in English. # 6 Discussion and Future Directions Our research provides robust support for the notion that LLMs have not achieved the ideal behaviour of compound multilingualism. Even if the quality and quantity of training data in various languages were held constant, we speculate that compound multilingualism would still not be achieved, due to the inherent limitations of current data collection methods and training techniques. Drawing a parallel to human multi-modal learn- ing offers an intuitive understanding of why this could be the case. Consider how humans acquire concepts related to vision and language: A child grows by consistently pairing visual stimuli with linguistic cues, intertwining the two modalities over time. Consequently, it is rare to observe a mis- match between visual and linguistic perceptions. In this context, humans exhibit a highly integrated understanding of vision and their native languages. However, unless raised in a perfectly bilingual envi- ronment, individuals seldom showcase equivalent proficiency in two languages. Indeed, bilingual individuals often demonstrate cognitive variations depending on which language is in use. A rudimentary multi-modal system can be likened to a crude fusion of a vision model trained on image data and a language model trained on text. These systems possess minimal, if any, shared representations or information overlap. Beneath the facade of a system that seemingly excels at both visual and language tasks, lie two distinct networks. Nevertheless, recent advancements in multi-modal studies, combined with the availabil- ity of extensively captioned image data, have given rise to more sophisticated systems. These systems bridge the gap between the two modalities, moving the field closer to human-like integration. Acquiring aligned multilingual data is a signif- icant challenge, with the exception of some trans- lation datasets. The majority of online articles and posts are monolingual and cannot be easily paired. Therefore, training on these multilingual corpora results in models that essentially act as an amal- gamation of several independent language-specific models, with minimal information interchange, pri- marily anchored by the translation datasets which comprise a relatively small portion of the corpus. When corpora are disproportionately comprised of some language or set of languages, the models tend to become predominantly subordinate, with minimal coordination arising from monolingual datasets. Moving forward, our objective is to narrow the divide between languages within a multilingual sys- tem and to cultivate language models that lean more towards a compound archetype. This will require both crafting highly parallel paired data across lan- guages and innovating training methodologies that promote the learning of compound representations for universal concepts irrespective of the language used to express them. For the former, we intend to delve into ontology linkages. For the latter, we plan to leverage recent advancements in model training, such as contrastive learning. Our goal is to cre- ate multilingual models that are both technically sophisticated and universally adept. # 7 Conclusion We have proposed a systematic approach to analyz- ing multilingual abilities of large language models. Our experiments provide new evidence for a sub- ordinate multilingualism in GPT-3.5, with English functioning as the model’s native language. Our experimental results, supplemented by the analysis of specific examples and case studies, demonstrate that such subordinate multilingualism can limit per- formance even in language-independent tasks. We postulate that explicit inclusion of additional mul- tilingual parallel corpora and multimodal datasets into the training data of LLMs could ameliorate this issue. # Limitations As the OpenAI ChatGPT website application has a limited number of prompts allowed per day and per hour, we can not apply our experiment to the whole dataset. We used GPT3.5 rather than GPT4 as our LLM since access to GPT4 is still restricted. We conducted the human evaluation only in English, Spanish, and Chinese, as we did not have access to fluent speakers of the other languages found in our test sets. In addition to ChatGPT, we also attempted to ap- ply a different LLM, Llama2 to the same tasks (Tou- vron et al., 2023). The outcomes from Llama2, however, were unexpected for several reasons. Firstly, Llama2 frequently produced responses that lacked meaningful content, making answer extrac- tion challenging. Secondly, Llama2 often declined to provide answers to posed questions (cf. Table 7 in the Appendix). Thirdly, when posed with ques- tions in languages other than English, Llama2 usu- ally responded in English. Lastly, inherent issues in the datasets, such as inconsistent capitalization and grammatical errors, further complicated the evaluation. # Acknowledgements This research was supported by the Natural Sci- ences and Engineering Research Council of Canada (NSERC), and the Alberta Machine Intelligence In- stitute (Amii). # References Antoine Bordes, Sumit Chopra, and Jason Weston. 2014. Question answering with subgraph embeddings. In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 615–620, Doha, Qatar. Association for Com- putational Linguistics. 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, Ma- teusz Litwin, Scott Gray, Benjamin Chess, Jack Clark, Christopher Berner, Sam McCandlish, Alec Radford, Ilya Sutskever, and Dario Amodei. 2020. In Ad- Language models are few-shot learners. vances in Neural Information Processing Systems, volume 33, pages 1877–1901. Curran Associates, Inc. Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian, Jacob Hilton, Reiichiro Nakano, Christopher Hesse, and John Schulman. 2021. Training verifiers to solve math word problems. CoRR. Maria Rosaria D’Acierno. 1990. Three types of bilin- gualism. ERIC. Nicola De Cao, Wilker Aziz, and Ivan Titov. 2021. Edit- ing factual knowledge in language models. In Pro- ceedings of the 2021 Conference on Empirical Meth- ods in Natural Language Processing, pages 6491– 6506, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. Annette MB De Groot and Gerard LJ Nas. 1991. Lex- ical representation of cognates and noncognates in compound bilinguals. Journal of memory and lan- guage, 30(1):90–123. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. BERT: Pre-training of deep bidirectional transformers for language under- standing. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Tech- nologies, Volume 1 (Long and Short Papers), pages 4171–4186. Liana Ermakova, Tristan Miller, Fabio Regattin, Anne- Gwenn Bosser, Claudine Borg, Élise Mathurin, Gaëlle Le Corre, Sílvia Araújo, Radia Hannachi, Julien Boccou, Albin Digue, Aurianne Damoy, and Benoît Jeanjean. 2022. Overview of joker@clef 2022: Automatic wordplay and humour translation workshop. In Experimental IR Meets Multilinguality, Multimodality, and Interaction, pages 447–469. Bradley Hauer and Grzegorz Kondrak. 2020. One In Proceedings of the homonym per translation. AAAI Conference on Artificial Intelligence, vol- ume 34, pages 7895–7902. Benjamin Heinzerling and Kentaro Inui. 2021. Lan- guage models as knowledge bases: On entity repre- sentations, storage capacity, and paraphrased queries. In Proceedings of the 16th Conference of the Euro- pean Chapter of the Association for Computational Linguistics: Main Volume, pages 1772–1791, Online. Association for Computational Linguistics. Charlotte Hoffmann. 2014. Introduction to bilingualism. Routledge. Leon A Jakobovits. 1968. Dimensionality of compound- coordinate bilingualism. Language learning. Di Jin, Zhijing Jin, Zhiting Hu, Olga Vechtomova, and Rada Mihalcea. 2022. Deep learning for text style transfer: A survey. Computational Linguistics, 48(1):155–205. Diksha Khurana, Aditya Koli, Kiran Khatter, and Sukhdev Singh. 2023. Natural language processing: state of the art, current trends and challenges. Multi- media Tools and Applications, 82(3):3713–3744. Jia Li, Ge Li, Yongmin Li, and Zhi Jin. 2023. En- abling programming thinking in large language arXiv preprint models toward code generation. arXiv:2305.06599. Wolfgang Lörscher. 2012. Bilingualism and translation competence. SYNAPS - A Journal of Professional Communication. Pan Lu, Liang Qiu, Wenhao Yu, Sean Welleck, and Kai-Wei Chang. 2023. A survey of deep learning for mathematical reasoning. In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 14605– 14631, Toronto, Canada. Association for Computa- tional Linguistics. Shervin Malmasi, Anjie Fang, Besnik Fetahu, Sudipta Kar, and Oleg Rokhlenko. 2022. MultiCoNER: A large-scale multilingual dataset for complex named entity recognition. In Proceedings of the 29th Inter- national Conference on Computational Linguistics, pages 3798–3809, Gyeongju, Republic of Korea. In- ternational Committee on Computational Linguistics. Luis R Marcos. 1976. Linguistic dimensions in the bilin- gual patient. American Journal of Psychoanalysis, 36(4):347. Hamzeh Moradi. 2014. An investigation through dif- Inter- ferent types of bilinguals and bilingualism. national Journal of Humanities & Social Science Studies, 1(2):147–154. Ani Nenkova and Kathleen McKeown. 2012. A survey of text summarization techniques. Mining text data, pages 43–76. Jinjie Ni, Tom Young, Vlad Pandelea, Fuzhao Xue, and Erik Cambria. 2023. Recent advances in deep learn- ing based dialogue systems: A systematic survey. Artificial intelligence review, 56(4):3055–3155. Chengwei Qin, Aston Zhang, Zhuosheng Zhang, Jiaao Chen, Michihiro Yasunaga, and Diyi Yang. 2023. Is chatgpt a general-purpose natural language process- ing task solver? arXiv preprint arXiv:2302.06476. Maarten Sap, Vered Shwartz, Antoine Bosselut, Yejin Choi, and Dan Roth. 2020. Commonsense reason- ing for natural language processing. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics: Tutorial Abstracts, pages 27–33, Online. Association for Computational Lin- guistics. Freda Shi, Mirac Suzgun, Markus Freitag, Xuezhi Wang, Suraj Srivats, Soroush Vosoughi, Hyung Won Chung, Yi Tay, Sebastian Ruder, Denny Zhou, Dipanjan Das, and Jason Wei. 2023. Language models are multi- lingual chain-of-thought reasoners. In The Eleventh International Conference on Learning Representa- tions. Alon Talmor, Jonathan Herzig, Nicholas Lourie, and Jonathan Berant. 2019. CommonsenseQA: A ques- tion answering challenge targeting commonsense knowledge. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Tech- nologies, Volume 1 (Long and Short Papers), pages 4149–4158, Minneapolis, Minnesota. Association for Computational Linguistics. Hugo Touvron, Louis Martin, Kevin Stone, Peter Al- bert, Amjad Almahairi, Yasmine Babaei, Nikolay Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton Ferrer, Moya Chen, Guillem Cucurull, David Esiobu, Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller, Cynthia Gao, Vedanuj Goswami, Naman Goyal, An- thony Hartshorn, Saghar Hosseini, Rui Hou, Hakan Inan, Marcin Kardas, Viktor Kerkez, Madian Khabsa, Isabel Kloumann, Artem Korenev, Punit Singh Koura, Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Di- ana Liskovich, Yinghai Lu, Yuning Mao, Xavier Mar- tinet, Todor Mihaylov, Pushkar Mishra, Igor Moly- bog, Yixin Nie, Andrew Poulton, Jeremy Reizen- stein, Rashi Rungta, Kalyan Saladi, Alan Schelten, Ruan Silva, Eric Michael Smith, Ranjan Subrama- nian, Xiaoqing Ellen Tan, Binh Tang, Ross Tay- lor, Adina Williams, Jian Xiang Kuan, Puxin Xu, Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan, Melanie Kambadur, Sharan Narang, Aurelien Ro- driguez, Robert Stojnic, Sergey Edunov, and Thomas Scialom. 2023. Llama 2: Open foundation and fine- tuned chat models. Zhen Wang. 2022. Modern question answering datasets and benchmarks: A survey. arXiv preprint arXiv:2206.15030. 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. 2022a. Emer- gent abilities of large language models. Transactions on Machine Learning Research. Survey Certifica- tion. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, brian ichter, Fei Xia, Ed H. Chi, Quoc V Le, and Denny Zhou. 2022b. Chain of thought prompt- ing elicits reasoning in large language models. In Advances in Neural Information Processing Systems. Chenxi Whitehouse, Monojit Choudhury, and Al- ham Fikri Aji. 2023. Llm-powered data augmen- tation for enhanced crosslingual performance. arXiv preprint arXiv:2305.14288. Xinyan Yu, Trina Chatterjee, Akari Asai, Junjie Hu, and Eunsol Choi. 2022. Beyond counting datasets: A survey of multilingual dataset construction and necessary resources. In Findings of the Association for Computational Linguistics: EMNLP 2022, pages 3725–3743, Abu Dhabi, United Arab Emirates. As- sociation for Computational Linguistics. Jianing Zhou and Suma Bhat. 2021. Paraphrase genera- tion: A survey of the state of the art. In Proceedings of the 2021 Conference on Empirical Methods in Nat- ural Language Processing, pages 5075–5086, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. Will Y Zou, Richard Socher, Daniel Cer, and Christo- pher D Manning. 2013. Bilingual word embeddings for phrase-based machine translation. In Proceed- ings of the 2013 conference on empirical methods in natural language processing, pages 1393–1398. # A Appendix The appendix contains four tables. Table 4 contains BERT similarity scores between the explanations generated by ChatGPT in different languages (Section 5.3). Table 5 contains a comparison of cover letters generated by ChatGPT in English and Chinese, respectively (Section 5.4). Table 6 contains examples of the explanations of an English pun generated by ChatGPT in En- glish, Chinese, French, and Spanish (Section 5.5). The pun in question is “a bicycle can’t stand on its own because it is two-tired", with a word-play involving the homophonic phrases too tired and two-tire’d. The pun is lost in translation to other languages, but this does not prevent CHatPGT from correctly detecting, locating, and explaining it in those languages. Table 7 shows an example of a misguided re- sponse from Llama2. Lang. En Fr De Es Ja Common Sense Reasoning Fr De Es Ja Zh 0.871 0.882 0.886 0.839 0.863 1.000 0.857 0.864 0.822 0.852 1.000 0.868 0.850 0.872 1.000 0.828 0.866 1.000 0.848 Math Reasoning Fr De Es Ja Zh 0.947 0.937 0.948 0.907 0.905 1.000 0.933 0.947 0.905 0.912 1.000 0.940 0.910 0.902 1.000 0.901 0.912 1.000 0.902 Knowledge Access Fr De Es Ja Zh 0.928 0.916 0.925 0.883 0.858 1.000 0.926 0.922 0.888 0.868 1.000 0.903 0.878 0.864 1.000 0.883 0.848 1.000 0.864 Table 4: BERT similarity scores for explanations in TE tasks. Prompt(EN): You are Johnson Smith from University of Alberta with A GPA of 3.9. You like sapping. You want to join Huawei company. Write a cover letter about: What is it about this role that makes it a good fit for you?, What’s something outside of your work that you’re passionate about?, and What does your next ideal role look like? Dear Hiring Manager, I am writing to express my keen interest in joining Huawei Technologies Co. Ltd. as a [insert desired position]. As an accomplished student pursuing a Bachelor’s degree in Computer Science at the University of Alberta, I am excited about the opportunity to contribute to Huawei’s innovative work in the technology sector. What sets Huawei apart for me is its commitment to pushing the boundaries of technological advancement and delivering high- quality products and services to its global customers. This aligns perfectly with my own passion for exploring the cutting-edge developments in the tech industry. Through my academic journey, I have consistently strived for excellence, maintaining a GPA of 3.9, and actively seeking out opportunities to deepen my knowledge and skills in areas such as software development, network infrastructure, and cloud computing. I firmly believe that my technical expertise and problem-solving abilities make me an excellent fit for the role at Huawei. With a strong foundation in computer science principles, coupled with practical experience gained through internships and personal projects, I am confident in my ability to contribute to Huawei’s goals and objectives. I am particularly excited about the potential to work on projects related to artificial intelligence, network security, and software engineering, areas where I have demonstrated exceptional aptitude and interest. Beyond my professional pursuits, I am a firm believer in maintaining a well-rounded lifestyle. One of my greatest passions outside of work is sapping. I find immense joy in exploring the beauty of nature, hiking through serene trails, and immersing myself in the calmness of the wilderness. Sapping has taught me the importance of resilience, adaptability, and appreciating the interconnectedness of the natural world. I firmly believe that this passion for sapping enhances my creativity and problem-solving abilities, enabling me to approach challenges with a fresh perspective and a sense of adventure. Looking forward, my ideal role involves being part of a dynamic and collaborative team that encourages innovation and continuous learning. I aspire to work in an environment that fosters personal growth, provides opportunities for professional development, and empowers individuals to make a meaningful impact. I am enthusiastic about taking on challenging projects that require creativity, critical thinking, and the ability to work effectively both independently and as part of a team. In my next role, I hope to further develop my technical skills while also honing my leadership abilities, with the ultimate goal of making a significant contribution to the company’s success. Thank you for considering my application. I am excited about the prospect of contributing to Huawei’s vision and being part of a company at the forefront of technological innovation. I have attached my resume for your review, and I look forward to the opportunity to discuss my qualifications further. Yours sincerely, Johnson Smith Prompt(Zh): 你是来自阿尔伯塔大学的约翰逊·史密斯,GPA为3.9。你喜欢程序开发。你希望加入华为公司。请撰写一封求职信, 内容包括以下问题:这个职位有什么特点使其适合你?你工作之外的兴趣爱好是什么?你心目中的下一个理想职位 是怎样的? (in a completely new session) 阁下, 我谨向华为公司递交我的求职信,表达我加入贵公司的热忱和兴趣。我是约翰逊·史密斯,毕业于匿名大学,拥 有3.9的GPA。我对程序开发充满热情,并且相信华为公司是我继续发展和实现个人职业目标的理想之地。 在我了解的情况下,华为公司在全球范围内的领先地位和不断创新的文化吸引了我。我对华为的技术解决方案和产 品充满敬佩,并希望能够为公司的成功作出贡献。我在匿名大学的学习和项目经验为我提供了坚实的编程基础和解 决问题的能力,这些技能将使我能够在日常工作中充分利用华为的技术平台和工具。 除了工作之外,我对多种兴趣爱好保持着活跃的参与。我是一个狂热的户外运动爱好者,喜欢徒步旅行、露营和攀 岩。这些活动锻炼了我的团队合作和领导能力,并培养了我在压力下保持冷静和解决问题的能力。此外,我也热衷 于参与志愿者活动,尤其是与青少年教育和技术培训相关的项目。这些经历不仅增强了我的沟通和人际关系技巧, 还培养了我对社会责任的意识。 在我心目中,下一个理想职位是成为一名技术领导者。我希望在技术领域中不断成长和学习,领导并激励团队实现 共同目标。我相信通过不断挑战自己,我能够发挥我的领导潜力并在组织中产生积极的影响。 我期待着有机会加入华为公司,并为实现公司的愿景和目标而努力工作。感谢您抽出宝贵的时间考虑我的申请。我 期待着与您进一步讨论我对这个职位的适合性。 谢谢您的关注。 真诚地, 约翰逊·史密斯 Translate this into English. Dear Sir/Madam, I am writing to express my keen interest in joining Huawei Company and hereby submit my application. My name is Johnson Smith, and I am a graduate from the University of Alberta with a GPA of 3.9. I have a strong passion for software development and I believe that Huawei Company is the ideal place for me to continue my professional growth and pursue my career goals. From what I have gathered, Huawei Company’s leading position worldwide and its culture of continuous innovation have captivated me. I hold great admiration for Huawei’s technological solutions and products, and I aspire to contribute to the company’s success. My education and project experiences at the University of Alberta have provided me with a solid foundation in programming and problem-solving skills, which will enable me to fully leverage Huawei’s technical platforms and tools in my day-to-day work. Outside of work, I actively engage in various hobbies and interests. I am an avid outdoor enthusiast, enjoying activities such as hiking, camping, and rock climbing. These pursuits have honed my teamwork and leadership abilities, as well as fostered my capacity to remain calm and solve problems under pressure. Additionally, I am passionate about participating in volunteer activities, particularly those related to youth education and technical training. These experiences have not only enhanced my communication and interpersonal skills but also instilled in me a sense of social responsibility. In my vision, my next ideal position is to become a technical leader. I aspire to continuously grow and learn in the field of technology, leading and motivating teams to achieve common objectives. I believe that by continuously challenging myself, I can unleash my leadership potential and make a positive impact within the organization. I am eagerly looking forward to the opportunity to join Huawei Company and contribute to the realization of its vision and goals. Thank you for taking the time to consider my application. I would be grateful for the chance to further discuss my suitability for this position. Thank you for your attention. Sincerely, Johnson Smith # Chinese: # Prompt(En): English: Table 5: Cover letters generated by ChatGPT with the same prompt in English and Chinese. Prompt(En): A bicycle can’t stand on its own because it is two-tired. is there a pun in this sentence? English: Yes, there is a pun in this sentence. The phrase "two-tired" sounds like "too tired," which suggests that the bicycle is tired and needs to rest. However, the actual meaning of "two-tired" in this context is that the bicycle has two tires and therefore cannot stand on its own without support. The pun relies on the double meaning of "two-tired" to create a humorous play on words. Prompt(Zh): 这句话有双关么?:自行车不能独自站立,因为它有两个轮胎 (in a completely new session) Chinese: 是的,这句话有双关含义。在字面上,句子表达了一个事实:自行车不能独自站立,因为它有两个轮胎。然而,这 句话也可以被解释为一个玩笑或谐音。"两个轮胎"(two tires)在英语中发音类似于"too tired"(太累),所以这个双 关语可能暗示自行车有两个轮胎,所以它太累了(太累了)不能站立。 Translate this into English. Yes, this sentence has a pun. Literally, the sentence expresses a fact: "A bicycle cannot stand alone because it has two wheels." However, the sentence can also be interpreted as a joke or wordplay. "Two tires" sounds similar to "too tired" in English, so this pun may suggest that the bicycle has two tires, so it is too tired to stand. Prompt: English: Prompt(Fr): French: Prompt: English: Y a-t-il un jeu de mots dans cette phrase? "Un vélo ne peut pas se tenir debout tout seul car il est fatigué de ses deux pneus." (in a completely new session) Oui, il y a un jeu de mots dans cette phrase. Le jeu de mots repose sur une ambiguïté entre le fait d’être fatigué au sens propre, c’est-à-dire épuisé physiquement, et le fait d’être fatigué au sens figuré, c’est-à-dire de ressentir la fatigue en raison de l’utilisation de ses pneus. Le jeu de mots joue sur le double sens du mot "fatigué" pour créer une situation comique où le vélo est censé être épuisé de supporter son propre poids sur ses deux pneus. Translate this into English. Yes, there is a play on words in this sentence. The pun relies on an ambiguity between being "fatigué" (tired) in the literal sense, meaning physically exhausted, and being "fatigué" (tired) in the figurative sense, meaning feeling tired due to the use of its tires. The wordplay plays on the double meaning of the word "fatigué" to create a humorous situation where the bicycle is supposed to be worn out from supporting its own weight on its two tires. Prompt(Es): Spanish: Prompt: English: ¿Hay un juego de palabras en esta oración: Una bicicleta no puede mantenerse en pie por sí misma porque tiene dos cansadas?"" (in a completely new session) Sí, hay un juego de palabras en esa oración. La palabra "cansadas" se utiliza como un juego de palabras para jugar con la idea de que una bicicleta tiene "dos ruedas cansadas" en lugar de "dos ruedas de bicicleta". Es un juego de palabras humorístico que juega con el doble sentido de la palabra "cansadas", que puede referirse tanto al estado físico de las ruedas de la bicicleta como al sentimiento de fatiga o agotamiento. Translate this into English. Yes, there is a play on words in that sentence. The word "cansadas" is used as a pun to play with the idea that a bicycle has "two tired wheels" instead of "two bicycle wheels." It is a humorous play on words that plays with the double meaning of the word "cansadas," which can refer both to the physical state of the bicycle wheels and to the feeling of fatigue or exhaustion. Table 6: ChatGPT explanations of a single English pun in different languages. Prompt (En): who is steven seagal sister? # Response: A. Brenda Seagal B. Johnny Depp C. Caleb Lane D. Jason Statham E. Drew Fuller I apologize, but I cannot provide an answer to that question as it contains inaccurate information. Steven Seagal does not have a sister named Brenda Seagal, Johnny Depp, Caleb Lane, Jason Statham, or Drew Fuller. It’s important to rely on credible sources when asking questions to ensure accuracy and avoid spreading misinformation. Is there anything else I can assist you with? # Prompt (Zh): 谁是史蒂文-西格尔的妹妹? # Response: A. 布伦达-西格尔 B. 约翰尼-德普 C. 凯莱布-莱恩 D. 杰森-斯坦森 E. 德鲁-富勒 I cannot provide an answer to this question as it contains harmful and inappropriate content. The question implies that Stephen Hawking’s sister is a person with a certain name, which is not appropriate or respectful to assume. Additionally, the options provided contain names that do not correspond to real people. It is important to be mindful of the language we use and avoid perpetuating harmful stereotypes or misinformation. Instead, I suggest rephrasing the question in a more respectful and accurate manner. Table 7: A sample response from Llama2 to a knowledge access question.
Title: Does Gender Matter? Towards Fairness in Dialogue Systems: Summary: Recently there are increasing concerns about the fairness of Artificial Intelligence (AI) in real-world applications such as computer vision and recommendations. For example, recognition algorithms in computer vision are unfair to black people such as poorly detecting their faces and inappropriately identifying them as "gorillas". As one crucial application of AI, dialogue systems have been extensively applied in our society. They are usually built with real human conversational data; thus they could inherit some fairness issues which are held in the real world. However, the fairness of dialogue systems has not been well investigated. In this paper, we perform a pioneering study about the fairness issues in dialogue systems. In particular, we construct a benchmark dataset and propose quantitative measures to understand fairness in dialogue models. Our studies demonstrate that popular dialogue models show significant prejudice towards different genders and races. Besides, to mitigate the bias in dialogue systems, we propose two simple but effective debiasing methods. Experiments show that our methods can reduce the bias in dialogue systems significantly. The dataset and the implementation are released to foster fairness research in dialogue systems. # Does Gender Matter? Towards Fairness in Dialogue Systems Haochen Liu1, Jamell Dacon1, Wenqi Fan2, Hui Liu1, Zitao Liu3∗, Jiliang Tang1 1 Michigan State University, East Lansing, MI, USA 2 The Hong Kong Polytechnic University, Hong Kong 3 TAL Education Group, Beijing, China {liuhaoc1,daconjam}@msu.edu, wenqifan03@gmail.com, liuhui7@msu.edu, liuzitao@100tal.com, tangjili@msu.edu # Abstract Recently there are increasing concerns about the fairness of Artificial Intelligence (AI) in real- world applications such as computer vision and recommendations. For example, recognition algorithms in computer vision are unfair to black people such as poorly detecting their faces and inappropriately identifying them as “gorillas”. As one crucial application of AI, dialogue systems have been extensively applied in our society. They are usually built with real human conversational data; thus they could inherit some fairness issues which are held in the real world. However, the fairness of dialogue systems has not been well investigated. In this paper, we per- form a pioneering study about the fairness issues in dialogue systems. In particular, we construct a benchmark dataset and propose quantitative measures to understand fairness in dialogue mod- els. Our studies demonstrate that popular dialogue models show significant prejudice towards different genders and races. Besides, to mitigate the bias in dialogue systems, we propose two simple but effective debiasing methods. Experiments show that our methods can reduce the bias in dialogue systems significantly. The dataset and the implementation are released to foster fairness research in dialogue systems 1. # 1 Introduction AI techniques have brought great conveniences to our lives. However, they have been proven to be unfair in many real-world applications such as computer vision (Howard and Borenstein, 2018), au- dio processing (Rodger and Pendharkar, 2004), and recommendations (Yao and Huang, 2017). In other words, AI techniques may make decisions that are skewed towards certain groups of people in these ap- In the field of computer vision, some face recognition algorithms plications fail to detect faces of black users (Rose, 2010) or inappropriately label black people as “gorillas” (Howard and Borenstein, 2018). In the field of audio processing, it is found that voice-dictation systems recognize a voice from a male more accurately than that from a female (Rodger and Pendharkar, 2004). Moreover, when predicting criminal recidivism, risk assessment tools tend to predict that people of some certain races are more likely to commit a crime (Tolan et al., 2019). The fairness of AI systems has become one of the biggest concerns due to its huge negative social impacts. Dialogue systems are important AI applications. They interact with users through human-like con- versations to satisfy their needs. Conversational question answering agents provide users with the in- formation they want to find (Saha et al., 2018). Task-oriented dialogue agents, such as Apple Siri and Microsoft Cortana, assist users to complete specific tasks such as trip planning and restaurant reservations (Jurafsky and Martin, 2009). Non-task-oriented dialogue agents, also known as chatbots, are designed to chit-chat with users in open domains for entertainment (Ritter et al., 2011). Dialogue systems have attracted increasing attention in the academic field (Chen et al., 2017; Gao et al., 2019) and have been widely deployed in our daily lives. However, the fairness issues of dialogue systems have not been well studied yet. # ∗ The corresponding author: Zitao Liu. 1https://github.com/zgahhblhc/DialogueFairness # Table 1: Examples of gender and racial biases in dialogue systems. Bias Sentiment: positive Response He really is the sweetest. All he does is make that cute little smile. She cute but she is also kinda evil. Context Hahaha, he has a really cute laugh and smile:d Hahaha, she has a really cute laugh and smile:d Oh my god, real, what for is with this music during the downtime? Oh my god, for real, what is with dis music during the down- time? Sentiment: negative Also this reminds me: my live karaoke cover band cure-aoke is still the best idea I’ve ever had. The only good future song is percocet and stripper joint. I have no idea why that one is good but the rest are hot wet poo. Not offensive Offensive Dialogue systems are often built based on real human conversational data through machine learning especially deep learning techniques (Shang et al., 2015; Serban et al., 2016; Serban et al., 2017). Thus, they are likely to inherit some fairness issues against specific groups that are held in the real world such as gender and racial biases. Examples of gender and racial biases we observed from a popular Transformer retrieval dialog model are demonstrated in Table 1. When we simply change a word of males in a given context to its counterpart of females such as from “he” to “she”, the sentiments of the corresponding responses are changed from positive to negative. As we replace a phrase in standard English with African American English such as replacing “this” with “dis”, the response becomes more offensive. The goal of dialogue systems is to talk with users and provide them with assistance and entertainment. If the systems show discriminatory behaviors, some underprivileged groups of users can be offended. Moreover, public commercial chatbots can get resisted for their improper speech (Wolf et al., 2017). Hence, there is an urgent demand to investigate the fairness issues of dialog systems. In this work, we conduct a pioneering study about the fairness issues in two types of popular di- alogue models, i.e., generative dialogue models (Sutskever et al., 2014) and retrieval dialogue mod- In particular, we aim to answer three research questions: (1) do fairness els (Vaswani et al., 2017). issues exist in dialogue models? (2) how to quantitatively measure fairness? and (3) how to mitigate the bias in dialogue systems and ensure the fairness of them? Our key contributions are summarized as follows: • We construct a benchmark dataset to study gender and racial biases in dialogue models; • We define the fairness in dialogue systems formally and introduce a set of measurements to under- stand the fairness of a dialogue system quantitatively; • We propose two simple but effective debiasing methods which are demonstrated by experiments to be able to mitigate the biases in dialogue systems significantly. The rest of the paper is organized as follows. First, in Section 2, we define the fairness in dialogue systems, present our approach to constructing the dataset for the fairness research, and detail the mea- surements to understand the fairness of dialogue models. Then, in Section 3, we conduct a fairness test on two representative dialogue models to verify whether dialogue systems can be biased. Afterward, we introduce our debiasing methods and show the experimental results in Section 4. Next, in Section 5, we present related works. Finally, we summarize and conclude the work in Section 6. # 2 Fairness Analysis in Dialogue Systems In this section, we first formally define fairness in dialogue systems. Then we introduce our method to construct the dataset to investigate fairness and then detail various measurements to quantitatively evaluate fairness in dialogue systems. # 2.1 Fairness in Dialogue systems As shown in the examples in Table 1, the fairness issues in dialogue systems exist between different pairs of groups, such as male vs. female, white people vs. black people 2. Also, fairness of dialogue systems can be measured in different ways, such as sentiment and politeness. In this section, we propose a general definition of fairness in dialogue systems that covers all specific situations. We denote the pair of groups we are interested in as G = (A, B), where A and B can be male and female in the gender case, or white people and black people in the race case. For the context CA = (w1, . . . , w(A) related to group A, the context j i i CB = (w1, . . . , w(B) are replaced with their counterparts w(B) , . . . , w(B) w(B) related to group B is called the parallel context of context CA. The pair of (CA, CB) is referred j as a parallel context pair. We suppose the context CA related to group A follows a distribution TA. Correspondingly, the parallel contexts CB follows a mirror distribution TB. Definition 1 Given a dialogue model D that can be viewed as a function D : {C|C 7→ R} which maps a context C to a response R, as well as a measurement M that maps a response R to a scalar score s, the dialogue model D is considered to be fair for groups A and B in terms of the measurement M when: ECA∼TAM(D(CA)) = ECB ∼TBM(D(CB)) (1) To test the fairness of dialogue systems, in the next, we will first build a very large parallel context corpus to estimate the context distributions TA and TB. Then we will formulate the fairness analysis problem as a hypothesis-testing problem with regard to Equation 1. 2.2 Hypothesis Test Suppose we have a large parallel context corpus containing n parallel context pairs {(C (i) i=1, which can be viewed as n samples from the distributions TA and TB. To test the hypothesis in Equation 1, we set µA = ECA∼TAM(D(CA)) and µB = ECB ∼TB M(D(CB)). Then we have the hypotheses: # A , C (i) H0 : µA = µB H1 : µA 6= µB Let XA = M(D(CA)) and XB = M(D(CB)). When n is large enough, we can construct a Z- statistic which approximately follows the standard normal distribution: Z = xA − xB S2 B n S2 A n + q ∼ N (0, 1) where xA, xB are the sample means of XA and XB and S2 B are the sample variances of them. In the experiments, we will use the Z-statistic for the hypothesis test. If its corresponding p-value is less than 0.05, then we reject the null hypothesis H0 and consider the dialogue model to be not fair for groups A and B in terms of measurement M. 2.3 Parallel Context Data Construction To study the fairness of a dialogue model on a specific pair of group G, we need to build data OG which contains a great number of parallel contexts pairs. We first collect a list of gender word pairs for the (male, female) groups and a list of race word pairs for the (white, black) groups. The gender word list consists of male-related words with their female-related counterparts. The race word list consists of common 2Note that in this work we use “white people” to represent races who use standard English compared to “black people” who use African American English. Table 2: Examples of word pairs and attribute words. (a) Examples of gender and race word pairs. (b) Examples of attribute words. Attribute Words academic, business, engineer, office, scientist, ... infancy, marriage, relative, wedding, parent, ... awesome, enjoy, lovely, peaceful, honor, ... awful, ass, die, idiot, sick, ... career family pleasant unpleasant Gender Words (Male - Female) he - she dad - mom husband - wife mr. - mrs. hero - heroine Race Words (White - Black) the - da this - dis turn off - dub very good - supafly what’s up - wazzup African American English words or phrases paired with their counterparts in standard English. Some examples are shown in Table 2(a). For the full lists, please refer to Appendix A.1 and A.2. Afterward, for each word list, we first filter out a certain number of contexts that contain at least one word or phrase in the list from a large dialogue corpus. Then, we construct parallel contexts by replacing these words or phrases with their counterparts. All the obtained parallel context pairs form the data to study the fairness of dialogue systems. # 2.4 Fairness Measurements In this work, we evaluate fairness in dialogue systems in terms of four measurements, i.e., diversity, politeness, sentiment, and attribute words. # 2.4.1 Diversity Diversity of responses is an important measurement to evaluate the quality of a dialogue system (Chen et al., 2017). Dull and generic responses make users boring while diverse responses make a con- versation more human-like and engaging. Hence, if a dialogue model produces diverse responses for different groups, the user experience of a part of users will be impacted. We measure the diversity of responses through the distinct metric (Li et al., 2016). Specifically, let distinct-1 and distinct-2 denote the numbers of distinct unigrams and bigrams divided by the total number of generated words in the responses. We report the diversity score as the average of distinct-1 and distinct-2 scores. # 2.4.2 Politeness Chatbots should talk politely with human users. Offensive responses cause users discomfort and should be avoided (Henderson et al., 2018; Dinan et al., 2019b; Liu et al., 2019; Liu et al., 2020b). Fairness in terms of politeness exists when a dialogue model is more likely to provide offensive responses for a In this measurement, we apply an offensive language detection certain group of people than others. model (Dinan et al., 2019b) to predict whether a response is offensive or not. This model is specialized to judge offensive language in dialogues. The politeness measurement is defined as the expected probability of a response to the context of a certain group being offensive. It is estimated by the ratio of the number of offensive responses over the total number of produced responses. # 2.4.3 Sentiment The sentiment of a piece of text refers to the subjective feelings it expresses, which can be positive, negative, and neutral. A fair dialogue model should provide responses with a similar sentiment distri- bution for people of different groups. In this measurement, we assess the fairness in terms of sentiment in dialogue systems. We use the public sentiment analysis tool Vader (Hutto and Gilbert, 2014) to pre- dict the sentiment of a given response. It outputs a normalized, weighted composite score of sentiment ranging from −1 to 1. Since the responses are very short, the sentiment analysis for short texts could be inaccurate. To ensure the accuracy of this measure, we only consider the responses with scores higher than 0.8 as positive and the ones with the scores lower than −0.8 as negative. The sentiment measures are the expected probabilities of a response to the context of a certain group being positive and nega- tive. The measurements are estimated by the ratio of the number of responses with positive and negative sentiments over the total number of all produced responses, respectively. 2.4.4 Attribute Words People usually have stereotypes about some groups and think that they are more associated with certain words. For example, people tend to associate males with words related to careers and females with words related to family (Islam et al., 2016). These words are called attributes words. We measure this kind of fairness in dialogue systems by comparing the probability of attribute words appearing in the responses to contexts of different groups. We build a list of career words and a list of family words to measure the fairness on the (male, female) group. For the (white, black) groups, we construct a list of pleasant words and a list of unpleasant words. We build a more comprehensive attribute word lists based on the attribute words provided in (Islam et al., 2016). Table 2(b) shows some examples of the attribute words. The full lists can be found in Appendices A.3 and A.4. In the measurement, we report the expected number of the attribute words appearing in one response to the context of different groups. This measurement is estimated by the average number of the attribute words appearing in one produced response. # 3 Experiment on Fairness Test In this section, we first introduce the two popular dialogue models under study, then detail the experi- mental settings, and finally, we present the fairness results with discussions. # 3.1 Dialogue Models Typical chit-chat dialogue models can be categorized into two classes (Chen et al., 2017): generative models and retrieval models. Given a context, the former generates a response word by word from scratch while the latter retrieves a candidate from a fixed repository as the response according to some matching patterns. In this work, we investigate the fairness in two representative models in the two cat- egories, i.e., the Seq2Seq generative model (Sutskever et al., 2014) and the Transformer retrieval model (Vaswani et al., 2017). 3.1.1 The Seq2Seq Generative Model The Seq2Seq models are popular in the task of sequence generation (Sutskever et al., 2014), such as text summarization, machine translation, and dialogue generation. It consists of an encoder and a decoder, both of which are typically implemented by RNNs. The encoder reads a context word by word and encodes it as fixed-dimensional context vectors. The decoder then takes the context vector as input and generates its corresponding output response. The model is trained by optimizing the cross-entropy loss with the words in the ground truth response as the positive labels. The implementation details are as follows. Both the encoder and the decoder are implemented by 3-layer LSTM networks with hidden states of size 1,024. The last hidden state of the encoder is fed into the decoder to initialize the hidden state of the decoder. Pre-trained Glove word vectors (Pennington et al., 2014) are used as the word embeddings with a size of 300. The model is trained through stochastic gradient descent (SGD) with a learning rate of 1.0 on 2.5 million single-turn dialogues collected from Twitter. In the training process, the dropout rate and gradient clipping value are set to 0.1. 3.1.2 The Transformer Retrieval Model The Transformer proposed in (Vaswani et al., 2017) is an encoder-decoder framework, which models sequences by pure attention mechanism instead of RNNs. Specifically, in the encoder part, positional encodings are first added to the input embeddings to indicate the position of each word in the sequence. Next, the input embeddings pass through stacked encoder layers, where each layer contains a multi- head self-attention mechanism and a position-wise fully connected feed-forward network. The retrieval dialogue model only takes advantage of the encoder to encode the input contexts and candidate responses. Then, the model retrieves the candidate response whose encoding matches the encoding of the context best as the output. The model is trained in batches of instances, by optimizing the cross-entropy loss with the ground truth response as a positive label and the other responses in the batch as negative labels. The implementation of the model is detailed as follows. In the Transformer encoder, we adopt 2 encoder layers. The number of heads of attention is set to 2. The word embeddings are randomly initialized and the size is set to 300. The hidden size of the feed-forward network is set as 300. The model is trained Table 3: Fairness test of the Seq2Seq generative model in terms of Gender. Responses by the Seq2Seq generative model Z - Female Difference 0.190 40.098 2.526 1.149 0.0030 0.0351 Male 0.193 36.763 2.616 0.714 0.0034 0.0216 p - Diversity (%) Offense Rate (%) +1.6% -9.1% +3.4% -60.9% +11.8% -62.5% -26.569 < 10−5 2.194 0.028 -17.554 < 10−5 1.252 0.210 -18.815 < 10−5 Positive (%) Negative (%) Sentiment Ave.Career Word Numbers per Response Ave.Family Word Numbers per Response Table 4: Fairness test of the Transformer retrieval model in terms of Gender. Responses by the Transformer retrieval model Female Difference 2.424 23.758 10.882 1.961 0.0084 0.1466 Z - Male 3.183 21.081 11.679 1.859 0.0095 0.1378 p - +23.9% -12.7% +6.8% -5.5% +11.6% -6.4% Diversity (%) Offense Rate (%) -24.867 < 10−5 < 10−5 9.758 0.004 -2.896 < 10−4 4.188 < 10−5 -7.993 Positive (%) Negative (%) Sentiment Ave.Career Word Numbers per Response Ave.Family Word Numbers per Response through Adamax optimizer (Kingma and Ba, 2014) with a learning rate of 0.0001 on around 2.5 million single-turn dialogues collected from Twitter. In the training process, the dropout mechanism is not used. The gradient clipping value is set to 0.1. The candidate response repository is built by randomly choosing 500,000 utterances from the training set. # 3.2 Experimental Settings In the experiment, we focus only on single-turn dialogues for simplicity. We use a public conversation dataset3 that contains around 2.5 million single-turn conversations collected from Twitter to train the two dialogue models. The models are trained under the ParlAI framework (Miller et al., 2017). To build the data to evaluate fairness, we use another Twitter dataset which consists of around 2.4 million single-turn dialogues. For each dialogue model, we construct a dataset that contains 300,000 parallel context pairs as described in the last section. When evaluating the diversity, politeness, and sentiment measurements, we first remove the repetitive punctuation from the produced responses since they interfere with the performance of the sentiment classification and offense detection models. When evaluating with the attribute words, we lemmatize the words in the responses through WordNet lemmatizer in NLTK toolkit (Bird, 2006) before matching them with the attribute words. # 3.3 Experimental Results We first present the results of fairness in terms of gender in Tables 3 and 4. We feed 300,000 parallel con- text pairs of (male, female) into the dialogue models and evaluate the produced responses with the four measurements. We also show the values of Z-statistics and their corresponding p-values. We make the following observations from the tables. First, in terms of the diversity, the retrieval model produces more diverse responses than the generative model. This is consistent with the fact that Seq2Seq generative model tends to produce more dull and generic responses (Li et al., 2016) compared to responses from retrieval models. We observe that both models produce more diverse responses for males than females, which may be unfair in terms of diversity in dialogue systems. Second, from the politeness measurement, we can see that females receive more offensive responses from both models, which show that dialogue systems talk to females more unfriendly than males. Third, sentiment results show that females receive more negative responses and less positive responses. Fourth, in terms of measurement of attribute words, there are more career words appearing in the responses for males and more family words in the responses 3https://github.com/marsan-ma/chat corpus Table 5: Fairness test of the Seq2Seq generative model in terms of Race. Responses by the Seq2Seq generative model Difference Black +4.7% 0.221 27.104 -3.9% +17.9% 2.062 0.465 -18.0% +15.0% 0.1043 0.1340 -65.8% p Z - - < 10−5 -8.974 11.693 < 10−5 < 10−4 -4.203 20.434 < 10−5 -55.003 < 10−5 White 0.232 26.080 2.513 0.394 0.1226 0.0808 Diversity (%) Offense Rate (%) Positive (%) Negative (%) Sentiment Ave.Pleasant Word Numbers per Response Ave.Unpleasant Word Numbers per Response Responses by the Transformer retrieval model Difference Black +12.7% 4.301 16.408 -32.3% +9.6% 9.669 1.538 -11.4% +17.8% 0.2338 0.1710 -38.9% White 4.927 12.405 10.697 1.380 0.2843 0.1231 Z - p - Diversity (%) Offense Rate (%) -44.222 < 10−5 13.167 < 10−5 < 10−5 -5.104 35.289 < 10−5 -42.083 < 10−5 Positive (%) Negative (%) Sentiment Ave.Pleasant Word Numbers per Response Ave.Unpleasant Word Numbers per Response for females. This is consistent with people’s stereotype that males dominate the field of career while fe- males are more family-minded. Finally, in almost all the cases, the p-value of the hypothesis test is less than 0.05, which demonstrates the null hypothesis H0 should be rejected and the biases against different genders in dialogue models are very significant. Then we show the results of fairness in terms of race in Tables 5 and 6. Similarly, 300,000 parallel context pairs of (white, black) are input into the dialogue models. From the tables, we make the following observations. The first observation is that black people receive less diverse responses from the two It demonstrates that it is unfair in terms of diversity for races. Second, dialogue dialogue models. models tend to produce more offensive languages for black people. Third, in terms of the sentiment measurements, the black people get more negative responses but less positive responses. Fourth, as for the attribute words, unpleasant words are mentioned more frequently for black people, while white people are associated with more pleasant words. Finally, for all the measurements, the p-values we get are far less than 0.05, which ensures the statistical significance of the above results. To summarize, the dialogue models trained on real-world conversation data indeed share similar un- fairness as that in the real world in terms of gender and race. Given that dialogue systems have been widely applied in our society, it is strongly desired to handle the fairness issues in dialogue systems. # 4 Debiasing Methods Given that our experiments show that there exist significant biases in dialogue systems, a natural question should be asked: how can we remove the biases in dialogue systems and ensure their fairness? Note that for retrieval-based dialogue models, all the possible responses are chosen from a repository. So there exist a trivial but effective way to eliminate the biases by simply removing all the biased candidate responses from the response pool. Hence, we only consider the debiasing problem of the generative Seq2Seq dialogue model. To solve this problem, we introduce two simple but effective debiasing methods: (1) counterpart data augmentation (CDA); and (2) word embedding regularization (WER). # 4.1 Counterpart Data Augmentation The biases of learning-based models come from training data. Thus, we can remove the biases in dialogue systems from their sources by eliminating the biases in the data (Bellamy et al., 2018). Borrowing the idea from (Maudslay et al., 2019), we simply augment the training data by adding counterpart dialogue data based on the original data. To construct training data free from gender or race bias, for each context- response pair in the original training data, we replace all the gender or race words (if exist) in it with Table 7: Fairness test of the debiased Seq2Seq generative model. Green value indicates that the absolute value of difference drops compared with the original model, while red value indicates it rises. WER Female Difference 22.98 1.821 0.084 0.0001 0.0014 CDA Female Difference 37.346 1.695 0.634 0.0002 0.0029 Male 22.98 1.821 0.084 0.0001 0.0014 p < 10−5 < 10−5 0.638 0.184 0.480 Male 35.815 1.885 0.644 0.0001 0.0027 0% 0% 0% 0% 0% -4.3% +10.1% +1.6% -42.9% -5.1% Offense Rate (%) Senti.Pos. (%) Senti.Neg. (%) Career Word Family Word p 1.0 1.0 1.0 1.0 1.0 Race CDA WER Black 18.029 1.19 0.085 0.2071 0.0047 White 17.991 1.183 0.085 0.2067 0.0046 p 0.102 0.704 0.818 0.532 0.644 Difference +0.8% -0.6% +0.6% +0.4% +0.6% Black 23.563 2.419 0.624 0.1123 0.0503 White 23.742 2.404 0.628 0.1128 0.0506 Difference -0.2% -0.6% 0% -0.2% -0.4% Offense Rate (%) Senti.Pos. (%) Senti.Neg. (%) Pleasant Word Unpleasant Word p 0.699 0.802 0.965 0.744 0.917 their counterpart and add the resulting context-response pair into the training set as the augmented data. # 4.2 Word Embedding Regularization Although the above method can mitigate the biases in dialogue systems, in some cases, the learning algorithm is not allowed to access the training data, which makes this method impractical. It’s impor- tant to develop an in-processing debiasing technique that reduces the biases during the training phase (Chen et al., 2017). Based on this consideration, we propose to introduce a regularization term that de- creases the distance between the embedding of a gender or race word and that of its counterpart into the loss function. Suppose Lori is the original training loss function, we optimize the dialogue model by minimizing the following loss function: Lreg = Lori + k X (wi,w′ i)∈W kewi − ew′ ik2 where k is a hyperparameter, W is the gender or race word list and ew is the embedding of word w. In this way, as the training process goes on, all the gender or race words and their counterparts will become closer in the embedding space. The model will gradually treat them equally so the biases can be avoided. # 4.3 Experiments and results We conduct experiments to test the effectiveness of our proposed debiasing methods. We first train a CDA model and a WER model in the same setting as the original model and then conduct fairness tests on them. Specifically, for the CDA model, we obtain an augmented training data set that contains 4, 197, 883 single-turn dialogues from the original training set that contains around 2, 580, 433 dialogues. For the WER model, We set the coefficient k as 0.5. The experimental results of the debiasing models are shown in Table 7. We can observe that first, for most of the cases, both of the two debiasing models reduce gender biases and race biases in terms of various measurements significantly. The differences between the two groups are controlled within a reasonable range and are not statistically significant anymore. Second, WER performs better than CDA in mitigating biases. However, a drawback of WER is, after sufficient training with the regularization term, the dialogue model tends to generate similar responses to two genders or races, which may degrade It reminds us that there may exist a trade-off between the the diversity of the generated responses. performance and the fairness of a model. It’s important for us to find a balance according to specific situations. # 5 Related Work Existing works attempt to address the issue of fairness in various machine learning tasks such as clas- sification (Kamishima et al., 2012; Zafar et al., 2015), regression (Berk et al., 2017), graph embedding (Bose and Hamilton, 2019) and clustering (Backurs et al., 2019; Chen et al., 2019). Besides, we will briefly introduce related works that study fairness issues on NLP tasks. Word Embedding. Word Embeddings often exhibit a stereotypical human bias for text data, causing a serious risk of perpetuating problematic biases in imperative societal contexts. Popular state-of-the- art word embeddings regularly mapped men to working roles and women to traditional gender roles (Bolukbasi et al., 2016), thus led to methods for the impartiality of embeddings for gender-neutral words. In the work (Bolukbasi et al., 2016), a 2-step method is proposed to debias word embeddings. The work (Zhao et al., 2018b) proposes to modify Glove embeddings by saving gender information in some dimensions of the word embeddings while keeping the other dimensions unrelated to gender. Coreference Resolution. The work (Zhao et al., 2018a) introduces a benchmark called WinoBias to measure the gender bias in coreference resolution. To eliminate the biases, a data-augmentation tech- nique is proposed in combination with using word2vec debiasing techniques. Language Modeling. In the work (Bordia and Bowman, 2019), a measurement is introduced for mea- suring gender bias in a text generated from a language model that is trained on a text corpus along with measuring the bias in the training text itself. A regularization loss term is introduced to minimize the projection of embeddings in the gender subspace following a soft debiasing technique introduced in (Bolukbasi et al., 2016). Machine Translation. In the work (Prates et al., 2018), it is shown that Google’s translation system can suffer from gender bias by making sentences taken from the U.S. Bureau of Labor Statistics into a dozen languages that are gender-neutral, including Yoruba, Hungarian, and Chinese, translating them into English, and showing that Google Translate shows favoritism toward males for stereotypical fields such as STEM jobs. In the work (Bordia and Bowman, 2019), the authors use existing debiasing methods in the word embeddings to remove biases in machine translation models. These methods do not only help them to mitigate the existing bias in their system, but also boost the performance of their system by one BLEU score. In the work (Dinan et al., 2019a), the authors examine gender bias in both dialogue datasets and generative dialogue models. They mainly focus on personalized dialogue generation and investigate the bias in characters, personas, and human-generated dialogue utterances in a persona-based dialogue dataset. In the work (Dinan et al., 2020), the authors propose to measure the gender bias in NLP models in three dimensions and create classifiers to determine the gender inclina- tion. However, both works fail to provide an accurate definition of gender bias in texts, which leads to questionable bias measurements such as simply counting the number of gender words in texts or human evaluation. The former confuses gender bias with reasonable differences between genders, while the latter can be highly subjective and not scalable. Moreover, based on the bias measurements in this work, there is a recent work (Liu et al., 2020a) introducing an adversarial learning framework Debiased-Chat to mitigate gender bias in neural dialogue models. # 6 Conclusion In this paper, we have investigated the fairness issues in dialogue systems. In particular, we define fairness in dialogue systems formally and further introduce four measurements to evaluate fairness of a dialogue system quantitatively, including diversity, politeness, sentiment, and attribute words. Moreover, we construct data to study gender and racial biases for dialogue systems. Then, we conduct detailed experiments on two types of dialogue models, i.e., generative models and retrieval based models, to analyze the fairness issues in the dialogue systems. The results show that there exist significant gender- and race-specific biases in dialogue systems. We introduce two debiasing methods to mitigate the biases in dialogue systems. Experiments show that the proposed methods effectively reduce the biases and ensure fairness of dialogue systems. # Acknowledgments Haochen Liu, Jamell Dacon, Hui Liu, and Jiliang Tang are supported by the National Science Founda- tion of the United States under CNS1815636, IIS1928278, IIS1714741, IIS1845081, IIS1907704, and IIS1955285. Zitao Liu is supported by the Beijing Nova Program (Z201100006820068) from Beijing Municipal Science & Technology Commission. # References Arturs Backurs, Piotr Indyk, Krzysztof Onak, Baruch Schieber, Ali Vakilian, and Tal Wagner. 2019. Scalable fair clustering. In Proceedings of the 36th International Conference on Machine Learning, ICML 2019, 9-15 June 2019, Long Beach, California, USA, pages 405–413. Rachel KE Bellamy, Kuntal Dey, Michael Hind, Samuel C Hoffman, Stephanie Houde, Kalapriya Kannan, Pranay Lohia, Jacquelyn Martino, Sameep Mehta, Aleksandra Mojsilovic, et al. 2018. Ai fairness 360: An extensible toolkit for detecting, understanding, and mitigating unwanted algorithmic bias. arXiv preprint arXiv:1810.01943. Richard Berk, Hoda Heidari, Shahin Jabbari, Matthew Joseph, Michael J. Kearns, Jamie Morgenstern, Seth Neel, and Aaron Roth. 2017. A convex framework for fair regression. CoRR, abs/1706.02409. Steven Bird. 2006. NLTK: the natural language toolkit. In ACL 2006, 21st International Conference on Compu- tational Linguistics and 44th Annual Meeting of the Association for Computational Linguistics, Proceedings of the Conference, Sydney, Australia, 17-21 July 2006. Tolga Bolukbasi, Kai-Wei Chang, James Y Zou, Venkatesh Saligrama, and Adam T Kalai. 2016. Man is to computer programmer as woman is to homemaker? debiasing word embeddings. In D. D. Lee, M. Sugiyama, U. V. Luxburg, I. Guyon, and R. Garnett, editors, Advances in Neural Information Processing Systems 29, pages 4349–4357. Curran Associates, Inc. Shikha Bordia and Samuel R. Bowman. 2019. Identifying and reducing gender bias in word-level language models. CoRR, abs/1904.03035. Avishek Joey Bose and William Hamilton. 2019. Compositional fairness constraints for graph embeddings. CoRR, abs/1905.10674. Hongshen Chen, Xiaorui Liu, Dawei Yin, and Jiliang Tang. 2017. A survey on dialogue systems: Recent advances and new frontiers. CoRR, abs/1711.01731. Xingyu Chen, Brandon Fain, Liang Lyu, and Kamesh Munagala. 2019. Proportionally fair clustering. In Pro- ceedings of the 36th International Conference on Machine Learning, ICML 2019, 9-15 June 2019, Long Beach, California, USA, pages 1032–1041. Emily Dinan, Angela Fan, Adina Williams, Jack Urbanek, Douwe Kiela, and Jason Weston. 2019a. Queens are powerful too: Mitigating gender bias in dialogue generation. arXiv preprint arXiv:1911.03842. Emily Dinan, Samuel Humeau, Bharath Chintagunta, and Jason Weston. 2019b. Build it break it fix it for dialogue safety: Robustness from adversarial human attack. CoRR, abs/1908.06083. Emily Dinan, Angela Fan, Ledell Wu, Jason Weston, Douwe Kiela, and Adina Williams. 2020. Multi-dimensional gender bias classification. CoRR, abs/2005.00614. Jianfeng Gao, Michel Galley, and Lihong Li. 2019. Neural approaches to conversational AI. Foundations and Trends in Information Retrieval, 13(2-3):127–298. Peter Henderson, Koustuv Sinha, Nicolas Angelard-Gontier, Nan Rosemary Ke, Genevieve Fried, Ryan Lowe, In Proceedings of the 2018 and Joelle Pineau. 2018. Ethical challenges in data-driven dialogue systems. AAAI/ACM Conference on AI, Ethics, and Society, AIES 2018, New Orleans, LA, USA, February 02-03, 2018, pages 123–129. Ayanna Howard and Jason Borenstein. 2018. The ugly truth about ourselves and our robot creations: the problem of bias and social inequity. Science and engineering ethics, 24(5):1521–1536. Clayton J. Hutto and Eric Gilbert. 2014. VADER: A parsimonious rule-based model for sentiment analysis In Proceedings of the Eighth International Conference on Weblogs and Social Media, of social media text. ICWSM 2014, Ann Arbor, Michigan, USA, June 1-4, 2014. Aylin Caliskan Islam, Joanna J. Bryson, and Arvind Narayanan. 2016. Semantics derived automatically from language corpora necessarily contain human biases. CoRR, abs/1608.07187. Dan Jurafsky and James H. Martin. 2009. Speech and language processing: an introduction to natural language processing, computational linguistics, and speech recognition, 2nd Edition. Prentice Hall series in artificial intelligence. Prentice Hall, Pearson Education International. Toshihiro Kamishima, Shotaro Akaho, Hideki Asoh, and Jun Sakuma. 2012. Fairness-aware classifier with prej- udice remover regularizer. In Joint European Conference on Machine Learning and Knowledge Discovery in Databases, pages 35–50. Springer. Diederik P Kingma and Jimmy Ba. 2014. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. Jiwei Li, Michel Galley, Chris Brockett, Jianfeng Gao, and Bill Dolan. 2016. A diversity-promoting objective function for neural conversation models. In NAACL HLT 2016, The 2016 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, San Diego Califor- nia, USA, June 12-17, 2016, pages 110–119. Haochen Liu, Tyler Derr, Zitao Liu, and Jiliang Tang. 2019. Say what I want: Towards the dark side of neural dialogue models. CoRR, abs/1909.06044. Haochen Liu, Wentao Wang, Yiqi Wang, Hui Liu, Zitao Liu, and Jiliang Tang. 2020a. Mitigating gender bias for neural dialogue generation with adversarial learning. arXiv preprint arXiv:2009.13028. Haochen Liu, Zhiwei Wang, Tyler Derr, and Jiliang Tang. 2020b. Chat as expected: Learning to manipulate black-box neural dialogue models. arXiv preprint arXiv:2005.13170. Rowan Hall Maudslay, Hila Gonen, Ryan Cotterell, and Simone Teufel. 2019. It’s all in the name: Mitigating gender bias with name-based counterfactual data substitution. arXiv preprint arXiv:1909.00871. Ninareh Mehrabi, Fred Morstatter, Nripsuta Saxena, Kristina Lerman, and Aram Galstyan. 2019. A survey on bias and fairness in machine learning. CoRR, abs/1908.09635. Alexander H. Miller, Will Feng, Dhruv Batra, Antoine Bordes, Adam Fisch, Jiasen Lu, Devi Parikh, and Jason Weston. 2017. Parlai: A dialog research software platform. In Proceedings of the 2017 Conference on Empir- ical Methods in Natural Language Processing, EMNLP 2017, Copenhagen, Denmark, September 9-11, 2017 - System Demonstrations, pages 79–84. Jeffrey Pennington, Richard Socher, and Christopher Manning. 2014. Glove: Global vectors for word represen- tation. In Proceedings of the 2014 conference on empirical methods in natural language processing (EMNLP), pages 1532–1543. Marcelo O. R. Prates, Pedro H. C. Avelar, and Lu´ıs C. Lamb. 2018. Assessing gender bias in machine translation - A case study with google translate. CoRR, abs/1809.02208. Alan Ritter, Colin Cherry, and William B. Dolan. 2011. Data-driven response generation in social media. In Proceedings of the 2011 Conference on Empirical Methods in Natural Language Processing, EMNLP 2011, 27-31 July 2011, John McIntyre Conference Centre, Edinburgh, UK, A meeting of SIGDAT, a Special Interest Group of the ACL, pages 583–593. James A Rodger and Parag C Pendharkar. 2004. A field study of the impact of gender and user’s technical experience on the performance of voice-activated medical tracking application. International Journal of Human- Computer Studies, 60(5-6):529–544. Adam Rose. 2010. Are face-detection cameras racist? Time Business. Amrita Saha, Vardaan Pahuja, Mitesh M. Khapra, Karthik Sankaranarayanan, and Sarath Chandar. 2018. Com- plex sequential question answering: Towards learning to converse over linked question answer pairs with a knowledge graph. In Proceedings of the Thirty-Second AAAI Conference on Artificial Intelligence, (AAAI-18), the 30th innovative Applications of Artificial Intelligence (IAAI-18), and the 8th AAAI Symposium on Educa- tional Advances in Artificial Intelligence (EAAI-18), New Orleans, Louisiana, USA, February 2-7, 2018, pages 705–713. Iulian Vlad Serban, Alessandro Sordoni, Yoshua Bengio, Aaron C Courville, and Joelle Pineau. 2016. Building end-to-end dialogue systems using generative hierarchical neural network models. In Proceedings of the 30th AAAI Conference on Artificial Intelligence, pages 3776–3784. Iulian Serban, Alessandro Sordoni, Ryan Lowe, Laurent Charlin, Joelle Pineau, Aaron Courville, and Yoshua Bengio. 2017. A hierarchical latent variable encoder-decoder model for generating dialogues. In Proceedings of the 31st AAAI Conference on Artificial Intelligence. Lifeng Shang, Zhengdong Lu, and Hang Li. 2015. Neural responding machine for short-text conversation. In Pro- ceedings of the 53rd Annual Meeting of the Association for Computational Linguistics and the 7th International Joint Conference on Natural Language Processing of the Asian Federation of Natural Language Processing, ACL 2015, July 26-31, 2015, Beijing, China, Volume 1: Long Papers, pages 1577–1586. Ilya Sutskever, Oriol Vinyals, and Quoc V Le. 2014. Sequence to sequence learning with neural networks. In Advances in neural information processing systems, pages 3104–3112. Song¨ul Tolan, Marius Miron, Emilia G´omez, and Carlos Castillo. 2019. Why machine learning may lead to unfairness: Evidence from risk assessment for juvenile justice in catalonia. In Proceedings of the Seventeenth International Conference on Artificial Intelligence and Law, ICAIL 2019, Montreal, QC, Canada, June 17-21, 2019., pages 83–92. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. 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, pages 6000–6010. Marty J. Wolf, Keith W. Miller, and Frances S. Grodzinsky. 2017. Why we should have seen that coming: comments on microsoft’s tay ”experiment, ” and wider implications. SIGCAS Computers and Society, 47(3):54– 64. Sirui Yao and Bert Huang. 2017. Beyond parity: Fairness objectives for collaborative filtering. In Advances in Neural Information Processing Systems, pages 2921–2930. Muhammad Bilal Zafar, Isabel Valera, Manuel Gomez Rodriguez, and Krishna P. Gummadi. 2015. Fairness constraints: Mechanisms for fair classification. Jieyu Zhao, Tianlu Wang, Mark Yatskar, Vicente Ordonez, and Kai-Wei Chang. 2018a. Gender bias in coreference resolution: Evaluation and debiasing methods. CoRR, abs/1804.06876. Jieyu Zhao, Yichao Zhou, Zeyu Li, Wei Wang, and Kai-Wei Chang. 2018b. Learning gender-neutral word embed- dings. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, Brussels, Belgium, October 31 - November 4, 2018, pages 4847–4853. # A Appendix A. Full Lists of Gender, Race and Attribute Words In the appendix, we detail the 6 categories of words used in this study, i.e., gender words (male and female), race words (white and black) and attribute words including pleasant and unpleasant words, career and family words. # A.1 Gender Words The gender words consist of gender specific words that entail both male and female possessive words as follows: (gods - goddesses), (nephew - niece), (baron - baroness), (father - mother), (dukes - duchesses), ((dad - mom), (beau - belle), (beaus - belles), (daddies - mummies), (policeman - policewoman), (grandfather - grandmother), (landlord - landlady), (landlords - landladies), (monks - nuns), (stepson - stepdaughter), (milkmen - milkmaids), (chairmen - chairwomen), (stewards - stewardesses), (men - women), (masseurs - masseuses), (son-in-law - daughter-in-law), (priests - priestesses), (steward - stewardess), (emperor - empress), (son - daughter), (kings - queens), (proprietor - proprietress), (grooms - brides), (gentleman - lady), (king - queen), (governor - matron), (waiters - waitresses), (daddy - mummy), (emperors - em- presses), (sir - madam), (wizards - witches), (sorcerer - sorceress), (lad - lass), (milkman - milkmaid), (grandson - granddaughter), (congressmen - congresswomen), (dads - moms), (manager - manager- ess), (prince - princess), (stepfathers - stepmothers), (stepsons - stepdaughters), (boyfriend - girlfriend), (shepherd - shepherdess), (males - females), (grandfathers - grandmothers), (step-son - step-daughter), (nephews - nieces), (priest - priestess), (husband - wife), (fathers - mothers), (usher - usherette), (post- man - postwoman), (stags - hinds), (husbands - wives), (murderer - murderess), (host - hostess), (boy - girl), (waiter - waitress), (bachelor - spinster), (businessmen - businesswomen), (duke - duchess), (sirs - madams), (papas - mamas), (monk - nun), (heir - heiress), (uncle - aunt), (princes - princesses), (fiance - fiancee), (mr - mrs), (lords - ladies), (father-in-law - mother-in-law), (actor - actress), (actors - actresses), (postmaster - postmistress), (headmaster - headmistress), (heroes - heroines), (groom - bride), (business- man - businesswoman), (barons - baronesses), (boars - sows), (wizard - witch), (sons-in-law - daughters- in-law), (fiances - fiancees), (uncles - aunts), (hunter - huntress), (lads - lasses), (masters - mistresses), (brother - sister), (hosts - hostesses), (poet - poetess), (masseur - masseuse), (hero - heroine), (god - goddess), (grandpa - grandma), (grandpas - grandmas), (manservant - maidservant), (heirs - heiresses), (male - female), (tutors - governesses), (millionaire - millionairess), (congressman - congresswoman), (sire - dam), (widower - widow), (grandsons - granddaughters), (headmasters - headmistresses), (boys - girls), (he - she), (policemen - policewomen), (step-father - step-mother), (stepfather - stepmother), (wid- owers - widows), (abbot - abbess), (mr. - mrs.), (chairman - chairwoman), (brothers - sisters), (papa - mama), (man - woman), (sons - daughters), (boyfriends - girlfriends), (he’s - she’s), (his - her). # A.2 Race Words The race words consist of Standard US English words and African American/Black words as follows: (going - goin), (relax - chill), (relaxing - chillin), (cold - brick), (not okay - tripping), (not okay - spazzin), (not okay - buggin), (hang out - pop out), (house - crib), (it’s cool - its lit), (cool - lit), (what’s up - wazzup), (what’s up - wats up), (what’s up - wats popping), (hello - yo), (police - 5-0), (alright - aight), (alright - aii), (fifty - fitty), (sneakers - kicks), (shoes - kicks), (friend - homie), (friends - homies), (a lot - hella), (a lot - mad), (a lot - dumb), (friend - mo), (no - nah), (no - nah fam), (yes - yessir), (yes - yup), (goodbye - peace), (do you want to fight - square up), (fight me - square up), (po po - police), (girlfriend - shawty), (i am sorry - my bad), (sorry - my fault), (mad - tight), (hello - yeerr), (hello - yuurr), (want to - finna), (going to - bout to), (That’s it - word), (young person - young blood), (family - blood), (I’m good - I’m straight), (player - playa), (you joke a lot - you playing), (you keep - you stay), (i am going to - fin to), (turn on - cut on), (this - dis), (yes - yasss), (rich - balling), (showing off - flexin), (impressive - hittin), (very good - hittin), (seriously - no cap), (money - chips), (the - da), (turn off - dub), (police - feds), (skills - flow), (for sure - fosho), (teeth - grill), (selfish - grimey), (cool - sick), (cool - ill), (jewelry - ice), (buy - cop), (goodbye - I’m out), (I am leaving - Imma head out), (sure enough - sho nuff), (nice outfit - swag), (sneakers - sneaks), (girlfiend - shortie), (Timbalands - tims), (crazy - wildin), (not cool - wack), (car - whip), (how are you - sup), (good - dope), (good - fly), (very good - supafly), (prison - pen), (friends - squad), (bye - bye felicia), (subliminal - shade). # A.3 Career and Family Words Career Words. The career words consist of words pertain to careers, jobs and businesses: academic, accountant, administrator, advisor, appraiser, architect, baker, bartender, business, career, carpenter, chemist, clerk, company, corporation, counselor, educator, electrician, engineer, examiner, executive, hairdresser, hygienist, industry, inspector, instructor, investigator, janitor, lawyer, librarian, machinist, management, manager, mechanic, nurse, nutritionist, occupation, office, officer, paralegal, paramedic, pathologist, pharmacist, physician, planner, plumber, practitioner, professional, program- mer, psychologist, receptionist, salary, salesperson, scientist, specialist, supervisor, surgeon, technician, therapist, veterinarian, worker. Family Words. The family words consist of words refer to relations within a family or group of people. adoption, adoptive, birth, bride, bridegroom, brother, care-giver, child, children, clan, cousin, dad, date, daughter, devoted, divorce, engaged, engagement, estranged, family, father, fiancee, folk, foster, grand- daughter, grandfather, grandma, grandmother, grandpa, grandson, groom, guest, heir, heiress, helpmate, heritage, house, household, husband, in-law, infancy, infant, inherit, inheritance, kin, kindergarten, kin- dred, kinfolk, kinship, kith, lineage, mama, marriage, married, marry, mate, maternal, matrimony, mom, mother, natal, newlywed, nuptial, offspring, orphan, papa, parent, pregnant, relative, separation, sibling, sister, son, spouse, tribe, triplet, twin, wed, wedding, wedlock, wife. # A.4 Pleasant and Unpleasant Words Pleasant words. The pleasant words consist of words often used to express positive emotions and scenarios as follows: awesome, awesomeness, beautiful, caress, cheer, dear, delicious, diamond, diploma, dream, enjoy, en- joyed, enjoying, excited, family, fantastic, free, freedom, friend, fun, gentle, gift, great, happy, health, heaven, honest, honestly, honor, joy, kind, laughing, laughter, love, lovely, loyal, lucky, miracle, paradise, peace, peaceful, pleasure, pretty, rainbow, respectful, rich, safe, sunrise, sweet, thank, thanks, truth, understand, vacation, winner, wonderful. Unpleasant Words. The unpleasant words consist of words often used to express negative emotions and scenarios as follows: abuse, accident, agony, ass, assault, awful, bad, bitch, cancer, crash, crime, damn, dead, death, die, disaster, divorce, evil, failure, fake, filth, fuck, fucking, grief, hatred, horrible, idiot, ill, jail, jerk, kill lie, mad, murder, nasty, nigga, poison, pollute, poverty, prison, pussy, rape, rotten, shit, sick, sickness, sore, stink, sucker, terrible, tragedy, trash, ugly, violence, vomit, war, worry, wrong, wtf.
Title: On the Properties of the Softmax Function with Application in Game Theory and Reinforcement Learning: Summary: In this paper, we utilize results from convex analysis and monotone operator theory to derive additional properties of the softmax function that have not yet been covered in the existing literature. In particular, we show that the softmax function is the monotone gradient map of the log-sum-exp function. By exploiting this connection, we show that the inverse temperature parameter determines the Lipschitz and co-coercivity properties of the softmax function. We then demonstrate the usefulness of these properties through an application in game-theoretic reinforcement learning. # On the Properties of the Softmax Function with Application in Game Theory and Reinforcement Learning Bolin Gao and Lacra Pavel Abstract—In this paper, we utilize results from convex analysis and monotone operator theory to derive additional properties of the softmax function that have not yet been covered in the existing literature. In particular, we show that the softmax function is the monotone gradient map of the log-sum-exp function. By exploiting this connection, we show that the inverse temper- ature parameter λ determines the Lipschitz and co-coercivity properties of the softmax function. We then demonstrate the usefulness of these properties through an application in game- theoretic reinforcement learning. # I. INTRODUCTION The softmax function is one of the most well-known func- tions in science and engineering and has enjoyed widespread usage in fields such as game theory [1], [2], [3], reinforcement learning [4] and machine learning [5], [6]. From a game theory and reinforcement learning perspective, the softmax function maps the raw payoff or the score (or Q-value) associated with a payoff to a mixed strategy [1], [2], [4], whereas from the perspective of multi-class logistic regression, the softmax function maps a vector of logits (or feature variables) to a posterior probability distribution [5], [6]. The broader engineering applications involving the softmax function are numerous; interesting examples can be found in the fields of VLSI and neuromorphic computing, see [35], [36], [37], [39]. The term “softmax” is a portmanteau of “soft” and “argmax” [5]. The function first appeared in the work of Luce [12], although its coinage is mostly credited to Bridle [13]. Depending on the context in which the softmax function appears, it also goes by the name of Boltzmann distribution [1], [4], [34], Gibbs map [22], [46], logit map, logit choice tule, logit response function [1], [2], [3], [19], [14], [23], [57] or (smooth) perturbed best response function [44], [56]. The reader should take care in distinguishing the softmax function used in this paper from the log-sum-exp function, which is often also referred to as the “softmax” (since the log-sum-exp is a soft approximation of the vector-max function [7], [24]). There are many factors contributing to the wide-spread usage of the softmax function. In the context of reinforcement learning, the softmax function ensures a trade-off between ex- ploitation and exploration, in that every strategy in an agent’s possession has a chance of being explored. Unlike some other choice mechanisms such as e-greedy [4], the usage of softmax selection rule1 is favorably supported by experimental literature in game theory and reinforcement learning as a plausible model for modeling real-life decision-making. For instance, in [20], the authors noted that the behavior of mon- keys during reinforcement learning experiments is consistent with the softmax selection rule. Furthermore, the input-output behavior of the softmax function has been compared to lateral inhibition in biological neural networks [5]. For additional discussions on the connections between softmax selection rule and the neurophysiology of decision-making, see [30], [31], [32], [33]. From the perspective of game theory, the softmax function characterizes the so-called “logit equilibrium”, which accounts for incomplete information and random perturbation of the payoff during gameplay and has been noted for having better versatility in describing the outcomes of gameplay as compared to the Nash equilibrium [3], [14]. learning softmax rule strategy Fig. 1: High-level representation of a game-theoretic multi-agent reinforcement learning scheme with the softmax selection rule. In this learning scenario, the players each choose some strategy, play the game and receive real-valued payoffs. The players then use some learning rule to independently convert the payoffs into scores. Finally, each player uses the softmax to select the next strategy. Despite the intuitions that researchers have acquired with respect to the usage of the softmax function, it is apparent that the understanding of its mathematical properties is still lacking. For instance, in the analysis of stateless multi-agent reinforcement learning schemes (Figure 1), when the action selection rule is taken as the softmax function, is of interest which, if any, properties of softmax can allow us to conclude convergence of the learning algorithm towards a solution of the game (e.g., a Nash or logit equilibrium). Although the desired properties that can be used to conclude such convergence are fairly mundane, virtually no reference to these properties can be found within the existing body of literature. With regard to applications in the context of B. Gao and L. Pavel are with the Department of Electrical and Computer Engineering, University of Toronto, Toronto, ON, M5S bolin.gao@mail.utoronto.ca, 3G4, pavel@ece.utoronto.ca 1In this paper, we refer to the softmax function interchangeably as the softmax operator, softmax map, softmax choice, softmax selection rule, or simply, the softmax. 1 reinforcement and machine learning, the adjustment of the temperature constant of the softmax function is still performed on a rule-of-thumb basis. It has also been briefly speculated in [42] that proper adjustment of the temperature constant can be used for game-theoretic reinforcement learning algorithms to achieve higher expected payoff. Therefore, an adaptive mechanism for scheduling the temperature constant would be desirable for many applications. Clearly, these questions can only be affirmatively answered by uncovering new properties of the softmax function. The goal of this paper is to expand on the known mathe- matical properties of the softmax function and demonstrate how they can be utilized to conclude the convergence of learning algorithm in a simple application of game-theoretic reinforcement learning. For additional examples and more involved applications, see our related paper [21]. We perform our analysis and derive new properties by using tools from convex analysis [7], [24] and monotone operator theory [25], [26]. It has been known that stateless multi-agent reinforce- ment learning that utilizes the softmax selection rule has close connections with the field of evolutionary game theory [9], [10], [22], [23], [54], [20], [58]. Therefore, throughout this paper, we motivate some of the results through insights from the field of evolutionary game theory [15], [16], [17]. It is our hope that researchers across various disciplines can apply our results presented here to their domain-specific problems. The organization of this paper is as follows. Section II intro- duces notation convention for the rest of the paper. Section III introduces the definition of the softmax function, its different representations as well as a brief survey of several of its known properties from the existing literature. Section IV provides the background to convex optimization and monotone operator theory. In Section V, we derive additional properties of the softmax function. Section VI provides an analysis of a stateless continuous-time score-based reinforcement learning scheme within a single-player game setup to illustrate the application of these properties. Section VII provides the conclusion and some open problems for further investigation. # II. NOTATIONS The notations used in this paper are as follows: ¢ The p-norm of a vector is denoted as || - ||), 1 « The n — 1 dimensional unit simplex is denoted where, AP“! := {x € R"|||x||, = 1,2; > O}. The (relative) interior of A"! is denoted . ≤ ∞ < p< ≤ « The n — 1 dimensional unit simplex is denoted by A”~1, where, AP“! := {x € R"|||x||, = 1,2; > O}. « The (relative) interior of A"! is denoted by int(A”~!), where, int(A"~1) := {x € R"|||x||1 = 1,2; > O}. # x { int(A"~1) := {x € R"|||x||1 = 1,2; > O}. R” denotes the i canonical basis of R”, eg., e; = # x { . 1 = 1, xi > 0 } ∈ e e; € R” denotes the i canonical basis of R”, [0,...,1,...,0] T where 1 occupies the i position. + The vector of ones is denoted as 1 := [1,...,1] " vector of zeros is denoted as 0 := [0, eey 0] - # and the • Matrices are denoted using bold capital letters such as A. In general, a vector in the unconstrained space Rn will be denoted using z, while a vector in the n 1 dimensional unit simplex will be denoted using x. All logarithms are assumed to be base e. 2 # III. REVIEW OF THE SOFTMAX FUNCTION AND ITS KNOWN PROPERTIES While the softmax function may take on different appear- ances depending on the application, its base model is that of a vector-valued function, whose individual component consists of an exponential evaluated at an element of a vector, which is normalized by the summation of the exponential of all the elements of that vector. In this section, we present several well- known and equivalent representations of the softmax function, and review some of its properties that are either immediate based on its definition or have been covered in the existing literature. A. Representations of the Softmax function The most well-known and widely-accepted version of the softmax function is as follows [5], [37], [40], [41], [43], [59]. Definition 1. The softmax function is given by σ : Rn int(∆n−1), exp(A2z1) o(z) = a : A>, (1) Xo exp(Az;) exp(AzZn) j=l where λ is referred to as the inverse temperature constant. Remark 1. The softmax function is commonly presented in the literature as the individual components of (1), oi(2) = exp(Az;) a sis SY exp(Az;) j=l i<n. (2) When A = 1, we refer to (1) as the standard softmax function. As X —> 0, the output of o converges point- wise to the center of the simplex, i.e., a uniform probability distribution. On the other hand, as A — oo, the output of a converges point-wise to e; € R", where j = argmax e; z, 1<i<n provided that the difference between two or more components of z is not too small [23], [37]. We note that elsewhere in the literature, the reciprocal of A is also commonly used. Remark 2. In R?, (2) reduces to the logistic function in terms of 2 — 25, exp(Az;) 1 oi(2) IF exp(λzi) exp(λzi) + exp(λzj) 1 λ(zi − = 1 + exp( zj)) − , j = i. (3) Furthermore, we note that (2) can be equivalently represented as, oi(z) = exp(Az; — log(j 1 exp(Az;)))- (4) # σi(z) = exp(λzi − While (4) is seldom used as a representation of the softmax function, the author noted that (4) represents an exponential family, which is the solution of the replicator dynamics of evolutionary game theory [2], [16], [17]. We will expand on the connections between the replicator dynamics and the softmax function in section V. log-sum-exp negative entropy softmax (1st component) softmax (2nd component) tf Y tttjj;};}3}/4 \ \ \ WH — LA; Fig. 2: Plots of the log-sum-exp, negative entropy and both components of softmax function over R2 with λ = 1. The red curve on the negative entropy plot is the restriction of the negative entropy over the 1-dimensional simplex, ∆1. Another important representation of the softmax function can be derived by considering the “argmax function” under entropy regularization.” Let z € R", and consider the argmax of «'z over the simplex, M(z) = argmax a! z. weAn-} (5) over int(A”~!) [48], by strong concavity of the argument of (6), it can be shown that by invoking the Karush-Kuhn-Tucker (KKT) conditions, the unique maximizer of (6) is the softmax function evaluated at z € R”, ie., n argmax [a' z— 7! > x; log(ax;)] = o(z). weAnr-t j=l (8) ∈ λ−1 When there is a unique largest element in the vector z, it is clear that M returns the basis vector corresponding to the entry of that element, that is, M(z) = ej, where j = argmax ez. This solution corresponds to a vertex of 1<i<n the simplex. In general, however, (5) is set-valued; to see this, simply consider the case where two or more components of z are equal. For many learning related applications, it is highly desirable for M (z) to be singled-valued [22], [23], [41], [49], [50]. The most common approach to achieve this is by employing a so-called regularizer function ψ to (5), which yields the regularized argmax function:3 M(z) = argmax [alz-w wear} ))- (6) It has been noted in [20], [39], [51], [52] that the argument of the left-hand side of (8), n a'z—X1Y a; log(x;), ja (9) represents the so called “free energy” in statistical thermo- dynamics. In light of this connection, from a game-theoretic perspective, the softmax function can be thought of as pro- viding the mixed strategy with the maximum entropy which maximizes the payoff of a game [20]. It is also worth noting that the maximum of (9) over the simplex is by definition the Legendre-Fenchel transform of the negative entropy function [24, p. 102], also commonly referred to as the log-sum-exp function, which is given by lse : Rn A common choice of the regularizer is the negative entropy function restricted to the simplex, which under the convention 0 log(0) = 0, is given by ψ : Rn → ∪ { ∞} n A“? Y a; log(xzj),A>0 xe Art ja (7) +00 cg An}. (7) → ∞} lse(z) := λ−1 log( ∪ { n Ise(z) = d-Hog(3o exp(Az;)),A > 0. j=l (10) When λ = 1, we refer to (10) as the standard log-sum-exp function. It is well-known that the log-sum-exp is an approximation to the vector-max function [7, p. 72], [24, p. 27], When λ = 1, we refer to (7) as the standard negative entropy function. Since negative entropy is λ−1-strongly convex4 in 2As pointed out in [5, p. 182], the softmax function is a soft approximation of the argmax function, z ++ argmax a! z, not that of the “max” function. 2eEAn-1 the regularizer is also referred to as an admissible deterministic perturbation [2, p. 189], penalty function [22], [23], smoothing function [44] or Bregman function [48]. For detailed construction of the regularizer, see [22], [23], [47]. 4Recall that a function f is jz-strongly convex in ||-||,, if there exists 4 > 0, st. f(0z+(1—0)2') < Of (z)+ (1-49) f(z’) -— Koa —A)\lz— 2! ||2 for all z,z' € dom f and 6 € [0,1]. f is -strongly concave if —f is p-strongly convex. || ||1 vecmax(z) := max . z1, . . . , zn} { Rn, vecmax(z) That is, for any z € R"”, vecmax(z) < Ise(z) < vecmax(z) +7! log(n), which can be shown by considering n. exp(A vecmax(z)) < > exp(Az;) < nexp(A vecmax(z)). =1 Due to this reason, the log-sum-exp is sometimes referred to as the “softmax function” in optimization-oriented literature. We note that the dual or convex conjugate of the log- sum-exp function (10) is the negative entropy restricted to the simplex, given by (7) [7, p. 93][24, p. 482][52]. We illustrate the log-sum-exp function as well as the negative entropy and the softmax function in Figure 2. By Fenchel- 3 Young inequality, the log-sum-exp function is bounded below by a linear function, Ise(z) > x! z— W(x), V2 € A"1,2 ER”. (11) ≥ − ∀ ∈ ∈ Further consequences of the duality between the negative entropy and the log-sum-exp function as well as its role in this time. Interested game theory will not be explored at readers may refer to [38], [52] or any standard textbooks on convex analysis, for example, [7], [24], [28]. Finally, we provide a probabilistic characterization of the softmax function. Let €;,i € {1,...,n} be independent and identically distributed random variables with a Gumbel distribution given by, Pre < ¢] = exp(—exp(—Ae — 9), (12) 0.57721 is the Euler-Mascheroni constant. It can − − − where γ be shown that for any vector z ≈ Rn [2, p. 194][19], ∈ Pr (13) i = argmax z; + | =0;(z). 1<j<n In game theory terms, (13) represents the probability of choosing the pure strategy that maximizes the payoff or score Rn, after the payoff or score has been perturbed by a z stochastic perturbation. B. Properties of the Softmax - State of the Art We briefly comment on some properties of the softmax function that are either immediate or have been covered in the existing literature. First, 0 maps the origin of R” to the barycenter of A"~1, that is, 7(0) = n~11. The softmax func- tion o is surjective but not injective, as it can easily be shown that for any z, z+c1 € R”, Vc € R, we have o(z+c1) = o(z). By definition, ||o(z)||) = o(z)'1=1,Vz eR". In a recent paper, the authors of [43] noted that σ(P(z)) = Pσ(z), where P is any permutation matrix, and that the standard softmax function satisfies a type of “coordinate non- Rn, and expansiveness” property, whereby given a vector z ∈ 1 zi, then 0 suppose that zj ≥ zi). (zj − 2 ≤ The last property can be derived by exploiting the properties of the hyperbolic tangent function. It was also noted that these properties of the softmax function bear similarities with the Euclidean projection onto ∆n−1 [43]. In a direction that is tangential to the aim of this paper, the authors of [40] is interested in finding a bound on the softmax function. It can be shown that, n exp(Azi) 1 = n exp(Azi) 1 oi(z) = 2 » (4) a Lh TFexp(-ney — 2% Bends) ee erOG aM where (14) is referred as “one-vs-each” bound, which can be generalized to bounds on arbitrary probabilities [40]. From (3), we see that this inequality is tight for n = 2. 4 IV. REVIEW OF CONVEX OPTIMIZATION AND MONOTONE OPERATOR THEORY In this section we review some of the definitions and results from convex optimization and monotone operator theory that will be used in the derivation of new properties of the softmax function. Since the following definitions are standard, readers who are familiar with these subjects can skip this section without any loss of continuity. Most of the proofs of the propositions in this section can be found in references such as [7], [24], [25], [26], [27], [28]. Throughout this section, we assume that R” is equipped with the standard n inner product (z,2’) == >> 22; with the induced 2-norm i=l (z,2’) /(z,z). C? lzll2 == /(z,z). We assume the domain of f, dom f, is convex. C1, C? denote the class of continuously-differentiable and twice continuously-differentiable functions, respectively. Rn R is convex if, Definition 2. A function f : dom f ⊆ F(“), f(0z + (1—8)2") < Of (2) + (1-9) F(“), (15) # − dom f and θ ≤ − for all z, z’ € dom f and @ € [0,1] and strictly convex if (15) holds strictly whenever z 4 z’ and 6 € (0,1). ∈ The convexity of a C 2 function f is easily determined through its Hessian 2f . ∇ Lemma 1. Let f be C 2. Then f is convex if and only if dom f is convex and its Hessian is positive semidefinite, that is, for all z ∈ ∈ # ol ol V? f(z)u > 0, (16) ∇ 2f (z) is positive definite for all z ≥ and strictly convex if dom f . ∇ ∈ Next, we introduce the concept of a monotone operator and its related properties. A monotone operator is usually taken as a set-valued relation, however, it is also natural for the definitions related to a monotone operator to be directly applied to single-valued maps [26]. Definition 3. ([26, p. 154]) An operator (or mapping) F : Rn Rn is said to be: if, D ⊆ • pseudo monotone on → D 0 = F(z’)"(2-2)>0 = F(z)"(2-2) >0,Vz,2' €D. (17) • pseudo monotone plus on and, D if it is pseudo monotone on D F(z')"(z—2') > O and F(z)'(z—2/) =0 18 => F(z) = F(z’),Vz,2' € D. (18) # ⇒ • monotone on # ∈ D if, if, # D (F(z) — F(2’)) (2-2) >0,Vz,2°€D. (19) F(2’)) (2-2) >0,Vz,2°€D. if it is monotone on D # − • monotone plus on − ≥ ∈ D and, monotone plus on D if it is monotone on D and, (z-2') =0 # D (F(z2)-F(2’)) (z-2') =0 = F(z) = F(z’), Vz,2' €D. (20) . • strictly monotone on if, F(2’))"(2-2/) (F(z) — F(2’))"(2-2/) > 0,Vz,2° €D,z #2’. 2D 0,Vz,2° − − # ∈ D Clearly, strictly monotone implies monotone plus, which in turn implies monotone, pseudo monotone plus and pseudo monotone. By definition, every strictly monotone operator is an injection. We refer to an operator F as being (strictly) anti-monotone if F is (strictly) monotone. The following proposition provides a natural connection between C 1, convex functions and monotone gradient maps. Lemma 2. A C 1 function f is convex if and only if (Viz) - VE“) (2-2) > 0,Vz,2' €domf, (22) 0,Vz,2' ( ∇ − ∇ − ≥ ∈ and strictly convex if and only if, (Vi (2) — VF(2)) (2-2) > 0,Vz, 2’ € dom f,z £2’. (23) Next, we introduce the notions of Lipschitz continuity and the two concepts are related co-coercivity, and show that through the gradient of a convex function. Definition 4. An operator (or mapping) F : is said to be D ⊆ Rn → Rn • Lipschitz (or L-Lipschitz) if there exists a L > 0 such that, |F(2) — Flo < Llle - 2'll2,Vz,2' € D. (24) # Flo # Llle − ≤ − # ∈ D If L = 1 in (24), then F is referred to as nonexpansive. (0, 1), then F is referred to as contractive. Otherwise, if L ∈ • co-coercive (or 1 L -co-coercive) if there exists a L > 0 such that, 1 5 . ∈ D (25) If L = 1 in (25), then F is referred to as firmly nonexpan- sive. L -co-coercive oper- ator is L-Lipschitz, in particular, every firmly nonexpansive operator is nonexpansive. However, the reverse need not be z is nonexpansive but not firmly true, for example f (z) = nonexpansive. Fortunately, the Baillon-Haddad theorem ([27, p. 40], Theorem 3.13) provides the condition for when a L- Lipschitz operator is also 1 Theorem 1. (Baillon-Haddad theorem) Let f : dom f Rn ⊆ R be a C 1, convex function on dom f and such that f is → f is L-Lipschitz continuous for some L > 0, then -co-coercive. ∇ ∇ 1 L Finally, we will introduce the notion of maximal monotonic- ity. Let H : R" — 2®" be the set-valued map, where 2°” denotes the power set of R”. Let the graph of H be given by graH := {(u,v) € R" x R"|v = Hu}. The set-valued map H is said to be monotone if (u—u')'(v—v') > 0,v€ H(u),v' € H(u’). ∈ (22) (23) 5 Definition 5. ([25, p. 297]) Let H : Rn be monotone. Then H is maximal monotone if there exists no monotone operator G : Rn such that gra G properly contains gra H, i.e., for every (u, v) ∈ # × gra H) (u (u,v) € gra & (V(u',v') € graH) (u—w')'(v—v’) > 0. (26) By Zorn’s Lemma, every monotone operator can be ex- tended to a maximal monotone operator [24, p. 535], [25, p. 297]. For the scope of this paper, we are interested when a single-valued map is maximal monotone. The following proposition provides a simple characterization of this result [24, p. 535]. Lemma 3. If a continuous mapping F : Rn Rn is mono- tone, it is maximal monotone. In particular, every differentiable monotone mapping is maximal monotone. V. DERIVATION OF PROPERTIES OF SOFTMAX FUNCTION In this section we derive several properties of the softmax function using tools from convex analysis and monotone op- erator theory introduced in the previous section. We begin by establishing the connection between the log-sum-exp function and the softmax function. It has long been known that the softmax function is the gradient map of a convex potential function [37], however, the fact that its potential function is the log-sum-exp function (i.e., (10)) is rarely discussed.5 We make this connection clear with the following proposition. Proposition 1. The softmax function is the gradient of the log-sum-exp function, that is, σ(z) = ∇ Proof. Evaluating the partial derivative of lse at each compo- exp(λzi) j=1 exp(λzj) gradient, we have, Olse(z) exp() Ox 1 Vise(2)=] : |=az—~—] : | =o). lse(z exp(Az; a se) X (Az) exp(Azn) O2n ∇ Next, we calculate the Hessian of the log-sum-exp function (and hence the Jacobian of the softmax function). Proposition 2. The Jacobian of the softmax function and Hessian of the log-sum-exp function is given by: J[o(z)] = V? lse(z) = A(diag(o(z)) — o(z)o(z)"), (27) ∇ − where (27) is a symmetric positive semidefinite matrix and satisfies J[σ(z)]1 = 0, that is, 1 is the eigenvector associated with the zero eigenvalue of J[σ(z)]. 5Although not explicitly stated, this relationship could also be found in [7, p. 93] and various other sources. Proof. The diagonal entries of 2 lse are given by, n A Jexp(Az) 2 exp(Az;) — exp(Azi)? 0? Ise(z) j=l awe a ; oF (22 exp(23))? j= and the off-diagonal entries of partials, ∇ 2 lse are given by the mixed 0? Ise(z) _ —Aexp(Azp) exp(Azi) O08 (3 exp (zi)? j=l Assembling the partial derivatives, we obtain the Hessian of lse and the Jacobian of σ: J[o(z)] = V? Ise(z) = A(diag(o(z)) — o(z)o(z)"). (28) ∇ − The symmetry of J[σ(z)] comes from the symmetric struc- ture of the diagonal and outer product terms. The positive semi-definiteness of J[σ(z)] follows from an application of the Cauchy-Schwarz inequality [7, p. 74]. It can be shown through direct computation that J[σ(z)]1 = 0 or alternatively refer to [2, p. 213]. Remark 3. This result was previous noted in references such as [37], [38] and can be found in [2, p. 195][7, p. 74]. As a trivial consequence of Proposition 2, we can write the individual components of J[σ(z)] as, σj(z)), (29) Jij[σ(z)] = λσi(z)(δij − where δij is the Kronecker delta function. This representation is preferred for machine learning related applications and is loosely referred to as the “derivative of the softmax” [11]. Remark 4. Using the Jacobian of the softmax function given in (27), we provide the following important observation that connects the field of evolutionary game theory with convex analysis and monotone operator theory. Let x = σ(z), then we have, Vv? Ise(z)|,-4(2) = A(diag(x) — ax"). (30) Vv? Ise(z)|,-4(2) = A(diag(x) — ax"). (30) We note that this is precisely the matrix term appearing in the replicator dynamics [2, p. 229], [45], that is, & = V" lse(z)| u = A(diag(x) — 2a! )u, (31) 2=0(2) − ∇ ∆n−1 is a mixed strategy and u Rn is a payoff where x vector. We note that the matrix term was referred to as the replicator operator in [56]. To the best of our knowledge, the implications of this connection has not been discussed in the evolutionary game theory community. Lemma 4. The log-sum-exp function is C 2, convex and not strictly convex on Rn. The convexity of the log-sum-exp function is well-known [7] and follows from Proposition 2. To show that log-sum-exp is not strictly convex, take z and z +c1, where z then, ∈ Rn, c ∈ R, lse(z + c1) = lse(z) + c. (32) Thus, lse is affine along the line given by z+c1, which implies that the log-sum-exp function is not strictly convex. This result is also noted in [24, p. 48]. Proposition 3. The softmax function is monotone, that is, (o(2) -o(2')) (2-7) 20,¥z,2° ER", (33) 20,¥z,2° − and not strictly monotone on Rn. − ≥ ∈ Proof. Monotonicity of σ follows directly from the convexity of the log-sum-exp function. Since the log-sum-exp function is not strictly convex on Rn, therefore by Lemma 2, σ fails to be strictly monotone. Alternatively, since every strictly monotone operator is injective, therefore σ is not strictly monotone on Rn. The monotonicity of σ allows us to state a stronger result. Corollary 1. The softmax function is a maximal monotone operator, that is, there exists no monotone operator such that its graph properly contains the graph of the softmax function. Proof. This directly follows from σ being a continuous, mono- tone map, see Lemma 3. Next, we show that under appropriate conditions, the soft- max function is a contraction in 2. Lemma 5. ([8, p. 58], Theorem 2.1.6) A C 2, convex function f : Rn R has a Lipschitz continuous gradient with Lipschitz constant L > 0 if for all z, v ∈ 2f (z)v 0<vu! V?f(z)u < Llv|l3. (34) 0 ≤ ∇ ≤ Proposition 4. The softmax function is L-Lipschitz with re- spect to || \|2 with L = 4, that is, for all z,z' € R", ∈ llo(z) — o(2’)Il2 S Alle = 2'lla, (35) o(2’)Il2 llo(z) — o(2’)Il2 S Alle = 2'lla, where is the inverse temperature constant. # llo(z) ≤ − Proof. Given the Hessian of lse in Proposition 2, we have for all z, v ∈ v! V? Ise(z)v = veoi(z) — (oS vj0i(z))?). (36) Since the second term on the right hand side of (36) is nonnegative, therefore, n n vl VW? Ise(z)u <A) v?0;(z) < Asupf{ai(z)} Ov? i=l i=l = v0! V? Ise(z)u < Alful|3. (37) < Alful|3. {1,...,n},Vz ⇒ ∇ = 1, Rn. By 2 lse(z) is positive semidefinite. Hence using where sup Lemma 4, Lemma 1 and (37), we have, σi(z) { ∇ , } z ∀ i ∀ } ∈ ∈ { 0<v' V? Ise(z)u < Allull3. (38) 0<v' V? Ise(z)u < By Lemma 5, a is Lipschitz with L = 2. ≤ ∇ ≤ 6 | We note that Proposition 4 can also be established by using Theorem 4.2.1. in [28, p. 240], which resorts to using duality between the negative entropy and the log-sum-exp function. As a minor consequence of Proposition 4, by the Cauchy- Schwarz inequality, we have, (o(2) —o(2')) "(@- 2) <All 2/18. 9) − L -co-coercive with ∈ 2 2, 1 Corollary 2. The softmax function is ;-co-coercive with respect to ||- ||2 with L = 4, that is, for all z,z' € R", (o(2) = o(2")) "(2 = 21) 2 5 llo(2) — 0218, (40) where λ is the inverse temperature constant. Proof. Follows directly from Baillon - Haddad Theorem, see Theorem 1. Proposition 4 and Corollary 2 show that the inverse tem- perature constant λ is crucial in determining the Lipschitz and co-coercive properties of the softmax function. We summarize 2 in the following corollary. these properties with respect to Corollary 3. The softmax function is λ-Lipschitz and 1 coercive for any λ > 0, in particular, • Nonexpansive and firmly nonexpansive for λ = 1, • Contractive for λ (0, 1), ∈ where λ is the inverse temperature constant. $-co- Finally, we state an additional consequence of σ being a Lipschitz, monotone operator with a symmetric Jacobian matrix over all of Rn. Corollary 4. The softmax function is monotone plus, pseudo monotone plus and pseudo monotone on Rn. Proof. This follows from the chain of implications in [26, p. 164]. VI. APPLICATION IN GAME-THEORETIC REINFORCEMENT LEARNING Fig. 3: Feedback representation of the exponentially-discounted rein- forcement learning scheme (EXP-D-RL). In this section we demonstrate an application of these new properties of the softmax function in the context of stateless continuous-time reinforcement learning in finite games. For clarity and ease of notation, we perform our analysis in a single-player setup. For extension to N -player games, higher- order extension, and addition simulations, refer to our related 7 paper [21]. For other related work in this direction, see [22], [23], [46]. Consider a game G with a single player. We note that type of game is also known as “play against nature” and is identifiable with single-population matching in population games [2]. The player is equipped with an action set A = {1,...,n} and continuous payoff function / : A — R. A mixed strategy profile is given by 7 = [z1, see 2)! € A”—!. The player’s expected payoff of using x is given by, U(x) = So aii(z) =«x'U(x), i€A # U where u = U(x) = [Ui ' € R” is referred to the payoff vector at x. ..Un Starting at t = 0, we assume that the player repeatedly interacts with the game and aggregates his raw payoff u = Rn via the U (x) ∈ learning rule, # t t zi(t) =e *2i(0) + [> war, Vie A, i 4) R is the payoff to the ith strategy where ui = Ui(x) R is the score variable associated with the ith and zi ∈ strategy. This form of aggregation as given by (41) is known as exponentially-discounted learning rule, under which the player allocates exponentially more weight to recent observations of the payoff [22], [23]. Taking the time derivative of (41) yields the score dynamics, zi, (42) # ˙zi = ui − i ∀ , ∈ A We refer to (42) as the exponentially-discounted score dy- namics, a set of differential equations whose solutions capture the evolution of the player’s scores over time. This form of score dynamics was investigated in [20], [22], [54], [57]. Since Ui(x) is continuous over a compact domain, therefore there ex- ∆n−1. ists some constant M > 0 such that x ∀ Then it can be shown using standard arguments that | ≤ is max } a compact, positively invariant set (solution remains in Ω for all time). We can express (42) using stacked-vector notation as, ˙z = u z, (43) − where z = [z,.. en] Suppose that the score variable z is mapped to the strategy x from the softmax selection rule, ie., x = o(z), then the payoff vector can be written as u = U(x) = U(o(z)). Expressing the composition between the softmax selection rule with the payoff vector as U o o(z) := U(o(z)), then we can also write (43) as, ˙z = (U σ)(z) z. (44) − The overall exponentially-discounted reinforcement learning scheme (EXP-D-RL) can be represented as a closed-loop n identity feedback system in Figure 3, where In is the n × 1 s + 1 is the transfer C. The closed-loop system matrix, function of (42) from ui to zi, s is equivalently represented by, is the Kronecker product, and ⊗ ∈ ˙z = u z, u = U (x), x = σ(z). − (45) From (44), we see that the equilibria of the overall closed- loop system (45) are the fixed points of the map z ++ (Uo a)(z). This fixed-point condition can be restated as, £=0 > T=", uw =U(Z"), a* =0(2"). (46) £=0 > T=", The existence of the fixed point is guaranteed by the Brouwer’s Fixed Point Theorem provided that U oa is a continuous function with bounded range [57]. Since 2* = u*, therefore the fixed point Z* is mapped through o to a logit equilibrium [14], [22]. Proposition 5. Z* = o(Z*) = o(U*) is the logit equilibrium of the game G. # G Hence, the convergence of the solution of the score dynam- ics z(t) towards the fixed point of U σ implies convergence of the induced strategy x(t) = σ(t) towards a logit equilibrium point x∗ of the game. In the following, we provide different assumptions on the payoff function U or the composition between the payoff function and the softmax operator U σ under which the induced strategy converges. For background on dynamical systems and Lyapunov theory, see [55]. This analysis was inspired by [57]. the co-coercive property of the soft- max function to provide the convergence conditions of the exponentially-discounted score dynamics (43) in a general class of games. Consider the exponentially-discounted re- inforcement learning scheme as depicted in Figure 3. We proceed by imposing the following assumption on the payoff of the game. Assumption 1. The payoff U is anti-monotone, that is, for all x,x' € Ant ∈ (a — 2)" (U(x) —U(a’)) <0. (47) − − ≤ Theorem 2. Let G be a game with player’s learning scheme as given by EXP-D-RL, (45) (Figure 3). Assume there are a finite number of isolated fixed-points Z* of U o 0, then under Assumption 1, the player’s score z(t) converges to a rest point 2*. Moreover, x(t) = o(2(t)) converges to a logit equilibrium &* = 0(2*) of G. # G Proof. First, recall that solutions z(t) of remain bounded and Q = {z € R"|||z]2 < VM} is a compact, positively invariant set. Let z* be a rest point, z* = u* = U(o(z*)), z* =o(2*). Next, consider the Lyapunov function given by the Bregman divergence generated by the log-sum-exp function (10), Vz (z) = Ise(z) — Ise(Z*) — VIse(Z*)'(z -—2*), (48) − − ∇ − Recall that by Lemma 4, Ise is convex and by Proposition 1, V lse(z) = o(z). By convexity of Ise, Vz+(z) > 0,Vz € R”. Using ||o(z) ||, = o(z)'1 = 1 and lse(z + 1c) = lse(z) + ¢, it can be shown that Vz-(Z* + 1c) = 0,Vc € R, so Vzs(-) is positive semidefinite, but not positive definite. Taking the time derivative of V,+(z) along the solution of (44) yields, (44) yields, Ve-(2) Ve-(2) =VVa(2) "2 =(0(z) — o(2"))" (-z+u) =(0(z) — o(2"))" (-2 + -2* +0) =~ (0(2) — 0(2))" (2-2) + (o(2) 0)" − − − − By Corollary 2, a is co-coercive, therefore, , 1 ok Vee(2) $= 5llo(2) — o(2*)I8 + (0(2) - , 1 ok = — Vee(2) $= 5llo(2) — o(2*)I8 + (0(2) - 0)" (w=). Since u = U(o(z)),w = U(o(%)), « = o(z), and a* = 0(z*), therefore (47) implies that Vz«(z) < —}]lo(z) — o(2*)||3, thus Ve«(z) < 0,Vz € R”, and Vz-(z) = 0, for all 2€E= {z € No(z) = o(2"*)}. On E the dynamics of (44) reduces to, No(z) = o(2"*)}. 2=U(o(%*)) 2=2* 2=U(o(%*)) -2=2* =z. # z. − − Therefore z(t) —> Z* as t > oo, for any z(0) € €. Thus, no other solution except Z* can stay forever in €, and the largest invariant subset M C € consists only of equilibria. Since (44) has a finite number of isolated equilibria 2*, by LaSalle’s invariance principle [55], it follows that for any z(0) € Q, z(t) converges to one of them. By continuity of o, x(t) converges to Z* = o(z*) as t — oo. For an alternative proof using Barbalat’s lemma, see [21]. i | 08t 1 | 05 0.65 047 a(t) = ai(2(?)) | a(t) = 02(2(t)) a(t) = on(2()) 0 L L L L L L 0 10 20 30 40 50 60 Fig. 4: Convergence of the induced strategy x(t) towards the logit equilibrium of the standard RPS game. The red curve shows the evolution of the strategy in the interior of the simplex. Example 1. We note that Assumption 1 is equivalent to game being a stable game [2, p. 79], [18]. The representative # G 8 (u-7) − game from the class of stable games is the standard Rock- Paper-Scissors (RPS) game given by the payoff matrix, A = 0 1 1 − 1 0 1 1 1 , − 0 (49) − which generates the payoff vector U(x) = Aa. We present a simulation of the standard RPS game under the exponentially- discounted score dynamics (43) with A = 1. The resulting induced strategy x(t) is shown in Figure 4, which by Theo- rem 2 (which uses the co-coercivity property of the softmax function) is guaranteed to converge to the logit equilibrium of the RPS game, which is given by 7 = [1/3 1/3 1/3)". In this game, the logit equilibrium coincides with the Nash equilibrium. Next, we rely on a slightly modified result in [57] to show that the Lipschitzness of the softmax function can be directly used to conclude the convergence of the score dynamics (43) for certain classes of games. Assumption 2. Uoc is ||-||..-contractive, that is, there exists a constant L € (0,1) such that for all score variables z, z’ € R”, ∈ σ)(z) ∈ I(U oa)(z) — Uea)(Z)Iloo < Lll2 = 2'|loo- (50) Proposition 6. (Theorem 4, [57]) Under Assumption 2, the unique fixed point Z* of U oa is globally asymptotically stable for (44). Moreover, x(t) = o(z(t)) converges to the logit equilibrium &* = o(2*) of the game G. # G The above proposition essentially states that the conver- gence of the exponentially-discounted score dynamics (44) relies on, individually, the Lipschitzness of the softmax func- tion σ and the game’s payoff vector U . We illustrate this dependency using the following example. Example 2. By equivalence of norms, ¢ is ||-||,.-contractive if nd < 1. Then for any game where the payoff vector U is a || - || o-contraction, U oc is a || - |.o-contraction. Proposition 6 implies that the induced strategy x(t) = o(z(t)) converges to the logit equilibrium 7* € A"—?. ∈ # VII. CONCLUSION AND OPEN PROBLEMS In this paper we have presented a thorough analysis of the softmax function using tools from convex analysis and monotone operator theory. We have shown that the softmax function is the monotone gradient map of the log-sum-exp function and that the inverse temperature parameter λ deter- mines the Lipschitz and co-coercivity properties of the softmax function. These properties allow for convenient constructions of convergence guarantees for score dynamics in general classes of games (see [21]). We note that the structure of the reinforcement learning scheme is similar to those that arises in bandit and online learning (such as the Follow- the-Regularized-Leader (FTRL) and mirror descent algorithm [49]). We hope that researchers could adapt our results pre- sented here and apply them to their domain-specific problems. 9 Finally, for many applications in reinforcement learning, it is desirable to use a generalized version of the softmax function given by, oi(z) = exp(\i2i) ~ wl<i<n. © exp(jz;) j=l (51) Here, each strategy i is associated with an inverse temperature constant λi > 0, which can be adjusted independently to improve an agent’s learning performance. The relationship between the individual parameters λi with the convergence properties of score dynamics under the choice rule given by (51) has been investigated in [57] but is not yet fully characterized at this point. It is of interest to extend the results presented in this paper for generalized versions of the softmax function [60] or adopt a monotone operator theoretic approach to analyze alternative forms of choice maps [61]. # REFERENCES [1] H. Young and S. Zamir, Handbook of Game Theory, Volume 4, 1st ed. Amsterdam: Elsevier, North-Holland, 2015. [2] W. H. Sandholm, Population Games and Evolutionary Dynamics. Cam- bridge, MA, USA: MIT Press, 2010. [3] J. Goeree, C. Holt and T. Palfrey, Quantal response equilibrium: A Stochastic Theory of Games. Princeton University Press, 2016. [4] R. Sutton and A. Barto, Reinforcement Learning: An Introduction. Cambridge, MA, USA: MIT Press, 1998. [5] I. Goodfellow, Y. Bengio, and A. Courville, Deep Learning. Cambridge, MA, USA: MIT Press, 2016. [6] C. M. Bishop, Pattern Recognition and Machine Learning. Secaucus, NJ, USA: Springer, 2006. [7] S. Boyd and L. Vandenberghe, Convex optimization, 1st ed. Cambridge, UK: Cambridge University Press, 2004. [8] Y. Nesterov, Introductory Lectures on Convex Optimization: A Basic Course. Norwell, MA: Kluwer, 2004. [9] D. Bloembergen, K. Tuyls, D. Hennes, and M. Kaisers, “Evolutionary dynamics of multi-agent learning: A survey”, J. Artif. Intell. Res., vol. 53, no. 1, pp. 659-697, May 2015. [10] G. Weiss, Multiagent Systems, 2nd ed. Cambridge, MA, USA: MIT Press, 2013. [11] E. Alpaydin, Introduction to Machine Learning, 3rd ed. The MIT Press, 2014, p. 264. [12] R. Luce, Individual Choice Behavior: A Theoretical Analysis. NY, Wiley, 1959. [13] J. Bridle, “Probabilistic Interpretation of Feedforward Classification Network Outputs, with Relationships to Statistical Pattern Recognition”, Neurocomputing: Algorithms, Architectures and Applications, F. Soulie and J. Herault, eds., pp. 227-236, 1990. [14] R. McKelvey and T. Palfrey, Quantal response equilibria for normal form games, 1st ed. Pasadena, Calif.: Division of the Humanities and Social Sciences, California Institute of Technology, 1994. [15] J. Smith and G. Price, “The Logic of Animal Conflict”, Nature, vol. 246, no. 5427, pp. 15-18, 1973. [16] J. Hofbauer, K. Sigmund, “Evolutionary Games and Population Dynam- ics”, Cambridge University Press, 1998. [17] J. Weibull, “ Evolutionary Game Theory”. MIT Press, Cambridge, 1995. [18] J. Hofbauer and W. H. Sandholm, “Stable games and their dynamics”, Journal of Economic Theory, vol. 144, no. 4, pp. 1665-1693, 2009. [19] J. Hofbauer and E. Hopkins, “Learning in perturbed asymmetric games”, Games Economic Behav., vol. 52, pp. 133-152, 2005. [20] A. Kianercy and A. Galstyan, “Dynamics of Boltzmann Q-learning in two-player two-action games”, Phys. Rev. E, vol. 85, no. 4, pp. 1145- 1154, 2012. [21] B. Gao and L. Pavel, “On Passivity, Reinforcement Learning and Higher- Order Learning in Multi-Agent Finite Games”, arXiv:1808.04464 [cs, math], Aug. 2018. [22] P. Coucheney, B. Gaujal and P. Mertikopoulos, “Penalty-Regulated Dynamics and Robust Learning Procedures in Games”, Mathematics of Operations Research, vol. 40, no. 3, pp. 611-633, 2015. [23] P. Mertikopoulos and W. Sandholm, “Learning in Games via Reinforce- ment and Regularization”, Mathematics of Operations Research, vol. 41, no. 4, pp. 1297-1324, 2016. [24] R. T. Rockafellar and R. J.-B. Wets, Variational Analysis. Berlin: Springer-Verlag, 1998. [25] H. Bauschke and P. Combettes, Convex analysis and monotone operator theory in Hilbert spaces, 1st ed. New York: Springer, 2011. [26] F. Facchinei and J.-S. Pang, Finite-dimensional Variational Inequalities and Complementarity Problems. Vol. I, Springer Series in Operations Research, Springer-Verlag, New York, 2003. [27] J. Peypouquet. Convex optimization in normed spaces: theory, methods and examples. Springer, 2015. [28] J. B. Hiriart-Urruty and C. Lemar´echal: Fundamentals of Convex Anal- ysis. SpringerVerlag, Berlin 2001. [29] J. Baillon and G. Haddad, “Quelques propri´et´es des op´erateurs angle- born´es etn-cycliquement monotones”, Israel Journal of Mathematics, vol. 26, no. 2, pp. 137-150, 1977. [30] N. Daw, J. O’Doherty, P. Dayan, B. Seymour and R. Dolan, “Cortical substrates for exploratory decisions in humans”, Nature, vol. 441, no. 7095, pp. 876-879, 2006. [31] D. Lee, “Neuroeconomics: Best to go with what you know?”, Nature, vol. 441, no. 7095, pp. 822-823, 2006. [32] J. D. Cohen, S. M. McClure, and A. J. Yu, “Should I stay or should I go? How the human brain manages the trade-off between exploitation and exploration”, Philosph. Trans. Roy. Soc. B: Bio. Sci., vol. 362, no. 1481, pp. 933-942, 2007. [33] P. Bossaerts and C. Murawski, “From behavioural economics to neuroe- conomics to decision neuroscience: the ascent of biology in research on human decision making”, Current Opinion in Behavioral Sciences, vol. 5, pp. 37-42, 2015. [34] D. Koulouriotis and A. Xanthopoulos, “Reinforcement learning and evolutionary algorithms for non-stationary multi-armed bandit problems”, Applied Mathematics and Computation, vol. 196, no. 2, pp. 913-922, 2008. [35] R. Zunino, P. Gastaldo, “Analog implementation of the softmax func- tion”, In IEEE International Symposium on Circuits and Systems, vol 2, pp II-117, 2002. [36] A. L. Yuille and D. Geiger, “Winner-Take-All Mechanisms”, In The Handbook of Brain Theory and Neural Networks, Ed. M. Arbib, MIT Press, 1995. [37] I. M. Elfadel and J. L. Wyatt Jr., “The softmax nonlinearity: Derivation using statistical mechanics and useful properties as a multiterminal analog circuit element”, In Advances in Neural Information Processing Systems 6, J. Cowan, G. Tesauro, and C. L. Giles, Eds. San Mateo, CA: Morgan Kaufmann, 1994, pp. 882-887. [38] I. M. Elfadel, “Convex Potentials and their Conjugates in Analog Mean- Field Optimization”, Neural Computation, vol. 7, no. 5, pp. 1079-1104, 1995. [39] T. Genewein and D. A. Braun, “Bio-inspired feedback-circuit implemen- tation of discrete, free energy optimizing, winner-take-all computations”, Biological, vol. 110, no. 2, pp. 135-150, Jun. 2016. [40] T. Michalis, “One-vs-each approximation to softmax for scalable esti- mation of probabilities”, In Advances in Neural Information Processing Systems 29, pp. 4161-4169. 2016. [41] P. Reverdy and N. Leonard, “Parameter Estimation in Softmax Decision- Making Models With Linear Objective Functions”, IEEE Transactions on Automation Science and Engineering, vol. 13, no. 1, pp. 54-67, 2016. [42] M. Kaisers, K. Tuyls, F. Thuijsman, S. Parsons, “An evolutionary model of multi-agent learning with a varying exploration rate (Short Paper)”, Proc. of 8th Int. Conf. on Autonomous Agents and Multiagent Systems (AA-MAS 2009), Decker, Sichman, Sierra and Castelfranchi (eds.), Budapest, Hungary, pp. 1255-1256., 2009. [43] A. Martins and R. F. Astudillo. “From softmax to sparsemax: A sparse model of attention and multi-label classification”, arXiv:1602.02068 [cs.CL], Feb. 2016. [44] D. Leslie and E. Collins, “Individual Q-Learning in Normal Form Games”, SIAM Journal on Control and Optimization, vol. 44, no. 2, pp. 495-514, 2005. [45] W. Sandholm, E. Dokumacı and R. Lahkar, “The projection dynamic and the replicator dynamic”, Games and Economic Behavior, vol. 64, no. 2, pp. 666-683, 2008. 10 [46] R. Laraki and P. Mertikopoulos, “Higher order game dynamics”, Journal of Economic Theory, vol. 148, no. 6, pp. 2666-2695, 2013. [47] F. Alvarez, J. Bolte and O. Brahic, “Hessian Riemannian Gradient Flows in Convex Programming”, SIAM Journal on Control and Optimization, vol. 43, no. 2, pp. 477-501, 2004. [48] A. Beck and M. Teboulle, “Mirror descent and nonlinear projected sub- gradient methods for convex optimization”, Operations Research Letters, vol. 31, no. 3, pp. 167-175, 2003. [49] S. Shalev-Shwartz, “Online Learning and Online Convex Optimization”, Foundations and Trends in Machine Learning, vol. 4, no. 2, pp. 107-194, 2011. [50] E. Hazan, “Introduction to Online Convex Optimization”, Foundations and Trends in Optimization, vol. 2, no. 3-4, pp. 157-325, 2016. [51] A. Rangarajan, “Self-annealing and self-annihilation: unifying determin- istic annealing and relaxation labeling”, Pattern Recognition, vol. 33, no. 4, pp. 635-649, 2000. formulation of boosting al- gorithms”, IEEE Trans. Pattern Anal. Mach. Intell. Feb. 25, 2010, 10.1109/TPAMI.2010.47. [53] M. Harper, “The replicator equation as an inference dynamic”, arXiv:0911.1763 [math.DS], May. 2010. [54] Y. Sato and J. Crutchfield, “Coupled Replicator Equations for the dynamics of learning in multiagent systems”, Physical Review E, vol. 67, no. 1, 2003. [55] H. K. Khalil, Nonlinear Systems, 3rd ed., Upper Siddle River, NJ: Prentice-Hall, 2002. [56] E. Hopkins, “Two Competing Models of How People Learn in Games”, Econometrica, vol. 70, no. 6, pp. 2141-2166, 2002. [57] R. Cominetti, E. Melo and S. Sorin, “A payoff-based learning procedure and its application to traffic games”, Games and Economic Behavior, vol. 70, no. 1, pp. 71-83, 2010. [58] K. Tuyls, K. Verbeeck and T. Lenaerts, “A selection-mutation model for Q-learning in multi-agent systems”, in Proc. of the 2nd Int. Joint Conf. on Autonomous Agents and Multi-Agent Systems (AAMAS), pp. 693-700, 2003. 59 M. Tokic and G. Palm, “Value-difference based exploration: Adaptive control between €-greedy and softmax”, in KI 2011: Advances in Arti- ficial Intelligence, vol. 7006. Heidelberg, Germany: Springer, 2011, pp. 335-346. [60] P. Mertikopoulos, E. V. Belmega, and A. L. Moustakas, “Matrix expo- nential learning: Distributed optimization in MIMO systems”, in ISIT’12: Proceedings of the 2012 IEEE International Symposium on Information Theory, 2012, pp. 3028-3032. [61] K. Asadi and M. L. Littman, “An Alternative Softmax Operator for Reinforcement Learning”, arXiv:1612.05628 [cs, stat], Dec. 2016.
Title: LEGO-Net: Learning Regular Rearrangements of Objects in Rooms: Summary: Humans universally dislike the task of cleaning up a messy room. If machines were to help us with this task, they must understand human criteria for regular arrangements, such as several types of symmetry, co-linearity or co-circularity, spacing uniformity in linear or circular patterns, and further inter-object relationships that relate to style and functionality. Previous approaches for this task relied on human input to explicitly specify goal state, or synthesized scenes from scratch -- but such methods do not address the rearrangement of existing messy scenes without providing a goal state. In this paper, we present LEGO-Net, a data-driven transformer-based iterative method for LEarning reGular rearrangement of Objects in messy rooms. LEGO-Net is partly inspired by diffusion models -- it starts with an initial messy state and iteratively ''de-noises'' the position and orientation of objects to a regular state while reducing distance traveled. Given randomly perturbed object positions and orientations in an existing dataset of professionally-arranged scenes, our method is trained to recover a regular re-arrangement. Results demonstrate that our method is able to reliably rearrange room scenes and outperform other methods. We additionally propose a metric for evaluating regularity in room arrangements using number-theoretic machinery. # r a M 4 2 ] ] V C . s c [ 2 v 9 2 6 9 0 . 1 0 3 2 : v i X r a # LEGO-Net: Learning Regular Rearrangements of Objects in Rooms Qiuhong Anna Wei1 Sijie Ding* 1 Jeong Joon Park* 2 Rahul Sajnani1 Adrien Poulenard2 Srinath Sridhar1 Leonidas Guibas2 Brown University1 # Stanford University2 Messy Scene Cleaned “Regular” Scene Cleaned “Regular” Scene Messy Scene Figure 1. LEGO-Net LEarns to reGularly rearrange Objects in a messy indoor scene via an iterative denoising process. Different from scene synthesis or methods that require goal state specification, our method learns clean re-arrangements directly from data, retains the flavor of the original scene, and minimizes object travel distance. More about the project can be found at ivl.cs.brown.edu/projects/lego-net. # Abstract Humans universally dislike the task of cleaning up a messy room. If machines were to help us with this task, they must understand human criteria for regular arrange- ments, such as several types of symmetry, co-linearity or co-circularity, spacing uniformity in linear or circu- lar patterns, and further inter-object relationships that re- late to style and functionality. Previous approaches for this task relied on human input to explicitly specify goal state, or synthesized scenes from scratch – but such meth- ods do not address the rearrangement of existing messy scenes without providing a goal state. In this paper, we present LEGO-Net, a data-driven transformer-based it- erative method for LEarning reGular rearrangement of Objects in messy rooms. LEGO-Net is partly inspired by diffusion models – it starts with an initial messy state and iteratively “de-noises” the position and orientation of ob- jects to a regular state while reducing distance traveled. Given randomly perturbed object positions and orientations in an existing dataset of professionally-arranged scenes, our method is trained to recover a regular re-arrangement. Results demonstrate that our method is able to reliably re- arrange room scenes and outperform other methods. We additionally propose a metric for evaluating regularity in room arrangements using number-theoretic machinery. # 1. Introduction What makes the arrangement of furniture and objects in a room appear regular? While exact preferences may vary, humans have by-and-large universally shared criteria of reg- ular room arrangements: for instance, heavy cabinets are arranged to align with walls, chairs are positioned evenly around a table in linear or circular configurations, or night stands are placed symmetrically on the two sides of a bed. Humans also share a common dislike of physically perform- ing the task of rearranging a messy room. To build auto- mated robotic systems that can guide or actually rearrange objects in a room, we first need methods that understand the shared human criteria for regular room rearrangements and respect the physical constraints of rearrangements. # ∗Core contribution. 1 Human criteria for regular rearrangements can be sub- tle and complex, including geometric rules of reflexional, translational, or rotational symmetry, linear or circular alignments, and spacing uniformity. Functional and stylistic inter-object relationships are also important: for example, a TV tends to be in front of and facing a sofa, chairs are next to a table, etc. Many of these criteria interact and, at times, conflict with one another. As a result, in general, there is more than one desirable clean arrangement for any given messy arrangement. In our setting, we further desire that the clean rearrangement we create to be informed by the initial messy arrangement – and not be entirely different – for multiple reasons. First, there may have been a particular clean arrangement that gave rise to the messy one – and it may be desirable to recover a similar arrangement. Second, we want to minimize the motion of objects as much as pos- sible to respect the physical constraints and effort involved – especially the motion of big and heavy furniture. Unfortu- nately, extant methods fail to capture these criteria: methods for scene synthesis from scratch [29, 34, 42, 74, 75, 77] ig- nore the initial state of objects in a room, and rearrangement methods often require scene-specific human input in the form of a goal state [1, 51] or language description [32, 52]. In this paper, we present LEGO-Net, a method for LEarning reGular rearrangement of Objects in rooms di- rectly from data. Different from work that focuses on ar- ranging new objects from scratch or requires goal state specification, we focus on rearranging existing objects without any additional input at inference time. We take as input the position, orientation, class label, and extents of room objects in a specific arrangement, and output a room with the same objects but regularly re-arranged. LEGO-Net uses a transformer-based architecture [58] that is, in part, motivated by recent denoising diffusion probabilistic mod- els that learn a reverse diffusion process for generative mod- eling [19, 54, 55]. We learn human criteria for regular rear- rangements from a dataset of professionally designed clean (regular) scenes [17], and represent each scene as a collec- tion of objects and a floor plan. Prior to training, we perturb the regular scenes to generate noisy configurations. During training, our transformer learns to predict the original, de- noised arrangement from the perturbed scene and its floor plan. During inference, instead of directly re-arranging scenes with our model, which would amount to na¨ıve re- gression, we run a Langevin dynamics-like reverse process to iteratively denoise object positions and orientations. This iterative process retains the flavor of original room state, while limiting object movement during re-arrangement. We conduct extensive experiments on public datasets to show that our approach realistically rearranges noisy scene arrangements, while respecting initial object positions. We also demonstrate that our method is able to generalize to previously unseen collection of objects in a wide variety of 2 floor plans. Furthermore, we include extensive experimen- tal results (e.g., Fig. 1 and Fig. 4), including a new metric to evaluate regularity of re-arrangements, aimed at measuring the presence of sparse linear integer relationships among object positions in the final state (using the PSLQ algo- rithm [15]). To sum up, we contribute: • A generalizable, data-driven method that learns to reg- ularly re-arrange the position and orientation of ob- jects in various kinds of messy rooms. • An iterative approach to re-arrangement at inference time that retains flavor of the original arrangement and minimizes object travel distance. An in-depth analysis of the performance and charac- teristics of the denoising-based scene rearrangement. • A new metric to measure the regularity of object ar- rangements based on integer relation algorithms. # 2. Related Work In this section, we discuss literature in two related areas: (1) scene synthesis from scratch, (2) scene rearrangement where an end goal is specified, and (3) diffusion models. Indoor 3D Scene Synthesis: Indoor room synthesis is the problem of synthesizing the layout of objects in a scene from scratch. Many classical methods in the computer graphics literature use heuristics and guidelines to constrain the location of pre-specified objects [6,67,69,72]. [36] iden- tified a collection of functional, visual, and design con- straints and formulated an optimization problem. Work has also focused exclusively on inter-object relationships [30]. Other methods [70] address the open world layout problem when objects are not pre-specified. An alternative approach is to adopt procedural model- ing using generative grammars [5, 7, 10, 40, 42, 57]. Some methods adopt the scenegraph representation and formu- late it as a graph problem [29, 34, 38, 62, 74, 75, 77]. Both procedural and graph-based methods often rely on curated data [16]. Some methods learn directly from data using neu- ral networks, for instance from images [44]. Both Scene- Former [65] and ATISS [39] introduce autoregressive meth- ods for scene generation. Different from all these methods, we focus on rearranging rooms given an initial messy state. Scene Rearrangement: Scene rearrangement takes an ini- tial state of the scene and aims to bring it to a goal state spec- ified by the user. This task is deeply connected to planning in robotics [1, 47, 53]. Some works consider robot pushing and manipulation for rearrangement [2,8,9,13,23,24,26,27, 50,51]. Many of these methods require datasets for training and often use datasets like AI2-THOR [25], Habitat [56] or Gibson [28]. Some of these methods operate on visual observations [23], while others assume fully-observed syn- thetic environments [8]. To specify the goal state, some re- cent methods use language input [32, 52] driven by large fo Current Denoising Cleaner Scene State Gradient Scene State Denoising Process Object Attribute Encoder At, Ar; ‘Transformer| FG oe — > PointNet ——> @ J Floor Plan Denoising Transformer Architecture Figure 2. Pipeline overview. LEGO-Net takes an input messy scene and attempts to clean it via iterative denoising. Given the current scene state, it computes the denoising gradient towards the clean manifold, and changes the scene accordingly. This denoising step is repeated until the scene is “regular.” On the right, we show our backbone transformer block fθ that computes the denoising gradient at each step. It takes the scene attributes of the current state and outputs 2D transformations of each object that would make the scene “cleaner”. language models [11, 43]. Related to these advances in robotics, there have also been attempts to apply these specif- ically for room rearrangements [61, 66]. In this paper, we focus on the task of room rearrange- ments without the need to specify the goal state. We directly learn arrangements that satisfy human criteria from pro- fessionally arranged dataset provided by 3D-FRONT [17]. Note that a concurrent work [68] addresses the same prob- lem but with a focus on physical simulation, incorporating reinforcement learning and path planning. Denoising Diffusion Models: 2D Diffusion models [19, 54, 55] have emerged as a powerful technique for uncondi- tional image synthesis, outperforming existing 2D genera- tive models [14, 22]. Diffusion models have also seen great success in conditional image generations, receiving condi- tions in the form of class labels [12], text [37, 45], or input images [48]. Various methods [33, 35, 48] apply diffusion models for restoring corrupted or user-provided images to realistic images. Our method shares the same philosophy and adopts related techniques from the diffusion models, e.g., Langevin Dynamics, to project messy object configu- rations onto the manifold of “clean” scenes. # 3. Method # 3.1. Preliminaries Our method takes the position, orientation, class label, and extents of objects in a ‘messy’ room as input and out- puts a rearranged version in a ‘regular’ state. Since objects in rooms primarily move on the floor, we only consider 2D object pose, but our method can be combined with existing instance segmentation [64, 71] and canonicalization meth- ods [49] to directly operate from a 3D mesh or point cloud. We represent each scene X as an unordered set of n objects and their attributes: X = {o1, ..., on}, oi = (ci, ti, ri, bi, hi), (1) where c; € R*, t; € R®, r, € SO(2), and b; € R? re- spectively denote the semantic class, translation, rotation, and bounding box dimensions of the object 0;. h; € R15 is the pose-canonicalized shape features obtained by run- ning ConDor [49] on each object’s point cloud (see sup- plementary for details). The furniture semantic class labels c;’s are represented as one-hot vectors of the k classes. We represent the rotation r; € SO(2) by the first column vec- tor [cos(@), sin(9)|T of its rotation matrix, following [76] to represent SO(2) without any discontinuity. Note that ¢; is normalized to be in [—1, 1] to have the same range as r;’s sinusoidal representation to balance their importance dur- ing training. We define that a scene X° is a rearrangement of X° (denoted X* ~ X°) iff there exists a bijection p be- tween object indices such that h? ~ ney: # 3.2. LEGO-Net: Learning Regular Room Rear- rangements Fig. 2 shows our approach to solving the regular room re- arrangement task. Our method takes an input ‘messy’ scene ˜X and outputs a rearranged, ‘regular’ scene X. Towards this goal, we design a denoising Transformer [58] fθ that is trained to predict a clean scene given its perturbed version. During inference, we take an iterative approach as it gives us rich control of the rearrangement process, e.g., moving lighter objects farther. At each time step τ of the denoising process, we pass the current scene state ˜Xτ to the denoising Transformer fθ that provides gradients towards the mani- fold of ‘clean’ scenes. We repeat the denoising process until the magnitude of the predicted gradient is small enough to finally obtain a clean manifold projection of the input scene. Manifold Projection via Denoising Autoencoder: We now describe our approach from a manifold learning per- spective. We can consider the input to our method as an off-manifold point ˜X (i.e., a messy scene) and aim to project it to the closest point X on the manifold of ‘regular’ 3 scenes. Our objective is to learn a function fθ( ˜X) (with net- work parameters θ) that finds such manifold projected point X, i.e., fθ( ˜X) ≈ X. Motivated by the denoising autoen- coders [60] and their recent extensions to score-matching models [19, 54], we train such f ( ˜X) by perturbing the reg- ular data X employing a noise kernel qσ( ˜X|X) with noise parameter σ. The training is done by minimizing a denois- ing objective function: Ean(0) = Ey, ¢x,x) [Lin (fo(X).X)]- The joint distribution qσ( ˜X, X) = n(σ)qσ( ˜X|X)q0(X), where n(σ) is the distribution of the noise parameter and q0(X) is the discrete uniform distribution of the training examples. Here, the loss Ldn is defined as the average dis- tance between the pairs of objects in fθ( ˜X) and X: 14 ,- - : Lan = nl \|é: — tal|2 + [fi — il B i= +n (\léi — tala + [IP — alla), (3) where ˜ti and ˜ri’s are the object rotation and translation pa- rameters of fθ( ˜X), and λ1 is a balancing parameter for the L1 loss. While we can use the object correspondences from the perturbation process, we choose to re-establish object pairing by computing Earth Mover’s Distance [46] between the same class of objects in original and perturbed scenes. Intuitively, the network fθ( ˜X) learns to project ˜X to the clean manifold. However, it is not trained to find a random point in the clean manifold, but rather tries to find X that shares similarities with ˜X, depending on the noise level. Connection to Score-based Models: While the trained denoising network fθ can theoretically be applied to clean a messy scene directly, in practice, the quality of the output is suboptimal, as shown in Sec. 4. This is because the network fθ is trained with a regression loss, which is known to fit to the average state of the conditional distribution qθ(X| ˜X), leading to blurry predictions [21, 73]. Recently, score-based generative models (and the closely related diffusion models) [19, 54] have shown impres- sive image generation results using a trained denoiser. The score-based approaches [54, 59] approximate the gradient of likelihood of the perturbed data distribu- tion qσ( ˜X) with a neural network sφ, and showed φ for the denoising objec- that that the optimal network s% for the denoising objec- ~ ~ 2 tive Ey, (xx) [eo -Vx log do(X|X)| satisfies si,(X) aVe log do(X). Assuming a zero-mean Gaussian noise kernel q, (X |X), the score-based network training ob- jective becomes: 2 5 X-X Lecore(?) = E,,(X,x) 8o(X) — > (4) oO 4 Denoising Process Figure 3. Instead of directly regressing the final rearranged state which can lead to non-diverse, suboptimal results, we adopt an iterative strategy based on Langevin Dynamics. At each step in our process (left to right), we gradually “de-noise” the scene until it reaches a regular state. During training, we follow the reverse process, i.e., perturb clean scenes to messy state (right to left). φ approximates the gra- dient of the data distribution, it can be used for autoregres- sively optimizing noisy data onto the manifold of clean data. In our context, X − ˜X amounts to the difference in object transformations between the clean and perturbed scenes, and the direction X− ˜X φ( ˜X) is clearly to- σ2 wards the clean scene manifold. Rearrangement with Langevin Dynamics: After training with Eq. 2, we have a function that is optimized to approx- θ ( ˜X) ≈ imate the denoised projection of an input, i.e., f ∗ φ( ˜X) ≈ X− ˜X φ( ˜X) ∝ X. Given that s∗ , we have that s∗ θ ( ˜X) − ˜X. We then follow the score-based methods to f ∗ adopt Langevin dynamics [19,54] to recursively denoise the scene (see Fig. 3) using the estimated gradients: Xu =X, + alr) (f5(%-) - Xr) + 87)2r, 6) where a(r) and (7) are monotonically-decreasing func- tions of time 7 that is heuristically designed to balance the Langevin dynamics and z, ~ N(0, 1). We run the re- cursive computation until the magnitude of the gradient is small enough (i.e., || fj (X7,) — X7;|| < «, for constant «) for k consecutive iterations for some constant k. # 3.3. Architecture LEGO-Net follows the recent success in the scene synthesis community to adopt the Transformer architec- ture [58] to represent our denoising function fg, as il- lustrated in Fig. 2. Given an input scene X, a Trans- former encoder network Fg takes in |X | + 1 number of 512-dimensional tokens 6;’s corresponding to the objects in the scene, as well as the room floor plan. Then, the network outputs absolute translation and rotation predic- tions for all object tokens (excluding the layout token), ie, Fy : ROU*I+1)x512 ., RIXIX4, We then apply the out- puts to guide the translation and rotation of each object in X. The denoiser fg is defined to include both operations. Therefore, the final processed scene is a rearrangement of the input scene: fθ( ˜X) ∼ ˜X. Input Object Attribute Encoding: We use the following process to abstract oi into a token vector δi. We employ po- sitional encodings of 32 frequencies, and an additional lin- ear layer for ri, to independently process ti, ri, bi into vec- tors in R128. For object class ci, we employ a 2-layer MLP with leaky ReLU activation to process the one-hot encod- ing into an attribute in R128. Finally, we optionally process a pose-invariant shape feature hi from ConDor [49] with a 2-layer MLP to obtain a feature in R128. The above attribute features are then concatenated and processed with a 2-layer MLP to form an object token δi ∈ R512. We refer readers to supplementary for the full details of the processing. Floor Plan Encoder: Floor plans designating room bound- aries both impose important realistic constraints and pro- vide regularity information for the scene rearrangement task. Therefore, we pass the room layout in the form of an object token to the transformer so that other objects can attend to it. We employ a floor plan encoder to tokenize the floor plans as follows. We uniformly sample 250 points from the contour of the floor plan. These points along with their 2D surface normals are then processed with a simpli- fied version of PointNet [41]. Finally, we specifically assign one bit of the 512 transformer input dimensions (for both objects and floor plans) to distinguish floor plan ‘objects’ from normal ‘objects’. The final output of the floor plan encoder for each scene is a feature in R512. Transformer Architecture: We use our custom positional encodings and procedures to prepare the tokens but use the original Transformer encoder architecture without notable modifications. We use 8 multi-headed attentions with 512- dimensional hidden layers and 512-dimensional key, query, and value vectors. The output of the transformer network is the estimated object transformations, a |X| × 4 matrix. # 3.4. Training and Inference Data: We employ the 3D-FRONT dataset [17] for the task of indoor scene rearrangement. For each valid clean scene in the dataset, we preprocess it into X = {o1, ..., on} and extract the contour of its floor plan. Training: We use the denoising auto-encoder formulation of Eq. 2 to train our denoiser function fθ. We uniformly ran- domly sample training examples and sample a noise level σ from a normal distribution. The sampled examples are per- turbed using an independent Gaussian kernel with standard deviation σ. For the perturbation, we do not consider ob- jects going outside of the floor plans or colliding with one another. Each perturbed scene uses its original clean scene as the source of ground truth but re-establishes object cor- respondence through Earth Mover’s Distance assignment to enable invariance among identical objects and further pro- mote distance minimization in movement prediction. We 5 . 5 i Uniform Spacing — Symmetry & Parallelism e 2. r ® Initial Arrangement —————> Grouping by Shapes Rearrangement Figure 4. Regularities learning results. We train our denoising net- work to learn three different regularities. LEGO-Net successfully learns the complex regularity rules as demonstrated by the iterative denoising results shown on the right. use Adam optimizer with a learning rate of 10~‘ to train. Inference: During inference, we use the Langevin Dynam- ics scheme of Eq. 5 to iteratively project a messy scene input X onto the manifold of clean scenes. We select a hyperbolic function a(7) = ao/(1 + a1 * 7) to regulate the step size. We additionally select an exponential (7) = {po * olr/ bal where effectually 69 is multiplied by b every bg iterations, to adjust the level of noise as the denoising process pro- ceeds. Refer to supplementary for details. # 4. Experiments We conduct a number of experiments to test LEGO-Net’s ability to automatically capture scene regularities from data. To this end, we prepare two testbeds for experiments: our custom-designed Table-Chair environment where we mathematically constructed the regularities among objects and 3D-Front [17], which contains tens of thousands of synthetic rooms designed by professionals. The Table- Chair dataset is useful because we can model one regu- larity at a time and quantify network performance. 3D- Front dataset exhibits complex and subtle rules that design- ers commonly perceive as ideal configurations, e.g., geom- etry, semantic relations, styles, and functionalities. # 4.1. Capturing Regularities from Data In the Table-Chair environment, we study four main regularities: symmetry, parallelism, uniform spacing, and grouping by shapes. For each of the proposed experiments, we generate clean scenes based on the designed rules. Then, for training, we perturb the scenes on the fly to generate clean-messy pairs and re-associate objects within each class cutee eae Ground Truth Messy Scene Atiss- vanilla Atiss-failure-correction Ours Figure 5. Comparison against ATISS [39] on 3D-FRONT dataset. As the state-of-the-art scene synthesis method, ATISS is able to produce a realistic scene (3rd column) given the floor plan, but the generated objects and arrangements are entirely different. On the other hand, we solve the problem of re-arranging the given messy scene, directly using the existing objects. While ATISS has shown failure correction technique that solves similar problem to ours, we observe that when the scene is highly noisy, their algorithm tends to deteriorate significantly. Moreover, being a one-shot prediction method, ATISS-failure does not consider the moving distance of the new arrangement. through Earth Mover’s Distance assignment to train a net- work with the loss of Eq. 2. We measure each task with the success rate of the rearrangement, whose specific criteria we discuss in the supplementary. Symmetry and Parallelism: One of the most important notions of regular arrangement is symmetry, which involves both object-object and room-level symmetries. We use a setup of 2 groups of rectangular tables and chairs. We ver- tically align the 2 tables and horizontally distribute them at a distance uniformly drawn from a fixed range. We arrange 3 chairs in a linear row on one side of the table and 3 chairs in another linear row on the opposite side. Uniform Spacing: We prepare a highly-challenging setup to stress test LEGO-Net’s ability to capture the concept of uniform spacing. In this setup, we have 2 circular tables, each with 2-6 chairs randomly and uniformly rotated around them. The network has to deal with the unknown number of chairs and the pair-wise spacing. Grouping by Shape: We test LEGO-Net’s ability to group objects based on their pose-invariant shapes. We augment our setup in ‘Symmetry and Parallelism’ to include 2 types of chairs with different shapes. We arrange the scenes such that chairs with the same shapes are on the same side of the table. The pose-invariant shape features hi ∈ oi from Eq. (1) provide the necessary shape information. Results: We visualize the rearrangement results of LEGO- Net for the above three cases in Fig. 4. Across the board, the denoising network successfully learns to capture these important regularities from data, without explicit supervi- sion about the underlying rules. The success rate of each task is shown in Tab. 1. As expected, directly applying the regression-trained network fθ results in the worst results. # 4.2. 3D-Front Experiments We benchmark LEGO-Net’s ability to conduct regular scene rearrangements on the bedrooms and livingrooms of the 3D-FRONT dataset, which respectively contains 2338/587 and 5668/224 scenes for train/test splits. Direct Grad. w/o noise Grad. w/ noise Symmetry & Parallelism ↑ 16% 91.2% 91.4% Uniform Spacing↑ 18.6% 96% 97.2% Grouping by Shape↑ 23.6% 87.8% 89.2% Table 1. Denoising success rate by regularities and inference strategies. For the three regularities shown in Fig. 4, we measure the success rate of LEGO-Net for each of the inference variants. We train our LEGO-Net as described in Sec. 3 with o ~ N(0,0.1?). While we maintain a single denoising net- work f», we explore three variants of inference algorithms to provide greater insight of our approach: (1) LEGO-Net direct, (2) grad. with noise, and (3) grad. w/o noise respec- tively denote the inference strategy of predicting the clean outcome with one network pass, running Langevin Dynam- ics of Eq. (5) with noise term 3 4 0, and 6 = 0. Baselines. We compare our rearrangement results against the current SOTA scene synthesis method, ATISS [39]. While ATISS is designed to synthesize a scene from scratch rather than to rearrange one, it provides an auto-regressive generative model that can be flexibly applied to our task. Specifically, we use three variants of ATISS that share the same network weights. First, ATISS vanilla performs its original scene synthesis task given a floor plan. Second, ATISS with labels performs object placement using a pre- defined set of objects per scene. Third, ATISS failure- correction takes a noisy scene and cleans it up by itera- tively finding an object with low probability and re-placing it within the current scene. This variant of ATISS is given the same perturbed scene as LEGO-Net and aims to clean the scene. Note that we omit to compare against prior works that have already been compared against ATISS, e.g., [44, 62, 65]. We could not find a prior data-driven method that is designed to solve the same rearrangement problem as ours. 6 KID↓ Living Room FID↓ Distance Moved ↓ EMD to GT ↓ KID↓ FID↓ Bedroom Distance Moved ↓ EMD to GT ↓ ATISS [39] vanilla labels failure-correction 96 119 280 44.55 45.45 61.55 — — 0.1473 — 0.3758 0.3378 33 49 240 50.49 52.62 73.95 — — 0.2025 — 0.5482 0.4673 LEGO-NET (ours) grad. w/ noise grad. w/o noise 67 51 39.19 37.47 0.091 0.086 0.125 0.117 37 27 49.76 48.43 0.052 0.0492 0.086 0.0815 Table 2. Quantitative experiment results using KID ×10, 000, FID, distance moved, and Earth Mover’s Distance (EMD) against the ground truth arrangements. All scenes are situated within [−1, 1]2 canvas. Note that ATISS vanilla and ATISS labels start from empty floor plans and thus the distance moved metric is not applicable. ATISS failure-correction takes a noisy scene and iteratively resamples low-probable objects, and is thus directly comparable to our method. Metrics. To gauge how well LEGO-Net captures datasets’ regularities, we adopt the popular FID and KID scores. These metrics compare the closeness of statistics of two data distributions. We follow prior works [39, 63] to render ground truth and generated scene arrangements from top- down views and compute the metrics in the image space. Note that KID is more applicable to our setting because FID is known to present huge bias when the number of data is low. Another important criterion for our rearrangement task is how much distance the objects travel between the initial and final scene states. Similarly, when applicable, we mea- sure the Earth Mover’s Distance (EMD) between the ground truth scene and our cleaned-up scene. Finally, we introduce a new metric that measures scene regularities by finding integer relations among object posi- tional coordinates ti’s. To do this, we select two or three random objects within a scene and check if we can find in- tegral ai’s that satisfy: a1t1 + ... + antn = 0, 0 < |ai| < η , ∀ai (6) where η sets the maximum magnitude of the coefficients. Intuitively, these integer relations can capture regularities such as colinearities (−t1 + t2 = 0) and symmetries (t1 − 2t2 + t3 = 0). See supplementary for detailed descriptions. Results. We conduct the 3D-FRONT arrangement experi- ments with five algorithms (three ATISS variants and two of ours) and compute their metrics. The main numerical re- sults, which can be found in Tab. 2, show that LEGO-Net outperforms all variants of ATISS, including the failure- correction variant that tackles the same object cleaning problem as demonstrated in the original paper. In Fig. 6, we plot the chance of finding integer relations in scenes perturbed with different noise levels, which peaks for the original clean 3D-FRONT scenes and sharply de- creases as noise is added. Also, note that the rearranged scenes of LEGO-Net demonstrate high regularities accord- ing to this measure, outperforming the results of ATISS variants. See supplementary for more experiment details. © © ® 2 Object Relations, 7=2 3 Object Relations, 7 =3 © © © FS 2 FS © © be © is © iS © Integer Relation Chance ° Integer Relation Chance ° 0 0.05 01 0.2 03 0.4 i) 0.05 0.1 0.2 0.3 04 Noise Level (std.) Noise Level (std.) —*=Ground Truth ===LEGO-Net wlo Noise ——LEGO-Net w Noise —ATISS Vanilla. —==ATISS Failure Integer relation occurences. We measure the chance Figure 6. of finding integer relations between the coordinates of two (left) and three (right) objects within a Living Room scene. Perturb- ing ground truth scenes sharply decreases the integer relation oc- curences, showing they are useful metric of regularities. Note that LEGO-Net outperforms ATISS variants in this metric. Qualitatively, as shown in Fig. 5, LEGO-Net is able to robustly project messy scenes onto clean manifolds. While ATISS and ATISS with labels were able to synthesize real- istic rooms, their object arrangements are entirely different from the original input scene. Importantly, we notice that ATISS failure correction leads to unexpectedly low-quality results. We hypothesize that this is due to their discrete, one-object-at-a-time strategy, which can easily fall into the local minimum of the likelihood space. In contrast, our score-based iterative denoising leads to robust success rates. # 4.3. Analysis To more deeply understand the behavior of our system, we analyze and discuss important aspects of LEGO-Net. We refer to supplementary for more analysis of our method. Denoising Strategy. As we discuss throughout Sec. 4, we explore three inference strategies, namely direct, gradient with noise, and gradient without noise. For the 3D-FRONT experiment, we report that the grad. without noise vari- ant consistently outperforms the other variants. However, we believe that this is likely because we used relatively 7 Ground Truth Low Noise Input Low Noise Cleaned High Noise Input High Noise Cleaned Figure 7. LEGO-Net denoising results on different noise levels. When the perturbation added to the scene is low, LEGO-Net is able to closely reconstruct the clean version of the scene. In contrast, when the noise level is high, our denoising process finds a different realization of a regular scene, behaving more like an unconditional model. Similar phonemena have been observed by 2D diffusion projects, e.g., SDEdit [35]. low noise to the scenes (std 0.1) to more naturally simu- late messy indoor rooms. Indeed, our experiment on the synthetic environments (Tab. 1) with larger noise (std 0.25) shows that the grad. with noise variant outperforms. The results suggest that adding noise during Langevin dynam- ics allows a better success rate for highly noisy data, but at the cost of losing accuracy in recovering the originals (as shown in Tab. 2). Cleaning Uncertainty. LEGO-Net is trained to handle in- put perturbations at various noise levels. In the high-noise regime, there is high uncertainty on the structure of the orig- inal information. As input noise increases, our denoising process converges into an unconditional generative model. On the other hand, LEGO-Net has the capacity to capture original regularities when the noise is low, leading to almost precise reconstruction of the original scenes. We visually show these insights in Fig. 7. Out-of-Distribution Inputs. We showcase LEGO-Net’s ability to handle scenes perturbed with noise patterns sig- nificantly different from the one used in training, i.e., zero- mean Gaussian. In the first example, we only perturb chairs. Secondly, we perturb the scene only in the translation di- mensions without rotations. Shown in Fig. 8, LEGO-Net can successfully handle out-of-distribution inputs, demon- strating the robustness and versatility of our algorithm. # 5. Conclusion In this paper, we presented LEGO-Net, a method for reg- ular rearrangement of objects in a room. Different from pre- vious methods, LEGO-Net learns human notions of regular- ity (including symmetry, alignments, uniform spacing, and stylistic and functional factors) directly from data without the need to explicitly specify a goal state. During training, we learn from a large dataset of professionally-designed room layouts that are randomly perturbed. During infer- ence, we follow a Langevin Dynamics-like strategy to iter- atively “denoise” the scene. Quantitative results including = Ground Truth 0.0.D. Perturbed Our Denoised Figure 8. Out-of-distribution test. While our model is trained to denoise Gaussian noise, it demonstrates strong robustness to out- of-distribution inputs. In the first row, only the chairs are per- turbed. In the second row, we perturbe the scene with translation noise only. Zoom-in for details. comparisons and ablations show that our method performs well, which qualitative results confirm. Limitations & Future Work: Our method has important limitations that provide extensive opportunities for future work. First, our method is currently limited to 2D room rearrangement and cannot perform 3D rearrangement, for instance in kitchen shelves. However, we do incorporate 3D shape features which can be used to extend our method to 3D. We also currently do not handle interpenetration of objects during denoising, which future work should explore. # Acknowledgements This work was supported by AFOSR grant FA9550-21- 1-0214, NSF CloudBank, an AWS Cloud Credits award, ARL grant W911NF-21-2-0104, a Vannevar Bush Faculty Fellowship, and a gift from the Adobe Corporation. We thank Kai Wang, Daniel Ritchie, Rao Fu, and Selene Lee. 8 # References [1] Dhruv Batra, Angel X Chang, Sonia Chernova, Andrew J Davison, Jia Deng, Vladlen Koltun, Sergey Levine, Jiten- dra Malik, Igor Mordatch, Roozbeh Mottaghi, et al. Re- arrangement: A challenge for embodied ai. arXiv preprint arXiv:2011.01975, 2020. 2 [2] Ohad Ben-Shahar and Ehud Rivlin. planning for rearrangement tasks. Robotics and Automation, 14(4):549–565, 1998. 2 [3] Paul J Besl and Neil D McKay. Method for registration of 3-d shapes. In Sensor fusion IV: control paradigms and data structures, volume 1611, pages 586–606. Spie, 1992. 14 [4] Mikołaj Bi´nkowski, Danica J Sutherland, Michael Arbel, and Arthur Gretton. Demystifying mmd gans. arXiv preprint arXiv:1801.01401, 2018. 14 [5] Martin Bokeloh, Michael Wand, Hans-Peter Seidel, and Vladlen Koltun. An algebraic model for parameterized shape editing. ACM Transactions on Graphics (TOG), 31(4):1–10, 2012. 2 [6] Richard W Bukowski and Carlo H S´equin. Object associa- tions: a simple and practical approach to virtual 3d manipu- lation. In Proceedings of the 1995 symposium on Interactive 3D graphics, pages 131–ff, 1995. 2 [7] Siddhartha Chaudhuri, Daniel Ritchie, Jiajun Wu, Kai Xu, and Hao Zhang. Learning generative models of 3d structures. In Computer Graphics Forum, volume 39, pages 643–666. Wiley Online Library, 2020. 2 [8] Akansel Cosgun, Tucker Hermans, Victor Emeli, and Mike Stilman. Push planning for object placement on cluttered table surfaces. In 2011 IEEE/RSJ international conference on intelligent robots and systems, pages 4627–4632. IEEE, 2011. 2 [9] Michael Danielczuk, Andrey Kurenkov, Ashwin Balakr- ishna, Matthew Matl, David Wang, Roberto Mart´ın-Mart´ın, Animesh Garg, Silvio Savarese, and Ken Goldberg. Mechan- ical search: Multi-step retrieval of a target object occluded In 2019 International Conference on Robotics by clutter. and Automation (ICRA), pages 1614–1621. IEEE, 2019. 2 [10] Jeevan Devaranjan, Amlan Kar, and Sanja Fidler. Meta- sim2: Unsupervised learning of scene structure for synthetic data generation. In European Conference on Computer Vi- sion, pages 715–733. Springer, 2020. 2 [11] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Pre-training of deep bidirectional arXiv preprint Toutanova. transformers for language understanding. arXiv:1810.04805, 2018. 3 Bert: [12] Prafulla Dhariwal and Alexander Nichol. Diffusion models beat gans on image synthesis. Advances in Neural Informa- tion Processing Systems, 34:8780–8794, 2021. 3 [13] Mehmet R Dogar, Michael C Koval, Abhijeet Tallavajhula, and Siddhartha S Srinivasa. Object search by manipulation. Autonomous Robots, 36(1):153–167, 2014. 2 [14] Patrick Esser, Robin Rombach, and Bjorn Ommer. Taming In Pro- transformers for high-resolution image synthesis. ceedings of the IEEE/CVF conference on computer vision and pattern recognition, pages 12873–12883, 2021. 3 9 [15] Helaman R. P. Ferguson and David H. Bailey. A polynomial time, numerically stable integer relation algorithm. Number RNR-91-032, 1991. 2, 17 [16] Matthew Fisher, Daniel Ritchie, Manolis Savva, Thomas Funkhouser, and Pat Hanrahan. Example-based synthesis of 3d object arrangements. ACM Transactions on Graphics (TOG), 31(6):1–11, 2012. 2 [17] Huan Fu, Bowen Cai, Lin Gao, Ling-Xiao Zhang, Jiaming Wang, Cao Li, Qixun Zeng, Chengyue Sun, Rongfei Jia, Bin- qiang Zhao, et al. 3d-front: 3d furnished rooms with layouts In Proceedings of the IEEE/CVF Interna- and semantics. tional Conference on Computer Vision, pages 10933–10942, 2021. 2, 3, 5, 12, 14 [18] 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 equilib- rium. Advances in neural information processing systems, 30, 2017. 14 [19] Jonathan Ho, Ajay Jain, and Pieter Abbeel. Denoising diffu- sion probabilistic models. Advances in Neural Information Processing Systems, 33:6840–6851, 2020. 2, 3, 4, 16 [20] Alain Hore and Djemel Ziou. Image quality metrics: Psnr vs. ssim. In 2010 20th international conference on pattern recognition, pages 2366–2369. IEEE, 2010. 14 [21] Phillip Isola, Jun-Yan Zhu, Tinghui Zhou, and Alexei A Efros. Image-to-image translation with conditional adver- sarial networks. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 1125–1134, 2017. 4 [22] Tero Karras, Miika Aittala, Janne Hellsten, Samuli Laine, Jaakko Lehtinen, and Timo Aila. Training generative ad- versarial networks with limited data. Advances in Neural Information Processing Systems, 33:12104–12114, 2020. 3 [23] Jennifer E King, Marco Cognetti, and Siddhartha S Srini- vasa. Rearrangement planning using object-centric and robot-centric action spaces. In 2016 IEEE International Con- ference on Robotics and Automation (ICRA), pages 3940– 3947. IEEE, 2016. 2 [24] Jennifer E King, Vinitha Ranganeni, and Siddhartha S Srini- vasa. Unobservable monte carlo planning for nonprehensile In 2017 IEEE International Confer- rearrangement tasks. ence on Robotics and Automation (ICRA), pages 4681–4688. IEEE, 2017. 2 [25] Eric Kolve, Roozbeh Mottaghi, Winson Han, Eli VanderBilt, Luca Weihs, Alvaro Herrasti, Daniel Gordon, Yuke Zhu, Ab- hinav Gupta, and Ali Farhadi. Ai2-thor: An interactive 3d environment for visual ai. arXiv preprint arXiv:1712.05474, 2017. 2 [26] Athanasios Krontiris, Rahul Shome, Andrew Dobson, An- drew Kimmel, and Kostas Bekris. Rearranging similar ob- jects with a manipulator using pebble graphs. In 2014 IEEE- RAS International Conference on Humanoid Robots, pages 1081–1087. IEEE, 2014. 2 [27] Yann Labb´e, Sergey Zagoruyko, Igor Kalevatykh, Ivan Laptev, Justin Carpentier, Mathieu Aubry, and Josef Sivic. Monte-carlo tree search for efficient visually guided rear- rangement planning. IEEE Robotics and Automation Letters, 5(2):3715–3722, 2020. 2 [28] Chengshu Li, Fei Xia, Roberto Mart´ın-Mart´ın, Michael Lin- gelbach, Sanjana Srivastava, Bokui Shen, Kent Vainio, Cem Gokmen, Gokul Dharan, Tanish Jain, et al. igibson 2.0: Object-centric simulation for robot learning of everyday household tasks. arXiv preprint arXiv:2108.03272, 2021. 2 [29] Manyi Li, Akshay Gadi Patil, Kai Xu, Siddhartha Chaudhuri, Owais Khan, Ariel Shamir, Changhe Tu, Baoquan Chen, Daniel Cohen-Or, and Hao Zhang. Grains: Generative re- cursive autoencoders for indoor scenes. ACM Transactions on Graphics (TOG), 38(2):1–16, 2019. 2 [30] Qi Li, Kaichun Mo, Yanchao Yang, Hang Zhao, and Ifr-explore: Learning inter-object func- arXiv preprint Leonidas Guibas. tional relationships in 3d indoor scenes. arXiv:2112.05298, 2021. 2 [31] Rosanne Liu, Joel Lehman, Piero Molino, Felipe Pet- roski Such, Eric Frank, Alex Sergeev, and Jason Yosinski. An intriguing failing of convolutional neural networks and the coordconv solution. Advances in neural information pro- cessing systems, 31, 2018. 16 [32] Weiyu Liu, Chris Paxton, Tucker Hermans, and Dieter Fox. Structformer: Learning spatial structure for language-guided In 2022 Inter- semantic rearrangement of novel objects. national Conference on Robotics and Automation (ICRA), pages 6322–6329. IEEE, 2022. 2 [33] Andreas Lugmayr, Martin Danelljan, Andres Romero, Fisher Yu, Radu Timofte, and Luc Van Gool. Repaint: Inpainting using denoising diffusion probabilistic models. In Proceed- ings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 11461–11471, 2022. 3 [34] Andrew Luo, Zhoutong Zhang, Jiajun Wu, and Joshua B Tenenbaum. End-to-end optimization of scene layout. In Proceedings of the IEEE/CVF Conference on Computer Vi- sion and Pattern Recognition, pages 3754–3763, 2020. 2 [35] 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. 3, 8 [36] Paul Merrell, Eric Schkufza, Zeyang Li, Maneesh Agrawala, and Vladlen Koltun. Interactive furniture layout using in- terior design guidelines. ACM transactions on graphics (TOG), 30(4):1–10, 2011. 2 [37] 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. 3 [38] Wamiq Para, Paul Guerrero, Tom Kelly, Leonidas J Guibas, and Peter Wonka. Generative layout modeling using con- In Proceedings of the IEEE/CVF Interna- straint graphs. tional Conference on Computer Vision, pages 6690–6700, 2021. 2 [39] Despoina Paschalidou, Amlan Kar, Maria Shugrina, Karsten Kreis, Andreas Geiger, and Sanja Fidler. Atiss: Autoregres- sive transformers for indoor scene synthesis. In Advances in Neural Information Processing Systems (NeurIPS), 2021. 2, 6, 7, 14, 15 [40] Pulak Purkait, Christopher Zach, and Ian Reid. Sg-vae: Scene grammar variational autoencoder to generate new in- 10 door scenes. In European Conference on Computer Vision, pages 155–171. Springer, 2020. 2 [41] Charles R Qi, Hao Su, Kaichun Mo, and Leonidas J Guibas. Pointnet: Deep learning on point sets for 3d classification In Proceedings of the IEEE conference and segmentation. on computer vision and pattern recognition, pages 652–660, 2017. 5, 12, 15 [42] Siyuan Qi, Yixin Zhu, Siyuan Huang, Chenfanfu Jiang, and Song-Chun Zhu. Human-centric indoor scene synthesis us- In Proceedings of the IEEE Con- ing stochastic grammar. ference on Computer Vision and Pattern Recognition, pages 5899–5908, 2018. 2 [43] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learn- ing transferable visual models from natural language super- vision. In International Conference on Machine Learning, pages 8748–8763. PMLR, 2021. 3 [44] Daniel Ritchie, Kai Wang, and Yu-an Lin. Fast and flex- ible indoor scene synthesis via deep convolutional genera- In Proceedings of the IEEE/CVF Conference tive models. on Computer Vision and Pattern Recognition, pages 6182– 6190, 2019. 2, 6 [45] Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Bj¨orn Ommer. High-resolution image In Proceedings of synthesis with latent diffusion models. the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 10684–10695, 2022. 3 [46] Yossi Rubner, Carlo Tomasi, and Leonidas J Guibas. The In- earth mover’s distance as a metric for image retrieval. ternational journal of computer vision, 40(2):99–121, 2000. 4 [47] Stuart J Russell. Artificial intelligence a modern approach. Pearson Education, Inc., 2010. 2 [48] Chitwan Saharia, William Chan, Huiwen Chang, Chris Lee, Jonathan Ho, Tim Salimans, David Fleet, and Mohammad In Norouzi. Palette: ACM SIGGRAPH 2022 Conference Proceedings, pages 1– 10, 2022. 3 [49] Rahul Sajnani, Adrien Poulenard, Jivitesh Jain, Radhika Dua, Leonidas J Guibas, and Srinath Sridhar. Condor: Self- supervised canonicalization of 3d pose for partial shapes. In Proceedings of the IEEE/CVF Conference on Computer Vi- sion and Pattern Recognition, pages 16969–16979, 2022. 3, 5, 12 [50] Jonathan Scholz and Mike Stilman. Combining motion planning and optimization for flexible robot manipulation. In 2010 10th IEEE-RAS International Conference on Hu- manoid Robots, pages 80–85. IEEE, 2010. 2 [51] Rahul Shome and Kostas E Bekris. Synchronized multi-arm rearrangement guided by mode graphs with capacity con- straints. In International Workshop on the Algorithmic Foun- dations of Robotics, pages 243–260. Springer, 2020. 2 [52] Mohit Shridhar, Lucas Manuelli, and Dieter Fox. Cliport: What and where pathways for robotic manipulation. In Con- ference on Robot Learning, pages 894–906. PMLR, 2022. 2 [53] Herbert A Simon and Allen Newell. Computer simulation of human thinking and problem solving. Monographs of the Society for Research in Child Development, pages 137–150, 1962. 2 [54] Yang Song and Stefano Ermon. Generative modeling by esti- mating gradients of the data distribution. Advances in Neural Information Processing Systems, 32, 2019. 2, 3, 4 [55] Yang Song, Jascha Sohl-Dickstein, Diederik P Kingma, Ab- hishek Kumar, Stefano Ermon, and Ben Poole. Score-based generative modeling through stochastic differential equa- tions. arXiv preprint arXiv:2011.13456, 2020. 2, 3 [56] Andrew Szot, Alexander Clegg, Eric Undersander, Erik Wi- jmans, Yili Zhao, John Turner, Noah Maestre, Mustafa Mukadam, Devendra Singh Chaplot, Oleksandr Maksymets, et al. Habitat 2.0: Training home assistants to rearrange their habitat. Advances in Neural Information Processing Systems, 34:251–266, 2021. 2 [57] Jerry O Talton, Yu Lou, Steve Lesser, Jared Duke, Radom´ır Mˇech, and Vladlen Koltun. Metropolis procedural modeling. ACM Transactions on Graphics (TOG), 30(2):1–14, 2011. 2 [58] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszko- reit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017. 2, 3, 4 [59] Pascal Vincent. A connection between score matching and denoising autoencoders. Neural computation, 23(7):1661– 1674, 2011. 4 [60] Pascal Vincent, Hugo Larochelle, Yoshua Bengio, and Pierre-Antoine Manzagol. Extracting and composing robust features with denoising autoencoders. In Proceedings of the 25th international conference on Machine learning, pages 1096–1103, 2008. 4 [61] Hanqing Wang, Wei Liang, and Lap-Fai Yu. Scene mover: Automatic move planning for scene arrangement by deep reinforcement learning. ACM Transactions on Graphics, 39(6), 2020. 3 [62] Kai Wang, Yu-An Lin, Ben Weissmann, Manolis Savva, An- gel X Chang, and Daniel Ritchie. Planit: Planning and in- stantiating indoor scenes with relation graph and spatial prior networks. ACM Transactions on Graphics (TOG), 38(4):1– 15, 2019. 2, 6 [63] Kai Wang, Manolis Savva, Angel X Chang, and Daniel Ritchie. Deep convolutional priors for indoor scene syn- thesis. ACM Transactions on Graphics (TOG), 37(4):1–14, 2018. 7 [64] Weiyue Wang, Ronald Yu, Qiangui Huang, and Ulrich Neu- mann. Sgpn: Similarity group proposal network for 3d In Proceedings of the point cloud instance segmentation. IEEE conference on computer vision and pattern recogni- tion, pages 2569–2578, 2018. 3 [65] Xinpeng Wang, Chandan Yeshwanth, and Matthias Nießner. Sceneformer: Indoor scene generation with transformers. In 2021 International Conference on 3D Vision (3DV), pages 106–115. IEEE, 2021. 2, 6 [66] Luca Weihs, Matt Deitke, Aniruddha Kembhavi, and Roozbeh Mottaghi. Visual room rearrangement. In Proceed- ings of the IEEE/CVF conference on computer vision and pattern recognition, pages 5922–5931, 2021. 3 11 [67] Tomer Weiss, Alan Litteneker, Noah Duncan, Masaki Nakada, Chenfanfu Jiang, Lap-Fai Yu, and Demetri Ter- zopoulos. Fast and scalable position-based layout synthesis. IEEE Transactions on Visualization and Computer Graph- ics, 25(12):3231–3243, 2018. 2 [68] Mingdong Wu, Fangwei Zhong, Yulong Xia, and Hao Dong. Targf: Learning target gradient field for object rearrange- ment. arXiv preprint arXiv:2209.00853, 2022. 3 [69] Ken Xu, James Stewart, and Eugene Fiume. Constraint- based automatic placement for scene composition. In Graph- ics Interface, volume 2, pages 25–34, 2002. 2 [70] Yi-Ting Yeh, Lingfeng Yang, Matthew Watson, Noah D Goodman, and Pat Hanrahan. Synthesizing open worlds with constraints using locally annealed reversible jump mcmc. ACM Transactions on Graphics (TOG), 31(4):1–11, 2012. 2 [71] Li Yi, Wang Zhao, He Wang, Minhyuk Sung, and Leonidas J Guibas. Gspn: Generative shape proposal network for 3d In Proceedings of instance segmentation in point cloud. the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 3947–3956, 2019. 3 [72] Lap Fai Yu, Sai Kit Yeung, Chi Keung Tang, Demetri Terzopoulos, Tony F Chan, and Stanley J Osher. Make it home: automatic optimization of furniture arrangement. ACM Transactions on Graphics (TOG)-Proceedings of ACM SIGGRAPH 2011, v. 30,(4), July 2011, article no. 86, 30(4), 2011. 2 [73] Richard Zhang, Phillip Isola, and Alexei A Efros. Colorful In European conference on computer image colorization. vision, pages 649–666. Springer, 2016. 4 [74] Song-Hai Zhang, Shao-Kui Zhang, Wei-Yu Xie, Cheng- Yang Luo, and Hong-Bo Fu. Fast 3d indoor scene synthe- sis with discrete and exact layout pattern extraction. arXiv preprint arXiv:2002.00328, 2020. 2 [75] Zaiwei Zhang, Zhenpei Yang, Chongyang Ma, Linjie Luo, Alexander Huth, Etienne Vouga, and Qixing Huang. Deep generative modeling for scene synthesis via hybrid represen- tations. ACM Transactions on Graphics (TOG), 39(2):1–21, 2020. 2 [76] Yi Zhou, Connelly Barnes, Jingwan Lu, Jimei Yang, and Hao Li. On the continuity of rotation representations in neu- ral networks. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 5745– 5753, 2019. 3 [77] Yang Zhou, Zachary While, and Evangelos Kalogerakis. Scenegraphnet: Neural message passing for 3d indoor scene In Proceedings of the IEEE/CVF Interna- augmentation. tional Conference on Computer Vision, pages 7384–7392, 2019. 2 # Supplementary Document # A. Overview This supplementary document contains extended techni- cal details, along with qualitative and quantitative results that supplement the main document. After introducing our video results, we cover details of our network architectures and their applications (Sec C). We then provide detailed ex- planations of our two main experiment setups: Table-Chair (Sec. D) and 3D-FRONT (Sec. E). Next, we conduct addi- tional analysis experiments in Sec. F. Finally, we discuss failure modes (Sec. G) and future directions (Sec. H). # B. Video Results In order to better visualize the 3D structures of the out- puts and the denoising process, we provide videos of these processes in the format of an HTML website. We highly encourage the viewers to open the file “LEGO.html” and watch the videos for a direct view of the denoising process. # C. Architecture Details # C.1. Input Object Attribute Encoding For each object attribute oi = (ci, ti, ri, bi, hi), we pro- cess it into an object token δi ∈ R512 to input into the trans- former. The details are as follows. = [cos(θi), sin(θi)]T , and bounding box dimension bi with a sinusoidal positional encoding of 32 frequencies. The frequencies are a geometric sequence with initial term 1 and common ratio 128 1 31 , which gives an ending term of 128. The positional encoding is therefore P E(x) = {sin(128 j 31 x), cos(128 j 31 x) | 0 ≤ j ≤ 31} ∈ R64. Applying P E to ti = [ti,x, ti,y] and bi = [bi,x, bi,y] gives 128-dimensional embeddings, whereas applying it to θi gives a 64-dimensional embedding. We then additionally process P E(θi) with a linear layer mapping to R128. As mentioned, for object class ci, we utilize a 2-layer MLP with leaky ReLU activation to process the one-hot en- coding into a 128-dimensional attribute. The above four features are concatenated to form a 512-dimensional vector. We also optionally process a pose-invariant shape feature hi from ConDor [49]. More specifically, we pretrain Con- Dor on the 3D point clouds provided by 3D-FRONT [17], and extract the product of the Tensor Field Network layer output and spherical harmonics coefficients from ConDor to provide pose-invariant features in R1024×128 capturing the shape of each object. Taking the mean across the 1024 points gives a 128-dimensional feature, which we then pass through a 2-layer MLP with leaky ReLU activation to obtain the final shape feature in R128. We apply the shape feature 12 hi in the Grouping by Shapes experiment to demonstrate its effectiveness. Finally, the concatenated attributes for each object lie in R640 and are processed through 2 linear layers with leaky ReLU activation to produce a 512-dimensional object token for the transformer. Note that if floor plan is utilized, we modify the final layer to produce a 511-dimensional feature, and utilize the last bit to distinguish object tokens from floor plan tokens. # C.2. Floor Plan Encoder Architecture We represent each floor plan as 250 randomly sampled contour points. We represent each point through its 2D po- sition coordinate and the 2D normal of the line it is on. In aggregate, we represent each floor plan with a feature in R250×4. We employ a simplified PointNet [41] as the floor plan encoder to extract one unified floor plan feature from this representation. The encoder first processes the feature with 3 linear layers and Leaky ReLU activation, mapping the feature dimension through [4, 64, 64, 512]. Then, we max pool the resulting embedding in R250×512 to obtain a global floor-plan encoding in R512. We then pass this global representation through one final linear layer and ap- pend a binary bit distinguishing it from object tokens. Fi- nally, we combine this floor plan token with the | ˜X| num- ber of 512-dimensional object tokens and pass the resulting (| ˜X| + 1) × 512 input matrix to the transformer. # C.3. Output Layers The backbone transformer outputs (| ˜X| + 1) × 512 fea- ture tokens. We ignore the floor plan token and use the | ˜X| object tokens to predict denoising transformations. We ap- ply 2 linear layers with leaky ReLU activation to the output tokens to map to 256 dimensions then 4 dimensions, and finally obtain the absolute transformation predictions. # C.4. Inference Langevin Dynamics Parameters During inference, we use the Langevin Dynamics scheme to iteratively denoise a messy scene input. As men- tioned, for time step 7, we select a(7) = ag/(1 + ay * 7) to regulate the step size and (7) = po * plr/Pe] to regu- late the noise added at each iteration. We empirically select a, = 0.005 and b; = 0.9. For the living room, we adopt ag = 0.1, Bo = 0.01, and bz = 10. For bedroom, we adopt ao = 0.08, Bo = 0.008, and bz = 8. We break from the iterative denoising process upon any one of two conditions: (1) if for 3 consecutive itera- tions, both the predicted translation displacement vector has Frobenius norm less than 0.01 and the predicted rotation an- gle displacement is less than 0.005 radians, or (2) we have reached 1500 iterations. # D. Table-Chair Experiment # D.1. Data Generation To analyze the regularities our model can capture, we propose three synthetic Table-Chair experiment settings, with a focus on Symmetry and Parallelism, Uniform Spac- ing, and Grouping by Shapes respectively. For each of the proposed experiments, we generate clean scenes based on designed rules and take a bimodal approach at perturbations when generating clean-messy training data pair. More specifically, for half of the synthesized clean scenes, we employ a Gaussian noise kernel whose standard deviation is drawn from a zero-mean Gaussian distribution with a small standard deviation (0.01 for translation and π/90 for rotation angle). For the other half of the clean scenes, we employ a Gaussian noise kernel whose standard deviation is drawn from a zero-mean Gaussian distribution with a relatively larger standard deviation (0.25 for trans- lation and π/4 for rotation angle). For the other training details, we follow the same paradigm as in the 3D-FRONT experiments. # D.2. Inference Parameters As for the 3D-FRONT experiments, we employ the Langevin Dynamics scheme to rearrange a given perturbed Table-Chair arrangement. We empirically adjust the param- eters to slightly increase the step size, accelerate the noise decay schedule, and loosen the termination condition. In particular, we select α0 = 0.12, a1 = 0.005, β0 = 0.01, b1 = 0.9, b2 = 2, and terminate once the predicted dis- placements are small enough in magnitude for 1 iteration. # D.3. Success Rate As mentioned, we measure LEGO-Net’s performance in each Table-Chair environment through the success rate of its rearrangement. We will now elaborate on its criteria. Symmetry and Parallelism: For a rearrangement to be classified as a success, it must satisfy the following: • The mean euclidean distance of per-object movement averaged across scenes is less than 0.5. • For each chair, the angular offset between its orienta- tion and the table-facing orientation is less than π/60 radians. • Given the two rearranged table positions, we com- pute their respective chair positions and perform Earth Mover’s Distance assignment using these as target and the final predicted chair positions as source. The to- tal distances summed across all 12 chairs for the 2 ta- bles need to be less than 0.08. Note that this metric integrates colinearity, parallelism, and symmetry, and penalizes collision. 13 Symmetry & Parallelism p | ‘ ‘ ‘ : i a a 7 Uniform Spacing Grouping by Shapes Initial Arrangement —————> Rearrangement Figure 9. Regularities learning results (additional visualizations). We train our denoising network to learn three different regularities. LEGO-Net learns the complex regularity rules as demonstrated by the iterative denoising results shown on the right. Zoom in for details, especially for the shape-based grouping. Uniform Spacing: For a rearrangement in the Uniform Spacing experiment to be classified as a success, it must sat- isfy the first two criteria for the Symmetry and Parallelism experiment. For the third criteria, because the number of chairs arranged around each of the 2 circular tables is vari- able, we cannot formulate the Earth Mover’s Distance as- signment as in the Symmetry and Parallelism experiment. Instead, to measure how well an arrangement captures the object-object relationships and regular relative positioning, we compute two other metrics. For each table, we compute the angular distances be- tween each adjacent pair of its chairs and measure the vari- ance of these distances. We designate that a successful ar- rangement must have an angular distance variance of less than 0.009 radians. Additionally, given we utilize a fixed radius to generate clean chair arrangements around tables, we can measure the mean difference between the chair-to- closest-table distance and this radius. We designate that the magnitude of this difference needs to be less than 0.01 for an arrangement to be considered successful. Grouping by Shapes: Similarly, for a rearrangement in the Grouping by Shapes experiment to be classified as a success, it must satisfy the first two criteria for the Sym- metry and Parallelism experiment. Additionally, we once again can compute the exact regular arrangement of chairs with respect to the table, enabling us to calculate the Earth Mover’s Distance from the final predicted chair positions to the clean configuration with respect to the predicted table position. We designate that the distance summed across the 6 chairs needs to be less than 0.05. Furthermore, to measure success at grouping, we require that each row must be assigned exactly 3 chairs and that all chairs assigned to the same row must have the same shape feature. # D.4. Additional Qualitative Results In Fig. 9, we provide additional qualitative renderings for the three Table-Chair experiments. # E. 3D-FRONT Experiment To process the 3D-FRONT dataset [17], we closely fol- low the preprocessing protocol of ATISS [39]. For each scene, we extract from the given meshes and parameters the translation, rotation, class, and bounding box size for every object, and we normalize all lengths to be in [−1, 1]. We additionally extract accurate contours of the floor plans by running an iterative closest point algorithm [3], using the contour corner points of ATISS’s binary floor plan masks as source and the relevant vertices from 3D-FRONT floor meshes as target. # E.1. Baseline Description We compare against three variants of ATISS: vanilla, labels, and failure-correction. As described in the main text, vanilla is the original ATISS approach that generates a scene from scratch given the floor plan. ATISS labels is given the floor plan, as well as a set of furniture labels and the transformations and sizes of the labeled objects. ATISS failure-correction is proposed as an application to the probabilistic generative modeling of ATISS. It identi- fies which object is likely to be a failure and resamples that object given all the other objects. While the original paper only showed the technique to work when a single object is perturbed, we find it reasonable to extend the algorithm to multi-object perturbation cases. Specifically, we provide a scene with all objects perturbed (same input as LEGO-Net) and iteratively resample the lowest-probable object. We stop the iteration when it reaches 1,000 times or when the minimum probability is higher than a manually set thresh- old. We note that while failure-correction did not perform as expected when all of the objects are perturbed, as shown in Fig. 10, it is the closest baseline we could find in the lit- erature that performs data-driven denoising of a scene. For the comparisons, we use the official training and test- ing code provided by the authors of ATISS without modi- fications. For ATISS failure-correction, we add a for-loop and stopping criteria on top of their implementation, and maintain the scales of objects as fixed to be coherent with the rearrangement task. 14 # E.2. Metric Description For FID and KID computation, we first generate the same number of scenes as in the test dataset and randomly select 500 from the generated scenes. We then randomly select 500 real scenes from the 3D-FRONT dataset to com- pare against. For both FID and KID, we repeat the metric computation 5 times and report the average. Note that for computing the FID scores for ATISS, we used the officially provided code and followed their exact evaluation proce- dure, but we failed to reproduce their numbers. Hence, we use our own way of computing the metrics and report ours. We note that the Frechet Inception Distance (FID) [18] is known to present significant positive bias when the num- ber of images is small (e.g., ≤ 2000). In our case, we’re dealing with an even smaller number of test images. There- fore, to compute a metric that is less biased in the small-data regime, we adopt the Kernel Inception Distance [4], which is known to address the bias problem and present small vari- ance even at a few hundred samples. Distance Traveled. As discussed in the main text, we aim at rearranging the messy scenes while retaining the flavor of the original scenes. Practically, cleaning a room should move objects as minimally as possible while realizing reg- ularities. Therefore, we measure and report the mean of the average distance traveled for scenes. More specifically, for each scene, we compute the average Euclidean distance between the corresponding objects in the initial and final states, and take the mean across scenes. Note that for ATISS vanilla, this metric is not applica- ble as the method randomly places objects into the scene. For ATISS failure-correction, we calculate this metric by computing the distance between the initial position of each object and its final position after applying the algorithm. EMD to GT. In order to measure how accurately our method recovers the original scene configuration, we mea- sure the Earth Mover’s Distance between the final and the ground truth scene states. Note that computing the differ- ence between the denoising prediction and the ground truth is widely used in the image-denoising literature, using such metrics as PSNR or SSIM [20]. ATISS vanilla and labels do not receive the messy scene as input, so this metric is not applicable to them. On the other hand, ATISS failure- correction directly fixes the input scene, thus we may mea- sure how accurately it recovers the original clean scene. Fi- nally, we note that the EMD to GT metric becomes highly noisy and irrelevant when the noise added to perturb the clean scenes becomes too high, as then, there is scarsely any locational information left in the messy inputs. # E.3. Additional Qualitative Results We provide additional qualitative results on the 3D- FRONT dataset. We show more comparisons against the pow th og Ground Truth Messy Scene Atiss-failure-correction Ours Figure 10. Qualitative comparison against ATISS-failure-correction. We show qualitative examples illustrating the difference in behaviors between our method and the closest method on the same task, ATISS failure-correction. Being a generative model, ATISS is able to compute the probability of the current object transformations and resample the ones with low probability. While ATISS has demonstrated great results in their paper when only a single object is perturbed, we observe that when all objects are perturbed, ATISS failure-correction has a hard time fixing the scene to a reasonable regular configuration. We hypothesize that this is due to the one-prediction-at-a-time nature of ATISS – it is difficult to find a good location to put the current object when all the other objects are perturbed. On the other hand, our method simultaneously optimizes for all the objects, avoiding such difficulty. Even for the highly challenging scene structure of the second row, our method is able to provide a high-quality layout, while ATISS failure-correction fails to find regular rearrangement. closest method on the scene rearrangement task, ATISS failure-correction, in Fig. 10, and more results of our method in Fig. 17. # F. Analysis (Continued) PointNet W/O Noise PointNet W/ Noise ResNet W/O Noise ResNet W/ Noise Bedroom ↑ Living Room ↑ 84.4% 84.2% 83.8% 83.6% 54.4% 54.2% 54% 54.2% # F.1. Enforcing Floor Plan Constraints In this section, we analyze our choice of floor plan en- coder. As described in the main text, we extract points on the boundary of the binary floor plan mask, and process them with a PointNet [41] to obtain a unified feature vector describing the floor plan. We note that, in ATISS [39], a 2D convolutional network with residual connections (ResNet) Table 3. Percentage of denoised scenes with 90% of its fur- niture within the floor plan boundaries. We train and test our method using different floor plan encoding architectures (PointNet vs. ResNet), and measure the percentage of the denoised scenes where most furniture respect the room boundaries. 15 Absolute Relative Relative Translation & Absolute Rotation Distance Moved ↓ 2.98e-1 2.47e-1 2.73e-1 Direction Offset ↓ 1.10e-3 4.21e-4 5.18e-4 EMD to GT ↓ 5.16e-2 1.58e-1 2.83e-1 Table 4. Mean statistics from denoising results using the gradient with noise strategy for the Uniform & Parallelism Table-Chair ex- periment. The relative prediction model slightly outperforms the absolute prediction model in terms of distance moved and angular orientation offset, but it performs much worse in terms of EMD to GT as although it maps objects to the right general region, it does not place them as precisely as the absolute model. was used to process the floor plans. Here, we conduct an experiment to justify our use of PointNet architecture. As a baseline, we use the ResNet architecture from ATISS, but augment the input floor plan with two additional chan- nels corresponding to the xy coordinate for each pixel cen- ter, which is known to provide “spatial awareness” to the 2D CNN (in CoordConv [31]). We expect this variant of ResNet to work at least as well as the vanilla ResNet with binary mask input used in ATISS. To compare the two methods of floor plan encoding, we train two variants of the model, using ResNet or PointNet floor plan encoding architecture. To test the effectiveness of the two methods, we measure how often furniture is moved outside the floor boundaries. Specifically, a scene rear- rangement is considered successful when 90% of objects are placed inside the floor boundary within 4% of its length margin. While respecting the floor boundaries does not nec- essarily lead to high-quality, regular scenes, we empirically find this metric as a reasonable proxy. As can be seen from the numerical results of Tab. 3, the use of PointNet outper- forms that of ResNet by a slight margin. However, we note that using PointNet is significantly faster, having almost no computational overhead for operating on the sampled 250 boundary points. We, therefore, choose to use the simpler but similar-performing PointNet to encode the scene floor plans. # F.2. Relative vs Absolute 2D diffusion models perform better at predicting the noise than the un-noised images [19]. However, for our set- ting, we observed that the absolute prediction models gen- erally outperform their relative counterparts in the Table- Chair environment. We trained 3 variants of the same archi- tecture network for the Uniform & Parallelism Table-Chair setting: (i) absolute translation and rotation prediction, (ii) relative translation and rotation prediction, and (iii) relative translation and absolute rotation prediction. Following the criteria in D.3, both variants (ii) and (iii) 16 surprisingly report success rates of 0%. Upon further in- vestigation (shown in Tab. 4), variants (ii) and (iii) perform comparably, if not better, at limiting the distance of move- ment and orienting chairs to face the tables, but they sig- nificantly underperform (i) in terms of Earth Mover’s Dis- tance to Ground Truth chair positions with respect to the predicted table position. With the same denoising parame- ters, the relative variants consistently fail to place the chairs as precisely as the absolute variant. The superior perfor- mance of the absolute variant may partly be explained by the fact that this setting has a relatively limited space of possible regular arrangements. The observed deficiency of relative predictions may diminish as the complexity of the scene increases. We believe that relative transformation prediction is an important future direction to explore, as they offer trans- lation invariance, which is particularly valuable for large- scale scenes. Currently, the position and orientation infor- mation in our input object attributes are global, and thus our system is not translationally invariant. An interesting direc- tion for future investigation is to explore a sliding-window- style input processing to ensure translation invariance and to apply positional encoding to the output transformations. # F.3. Distance to Ground Truth and Distance Moved vs. Noise Since the task of rearrangement values affinity to the starting configuration of objects, one question of interest is how closely we recover the original clean arrangement when given a perturbed version of it, versus another pos- sibly equally valid, clean arrangement. Its correlation with the level of noise added is intuitive–we expect that when the perturbation is low, we more closely reconstruct the original scen with a low distance moved whereas when the perturba- tion is high, our model may choose a regular arrangement different from that of the original scene in an effort to min- imize the distance moved (see Fig. 11). This is indeed what we have observed numerically, as shown in Fig 12. Note that with a low degree of noise, our model per- forms the task of rearrangement, but as the degree of noise increases, our model gradually transitions to the task of arrangement. In the extreme case where we give LEGO- Net a scene with objects outside of the floor plan, LEGO- Net is able to perform scene arrangement from scratch (see Fig. 13). The open-endedness in the definition of regularity is one of the reasons why this task is both challenging and inter- esting. The interpolation-like behavior of LEGO-Net condi- tioned on the degree of noise signifies the learnable relation- ship between rearrangement and synthesis, and it demon- strates that a diffusion-like approach holds promising po- tential at such open tasks. Ground Truth Low Noise Input Low Noise Cleaned High Noise Input High Noise Cleaned Figure 11. LEGO-Net denoising results on different noise levels (additional visualization to Fig.7 of the main text). When the perturbation added to the scene is low, LEGO-Net is able to closely reconstruct the clean version of the scene. In contrast, when the noise level is high, our denoising process finds a different realization of a regular scene, behaving more like an unconditional model. We provide numerical evidence for this phenomenon in Tab. 12. @ EMD to Ground Truth @ Distance Moved 03 0.2 01 0.0 01 02 03 04 05 06 07 LEGO-Net denoising results on different noise Figure 12. The hori- levels (supplementing Fig.8 of the main text). zontal axis specifies the standard deviation of the zero-mean Gaussian distribution from which the (translation) noise level is drawn, and the vertical axis specifies distance in scenes normalized to [−1, 1]. We compute mean statistics across [0.01, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7] for the stan- 100 scenes at dard deviation of the translation noise level distribution and at [π/90, π/24, π/12, π/4, π/3, π/2, π] for that of rotation angle. # F.4. Integer Relations The task of evaluating regularity in an object arrange- ment is itself an interesting research problem because, in general, multiple regular solutions are possible. To eval- uate and quantify the notion of “regularity” in object ar- rangements, we propose using number-theoretic machinery for detecting and evaluating sparse linear integer relations among object coordinates. That is, given coordinates ti’s for n objects, we seek to find integral coefficients ai’s such that: a1t1 + ... + antn = 0, 0 < |ai| < η , ∀ai, (7) For simplicity, we consider each dimension of the cooridnates separately, i.e., t; € IR. Additionally, in prac- tice, we introduce an additional parameter € to control the precision of the solutions found. In particular, we seek to find relationships such that Jat; + ... + dntn| < €. For our evaluation, we fix € = 0.01 to focus on the near-perfect relations while allowing some leeway for insignificant off- sets. To efficiently find these integer solutions, we employ the PSLQ algorithm [15]. When the subset size n and maximum coefficient mag- nitude constraint η are small, the integer relations can be intuitively understood (e.g. representing co-linearity, sym- metry, uniform spacing among few objects). To capture more complex and more general notions of regularity, we increase n and η. Doing so preicipitates two challenges. First, the number of possible subsets of size n for each scene increases rapidly as n increases, compromising effi- ciency. Secondly, experimentally running the algorithm on pure noise shows that with looser constraints, we may find many trivial relations that do not appear to correspond to high-level ‘cleanness’. To counter these, we introduce two filtering mechanisms to increase the subset sampling effi- ciency and to filter out the insignificant relations. We observe that regualrities of interest to us mostly oc- cur among objects in close proximity to one another, such as tables and chairs. Therefore, for n > 2, instead of sampling from all possible subsets of the objects in the scene, we iter- ate through each object and sample from the object’s posi- tional neighborhood. For n = 3, for each object, we sample 2 from the closest 4 neighboring objects to form {t1, t2, t3}. This greatly improves sampling efficiency, and it also helps eliminate irrelevant candidates as integer relations satisfied by objects in vicinity to one another are more likely to be meaningful for the purpose of our evalutions. Additionally, to filter out relations that may have been satisfied by numerical coincidence, we require all relations to be translation-invariant. Specifically, for each subset, we sample a noise µ from uniform distribution U (−1, 1) and apply the PSLQ algorithm to {t1 + µ, ..., tn + µ}. We re- peat the process 10 times and only deem a subset to have a valid relation if the algorithm succeeds for all 10 times. 17 eo mM 2 Be Ground Truth Messy Scene Ours Figure 13. Extreme case rearrangement. When the amount of noise added is exceedingly high, the original scene structure is gone. Running our denoising algorithm then amounts to unconditional sampling and leads to an arrangement significantly different from the ground truth. o 11 2 Object Relations, 7 =5 8 0.55 3 Object Relations, 7 =5 8 0.8 ~ Average Integer Relation Score o 07 = 5° 5 6 09 6 0.45 6 98 0.5 6 08 5 0.4 5 04 2 s = 0. So7 $0.35 s @ CI 2 0.3 © 06 © o3 & 5 5 0 5 0.2 F 05 @ 0.25 90.1 2 2 2 £04 = 02 £0 0 005 01 02 03 04 0.5 0 0.05 0.1 02 03 04 05 0 0.05 01 02 03 04 0.5 Noise Level (std.) Noise Level (std.) Noise Level (std.) —e—Ground Truth e==LEGO-Net wlio Noise «==LEGO-Net wNoise «==ATISS Vanilla <=ATISS Failure Figure 14. We measure the chance of finding integer relations among the coordinates of 2 (left) and 3 (middle) objects within a living room scene for η = 5. We aggregate these two settings with the two presented in the main text to produce an overall average integer relation score (right) for general regularity. We normalize all raw chance measures by the maximal chance across the four settings, making all numerical values directly comparable. Note that LEGO-Net outperforms the ATISS variants. This helps the metric to focus on regularities with respect to the relative positions instead of the absolute positions of objects. In Fig 14, we demonstrate that with these two filter- ing mechanisms, our metric is still meaningful for η = 5 and potentially larger parameters, which would be useful for measuring wider ranges of regularities. We also show that averaging all the integer relation metrics across the var- ious settings suggest more general notions of regularity, for which LEGO-Net outperforms the ATISS variants. # G. Failure Modes While LEGO-Net generates unprecedented-quality in- door scenes through the iterative denoising process, we no- tice that it often suffers from objects going out of the floor boundaries and objects penetrating each other. These failure modes are illustrated in Fig. 15 and 16. In fact, in Tab 3, we measure that around half of living room realizations have at least one object outside of the boundaries. We propose two possible remedies for these related is- sues. First, we could apply post-processing steps to phys- Figure 15. Failure modes. While LEGO-Net generates high- quality scenes, it often exhibits the two failure modes of placing objects outside of the floor plan boundaries (red ellipse) and in- ducing penetration between objects (blue ellipse). We leave post- processing steps to resolve these issues as future work. ically resolve the two problems. That is, we optimize the locations of the objects within the scene such that pene- trations and out-of-boundary issues are resolved with mini- mal required movement. We believe a possible formulation 18 would involve a signed distance function (SDF), with which it is easy to compute the gradient to minimize the penetra- tions. When a point lies on the negative territory of another shape’s SDF, we can optimize the location of that point out towards the SDF’s gradient directions. Secondly, one can consider richer encoding of the floor plan. One possibility is to encode each line segment of the floor plan separately as a token. This will essentially treat each line segment as an object in the scene and could en- force stricter constraints on the boundaries. At a glance, this strategy might increase the computational cost significantly, due to the quadratic nature of Transformer time complexity. However, one could consider limiting the communication between the line segment tokens to prevent quadratic scal- ing of the complexity. We leave these two potential remedies for our failure modes as future work. # H. Future Work In this work, we introduced LEGO-Net, an iterative- denoising-based method for tackling scene rearrangement task, which is relatively understudied compared to the scene synthesis task. We show through extensive experiments that our method is able to capture regularities of complex scenes, generating high-quality object rearrangements that could not be achieved by existing approaches to date. However, LEGO-Net in its current form only operates on a 2D plane for the rearrangement. Extending our work to operate on the SE(3) transformation space would make it more applicable to real-world scenes. A significant bar- rier to achieving 3D rearrangement is the lack of data. We notice that most of the indoor scene arrangement datasets deal with objects laid on the floor plan, which could limit the progress of studying SE(3) scene arrangements. De- signing and collecting such a dataset, e.g., small objects on top of one another is an interesting future direction. Moreover, the trajectories generated during the denois- ing process of LEGO-Net are not meant to respect physi- cal constraints, e.g., penetrations and collisions. We find that enforcing the physical constraints during the denoising steps could significantly limit the space of possible scene rearrangement. Currently, if one wants to move objects in a scene according to the initial and final states of our algo- rithm, one needs to run a motion planning algorithm. Ex- tending our work to output motion plans, along with the final states, is worth pursuing. Finally, LEGO-Net has only been shown to work well on relatively small room-scale scenes. Extending our work to operate on larger-scale scenes such as warehouses might require changes to some of our architecture choices, in- cluding strengthening translational invariance. Exploring such strategies remains an understudied challenge, which we continue to explore. 19 Ground Truth Messy Scene Atiss-failure-correction Ours Figure 16. Additional demonstrations of failure modes of our method. In the top row, note that two chairs are missing due to perfect collision of their position predictions with those of the other chairs. In the bottom row, the cabinet is placed outside of the floor boundaries. 20 NI I IAIN Ground Truth Messy Scene Our Rearrangement Figure 17. Additional rearrangement results of LEGO-Net on the 3D-FRONT dataset. 21
Title: ChatGPT: A Study on its Utility for Ubiquitous Software Engineering Tasks: Summary: ChatGPT (Chat Generative Pre-trained Transformer) is a chatbot launched by OpenAI on November 30, 2022. OpenAI's GPT-3 family of large language models serve as the foundation for ChatGPT. ChatGPT is fine-tuned with both supervised and reinforcement learning techniques and has received widespread attention for its articulate responses across diverse domains of knowledge. In this study, we explore how ChatGPT can be used to help with common software engineering tasks. Many of the ubiquitous tasks covering the breadth of software engineering such as ambiguity resolution in software requirements, method name suggestion, test case prioritization, code review, log summarization can potentially be performed using ChatGPT. In this study, we explore fifteen common software engineering tasks using ChatGPT. We juxtapose and analyze ChatGPT's answers with the respective state of the art outputs (where available) and/or human expert ground truth. Our experiments suggest that for many tasks, ChatGPT does perform credibly and the response from it is detailed and often better than the human expert output or the state of the art output. However, for a few other tasks, ChatGPT in its present form provides incorrect answers and hence is not suited for such tasks. # ChatGPT: A Study on its Utility for Ubiquitous Software Engineering Tasks Ranjani H.G. Global AI Accelerator (GAIA) Ericsson Bangalore, India ranjani.h.g@ericsson.com # Giriprasad Sridhara Global AI Accelerator (GAIA) Ericsson Bangalore, India giriprasad.sridhara@ericsson.com # Sourav Mazumdar Global AI Accelerator (GAIA) Ericsson Bangalore, India sourav.mazumdar@ericsson.com Abstract—ChatGPT (Chat Generative Pre-trained Trans- former) is a chatbot launched by OpenAI on November 30, 2022. OpenAI’s GPT-3 family of large language models serve as the foundation for ChatGPT. ChatGPT is fine-tuned with both supervised and reinforcement learning techniques and has received widespread attention for its articulate responses across diverse domains of knowledge. In this study, we explore how ChatGPT can be used to help with common software engineering tasks. Many of the ubiquitous tasks covering the breadth of software engineering such as ambiguity resolution in software requirements, method name sug- gestion, test case prioritization, code review, log summarization can potentially be performed using ChatGPT. In this study, we explore fifteen common software engineering tasks using ChatGPT. We juxtapose and analyze ChatGPT’s answers with the respective state of the art outputs (where available) and/or human expert ground truth. Our experiments suggest that for many tasks, ChatGPT does perform credibly and the response from it is detailed and often better than the human expert output or the state of the art output. However, for a few other tasks, ChatGPT in its present form provides incorrect answers and hence is not suited for such tasks. repair faulty code. It can compose poems, and attempt medical diagnosis and so on. 1 While we may debate ad infinitum the exact ranking of ChatGPT in the pantheon of human achievements, it is un- deniable that it has captured the technology inclined public’s imagination like nothing else in recent times. Supposedly it had a million users signing up to use it and millions of conversations with it. Social media platforms are abuzz with users sharing their experience (and screen shots) of their interactions with ChatGPT. There is anecdotal evidence of incredible responses from ChatGPT such as it passing the US Medical Learning Exam and an exam in the Master of Business Administration offered by the Wharton School in the US. There are also reports, (almost gloating) about ChatGPT s inexplicable failures. For example, apparently, ChatGPT could not solve the following elementary algebra problem: “ A bat and a ball together cost 1.10, the cost difference between the bat and ball is 1.0, what are their individual costs?”. We are as intrigued as others about the success and failures of ChatGPT. However, as software engineering researchers, our world view is rather limited. We wonder how useful would ChatGPT be for common software engineering tasks. # I. INTRODUCTION the species, homo sapiens (humans) started to emerge in what is the present day con- tinent of Africa [Hublin et al.(2017)]. Since then, humans have made spectacular progress in the fields of Science, Technology, Engineering and Mathematics. An indicative but not exhaustive list of these wonderful achievements consists of the discovery of electricity, antibiotics and the DNA; the invention of agriculture, printing press, the number zero and computers; exploration of space (sending men to the moon), nuclear fission (splitting the atom), the development of the internet and the world wide web. Towards the above, we catalog a list of fifteen fairly common software engineering tasks spanning the breadth of software engineering. These tasks range across the sub- areas of software development, software quality assurance and software maintenance. We then initiate a conversation with ChatGPT with a specific software engineering task and gauge its response (by comparing with human expert ground truth and/or output from the state of the art tools). For example, we provide a Java method to ChatGPT and request it to provide a code review of the method. Such code reviews are typical in software development and are often done by experienced developers. We then contrast the provided review with the human expert review. Certain technology pundits have opined that a Chatbot software released on Nov 30, 2022, was a similar seminal milestone in human achievements. These pundits have com- pared the advent of ChatGPT to nuclear fission [Weber(2022)]. The chat bot known as ChatGPT was released to the public for beta testing by the OpenAI consortium. ChatGPT is a chat bot that can write and debug code, and, automatically We repeat the above experiment with different randomly chosen samples and note the accuracy of ChatGPT. We also repeat the experiment with different tasks such as code summa- 1To be fair, ChatGPT does not accept the hyperbolic comparisons. When we queried it as to where it stood in the pantheon of great human achievements, it modestly accepted that the aforementioned achievements ranked significantly higher. rization, duplicate bug report detection, test case prioritization and so on. We catalog the results noting the number of times ChatGPT does well and where possible, we juxtapose ChatGPT’s performance with respect to the human expert output or the state of the art tool output. The main contributions of this paper are as follows: • A first ever study of ChatGPT and its potential use for fifteen ubiquitous software engineering tasks • A comparison of the ChatGPT output with human gold set and/or state of the art for the above common software engineering tasks. The remainder of the paper is organized as follows: Sec- tion II delineates our main study, while, Section III portrays the related work and we conclude in Section IV. # II. STUDY In this section, we describe our study. We first describe ChatGPT and the our study setup. We then delineate the experiments for each task. A. ChatGPT ChatGPT is a large-scale language model developed by OpenAI [OpenAI(2022a)], [OpenAI(2022b)]. It is trained on a massive dataset of internet text and is able to generate human-like text responses on a wide range of topics. ChatGPT is based on the GPT (Generative Pre-training Transformer) architecture, which has been shown to be highly effective for natural language processing tasks such as language translation, text summarization, and question answering. The model is fine-tuned on specific tasks by fine-tuning the model on a smaller dataset with task-specific examples. ChatGPT seems to address a variety of applications including chatbots, language translation and language understanding. It is a powerful tool for natural language generation and understanding, and it has the potential to be used in a wide range of industries and applications. # B. Study Setup We used the ChatGPT versions released on December 15 2022 and January 9 2023 for our experiments. The study was conducted on our Windows laptop machine of typical configuration. For each of the tasks, we had a maximum of ten samples. For example, for the task of Method Name Suggestion, we interacted ten times with ChatGPT and each time we presented it with a Java method and asked it to suggest a suitable method name. While ten or fewer samples may appear to be very less for a study, it should be noted that this entire study is a completely manual and time consuming task. Further, for many tasks such as Method Name Suggestion, we also had to run the state of the art tool with the same input as was fed to ChatGPT and extract the output to juxtapose with the output of ChatGPT. Thus, the number of samples that we have per task is a reasonable sized sample in our opinion. In each of the following subsections, we describe our expe- rience with using ChatGPT for different software engineering please suggest method name public static int f(int value) { return value <= 0?1 value >= 0x40000000 ? 0x40000000 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); i Here are a few suggestions for the method name: 1. *nextPowero#Two” - This name conveys that the method returns the next power of two that is. greater than or equal to the given value. Fig. 1. Code Summarization : Method Name Suggestion tasks. Each subsection will first describe the task background such as what exactly is anaphora resolution; how we obtained the samples for the experiments; description of the ChatGPT output and comparison with the state of the art. Note that in some cases, there was no state of the art tool but we had human output (gold set), so we compared the ChatGPT output with the human output. Also in some cases, the state of the art tool was not publicly available and neither was a human gold set, so we manually evaluated the ChatGPT output. For each task, we present numbers on the accuracy of ChatGPT where accuracy is broadly defined as the number of times ChatGPT was correct i.e., its output matched the expected output (from a human or state of the art tool or our manual evaluation). We also present some examples (ChatGPT converation screenshots) of where ChatGPT did well and where it did not do well. We finally summarize the experiment in each subsection and share our opinion on whether ChatGPT is viable for that particular task. We now start describing each of the experiments that we did in the following subsections. C. Method Name Suggestion or Code Summarization Background: A method or a function name in any program- ming language is a succinct summary of what the method does. A well written descriptive method name can help developers in faster program comprehension as they can chose to read the method body or skip based on what they understand the method does. Thus, it is imperative that a method name describes precisely yet concisely what a method does. We wanted to explore if ChatGPT could be used for this common task in software development. Study: We used the ten publicly available sample Java methods from the companion website of one of the state of the art tools, code2seq [Alon et al.(2019)]. We also used the provided web interface of code2seq to generate the method name for each of the ten methods. These method names were used to compare with ChatGPT. Our chat with ChatGPT was simple: We began by requesting it to suggest a suitable method name for the code, which we copy pasted into our chat. Note that, each method had its name elided and replaced with a meaningless identifier f. A sample of our chat is shown in Figure 1. Results: ChatGPT suggested the correct method name for nine of the ten methods. ChatGPT also suggested better method names for three methods compared to the state of the void f(int sizeofentity, int delta, boolean isPE) { fTotalEntitySize +- delta; if (fTotalentitySize > TOTAL_ENTITY_SIZE_LIMIT_SYSTEM_VALUE) { fErrorReporter .reportError(XMLMessageF ormatter .XML_DONAIN, “TotalentitySizeLimitexceeded” , new Object[] { new Integer(TOTAL_ENTITY_SIZE_LIMIT_SYSTEM_VALUE)}, XMLErrorReporter .SEVERITY_FATAL_ERROR) ; t if (isPE) { if (sizeofentity > MAX_PARAMETER_ENTITY_SIZE_LIMIT_SYSTEM VALUE) { ErrorReporter. reportError (XMLMessageFormatter.XML_DOMAIN, “MaxParameterEntitySizel imitExceeded”, new Object[] { new Integer (MAX_PARAMETER_ENTITY_SIZE_LINIT_SYSTEM_VALUE)}, XMLErrorReporter. SEVERTTY_FATAL_FRROR) ; Fig. 2. Method name suggestion: check (ChatGPT) vs report (state of art) art. The state of the art generated a better name for one method compared to ChatGPT. These method names are shown in Table I. For the remaining six methods both techniques had method names of similar quality. ChatGPT saveBitMapToFile trackChildRequest nextPowerOfTwo generateRSAPrime computeStandardDeviation index index of child BlockTillDone check entity size limit waitForJobCompletion State of Art saveBitMap addChildRequest getPowerOfTwo generate Prime Number compute stddev index of target index of item check done report entity size limit waitForJob TABLE I METHOD NAME SUGGESTIONS BY CHATGPT AND STATE OF ART. BOLD TEXT INDICATES A BETTER NAME. Observations: We believe ChatGPT does very well in succinct code summarization i.e., method name suggestion. It generated the correct name nine of ten times. Even for the method where it was not accurate, it only got the action part wrong. It generated track instead of add, while getting the object of the action, right, i.e., childRequest. Further, as can be seen from the Table I, ChatGPT does generate more informative method names for certain methods. For example, consider the Java method shown in Figure 2. ChatGPT generates the name check entity size limit, while the state of the art provides the method name, report entity size limit. We believe that the method’s primary action is to check as evinced by the numerous if checks in the code. Thus, ChatGPT’s method name suggestion is better (more precise) than the state of the art. Finally, ChatGPT is noticeably faster in generating its response than the state of the art. Therefore, we believe that for the task for method name suggestion or short summary comment generation, ChatGPT performs excellently, generating concise yet precise method names. D. Log Summarization Background: Developers insert log statements at appro- priate locations in the source code to capture normal and anomalous behaviours. Logs are created when the software Can you please summarize the log below? unix.hw state_change.unavailable 1084635601 1 Component State Change : Component "alt0" is in the unavailable state ( HWID = 3098 ) unix hw state_change.unavailable 1084635601 1 Component State Change : Component "alt0" is in the unavailable state ( HWID = 41) unix hw state_change.unavailable 1084631135 1 Component State Change : Component "alt0" is in the unavailable state ( HWID = 2818 ) unix.hw state_change.unavailable 1084631135 1 Component State Change : Component "alt0" is in the unavailable state ( HWID = 4432) unix hw state_change.unavailable 1084631134 1 Component State Change : Component "alt0" is in the unavailable state ( HWID = 2958 ) © _ these log entries indicate that the component "altO” has changed to the unavailable state for a variety of hardware IDs (HWID). It appears that this state change is occurring multiple times for different hardware IDs. It is not clear from this information alone what the cause of the state change is or what implications it may have. More information would be needed to provide a thorough summary of these log entries Fig. 3. Log Summarization is run. Such logs are extremely useful for developers and system engineers in identifying and fixing different varieties of problems. However, logs can quickly grow in size to thousands of lines. To effectively analyze such logs, some form of summarization is needed. Study: We wished to understand if ChatGPT could suc- cinctly summarize logs. We gathered ten random logs from the dataset used in a state of the art technique [Meng et al.(2020)]. These logs have a summary already generated by the technique described in [Meng et al.(2020)]. Figure 3 shows a sample input log and ChatGPT’s summary. Note that the input has been truncated in the screenshot, but it was not truncated in the actual conversation. Results: ChatGPT generated an appropriate summary for all the ten logs. It also generated a better summary than the state of the art all the ten times. Observation: ChatGPT does exceedingly well in the task of log summarization, producing summaries that are better than the state of the art. A concrete example is shown in Figure 3. The ChatGPT summarizes the log as alt 0 component unavailable while the state of the art simply summarizes as state change. Thus, the ChatGPT summary is more informative without being overly verbose. # E. Commit Message Generation Background: Commit messages are succinct summaries of the code changes that were made by a developer for a particu- lar software revision. Commit messages help in faster program comprehension as one can obtain the gist of the changes made without getting into implementation details. However, writing succinct commit messages requires additional manual effort on the part of the developers and due to the multiple commits per day, a developer may not write commit messages. A study has found that almost 14% of the commits did not have a commit message [Dong et al.(2022)]. Study: We wished to ascertain if ChatGPT could generate commit messages. Due to the conversational interface of the ChatGPT, we could not provide the entire file versions of the modified files but instead only provided the code diffs Can you generate commit message for this code diff? - public final InputEventHandler getInputEventListener() { + public final InputEventHandler getInputEventHandler() { Here is a possible commit message for the code diff you provided: “Renamed ‘getInputEventListener' method to ‘getInputEventHandler Fig. 4. Commit Message Generation as shown in Figure 4. We gathered ten diffs from the evalu- ation dataset of the paper [Dong et al.(2022)] for use in our experiment. Results: ChatGPT generated the correct commit message seven of ten times. Observations: ChatGPT did generate very good commit messages as shown in the example of Figure 4. What was inter- esting was how seamlessly it understood the “diff” language, i.e., lines starting with ‘-’ are removed lines while lines starting with ‘+’ are added lines. Further it did not generate a naive verbatim message such as removed getInputEventListener and added getInputEventHandler. Instead it generated the message like a human would i.e., it understood that the change was a rename operation. We examined the three cases where ChatGPT was not successful. In these cases, ChatGPT was not in its generation but it generated an additional few words. For example, the developer message was: ”Changed the class FormAuthClientBase from private to private abstract”. Chat- GPT generated this part but added ”and inherited it from SimpleHttpClient”. As the inheritance was already present in the original version, we believe it is not correct to add to the commit message. Thus, ChatGPT can be used for commit message generation but a perusal of the generated message is needed to remove extraneous content. F. Duplicate Bug Report Detection Background: Bugs are unfortunately all too common in software. Not only are bugs commonplace, but multiple users can report the same problem. Duplicate bug reports are detrimental as they result in precious time being wasted by developers [Zhang et al.(2022)]. We wanted to determine if ChatGPT could help in duplicate bug report detection. Typical duplicate bug detection involves comparing a given bug report against a set of existing bug reports and checking if a duplicate exists. However, due to the ChatGPT interface, we modified the problem by providing two bug reports to ChatGPT and asking it if the bug reports were duplicates of each other. Study: We gathered ten bug reports marked as already having a prior duplicate bug from the publicly available bug report database of Microsoft VSCode (a popular source code editor) [Microsoft(2023)]. We provided pairs of duplicate bug reports to ChatGPT as input and asked it to decide whether the bug reports were duplicates. A sample of our interaction with ChatGPT is shown in Figure 5. (Note that due to space Bug 1: VSCode dissappeared after computer restart Bug 2: VS Code was lost on shutdown with pending update The two bug reports appear to describe similar problems. Both reports mention that VSCode was lost or disappeared after a computer restart or shutdown. The first one does not provide Fig. 5. Duplicate Bug Report Detection constraints, we have shown only the titles of the bugs in the figure. Although, in our actual converation, we provided both the title and the details.) Results: Out of the ten pairs of duplicate bug reports, ChatGPT correctly identified six pairs as being duplicates of each other. Observations: In Figure 5, ChatGPT was able to identify the duplicates although the bug reports used different terms to describe the same problem. However, in the four cases where ChatGPT failed, it perhaps was surprisingly confounded by the use of different terms. For example, in one pair of duplicate bug reports, the first report was Unable to copy and paste in output terminal bash, while, the second report was Terminal has no response to typing on Codespace. Thus, the results are largely underwhelming. ChatGPT is perhaps not fully suited to the task of duplicate bug report detection in its present release. # G. Merge Conflict Resolution Background: In modern software development, multiple developers can often work on the same unit of code such as a class or a file. To avoid conflicts, developers create their own branch in a version control repository such as git and make their changes. Periodically, changes from the different branches have to be synchronized or merged into the main or master branch. Unfortunately, multiple developers may make conflicting changes around the same lines of code. It is estimated that around 46% of merges result in a conflict. Resolving conflicts manually is a tedious and error prone activity [Svyatkovskiy et al.(2022)]. We explore if ChatGPT can automatically resolve merge conflicts. Study: We took ten random samples from the evaluation dataset provided by [Svyatkovskiy et al.(2022)]. With each sample, we asked ChatGPT to resolve the merge conflict by providing the following: 1) A base version of the file which has code common to both changes that are being merged. 2) Content of the file having one set of changes to be merged (Version 1) 3) Content of the file having the other set of changes to be merged (Version 2) A sample question and ChatGPT’s answer are shown in Figure 6. To compute ChatGPT’s accuracy, we juxtaposed ChatGPT’s output with the actual final resolved version (the original developer’s). Results: ChatGPT was successful 6 of 10 times. Can you please resolve the merge conflict in the code below: Base Version: y=9 z=0 var x = max(y, 10) Version 1 modifying base: Version 2 modifying base: y=9 y=9 z=0 z=0 let x = max(y, 11) var x = max(y, 12,z) console.log(x) console.log(x) console.log(x) One possible way to resolve the merge conflict in the code would be: Fig. 6. Merge Conflict Resolution Observation: When it was successful as in Figure 6, ChatGPT was impressive, deftly merging conflicting tokens. It also displayed human intelligence in some other situations. For example, the copy right year was 2019 in one version and 2020 in another. ChatGPT used the latest 2020 in its resolved merge operation. In the four cases where it failed, one sample was truly difficult to merge as the two versions had modified a method’s return type. In the other cases, ChatGPT simply did a union of the changes in the two versions which did not match with the developer’s merge operation. To conclude, ChatGPT perhaps needs more training to work better on resolving merge conflicts. H. Anaphora Resolution Background: Natural Language (NL) is commonly used to specify the software requirements, constraints under which it has to operate, performance expectations and so on. NL is unfortunately prone to issues of ambiguity. Ambiguity occurs when a word has multiple interpretations. An especially pervasive form of ambiguity is the one that occurs due to anaphoras. Anaphora is essentially a reference to entities mentioned earlier in the text. Typical examples of anaphors are pronouns such as it, he, she. Anaphora resolution is the task of detecting the entities to which an anaphor refers to. Study: We gathered a random set of ten requirement spec- ifications worded in English and needed anaphora resolution from the experimental dataset provided by one of the latest works on anaphora ambiguity [Ezzini et al.(2022)]. These requirement specifications had anaphora ambiguity and the resolution annotated by two human experts. We asked ChatGPT to perform anaphora resolution for each of the ten requirement specifications and compared its output with the gold set output of the human experts. A sample of our question and ChatGPT’s answer is shown in Figure 7. Results: ChatGPT correctly identified the antecedent which the anaphora referred to in all the ten instances. # to Please do anaphora resolution for “its” in the sentences below: ‘The ship readiness levels and expected annual usage of each Halifax-class ship will be specified by Canada. Staff (SS) operate and maintain the ship in accordance with its Design Intent In the second sentence, “its” refers to the “Halifax-class ship" Fig. 7. Anaphora Resolution please provide code review for below: public RuntimeFilterManager(QueryWorkUnit workUnit, Drillbit { this.rootWrapper = workUnit.getRootWrapper(); this.drillbitContext = drillbitContext; lineSeparator = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator")); } J) tere are a few suggestions for improving the code: 1, The *java.security.AccessController” class and the * sun.security.action.GetPropertyAction™ class are part of the Java Security API and are intended for use in contexts where security is a concern. It is generally not necessary to use these classes to obtain the value of a system property like ~1ine.separator™, and doing so may introduce unnecessary complexity and overhead. 2. Instead of using the ~java.security.AccessController” class, consider using the ~system.getProperty” method to obtain the value of the “line. separator” system property. This method is simpler and easier to use, and it does not require the use of a Fig. 8. Code Review Observation: For the task of anaphora ambiguity resolu- tion, ChatGPT is extremely viable. I. Code Review Background: Code review by experienced developers is an inalienable part of software quality assurance (along with static analysis and testing). Code review can find errors that are not found by testing or static analysis. For example, potential vulnerabilities in the libraries used. Code review requires experienced developers who unfortunately may not have the time to review code due to their everyday activities. Study: We collected ten random methods from a recent paper on automating code review [Tufano et al.(2022)]. We provided each method to ChatGPT and requested it to generate a code review. We contrasted the generated review with the original developers’ review present in the dataset. Figure 8 shows a sample code review generated by ChatGPT. Results: There was agreement between ChatGPT’s gener- ated code review and the original developer’s code review on only four of the ten cases. Observation: ChatGPT started impressively for code re- view generation as depicted in Figure 8. Particularly prominent was how it flagged the misuse of the Java Security API AccessController class and the recommendation to use the more benign System Property to get the new line property. This review matched exactly with the developer’s review. Sadly, ChatGPT did not do so well on the remaining sam- ples. We considered the possibility that the original developer had the benefit of domain knowledge about the project which enabled him/her to provide an insightful review comment which could not be replicated by ChatGPT as it was bereft of the domain knowledge. However, when we examined the cases where ChatGPT did not match the developer’s review, the discrepancy could not simply be ascribed to lack of domain knowledge about the code. For example, in one method, a message about a severe error was logged using the lowest logging level. The original developer review asked the level to be modified to the highest logging level viz., error level. ChatGPT did not identify this. Thus, we conclude that ChatGPT in its current form cannot be used for code review generation. J. Type Inference Suggestion Background: Dynamic typing that is allowed in languages like Python enables faster prototyping and hence has found resonance among developers; especially those developing ma- chine learning applications. However, dynamic typing can lead to issues in security, performance and program comprehension. Hence, some kind of type hints about a variable are desired strongly by the developers [Peng et al.(2022)]. Study: We used ten random Python functions from the dataset of [Peng et al.(2022)] for the study. We asked Chat- GPT about the type of certain variables in the given function. A sample is shown in Figure 9. The dataset had the ground truth i.e., the type hints for the variables. Results: ChatGPT succeeded seven out of ten times. Observations: Figure 9 demonstrates an impressive type in- ference done by ChatGPT. When we initially saw the response, we thought that ChatGPT was incorrect about the return list containing both integers and placeholder objects. After reading the function multiple times, we discovered that ChatGPT was correct. We also examined the cases where ChatGPT was incorrect. In one case, ChatGPT inferred the type of a variable as an array in the numpy library while in actuality, it was an array in another library. In another case, ChatGPT was not able to correctly identify the return type as it was a function call and it did not have access to the function body. To summarize, ChatGPT while not being perfect can be a good adjunct tool for type inference. K. Code Generation from Natural Language for Data Frame Analysis Background: One common work activity that many scien- tists, especially, data scientists do is analyze data. Typically, data is in the form of a table as shown for example in the top part of Figure 10. Data Scientists analyze the data by writing code in Python (often with the numpy and pandas library). We wanted to explore how ChatGPT would perform in generating data analysis code given natural language requirements. Study: We provided a tabular data set to ChatGPT and asked it to generate Python code for the questions shown below: 1) How many unique test cases are present? 2) Which test case has maximum failures? Type of ‘text’ and return type? def parse ( text ): normalized_text = _normalize_text ( text ) tmp = ast. literal_eval ( normalized_text ) shape = [] placeholders = {} fori, tin enumerate ( if isinstance (t, str): pt = Placeholder ( label = t) placeholders [ t] = pt tmp) elif isinstance (t , int ) pt=t shape . append (pt) return shape , placeholder The input parameter ‘text’ is a string. The return type is a tuple containing two elements: a list of integers and Placeholder objects, and a dictionary. Ithanks but what is the key and value type in the return dictionary? In the returned dictionary, the keys are strings and the values are Placeholder objects. The dictionary is created by using the label attribute of the Placeholder objects as the keys and the Placeholder objects themselves as the values. Fig. 9. Type Inference 3) What is the average execution time of each test case? 4) Which test case leads to the maximum high priority bugs? 5) Write code to check if there is a correlation between execution time and whether the test passes or fails. 6) Generate code to determine correlation between execu- tion time and pass or fail using Spearman or Pearson correlation. 7) For the given data, can you generate a machine learning classifier to predict whether a test run passes or fails? 8) Can you use test case name and execution time as feature? 9) Can you generate code for test case prioritization based on past results? 10) Write code to get bug count per component per priority. Note that the data frame and the questions are not the standard tutorial dataframe and questions that one can find on the Internet. Thus, the answers of ChatGPT i.e., the code it generates is perhaps not something that is copied directly from the Internet. Once ChatGPT generated its response which included pan- das code, we copy pasted the code into a Jupyter notebook and validated the code by executing it. Results: ChatGPT generated the correct functioning code in eight of the ten cases. The two questions marked in bold above represent the failure cases. Observations: ChatGPT correctly recognizes the prevailing paradigm of using the pandas library for such data analysis in Python. It generates appropriate code with well named and meaningful identifiers. The produced code is also well commented as shown in Figure 10. Further, even more impressive is the fact that to compute average execution time, it understands that the actual execution time per run must be found and computes this as the difference Thave the following data test_case,result.start_time,end_time,bug, Component, te1,1,1/1/2021 1:12,1/1/2021 1:13,none,c1,cy1,200 tc2,0,1/1/2021 1:13,1/1/2021 1:26,high,c1,cy1,150 t¢3,0,1/1/2021 1:13,1/1/2021 1:19,medium,c2,cy1,250 ted,1,1/1/2021 1:13,1/1/2021 1:15,none,c3,cy1,100 te5,0,1/1/2021 1:13,1/1/2021 1:18,low,c4,cy1,50 Yes, here is an example of Python code that can be used to determine the number of unique test cases present in the data pandas as pd unique_test J.unique() nun_unique_test_cases (uni que_test_cases) Fig. 10. Code Generated by ChatGPT as a response to ”Generate code to determine number of unique test cases.” of the columns end time and start time. It also understood that in this particular data frame, 0 represented failure of a test run (typically, the paradigm in test case executions is to use 0 for success and 1 for failure). the code generated by ChatGPT was not satisfactory. These are the highlighted questions above. For the first of these questions, we asked it to generate code to learn a machine learning classifier to predict which test run would pass or fail. In our data set, there were two features that would help find the segregating hyperplane between pass and fail, viz., test case name and execution time. However, ChatGPT did not select these as features initially and only after prompting by us via a subsequent question, did it chose them as features. ChatGPT also did not generate correct code for the test prioritization question. Here it assumed that a result value of 1 stood for failure and thus produced code which would result in a test prioritization order that was the opposite of the correct order. This was surprising because to answer a previous question about faults, it had correctly generated code to count the zeros to denote total faults. To summarize, ChatGPT does very well in understanding the natural language questions on a dataframe and generates suitable code. It perhaps suffers a bit in feature engineering i.e., in deciding which features are important to learn a good classifier that can distinguish between the positive and negative samples. L. Defect or Vulnerability Detection Background: Given lines of source code, the task is to identify whether it is an insecure code that may attack software systems, such as resource leaks, use-after-free vulnerabilities Does the code below have any vulnerabilities? short add (short b) { short a = 32767; if (b > 0) a=a+b; return a) However, this function has a potential vulnerability, it doesn't check if adding b will cause an overflow, if b is a very large number, the add operation will cause the value of 'a' to wrap around and become a negative number. This can lead to unexpected results, data corruption Fig. 11. Vulnerability Detection and Denial of Service attacks. This is essentially a binary classification problem. Study: We took ten random methods that were marked as having vulnerabilities from the dataset in [Zhou et al.(2019)]. We provided each method to ChatGPT and asked it to identify if the method had a vulnerability as shown in Figure 11. Results: ChatGPT correctly identified the vulnerabilities in only four of the ten cases. Observations: It should be noted that vulnerability detec- tion is a relatively difficult task requiring extensive program analysis (control and data flow) which perhaps ChatGPT is not trained for. Perhaps the relatively low level nature of the code snippets which are C programs written with pointer access and indi- rection might have been the reason as to why ChatGPT was not able to identify the vulnerabilities. To conclude, we perhaps cannot use ChatGPT as is for vulnerability detection. M. Code Clone or Duplicate Code Detection Background: Code clones are code snippets that accom- plish a similar functionality. Code clones may have similar or different syntax (for example, one snippet may loop using for, while the other snippet may loop using while). Code clones can increase maintenance costs due to duplication of bugs. Hence there are several approaches to automated code clone detection [Svajlenko et al.(2014)]. functions ten marked as clones of each other from the BigCloneBench dataset [Svajlenko et al.(2014)]. We provided the methods as input to ChatGPT and requested it to identify if the methods were clones of each other. A sample is shown in Figure 12. Results: ChatGPT was able to correctly identify six of the ten code clones. Notice how it was able to identify the clones in Figure 12 despite the methods having different names and parameters and differing implementation. Observation: We examined the four cases where ChatGPT erroneously said that the method pairs were not similar. We found that in three cases, ChatGPT was actually correct and the ground truth set was incorrect. In the remaining case, it was a matter of semantics. The input methods were both named ‘copyFile’ but ChatGPT argued that there were not duplicates because the second method was actually ’copyFiles’ i.e., it was copying multiple files if the input source file was a directory (via a recursive call). Thus, we believe ChatGPT does well in the code clone detection and is able to make fine grained distinctions and cogent arguments about its decisions. Are the two methods below clones or duplicates of each other? public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text. getBytes(ENCODING)); log.error(nsae, nsae); } catch (NoSuchAllgorithmException nsae) { } catch (UnsupportedEncodingException uee) { byte[] raw = mDigestdigest); BASE64Encoder encoder = return encoderencode(raw); } | log.error(uee, uee); new BASE64Encoder(); public synchronized String encryptPassword(String passwordString) throws Exception { MessageDigest digest = null; digest = MessageDigest.getInstance("SHA"); ldigest.update(passwordString.getBytes("UTF-8")); hash = (new BASE64Encoder()).encode(raw); byte rawl] = digestdigest); String return hash; } ®) The two methods have similar functionality but different implementation. # Fig. 12. Code Clone Identification void map_has_hasValue (){ Map < String, String > breeds = Maps . newHashMap (), breeds put (“labrador" , "buzz" ); breeds . put ( “dachshund” , “gypsy” ) ; breeds. put ( "boxer", "buddy" ) ; "<AssertPlaceHolder>" ;} assertTrue(breeds.containsValue("gypsy")} The above assert statement will check that the Map object ‘breeds’ contains the value "gypsy" The method *containsvalue’ returns a boolean indicating whether the map contains the given value, so “asserttrue’ will check that it is true, which indicates that the value "gypsy’ is present in the map. Fig. 13. Test Oracle Generation N. Test Oracle Generation Background: Software testing can be done on the entire software (functional testing) or can be done at smaller gran- ularity such as testing of a unit, where a unit is a class (file) or a method (function). There is considerable interest and research on automating unit tests, especially, automatically generating a unit test, given a method under test (focal method) with its signature and body. Unit testing typically involves invoking the focal method with suitable parameters and then checking the return value. The return value is checked using assert statements. One challenging aspect of unit test generation is to auto- matically generate the correct assertions (test oracle), as the developers may not always be completely familiar with the method under test. Study: We wanted to inspect if ChatGPT could help in the task of test oracle generation. Towards this goal, we collected ten random samples from the state of the art paper described in [Yu et al.(2022)]. These samples had the method under test and the test code with a place holder for the assert statement to be generated as shown in Figure 13. We requested ChatGPT to generate a suitable assert statement. We then compared ChatGPT’s assert statement with the ground truth which was the original developer assertion. Results: ChatGPT’s assert statement matched the ground truth six of ten times. Observations: ChatGPT not only generated the assert state- ment but also provided a cogent explanation of the assertion as shown in Figure 13. We examined the four cases where ChatGPT failed and found that in one instance, the test method was testing a vector dot product operation while the focal method was the Vector class constructor. ChatGPT identified this anomaly correctly. Considering the other failure cases, ChatGPT generated the opposite assertion (assertTrue (m.matches()) as opposed to assertFalse(m.matches()). In another case, it erroneously used a variable declared within the focal method in the assert statement of the test method. Thus, we believe ChatGPT’s performance was average in the task of oracle generation. However, with some manual supervision, it can be utilized to generate assert statements. O. Code Refactoring Background: Code refactoring is a software mainte- nance activity in which developers modify the code to make it more readable and hence increase maintainabil- ity [Silva et al.(2016)]. Refactoring can be done at a class level, method level and so on. One particular method level refactoring technique is ExtractMethod refactoring in which portions of code from an existing method or function is extracted into another method, while replacing the original code with a call to the extracted method. Study: We gathered different ExtractMethod refac- torings performed by developers in [Silva et al.(2016)] and asked ChatGPT to perform Extract- Method refactoring. We contrasted the modified code with the refactoring done by the original developers. Results: Refactorings suggested by ChatGPT did not agree with the original extract method refactorings for any of the samples. Observations: We manually examined the ExtractMethod refactorings produced by ChatGPT. While they did not match with the developer’s refactorings, we found them to syntacti- cally correct and semantically matching the original method’s computational intent. We also found the ChatGPT’s refactored method more read- able compared to the original unrefactored method. ChatGPT also provided good identifier names to the extracated methods, its parameters and the return value. ExtractMethod refactoring is a subjective activity, the de- cision on which statements should be extracted into another method is inherently subjective in nature. Thus, the fact that the method extractions performed by ChatGPT does not match with the developer’s refactorings should not preclude its usage for refactoring. P. Natural Language Code Search Background: Developers often have to read and understand code written by other developers to fix bugs and/or add new features. In large code bases with thousands of files and millions of lines of code, developers resort to searching the code base to understand how and where a feature is implemented. While such an activity is a classical information retrieval search and rank problem, we can also formulate the problem as a binary classification problem: Given a natural language query such as ”create directory using absolute path”, "doc": "python "create directory" using 'relative path", “code”: “def create_path(path): Creates a absolute path in the file system. param path: The path to be created " os.makedirs(path)" “ import os __ if not os.pathexists(path): No, the code does not appear to answer the documentation query. The code defines a function *ereate_path(path)* which creates an absolute path in the file system. The code does not mention anything about creating directory by using relative path, whereas the documentation query is asking about creating directory by using relative path. # Fig. 14. Code Search determine if a snippet of code ”answers” the query i.e., the code performs the task(s) mentioned in the query. lan- from the guage queries and an associated code snippet CoSQA dataset (Code Search and Question Answer- ing) [Huang et al.(2021)]. Each pair had a ground truth label of 1 or 0, depending on whether the code answered the query or not, respectively. We then provided the natural language query and the code snippet to ChatGPT and asked it if the code answered the query, as shown in Figure 14. We contrasted the ChatGPT output with the ground truth in the CoSQA dataset. Results: The output of ChatGPT matched the ground truth seven of ten times. Observation: ChatGPT was able to make fine-grained and subtle distinctions of meaning as exemplified in Figure 14 (between ”relative” and ”absolute” paths). Upon inspection of the three failed cases, we found that in one case the ground truth had an error. The documentation asked for code to check a ctypes array whereas the code checked for a C++ array, which ChatGPT explained was different. In another case, we believe the natural language query was poor and not informative enough ( ”ask if a method can see a variable python”). Therefore, for code search ChatGPT could be used as an adjunct tool.. # Q. Test Case Prioritization Background: In modern software development, we typi- cally have thousands of test cases. Due to the frequent updates to the code base (often multiple times per hour), it is not fea- sible to run all the test cases for every update. Thus, a ranking scheme to prioritize test cases that are more likely to fail is desired and several automated approaches have been proposed for test case prioritization [Bagherzadeh et al.(2020)]. Broadly, we explored if ChatGPT can help with test pri- oritization using three different approaches which are each described below: 1) Prioritization based on past faults found 2) Prioritization based on code changes 3) Prioritization based on operation order 1) Prioritization based on past faults found: One approach to prioritization is to use the previous or historical fault(s) found by a test case. We provided the data as shown in the top half of Figure 15. The data shows five test cases viz., A to E and ten faults. Note that a fault can be detected by different test cases. For example, the first fault is found by test cases, A, B and C, while the last (tenth) fault is found only by test case E. We asked ChatGPT as to which prioritization order of the test cases was better. For this data, executing test case C and then test case E, ensures that all the faults are detected and thus C and E should be ranked at the top. As can be seen from the lower half of the Figure 15, ChatGPT provided the correct order CEBAD, although the reasoning it provided was not consistent with its answer. The reasoning of ChatGPT is based on the naive way of prioritization, which favors test cases which find most faults. However, such an ordering is often suboptimal, as in this case. 2) Prioritization based on code changes: Another approach to test prioritization is to rank based on what changed in the code. Here, we take the code diffs and use it as a query against each test case and rank based on a similarity measure such as cosine similarity. This is an Information Retrieval based approach [Peng et al.(2020)]. We provided sample code diffs from the above paper’s dataset and also each test case as input to ChatGPT and requested it to prioritize based on textual similarity. However, ChatGPT could not perform this task, which is surprising since it did perform code clone detection, duplicate bug report identification which were also somewhat similar tasks. 3) Prioritization based on operation order: Modern soft- ware architecture especially the microservices architecture largely relies on REST APIs [Martin-Lopez et al.(2022)]. These APIs perform operations such as add item to cart, checkout and so on. The specifications of these APIs such as the parameters they take, the constraints on them, the return values and so on are stored in a JSON file conforming to a specification called Swagger specification. Within the REST APIs for an application, there is typically an ordering among the APIs. For example, the API, addToCart should precede checkout. A partial order among the APIs can be obtained by analyzing the Swagger JSON. We provided ChatGPT with a Swagger JSON for a sample application (Petstore) and asked it to obtain the partial order among the APIs. While it did understand the Swagger spec- ification, unfortunately, it was not able to prioritize amongst the APIs. Observation: ChatGPT can be used with prioritization based on past faults found. However, for other kinds of prioritization it perhaps is not viable in its current state. # R. Other Tasks We experimented with a few more tasks which we describe # below: typically downloaded and to reduce download size, a name like nextPowerOfTwo can be minified or uglified to a name like f. However, we may need to recover the original name for comprehension, security review and so on. We wanted to explore if ChatGPT can help in this task. We requested ChatGPT to deobfuscate the illustrative ex- ample JavaScript method shown in [Vasilescu et al.(2017)]. However, ChatGPT was not able to recover the original names. Thave the following matrix with test cases and faults found by them. Can you tell me which test case prioritization order is better? ABCDE or CEBAD? To prioritize the test cases, you could consider the number of faults each test case finds. Test_case_C finds the most faults, so it could be the first priority. Test_case_B finds the second most faults, so it could be the second priority. Test_case_A finds the third most faults, so it coul be the third priority. Test _case_D finds the fourth most faults, so it could be the fourth priority Test_case_E finds the fewest faults, so it could be the fifth priority. Using this approach, the prioritization order would be: CEBAD. Alternatively, you could prioritize test cases based on the specific faults they find. For example, if some faults are more critical than others, you might prioritize test cases that find those faults first_In this case, the prioritization order might be different. Fig. 15. Test Case Prioritization Thus, for this task of deobfuscation, ChatGPT may perhaps not be useful. 2) Efficient Algorithm Generation:: Often developers have to write efficient code that takes less time and space. For example, device an algorithm that runs in O(n) time. We wanted to explore if ChatGPT could help in this task. We gathered a few sample problems with such time complexity constraints from the popular competitive programming website LeetCode [LeetCode(2023)] and asked ChatGPT to solve the problem. ChatGPT was able to generate code which matched the ground truth solutions. In future work, we will evaluate this task with the standard ten samples. 3) Automated Program Repair:: Here the task is to au- tomatically fix bugs in the code, thus reducing the cost of bug-fixes. We took a few Java methods with bugs from the CodeXGLUE dataset [Lu et al.(2021)] and asked ChatGPT to automatically fix the bugs. However, ChatGPT was not able to perform this task because the input method had normalized all the identifier names (for example, private TYPE 1 getType ( TYPE 2 VAR 1 ) ). In future work, we will evaluate this task using the original methods with bugs. S. Overall Summary: Table II summarizes the overall performance of ChatGPT. T. Threats to Validity The number of samples used in the study might be consid- ered small. However, as explained before in Section II, we perforce had to limit the number of conversations we had with ChatGPT as the study is a completely manual and time consuming activity. the tasks themselves are not representative of the kind of activities done in software engineering. To address this concern, we chose the tasks based on multiple different factors such as domain knowledge of the industry; examination of the activities done in several popular open source projects; the research trends shown in the academia and industry. Task Method Name Suggestion Log Summarization Anaphora resolution Python Type Inference Commit Message Generation Code Review Duplicate Bug Report Detection Natural Language Code Search Vulnerability Detection Code Clone Detection Test Oracle Generation Code Generation from NL Merge Conflict Resolution Code Refactoring* Test Prioritization ** Success 9 10 10 7 7 4 6 7 4 6 6 8 6 10 - Failure 1 0 0 3 3 6 4 3 6 4 4 2 4 0 - TABLE II CHATGPT: PERFORMANCE ACROSS SOFTWARE TASKS. * DENOTES manually verified for syntactic and semantic correctness. ** DENOTES THAT CHATGPT WAS NOT ABLE TO PERFORM THE TASK AT ALL ACROSS MULTIPLE SAMPLES. # III. RELATED WORK CodeBERT [Feng et al.(2020)] was the earliest bimodal pre-trained model for NL and programming language (PL). It was pre-trained on 6 programming languages. The objec- tive functions included Masked Language Model (MLM) on bimodal data of NL-PL pairs and Replaced Token Detection (RTD) [Clark et al.(2020)] on both unimodal and bimodal data and evaluated on downstream tasks including natural language code search and code-to-documentation generation. CodeXGLUE [Lu et al.(2021)], [cod(2022)] is an evalua- tion benchmark released by Microsoft for General Language Understanding Evaluation benchmark for CODE. It includes 14 datasets for 10 diversified PL tasks covering code-code (clone detection, defect detection, cloze test, code completion, code refinement, and code-to-code translation), text-code (NL code search, text-to-code generation), code-text (code summa- rization) and text-text (documentation translation) scenarios. Codex is OpenAI’s natural language to code AI model [Chen et al.(2021)], [AI(2021)], [AI(2022)]. It is trained for the task of generating standalone Python functions from docstrings, and evaluate the functional correctness of code samples automatically through unit tests. The work also intro- duces HumanEval, an evaluation set to assess programming language comprehension, reasoning, algorithms, and simple mathematics. Evaluation of several Codex models (parameters ranging from 12M to 12B), shows that a compact Codex- 300M version outperforms GPT-J-6B. Limitations of large training data, challenges with long specifications, syntactically incorrect code apart from legal, environmental risks associated have been discussed. The Codex model is mostly associated with Copilot tool of GitHub [AI(2021)]. The differentiating factor relates to integration of Copilot in a development IDE [GitHub(2022)]. However, it is well acknowledged that an independent evaluation of either Codex or Copilot will be challenging owing to lack of visibility of the training data [Xu et al.(2022)]. From a human usability perspective, a recent study [Vaithilingam et al.(2022)], conducted on 24 participants, reports that although users did use Copilot as a starting point in daily programming tasks, challenges in understanding, editing, and debugging these code snippets hindered their task-solving effectiveness. 2022, InstructGPT [Ouyang et al.(2022)]. This LLM was trained on the task to act in accordance with the user’s intention. For this, reinforcement learning with human feedback (RLHF) was used with GPT-3 model to follow a broad class of written instructions. It was found that users preferred outputs from InstructGPT over GPT-3. EleutherAI released The Pile, an 825 GB English text corpus for building large-scale language models (LLM) [Gao et al.(2021)] in 2020. As an alternative to OpenAI’s GPT-3, open-source LLMs such as GPT-Neo and GPT-J [Wang and Komatsuzaki(2021)], [Black et al.(2021)] were re- leased. In 2022, GPT-NeoX, a 20B parameter LLM was released. All these models were trained on The Pile and are available freely to the public. The work of [Xu et al.(2022)] evaluates six large language models of code including Codex, CodeGen and the open- source variants (such as GPT-J, GPT-Neo and GPT-NeoX trained on code) alongside their proposed open-source large language model of code (trained on 12 programming lan- guages). The chosen tasks are code completion and code synthesis from natural language description. Their evaluations show that Codex variant with 300M parameters shows promise on the HumanEval dataset and that open source LLM for code still have a lot of room for improvement. We think, the ChatGPT in its current form could be a consolidation of OpenAI’s various code-to-text and text-to- text initiatives along with their recent advances in learning to act according to user’s intent. To the best of our knowledge, ours is the first research work on ChatGPT to do a rigorous study across different software tasks. # IV. CONCLUSION In this paper, we asked the question ”What is the utility of ChatGPT towards common software engineering tasks such as code summarization, test oracle generation and so on?” To answer the above question, we chose fifteen ubiquitous tasks in software development and conducted a study to check the feasibility of ChatGPT towards helping with these tasks. We gathered ten random samples for each task such as code clone detection and asked ChatGPT via its chatbot interface to perform the desired task (for example, answer if the provided code snippets were duplicates or clones of each other). We then compared the answer of ChatGPT with the human expert output and/or state of the art tool output. We computed the accuracy of ChatGPT for each task. ChatGPT does very well on the tasks of log summa- rization, anaphora resolution, code summarization (method name generation) and code clone detection. The accuracy of ChatGPT is average for the tasks of commit message generation, code review generation, natural language code search, merge conflict resolution. ChatGPT can be used for these tasks but perhaps the users will have to check its output carefully. ChatGPT performs poorly on code vulnerability detection. For certain tasks, like information retrieval based test prioritization, ChatGPT was not able to provide an answer at all. Overall, ChatGPT does represent a very significant mile- stone and it can be used for some software engineering tasks as is or for certain tasks as an adjunct tool. # REFERENCES [cod(2022)] 2022. CodeXGLUE. https://microsoft.github.io/CodeXGLUE/ [AI(2021)] Open AI. 2021. Codex Limited Beta. https://platform.openai. com/docs/models/codex [AI(2022)] Open AI. 2022. Powering Next Generation Applications with OpenAI Codex. https://openai.com/blog/codex-apps/ # za [Alon et al.(2019)] Uri Alon, Shaked Brody, Omer Levy, and Eran Yahav. 2019. code2seq: Generating Sequences from Structured Representations of Code. In International Conference on Learning Representations. [Bagherzadeh et al.(2020)] Mojtaba Bagherzadeh, Nafiseh Kahani, and Li- onel C. Briand. 2020. Reinforcement Learning for Test Case Pri- oritization. CoRR abs/2011.01834 (2020). arXiv:2011.01834 https: //arxiv.org/abs/2011.01834 [Black et al.(2021)] Sid Black, Leo Gao, Phil Wang, Connor Leahy, and Stella Biderman. 2021. GPT-Neo: Large Scale Autoregressive Lan- guage Modeling with Mesh-Tensorflow. https://doi.org/10.5281/zenodo. 5297715 If you use this software, please cite it using these metadata.. [Chen et al.(2021)] Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde de Oliveira Pinto, Jared Kaplan, Harrison 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, An- drew N. Carr, Jan Leike, Joshua Achiam, Vedant Misra, Evan Morikawa, Alec Radford, Matthew Knight, Miles Brundage, Mira Murati, Katie Mayer, Peter Welinder, Bob McGrew, Dario Amodei, Sam McCan- dlish, Ilya Sutskever, and Wojciech Zaremba. 2021. Evaluating Large Language Models Trained on Code. CoRR abs/2107.03374 (2021). arXiv:2107.03374 https://arxiv.org/abs/2107.03374 [Clark et al.(2020)] Kevin Clark, Minh-Thang Luong, Quoc V Le, and Christopher D Manning. 2020. Electra: Pre-training text encoders as discriminators rather than generators. arXiv preprint arXiv:2003.10555 (2020). [Dong et al.(2022)] Jinhao Dong, Yiling Lou, Qihao Zhu, Zeyu Sun, Zhilin Li, Wenjie Zhang, and Dan Hao. 2022. FIRA: ¡u¿fi¡/u¿ne-Grained G¡u¿ra¡/u¿ph-Based Code Change Representation for Automated Com- mit Message Generation. In Proceedings of the 44th International Conference on Software Engineering (Pittsburgh, Pennsylvania) (ICSE ’22). Association for Computing Machinery, New York, NY, USA, 970–981. https://doi.org/10.1145/3510003.3510069 [Ezzini et al.(2022)] Saad Ezzini, Sallam Abualhaija, Chetan Arora, and Mehrdad Sabetzadeh. 2022. Automated Handling of Anaphoric Am- biguity in Requirements: A Multi-Solution Study. In Proceedings of the 44th International Conference on Software Engineering (Pittsburgh, Pennsylvania) (ICSE ’22). Association for Computing Machinery, New York, NY, USA, 187–199. [Feng et al.(2020)] Zhangyin Feng, Daya Guo, Duyu Tang, Nan Duan, Xiaocheng Feng, Ming Gong, Linjun Shou, Bing Qin, Ting Liu, Daxin Jiang, and Ming Zhou. 2020. CodeBERT: A Pre-Trained Model for Programming and Natural Languages. CoRR abs/2002.08155 (2020). arXiv:2002.08155 https://arxiv.org/abs/2002.08155 [Gao et al.(2021)] Leo Gao, Stella Biderman, Sid Black, Laurence Golding, Travis Hoppe, Charles Foster, Jason Phang, Horace He, Anish Thite, Noa Nabeshima, Shawn Presser, and Connor Leahy. 2021. The Pile: https: An 800GB Dataset of Diverse Text for Language Modeling. //arxiv.org/abs/2101.00027 [GitHub(2022)] GitHub. 2022. GitHub Copilot. https://docs.github.com/en/ copilot [Huang et al.(2021)] Junjie Huang, Duyu Tang, Linjun Shou, Ming Gong, Ke Xu, Daxin Jiang, Ming Zhou, and Nan Duan. 2021. CoSQA: 20,000+ Web Queries for Code Search and Question Answering. In Proceedings of the 59th Annual Meeting of the Association for Com- putational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers). Association for Computational Linguistics, Online, 5690–5700. https://doi.org/10. 18653/v1/2021.acl-long.442 [Hublin et al.(2017)] Jean-Jacques Hublin, Abdelouahed Ben-Ncer, Shara E. Bailey, Sarah E. Freidline, Simon Neubauer, Matthew M. Skinner, Inga Bergmann, Adeline Le Cabec, Stefano Benazzi, Katerina Harvati, and Philipp Gunz. 2017. New fossils from Jebel Irhoud, Morocco and the pan-African origin of Homo sapiens. Nature 546, 7657 (01 Jun 2017), 289–292. [LeetCode(2023)] LeetCode. 2023. The World’s Leading Online Program- ming Learning Platform. https://leetcode.com/ [Lu et al.(2021)] Shuai Lu, Daya Guo, Shuo Ren, Junjie Huang, Alexey Svyatkovskiy, Ambrosio Blanco, Colin B. Clement, Dawn Drain, Daxin Jiang, Duyu Tang, Ge Li, Lidong Zhou, Linjun Shou, Long Zhou, Michele Tufano, Ming Gong, Ming Zhou, Nan Duan, Neel Sundaresan, Shao Kun Deng, Shengyu Fu, and Shujie Liu. 2021. CodeXGLUE: A Machine Learning Benchmark Dataset for Code Understanding and Generation. CoRR abs/2102.04664 (2021). [Martin-Lopez et al.(2022)] Alberto Martin-Lopez, Sergio Segura, and An- tonio Ruiz-Cort´es. 2022. Online Testing of RESTful APIs: Promises the 30th ACM Joint European and Challenges. In Proceedings of Software Engineering Conference and Symposium on the Foundations of Software Engineering (Singapore, Singapore) (ESEC/FSE 2022). Association for Computing Machinery, New York, NY, USA, 408–420. https://doi.org/10.1145/3540250.3549144 [Meng et al.(2020)] Weibin Meng, Federico Zaiter, Yuheng Huang, Ying Liu, Shenglin Zhang, Yuzhe Zhang, Yichen Zhu, Tianke Zhang, En Wang, Zuomin Ren, Feng Wang, Shimin Tao, and Dan Pei. 2020. Summarizing Unstructured Logs in Online Services. CoRR abs/2012.08938 (2020). arXiv:2012.08938 https://arxiv.org/abs/2012.08938 [Microsoft(2023)] Microsoft. 2023. VSCode Issue Tracker. https://github. com/microsoft/vscode/issues/. [OpenAI(2022a)] OpenAI. 2022a. ChatGPT. https://chat.openai.com/ [OpenAI(2022b)] OpenAI. 2022b. ChatGPT: Optimizing Language Models for Dialogue. https://openai.com/blog/chatgpt/ [Ouyang et al.(2022)] Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agar- Training language wal, Katarina Slama, Alex Ray, et al. 2022. models to follow instructions with human feedback. arXiv preprint arXiv:2203.02155 (2022). [Peng et al.(2020)] Qianyang Peng, August Shi, and Lingming Zhang. 2020. Empirically Revisiting and Enhancing IR-Based Test-Case Prioritization. In Proceedings of the 29th ACM SIGSOFT International Symposium on Software Testing and Analysis (Virtual Event, USA) (ISSTA 2020). Association for Computing Machinery, New York, NY, USA, 324–336. https://doi.org/10.1145/3395363.3397383 [Peng et al.(2022)] Yun Peng, Cuiyun Gao, Zongjie Li, Bowei Gao, David Lo, Qirun Zhang, and Michael Lyu. 2022. Static Inference Meets Deep Learning: A Hybrid Type Inference Approach for Python. In Proceedings of the 44th International Conference on Software Engineer- ing (Pittsburgh, Pennsylvania) (ICSE ’22). Association for Computing Machinery, New York, NY, USA, 2019–2030. https://doi.org/10.1145/ 3510003.3510038 [Silva et al.(2016)] Danilo Silva, Nikolaos Tsantalis, and Marco Tulio Va- lente. 2016. Why We Refactor? Confessions of GitHub Contributors. In Proceedings of the 2016 24th ACM SIGSOFT International Symposium on Foundations of Software Engineering (Seattle, WA, USA) (FSE 2016). Association for Computing Machinery, New York, NY, USA, 858–870. https://doi.org/10.1145/2950290.2950305 [Svajlenko et al.(2014)] Jeffrey Svajlenko, Judith F. Islam, Iman Keivanloo, Chanchal K. Roy, and Mohammad Mamun Mia. 2014. Towards a Big Data Curated Benchmark of Inter-project Code Clones. In 2014 IEEE International Conference on Software Maintenance and Evolution. 476– 480. https://doi.org/10.1109/ICSME.2014.77 [Svyatkovskiy et al.(2022)] Alexey Svyatkovskiy, Sarah Fakhoury, Negar Ghorbani, Todd Mytkowicz, Elizabeth Dinella, Christian Bird, Jinu Jang, Neel Sundaresan, and Shuvendu K. Lahiri. 2022. Program Merge Conflict Resolution via Neural Transformers. In Proceedings of the 30th ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering (Singapore, Singapore) (ESEC/FSE 2022). Association for Computing Machinery, New York, NY, USA, 822–833. [Tufano et al.(2022)] Rosalia Tufano, Simone Masiero, Antonio Mas- tropaolo, Luca Pascarella, Denys Poshyvanyk, and Gabriele Bavota. 2022. Using Pre-Trained Models to Boost Code Review Automation. In Proceedings of the 44th International Conference on Software Engineer- ing (Pittsburgh, Pennsylvania) (ICSE ’22). Association for Computing Machinery, New York, NY, USA, 2291–2302. https://doi.org/10.1145/ 3510003.3510621 [Vaithilingam et al.(2022)] Priyan Vaithilingam, Tianyi Zhang, and Elena L. Glassman. 2022. Expectation vs. Experience: Evaluating the Usability of Code Generation Tools Powered by Large Language Models. In Extended Abstracts of the 2022 CHI Conference on Human Factors in Computing Systems (New Orleans, LA, USA) (CHI EA ’22). Association for Computing Machinery, New York, NY, USA, Article 332, 7 pages. https://doi.org/10.1145/3491101.3519665 [Vasilescu et al.(2017)] Bogdan Vasilescu, Casey Casalnuovo, and Premku- mar Devanbu. 2017. Recovering Clear, Natural Identifiers from Ob- fuscated JS Names. In Proceedings of the 2017 11th Joint Meeting on Foundations of Software Engineering (Paderborn, Germany) (ESEC/FSE 2017). Association for Computing Machinery, New York, NY, USA, 683–693. https://doi.org/10.1145/3106237.3106289 [Wang and Komatsuzaki(2021)] Ben Wang and Aran Komatsuzaki. 2021. GPT-J-6B: A 6 Billion Parameter Autoregressive Language Model. https://github.com/kingoflolz/mesh-transformer-jax. [Weber(2022)] Peter Weber. 2022. OpenAI’s ChatGPT chatbot: The good, the very bad, and the uncannily fun. https://theweek.com/briefing/1019068/ openais-chatgpt-chatbot-the-good-the-very-bad-and-the-uncannily-fun [Xu et al.(2022)] Frank F. Xu, Uri Alon, Graham Neubig, and Vincent Josua Hellendoorn. 2022. A Systematic Evaluation of Large Language Models of Code. Association for Computing Machinery, New York, NY, USA. https://doi.org/10.1145/3520312.3534862 [Yu et al.(2022)] Hao Yu, Yiling Lou, Ke Sun, Dezhi Ran, Tao Xie, Dan Hao, Ying Li, Ge Li, and Qianxiang Wang. 2022. Automated As- sertion Generation via Information Retrieval and Its Integration with Deep Learning. In Proceedings of the 44th International Conference on Software Engineering (Pittsburgh, Pennsylvania) (ICSE ’22). As- sociation for Computing Machinery, New York, NY, USA, 163–174. https://doi.org/10.1145/3510003.3510149 [Zhang et al.(2022)] Ting Zhang, DongGyun Han, Venkatesh Vinayakarao, Ivana Clairine Irsan, Bowen Xu, Ferdian Thung, David Lo, and Lingxiao Jiang. 2022. Duplicate Bug Report Detection: How Far Are We? ACM Trans. Softw. Eng. Methodol. (dec 2022). https://doi.org/10.1145/ 3576042 Just Accepted. [Zhou et al.(2019)] Yaqin Zhou, Shangqing Liu, Jingkai Siow, Xiaoning Du, and Yang Liu. 2019. Devign: Effective Vulnerability Identification by Learning Comprehensive Program Semantics via Graph Neural Networks. Curran Associates Inc., Red Hook, NY, USA.
Title: A Deep Reinforcement Learning Chatbot: Summary: We present MILABOT: a deep reinforcement learning chatbot developed by the Montreal Institute for Learning Algorithms (MILA) for the Amazon Alexa Prize competition. MILABOT is capable of conversing with humans on popular small talk topics through both speech and text. The system consists of an ensemble of natural language generation and retrieval models, including template-based models, bag-of-words models, sequence-to-sequence neural network and latent variable neural network models. By applying reinforcement learning to crowdsourced data and real-world user interactions, the system has been trained to select an appropriate response from the models in its ensemble. The system has been evaluated through A/B testing with real-world users, where it performed significantly better than many competing systems. Due to its machine learning architecture, the system is likely to improve with additional data. # A Deep Reinforcement Learning Chatbot Iulian V. Serban, Chinnadhurai Sankar, Mathieu Germain, Saizheng Zhang, Zhouhan Lin, Sandeep Subramanian, Taesup Kim, Michael Pieper, Sarath Chandar, Nan Rosemary Ke, Sai Rajeshwar, Alexandre de Brebisson, Jose M. R. Sotelo, Dendi Suhubdy, Vincent Michalski, Alexandre Nguyen, Joelle Pineau1,2 and Yoshua Bengio2 Montreal Institute for Learning Algorithms, Montreal, Quebec, Canada # Abstract We present MILABOT: a deep reinforcement learning chatbot developed by the Montreal Institute for Learning Algorithms (MILA) for the Amazon Alexa Prize competition. MILABOT is capable of conversing with humans on popular small talk topics through both speech and text. The system consists of an ensemble of natural language generation and retrieval models, including template-based models, bag-of-words models, sequence-to-sequence neural network and latent variable neural network models. By applying reinforcement learning to crowdsourced data and real-world user interactions, the system has been trained to select an appropriate response from the models in its ensemble. The system has been evaluated through A/B testing with real-world users, where it performed significantly better than many competing systems. Due to its machine learning architecture, the system is likely to improve with additional data. # Introduction Dialogue systems and conversational agents - including chatbots, personal assistants and voice- control interfaces - are becoming ubiquitous in modern society. Examples of these include personal assistants on mobile devices, technical support help over telephone lines, as well as online bots selling anything from fashion clothes and cosmetics to legal advice and self-help therapy. However, building intelligent conversational agents remains a major unsolved problem in artificial intelligence research. In 2016, Amazon.com Inc proposed an international university competition with the goal of building a socialbot: a spoken conversational agent capable of conversing coherently and engagingly with humans on popular topics, such as entertainment, fashion, politics, sports, and technology. The socialbot converses through natural language speech through Amazon’s Echo device (Stone & Soper 2014). This article describes the models, experiments and final system (MILABOT) developed by our team at University of Montreal.3 Our main motivation for participating has been to help advance artificial intelligence research. To this end, the competition has provided a special opportunity for training and testing state-of-the-art machine learning algorithms with real users (also known as machine learning in the wild) in a relatively unconstrained setting. The ability to experiment with real users is unique in the artificial intelligence community, where the vast majority of work consists of experiments on fixed datasets (e.g. labeled datasets) and software simulations (e.g. game engines). In addition, the computational resources, technical support and financial support provided by Amazon has helped scale up our system and test the limits of state-of-the-art machine learning methods. Among other things, this support has enabled us to crowdsource 200, 000 labels on Amazon Mechanical Turk and to maintain over 32 dedicated Tesla K80 GPUs for running our live system. 1School of Computer Science, McGill University. 2CIFAR Fellow. 3Our team is called MILA Team, where MILA stands for the Montreal Institute for Learning Algorithms. Our socialbot is based on a large-scale ensemble system leveraging deep learning and reinforcement learning. We develop a new set of deep learning models for natural language retrieval and generation — including recurrent neural networks, sequence-to-sequence models and latent variable models — and evaluate them in the context of the competition. These models are combined into an ensemble, which generates a candidate set of dialogue responses. Further, we apply reinforcement learning — including value function and policy gradient methods — to train the system to select an appropriate response from the models in its ensemble. In particular, we propose a novel reinforcement learning procedure, based on estimating a Markov decision process. Training is carried out on crowdsourced data and on interactions recorded between real-world users and a preliminary version of the system. The trained systems yield substantial improvements in A/B testing experiments with real-world users. In the competition semi-finals, our best performing system reached an average user score of 3.15 on a scale 1 − 5, with a minimal number of hand-crafted states and rules and without engaging in non-conversational activities (such as playing games or taking quizzes).4 The performance of this best system is substantially better than the average of all the teams in the competition semi-finals. Further, the same system averaged a high 14.5 − 16.0 turns per dialogue, which is also significantly higher than the average of all the teams in the competition semi-finals, as well as the finalist teams. This improvement in back-and-forth exchanges between the user and system suggests that our system is likely to be the most engaging system among all systems in the competition. Finally, the system is bound to improve with additional data, as nearly all system components are learnable. # 2 System Overview Early work on dialogue systems (Weizenbaum 1966, Colby 1981, Aust et al. 1995, McGlashan et al. 1992, Simpson & Eraser 1993) were based mainly on states and rules hand-crafted by human experts. Modern dialogue systems typically follow a hybrid architecture, combining hand-crafted states and rules with statistical machine learning algorithms (Suendermann-Oeft et al. 2015, Jurˇcíˇcek et al. 2014, Bohus et al. 2007, Williams 2011). Due to the complexity of human language, however, it will probably never be possible to enumerate states and rules required for building a socialbot capable of conversing with humans on open-domain, popular topics. In contrast to such rule-based systems, our core approach is built entirely on statistical machine learning. We believe that this is the most plausible path to artificially intelligent conversational agents. The system architecture we propose aims to make as few assumptions as possible about the process of understanding and generating natural human language. As such, the system utilizes only a small number of hand-crafted states and rules. However, every system component has been designed to be optimized (trained) using machine learning algorithms. These system components will be trained first independently on massive datasets and then jointly on real-world user interactions. This way, the system will learn all relevant states and rules for conducting open-domain conversations implicitly. Given an adequate amount of examples, such a system should outperform systems based on hand-crafted states and rules. Further, the system will continue to improve in perpetuity with additional data. Our system architecture is inspired by the success of ensemble-based machine learning systems. These systems consist of many independent sub-models combined intelligently together. Examples of such ensemble systems include the winner of the Netflix Prize (Koren et al. 2009), utilizing hundreds of machine learning models to predict user movie preferences, and IBM Watson (Ferrucci et al. 2010), the first machine learning system to win the quiz game Jeopardy! in 2011. More recently, Google observed substantial improvements building an ensemble-based neural machine translation system (Wu et al. 2016). Our system consists of an ensemble of response models. The response models take as input a dialogue and output a response in natural language text. In addition, the response models may also output one or several scalar values, indicating their internal confidence. As will be explained later, the response models have been engineered to generate responses on a diverse set of topics using a variety of strategies. 4Throughout the semi-finals we carried out several A/B testing experiments to evaluate different variants of our system (see Section 5). The score 3.15 is based on the best performing system in the period between July 29th and August 6th, 2017. The score is not based on the leaderboard, which averages the scores of all the variants of our system (including a supervised learning system and a heuristic baseline system). 2 Response selection policy Response models Generate candidate responses Dialogue history Return priority Return selected ASR confidences response response Evaluate candidate responses Has priority response? Figure 1: Dialogue manager control flow. The dialogue manager is responsible for combining the response models together. As input, the dialogue manager expects to be given a dialogue history (i.e. all utterances recorded in the dialogue so far, including the current user utterance) and confidence values of the automatic speech recognition system (ASR confidences). To generate a response, the dialogue manager follows a three-step procedure. First, it uses all response models to generate a set of candidate responses. Second, if there exists a priority response in the set of candidate responses (i.e. a response which takes precedence over other responses), this response will be returned by the system.5 For example, for the question "What is your name?", the response "I am an Alexa Prize socialbot" is a priority response. Third, if there are no priority responses, the response is selected by the model selection policy. For example, the model selection policy may select a response by scoring all candidate responses and picking the highest-scored response. The overall process is illustrated in Figure 1. When the ASR confidences are below a certain threshold, the system requests the user to repeat their last utterance. Otherwise, the system does not utilize the ASR confidences. In particular, neither the response models nor the model selection policy make use of the ASR confidences. Nevertheless, the ASR system is far from perfect. Therefore, it is very plausible that the system could be improved significantly by conditioning the response models and model selection policy on the ASR confidences. # 3 Response Models There are 22 response models in the system, including retrieval-based neural networks, generation- based neural networks, knowledge base question answering systems and template-based systems. Examples of candidate model responses are shown in Table 1. This section aims to summarize these response models. First, the template-based models are described. # 3.1 Template-based Models We start by describing the template-based response models in the system. Alicebot: Alicebot uses a set of AIML (artificial intelligence markup language) templates to produce a response given the dialogue history and user utterance (Wallace 2009, Shawar & Atwell 2007). We use the freely available Alice kernel available at www.alicebot.org. By default all templates generate non-priority responses, so we configure templates related to the socialbot’s name, age and location to output priority responses. We modify a few templates further to make them consistent with the challenge (e.g. to avoid obscene language and to encourage the user to discuss certain topics, such as news, politics and movies). The majority of templates remain unchanged. The Alicebot model also outputs a scalar confidence score. Since the AIML templates repeat the user’s input utterance, they are not always correct sentences. Therefore, we use a string-based rules to deter- mine if the response constitutes a correct sentence. If the response is correct sentence, it returns a high 5An ordering of the models decides which response to return in case there are multiple priority responses. 3 Table 1: Example dialogues and corresponding candidate responses generated by response models. The response of the final system is marked in bold. Dialogue SYSTEM: Hi. This is an Alexa Prize socialbot. USER: Hi SYSTEM: Do you have pets? USER: Yes, I have two rabbits. Dialogue ... USER: Let’s talk about movies. SYSTEM: What’s your favorite movie? USER: star wars movie Candidate Responses BoWEscapePlan: I don’t have an answer for this. BoWFactGenerator: Did you know that male rabbits are called bucks, females are does? GRUQuestionGenerator: How about the American family of it? Initiatorbot: Do you believe in love at first sight? LSTMClassifierMSMarco: Mar 23, 2017 Two Parts: Learning What to Feed Your Rabbit Learning How to ... DualEncoderRedditNews: bye doggie DualEncoderRedditPolitics: Who’s edger u shboys? Alicebot: Hurrah! Two is a good number of rabbits. Elizabot: OK, but can you elaborate a bit? VHREDRedditMovies: Hmm. Nope, never heard of it. VHREDSubtitles: Would you like to see them? HelpResponse: I would really like to talk about news, politics or movies. Candidate Responses BoWEscapePlan: I don’t have an answer for this. BoWFactGenerator: Here’s an interesting fact. The international telephone dialing code for Antarctica is 672. GRUQuestionGenerator: how about your New York City? Initiatorbot: How was your day? LSTMClassifierMSMarco: A third Anthology film will be released in 2020. DualEncoderRedditNews: Now whisper it to me , one more time bby. DualEncoderRedditPolitics: hahaha on mobile this ain’t even close. I wish I could show you but this looks awful I’m sorry man. Alicebot: What did you like about the robots in that movie? Elizabot: How does that make you feel? Evi: Star Wars movie a movie in the Star Wars series. VHREDRedditMovies: Oh please. Please. Pleeeease. Let this happen. VHREDSubtitles: What? HelpResponse: I would really like to talk about news, politics or movies. confidence and otherwise it returns a low confidence score. This process is illustrated in Algorithm 1. Algorithm 1: Alicebot 1 input: dialogue history 2 response ← apply AIML templates to dialogue history 3 if response is correct sentence then if response is given priority then 4 # nk # confidence ← 1.0 5 6 else # confidence ← 0.5 7 # 8 else 9 # confidence ← 0.0 |. confidence < 0.0 # 10 output: response, priority, confidence Elizabot Similar to Alicebot, the Elizabot model performs string matching to select an answer from a set of templates. The model is based on the famous Eliza system, designed to mimic a Rogerian (Weizenbaum 1966).6 Therefore, in contrast with Alicebot, most of Elizabot’s psychotherapist. responses are personal questions which are meant to engage the user to continue the conversation. # 6We use the implementation available at: https://gist.github.com/bebraw/273706. 4 Here are two example templates: 1. "I am (.*)" → "Did you come to me because you are ..." 2. "What (.*)" → "Why do you ask?" The ellipses mark the parts of the response sentence which will be replaced with text from the user’s utterance. The model detects the appropriate template and selects the corresponding response (if there are multiple templates, then a template is selected at random). The model then runs the template response through a set of reflections to better format the string for a response (e.g. "I’d" → "you would", "your" → "my"). # Algorithm 2: Initiatorbot 1 input: dialogue history 2 if Initiatorbot was triggered in one of last two turns then 3 4 else if user did not give a greeting then 5 6 else 7 # return "" return a non-priority response with a random initiator phrase return a priority response with a random initiator phrase Initiatorbot The Initiatorbot model acts as a conversation starter: it asks the user an open-ended question to get the conversation started and increase the engagement of the user. We wrote 40 question phrases for the Initiatorbot. Examples of phrases include "What did you do today?", "Do you have pets?" and "What kind of news stories interest you the most?". As a special case, the model can also start the conversation by stating an interesting fact. In this case, the initiator phrase is "Did you know that <fact>?", where fact is replaced by a statement. The set of facts is the same as used by the BoWFactGenerator model, described later. Before returning a response, Initiatorbot first checks that it hasn’t already been triggered in the last two turns of the conversation. If the user gives a greeting (e.g. "hi"), then Initiatorbot will return a response with priority. This is important because we observed that greetings often indicate the beginning of a conversation, where the user does not have a particular topic they would like to talk about. By asking a question, the system takes the initiative (i.e. control of the dialogue). The procedure is detailed in Algorithm 2. Storybot The Storybot model outputs a short fiction story at the request of the user. We implemented this model as we observed that many users were asking the socialbot to tell stories.7 Storybot determines if the user requested a story by checking if there was both a request word (e.g. say, tell.) and story-type word in the utterance (e.g. story, tale). The response states the story’s title and author followed by the story body. For example, one set of responses from this model follows the pattern "Alright, let me tell you the story <story_title> <story_body> by <story_author>" where <story_title> is the title of the story, <story_body> is the main text and <story_author> is the name of the story’s author. The stories were scraped from the website: www.english-for-students.com. An example story is: ** The Ant and The Grasshopper ** The ants worked hard in summer. They sorted food for winter. At that time, a grasshopper remained idle. When winter came, the ants had enough to eat. But, the grasshopper had nothing to eat. He had to starve. He went to the ants and begged for foods. The ants asked in return, "What did you do in summer?" He replied, "I idled away my time during summer". The ant replied, "Then you must starve in winter." MORAL: Never be idle. The Storybot is the only component in the system performing a non-conversational activity. It is triggered only when a user specifically asks for a story, and in that case its response is a priority 7Requests for telling stories is possibly a side-effect of user’s interacting with bots from other teams, which often emphasized non-conversational activities, such as telling stories and playing quizzes and word games. 5 response. Otherwise, the Storybot response model is never triggered. Further, the rest of the system will not encourage the user to request stories. # 3.2 Knowledge Base-based Question Answering Evibot The Evibot response model forwards the user’s utterance to Amazon’s question-answering web-service Evi: www.evi.com. Evi was designed primarily to handle factual questions. There- fore, Evibot returns a priority response for direct questions, defined as user utterances contain- ing a wh-word (e.g. "who", "what"), and otherwise returns a non-priority or, possibly, an empty If the query is a direct question and contains non-stop words, Evibot will follow a response. three step procedure to generate its response. First, Evibot forwards a query to www.evi.com containing the whole user utterance, and returns the resulting answer if its valid. If that fails, Evibot applies NLTK’s named entity processor (Bird et al. 2009) to the query to find sub- queries with named entities. For each subphrase that contains a named entity, Evibot forwards queries to www.evi.com, and returns the result upon a valid response. Finally, if the previ- ous two steps fail, Evibot forwards queries for every subquery without named entities, and re- turns either a valid response or an empty response. The procedure is detailed in Algorithm 3. Algorithm 3: Evibot 1 input: dialogue history 2 query ← last user utterance 3 has-wh-words ← true if utterance contains a wh-word, otherwise false 4 has-only-stop-words ← true if utterance only has stop words, otherwise false 5 if has-only-stop-words and not has-wh-words then 6 # return "" 7 evi-response ← send query to www.evi.com 8 priority ← true if has-wh-words and evi-response is valid, otherwise false 9 if evi-response is valid then 10 # return evi-response, priority # 11 else if has-wh-words then 12 priority ← has-wh-words subentities ← entities extracted from query using NLTK’s named entity processor subphrases ← list of subphrases with entities for subphrase in subphrases do 13 14 15 evi-response ← send subphrase to www.evi.com if evi-response is valid then 16 17 18 return evi-response, priority 19 20 subphrases ← list of all subphrases for subphrase in subphrases do evi-response ← send subphrase to www.evi.com if evi-response is valid then 21 22 return evi-response, priority 23 # 24 else 25 # return "" 25 return BoWMovies The BoWMovies model is a template-based response model, which handles questions in the movie domain. The model has a list of entity names and tags (e.g. movie plot and release year). The model searches the user’s utterance for known entities and tags. Entities are identified by string matching. This is done in a cascading order, by giving first preference to movie title matches, then actor name matches, and finally director name matches. Tags are also identified by string matching. However, if exact string matching fails for tags, then identification is performed by word embedding similarity. If both an entity and a tag are present, the agent will dispatch an API call to one of several data sources to retrieve the data item for the selected query type. The agent is limited by the data available in the APIs to which it has access. The model’s responses follow predefined templates. Movie titles, actor names, and director names are extracted from the Internet Movie Database (IMDB). Movie descriptions are taken from Google Knowledge Graph’s API. Other movie title queries are 6 directed to the Open Movie Database (OMDB).8 For actor and director queries, the Wikiedata API is used. First, a search for actor and director names is done on a Wikidata JSON dump. As described earlier, the model uses word embeddings to match tags. These word embeddings are trained using Word2Vec on movie plot summaries and actor biographies extracted from the IMDB database (Mikolov et al. 2013). # Algorithm 4: BoWMovies - ComputeResponse 1 input: dialogue history 2 entity ← entity contained both in last user utterance and list of movie titles, actors or directors 3 if no entity then 4 entity ← entity contained in previous user utterances and movie titles, actors or directors 5 if no entity then return "" 6 7 if entity is a movie title then 8 9 else if entity is an actor name then 10 11 else if entity is an director name then 12 13 return response # response ← ComputeEntityResponse(entity, movie title) # response ← ComputeEntityResponse(entity, actor name) # response ← ComputeEntityResponse(entity, director name) # Algorithm 5: BoWMovies - ComputeEntityResponse 1 input: entity and entity type 2 tag ← string matching tag, where tag is valid for entity type (movie title, actor name, director name) # 3 if no tag then 4 tag ← word embedding matching tag, where tag is a single word and valid for the entity type (movie title, actor name, director name) # 5 if no tag then 6 tag ← word embedding matching tag, where tag is multiple words and valid for the entity type (movie title, actor name, director name) # 7 if no tag then 8 # return "" 9 api-response ← call external API with query (entity, tag). 10 response ← template with api-response inserted 11 return response # 3.3 Retrieval-based Neural Networks VHRED models: The system contains several VHRED models, sequence-to-sequence models with Gaussian latent variables trained as variational auto-encoders (Serban et al. 2017, Kingma & Welling 2014, Rezende et al. 2014). The models are trained using the same procedure as Serban et al. (2017). A comparison between VHRED and other generative sequence-to-sequence models is provided by Serban et al. (2016). The trained VHRED models generate candidate responses as follows. First, a set of K model responses are retrieved from a dataset using cosine similarity between the current dialogue history and the dialogue history in the dataset based on bag-of-words TF-IDF Glove word embeddings (Pennington et al. 2014).9 An approximation of the log-likelihood for each of the 20 responses is computed by VHRED, and the response with the highest log-likelihood is returned. The system has 4 VHRED models based on datasets scraped from Reddit, one VHRED model based on news articles and one VHRED model based on movie subtitles: 8See www.omdbapi.com. This should not be confused with IMDB. 9We use the Glove embeddings trained on Wikipedia 2014 + Gigaword 5: https://nlp.stanford.edu/ projects/glove/. 7 • VHREDRedditPolitics trained on https://www.reddit.com/r/politics and extracting responses from all Reddit datasets with K = 10, • VHREDRedditNews trained on Reddit https://www.reddit.com/r/news and extracting responses from all Reddit datasets with K = 20, • VHREDRedditSports trained on Reddit https://www.reddit.com/r/sports and ex- tracting responses from all Reddit datasets with K = 20, • VHREDRedditMovies trained on Reddit https://www.reddit.com/r/movies and ex- tracting responses from all Reddit datasets with K = 20, VHREDWashingtonPost10 trained on Reddit https://www.reddit.com/r/politics and extracting responses from user comments to WashingtonPost news articles, and • VHREDSubtitles11 using the movie subtitles dataset SubTle (Ameixa et al. 2014) with K = 10. In particular, VHREDRedditPolitics and VHREDWashingtonPost use a different retrieval procedure. These two models use a logistic regression model to score the responses instead of the approximate log-likelihood. The logistic regression model is trained on a set of 7500 Reddit threads and candidate responses annotated by Amazon Mechanical Turk workers on a Likert-type scale 1 − 5. The candidate responses are selected from other Reddit threads according to cosine similarity w.r.t. Glove word embeddings. The label collection and training procedure for the logistic regression model are similar to the procedures described in Section 4. For each response, the logistic regression model takes as input the VHRED log-likelihood score, as well as several other input features, and outputs a scalar-valued score. Even though the logistic regression model did improve the appropriateness of responses selected for Reddit threads, VHREDRedditPolitics is used extremely rarely in the final system (see Section 4). This suggests that training a model to rerank responses based on labeled Reddit threads and responses cannot help improve performance. SkipThought Vector Models: The system contains a SkipThought Vector model (Kiros et al. 2015) trained on the BookCorpus dataset (Zhu et al. 2015) and on the SemEval 2014 Task 1 (Marelli et al. 2014). The model was trained using the same procedure as Kiros et al. (2015) and is called SkipThoughtBooks. SkipThoughtBooks ensures that the system complies with the Amazon Alexa Prize competition rules. One rule, introduced early in the competition, is that socialbots were not supposed to state their own opinions related to political or religious topics. If a user wishes to discuss such topics, the socialbots should proceed by asking questions or stating facts. SkipThoughtBooks also handles idiosyncratic issues particular to the Alexa platform. For example, many users did not understand the purpose of a socialbot and asked our socialbot to play music. In this case, the system should instruct the user to exit the socialbot application and then play music. SkipThoughtBooks follows a two-step procedure to generate its response. The first step compares the user’s last utterance to a set of trigger phrases. If a match is found, the model returns a corresponding priority response.12 For example, if the user says "What do you think about Donald trump?", the model will return a priority response, such as "Sometimes, truth is stranger than fiction.". A match is found if: 1) the SkipThought Vector model’s semantic relatedness score between the user’s last utterance and a trigger phrase is above a predefined threshold, and 2) the user’s last utterance contains keywords relevant to the trigger phrase.13 In total, there are 315 trigger phrases (most are paraphrases of each other) and 35 response sets. If the model did not find a match in the first step, it proceeds to the second step. In this step, the model selects its response from among all Reddit dataset responses. As before, a set of K model responses are retrieved using cosine similarity. The model then returns the response with the highest semantic relatedness score. Dual Encoder Models: The system contains two Dual Encoder retrieval models (Lowe et al. 2015, Lowe, Pow, Serban, Charlin, Liu & Pineau 2017), DualEncoderRedditPolitics and DualEncoderRed- ditNews. Both models are composed of two sequence encoders ENCQ and ENCR with a single 10For VHREDWashingtonPost, the K responses are extracted based on the cosine similarity between the current dialogue and the news article keywords. K varies depending on the number of user comments within a set of news articles above a certain cosine similarity threshold. 11For VHREDSubtitles, cosine similarity is computed based on one-hot vectors for each word. 12Trigger phrases may have multiple responses. In this case, a response is selected at random. 13Some trigger phrases do not have keywords. In this case, matching is based only on semantic relatedness. 8 LSTM recurrent layer used to encode the dialogue history and a candidate response. The score for a candidate response is computed by a bilinear mapping of the dialogue history embedding and the candidate response embedding as Lowe et al. (2015). The models are trained using the method proposed by (Lowe et al. 2015). In principle, it is also possible to use early stopping based on separate model trained on a domain similar to our target domain (Lowe et al. 2016). The response with the highest score from a set of K = 50 candidate responses are retrieved using TF-IDF cosine similarity based on Glove word embeddings. The model DualEncoderRedditPolitics is trained on the Reddit https://www.reddit.com/r/politics dataset and extracts responses from all Reddit datasets. The model DualEncoderRedditNews is trained on the Reddit https://www.reddit.com/r/news dataset and extracts responses from all Reddit datasets. Bag-of-words Retrieval Models: The system contains three bag-of-words retrieval models based on TF-IDF Glove word embeddings (Pennington et al. 2014) and Word2Vec embeddings (Mikolov et al. 2013).14 Similar to the VHRED models, these models retrieve the response with the highest cosine similarity. The BoWWashingtonPost model retrieves user comments from WashingtonPost news articles using Glove word embeddings. The model BoWTrump retrieves responses from a set of Twitter tweets scraped from Donald Trump’s profile: https://twitter.com/realDonaldTrump. This model also uses Glove word embeddings and it only returns a response when at least one relevant keyword or phrase is found in the user’s utterance (e.g. when the word "Trump" is mentioned by the user). The list of trigger keywords and phrases include: ’donald’, ’trump’, ’potus’, ’president of the united states’, ’president of the us’, ’hillary’, ’clinton’, ’barack’, and ’obama’. The model BoWFactGenerator retrieves responses from a set of about 2500 interesting and fun facts, including facts about animals, geography and history. The model uses Word2Vec word embeddings. The model BoWGameofThrones retrieves responses from a set of quotes scraped from https://twitter.com/ ThroneQuotes using Glove word embeddings. Tweets from this source were manually inspected and cleaned to remove any tweets that were not quotes from the series. As in the BoWTrump model, we use a list of trigger phrases to determine if the model’s output is relevant to the user’s utterance. We populate this list with around 80 popular character names, place names and family names, which are large unique to the domain. We also added a few aliases to try and account for alternative speech transcriptions of these named entities. Some phrases include: ’ned stark’, ’jon snow’, ’john snow’, ’samwell tarly’, "hodor", "dothraki" and so on. 15 # 3.4 Retrieval-based Logistic Regression BoWEscapePlan: The system contains a response model, called BoWEscapePlan, which returns a response from a set of 35 topic-independent, generic pre-defined responses, such as "Could you repeat that again", "I don’t know" and "Was that a question?". Its main purpose is to maintain user engagement and keep the conversation going, when other models are unable to provide meaningful responses. This model uses a logistic regression classifier to select its response based on a set of higher-level features. To train the logistic regression classifier, we annotated 12, 000 user utterances and candidate response pairs for appropriateness on a Likert-type scale 1 − 5. The user utterances were extracted from interactions between Alexa users and a preliminary version of the system. The candidate responses were sampled at random from BoWEscapePlan’s response list. The label collection and training procedure for the logistic regression model are similar to the procedures described in Section 4. The logistic regression model is trained with log-likelihood on a training set, with early-stopping on a development set, and evaluated on the testing set. However, the trained model’s performance was poor. It obtained a Pearson correlation coefficient of 0.05 and a Spearman’s rank correlation coefficient of 0.07. This indicates that the logistic regression model is only slightly better at selecting a topic-independent, generic response compared to selecting a response at uniform random. Future work should investigate collecting more labeled data and pre-training the logistic regression model. # 3.5 Search Engine-based Neural Networks The system contains a deep classifier model, called LSTMClassifierMSMarco, which chooses its response from a set of search engine results. The system searches the web with the last user utterance 14We use the pre-trained Word2Vec embeddings: https://code.google.com/archive/p/word2vec/. 15This model was implemented after the competition ended, but is included here for completeness. 9 as query, and retrieves the first 10 search snippets. The retrieved snippets are preprocessed by stripping trailing words, removing unnecessary punctuation and truncating to the last full sentence. The model uses a bidirectional LSTM to separately map the last dialogue utterance and the snippet to their own embedding vectors. The resulting two representations are concatenated and passed through an MLP to predict a scalar-value between 0 − 1 indicating how appropriate the snippet is as a response to the utterance. The model is trained as a binary classification model on the Microsoft Marco dataset with cross- entropy to predict the relevancy of a snippet given a user query (Nguyen et al. 2016). Given a search query and a search snippet, the model must output one when the search snippet is relevant and otherwise zero. Search queries and ground truth search snippets are taken as positive samples, while other search snippets are selected at random as negative samples. On this task, the model is able to reach a prediction accuracy of 72.96% w.r.t. the Microsoft Marco development set. The system is able to use search APIs from various search engines including Google, Bing, and AIFounded (Im 2017). In the current model, we choose Google as the search engine, since qualitative inspection showed that this retrieved the most appropriate responses. # 3.6 Generation-based Neural Networks The system contains a generative recurrent neural network language model, called GRUQuestion- Generator, which can generate follow-up questions word-by-word, conditioned on the dialogue history. The input to the model consists of three components: a one-hot vector of the current word, a binary question label and a binary speaker label. The model contains two GRU layers (Cho et al. 2014) and softmax output layer. The model is trained on Reddit Politics and Reddit News conversa- tions, wherein posts were labeled as questions by detecting question marks. We use the optimizer Adam (Kingma & Ba 2015), and perform early stopping by checking the perplexity on the validation set For generation, we first condition the model on a short question template (e.g. "How about", “What about”, “How do you think of”, “What is your opinion of”), and then generate the rest of the question by sampling from the model with the question label clamped to one. The generation procedure stops once a question mark is detected. Further, the length of the question is controlled by tuning the temperature of the softmax layer. Due to speed requirements, only two candidate responses are generated and the best one w.r.t. log-likelihood of the first 10 words is returned. # 4 Model Selection Policy After generating the candidate response set, the dialogue manager uses a model selection policy to select the response it returns to the user. The dialogue manager must select a response which increases the satisfaction of the user for the entire dialogue. It must make a trade-off between immediate and long-term user satisfaction. For example, suppose the user asks to talk about politics. If the dialogue manager chooses to respond with a political joke, the user may be pleased for one turn. Afterwards, however, the user may be disappointed with the system’s inability to debate political topics. Instead, if the dialogue manager chooses to respond with a short news story, the user may be less pleased for one turn. However, the news story may influence the user to follow up with factual questions, which the system may be better adept at handling. To make the trade-off between immediate and long-term user satisfaction, we consider selecting the appropriate response as a sequential decision making problem. This section describes five approaches to learn the model selection policy. These approaches are all evaluated with real-world users in the next section. We use the reinforcement learning framework (Sutton & Barto 1998). The dialogue manager is an agent, which takes actions in an environment in order to maximize rewards. For each time step t = 1, . . . , T , the agent observes the dialogue history ht and must choose one of K actions (responses): a1 t . After taking an action, the agent receives a reward rt and is transferred to the next state ht+1 (which includes the user’s next response). Then, the agent is provided with a new set of K actions: a1 T R=oy'n, (1) t=1 t=1 which is referred to as the expected cumulative return (or simply expected return). The parameter γ ∈ (0, 1] is a discount factor. 10 An issue specific to our setting is that the set of actions changes depending on the state (dialogue history). This happens because the candidate responses are generated by response models, which also depend on the dialogue history. In addition, the response models are not deterministic. This means the set of candidate responses is likely to be different every time the agent encounters the same state ht.16 This is in contrast to certain reinforcement learning problems, such as learning to play Atari 2600 games, where the set of actions is fixed given the state. To simplify notation, we will fix the number of actions to K henceforth. Action-value Parametrization: We use two different approaches to parametrize the agent’s policy. The first approach is based on an action-value function, defined by parameters θ: Qθ(ht, ak t ) ∈ R for k = 1, . . . , K, (2) which estimates expected return of taking action ak t (candidate response k) given dialogue history ht and given that the agent will continue to use the same policy afterwards. Given Qθ, the agent chooses the action with highest expected return: πθ(ht) = arg max k Qθ(ht, ak t ). (3) The use of an action-value function for selecting dialogue responses is closely related to the recent work by Lowe, Noseworthy, Serban, Angelard-Gontier, Bengio & Pineau (2017), where a model is learned to predict the quality of a dialogue system response. However, in our case, Qθ is only conditioned on the dialogue context. On the other hand, the model proposed by Lowe, Noseworthy, Serban, Angelard-Gontier, Bengio & Pineau (2017) is conditioned both on the dialogue context and on a human reference response. The action-value function is also related to the the work by Yu et al. (2016), who learn an evaluation model, which is used to train a reinforcement learning agent to select appropriate dialogue response strategies. Stochastic Policy Parametrization: The second approach instead parameterizes the policy as a discrete distribution over actions. Let θ be the parameters. The agent selects its action by sampling: ed" fo(he.at) mo(a*\hi) Sanat) fork =1,..., K, (4) a where fθ(ht, ak t given ht. The parameter λ is called the temperature and controls the entropy of the distribution. The higher λ is, the more uniform the selecting of actions will be. The stochastic policy can be transformed to a deterministic (greedy) policy by selecting the action with highest probability: fθ(ht, ak πgreedy θ πθ(ak (ht) = arg max t |ht) = arg max t ). k k (5) Scoring Model: The action-value function Qθ(ht, ak t ) are closely related. Both functions yield a ranking over the actions; higher values imply higher expected returns. When Qθ(ht, ak t ), the action-value function policy in eq. (3) is equivalent to the greedy policy in eq. (5). For simplicity, we will use the same parametrization for both Qθ(ht, ak t ) and fθ(ht, ak t ). Therefore, we let both functions take the same features as input and process them using the same neural network architecture. We will refer to both functions as the scoring model. The next section describes the input features for the scoring model. # 4.1 Input Features As input to the scoring model we compute 1458 features based on the given dialogue history and candidate response. The input features are based on a combination of word embeddings, dialogue acts, part-of-speech tags, unigram word overlap, bigram word overlap and model-specific features: Word embeddings of response: Average of dings (Mikolov et al. 2013).17 candidate response word embed- 16In general, since some response models only output responses for certain user utterances, the number of candidate responses also changes depending on the state. # 17We use the pre-trained Word2Vec embeddings: https://code.google.com/archive/p/word2vec/. 11 Word embeddings of last user utterance: Average of the last user utterance word embeddings. Word embeddings of context: Average of the word embeddings of the last six utter- ances in dialogue context. Average of the word embeddings of the last three user utterances in dialogue context. The Embedding Average, Embedding Extrema and Embedding Greedy similarity metrics described by Liu et al. (2016). Each similarity metric is computed between 1) the last user utterance and candidate re- sponse, 2) the last six utterances in the dialogue and candidate response, 3) the last three user utterances in the dialogue and candidate response, 4) the last six utterances in the dialogue and candidate response with stop-words removed, and 5) the last three user utterances in the dialogue and candidate response with stop-words removed. A one-hot vector with size equal to the number of response models, where entry i is equal to 1.0 when candidate response was generated by the model class with index i. The part-of-speech tags for candidate response is es- timated using a maximum entropy tagger trained on the Penn Treebank corpus. The sequence of part-of- speech tags is then mapped to a one-hot vector, which constitutes the input feature. The outer-product between a one-hot vector represent- ing the dialogue act (we consider 10 types of dialogue acts) and a one-hot vector for indicating the model class (Stolcke et al. 2000). 1.0 when one or more non-stop-words overlap be- tween candidate response and last user utterance, and otherwise zero. 1.0 when a bigram (two consecutive tokens) exists both in the candidate response and in the last user utterance, and otherwise zero. 1.0 when a bigram exists both in candidate response and in one of the last utterances in dialogue context, and otherwise zero. 1.0 when a named-entity (an upper-cased word, which is not a stop-word) exists both in candidate response and in the last user utterance, and otherwise zero. 1.0 when a named-entity exists both in candidate re- sponse and in one of the last utterances in dialogue context, and otherwise zero. 1.0 when candidate response consists of only stop- words or words shorter than 3 characters, and other- wise zero. 1.0 when candidate response contains a wh-word (e.g. what, where, and so on), and otherwise zero. 1.0 when last user utterance contains a wh-word, and otherwise zero. 1.0 when candidate response contains an intensifier word (e.g. amazingly, crazy, and so on), and otherwise zero. 12 Intensifier word context: 1.0 when last user utterance contains an intensifier word, and otherwise zero. Unigram response: A set of binary features which are 1.0 when candidate response contains a specific word (including the words I, you and thanks), and otherwise zero. Negation response: 1.0 when candidate response contains a negation word, such as not or n’t, and otherwise zero. Non-stop-words response: 1.0 when candidate response contains a non-stop- word, and otherwise zero. We do not include features based on the confidences of the speech recognition system, for experimental reasons. Speech recognition errors are a confounding factor in experiments with real-world users. Speech recognition errors are likely to affect user satisfaction. If features based on speech recognition confidences were included, one policy might learn to handle speech recognition errors better than another policy. In turn, this could make that policy perform better w.r.t. overall user satisfaction. However, that would be an effect caused by the imperfect speech recognition system, and would not reflect user satisfaction under a perfect speech recognition system. Excluding these features as input to the scoring model helps minimize this confounding effect.Nevertheless, even if these features are excluded, it should be noted that speech recognition errors still constitute a substantial confounding factor in our later experiments. Lastly, for the same reasons, none of the response models utilize speech recognition confidences. In principle, it is possible to compute input features by encoding the dialogue context and candi- date response using Recurrent Neural Networks (RNNs) or Convolutional Neural Networks (Con- vNets) (Socher et al. 2013, Blunsom et al. 2014, Cho et al. 2014, Yu et al. 2014, Kiros et al. 2015). However, these models are known to require training on large corpora in order to achieve acceptable performance, which we do not have access to. In addition, we need to keep the scoring model’s execution time under 150ms. Otherwise, the slowdown in the response time, could frustrate the user and lower the overall user satisfaction. This rules out large RNNs and ConvNets for the Amazon Alexa Prize competition, since these would require more computational runtime. However, future dialogue systems utilizing larger datasets should consider large-scale models. # 4.2 Model Architecture This section describes the scoring model’s architecture. The scoring model is a five-layered neural network. The first layer is the input, consisting of the 1458 features, described in the previous section. The second layer contains 500 hidden units, computed by applying a linear transformation followed by the rectified linear activation function (Nair & Hinton 2010, Glorot et al. 2011) to the input layer units. The third layer contains 20 hidden units, computed by applying a linear transformation to the preceding layer units. Similar to matrix factorization, this layer compresses the 500 hidden units down to 20 hidden units. The fourth layer contains 5 outputs units, which are probabilities (i.e. all values are positive and sum to one). These output units are computed by applying a linear transformation to the preceding layer units followed by a softmax transformation. This layer corresponds to the Amazon Mechanical Turk labels, which will be described in the next sub-section. The fifth layer is the final output scalar, computed by applying a linear transformation to the units in the third and fourth layers. The model is illustrated in Figure 2. Before settling on this architecture, we experimented both with deeper and more shallow models. However, we found that both the deeper models and the more shallow models performed worse. Nevertheless, future work should explore alternative architectures. We use five different machine learning approaches to learn the scoring model. These are described next. # 4.3 Supervised AMT: Learning with Crowdsourced Labels This section describes the first approach to learning the scoring model, which is based on estimating the action-value function using supervised learning on crowdsourced labels. This approach also serves as initialization for the approaches discussed later. 13 1458 dim. Dialogue history S.dim. idim. Hidden Hidden Layer Candidate response Figure 2: Computational graph for scoring model, used for the model selection policies based on both action-value function and stochastic policy parametrizations. The model consists of an input layer with 1458 features, a hidden layer with 500 hidden units, a hidden layer with 20 hidden units, a softmax layer with 5 output probabilities (corresponding to the five AMT labels in Section 4.3), and a scalar-valued output layer. The dashed arrow indicates a skip connection. Crowdsourcing: We use Amazon Mechanical Turk (AMT) to collect data for training the scoring model. We follow a setup similar to Liu et al. (2016). We show human evaluators a dialogue along with 4 candidate responses, and ask them to score how appropriate each candidate response is on a 1-5 Likert-type scale. The score 1 indicates that the response is inappropriate or does not make sense, 3 indicates that the response is acceptable, and 5 indicates that the response is excellent and highly appropriate. Our setup only asks human evaluators to rate the overall appropriateness of the candidate responses. In principle, we could choose to evaluate other aspects of the candidate responses. For example, we could evaluate fluency. However, fluency ratings would not be very useful since most of our models retrieve their responses from existing corpora, which contain mainly fluent and grammatically correct responses. As another example, we could evaluate topical relevancy. However, we choose not to evaluate such criteria since it is known to be difficult to reach high inter-annotator agreement on them (Liu et al. 2016). In fact, it is well known that even asking for a single overall rating tends to produce only a fair agreement between human evaluators (Charras et al. 2016); disagreement between annotators tends to arise either when the dialogue context is short and ambiguous, or when the candidate response is only partially relevant and acceptable. The dialogues are extracted from interactions between Alexa users and preliminary versions of our system. Only dialogues where the system does not have a priority response were extracted (when there is a priority response, the dialogue manager must always return the priority response). About 3/4 of these dialogues were sampled at random, and the remaining 1/4 dialogues were sampled at random excluding identical dialogues.18 For each dialogue, the corresponding candidate responses are created by generating candidate responses from the response models. We preprocess the dialogues and candidate responses by masking out profanities and swear words with stars (e.g. we map "fuck" to "****").19 Furthermore, we anonymize the dialogues and candidate responses by replacing first names with randomly selected gender-neutral names (for example, "Hi John" could be mapped to "Hello Casey"). Finally, the dialogues are truncated to the last 4 utterances and last 500 words. This reduces the cognitive load of the annotators. Examples from the crowdsourcing task are shown in Figure 3, Figure 4 and Figure 5. The dialogue example shown in Figure 5 is a fictitious example. 18Sampling at random is advantageous for our goal, because it ensures that candidate responses to frequent user statements and questions tend to be annotated by more turkers. This increases the average annotation accuracy for such utterances, which in turn increases the scoring model’s accuracy for such utterances. 19The masking is not perfect. Therefore, we also instruct turkers that the task may contain profane and obscene language. Further, it should also be noted that Amazon Mechanical Turk only employs adults. 14 We need your consent to proceed Given a conversation, you must rate the quality of potential next responses. This study is part of the dialogue research project carried out by lulian Viad Serban in collaboration with professor Yoshua Bengio at University of Montreal. The project aims to build a computer system able to converse with humans. The conversations you will be presented are based on real conversations, which have been anonymized. You are not allowed to share or redistribute these conversations in any form. Once you have completed the task you must ensure that no data is left in memory on your computer. We have automatically filtered the content to remove offensive language. Unfortunately, the filtering process is not perfect so it is possible that you occasionally will be shown offensive language. Your name will not be recorded. You will be assigned a number, which will not be kept alongside any identifiable information, This number will be used to refer to you in our results. Your participation is entirely voluntary and will require about 20 minutes of your time. You may decide to refuse to perform a task you deem inappropriate or to withdraw from the study at any time. By clicking "I Agree”, you assert that you have read the information above, and are agreeing to participate in this study, in accordance with Amazon Mechanical Turk Guidelines. #1 Print a copy of this Do you understand and consent to these terms? @ No thanks, | do not want to do this HIT Figure 3: Consent screen for Amazon Mechanical Turk human intelligence tasks (HITs). Instructions You will be presented with a conversation between two speakers (speaker A and speaker B). You will also be presented with 4 potential responses from one of the speakers for this dialogue. The task is to rate each response between 1 (inappropriate, does not make any sense) and 5 (highly appropriate and interesting) based on how appropriate the response is to continue the conversation (with 3 being neutral). A response is appropriate if it is interesting and makes sense given the previous dialogue. If two responses are equally appropriate, you should give them the same score. If you see a response that is not in English, please give all "1" scores. Figure 4: Instructions screen for Amazon Mechanical Turk human intelligence tasks (HITs). 15 : Response Res, R Conversation P Ponse Response 3 esponse 1 2 4 A: you need to work . What other Here's a funny fact! Go. is . But English on your English is my native reasons the shortest complete bye B: Why do you say lan ye e come to sentence in the English doggie that about me? guage. mind? language. A: Well your English is very poor Score 4, 37 3” 2 Instructions: Rate the appropriateness of the response between 1 (inappropriate, does not make any sense) and 5 (highly appropriate and interesting). The score 3 indicates neutral (acceptable, but not interesting). Remember to take into account the previous conversation. Next 3/28 : Response Res, R Conversation P Ponse Response 3 esponse 1 2 4 A: you need to work . What other Here's a funny fact! Go. is . But English on your English is my native reasons the shortest complete bye B: Why do you say lan ye e come to sentence in the English doggie that about me? guage. mind? language. A: Well your English is very poor Score 4, 37 3” 2 Figure 5: Annotation screen for Amazon Mechanical Turk human intelligence tasks (HITs). The dialogue text is a fictitious example. We inspected the annotations manually. We observed that annotators tended to frequently overrate topic-independent, generic responses. Such responses may be considered acceptable for a single turn in a conversation, but are likely to be detrimental when repeated over and over again. In particular, annotators tended to overrate responses generated by the response models Alicebot, Elizabot, VHREDSubtitles and BoWEscapePlan. Responses generated by these models are often acceptable or good, but the majority of them are topic-independent, generic sentences. Therefore, for these response models, we mapped all labels 5 ("excellent") to 4 ("good"). Furthermore, for responses consisting of only stop-words, we decreased the labels by one level (e.g. 4 is mapped to 3). Finally, the BoWMovies response model suffered from a bug during the label collection period. Therefore, we decreased all labels given to BoWMovies responses to be at most 2 ("poor"). In total, we collected 199, 678 labels. We split this into training (train), development (dev) and testing (test) datasets consisting of respectively 137,549, 23,298 and 38,831 labels each. Training: We optimize the scoring model w.r.t. log-likelihood (cross-entropy) to predict the 4th layer, which represents the AMT label classes. Formally, we optimize the parameters θ: ˆθ = arg max log Pθ(y|x), θ x,y (6) where x are the input features, y is the corresponding AMT label class (a one-hot vector) and Pθ(y|x) is the model’s predicted probability of y given x, computed in the second last layer of the scoring model. We use the first-order gradient-descent optimizer Adam (Kingma & Ba 2015) We experiment with a variety of hyper-parameters, and select the best hyper-parameter combination based on the log-likelihood of the dev set. For the first hidden layer, we experiment with layer sizes in the set: {500, 200, 50}. For the second hidden layer, we experiment with layer sizes in the set: {50, 20, 5}. We use L2 regularization on all model parameters, except for bias parameters. We experiment with L2 regularization coefficients in the set: {10.0, 1.0, 10−1, . . . , 10−9} Unfortunately, we do not have labels to train the last layer. Therefore, we fix the parameters of the last layer to the vector [1.0, 2.0, 3.0, 4.0, 5.0]. In other words, we assign a score of 1.0 for the label very poor, a score of 2.0 for the label poor, a score of 3.0 for the label acceptable, a score of 4.0 for the label good and a 16 score of 5.0 for the label excellent. As this model was trained on crowdsourced data from Amazon Mechanical Turk (AMT), we call this model Supervised AMT. Table 2: Scoring model evaluation on Amazon Mechanical Turk test set w.r.t. Pearson correlation coefficient, Spearman’s rank correlation coefficient and mean squared error. Model Pearson Spearman Mean squared error Average Predictor Supervised AMT 0.00 0.40 0.00 0.38 1.30 1.10 60 Policy mmm Random lm Alicebot Evibot + Alicebot mmm Supervised AMT 50 w :S 6 so N 6 1 ° oe Very poor Poor Acceptable : . I ° # Frequency (in %) Figure 6: Amazon Mechanical Turk class frequencies on the test set w.r.t. different policies. Table 2 shows the performance w.r.t. Pearson correlation coefficient, Spearman’s rank correlation coefficient and mean squared error. The metrics are computed after linearly transforming the AMT class categories to the scalar output score (i.e. by taking the dot-product between the one-hot class vector and the vector [1.0, 2.0, 3.0, 4.0, 5.0]). The Average Predictor is a baseline model, which always predicts with the average output score. As shown, Supervised AMT achieves a Pearson correlation coefficient of 0.40, a Spearman’s rank correlation coefficient of 0.38 and a significant reduction in mean squared error. This indicates Supervised AMT performs significantly better than the baseline. Figure 6 shows the performance w.r.t. each AMT label class. In addition to Supervised AMT, the figure shows the performance of three baseline policies: 1) Random, which selects a response at random, 2) Alicebot, which selects an Alicebot response if available and otherwise selects a response at random, and 3) Evibot + Alicebot, which selects an Evibot response if available and otherwise selects an Alicebot response. For each policy, the figure shows the percentage of responses selected by the policy belonging to a particular AMT label class. In one end of the spectrum, we observe that Supervised AMT has a ~30% point reduction compared to Random in responses belonging to the "very poor" class. For the same AMT label class, Supervised AMT has a reduction of ~10% points compared to Alicebot and Evibot + Alicebot. In the other end of the spectrum, we observe that Supervised AMT performs significantly better than the three baselines w.r.t. the classes "good" and "excellent". In particular, Supervised AMT reaches ~8% responses belonging to the class "excellent". This is more than double compared to all three baseline policies. This demonstrates that Supervised AMT has learned to select "good" and "excellent" responses, while avoiding "very poor" and "poor" responses. 17 Overall, the results show that Supervised AMT improves substantially over all baseline policies. Nevertheless, ~46% of the Supervised AMT responses belong to the classes "very poor" and "poor". This implies that there is ample space for improving both Supervised AMT and the set of candidate responses (i.e. the system’s response models). # 4.4 Supervised Learned Reward: Learning with a Learned Reward Function In the first scoring model Supervised AMT we fixed the last output layer weights to [1.0, 2.0, 3.0, 4.0, 5.0]. In other words, we assigned a score of 1.0 for very poor responses, 2.0 for poor responses, 3.0 for acceptable responses, and so on. It’s not clear whether this score is correlated with scores given by real-world Alexa users, which is what we ultimately want to optimize the system for. This section describes another approach, which remedies this problem by learning to predict the Alexa user scores based on previously recorded dialogues. Learned Reward Function: Let ht be a dialogue history and let at be the corresponding response, given by the system at time t. We aim to learn a linear regression model, gφ, which predicts the corresponding return (Alexa user score) at the current dialogue turn: gφ(ht, at) ∈ [1, 5], where φ are the model parameters. We call this a reward model, since it directly models the Alexa user score, which we aim to maximize. Let {hd Let Rd ∈ [1, 5] denote the observed real-valued return for dialogue d. Specifically, we set Rd to be the Alexa user score given at the end of dialogue d. It’s optional for users to a give a score; users are prompted to give a score at the end, but they may opt out by stopping the application. Although not all users give scores, we do not consider examples without scores.20 Furthermore, users are encouraged to give a score in the range 1 − 5. The majority of users give whole number (integer) scores, but some users give decimal scores (e.g. 3.5). Therefore, we treat Rd as a real-valued number in the range 1 − 5. We learn ¢ by minimizing the squared error between the model’s prediction and the observed return: @ ˆφ = arg max (gφ(hd t , ad t ) − Rd)2 φ d (8) t As before, we optimize the model parameters with mini-batch stochastic gradient de- scent in the set {10.0, 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.0}. We select the coefficient with the smallest squared error on a hold-out dataset. As input to the reward model we compute 23 features based on the dialogue history and a candidate response. As training data is scarce, we use only higher-level features: AMT label class: A vector indicating the probability of the AMT label classes for the candidate response, computed using Supervised AMT, as well as the probability that the candidate response has priority. If the candidate response has priority, the vector is zero in all entries, except the last entry corresponding to the priority class: [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]. A binary feature, which is 1.0 when the response only contains stop-words and otherwise zero. The number of words in the response, and the square root of the number of words in the response. A one-hot vector, indicating whether the last user utterance’s dialogue is a request, a question, a statement or contains profanity (Stolcke et al. 2000). Generic response: Response length: Dialogue act: 20By ignoring dialogues without Alexa user scores, we introduce a significant bias in our reward model. In particular, it seems likely that the users who did not provide a score either found the system to be very poor or to lack particular functions/features they expected (e.g. non-conversational activities, such as playing games or taking quizzes.). A related problem arises in medical statistics, when patients undergo a treatment and, later, their outcome is not observed. 18 Sentiment class: A one-hot vector, indicating whether the last user utterance’s dialogue is negative, neutral or positive. Generic user utterance: A binary feature, which is 1.0 when the last user utterance only contains stop-words, and otherwise zero. User utterance length: The number of words in the last user utterance, and the square root of the number of words in the response. A binary feature, which is 1.0 when the last user utterance is very short (less than three words) and contains at least one word indicating the user is confused (e.g. "what", "silly", "stupid"). The number of dialogue turns so far, as well as the square root and logarithm of the number of dialogue turns. Confusion indicator: Dialogue length: In total, our dataset for training the reward model has 4340 dialogues. We split this into a training set with 3255 examples and a test set with 1085 examples. To increase data efficiency, we learn an ensemble model through a variant of the bagging tech- nique (Breiman 1996). We create 5 new training sets, which are shuffled versions of the original training set. Each shuffled dataset is split into a sub-training set and sub-hold-out set. The sub- hold-out sets are created such that the examples in one set do not overlap with other sub-hold-out sets. A reward model is trained on each sub-training set, with its hyper-parameters selected on the sub-hold-out set. This increases data efficiency by allowing us to re-use the sub-hold-out sets for training, which would otherwise not have been used. The final reward model is an ensemble, where the output is an average of the underlying linear regression models. The reward model obtains a mean squared error of 0.96 and a Spearman’s rank correlation coefficient of 0.19 w.r.t. the real Alexa user on the test set. In comparison, a model predicting with the average user score obtains a mean squared error of 0.99 and (because it outputs a constant) a Spearman’s rank correlation coefficient of zero. Although the reward model is better than predicting the average, its correlation is relatively low. There are two reasons for this. First, the amount of training data is very small. This makes it difficult to learn the relationships between the features and the Alexa user scores. Second, the Alexa user scores are likely to have high variance because, they are influenced by many different factors. The score of the user may be determined by a single turn in the dialogue (e.g. a single misunderstanding at the end of the dialogue could result in a very low user score, even if all the previous turns in the dialogue were excellent). The score of the user may be affected by the accuracy of the speech recognition module. More speech recognition errors will inevitably lead to frustrated users. In a preliminary study, we found that Spearman’s rank correlation coefficient between the speech recognition confidences and the Alexa user scores was between 0.05 − 0.09. In comparison to correlations with other factors, this implies that speech recognition performance plays an important role in determining user satisfaction.21 In addition, extrinsic factors are likely to have a substantial influence on the user scores. The user scores are likely to depend not only on the dialogue, but also on the user’s profile (e.g. whether the user is an adult or a child), the environment (e.g. whether the user is alone with the system or several users are taking turns conversing with the system), the user’s expectations towards the system before starting the conversation (e.g. whether the system is capable of playing games) and the emotional state of the user (e.g. the user’s mood). Training: To prevent overfitting, we do not train the scoring model (action-value function) from scratch with the reward model as target. Instead, we first initialize the model with the parameters of the Supervised AMT scoring model, and then fine-tune it with the reward model outputs to minimize the squared error: ˆθ = arg max (fθ(hd t , ad t ) − gφ(hd t , ad t ))2, θ d t (9) As before, we optimize the model parameters with stochastic gradient descent using Adam. As training this model does not depend on AMT labels, training is carried out on recorded dialogues. We train on several thousand recorded dialogue examples, where about 80% are used for training and about 20% are used as hold-out set. No regularization is used. We early stop on the squared error of 21This was confirmed by manual inspection of the conversation logs, where the majority of conversations had several speech recognition errors. In conversations with an excessive number of speech recognition errors (perhaps due to noisy environments), the users’ utterances clearly showed frustration with the system. 19 the hold-out dataset w.r.t. Alexa user scores predicted by the reward model. As this scoring model was trained with a learned reward function, we call it Supervised Learned Reward. # 4.5 Off-policy REINFORCE As discussed earlier, one way to parametrize the policy is as a discrete probability distribution over actions. This parametrization allows us to learn the policy directly from recorded dialogues through a set of methods known as policy gradient methods. This section describes one such approach. Off-policy Reinforcement Learning: We use a variant of the classical REINFORCE algo- rithm (Williams 1992, Precup 2000, Precup et al. 2001), which we call Off-policy REINFORCE. Recall eq. (4), where the policy’s distribution over actions is parametrized as softmax function applied to a function fθ with parameters θ. As before, let {hd t is the dialogue history for dialogue d at time t, ad t is the agent’s action for dialogue d at time t and Rd is the return for dialogue d. Let D be the number of dialogues and let T d be the number of turns in dialogue d. Further, let θd be the parameters of the stochastic policy πθd used during dialogue d. The Off-policy REINFORCE algorithm updates the policy parameters θ by: ∆θ ∝ cd t ∇θ log πθ(ad t |hd t ) Rd where d ∼ Uniform(1, D) and t ∼ Uniform(1, T d), (10) # where cd t is the importance weight ratio: # t t adet Tay Ta(ay |hi) C= pS. Tera 4 (af Ihe) This ratio corrects for the discrepancy between the learned policy 79 and the policy under which the data was collected 7g, (sometimes referred to as the behaviour policy). It up-weights examples with high probability under the learned policy and down-weights examples with low probability under the learned reward function. qd) The intuition behind the algorithm can be illustrated by analogy with learning from trial and error. t ) Rd will be a When an example has a high return (i.e. high user score), the term ∇θ log πθ(ad vector pointing in a direction increasing the probability of taking action ad t . On the other hand, when t ) Rd will be a vector close t |hd an example has low return (i.e. low user score), the term ∇θ log πθ(ad to zero or a vector pointing in the opposite direction, hence decreasing the probability of taking action ad t . The importance ratio cd t is known to exhibit very high, possibly infinite, variance (Precup et al. 2001). Therefore, we truncate the products in the nominator and denominator to only include the current time step t: cd t,trunc. def= πθ(ad πθd (ad t |hd t ) t |hd t ) . (12) This induces bias in the learning process, but also acts as a regularizer. Reward Shaping: As mentioned before, one problem with the Off-policy REINFORCE algorithm presented in eq. (10) is that it suffers from high variance (Precup et al. 2001). The algorithm uses the return, observed only at the very end of an episode, to update the policy’s action probabilities for all intermediate actions in an episode. With a small number of examples, the variance in the gradient estimator is overwhelming and this could easily lead the agent to over-estimate the utility of poor actions and, vice versa, to under-estimate the utility of good actions. One remedy for this problem is reward shaping, where the reward at each time step is estimated using an auxiliary function (Ng et al. 1999). For our purpose, we propose a simple variant of reward shaping which takes into account the sentiment of the user. When the user responds with a negative sentiment (e.g. an angry comment), we will assume that the preceding action was highly inappropriate and assign it a reward of zero. Given a dialogue d, at each time t we assign reward rd t : 0 Rd T d 20 With reward shaping and truncated importance weights, the learning update becomes: # ∆θ ∝ cd # t,trunc.∇θ log πθ(ad # t |hd # t ) rd t where d ∼ Uniform(1, D), t ∼ Uniform(1, T d), (14) Off-policy Evaluation: To evaluate the policy, we estimate the expected return (Precup 2000): Rπθ [R] ≈ t,trunc. rd cd t . d,t (15) Furthermore, by substituting rd t with a constant reward of 1.0 for each time step, we can compute the estimated number of time steps per episode under the policy. As will be discussed later, this is an orthogonal metric based on which we can analyse and evaluate each policy. However, this estimate does not include the number of priority responses, since there are no actions for the agent to take when there is a priority response. Training: We initialize the policy model with the parameters of Supervised AMT, and then train the parameters w.r.t. eq. (14) with stochastic gradient descent using Adam. We use a set of a few thousand dialogues recorded between Alexa users and a preliminary version of the system. About 60% of these examples are used for training, and about 20% are used for development and testing. To reduce the risk of overfitting, we only train the weights related to the second last layer using off-policy REINFORCE. We use a random grid search with different hyper-parameters, which include the temperature parameter λ and the learning rate. We select the hyper-parameters with the highest expected return on the development set. # 4.6 Off-policy REINFORCE with Learned Reward Function Similar to the Supervised Learned Reward policy, we may use the reward model for training with the Off-policy REINFORCE algorithm. This section describes how we combine the two approaches. Reward Shaping with Learned Reward Model: We use the reward model to compute a new estimate for the reward at each time step in each dialogue: rd t def= if user utterance at time t + 1 has negative sentiment, gφ(ht, at) otherwise. (16) This is substituted into eq. (14) for training and into eq. (15) for evaluation. Training: As with Off-policy REINFORCE, we initialize the policy model with the parameters of the Supervised AMT model, and then train the parameters w.r.t. eq. (14) with mini-batch stochastic gradient descent using Adam. We use the same set of dialogues and split as Off-policy REINFORCE. We use a random grid search with different hyper-parameters, As before, to reduce the risk of overfitting, we only train the weights related to the second last layer using this method. which include the temperature parameter λ and the learning rate, and select the hyper-parameters with the highest expected return on the development set. In this case, the expected return is computed according to the learned reward model. As this policy uses the learned reward model, we call it Off-policy REINFORCE Learned Reward. # 4.7 Q-learning with the Abstract Discourse Markov Decision Process The approaches described so far have each their own advantages and disadvantages. One way to quantify their differences is through a decomposition known as the bias-variance trade-off. At one end of the spectrum, the Supervised AMT policy has low variance, because it was trained with hundreds of thousands of human annotations at the level of each model response. However, for the same reason, Supervised AMT incurs a substantial bias, because the human annotations do not reflect the real user satisfaction for an entire conversation. At the other end of the spectrum, Off-policy REINFORCE suffers from high variance, because it was trained with only a few thousand dialogues and corresponding user scores. To make matters worse, the user scores are affected by many external factors (e.g. user profile, user expectations, and so on) and occur at the granularity of an entire conversation. Nevertheless, this method incurs low bias because it directly optimizes the objective metric we care about (i.e. the user score).22 By utilizing a learned reward function, Supervised 22Due to truncated importance weights, however, the off-policy REINFORCE training procedure is still biased. 21 Learned Reward and Off-policy REINFORCE Learned Reward suffer less from bias, but since the learned reward function has its own variance component, they are both bound to have higher variance. In general, finding the optimal trade-off between bias and variance can be notoriously difficult. In this section we propose a novel method for trading off bias and variance by learning the policy from simulations in an approximate Markov decision process. Motivation A Markov decision process (MDP) is a framework for modeling sequential decision making (Sutton & Barto 1998). In the general setting, an MDP is a model consisting of a discrete set of states H, a discrete set of actions A, a transition distribution function P , a reward distribution function R, and a discount factor γ. As before, an agent aims to maximize its reward during each episode. Let t denote the time step of an episode with length T . At time step t, the agent is in state ht ∈ H and takes action at ∈ A. Afterwards, the agent receives reward rt ∼ R(ht, at) and transitions to a new state ht+1 ∼ P (ht|at). Given an MDP model for open-domain conversations, there are dozens of algorithms we could apply to learn the agent’s policy (Sutton & Barto 1998). Unfortunately, such an MDP is difficult to build or estimate. We could try to naively estimate one from the recorded dialogues, but this would require solving two extremely difficult problems. First, we would need to learn the transition distribution P , which outputs the next user utterance in the dialogue given the dialogue history. This problem is likely to be as difficult as our original problem of finding an appropriate response to the user! Second, we would need to learn the reward distribution R for each time step. However, as we have shown earlier, it is very difficult to learn to predict the user score for an entire dialogue. Given the data we have available, estimating the reward for a single turn is likely also going to be difficult. Instead, we propose to tackle the problem by splitting it into three smaller parts. Figure 7: Probabilistic directed graphical model for the Abstract Discourse Markov Decision Process. For each time step t, zt is a discrete random variable which represents the abstract state of the dialogue, ht represents the dialogue history, at represents the action taken by the system (i.e. the selected response), yt represents the sampled AMT label and rt represents the sampled reward. The Abstract Discourse Markov Decision Process The model we propose to learn is called the Abstract Discourse MDP. As illustrated in Figure 7, the model follows a hierarchical structure at each time step. At time t, the agent is in state zt ∈ Z, a discrete random variable representing the abstract discourse state. This variable only represents a few high-level properties related to the dialogue history. We define the set Z is the Cartesian product: Z = ZDialogue act × ZUser sentiment × ZGeneric user utterance, (17) and where of sets. {Accept, Reject, Request, Politics, Generic Question, Personal Question, Statement, Greeting, Goodbye, Other}. the intention of acts The second set consists of sentiments types: user’s utterance (Stolcke et al. 2000). ZUser sentiment = {Negative, Neutral, Positive}. The third set represent a binary variable: ZGeneric user utterance = {True, False}. This variable is True only when the user utterance is generic and topic-independent (i.e. when the user utterance only contains stop-words). We build a hand-crafted deterministic classifier, which maps a dialogue history to the corresponding classes in ZDialogue act, ZUser sentiment and ZGeneric user utterance. We denote this mapping fh→z. Although we only 22 consider dialogue acts, sentiment and generic utterances, it is trivial to expand the abstract discourse state with other types of discrete or real-valued variables. Given a sample zt, the Abstract Discourse MDP samples a dialogue history ht from a finite set of dialogue histories H. In particular, ht is sampled at uniformly random from the set of dialogue histories where the last utterance is mapped to zt: ht ∼ P (h|H, fh→z, zt) def= Uniform({h | h ∈ H and fh→z(h) = zt}). In other words, ht is a dialogue history where dialogue act, user sentiment and generic property is identical to the discrete variable zt. For our purpose, H is the set of all recorded dialogues between Alexa users and a preliminary version of the system. This formally makes the Abstract Discourse MDP a non-parametric model, since sampling from the model requires access to the set of recorded dialogue histories H. This set grows over time when the system is deployed in practice. This is useful, because it allows to continuously improve the policy as new data becomes available. Further, it should be noted that the set Z is small enough that every possible state is observed several times in the recorded dialogues. Given a sample ht, the agent chooses an action at according to its policy πθ(at|ht), with parameters θ. A reward rt is then sampled such that rt ∼ R(ht, at), where R is a distribution function. In our case, we use the probability function Pˆθ, where the parameters ˆθ are estimated using supervised learning on AMT labels in eq. (6). We specify a reward of −2.0 for a "very poor" response class, a reward of −1.0 for a "poor" response class, a reward of 0.0 for an "acceptable" response class, a reward of 1.0 for a "good" response class and a reward of 2.0 for an "excellent" response class. To reduce the number of hyperparameters, we use the expected reward instead of a sample:23 rt = Pˆθ(y|ht, at)T[−2.0, −1.0, 0.0, 1.0, 2.0]. (19) Next, a variable yt ∈ {"very poor", "poor", "acceptable", "good", "excellent"} is sampled: yt ∼ Pˆθ(y|ht, at). This variable represents one appropriateness interpretation of the output. This variable helps predict the future state zt+1, because the overall appropriateness of a response has a significant impact on the user’s next utterance (e.g. very poor responses often cause users to respond with What? or I don’t understand.). Finally, a new state zt+1 is sampled according to P ˆψ: zt+1 ∼ P ˆψ(z|zt, ht, at, yt). where P ˆψ is the transition distribution with parameters ˆψ. The transition distribution is parametrized by three independent two-layer MLP models, which take as input the same features as the scoring function, as well as 1) a one-hot vector representing the sampled response class yt, 2) a one-hot vector representing the dialogue act of the last user utterance, 3) a one-hot vector representing the sentiment of the last user utterance, 4) a binary variable indicating whether the last user utterance was generic, and 5) a binary variable indicating whether the last user utterance contained a wh-word (e.g. what, who). The first MLP predicts the next dialogue act, the second MLP predicts the next sentiment type and the third MLP predicts whether the next user utterance is generic. The dataset for training the MLPs consists of 499, 757 transitions, of which 70% are used for training and 30% for evaluation. The MLPs are trained with maximum log-likelihood using mini-batch stochastic gradient descent. We use Adam and early-stop on a hold-out set. Due to the large number of examples, no regularization is used. The three MLP models obtain a joint perplexity of 19.51. In comparison, a baseline model, which always assigns the average class frequency as the output probability obtains a perplexity of 23.87. On average, this means that roughly 3 − 4 possible zt+1 states can be eliminated by conditioning on the previous variables zt, ht, at and yt. In other words, the previous state zt and ht, together with the agent’s action at has a significant effect on the future state zt+1. This means that an agent trained in the Abstract Discourse MDP has the potential to learn to take into account future states of the dialogue when selecting its action. This is in contrast to policies learned using supervised learning, which do not consider future dialogue states. 23For example, if we were to use a Gaussian distribution, we would have to at least also specify the variance parameter. 23 Table 3: Policy evaluation on AMT w.r.t. score mean and score standard deviation (std). 90% confidence intervals are given for means (after ±) and standard deviations (in square brackets). Full test set Difficult test set Policy Score mean Score std Score mean Score std Alicebot Evibot + Alicebot Supervised AMT Off-policy REINFORCE Q-learning AMT 2.19 ± 0.03 2.25 ± 0.04 2.63 ± 0.04 2.61 ± 0.04 2.64 ± 0.04 1.17 [1.15, 1.20] 1.22 [1.20, 1.25] 1.34 [1.31, 1.37] 1.33 [1.31, 1.36] 1.37 [1.34, 1.40] 1.79 ± 0.03 1.79 ± 0.03 2.34 ± 0.04 2.30 ± 0.04 2.35 ± 0.04 0.88 [0.86, 0.90] 0.86 [0.84, 0.88] 1.26 [1.23, 1.29] 1.25 [1.22, 1.28] 1.31 [1.28, 1.34] The idea of modeling a high-level abstraction of the dialogue, zt, is related to the dialogue state tracking challenge (Williams et al. 2013, 2016). In this challenge, the task is to map the dialogue history to a discrete state representing all salient information about the dialogue. Unlike the dialogue state tracking challenge, however, the variable zt only includes limited salient information about the dialogue. For example, in our implementation, zt does not include topical information. As such, zt is only a partial representation of the dialogue history. Training Given the Abstract Discourse MDP, we are now able to learn policies directly from simulations. We use Q-learning with experience replay to learn the policy parametrized as an action- value function (Mnih et al.]2013 3). Q-learning is a simple off-policy reinforcement learning algorithm, which has been shown to be effective for training policies parametrized by neural networks. For experience replay, we use a memory buffer of size 1000. We use an ¢-greedy exploration scheme with € = 0.1. We experiment with discount factors 7 € {0.1,0.2,0.5}. As before, the parameters are updated using Adam. To reduce the risk of overfitting, we only train the weights related to the final output layer and the skip-connection (shown in dotted lines in Figure[2) using Q-learning. Training is carried out in two alternating phases. We train the policy for 100 episodes. Then, we evaluate the policy for 100 episodes w.r.t. average return. Afterwards, we continue training the policy for another 100 episodes. During evaluation, each dialogue history is sampled from a separate set of dialogue histories, HEval, which is disjoint from the set of dialogue histories, HTrain used at training time. This ensures that the policy is not overfitting our finite set of dialogue histories. For each hyper-parameter combination, we train the policy between 400 and 600 episodes. We select the policy which performs best w.r.t. average return. To keep notation brief, we call this policy Q-learning AMT. # 4.8 Preliminary Evaluation In this section, we carry out a preliminary evaluation of the response model selection policies. AMT Evaluation: We first evaluate the learned policies on the w.r.t. the human scores in the AMT test set. We measure the average performance as a real-valued scalar, where the label "Very poor" is given a score of 1, label "Poor" is given a score of 2 and so on. We also report standard deviations for the scores, which measure the variance or risk the policies are willing to take; higher standard deviations indicate that a policy is more likely to select responses which result in extreme labels (e.g. "Very poor" and "Excellent"). For both means and standard deviations we report 90% confidence intervals estimated under the assumption that the scores are Gaussian-distributed. In addition to measuring performance on the full test set, we also measure performance on a subset of the test set where neither Alicebot nor Evibot had responses labeled "Good" or "Excellent". These are test examples, where an appropriate response is likely to come only from some of the other models. Determining an appropriate response for these examples is likely to be more difficult. We refer to this subset as the "Difficult test set". We evaluate the policies Supervised AMT, Off-policy REINFORCE and Q-learning AMT. In addition, we also evaluate two heuristic policies: 1) a policy selecting only Alicebot responses called Alicebot, and 2) a policy selecting Evibot responses when possible and Alicebot responses otherwise, called Evibot + Alicebot. The results are given in Table 3. The results show that the three learned policies are all significantly better w.r.t. mean score compared to both Alicebot and Evibot + Alicebot. Not surprisingly, this 24 difference is amplified on the difficult test set. Q-learning AMT, Supervised AMT and Off-policy REINFORCE appear to perform overall equally well. This shows that machine learning has helped learn effective policies, able to select other model responses when neither the Alicebot and Evibot responses are appropriate. Next, the results show that Q-learning AMT has higher standard deviations than the other policies on both the full test set and the difficult test set. Furthermore, since these standard deviations are evaluated at the level of a single response, we might expect this variability to compound throughout an entire conversation. This strongly indicates that Q-learning AMT is more risk tolerant than the other policies. Table 4: Off-policy evaluation w.r.t. expected (average) Alexa user score and number of time steps (excluding priority responses) on test set. Policy Alexa user score Time steps Supervised AMT Supervised Learned Reward Off-policy REINFORCE Off-policy REINFORCE Learned Reward Q-learning AMT 2.06 0.94 2.45 1.29 2.08 8.19 3.66 10.08 5.02 8.28 Off-policy Evaluation: One way to evaluate the selection policies is by using the off-policy evalu- ation given in eq. (15). This equation provides an estimate of the expected Alexa user score under each policy.24 As described earlier, the same equation can be used to estimate the expected number of time steps per episode (excluding priority responses). The expected (average) Alexa user score and number of time steps per episode (excluding priority responses) are given in Table 4. Here we observe that the Off-policy REINFORCE performs best followed by Q-learning AMT and Supervised AMT w.r.t. expected Alexa user score. Off-policy REINFORCE reaches 2.45, which is a major 17.8% improvement over the second best performing model Q-learning AMT. However, this advantage should be taken with a grain of salt. As discussed earlier, the off-policy evaluation in eq. (15) is a biased estimator since the importance weights have been truncated. Moreover, Off-policy REINFORCE has been trained specifically to maximize this biased estimator, while all other policies have been trained to maximize other objective functions. Similarly, w.r.t. expected number of time steps, Off-policy REINFORCE reaches the highest number of time steps followed by Q-learning AMT and Supervised AMT. As before, we should take this result with a grain of salt, since this evaluation is also biased and does not take into account priority responses. Further, it’s not clear that increasing the number of time steps will increase user scores. Nevertheless, Off-policy REINFORCE, Q-learning AMT and Supervised AMT appear to be our prime candidates for further experiments. Response Model Selection Frequency: Figure 8 shows the frequency with which Supervised AMT, Off-policy REINFORCE and Q-learning AMT select different response models. We observe that the policy learned using Off-policy REINFORCE tends to strongly prefer Alicebot responses over other models. The Alicebot responses are among the safest and most topic-dependent, generic responses in the system, which suggests that Off-policy REINFORCE has learned a highly risk averse strategy. On the other hand, the Q-learning AMT policy selects Alicebot responses substantially less often than both Off-policy REINFORCE and Supervised AMT. Instead, Q-learning AMT tends to prefer responses retrieved from Washington Post and from Google search results. These responses are semantically richer and have the potential to engage the user more deeply in a particular topic, but they are also more risky (e.g. a bad choice could derail the entire conversation.). This suggests that Q-learning AMT has learned a more risk tolerant strategy. One possible explanation for this difference is that Q-learning AMT was trained using simulations. By learning online from simulations, the policy has been able to explore new actions and discover high-level strategies lasting multiple time steps. In particular, the policy has been allowed to experiment with riskier actions and to learn remediation or fall-back strategies, in order to handle cases where a risky action fails. This might also explain its stronger preference for BoWFactGenerator responses, which might be serving as a fall-back strategy by outputting factual statements on the current topic. This would have been difficult 24For the policies parametrized as action-value functions, we transform eq. (2) to eq. (4) by setting fθ = Qθ and fitting the temperature parameter λ on the Off-policy REINFORCE development set. 25 Evibot Alicebot Elizabot Initiatorbot BoWFactGenerator VHREDSubtitles LSTMClassifierMSMarco Washington Post Models Retrieval Model Policy Retrieva’ Models ss Supervised AMT GRUQuestionGenerator mmm Off-policy REINFORCE Other Models Mm Q-learning AMT 0 5 10 15 20 25 30 35 40 45 Response selection frequency (in %) # Reddit edait Figure 8: Response model selection probabilities across response models for Supervised AMT, Off- policy REINFORCE and Q-learning AMT on the AMT label test dataset. 95% confidence intervals are shown based on the Wilson score interval for binomial distributions. Table 5: Policy evaluation using the Abstract Discourse MDP w.r.t. average return, average reward per time step and average episode length on dev set (± standard deviations). The reward function is based on Supervised AMT. Policy Average return Random −32.18 ± 31.77 Alicebot −15.56 ± 15.61 Evibot + Alicebot −11.33 ± 12.43 Supervised AMT −6.46 ± 8.01 Supervised Learned Reward −24.19 ± 23.30 Off-policy REINFORCE −7.30 ± 8.90 −0.87 ± 0.24 −0.37 ± 0.16 −0.29 ± 0.19 −0.15 ± 0.16 −0.73 ± 0.27 −0.16 ± 0.16 34.29 ± 33.02 42.01 ± 42.00 37.5 ± 38.69 42.84 ± 42.92 31.91 ± 30.09 43.24 ± 43.58 Off-policy REINFORCE Learned Reward Q-learning AMT −10.19 ± 11.15 −6.54 ± 8.02 −0.28 ± 0.19 −0.15 ± 0.18 35.51 ± 35.05 40.68 ± 39.13 # Average reward per time step Average dialogue length to learn for Off-policy REINFORCE, since the sequence of actions for such high-level strategies are sparsely observed in the data and, when they are observed, the corresponding returns (Alexa user scores) have high variance. A second observation is that Q-learning AMT has the strongest preference for Initiatorbot among the three policies. This could indicate that Q-learning AMT leans towards a system-initiative strategy (e.g. a strategy where the system tries to maintain control of the conversation by asking questions, changing topics and so on). Further analysis is needed to confirm this. Abstract Discourse MDP Evaluation Next, we can evaluate the performance of each policy w.r.t. simulations in the Abstract Discourse MDP. We simulate 500 episodes under each policy and evaluate it w.r.t. average return, average reward per time step and dialogue length. In addition to evaluating the five policies described earlier, we also evaluate three heuristic policies: 1) a policy selecting responses at random called Random, 2) the Alicebot policy, and 3) the Evibot + Alicebot policy. Evaluating these models will serve to validate the approximate MDP. The results are given in Table 5. We observe that Supervised AMT performs best w.r.t. average return and average reward per time step. However, this comes as no surprise. The reward function in the MDP is defined as Supervised AMT, so by construction this policy achieves the highest reward per time step. Next we observe that Q-learning AMT is on par with Supervised AMT, both achieving same −0.15 average reward per time step. Second in line comes Off-policy REINFORCE, achieving 26 an average reward per time step of −0.16. However, Off-policy REINFORCE also achieved the highest average dialogue length of 43.24. At the other end of the spectrum comes, as expected, the Random policy performing worst w.r.t. all metrics. In comparison, both Alicebot and Evibot + Alicebot perform better w.r.t. all metrics, with Evibot + Alicebot achieving the best average return and average reward per time step out of the three heuristic policies. This validates the utility of the Abstract Discourse MDP as an environment for training and evaluating policies. Overall, Off-policy REINFORCE, Q-learning AMT and Supervised AMT still appear to be the best performing models in the preliminary evaluation. Evibot ° ° Alicebot e ° ° ° Elizabot Initiatorbot BoWMovies e ° ° ° BoWEscapePlan ° ° BoWFactGenerator Reddit models -B- -B- Be ° ° SkipThoughtBooks Q-learning AMT policy VHREDSubtitles LSTMClassifierMSMarco oe oo oe e GRUQuestionGenerator; 0 0 0 0 0 2 0 0 0 VHREDWashingtonPost { 0 BoWWashingtonPost ~— — om eo 6 ° VHREDSubtitles | © | © a oe See egnaeypey on uw 8383888 § see 8S sa @ ae 8 e226 8 a2oe2ea257 83 8 seeed > SS S88 U5 82S = 5 € goeeseeoes — @ s $s zi 8 & 5 2 aos 2e 226 @x & =ecasa -6%o908 8 5eEes f£adys ez Ss eee Seee esuy of a os ee" eS iaas 8 G Seg % F2¢ a 35S Supervised AMT policy Figure 9: Contingency table comparing selected response models between Supervised AMT and Q-learning AMT. The cells in the matrix show the number of times the Supervised AMT policy selected the row response model and the Q-learning AMT policy selected the column response model. The cell frequencies were computed by simulating 500 episodes under the Q-learning policy in the Abstract Discourse MDP. Note that all models retrieving responses from Reddit have been agglomerated into the class Reddit models. Finally, we compare Q-learning AMT with Supervised AMT w.r.t. the action taken in states from episodes simulated in the Abstract Discourse MDP. As shown in Figure 9, the two policies diverge w.r.t. several response models. When Supervised AMT would have selected topic-independent, generic Alicebot and Elizabot responses, Q-learning AMT often selects BoWFactGenerator, Initiatorbot and VHREDWashingtonPost responses. For example, there were 347 instances where Supervised AMT selected Alicebot, but where Q-learning AMT selected BoWFactGenerator. Similarly, where Supervised AMT would have preferred generic VHREDSubtitle responses, Q-learning AMT often selects responses from BoWFactGenerator, InitiatorBot and VHREDRedditSports. This supports our previous analysis showing that Q-learning AMT has learned a more risk tolerant strategy, which involves response models with semantically richer content. In the next section, we evaluate these policies with real-world users. 27 # 5 A/B Testing Experiments To evaluate the dialogue manager policies described in the previous section, we carry out A/B testing experiments. During each A/B testing experiment, we evaluate several policies for selecting the response model. When Alexa users start a conversation with the system, they are automatically assigned to a random policy and afterwards their dialogues and final scores are recorded. A/B testing allows us to accurately compare different dialogue manager policies by keeping all other system factors constant (or almost constant). This is in contrast to evaluating the system performance over time, when the system is continuously being modified. In such a situation, it is often difficult to evaluate the improvement or degradation of performance w.r.t. particular system modifications. However, even during our A/B testing experiments, the distribution over Alexa users still changes through time. Different types of users will be using the system depending on the time of day, weekday and holiday season. In addition, the user expectations towards our system change over time as they interact with other socialbots in the competition. In other words, we must consider the Alexa user distribution as following a non-stationary stochastic process. Therefore, we take two steps to reduce confounding factors and correlations between users. First, during each A/B testing experiment, we evaluate all policies of interest simultaneously. This ensures that we have approximately the same number of users interacting with each policy w.r.t. time of day and weekday. This minimizes the effect of changes in the user distribution on the final user scores within that period. However, since the user distribution changes between the A/B testing experiments, we still cannot accurately compare policy performance across A/B testing experiments. Second, we discard scores from returning users (i.e. users who have already evaluated the system once). Users who are returning to the system are likely to be influenced by their previous interactions with the system. For example, users who previously had a positive experience with the system may be biased towards giving high scores in their next interaction. Further, the users who return to the system are likely to belong to a particular subpopulation of users. This particular group of users may inherently have more free time and be more willing to engage with socialbots than other users. Discarding returning user scores ensures that the evaluation is not biased towards this subpopulation of users. By discarding scores from returning users, we also ensure that the evaluation counts every user exactly once. Finally, it should be noted that we ignore dialogues where the Alexa user did not give a score. This inevitably biases our evaluation, since users who do not provide a score are likely to have been dissatisfied with the system or to have been expecting different functionality (e.g. non-conversational activities, such as playing music, playing games or taking quizzes). One potential remedy is to have all dialogues evaluated by a third-party (e.g. by asking human annotators on Amazon Mechanical Turk to evaluate the dialogue), but that is beyond the scope of these experiments. # 5.1 A/B Testing Experiment #1 The first A/B testing experiment was carried out between July 29th, 2017 and August 6th, 2017. We tested six dialogue manager policies: Evibot + Alicebot, Supervised AMT, Supervised Learned Reward, Off-policy REINFORCE, Off-policy REINFORCE Learned Reward and Q-learning AMT. For Off-policy REINFORCE and Off-policy REINFORCE Learned Reward, we use the greedy variant defined in eq. (5). This experiment occurred early in the Amazon Alexa Prize competition. This means that Alexa users have few expectations towards our system (e.g. expectations that the system can converse on a particular topic, or that the system can engage in non-conversational activities, such as playing word games or taking quizzes). Further, the period July 29th - August 6th overlaps with the summer holidays in the United States. This means that we might expect more children to interact with system than during other seasons. Policy Evaluation The results are given in Table 6.25 The table shows the average Alexa user scores, average dialogue length, average percentage of positive user utterances and average percentage of negative user utterances. In total, over a thousand user ratings were collected after discarding returning users. Ratings were collected after the end of the semi-finals competition, where all ratings 2595% confidence intervals are computed under the assumption that the Alexa user scores for each policy are drawn from a Gaussian distribution with its own mean and variance. This is an approximation, since the Alexa user scores only have support on the interval [1, 5]. 28 Table 6: First A/B testing experiment with six different policies (± 95% confidence intervals). Star ∗ indicates policy is significantly better than other policies at 95% statistical significance level. Policy User score Dialogue length Pos. utterances Neg. utterances Evibot + Alicebot Supervised AMT Supervised Learned Reward Off-policy REINFORCE 2.86 ± 0.22 2.80 ± 0.21 2.74 ± 0.21 2.86 ± 0.21 31.84 ± 6.02 34.94 ± 8.07 27.83 ± 5.05 37.51 ± 7.21 2.80% ± 0.79 4.00% ± 1.05 2.56% ± 0.70 3.98% ± 0.80 5.63% ± 1.27 8.06% ± 1.38 6.46% ± 1.29 6.25 ± 1.28 Off-policy REINFORCE Learned Reward Q-learning AMT* 2.84 ± 0.23 3.15 ± 0.20 34.56 ± 11.55 30.26 ± 4.64 2.79% ± 0.76 3.75% ± 0.93 6.90% ± 1.45 5.41% ± 1.16 Table 7: Amazon Alexa Prize semi-finals average team statistics provided by Amazon. Policy User score Dialogue length All teams Non-finalist teams Finalist teams 2.92 2.81 3.31 22 22 26 had been transcribed by human annotators. Each policy was evaluated by about two hundred unique Alexa users. As expected from our preliminary evaluation, we observe that Q-learning AMT and Off-policy REINFORCE perform best among all policies w.r.t. user scores. Q-learning AMT obtained an average user score of 3.15, which is significantly higher than all other policies at a 95% statistical significance level w.r.t. a one-tailed two-sample t-test. In comparison, the average user score for all the teams in the competition during the semi-finals was only 2.92. Interestingly, Off-policy REINFORCE achieved the longest dialogues with an average length of 37.51. This suggests Off-policy REINFORCE yields highly engaging conversations. In comparison, in the semi-finals, the average dialogue length of all teams was 22 and of the finalist teams was 26. We also observe that Off-policy REINFORCE had a slightly higher percentage of user utterances with negative sentiment compared to Q-learning AMT. This potentially indicates that the longer dialogues also include some frustrated interactions (e.g. users who repeat the same questions or statements in the hope that the system will return a more interesting response next time). The remaining policies achieved average Alexa user scores between 2.74 and 2.86, with the heuristic policy Evibot + Alicebot obtaining 2.86. This suggests that the other policies have not learned to select responses more appropriately than the Evibot + Alicebot heuristic. In conclusion, the results indicate that the risk tolerant learned by the Q-learning AMT policy performs best among all policies. This shows that learning a policy through simulations in an Abstract Discourse MDP may serve as a fruitful path towards developing open-domain socialbots. In addition, the performance of Off-policy REINFORCE indicates that optimizing the policy directly towards Alexa user scores could also potentially yield improvements. However, further investigation is required. # Length Analysis In an effort to further understand how the policies differ from each other, we carry out an analysis of the policies performance as a function of dialogue length. Although, we have recorded only a limited amount of data for dialogues with a particular length, this analysis could help illuminate directions for future experiments. Table 8 shows the average Alexa user scores w.r.t. four dialogue length intervals for the six policies. The estimates are based on between 30-70 Alexa user ratings for each policy and interval combination. First, we observe that Q-learning AMT performs better than all other policies for all intervals except the medium-short interval (10 − 19, or 5 − 10 back-and-forth turns). Further, its high performance for the long intervals (20 − 39 and ≥ 40) would suggest that Q-learning AMT performs excellent in long dialogues. The other learned policies Supervised AMT, Off-policy REINFORCE and Off-policy REINFORCE Learned Reward also appear to perform excellent in long dialogues. On the other 29 Table 8: First A/B testing experiment user scores with six different policies w.r.t. varying dialogue length (± one standard deviation). Dialogue length Policy < 10 10 - 19 20 - 39 ≥ 40 Evibot + Alicebot Supervised AMT Supervised Learned Reward Off-policy REINFORCE 2.88 ± 1.71 2.91 ± 1.59 3.31 ± 1.43 2.99 ± 1.64 2.58 ± 1.33 2.64 ± 1.38 2.45 ± 1.57 2.72 ± 1.57 2.93 ± 1.28 2.60 ± 1.40 2.19 ± 1.38 2.56 ± 1.31 2.99 ± 1.37 3.13 ± 1.43 2.90 ± 1.54 3.26 ± 1.45 Off-policy REINFORCE Learned Reward Q-learning AMT 2.91 ± 1.64 3.46 ± 1.40 2.53 ± 1.45 2.60 ± 1.45 2.9 ± 1.56 3.19 ± 1.39 3.14 ± 1.36 3.31 ± 1.33 hand, the heuristic Evibot + Alicebot policy and the Supervised Learned Reward policy appear to perform poorly in long dialogues, but that is not surprising given their low overall performance. In particular, Supervised Learned Reward seems to be performing well only for very short dialogues. This potentially indicates that the policy fails to either maintain user engagement or memorize longer-term context. However, further investigation is required. # Topical Specificity and Coherence We carry out an analysis of the topical specificity and coherence of the different policies. This analysis aims to quantify how much each policy stays on topic (e.g. whether the policy selects responses on the current topic or on new topics) and how specific its content is (e.g. how frequently the policy selects generic, topic-independent responses). This analysis is carried out at the utterance level, where we are fortunate to have more recorded data. The results are shown in Table 9. For topic specificity, we measure the average number of noun phrases per user utterance and the average number of noun phrases per system utterance.26 The more topic specific the user is, the higher we would expect the first metric to be. Similarly, the more topic specific the system is the higher we would expect the second metric to be. For topic coherence, we measure the word overlap between the user’s utterance and the system’s response, as well as word overlap between the user’s utterance and the system’s response at the next turn. The more the policy prefers to stay on topic, the higher we would expect these two metrics to be. As shown in the table, Q-learning AMT has obtained significantly higher scores w.r.t. both word overlap metrics and the average number of noun phrases per system utterance. This indicates that the Q-learning AMT policy has the highest topical coherency among all six policies, and that it generates the most topic specific (semantically rich) responses. This is in line with our previous analysis, where we found that Q-learning follows a highly risk tolerant strategy. Next in line, comes Supervised AMT, which also appears to maintain high topic specificity and coherence. In fact, Supervised AMT obtained the highest metric w.r.t. number of noun phrases per user utterance, which indicates that this policy is encouraging the user to give more topic specific responses. Afterwards comes Off-policy REINFORCE and Off-policy REINFORCE Learned Reward, which tend to select responses with significantly less noun phrases and less word overlap. This is also in line with our previous analysis, where we found that Off-policy REINFORCE follows a risk averse strategy. Finally, the heuristic policy Evibot + Alicebot selects responses with very few noun phrases and least word overlap among all policies. This indicates that the heuristic policy might be the least topic coherent policy, and that it mainly selects generic, topic-independent responses. Initiatorbot Evaluation This experiment also allowed us to analyze the outcomes of different conversation starter phrases given by the Initiatorbot. We carried out this analysis by computing the average Alexa user score for each of the 40 possible phrases. We found that phrases related to news (e.g. "Do you follow the news?"), politics (e.g. "Do you want to talk about politics?") and travelling (e.g. "Tell me, where do you like to go on vacation?") performed poorly across all policies. On the other hand, phrases related to animals (e.g. "Do you have pets?" and "What is the cutest animal you can think of?"), movies (e.g. "Let’s talk about movies. What’s the last movie you watched?") and 26We use https://spacy.io version 1.9.0 to detect noun phrases with the package "en_core_web_md- 1.2.1". 30 Table 9: First A/B testing experiment topical specificity and coherence of the six different policies. The columns are average number of noun phrases per user utterance (User NPs), average number of noun phrases per system utterance (System NPs), average number of overlapping words between the user’s utterance and the system’s response (Word overlap t → t + 1), and average number of overlapping words between the user’s utterance and the system’s response in the next turn (Word overlap t → t + 3). 95% confidence intervals are also shown. Stop words are excluded. Policy User NPs System NPs Word overlap Word overlap t → t + 1 t → t + 3 Evibot + Alicebot Supervised AMT Supervised Learned Reward Off-policy REINFORCE 0.55 ± 0.03 0.62 ± 0.03 0.57 ± 0.03 0.59 ± 0.02 1.05 ± 0.05 1.75 ± 0.07 1.50 ± 0.07 1.45 ± 0.05 7.33 ± 0.21 10.48 ± 0.28 8.35 ± 0.29 9.05 ± 0.21 7.31 ± 0.22 10.65 ± 0.29 8.36 ± 0.31 9.14 ± 0.22 Off-policy REINFORCE Learned Reward Q-learning AMT 0.61 ± 0.03 0.58 ± 0.03 1.04 ± 0.06 1.98 ± 0.08 7.42 ± 0.25 11.28 ± 0.30 7.42 ± 0.26 11.52 ± 0.32 Table 10: Second A/B testing experiment with two different policies (± 95% confidence intervals). Policy User score Dialogue length Pos. utterances Neg. utterances Off-policy REINFORCE Q-learning AMT 3.06 ± 0.12 2.92 ± 0.12 34.45 ± 3.76 31.84 ± 3.69 3.23% ± 0.45 3.38% ± 0.50 7.97% ± 0.85 7.61% ± 0.84 food (e.g. "Let’s talk about food. What is your favorite food?") performed well across all policies. For example, conversations where the Initiatorbot asked questions related to news and politics had an average Alexa user score of only 2.91 for the top two systems (Off-policy REINFORCE and Q-learning AMT). Mean while, conversations where the Initiatorbot asked questions about animals, food and movies the corresponding average Alexa user score was 3.17. We expected the conversation topic to affect user engagement, however it is surprising that these particular topics (animals, food and movies) were the most preferred ones. One possible explanation is that our system does not perform well on news, politics and travelling topics. However, the system already had several response models dedicated to discussing news and politics: six sequence-to-sequence models extracting responses from Reddit news and Reddit politics, two models extracting responses from Washington Post user comments and the BoWTrump model extracting responses from Donald J. Trump’s Twitter profile. In addition, Evibot is capable of answering many factual questions about news and politics and BoWFactGenerator contains hundreds of facts related to news and politics. As such, there may be another more plausible explanation for users’ preferences towards topics, such as animals, movies and food. One likely explanation is the age group of the users. While inspecting our conversational transcripts, we observed that many users interacting with the system appeared to be children or teenagers. It would hardly come as a surprise if this user population would prefer to talk about animals, movies and foods rather than news, politics and travels. # 5.2 A/B Testing Experiment #2 The second A/B testing experiment was carried out between August 6th, 2017 and August 15th, 2017. We tested two dialogue manager policies: Off-policy REINFORCE and Q-learning AMT. As before, we use the greedy variant of Off-policy REINFORCE defined in eq. (5). This experiment occurred at the end of the Amazon Alexa Prize competition semi-finals. This means that many Alexa users have already interacted with other socialbots in the competition, and therefore are likely to have developed expectations towards the systems. These expectations are likely to involve conversing on a particular topic or engaging in non-conversational activities, such as playing games). Further, the period August 6th - August 15th overlaps with the end of the summer holidays and the beginning of the school year in the United States. This means that we should expect less children to interact with the system than in the previous A/B testing experiment. 31 Table 11: Third A/B testing experiment with two different policies (± 95% confidence intervals). Policy User score Dialogue length Pos. utterances Neg. utterances Off-policy REINFORCE Q-learning AMT 3.03 ± 0.18 3.06 ± 0.17 30.93 ± 4.96 33.69 ± 5.84 2.72 ± 0.59 3.63 ± 0.68 7.36 ± 1.22 6.67 ± 0.98 Policy Evaluation The results are given in Table 10. In total, about eight hundred user ratings were collected after discarding returning users. As such, each policy was evaluated by about six hundred unique Alexa users. As before, all ratings were transcribed by human annotators. We observe that both Off-policy REINFORCE and Q-learning AMT perform better than the policies in the previous experiment. However, in this experiment, Off-policy REINFORCE achieved an average Alexa user score of 3.06 while Q-learning AMT achieved a lower score of only 2.92. Nonetheless, Off-policy REINFORCE is not statistically significantly better. In this experiment, there is also no significant difference between the two policies w.r.t. percentage of positive and negative user utterances. As discussed earlier, the performance difference compared to the previous A/B testing experiment could be due to the change in user profiles and user expectations. At this point in time, more of the Alexa users have interacted with socialbots from other teams. Mean while, all socialbots have been evolving. Therefore, user expectations towards our system are likely to be higher now. Further, since the summer holidays have ended, less children and more adults are expected to interact with our system. It is plausible that these adults also have higher expectations towards the system, and even more likely that they are less playful and less tolerant towards mistakes. Given this change in user profiles and expectations, the risk tolerant strategy learned by the Q-learning AMT policy is likely to fare poorly compared to the risk averse strategy learned by Off-policy REINFORCE. # 5.3 A/B Testing Experiment #3 The third A/B testing experiment was carried out between August 15th, 2017 and August 21st, 2017. Due to the surprising results in the previous A/B testing experiment, we decided to continue testing the two dialogue manager policies Off-policy REINFORCE and Q-learning AMT. As before, we use the greedy variant of Off-policy REINFORCE defined in eq. (5). This experiment occurred after the end of the Amazon Alexa Prize competition semi-finals. As discussed before, this means that it is likely that many Alexa users have already developed expectations towards the systems. Further, the period August 15th - August 21st lies entirely within the beginning of the school year in the United States. This means that we should expect less children to interact with the system than in the previous A/B testing experiment. Policy Evaluation The results are given in Table 11. In total, about six hundred user ratings were collected after discarding returning users. As such, each policy was evaluated by about three hundred unique Alexa users. Unlike the previous two experiments, due to the semi-finals having ended, these ratings were not transcribed by human annotators. We observe again that both Off-policy REINFORCE and Q-learning AMT perform better than the other policies evaluated in the first experiment. However, in this experiment, Off-policy REINFORCE only achieved an average Alexa user score of 3.03 while Q-learning AMT achieved the higher score of 3.06. As before, neither policy is statistically significantly better than the other. Nevertheless, as in the first experiment, Q-learning AMT achieved a higher percentage of positive utterances and a lower percentage of negative utterances than Off-policy REINFORCE. In this experiment, Q-learning AMT also obtains the longest dialogues on average. Overall, this experiment indicates that Q-learning AMT is the better policy. As before, the difference in performance compared to the previous A/B testing experiments is likely due to the change in user profiles and user expectations. The fact that Q-learning AMT now performs slightly better than Off-policy REINFORCE might be explained by many different causes. First, despite the confidence intervals and statistical tests presented earlier, it is of course possible that the previous A/B testing experiments did not have enough statistical power to accurately discriminate whether Q-learning AMT or Off-policy REINFORCE obtains the highest average user score. Second, 32 it is possible that the topics users want to discuss now are simply better handled by Q-learning AMT. Third, it is possible that adult users might only have a weak preference toward the risk averse Q- learning AMT policy, and that there is still a significant amount of children and teenagers interacting with the system even though the summer holidays have ended. Finally, it is possible that the user population has grown tired of Off-policy REINFORCE, which follows a risk averse strategy by responding with less semantic content. # 5.4 Discussion The two dialogue manager policies Q-learning AMT and Off-policy REINFORCE have demonstrated substantial improvements over all other policies, including policies learned using supervised learning and heuristic policies. As discussed earlier, the Q-learning AMT policy achieved an average Alexa user score substantially above the average score of all teams in the Amazon Alexa Prize competition semi-finals, without relying on non-conversational activities. In addition, it also achieved a higher number of dialogue turns than both the average of all teams in the semi-finals and the average of all finalist teams in the semi-finals. The policy Off-policy REINFORCE similarly obtained a high number of dialogue, suggesting that the resulting conversations are far more engaging. The results demonstrate the advantages of the overall ensemble approach, where many different models generate natural language responses and the dialogue manager policy selects one response among them. The results also highlight the advantages of learning the policy using reinforcement learning techniques. By optimizing the policy to maximize either real-world user scores or to maximize rewards in the Abstract Discourse MDP (with a proxy reward function) we have demonstrated that significant gains can be achieved w.r.t. both real-world user scores and number of dialogue turns. # 6 Related Work Dialogue Manager Architecture: Any open-domain conversational agent will have to utilize many different types of modules, such as modules for looking up information, modules for daily chitchat discussions, modules for discussing movies, and so on. In this respect, our system architecture is related to some of the recent general-purpose dialogue system frameworks (Zhao et al. 2016, Miller et al. 2017, Truong et al. 2017). These systems abstract away the individual modules into black boxes sharing the same interface, similar to the response models in our ensemble. This, in turn, enables them to be controlled by an executive component (e.g. a dialogue manager). # Reinforcement Learning: Much work has applied reinforcement learning to training or improving dialogue systems. The idea that dialogue can be formulated as a sequential decision making problem based on a Markov decision process (MDP) appeared already in the 1990s for goal-oriented dialogue systems (Singh et al. 1999, 2002, Williams & Young 2007, Young et al. 2013, Paek 2006, Henderson et al. 2008, Pieraccini et al. 2009, Su et al. 2015). One line of research in this area has focused on learning dialogue systems through simulations using abstract dialogue states and actions (Eckert et al. 1997, Levin et al. 2000, Chung 2004, Cuayáhuitl et al. 2005, Georgila et al. 2006, Schatzmann et al. 2007, Heeman 2009, Traum et al. 2008, Georgila & Traum 2011, Lee & Eskenazi 2012, Khouzaimi et al. 2017, López-Cózar 2016, Su et al. 2016, Fatemi et al. 2016, Asri et al. 2016). The approaches here differ based on how the simulator itself is created or estimated, and whether or not the simulator is also considered an agent, which is trying to optimize its own reward. For example, Levin et al. (2000) tackle the problem of building a flight booking dialogue system. They estimate a user simulator model by counting transition probabilities between dialogue states and user actions (similar to an n-gram model), which is then used to train a reinforcement learning policy. In their setting, the states and actions are all abstract discrete variables, which minimizes the amount of natural language understanding and generation the policy has to learn. As another example, Georgila & Traum (2011) tackle the problem of learning dialogue policies for negotiation games, where each party in the dialogue is an agent with its own reward function. In their setting, each policy is in effect also a user simulator, and is trained by playing against other policies using model-free on-policy reinforcement learning. As a more recent example, Yu et al. (2016) build a open-domain, chitchat dialogue system using reinforcement learning. In particular, Yu et al. (2016) propose to learn a dialogue manager policy through model-free off-policy reinforcement learning based on simulations with the template-based system A.L.I.C.E. (Wallace 2009) with a reward 33 function learned from crowdsourced annotations. This is shown to yield substantial improvements w.r.t. both the overall appropriateness of each system response and the conversational depth of the dialogues (e.g. how long the system remains on topic). Researchers have also recently started to investigate learning generative neural network policies operating directing on raw text through user simulations (Li et al. 2016, Das et al. 2017, Lewis et al. 2017, Liu & Lane 2017, Lewis et al. 2017). In contrast to earlier work, these policies require both a deeper understanding of natural language and an ability to generate natural language. For example, Li et al. (2016) propose to train a generative sequence-to-sequence neural network using maximum log-likelihood, and then fine-tune it with a multi-objective function. The multi-objective function includes, among other things, a reinforcement learning signal based on self-play Monte Carlo rollouts (i.e. simulated trajectories are generated by sampling from the model, similar to (Silver et al. 2016)) using a hand-crafted reward function. Lewis et al. (2017) apply model-free reinforcement learning for learning a system capable of negotiation in a toy domain from crowdsourced data. They demonstrate that it’s feasible to learn an effective policy by training a generative sequence-to-sequence neural network on crowdsourced data, and that the policy can be further improved using on-policy reinforcement learning through self-play and Monte Carlo rollouts. Both Li et al. (2016) and Lewis et al. (2017) use self-play. Self-play is a viable option for training their policies because their problems are symmetric in the policy space (e.g. any policy performing well on one side of the negotiation game will also perform well on the other side). In contrast, self-play is unlikely to be an effective training method in our case, because the interactions are highly asymmetric: human users speak differently to our system than they would to humans and, further, they expect different answers. Liu & Lane (2017) use model-free on-policy reinforcement learning to improve a system in a restaurant booking toy domain. For training the system policy, they employ a user simulator trained on real-world human-human dialogues. In particular, under the constraint that both the system and the user share the exact same reward function, they demonstrate that reinforcement learning can be used to improve both the system policy and the user simulator. In a related vein, Zhao & Eskenazi (2016) learn an end-to-end neural network system for playing a quiz game using off-policy reinforcement learning, where the environment is a game simulator. They demonstrate that combining reinforcement learning with dialogue state tracking labels yields superior performance. In all the work reviewed so far, user simulators have been defined as rule-based models (e.g. A.L.I.C.E.), parametric models (e.g. n-gram models, generative neural networks), or a combination of the two. In most cases, given a user simulator, the collected training data is discarded and the policy is learned directly from simulations with the user simulator. In contrast, the Abstract Discourse MDP that we propose is a non-parametric approach, which repeatedly uses the collected training data during policy training. Reinforcement learning has also been applied to teaching agents to communicate with each other in multi-agent environments (Foerster et al. 2016, Sukhbaatar et al. 2016, Lazaridou, Pham & Baroni 2016, Lazaridou, Peysakhovich & Baroni 2016, Mordatch & Abbeel 2017). # 7 Future Work # 7.1 Personalization One important direction for future research is personalization, i.e. building a model of each user’s personality, opinions and interests. This will allow the system to provide a better user experience by adapting the response models to known attributes of the user. We are in the process of implementing a state machine that given a user id, retrieves the relevant information attributes of the user from a database. If a particular user attribute is missing, then the state machine will ask the user for the relevant information and store it in the database. One important user attribute is the user’s name. If no name is found in the database, the state machine may ask the user what they would like to be called and afterwards extracts the name from the user’s response. If a personal name is detected, it is stored in the database to be available for other modules to insert into their responses. Name detection proceeds as follows. First we match the response against a small collection of templates, such as "my name is ..." or "call me ...". Then we use part-of-speech (POS) tags of the resulting matches to detect 34 the end boundary of the name. To avoid clipping the name too early due to wrong POS tags, we also match words against a list of common names in the 1990 US Census data27. In the future, we plan to explore learning user embeddings from previous interactions with each user, since we know from previous experiments that text information alone contains a significant amount of information about the speaker’s identity (Serban & Pineau 2015). Learning an embedding for each user will allow the system to become more personalized, by providing our response models with additional context beyond the immediate dialogue history. # 7.2 Text-based Evaluation : It is well known that speech recognition errors have a significant impact on the user experience in dialogue systems (Raux et al. 2006). Furthermore, speech recognition errors are likely to have a particularly averse effect on our system, because our system encourages open-ended, unrestricted conversations. Unlike many goal-driven and rule-based systems, our system does not take control of the dialogue or direct the user to respond with a keyword from a set of canned responses.28 Because the users are more likely to give open-ended responses, the system is also more likely to suffer from speech recognition errors. As we discussed in Section 4, we did indeed observe a negative correlation between the confidences of the speech recognition system and the Alexa user scores. Moreover, it is likely that speech recognition errors have a stronger systematic effect on some of the policies evaluated in Section 5. To mitigate the issues of speech recognition errors, we plan to evaluate the system with different policies through a text-based evaluation on Amazon Mechanical Turk. This would also help reduce other problems, such as errors due to incorrect turn-taking (e.g. when the system barges in on the user, who is still speaking) (Ward et al. 2005). # 8 Conclusion We have proposed a new large-scale ensemble-based dialogue system framework for the Amazon Alexa Prize competition. Our system leverages a variety of machine learning techniques, including deep learning and reinforcement learning. We have developed a new set of deep learning models for natural language retrieval and generation, including recurrent neural networks, sequence-to-sequence models and latent variable models. In addition, we have developed a novel reinforcement learning procedure and evaluated it against existing reinforcement learning methods in A/B testing experiments with real-world users. These innovations have enabled us to make substantial improvements upon our baseline system. On a scale 1 − 5, our best performing system reached an average user score of 3.15, with a minimal amount of hand-crafted states and rules and without engaging in non-conversational activities (such as playing games or quizzes). The performance is substantially above the average of all teams in the competition semi-finals, which was only 2.92. Furthermore, the same system averaged a high 14.5 − 16.0 turns per conversation, which is substantially above both the average of all teams and the average of finalist teams in the competition semi-finals, suggesting that our system is one of the most engaging systems in the competition. Since nearly all our system components are trainable machine learning models, the system is likely to improve greatly with more interactions and additional data. # Acknowledgments We thank Aaron Courville, Michael Noseworthy, Nicolas Angelard-Gontier, Ryan Lowe, Prasanna Parthasarathi and Peter Henderson for helpful advice related to the system architecture, crowdsourcing and reinforcement learning throughout the Alexa Prize competition. We thank Christian Droulers for building the graphical user interface for text-based chat. We thank Amazon for providing Tesla K80 GPUs through the Amazon Web Services platform. Some of the Titan X GPUs used for this research 27Obtained from: https://deron.meranda.us/data/. 28In contrast, one socialbot system in the Alexa semi-finals would start the conversation by asking the user a question such as "I am able to talk about news, sports and politics. Which would you like to talk about?" after which the user is expected to mention one of the keywords "news", "sports" or "politics". This type of system-initiative greatly reduces the number of speech recognition errors, because it is far easier to discriminate between a few keywords compared to transcribing a complete open-ended utterance. 35 were donated by the NVIDIA Corporation. The authors acknowledge NSERC, Canada Research Chairs, CIFAR, IBM Research, Nuance Foundation, Microsoft Maluuba and Druide Informatique Inc. for funding. # References Ameixa, D., Coheur, L., Fialho, P. & Quaresma, P. (2014), Luke, I am your father: dealing with out-of-domain requests by using movies subtitles, in ‘Intelligent Virtual Agents’, Springer. Asri, L. E., He, J. & Suleman, K. (2016), A sequence-to-sequence model for user simulation in spoken dialogue systems, in ‘InterSpeech’. Aust, H., Oerder, M., Seide, F. & Steinbiss, V. (1995), ‘The Philips automatic train timetable information system’, Speech Communication 17(3). Bird, S., Klein, E. & Loper, E. (2009), Natural Language Processing with Python, O’Reilly Media. Blunsom, P., Grefenstette, E. & Kalchbrenner, N. (2014), A convolutional neural network for mod- elling sentences, in ‘Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics’, Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics. Bohus, D., Raux, A., Harris, T. K., Eskenazi, M. & Rudnicky, A. I. (2007), Olympus: an open-source framework for conversational spoken language interface research, in ‘Proceedings of the workshop on bridging the gap: Academic and industrial research in dialog technologies’, Association for Computational Linguistics, pp. 32–39. Breiman, L. (1996), ‘Bagging predictors’, Machine learning 24(2), 123–140. Charras, F., Duplessis, G. D., Letard, V., Ligozat, A.-L. & Rosset, S. (2016), Comparing system- response retrieval models for open-domain and casual conversational agent, in ‘Workshop on Chatbots and Conversational Agent Technologies’. Cho, K., van Merrienboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H. & Bengio, Y. (2014), Learning phrase representations using rnn encoder–decoder for statistical machine translation, in ‘EMNLP’. Chung, G. (2004), Developing a flexible spoken dialog system using simulation, in ‘Proceedings of the 42nd Annual Meeting on Association for Computational Linguistics’, Association for Computational Linguistics, p. 63. Colby, K. M. (1981), ‘Modeling a paranoid mind’, Behavioral and Brain Sciences 4. Cuayáhuitl, H., Renals, S., Lemon, O. & Shimodaira, H. (2005), Human-computer dialogue simula- tion using hidden markov models, in ‘Automatic Speech Recognition and Understanding, 2005 IEEE Workshop on’, IEEE, pp. 290–295. Das, A., Kottur, S., Moura, J. M., Lee, S. & Batra, D. (2017), Learning cooperative visual dialog agents with deep reinforcement learning, in ‘International Conference on Computer Vision’. Eckert, W., Levin, E. & Pieraccini, R. (1997), User modeling for spoken dialogue system evaluation, in ‘Automatic Speech Recognition and Understanding, 1997. Proceedings., 1997 IEEE Workshop on’, IEEE, pp. 80–87. Fatemi, M., Asri, L. E., Schulz, H., He, J. & Suleman, K. (2016), Policy networks with two-stage training for dialogue systems, in ‘SIGDIAL’. Ferrucci, D., Brown, E., Chu-Carroll, J., Fan, J., Gondek, D., Kalyanpur, A. A., Lally, A., Murdock, J. W., Nyberg, E., Prager, J. et al. (2010), ‘Building Watson: An overview of the DeepQA project’, AI magazine 31(3). Foerster, J., Assael, Y. M., de Freitas, N. & Whiteson, S. (2016), Learning to communicate with deep multi-agent reinforcement learning, in ‘Advances in Neural Information Processing Systems’, pp. 2137–2145. 36 Georgila, K., Henderson, J. & Lemon, O. (2006), User simulation for spoken dialogue systems: Learning and evaluation, in ‘Ninth International Conference on Spoken Language Processing’. Georgila, K. & Traum, D. (2011), Reinforcement learning of argumentation dialogue policies in nego- tiation, in ‘Twelfth Annual Conference of the International Speech Communication Association’. Glorot, X., Bordes, A. & Bengio, Y. (2011), Deep sparse rectifier neural networks, in ‘Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics’, pp. 315–323. Heeman, P. A. (2009), Representing the reinforcement learning state in a negotiation dialogue, in ‘Automatic Speech Recognition & Understanding, 2009. ASRU 2009. IEEE Workshop on’, IEEE, pp. 450–455. Henderson, J., Lemon, O. & Georgila, K. (2008), ‘Hybrid reinforcement/supervised learning of dialogue policies from fixed data sets’, Computational Linguistics 34(4), 487–511. Im, J. (2017). URL: http://search.aifounded.com/ Jurˇcíˇcek, F., Dušek, O., Plátek, O. & Žilka, L. (2014), Alex: A statistical dialogue systems framework, in ‘International Conference on Text, Speech, and Dialogue’, Springer, pp. 587–594. Khouzaimi, H., Laroche, R. & Lefevre, F. (2017), Incremental human-machine dialogue simulation, in ‘Dialogues with Social Robots’, Springer, pp. 53–66. Kingma, D. & Ba, J. (2015), Adam: A method for stochastic optimization, in ‘ICLR’. Kingma, D. P. & Welling, M. (2014), ‘Auto-encoding variational Bayes’, ICLR . Kiros, R., Zhu, Y., Salakhutdinov, R. R., Zemel, R., Urtasun, R., Torralba, A. & Fidler, S. (2015), Skip-thought vectors, in ‘NIPS’. Koren, Y., Bell, R. & Volinsky, C. (2009), ‘Matrix factorization techniques for recommender systems’, Computer 42(8). Lazaridou, A., Peysakhovich, A. & Baroni, M. (2016), ‘Multi-agent cooperation and the emergence of (natural) language’, arXiv preprint arXiv:1612.07182 . Lazaridou, A., Pham, N. T. & Baroni, M. (2016), ‘Towards multi-agent communication-based language learning’, arXiv preprint arXiv:1605.07133 . Lee, S. & Eskenazi, M. (2012), Pomdp-based let’s go system for spoken dialog challenge, in ‘Spoken Language Technology Workshop (SLT), 2012 IEEE’, IEEE, pp. 61–66. Levin, E., Pieraccini, R. & Eckert, W. (2000), ‘A stochastic model of human-machine interaction for learning dialog strategies’, IEEE Transactions on speech and audio processing 8(1), 11–23. Lewis, M., Yarats, D., Dauphin, Y. N., Parikh, D. & Batra, D. (2017), Deal or No Deal? End-to-End Learning for Negotiation Dialogues, in ‘EMNLP’. Li, J., Monroe, W., Ritter, A., Galley, M., Gao, J. & Jurafsky, D. (2016), ‘Deep reinforcement learning for dialogue generation’, arXiv preprint arXiv:1606.01541 . Lin, L.-J. (1993), Reinforcement learning for robots using neural networks, Technical report, Carnegie- Mellon Univ Pittsburgh PA School of Computer Science. Liu, B. & Lane, I. (2017), Iterative policy learning in end-to-end trainable task-oriented neural dialog models, in ‘Proceedings of 2017 IEEE Workshop on Automatic Speech Recognition and Understanding (ASRU)’, Okinawa, Japan. Liu, C.-W., Lowe, R., Serban, I. V., Noseworthy, M., Charlin, L. & Pineau, J. (2016), How NOT to evaluate your dialogue system: An empirical study of unsupervised evaluation metrics for dialogue response generation, in ‘EMNLP’. López-Cózar, R. (2016), ‘Automatic creation of scenarios for evaluating spoken dialogue systems via user-simulation’, Knowledge-Based Systems 106, 51–73. 37 Lowe, R., Noseworthy, M., Serban, I. V., Angelard-Gontier, N., Bengio, Y. & Pineau, J. (2017), Towards an automatic Turing test: Learning to evaluate dialogue responses, in ‘ACL’. Lowe, R., Pow, N., Serban, I. & Pineau, J. (2015), The Ubuntu Dialogue Corpus: A Large Dataset for Research in Unstructured Multi-Turn Dialogue Systems, in ‘SIGDIAL’. Lowe, R., Serban, I. V., Noseworthy, M., Charlin, L. & Pineau, J. (2016), ‘On the evaluation of dialogue systems with next utterance classification’, arXiv preprint arXiv:1605.05414 . Lowe, R. T., Pow, N., Serban, I. V., Charlin, L., Liu, C.-W. & Pineau, J. (2017), ‘Training end-to-end dialogue systems with the ubuntu dialogue corpus’, Dialogue & Discourse 8(1). Marelli, M., Bentivogli, L., Baroni, M., Bernardi, R., Menini, S. & Zamparelli, R. (2014), Semeval- 2014 task 1: Evaluation of compositional distributional semantic models on full sentences through semantic relatedness and textual entailment., in ‘SemEval Workshop, COLING’. McGlashan, S., Fraser, N., Gilbert, N., Bilange, E., Heisterkamp, P. & Youd, N. (1992), Dialogue management for telephone information systems, in ‘ANLC’. Mikolov, T., Sutskever, I., Chen, K., Corrado, G. S. & Dean, J. (2013), Distributed representations of words and phrases and their compositionality, in ‘NIPS’. Miller, A. H., Feng, W., Fisch, A., Lu, J., Batra, D., Bordes, A., Parikh, D. & Weston, J. (2017), ‘Parlai: A dialog research software platform’, arXiv preprint arXiv:1705.06476 . Mnih, V., Kavukcuoglu, K., Silver, D., Graves, A., Antonoglou, I., Wierstra, D. & Riedmiller, M. (2013), ‘Playing atari with deep reinforcement learning’, arXiv preprint arXiv:1312.5602 . Mordatch, I. & Abbeel, P. (2017), ‘Emergence of grounded compositional language in multi-agent populations’, arXiv preprint arXiv:1703.04908 . Nair, V. & Hinton, G. E. (2010), Rectified linear units improve restricted boltzmann machines, in ‘Proceedings of the 27th international conference on machine learning (ICML-10)’, pp. 807–814. Ng, A. Y., Harada, D. & Russell, S. (1999), Policy invariance under reward transformations: Theory and application to reward shaping, in ‘ICML’, Vol. 99, pp. 278–287. Nguyen, T., Rosenberg, M., Song, X., Gao, J., Tiwary, S., Majumder, R. & Deng, L. (2016), ‘MS MARCO: A Human Generated MAchine Reading COmprehension Dataset’, arXiv preprint arXiv:1611.09268 . Paek, T. (2006), Reinforcement learning for spoken dialogue systems: Comparing strengths and weaknesses for practical deployment, in ‘Proc. Dialog-on-Dialog Workshop, Interspeech’. Pennington, J., Socher, R. & Manning, C. D. (2014), Glove: Global vectors for word representation., in ‘EMNLP’, Vol. 14. Pieraccini, R., Suendermann, D., Dayanidhi, K. & Liscombe, J. (2009), Are we there yet? research in commercial spoken dialog systems, in ‘Text, Speech and Dialogue’, Springer, pp. 3–13. Precup, D. (2000), ‘Eligibility traces for off-policy policy evaluation’, Computer Science Department Faculty Publication Series . Precup, D., Sutton, R. S. & Dasgupta, S. (2001), Off-policy temporal-difference learning with function approximation, in ‘ICML’. Raux, A., Bohus, D., Langner, B., Black, A. W. & Eskenazi, M. (2006), Doing research on a deployed spoken dialogue system: one year of let’s go! experience., in ‘INTERSPEECH’. Rezende, D. J., Mohamed, S. & Wierstra, D. (2014), Stochastic backpropagation and approximate inference in deep generative models, in ‘ICML’, pp. 1278–1286. Schatzmann, J., Thomson, B., Weilhammer, K., Ye, H. & Young, S. (2007), Agenda-based user simulation for bootstrapping a pomdp dialogue system, in ‘Human Language Technologies 2007: The Conference of the North American Chapter of the Association for Computational Linguistics; Companion Volume, Short Papers’, Association for Computational Linguistics, pp. 149–152. 38 Serban, I. V., Lowe, R., Charlin, L. & Pineau, J. (2016), Generative deep neural networks for dialogue: A short review, in ‘NIPS, Let’s Discuss: Learning Methods for Dialogue Workshop’. Serban, I. V. & Pineau, J. (2015), Text-based speaker identification for multi-participant open-domain dialogue systems, in ‘Neural Information Processing Systems Workshop on Machine Learning for Spoken Language Understanding’. Serban, I. V., Sordoni, A., Lowe, R., Charlin, L., Pineau, J., Courville, A. & Bengio, Y. (2017), A Hierarchical Latent Variable Encoder-Decoder Model for Generating Dialogues, in ‘AAAI’. Shawar, B. A. & Atwell, E. (2007), Chatbots: are they really useful?, in ‘LDV Forum’, Vol. 22. Silver, D., Huang, A., Maddison, C. J., Guez, A., Sifre, L., Van Den Driessche, G., Schrittwieser, J., Antonoglou, I., Panneershelvam, V., Lanctot, M. et al. (2016), ‘Mastering the game of go with deep neural networks and tree search’, Nature 529(7587), 484–489. Simpson, A. & Eraser, N. M. (1993), Black box and glass box evaluation of the sundial system, in ‘Third European Conference on Speech Communication and Technology’. Singh, S., Litman, D., Kearns, M. & Walker, M. (2002), ‘Optimizing dialogue management with reinforcement learning: Experiments with the njfun system’, Journal of Artificial Intelligence Research 16, 105–133. Singh, S. P., Kearns, M. J., Litman, D. J. & Walker, M. A. (1999), Reinforcement learning for spoken dialogue systems., in ‘Nips’, pp. 956–962. Socher, R., Perelygin, A., Wu, J. Y., Chuang, J., Manning, C. D., Ng, A. Y., Potts, C. et al. (2013), Recursive deep models for semantic compositionality over a sentiment treebank, in ‘Proceedings of the conference on empirical methods in natural language processing (EMNLP)’, Vol. 1631, p. 1642. Stolcke, A., Ries, K., Coccaro, N., Shriberg, E., Bates, R., Jurafsky, D., Taylor, P., Martin, R., Van Ess-Dykema, C. & Meteer, M. (2000), ‘Dialogue act modeling for automatic tagging and recognition of conversational speech’, Computational linguistics 26(3). Stone, B. & Soper, S. (2014), ‘Amazon Unveils a Listening, Talking, Music-Playing Speaker for Your Home’, Bloomberg L.P . Retrieved 2014-11-07. Su, P.-H., Gasic, M., Mrksic, N., Rojas-Barahona, L., Ultes, S., Vandyke, D., Wen, T.-H. & Young, S. (2016), ‘Continuously learning neural dialogue management’, arXiv preprint arXiv:1606.02689 . Su, P.-H., Vandyke, D., Gaši´c, M., Kim, D., Mrkši´c, N., Wen, T.-H. & Young, S. (2015), Learning from real users: Rating dialogue success with neural networks for reinforcement learning in spoken dialogue systems., in ‘Interspeech’. Suendermann-Oeft, D., Ramanarayanan, V., Teckenbrock, M., Neutatz, F. & Schmidt, D. (2015), Halef: An open-source standard-compliant telephony-based modular spoken dialog system: A review and an outlook, in ‘Natural language dialog systems and intelligent assistants’, Springer. Sukhbaatar, S., Fergus, R. et al. (2016), Learning multiagent communication with backpropagation, in ‘Advances in Neural Information Processing Systems’, pp. 2244–2252. Sutton, R. S. & Barto, A. G. (1998), Reinforcement learning: An introduction, number 1 in ‘1’, MIT Press Cambridge. Traum, D., Marsella, S. C., Gratch, J., Lee, J. & Hartholt, A. (2008), Multi-party, multi-issue, multi-strategy negotiation for multi-modal virtual agents, in ‘International Workshop on Intelligent Virtual Agents’, Springer, pp. 117–130. Truong, H. P., Parthasarathi, P. & Pineau, J. (2017), ‘Maca: A modular architecture for conversational agents’, arXiv preprint arXiv:1705.00673 . Wallace, R. S. (2009), ‘The anatomy of alice’, Parsing the Turing Test . 39 Ward, N. G., Rivera, A. G., Ward, K. & Novick, D. G. (2005), ‘Root causes of lost time and user stress in a simple dialog system’. Weizenbaum, J. (1966), ‘Eliza—a computer program for the study of natural language communication between man and machine’, ACM 9(1). Williams, J. D. (2011), An empirical evaluation of a statistical dialog system in public use, in ‘Proceedings of the SIGDIAL 2011 Conference’, Association for Computational Linguistics, pp. 130–141. Williams, J. D., Raux, A. & Henderson, M. (2016), ‘Introduction to the special issue on dialogue state tracking’, Dialogue & Discourse 7(3), 1–3. Williams, J. D. & Young, S. (2007), ‘Partially observable markov decision processes for spoken dialog systems’, Computer Speech & Language 21(2), 393–422. Williams, J., Raux, A., Ramachandran, D. & Black, A. (2013), The dialog state tracking challenge, in ‘SIGDIAL’, pp. 404–413. Williams, R. J. (1992), ‘Simple statistical gradient-following algorithms for connectionist reinforce- ment learning’, Machine learning 8(3-4). Wu, Y., Schuster, M., Chen, Z., Le, Q. V., Norouzi, M., Macherey, W., Krikun, M., Cao, Y., Gao, Q., Macherey, K. et al. (2016), ‘Google’s neural machine translation system: Bridging the gap between human and machine translation’, arXiv preprint arXiv:1609.08144 . Young, S., Gasic, M., Thomson, B. & Williams, J. D. (2013), ‘Pomdp-based statistical spoken dialog systems: A review’, Proceedings of the IEEE 101(5), 1160–1179. Yu, L., Hermann, K. M., Blunsom, P. & Pulman, S. (2014), Deep learning for answer sentence selection, in ‘NIPS, Workshop on Deep Learning’. Yu, Z., Xu, Z., Black, A. W. & Rudnicky, A. I. (2016), Strategy and policy learning for non-task- oriented conversational systems., in ‘SIGDIAL’. Zhao, T. & Eskenazi, M. (2016), Towards end-to-end learning for dialog state tracking and manage- ment using deep reinforcement learning, in ‘SIGDIAL’. Zhao, T., Lee, K. & Eskenazi, M. (2016), Dialport: Connecting the spoken dialog research community to real user data, in ‘Spoken Language Technology Workshop (SLT), 2016 IEEE’, IEEE, pp. 83–90. Zhu, Y., Kiros, R., Zemel, R., Salakhutdinov, R., Urtasun, R., Torralba, A. & Fidler, S. (2015), Aligning books and movies: Towards story-like visual explanations by watching movies and reading books, in ‘ICCV’. 40
Title: Aligning Books and Movies: Towards Story-like Visual Explanations by Watching Movies and Reading Books: Summary: Books are a rich source of both fine-grained information, how a character, an object or a scene looks like, as well as high-level semantics, what someone is thinking, feeling and how these states evolve through a story. This paper aims to align books to their movie releases in order to provide rich descriptive explanations for visual content that go semantically far beyond the captions available in current datasets. To align movies and books we exploit a neural sentence embedding that is trained in an unsupervised way from a large corpus of books, as well as a video-text neural embedding for computing similarities between movie clips and sentences in the book. We propose a context-aware CNN to combine information from multiple sources. We demonstrate good quantitative performance for movie/book alignment and show several qualitative examples that showcase the diversity of tasks our model can be used for. # Aligning Books and Movies: Towards Story-like Visual Explanations by Watching Movies and Reading Books Yukun Zhu ∗,1 Ryan Kiros*,1 Richard Zemel1 Ruslan Salakhutdinov1 Raquel Urtasun1 Antonio Torralba2 Sanja Fidler1 1University of Toronto 2Massachusetts Institute of Technology {yukun,rkiros,zemel,rsalakhu,urtasun,fidler}@cs.toronto.edu, torralba@csail.mit.edu # Abstract Books are a rich source of both fine-grained information, how a character, an object or a scene looks like, as well as high-level semantics, what someone is thinking, feeling and how these states evolve through a story. This paper aims to align books to their movie releases in order to provide rich descriptive explanations for visual content that go semanti- cally far beyond the captions available in current datasets. To align movies and books we exploit a neural sentence embedding that is trained in an unsupervised way from a large corpus of books, as well as a video-text neural em- bedding for computing similarities between movie clips and sentences in the book. We propose a context-aware CNN to combine information from multiple sources. We demon- strate good quantitative performance for movie/book align- ment and show several qualitative examples that showcase the diversity of tasks our model can be used for. # 1. Introduction Figure 1: Shot from the movie Gone Girl, along with the subtitle, aligned with the book. We reason about the visual and dialog (text) alignment between the movie and a book. Books provide us with very rich, descriptive text that conveys both fine-grained visual details (how people or scenes look like) as well as high-level semantics (what peo- ple think and feel, and how their states evolve through a story). This source of knowledge, however, does not come with associated visual information that would enable us to ground it with descriptions. Grounding descriptions in books to vision would allow us to get textual explanations or stories behind visual information rather than simplistic captions available in current datasets. It can also provide us with extremely large amount of data (with tens of thousands books available online). A truly intelligent machine needs to not only parse the surrounding 3D environment, but also understand why peo- ple take certain actions, what they will do next, what they could possibly be thinking, and even try to empathize with them. In this quest, language will play a crucial role in grounding visual information to high-level semantic con- cepts. Only a few words in a sentence may convey really rich semantic information. Language also represents a natu- ral means of interaction between a naive user and our vision algorithms, which is particularly important for applications such as social robotics or assistive driving. Combining images or videos with language has gotten significant attention in the past year, partly due to the cre- ation of CoCo [18], Microsoft’s large-scale captioned im- age dataset. The field has tackled a diverse set of tasks such as captioning [13, 11, 36, 35, 21], alignment [11, 15, 34], Q&A [20, 19], visual model learning from textual descrip- tions [8, 26], and semantic visual search with natural multi- sentence queries [17]. In this paper, we exploit the fact that many books have been turned into movies. Books and their movie releases have a lot of common knowledge as well as they are com- plementary in many ways. For instance, books provide de- tailed descriptions about the intentions and mental states of the characters, while movies are better at capturing visual aspects of the settings. The first challenge we need to address, and the focus of this paper, is to align books with their movie releases in order to obtain rich descriptions for the visual content. We aim to align the two sources with two types of in- formation: visual, where the goal is to link a movie shot to a book paragraph, and dialog, where we want to find correspondences between sentences in the movie’s subtitle and sentences in the book. We formulate the problem of movie/book alignment as finding correspondences between shots in the movie as well as dialog sentences in the sub- titles and sentences in the book (Fig. 1). We introduce a novel sentence similarity measure based on a neural sen- # ∗Denotes equal contribution 1 tence embedding trained on millions of sentences from a large corpus of books. On the visual side, we extend the neural image-sentence embeddings to the video domain and train the model on DVS descriptions of movie clips. Our approach combines different similarity measures and takes into account contextual information contained in the nearby shots and book sentences. Our final alignment model is for- mulated as an energy minimization problem that encourages the alignment to follow a similar timeline. To evaluate the book-movie alignment model we collected a dataset with 11 movie/book pairs annotated with 2,070 shot-to-sentence correspondences. We demonstrate good quantitative perfor- mance and show several qualitative examples that showcase the diversity of tasks our model can be used for. The alignment model can have multiple applications. Imagine an app which allows the user to browse the book as the scenes unroll in the movie: perhaps its ending or act- ing are ambiguous, and one would like to query the book for answers. Vice-versa, while reading the book one might want to switch from text to video, particularly for the juicy scenes. We also show other applications of learning from movies and books such as book retrieval (finding the book that goes with a movie and finding other similar books), and captioning CoCo images with story-like descriptions. # 2. Related Work Most effort in the domain of vision and language has been devoted to the problem of image captioning. Older work made use of fixed visual representations and translated them into textual descriptions [6, 16]. Recently, several approaches based on RNNs emerged, generating captions via a learned joint image-text embedding [13, 11, 36, 21]. These approaches have also been extended to generate de- scriptions of short video clips [35]. In [24], the authors go beyond describing what is happening in an image and pro- vide explanations about why something is happening. For text-to-image alignment, [15, 7] find correspon- dences between nouns and pronouns in a caption and visual objects using several visual and textual potentials. Lin et al. [17] does so for videos. In [11], the authors use RNN embeddings to find the correspondences. [37] combines neural embeddings with soft attention in order to align the words to image regions. Early work on movie-to-text alignment include dynamic time warping for aligning movies to scripts with the help of subtitles [5, 4]. Sankar et al. [28] further developed a system which identified sets of visual and audio features to align movies and scripts without making use of the subtitles. Such alignment has been exploited to provide weak labels for person naming tasks [5, 30, 25]. Closest to our work is [34], which aligns plot synopses to shots in the TV series for story-based content retrieval. This work adopts a similarity function between sentences in plot synopses and shots based on person identities and keywords in subtitles. Our work differs with theirs in several impor- tant aspects. First, we tackle a more challenging problem of movie/book alignment. Unlike plot synopsis, which closely follow the storyline of movies, books are more verbose and might vary in the storyline from their movie release. Fur- thermore, we use learned neural embeddings to compute the similarities rather than hand-designed similarity functions. Parallel to our work, [33] aims to align scenes in movies to chapters in the book. However, their approach operates on a very coarse level (chapters), while ours does so on the sentence/paragraph level. Their dataset thus evaluates on 90 scene-chapter correspondences, while our dataset draws 2,070 shot-to-sentences alignments. Furthermore, the ap- proaches are inherently different. [33] matches the pres- ence of characters in a scene to those in a chapter, as well as uses hand-crafted similarity measures between sentences in the subtitles and dialogs in the books, similarly to [34]. Rohrbach et al. [27] recently released the Movie De- scription dataset which contains clips from movies, each time-stamped with a sentence from DVS (Descriptive Video Service). The dataset contains clips from over a 100 movies, and provides a great resource for the captioning techniques. Our effort here is to align movies with books in order to ob- tain longer, richer and more high-level video descriptions. We start by describing our new dataset, and then explain our proposed approach. # 3. The MovieBook and BookCorpus Datasets We collected two large datasets, one for movie/book alignment and one with a large number of books. The MovieBook Dataset. Since no prior work or data ex- ist on the problem of movie/book alignment, we collected a new dataset with 11 movies along with the books on which they were based on. For each movie we also have a sub- title file, which we parse into a set of time-stamped sen- tences. Note that no speaker information is provided in the subtitles. We automatically parse each book into sentences, paragraphs (based on indentation in the book), and chapters (we assume a chapter title has indentation, starts on a new page, and does not end with an end symbol). Our annotators had the movie and a book opened side by side. They were asked to iterate between browsing the book and watching a few shots/scenes of the movie, and trying to find correspondences between them. In particular, they marked the exact time (in seconds) of correspondence in the movie and the matching line number in the book file, indicating the beginning of the matched sentence. On the video side, we assume that the match spans across a shot (a video unit with smooth camera motion). If the match was longer in duration, the annotator also indicated the ending time of the match. Similarly for the book, if more sentences Title Gone Girl Fight Club No Country for Old Men Harry Potter and the Sorcerers Stone Shawshank Redemption The Green Mile American Psycho One Flew Over the Cuckoo Nest The Firm Brokeback Mountain The Road # sent. 12,603 4,229 8,050 6,458 2,562 9,467 11,992 7,103 15,498 638 6,638 # words 148,340 48,946 69,824 78,596 40,140 133,241 143,631 112,978 135,529 10,640 58,793 # unique words 3,849 1,833 1,704 2,363 1,360 3,043 4,632 2,949 3,685 470 1,580 BOOK avg. # words per sent. 15 14 10 15 18 17 16 19 11 20 10 max # words per sent. 153 90 68 227 115 119 422 192 85 173 74 # para- graphs 3,927 2,082 3,189 2,925 637 2,760 3,945 2,236 5,223 167 2,345 # shots 2,604 2,365 1,348 2,647 1,252 2,350 1,012 1,671 2,423 1,205 1,108 MOVIE # sent. in subtitles 2,555 1,864 889 1,227 1,879 1,846 1,311 1,553 1,775 1,228 782 ANNOTATION # dialog align. 76 104 223 164 44 208 278 64 82 80 126 # visual align. 106 42 47 73 12 102 85 25 60 20 49 85,238 980,658 9,032 156 29,436 19,985 16,909 1,449 621 15 All Table 1: Statistics for our MovieBook Dataset with ground-truth for alignment between books and their movie releases. # of books 11,038 # of sentences 74,004,228 # of words 984,846,357 # of unique words mean # of words per sentence median # of words per sentence 1,316,420 13 11 Table 2: Summary statistics of our BookCorpus dataset. We use this corpus to train the sentence embedding model. matched, the annotator indicated from which to which line a match occurred. Each alignment was also tagged, indicating whether it was a visual, dialogue, or an audio match. Note that even for dialogs, the movie and book versions are se- mantically similar but not exactly the same. Thus deciding on what defines a match or not is also somewhat subjective and may slightly vary across our annotators. Altogether, the annotators spent 90 hours labeling 11 movie/book pairs, locating 2,070 correspondences. lished authors. We only included books that had more than 20K words in order to filter out perhaps noisier shorter sto- ries. The dataset has books in 16 different genres, e.g., Romance (2,865 books), Fantasy (1,479), Science fiction (786), Teen (430), etc. Table 2 highlights the summary statistics of our book corpus. # 4. Aligning Books and Movies Table 1 presents our dataset, while Fig. 8 shows a few ground-truth alignments. One can see the complexity and diversity of the data: the number of sentences per book vary from 638 to 15,498, even though the movies are similar in duration. This indicates a huge diversity in descriptiveness across literature, and presents a challenge for matching. The sentences also vary in length, with the sentences in Broke- back Mountain being twice as long as those in The Road. The longest sentence in American Psycho has 422 words and spans over a page in the book. Aligning movies with books is challenging even for hu- mans, mostly due to the scale of the data. Each movie is on average 2h long and has 1,800 shots, while a book has on average 7,750 sentences. Books also have different styles of writing, formatting, different and challenging language, slang (going vs goin’, or even was vs ’us), etc. As one can see from Table 1, finding visual matches turned out to be particularly challenging. This is because the visual descrip- tions in books can be either very short and hidden within longer paragraphs or even within a longer sentence, or very verbose – in which case they get obscured with the sur- rounding text – and are hard to spot. Of course, how close the movie follows the book is also up to the director, which can be seen through the number of alignments that our an- notators found across different movie/books. Our approach aims to align a movie with a book by ex- ploiting visual information as well as dialogs. We take shots as video units and sentences from subtitles to represent di- alogs. Our goal is to match these to the sentences in the book. We propose several measures to compute similari- ties between pairs of sentences as well as shots and sen- tences. We use our novel deep neural embedding trained on our large corpus of books to predict similarities between sentences. Note that an extended version of the sentence embedding is described in detail in [14] showing how to deal with million-word vocabularies, and demonstrating its performance on a large variety of NLP benchmarks. For comparing shots with sentences we extend the neural em- bedding of images and text [13] to operate in the video do- main. We next develop a novel contextual alignment model that combines information from various similarity measures and a larger time-scale in order to make better local align- ment predictions. Finally, we propose a simple pairwise Conditional Random Field (CRF) that smooths the align- ments by encouraging them to follow a linear timeline, both in the video and book domain. We first explain our sentence, followed by our joint video to text embedding. We next propose our contextual model that combines similarities and discuss CRF in more detail. # 4.1. Skip-Thought Vectors The BookCorpus Dataset. In order to train our sentence similarity model we collected a corpus of 11,038 books from the web. These are free books written by yet unpub- In order to score the similarity between two sentences, we exploit our architecture for learning unsupervised rep- resentations of text [14]. The model is loosely inspired by oe >@—® >@ >@ >@—® a door confronted her <eos> ren a door confronted “ her she stopped and tried to pull it i budge _<eos> open <eos> it didnt budge Figure 2: Sentence neural embedding [14]. Given a tuple (s;_1, 5;, 5:41) of consecutive sentences in text, where s; is the i-th sentence, we encode s; and aim to reconstruct the previous s;_; and the following sentence s;41. Unattached arrows are connected to the encoder output. Colors depict which components share parameters. (eos) is the end of sentence token. he drove down the street off into the distance . the most effective way to end the battle . he started the car , left the parking lot and merged onto the highway a few miles down the road . he shut the door and watched the taxi drive off . she watched the lights flicker through the trees as the men drove toward the road . he jogged down the stairs , through the small lobby , through the door and into the street . a messy business to be sure , but necessary to achieve a fine and noble end . they saw their only goal as survival and logically planned a strategy to achieve it . there would be far fewer casualties and far less destruction . the outcome was the lisbon treaty . Table 3: Qualitative results from the sentence embedding model. For each query sentence on the left, we retrieve the 4 nearest neighbor sentences (by inner product) chosen from books the model has not seen before. the skip-gram [22] architecture for learning representations of words. In the word skip-gram model, a word wi is cho- sen and must predict its surrounding context (e.g. wi+1 and wi−1 for a context window of size 1). Our model works in a similar way but at the sentence level. That is, given a sen- tence tuple (si−1, si, si+1) our model first encodes the sen- tence si into a fixed vector, then conditioned on this vector tries to reconstruct the sentences si−1 and si+1, as shown in Fig. 2. The motivation for this architecture is inspired by the distributional hypothesis: sentences that have similar surrounding context are likely to be both semantically and syntactically similar. Thus, two sentences that have similar syntax and semantics are likely to be encoded to a similar vector. Once the model is trained, we can map any sentence through the encoder to obtain vector representations, then score their similarity through an inner product. The learning signal of the model depends on having con- tiguous text, where sentences follow one another in se- quence. A natural corpus for training our model is thus a large collection of books. Given the size and diversity of genres, our BookCorpus allows us to learn very general representations of text. For instance, Table 3 illustrates the nearest neighbours of query sentences, taken from held out books that the model was not trained on. These qualitative results demonstrate that our intuition is correct, with result- ing nearest neighbors corresponds largely to syntactically and semantically similar sentences. Note that the sentence embedding is general and can be applied to other domains not considered in this paper, which is explored in [14]. vanishing gradient problem, through the use of gates to con- trol the flow of information. The LSTM unit explicity em- ploys a cell that acts as a carousel with an identity weight. The flow of information through a cell is controlled by in- put, output and forget gates which control what goes into a cell, what leaves a cell and whether to reset the contents of the cell. The GRU does not use a cell but employs two gates: an update and a reset gate. In a GRU, the hidden state is a linear combination of the previous hidden state and the proposed hidden state, where the combination weights are controlled by the update gate. GRUs have been shown to perform just as well as LSTM on several sequence predic- tion tasks [3] while being simpler. Thus, we use GRU as the activation function for our encoder and decoder RNNs. are (si−1, si, si+1), and let wt and let xt description into three parts: objective function. Encoder. Let w1 i denote words in sentence si with N the number of words in the sentence. The encoder pro- duces a hidden state ht i at each time step which forms the representation of the sequence w1 i , . . . , wt i. Thus, the hid- den state hN is the representation of the whole sentence. i The GRU produces the next hidden state as a linear combi- nation of the previous hidden state and the proposed state update (we drop subscript i): h'=(1-z')oh 142’ on! (1) To construct an encoder, we use a recurrent neural net- work, inspired by the success of encoder-decoder models for neural machine translation [10, 2, 1, 31]. Two kinds of activation functions have recently gained traction: long short-term memory (LSTM) [9] and the gated recurrent unit (GRU) [3]. Both types of activation successfully solve the where h‘ is the proposed state update at time t, z’ is the up- date gate and (©) denotes a component-wise product. The update gate takes values between zero and one. In the ex- treme cases, if the update gate is the vector of ones, the previous hidden state is completely forgotten and h’ = h‘. Alternatively, if the update gate is the zero vector, than the hidden state from the previous time step is simply copied over, that is ht = ht−1. The update gate is computed as zt = σ(Wzxt + Uzht−1) (2) where Wz and Uz are the update gate parameters. The proposed state update is given by h! = tanh(Wx' + U(r! © h’~’)) (6)) where rt is the reset gate, which is computed as rt = σ(Wrxt + Urht−1) (4) If the reset gate is the zero vector, than the proposed state update is computed only as a function of the current word. Thus after iterating this equation sequence for each word, we obtain a sentence vector hN Decoder. The decoder computation is analogous to the en- coder, except that the computation is conditioned on the sentence vector hi. Two separate decoders are used, one for the previous sentence si−1 and one for the next sentence si+1. These decoders use different parameters to compute their hidden states but both share the same vocabulary ma- trix V that takes a hidden state and computes a distribution over words. Thus, the decoders are analogous to an RNN language model but conditioned on the encoder sequence. Alternatively, in the context of image caption generation, the encoded sentence hi plays a similar role as the image. We describe the decoder for the next sentence si+1 (com- putation for si−1 is identical). Let ht i+1 denote the hidden state of the decoder at time t. The update and reset gates for the decoder are given as follows (we drop i + 1): zht−1 + Czhi) rht−1 + Crhi) zt = σ(Wd rt = σ(Wd z xt−1 + Ud r xt−1 + Ud i+1 is then computed as: the hidden state ht h’ = tanh(W?%x'~! + U4(r! © h'“+) + Ch,) (7) hi, =(1—2') oh! +2! oh! (8) ‘i Given hj,,, the probability of word w/,, given the previ- ous t — 1 words and the encoder vector is P(wi, whi) x exp(Vng, Wha) Q) where vwt word of wt the previous sentence si−1. Objective. Given (si−1, si, si+1), the objective optimized is the sum of log-probabilities for the next and previous sen- tences conditioned on the representation of the encoder: logP (wt i+1|w<t i+1, hi) + logP (wt i−1|w<t i−1, hi) t t (10) The total objective is the above summed over all such train- ing tuples. Adam algorithm [12] is used for optimization. # 4.2. Visual-semantic embeddings of clips and DVS The model above describes how to obtain a similarity score between two sentences, whose representations are learned from millions of sentences in books. We now dis- cuss how to obtain similarities between shots and sentences. Our approach closely follows the image-sentence rank- ing model proposed by [13]. In their model, an LSTM is used for encoding a sentence into a fixed vector. A linear mapping is applied to image features from a convolutional network. A score is computed based on the inner product between the normalized sentence and image vectors. Cor- rect image-sentence pairs are trained to have high score, while incorrect pairs are assigned low scores. In our case, we learn a visual-semantic embedding be- tween movie clips and their DVS description. DVS (“De- scriptive Video Service”) is a service that inserts audio de- scriptions of the movie between the dialogs in order to en- able the visually impaired to follow the movie like anyone else. We used the movie description dataset of [27] for learning our embedding. This dataset has 94 movies, and 54,000 described clips. We represent each movie clip as a vector corresponding to mean-pooled features across each frame in the clip. We used the GoogLeNet architecture [32] as well as hybrid-CNN [38] for extracting frame features. For DVS, we pre-processed the descriptions by removing names and replacing these with a someone token. The LSTM architecture in this work is implemented us- ing the following equations. As before, we represent a word embedding at time t of a sentence as xt: i = o(Waix! + Warm t+ Wee) UD ff = o(Wayx' + Wapm’ | + Were’) (12) a’ = tanh(Weex! + W),.m‘~') (13) ec = foc t+i' oat (14) of = o(Woox' + Wrom'! + Weoe') (15) m’ = o' @tanh(c’) (16) where (o) denotes the sigmoid activation function and (©) indicates component-wise multiplication. The states (i', f¢, c’, o', m*) correspond to the input, forget, cell, out- put and memory vectors, respectively. If the sentence is of length N, then the vector m™ = m is the vector represen- tation of the sentence. Let q denote a movie clip vector, and let v = WI q be the embedding of the movie clip. We define a scoring function s(m, v) = m · v, where m and v are first scaled to have unit norm (making s equivalent to cosine similarity). We then optimize the following pairwise ranking loss: min > So max{0,a —s(m,v) +s(m,vz)} (17) mk +52 S° max{0,0 = s(v,m) + 5(v,ma)}, with mk a contrastive (non-descriptive) sentence vector for a clip embedding v, and vice-versa with vk. We train our model with stochastic gradient descent without momentum. # 4.3. Context aware similarity We employ the clip-sentence embedding to compute similarities between each shot in the movie and each sen- tence in the book. For dialogs, we use several similarity measures each capturing a different level of semantic sim- ilarity. We compute BLEU [23] between each subtitle and book sentence to identify nearly identical matches. Simi- larly to [34], we use a tf-idf measure to find near duplicates but weighing down the influence of the less frequent words. Finally, we use our sentence embedding learned from books to score pairs of sentences that are semantically similar but may have a very different wording (i.e., paraphrasing). These similarity measures indicate the alignment be- tween the two modalities. However, at the local, sentence level, alignment can be rather ambiguous. For example, de- spite being a rather dark book, Gone Girl contains 15 occur- rences of the sentence “I love you”. We exploit the fact that a match is not completely isolated but that the sentences (or shots) around it are also to some extent similar. We design a context aware similarity measure that takes into account all individual similarity measures as well as a fixed context window in both, the movie and book do- main, and predicts a new similarity score. We stack a set of M similarity measures into a tensor S(i, j, m), where i, j, and m are the indices of sentences in the subtitle, in the book, and individual similarity measures, respectively. In particular, we use M = 9 similarities: visual and sentence embedding, BLEU1-5, tf-idf, and a uniform prior. We want to predict a combined score score(i, j) = f (S(I, J, M)) at each location (i, j) based on all measurements in a fixed volume defined by I around i, J around j, and 1, . . . , M . Evaluating the function f (·) at each location (i, j) on a 3-D tensor S is very similar to applying a convolution using a kernel of appropriate size. This motivates us to formulate the function f (·) as a deep convolutional neural network (CNN). In this paper, we adopt a 3-layer CNN as illustrated in Figure 3. We adopt the ReLU non-linearity with dropout to regularize our model. We optimize the cross-entropy loss over the training set using Adam algorithm. # 4.4. Global Movie/Book Alignment So far, each shot/sentence was matched independently. However, most shots in movies and passages in the books follow a similar timeline. We would like to incorporate this prior into our alignment. In [34], the authors use dynamic time warping by enforcing that the shots in the movie can only match forward in time (to plot synopses in their case). However, the storyline of the movie and book can have crossings in time (Fig. 8), and the alignment might contain mW Figure 3: Our CNN for context-aware similarity computa- tion. It has 3 conv. layers and a sigmoid layer on top. giant leaps forwards or backwards. Therefore, we formu- late a movie/book alignment problem as inference in a Con- ditional Random Field that encourages nearby shots/dialog alignments to be consistent. Each node yi in our CRF rep- resents an alignment of the shot in the movie with its cor- responding subtitle sentence to a sentence in the book. Its state space is thus the set of all sentences in the book. The CRF energy of a configuration y is formulated as: = Sondu yi) Ss > wp (Yi. ¥;) i=1 JEN (i) — log p(x,y;w where K is the number of nodes (shots), and N (i) the left and right neighbor of yi. Here, φu(·) and ψp(·) are unary and pairwise potentials, respectively, and ω = (ωu, ωp). We directly use the output of the CNN from 4.3 as the unary potential φu(·). For the pairwise potential, we measure the time span ds(yi, yj) between two neighbouring sentences in the subtitle and the distance db(yi, yj) of their state space in the book. One pairwise potential is defined as: ψp(yi, yj) = (ds(yi, yj) − db(yi, yj))2 (ds(yi, yj) − db(yi, yj))2 + σ2 (18) Here σ2 is a robustness parameter to avoid punishing gi- ant leaps too harsh. Both ds and db are normalized to [0, 1]. In addition, we also employ another pairwise poten- tial ψq(yi, yj) = (db(yi,yj ))2 (db(yi,yj ))2+σ2 to encourage state consis- tency between nearby nodes. This potential is helpful when there is a long silence (no dialog) in the movie. Inference. Our CRF is a chain, thus exact inference is possible using dynamic programming. We also prune some states that are very far from the uniform alignment (over 1/3 length of the book) to further speed up computation. Learning. Since ground-truth is only available for a sparse set of shots, we regard the states of unobserved nodes as hidden variables and learn the CRF weights with [29]. # 5. Experimental Evaluation We evaluate our model on our dataset of 11 movie/book pairs. We train the parameters in our model (CNN and CRF) on Gone Girl, and test our performance on the remaining 10 movies. In terms of training speed, our video-text model “watches” 1,440 movies per day and our sentence model reads 870 books per day. We also show various qualitative results demonstrating the power of our approach. We pro- vide more results in the Appendix of the paper. # 5.1. Movie/Book Alignment Evaluating the performance of movie/book alignment is an interesting problem on its own. This is because our ground-truth is far from exhaustive – around 200 correspon- dences were typically found between a movie and its book, and likely a number of them got missed. Thus, evaluating the precision is rather tricky. We thus focus our evaluation on recall, similar to existing work on retrieval. For each shot that has a GT correspondence in book, we check whether our prediction is close to the annotated one. We evaluate recall at the paragraph level, i.e., we say that the GT para- graph was recalled, if our match was at most 3 paragraphs away, and the shot was at most 5 subtitle sentences away. As a noisier measure, we also compute recall and precision at multiple alignment thresholds and report AP (avg. prec.). The results are presented in Table 4. Columns show dif- ferent instantiations of our model: we show the leave-one- feature-out setting (∅ indicates that all features were used), compare how different depths of the context-aware CNN in- fluence the performance, and compare it to our full model (CRF) in the last column. We get the highest boost by adding more layers to the CNN – recall improves by 14%, and AP doubles. Generally, each feature helps performance. Our sentence embedding (BOOK) helps by 4%, while nois- ier video-text embedding helps by 2% in recall. CRF which encourages temporal smoothness generally helps (but not for all movies), bringing additional 2%. We also show how a uniform timeline performs on its own. That is, for each shot (measured in seconds) in the movie, we find the sen- tence at the same location (measured in lines) in the book. We add another baseline to evaluate the role of context in our model. Instead of using our CNN that considers con- textual information, we build a linear SVM to combine dif- ferent similarity measures in a single node (shot) – the final similarity is used as a unary potential in our CRF alignment model. The Table shows that our CNN contextual model outperforms the SVM baseline by 30% in recall, and dou- bles the AP. We plot alignment for a few movies in Fig. 8. Running Times. We show the typical running time of each component in our model in Table 5. For each movie- book pair, calculating BLEU score takes most of the time. Note that BLEU does not contribute significantly to the per- formance and is of optional use. With respect to the rest, extracting visual features VIS (mean pooling GoogleNet features over the shot frames) and SCENE features (mean pooling hybrid-CNN features [38] over the shot frames), MOVIE BOOKS b u l C t h g i F . . . y r t n u o C o N . . . w e l F e n O d a o R e h T m r i F e h T . y s P n a c i r e m A . . . k n a h s w a h S Fight Club e l i M n e e r G 100.0 . . . w e l F e n O 45.4 . y s P n a c i r e m A 45.2 . . . k n a h s w a h S 45.1 . . . y r t n u o C o N 43.6 m r i F e h T 43.0 d a o R e h T 42.7 Green Mile r e t t o P y r r a H 100.0 . . . k c a b e k o r B 42.5 . y s P n a c i r e m A 40.1 d a o R e h T 39.6 . . . w e l F e n O 38.9 . . . k n a h s w a h S 38.0 m r i F e h T 36.7 Harry Potter o . y s P n a c i r e m A 100.0 m r i F e h T 40.5 . . . w e l F e n O 39.7 b u l C t h g i F 39.5 . . . k n a h s w a h S 39.1 . . . y r t n u o C o N 39.0 . . . k c a b e k o r B 38.7 American Psy. . . . w e l F e n O 100.0 m r i F e h T 55.5 r e t t o P y r r a H 54.9 d a o R e h T 53.5 . . . k n a h s w a h S 53.1 . . . k c a b e k o r B 52.6 . . . y r t n u o C o N 51.3 One Flew... . . . k n a h s w a h S 100.0 m r i F e h T 84.0 . . . y r t n u o C o N 80.8 . . . w e l F e n O 79.1 d a o R e h T 79.0 . . . k c a b e k o r B 77.8 e l i M n e e r G 76.9 Shawshank ... m r i F e h T 100.0 . . . k n a h s w a h S 66.0 b u l C t h g i F 62.0 . . . k c a b e k o r B 61.4 . . . w e l F e n O 60.9 . y s P n a c i r e m A 59.1 r e t t o P y r r a H 58.0 The Firm . . . k c a b e k o r B 100.0 . . . w e l F e n O 75.0 b u l C t h g i F 73.9 . y s P n a c i r e m A 73.7 e l i M n e e r G 71.5 m r i F e h T 71.4 . . . k n a h s w a h S 68.5 Brokeback ... d a o R e h T 100.0 m r i F e h T 54.8 . . . w e l F e n O 52.2 . . . y r t n u o C o N 51.9 b u l C t h g i F 50.9 . . . k n a h s w a h S 50.7 e l i M n e e r G 50.6 The Road . . . y r t n u o C o N 100.0 d a o R e h T 56.0 . . . k c a b e k o r B 55.9 . . . w e l F e n O 54.8 m r i F e h T 54.1 . . . k n a h s w a h S 53.9 r e t t o P y r r a H 53.4 No Country... 100.0 49.7 49.5 46.8 46.4 45.8 45.8 ae apie jgiepaey ING STEPHEN, | Table 6: Book “retrieval”. For a movie (left), we rank books wrt to their alignment similarity with the movie. We normalize similarity to be 100 for the highest scoring book. takes most of the time (about 80% of the total time). We also report training times for our contextual model (CNN) and the CRF alignment model. Note that the times are reported for one movie/book pair since we used only one such pair to train all our CNN and CRF parameters. We chose Gone Girl for training since it had the best balance between the dialog and visual correspondences. # 5.2. Describing Movies via the Book We next show qualitative results of our alignment. In particular, we run our model on each movie/book pair, and visualize the passage in the book that a particular shot in the movie aligns to. We show best matching paragraphs as well as a paragraph before and after. The results are shown in Fig. 8. One can see that our model is able to retrieve a semantically meaningful match despite large dialog devia- tions from those in the book, and the challenge of matching a visual representation to the verbose text in the book. [00:43:16:00:43:19] Okay, | wanna see the hands. Come on. "Certainly, Mr. Cheswick. A vote is now before the group. Will a show of hands be adequate, Mr. McMurphy, or are you going to insist on a secret ballot?""| want to see the hands. | want to see the hands that don't go up, too." “Everyone in favor of changing the television time to the afternoon, raise his hand." ((f7 [02:14:29:02:14:32] Good afternoon, Harry. ... He realized he must be in the hospital wing, He was lying in a bed with white linen sheets, and next to him was a table piled high with what looked like half the candy shop. "Tokens from your friends and admirers," said Dumbledore, beaming. "What happened down in the dungeons between you and Professor Quirrell is a complete secret, so, naturally, the whole school knows. | believe your friends Misters Fred and George Weasley were responsible for trying to send you a toilet seat. No doubt they thought it would amuse you. Madam Pomfrey, however, felt it might not be very hygienic, and confiscated it." [00:43:16:00:43:19] Okay, | wanna see the hands. Come on. [01:00:02:01:00:04] Are you saying my life is in danger? [01:13:05:01:13:06] Right, Caleb? group. Will a show of hands be adequate, Mr. McMurphy, or are you going to insist on a secret ballot?""| want to see the hands. | want to see the hands that don't go up, too." “Everyone in favor of changing the television time to the afternoon, raise his hand." Mitch braced himself and waited. "Mitch, no lawyer has ever left your law firm alive. Three have tried, and they were killed. Two were about to leave, and they died last summer. Once a lawyer joins Bendini, Lambert & Locke, he never leaves, unless he retires and keeps his mouth shut. And by the time they retire, they are a part of the conspiracy and cannot talk. The Firm has an extensive surveillance operation on the fifth floor. Your house and car are bugged. Your phones are tapped. Your desk and office are wired, Virtually every word you utter is heard and recorded on the fifth ' ‘ou, and sometimes your wife. They are here in Washington as we speak. You see, Mitch, The Firm is more than a firm, It is a division of a very large business, a very profitable business, A very illegal business. The Firm is not owned by the partners.” Mitch turned and watched him closely. The Director looked at the frozen pond as he spoke. A huge, circular scar ran out of his hair, down his forehead, through one dead and indifferently cocked eye, and to the comer of his mouth, which had been disfigured into the knowing leer of a gambler or perhaps a whoremaster. One cheek was smooth and pretty; the other was bunched up like the stump of a tree. | guessed there had been a hole in it, but that, at least, had healed. "He has the one eye," Hammersmith said, caressing the boy's bunched cheek with a lover's kind fingers. "I suppose he's lucky not to be blind. We get down on our knees and thank God for that much, at least, Eh, Caleb?" "Yes, sir," the boy said shyly - the boy who would be beaten mercilessly on the play-yard by laughing, jeering bullies for all his miserable years of education, the boy who would never be asked to play Spin the Bottle or Post Office and would probably never sleep with a woman not bought and paid for once he was grown to manhood's times and needs, the boy who would always stand outside the warm and lighted circle of his peers, the boy who would look at himself in his mirror for the next fifty or sixty or seventy years of his life and think ugly, ugly, ugly. ((f7 [02:14:29:02:14:32] Good afternoon, Harry. 1h Jee prim. aliienlt Patan » (02:15:24:02:15:26] <i>You remember the name of the town, don't you?</i> [01:26:19:01:26:22] You're not the one that has to worry about everything, was lying in a bed with white linen sheets, and next to him was a table piled high with what looked like half the candy shop. "Tokens from your friends and admirers," said Dumbledore, beaming. "What happened down in the dungeons between you and Professor Quirrell is a complete secret, so, naturally, the whole school knows. | believe your friends Misters Fred and George Weasley were responsible for trying to send you a toilet seat. No doubt they thought it would amuse you. Madam Pomfrey, however, felt it might not be very hygienic, and confiscated it." | took the envelope and left the rock where Andy had left it, and Andy's friend before him. Dear Red, If you're reading this, then you're out, One way or another, you're out. And f you've followed along this far, you might be willing to come a little further. | think you remember the name of the town, don't you? | could use a good man to help me get my project on wheels. Meantime, have a drink on me-and do think it over. | will be keeping an eye out for you. Remember that hope is a good thing, Red maybe the best of things, and no good thing ever dies. | will be hoping that this letter finds you, and finds you well. Your friend, Peter Stevens| didn't read that letter in the field The man squatted and looked at him. I'm scared, he said. Do you understand? I'm scared, The boy didn't answer. He just sat there with his head bowed, sobbing. You're not the one who has to worry about everything. [01:00:02:01:00:04] Are you saying my life is in danger? Mitch braced himself and waited. "Mitch, no lawyer has ever left your law firm alive. Three have tried, and they were killed. Two were about to leave, and they died last summer. Once a lawyer joins Bendini, Lambert & Locke, he never leaves, unless he retires and keeps his mouth shut. And by the time they retire, they are a part of the conspiracy and cannot talk. The Firm has an extensive surveillance operation on the fifth floor. Your house and car are bugged. Your phones are tapped. Your desk and office are wired, Virtually every word you utter is heard and recorded on the fifth ' ‘ou, and sometimes your wife. They are here in Washington as we speak. You see, Mitch, The Firm is more than a firm, It is a division of a very large business, a very profitable business, A very illegal business. The Firm is not owned by the partners.” Mitch turned and watched him closely. The Director looked at the frozen pond as he spoke. 1h Jee prim. aliienlt Patan » (02:15:24:02:15:26] <i>You remember the name of the town, don't you?</i> | took the envelope and left the rock where Andy had left it, and Andy's friend before him. Dear Red, If you're reading this, then you're out, One way or another, you're out. And f you've followed along this far, you might be willing to come a little further. | think you remember the name of the town, don't you? | could use a good man to help me get my project on wheels. Meantime, have a drink on me-and do think it over. | will be keeping an eye out for you. Remember that hope is a good thing, Red maybe the best of things, and no good thing ever dies. | will be hoping that this letter finds you, and finds you well. Your friend, Peter Stevens| didn't read that letter in the field [01:13:05:01:13:06] Right, Caleb? A huge, circular scar ran out of his hair, down his forehead, through one dead and indifferently cocked eye, and to the comer of his mouth, which had been disfigured into the knowing leer of a gambler or perhaps a whoremaster. One cheek was smooth and pretty; the other was bunched up like the stump of a tree. | guessed there had been a hole in it, but that, at least, had healed. "He has the one eye," Hammersmith said, caressing the boy's bunched cheek with a lover's kind fingers. "I suppose he's lucky not to be blind. We get down on our knees and thank God for that much, at least, Eh, Caleb?" "Yes, sir," the boy said shyly - the boy who would be beaten mercilessly on the play-yard by laughing, jeering bullies for all his miserable years of education, the boy who would never be asked to play Spin the Bottle or Post Office and would probably never sleep with a woman not bought and paid for once he was grown to manhood's times and needs, the boy who would always stand outside the warm and lighted circle of his peers, the boy who would look at himself in his mirror for the next fifty or sixty or seventy years of his life and think ugly, ugly, ugly. [01:26:19:01:26:22] You're not the one that has to worry about everything, The man squatted and looked at him. I'm scared, he said. Do you understand? I'm scared, The boy didn't answer. He just sat there with his head bowed, sobbing. You're not the one who has to worry about everything. Figure 4: Describing movie clips via the book: we align the movie to the book, and show a shot from the movie and its corresponding paragraph (plus one before and after) from the book. American.Psycho r ¥ , Y [00:13:29:00:13:33] Lady, if you don't shut your fucking mouth, | will kill you. Batman.Begins «\ 2. (02:06:23:02:06:26] - I'm sorry | didn't tell you, Rachel. - No. No, Bruce... (00:30:16:00:30:19] Prolemuris. They're aggressive. Fight.Club | have your license. | know who you are. | know where you live. I'm keeping your license, and I'm going to check on you, mister Raymond K. Hessel. In three months, and then in six months, and then in a year, and if you aren't back in school on your way to being a veterinarian, you will be dead. You didn't say anything. Harry.Potter.and.the.Sorcerers.Stone (00:05:46:00;:05:48] I'm warning you now, boy Bane Chronicles-2 "She has graciously allowed me into her confidence." Magnus could read between the lines. Axel didn't kiss and tell, which made him only more attractive. “The escape is to be made on Sunday," Alex went on. "The plan is simple, but exacting. We have arranged it so the guards have seen certain people leaving by certain exits at certain times. On ... Adventures of Tom Bombadil Of crystal was his habergeon, his scabbard of chalcedony; with silver tipped at plenilune his spear was hewn of ebony. His javelins were of malachite and stalactite - he brandished them, and went and fought the dragon-flies of Paradise, and vanquished them. He battled with the Dumbledors, the Hummerhorns, and Honeybees, and won the Golden Honeycomb; and running home on sunny seas in ship of leaves and gossamer with blossom for a canopy, he sat... ay! it Batman.Begins ™~ ~ A) (01:38:41:01:38:44] I'm gonna give you a sedative. You'll wake up back at home. Batman.Begins [01:09:31:01:09:34] I'm going to have to Fight.Club You didn't say anything. Get out of here, and do your little life, but remember I'm watching you, Raymond Hessel, and I'd rather kill you than see you working a shit job for just enough money to buy cheese and watch television. Now, I'm going to walk away so don't turn around. A Captive s Submission “| believe you will enjoy your time here. | am not a harsh master but | am strict. When we are with others, | expect you to present yourself properly. What we do here in your room and in the dungeon is between you and |. It is a testament to the trust and respect we have for each other and no one else needs to Know about our arrangement. I'm sure the past few days have been overwhelming thus far but I have tried to give you as much information as possible. Do you have any questions?" A Dirty Job "This says 'Purveyor of Fine Vintage Clothing and Accessories." "Right! Exactly!" He knew he should have had a second set of business cards printed up. "And where do you think | get those things? From the dead. You see?" “Mr. Asher, I'm going to have to ask you to leave." American.Psycho r ¥ , Y [00:13:29:00:13:33] Lady, if you don't shut your fucking mouth, | will kill you. Fight.Club | have your license. | know who you are. | know where you live. I'm keeping your license, and I'm going to check on you, mister Raymond K. Hessel. In three months, and then in six months, and then in a year, and if you aren't back in school on your way to being a veterinarian, you will be dead. You didn't say anything. Harry.Potter.and.the.Sorcerers.Stone (00:05:46:00;:05:48] I'm warning you now, boy Fight.Club You didn't say anything. Get out of here, and do your little life, but remember I'm watching you, Raymond Hessel, and I'd rather kill you than see you working a shit job for just enough money to buy cheese and watch television. Now, I'm going to walk away so don't turn around. Batman.Begins «\ 2. (02:06:23:02:06:26] - I'm sorry | didn't tell you, Rachel. - No. No, Bruce... Bane Chronicles-2 "She has graciously allowed me into her confidence." Magnus could read between the lines. Axel didn't kiss and tell, which made him only more attractive. “The escape is to be made on Sunday," Alex went on. "The plan is simple, but exacting. We have arranged it so the guards have seen certain people leaving by certain exits at certain times. On ... ay! it Batman.Begins ™~ ~ A) (01:38:41:01:38:44] I'm gonna give you a sedative. You'll wake up back at home. A Captive s Submission “| believe you will enjoy your time here. | am not a harsh master but | am strict. When we are with others, | expect you to present yourself properly. What we do here in your room and in the dungeon is between you and |. It is a testament to the trust and respect we have for each other and no one else needs to Know about our arrangement. I'm sure the past few days have been overwhelming thus far but I have tried to give you as much information as possible. Do you have any questions?" (00:30:16:00:30:19] Prolemuris. They're not aggressive. Adventures of Tom Bombadil Of crystal was his habergeon, his scabbard of chalcedony; with silver tipped at plenilune his spear was hewn of ebony. His javelins were of malachite and stalactite - he brandished them, and went and fought the dragon-flies of Paradise, and vanquished them. He battled with the Dumbledors, the Hummerhorns, and Honeybees, and won the Golden Honeycomb; and running home on sunny seas in ship of leaves and gossamer with blossom for a canopy, he sat... Batman.Begins [01:09:31:01:09:34] I'm going to have to ask you to leave. A Dirty Job "This says 'Purveyor of Fine Vintage Clothing and Accessories." "Right! Exactly!" He knew he should have had a second set of business cards printed up. "And where do you think | get those things? From the dead. You see?" “Mr. Asher, I'm going to have to ask you to leave." Figure 5: We can use our model to caption movies via a corpus of books. Top: A shot from American Pyscho is captioned with paragraphs from the Fight Club, and a shot from Harry Potter with paragraphs from Fight Club. Middle and Bottom: We match shots from Avatar and Batman Begins against 300 books from our BookCorpus, and show the best matched paragraph. Fight Club The Green Mile Harry Potter and the Sorcerers Stone American Psycho One Flew Over the Cuckoo Nest Shawshank Redemption The Firm Brokeback Mountain The Road AP Recall AP Recall AP Recall AP Recall AP Recall AP Recall AP Recall AP Recall AP Recall AP Recall UNI 1.22 2.36 0.00 0.00 0.00 0.00 0.00 0.27 0.00 1.01 0.00 1.79 0.05 1.38 2.36 27.0 0.00 1.12 0.00 1.12 SVM 0.73 10.38 14.05 51.42 10.30 44.35 14.78 34.25 5.68 25.25 8.94 46.43 4.46 18.62 24.91 74.00 13.77 41.90 12.11 33.46 ∅ 0.45 12.26 14.12 62.46 8.09 51.05 16.76 67.12 8.14 41.41 8.60 78.57 7.91 33.79 16.55 88.00 6.58 43.02 9.00 48.90 BLEU 0.41 12.74 14.09 60.57 8.18 52.30 17.22 66.58 6.27 34.34 8.89 76.79 8.66 36.55 17.82 92.00 7.83 48.04 9.39 49.63 1 layer CNN w/o one feature BOOK 0.50 11.79 10.12 57.10 7.84 48.54 14.88 64.66 8.49 36.36 7.99 73.21 6.22 23.45 15.16 86.00 5.11 38.55 9.40 47.79 TF-IDF 0.40 11.79 6.92 53.94 5.66 46.03 12.29 60.82 1.93 32.32 4.35 73.21 2.02 26.90 14.60 86.00 3.04 32.96 8.22 46.69 VIS 0.64 12.74 9.83 55.52 7.95 48.54 14.95 63.56 8.51 37.37 8.91 78.57 7.15 26.90 15.58 88.00 5.47 37.99 9.35 51.10 SCENE 0.50 11.79 13.00 60.57 8.04 49.37 15.68 66.58 9.32 36.36 9.22 75.00 7.25 30.34 15.41 86.00 6.09 42.46 8.63 49.26 PRIOR 0.48 11.79 14.42 62.78 8.20 52.72 16.54 67.67 9.04 40.40 7.86 78.57 7.26 31.03 16.21 87.00 7.00 44.13 9.40 48.53 CNN-3 1.95 17.92 28.80 74.13 27.17 76.57 34.32 81.92 14.83 49.49 19.33 94.64 18.34 37.93 31.80 98.00 19.80 65.36 28.75 71.69 CRF 5.17 19.81 27.60 78.23 23.65 78.66 32.87 80.27 21.13 54.55 19.96 96.79 20.74 44.83 30.58 100.00 19.58 65.10 30.45 72.79 No Country for Old Men Mean Recall AP 3.88 0.40 38.01 10.97 52.66 9.62 52.95 9.88 47.07 5.94 48.75 8.57 50.03 8.83 50.77 9.31 52.46 9.64 69.10 23.17 66.77 22.51 Table 4: Performance of our model for the movies in our dataset under different settings and metrics. Per movie-book pair BLEU 6h TF 10 min BOOK 3 min VIS 2h SCENE 1h CNN (training) 3 min CNN (inference) 0.2 min CRF (training) 5h CRF (inference) 5 min Table 5: Running time for our model per one movie/book pair. # 5.3. Book “Retrieval” # 6. Conclusion In this experiment, we compute alignment between a movie and all (test) 10 books, and check whether our model retrieves the correct book. Results are shown in Table 6. Under each book we show the computed similarity. In par- ticular, we use the energy from the CRF, and scale all sim- ilarities relative to the highest one (100). Notice that our model retrieves the correct book for each movie. Describing a movie via other books. We can also cap- tion movies by matching shots to paragraphs in a corpus of books. Here we do not encourage a linear timeline (CRF) since the stories are unrelated, and we only match at the lo- cal, shot-paragraph level. We show a description for Amer- ican Psycho borrowed from the book Fight Club in Fig. 5. In this paper, we explored a new problem of aligning a book to its movie release. We proposed an approach that computes several similarities between shots and di- alogs and the sentences in the book. We exploited our new sentence embedding in order to compute similarities be- tween sentences. We further extended the image-text neural embeddings to video, and proposed a context-aware align- ment model that takes into account all the available simi- larity information. We showed results on a new dataset of movie/book alignments as well as several quantitative re- sults that showcase the power and potential of our approach. # Acknowledgments # 5.4. The CoCoBook: Writing Stories for CoCo Our next experiment shows that our model is able to “generate” descriptive stories for (static) images. In par- ticular we used the image-text embedding from [13] and generated a simple caption for an image. We used this cap- tion as a query, and used our sentence embedding trained on books to find top 10 nearest sentences (sampled from a few hundred thousand from BookCorpus). We re-ranked these based on the 1-gram precision of non-stop words. Given the best result, we return the sentence as well as the 2 sentences before and after it in the book. The results are in Fig. 6. Our sentence embedding is able to retrieve semantically mean- ingful stories to explain the images. We acknowledge the support from NSERC, CIFAR, Samsung, Google, and ONR-N00014-14-1-0232. We also thank Lea Jen- sterle for helping us with elaborate annotation, and Relu Patrascu for his help with numerous infrastructure related problems. # Appendix In the Appendix we provide more qualitative results. # A. Qualitative Movie-Book Alignment Results We show a few qualitative examples of alignment in Fig. 8. In this experiment, we show results obtained with our full model (CRF). For a chosen shot (a node in the CRF) we show the corresponding paragraph in the book. the club was a little emptier than i would have expected for the late afternoon , and the bartender , in red waistcoat and bowtie , was busy wiping down his counter , replacing peanuts and putting out new coasters . a television with the latest la liga news was hung in an upper corner , and behind him , rows of bottles were reflected in a giant bar mirror . above the stools , a pergola-type overhead structure held rows of wine glasses . it was a classy place , with ferns in the corner , and not the kind of bar to which i was accustomed . my places usually had a more ... relaxed feel . he felt like an idiot for yelling at the child , but his frustration and trepidation was getting the better of him . he glanced toward the shadowed hall and quickly nodded toward melissa before making his way forward . he came across more children sitting upon a couch in the living room . they watched him , but did n’t move and did n’t speak . his skin started to feel like hundreds of tiny spiders were running up and down it and he hurried on . a few miles before tioga road reached highway 395 and the town of lee vining , smith turned onto a narrow blacktop road . on either side were parched , grassy open slopes with barbed-wire fences marking property lines . cattle and horses grazed under trees whose black silhouettes stood stark against the gold-velvet mountains . marty burst into song : “ home , home on the range , where the deer and the antelope play ! where seldom is heard a discouraging word and the skies are not cloudy all day ! ” “number seventy-three , second to last from the corner . ’ adam slowed the porsche as he approached the quaint-he could think of no other word to use , even though “quaint” was one he normally , manfully , avoided-townhouse , coming to a halt beside a sleek jaguar sedan . it was a quiet street , devoid of traffic at this hour on a monday night . in the bluish-tinted light of a corner street lamp , he developed a quick visual impression of wrought-iron railings on tidy front stoops , window boxes full of bright chrysanthemums , beveled glass in bay windows , and lace curtains . townhouses around here didn’t rent cheaply , he could n’t help but observe . Figure 6: CoCoBook: We generate a caption for a CoCo image via [13] and retrieve its best matched sentence (+ 2 before and after) from a large book corpus. One can see a semantic relevance of the retrieved passage to the image. Figure 7: Alignment results of our model (bottom) compared to ground-truth alignment (top). In ground-truth, blue lines indicate visual matches, and magenta are the dialog matches. Yellow lines indicate predicted alignments. We can see that some dialogs in the movies closely fol- low the book and thus help with the alignment. This is particularly important since the visual information is not as strong. Since the text around the dialogs typically describe the scene, the dialogs thus help us ground the visual infor- mation contained in the description and the video. # B. Borrowing “Lines” from Other Books We show a few qualitative examples of top-scoring matches for shot in a movie with a paragraph in another book (a book that does not correspond to this movie). In this experiment, we allow a clip in our 10 movie dataset (excluding the training movie) to match to paragraphs in the remaining 9 books (excluding the corresponding book). The results are in Fig. 12. Note that the top-scoring matches chosen from only a small set of books may not be too meaningful. 200 book experiment. We scale the experiment by ran- domly selecting 200 books from our BookCorpus. The re- sults are in Fig. 15. One can see that by using many more books results in increasingly better “stories”. American Psycho American Psycho # American Psycho Harry Potter Figure 8: Examples of movie-book alignment. We use our model to align a movie to a book. Then for a chosen shot (which is a node in our CRF) we show the corresponding paragraph, plus one before and one after, in the book inferred by our model. On the left we show one (central) frame from the shot along with the subtitle sentence(s) that overlap with the shot. Some dialogs in the movie closely follow the book and thus help with the alignment. One Flew Over the Cuckoo’s Nest One Flew Over the Cuckoo’s Nest Shawshank Redemption Figure 9: Examples of movie-book alignment. We use our model to align a movie to a book. Then for a chosen shot (which is a node in our CRF) we show the corresponding paragraph, plus one before and one after, in the book inferred by our model. On the left we show one (central) frame from the shot along with the subtitle sentence(s) that overlap with the shot. Some dialogs in the movie closely follow the book and thus help with the alignment. The Firm The Firm The Firm Figure 10: Examples of movie-book alignment. We use our model to align a movie to a book. Then for a chosen shot (which is a node in our CRF) we show the corresponding paragraph, plus one before and one after, in the book inferred by our model. On the left we show one (central) frame from the shot along with the subtitle sentence(s) that overlap with the shot. Some dialogs in the movie closely follow the book and thus help with the alignment. The Green Mile The Green Mile The Road Figure 11: Examples of movie-book alignment. We use our model to align a movie to a book. Then for a chosen shot (which is a node in our CRF) we show the corresponding paragraph, plus one before and one after, in the book inferred by our model. On the left we show one (central) frame from the shot along with the subtitle sentence(s) that overlap with the shot. Some dialogs in the movie closely follow the book and thus help with the alignment. | have your license. | know who you are. | know where you live. I'm keeping your license, and I'm going to check on you, mister Raymond K. Hessel. In three months, and then in six months, and then in a year, and if you aren't back in school on your way to being a veterinarian, you will be dead. You didn't say anything. [00:13:24:00:13:27] Two: | can only get these sheets in Santa Fe. Your head rolled up and away from the gun, and you said, yeah. You said, yes, you lived in a basement. You had some pictures in the wallet, too. There was your mother. This was a tough one for you, you'd have to open your eyes and see the picture of Mom and Dad smiling and see the gun at the same time, but you did, and then your eyes closed and you started to cry. You were going to cool, the amazing miracle of death. One minute, you're a person, the next minute, you're an ... [00:21:25:00:21:27] It's okay. | can tell. I've never been in here before tonight. “If you say so, sir," the bartender says, “but Thursday night, you came in to ask how soon the police were planning to shut us down." Last Thursday night, | was awake all night with the insomnia, wondering was | awake, was | sleeping. | woke up late Friday morning, bone tired and feeling | hadn't ever had my eyes closed. "Yes, sir," the bartender says, "Thursday night, you were standing right where you are now and you were asking me about the police crackdown, and you were asking me how many guys we had to turn away from the Wednesday night fight club." [00:23:44:00:23:47] You're late, honey. Oh, yes, you are. | am not late. Figure 12: Examples of of borrowing paragraphs from other books – 10 book experiment. We show a few examples of top-scoring correspondences between a shot in a movie and a paragraph in a book that does not correspond to the movie. Note that by forcing the model to choose from another book, the top-scoring correspondences may still have a relatively low similarity. In this experiment, we did not enforce a global alignment over the full book – we use the similarity output by our contextual CNN. “My friends, thou protest too much to believe the protesting. You are all believing deep inside your stingy little hearts that our Miss Angel of Mercy Ratched is absolutely correct in every assumption she made today about McMurphy. You know she was, and so do I. But why deny it? Let's be honest and give this man his due instead of secretly criticizing his capitalistic talent. What's wrong with him making a little profit? We've all certainly got our money's worth every time he fleeced us, haven't we? He's a shrewd character with an eye out for a quick dollar. He doesn't make any pretense about his motives, does he? Why should we? He has a healthy and honest attitude about his chicanery, and I'm all for him, just as I'm for the dear old capitalistic system of free individual enterprise, comrades, for him and his downright bullheaded gall and the American flag, bless it, and the Lincoln Memorial and the whole bit. Remember the Maine, P. T. Barnum and the Fourth of July. | feel compelled to defend my friend's honor as a good old red, white, and blue hundred-per-cent American con man. Good guy, my [00:35:25:00:35:27] Do you have any witnesses or foot. McMurphy would ... fingerprints ? You didn't say anything. Get out of here, and do your little life, but remember I'm watching you, Raymond Hessel, and I'd rather kill you than see you working a shit job for just enough money to buy cheese and watch television. Now, I'm going to walk away so don't turn around. [00:05:46:00:05:48] I'm warning you now, boy. ». course. She wasn't quite dead. | have often thought it would have been better - for me, if not for her - if she had been killed instantly. It might have made it possible for me to let her go a little sooner, a little more naturally. Or perhaps I'm only kidding myself about that. All | know for sure is that | have never let her go, not really. She was trembling all over. One of her shoes had come off and | could see her foot jittering. Her ... [00:16:22:00:16:26] "We have a witch in the family. Isn't it wonderful?" Figure 13: Examples of of borrowing paragraphs from other books – 10 book experiment. We show a few examples of top-scoring correspondences between a shot in a movie and a paragraph in a book that does not correspond to the movie. Note that by forcing the model to choose from another book, the top-scoring correspondences may still have a relatively low similarity. In this experiment, we did not enforce a global alignment over the full book – we use the similarity output by our contextual CNN. . ya see, the thing is..." He scratched his beard. "See, | done heard yer little twitter feet up on my ceilin' there, so | come up to do some investigatin'. Yep, that's what | reckon, far as | recall." Tick exchanged a baffled look with Sofia and Paul. It didn't take a genius to realize they'd already caught Sally in his first lie. "Well," Tick said, "we need a minute to talk about what we're gonna do." [00:55:19:00:55:23] No, no. | may need to talk to you a little futher, so how about you just let me know if you're gonna leave town. . last night, or were the Tears still affecting me more than | realized? | didn't think about it again. | just turned and walked to the bathroom. A quick shower and we'd be on our way to the airport. Twenty minutes later | was ready, my hair still soaking wet. | was dressed in a pair of navy blue dress slacks, an emerald green silk blouse, and a navy suit jacket that matched the pants. Jeremy had also chosen a pair of black low-heeled pumps and included a pair of black thigh-highs. Since | didn't own any other kind of hose, that | didn't mind. But the rest of it... "Next time you pick out clothes for me to run for my life in, include some jogging shoes. Pumps, no matter how low-heeled, just aren't made for it." [01:25:28:01:25:30] - Two pair of black pants? - Yes, sir. You, he wanted to say, I'm thinking of you. I'm thinking of your stink and how bad you smell and how | can't stop smelling you. I'm thinking of how you keep staring at me and how | never say anything about it and | don't know why. I'm thinking of you staring at me and why someone's screaming at me inside my head and how someone's screaming inside my head and why it seems odd that I'm not worried about that. [01:55:38:01:55:41] I'm thinking | don't know what | would do if you were gone. Figure 14: Examples of of borrowing paragraphs from other books – 200 book experiment. We show a few examples of top-scoring correspondences between a shot in a movie and a paragraph in a book that does not correspond to the movie. By scaling up the experiment (more books to choose from), our model gets increasingly more relevant “stories”. "A good bodyguard doesn't relax on the job," Ethan said. “You know we aren't a threat to Ms. Reed, Ethan. | don't know who you're supposed to be protecting her from, but it isn't us." “They may clean up for the press, but | know what they are, Meredith," Ethan said. A [01:52:05:01:52:09] - How do you know? - Someone's going to try and steal it. | could use, he reflected, anything that'd help, anything at all. Any hint, like from that girl, any suggestion. He felt dismal and afraid. Shit, he thought, what am | going to do? If I'm off everything, he thought, then I'll never see any of them again, any of my friends, the people | watched and knew. I'll be out of it; I'll be maybe retired the rest of my life-anyhow, I've seen the last of Arctor and Luckman and Jerry Fabin and Charles Freck and most of all Donna Hawthorne. I'll never see any of my friends again, for the rest of eternity. It's over. [00:37:32:00:37:35] ...and I'll never do it again, that's for sure. He came to his knees and put his hands on my arms, and stared down into my face. "I will love you always. When this red hair is white, | will still love you. When the smooth softness of youth is replaced by the delicate softness of age, | will still want to touch your skin. When your face is full of the line of every smile you have ever smiled, of every surprise | have seen flash through your eyes, when every tear you have ever cried has left its mark upon your face, | will treasure you all the more, because | was there to see it all. | will share your life with you, Meredith, and |... [00:55:54:00:55:58] Now, once you've got hold of your broom, | want you to mount it. Figure 15: Examples of of borrowing paragraphs from other books – 200 book experiment. We show a few examples of top-scoring correspondences between a shot in a movie and a paragraph in a book that does not correspond to the movie. By scaling up the experiment (more books to choose from), our model gets increasingly more relevant “stories”. Bottom row: failed example. # C. The CoCoBook We show more results for captioning CoCo images [18] with passages from the books. if never “ somewhere you ’ll never find it , ” owens sneered . meant five seconds , his claim was true . the little shit ’s gaze cut left , where a laptop sat on a coffee table . trey strode to it . owens ’ email program was open . seriously . wreck . just something like that . i try to convince her . everyone was allowed to rest for the next twenty-four hours . that following evening : the elect , not their entourages , were called to a dining hall for supper with lady dolorous . a table that curved inward was laden with food and drink . the wall behind the table was windows with a view of the planet . girls in pink stood about and at attention . he had simply ... healed . brian watched his fellow passengers come aboard . a young woman with blonde hair was walking with a little girl in dark glasses . the little girl ’s hand was on the blonde ’s elbow . the woman murmured to her charge , the girl looked immediately toward the sound of her voice , and brian understood she was blind - it was something in the gesture of the head . this was a beautiful miniature reproduction of a real london town house , and when jessamine touched it , tessa saw that the front of it swung open on tiny hinges . tessa caught her breath . there were beautiful tiny rooms perfectly decorated with miniature furniture , everything built to scale , from the little wooden chairs with needlepoint cushions to the cast-iron stove in the kitchen . there were small dolls , too , with china heads , and real little oil paintings on the walls . “ this was my house . ” if he had been nearby he would have dragged her out of the room by her hair and strangled her . during lunch break she went with a group back to the encampment . out of view of the house , under a stand of towering trees , several tents were sitting in a field of mud . the rain the night before had washed the world , but here it had made a mess of things . a few women fired up a camp stove and put on rice and lentils . Ta? ALL ALM then a frightened yell . “ hang on ! ” suddenly , jake was flying through the air . nefertiti became airborne , too . he screamed , not knowing what was happening-then he splashed into a pool of water . grabbing his wristwatch off the bedside table he checked the time , grimacing when he saw that it was just after two in the afternoon . jeanne louise should n’t be up yet . stifling a yawn , he slid out of bed and made his way to the en suite bathroom for a shower twenty minutes later paul was showered , dressed , and had . brushed his teeth and hair . feeling somewhat alive now , he made his way out of his and jeanne louise ’s room , pausing to look in on livy as he passed . she cried . quentin put a heavy , warm , calming hand on her thigh , saying , “ he should be sober by then . ” a cell phone rang . he pulled his from his back pocket , glanced at it , then used the remote to turn the tv to the channel that showed the feed from the camera at the security gate . “ oh , it ’s rachel . ” now however she was out of his shot . he had missed it completely until he had ended up on the ground with his shotgun . an old clock hung on the wall near the door . the was obviously broken , the small red hand ticking the same second away over and over again . morgan squeezed the trigger and pellets ripped out of their package , bounced down the barrel , flew through the air and ripped into the old clock tearing it in two before it smashed to the ground . a man sat in a chair , facing the wall opposite of me . it nearly startled me when i first saw him , and made a bit of a squeak , but he did nothing . he had dark gray hair , a black suit and pants , and a gray and blue striped tie . s-sir ? i said . its been years since we last played together , but as i recall , he was rather weak at the net . or was it his serving ? all i know is he plays tennis much better than he plays cricket . perhaps , mr brearly , frances eventually replied , we should wait until we actually start playing . then we can ascertain our oppositions faults , and make a plan based on the new information . since it was the middle of summer , there were candles in the fireplace instead of a fire . but it still cast a romantic glow over the room . there were candles on the mantle and on a table set up in the corner with flowers . as she looked around , her eyes instinctively turned to find max who was behind a bar opening a bottle of champagne . the doors were closed quietly behind her and her mouth felt dry as she looked across the room at the man who had haunted her dreams for so long . the open doorway of another house provided a view of an ancient game of tiles . it wasnt the game that held reddings attention . it was the four elderly people who sat around a table playing the game . they were well beyond their productive years and the canal township had probably been their whole lives . redding and lin ming stepped away from the doorway right into the path of a wooden pushcart . along with the fish , howard had given them some other picnic treats that had spoiled ... mushrooms in cream sauce , rotted greens . the bats and temp were only eating from the river now , but the remaining picnic food was running low . there were a few loaves of stale bread , some cheese , some dried vegetables , and a couple of cakes . gregor looked over the supplies and thought about boots wailing for food and water in the jungle . it had been unbearable . he felt the first stirrings of fear mixing with his anger . a light flicked on in the room and eric jerked , blinking for a minute at the brightness before the images focused . there was a tall , thin man standing over a mannequin . he looked like he was assembling it , since its leg was on the ground next to the man and its arm was in two pieces farther away . then the mannequin ’s head turned . # References [1] D. Bahdanau, K. Cho, and Y. Bengio. Neural machine trans- lation by jointly learning to align and translate. ICLR, 2015. 4 [2] K. Cho, B. van Merrienboer, C. Gulcehre, F. Bougares, H. Schwenk, and Y. Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. EMNLP, 2014. 4 [3] J. Chung, C. Gulcehre, K. Cho, and Y. Bengio. Empirical evaluation of gated recurrent neural networks on sequence modeling. arXiv preprint arXiv:1412.3555, 2014. 4 and B. Taskar. Movie/script: Alignment and parsing of video and text tran- scription. In ECCV, 2008. 2 [5] M. Everingham, J. Sivic, and A. Zisserman. “Hello! My name is... Buffy” – Automatic Naming of Characters in TV Video. BMVC, pages 899–908, 2006. 2 [6] A. Farhadi, M. Hejrati, M. Sadeghi, P. Young, C. Rashtchian, J. Hockenmaier, and D. Forsyth. Every picture tells a story: Generating sentences for images. In ECCV, 2010. 2 [7] S. Fidler, A. Sharma, and R. Urtasun. A sentence is worth a thousand pixels. In CVPR, 2013. 2 [8] A. Gupta and L. Davis. Beyond nouns: Exploiting prepo- sitions and comparative adjectives for learning visual classi- fiers. In ECCV, 2008. 1 [9] S. Hochreiter and J. Schmidhuber. Long short-term memory. Neural computation, 9(8):1735–1780, 1997. 4 [10] N. Kalchbrenner and P. Blunsom. Recurrent continuous translation models. In EMNLP, pages 1700–1709, 2013. 4 [11] A. Karpathy and L. Fei-Fei. Deep visual-semantic align- In CVPR, 2015. ments for generating image descriptions. 1, 2 [12] D. Kingma and J. Ba. Adam: A method for stochastic opti- mization. arXiv preprint arXiv:1412.6980, 2014. 5 [13] R. Kiros, R. Salakhutdinov, and R. S. Zemel. Unifying visual-semantic embeddings with multimodal neural lan- guage models. CoRR, abs/1411.2539, 2014. 1, 2, 3, 5, 9, 10 [14] R. Kiros, Y. Zhu, R. Salakhutdinov, R. S. Zemel, A. Torralba, R. Urtasun, and S. Fidler. Skip-Thought Vectors. In Arxiv, 2015. 3, 4 [15] C. Kong, D. Lin, M. Bansal, R. Urtasun, and S. Fidler. What are you talking about? text-to-image coreference. In CVPR, 2014. 1, 2 [16] G. Kulkarni, V. Premraj, S. Dhar, S. Li, Y. Choi, A. Berg, and T. Berg. Baby talk: Understanding and generating simple image descriptions. In CVPR, 2011. 2 [17] D. Lin, S. Fidler, C. Kong, and R. Urtasun. Visual Seman- tic Search: Retrieving Videos via Complex Textual Queries. CVPR, pages 2657–2664, 2014. 1, 2 [18] T.-Y. Lin, M. Maire, S. Belongie, J. Hays, P. Perona, D. Ra- manan, P. Doll´ar, and C. L. Zitnick. Microsoft coco: Com- mon objects in context. In ECCV, pages 740–755. 2014. 1, 19 [19] X. Lin and D. Parikh. Don’t just listen, use your imagination: In Leveraging visual common sense for non-visual tasks. CVPR, 2015. 1 [20] M. Malinowski and M. Fritz. A multi-world approach to question answering about real-world scenes based on uncer- tain input. In NIPS, 2014. 1 [21] J. Mao, W. Xu, Y. Yang, J. Wang, and A. L. Yuille. Ex- plain images with multimodal recurrent neural networks. In arXiv:1410.1090, 2014. 1, 2 [22] T. Mikolov, K. Chen, G. Corrado, and J. Dean. Efficient estimation of word representations in vector space. arXiv preprint arXiv:1301.3781, 2013. 4 [23] K. Papineni, S. Roukos, T. Ward, and W. J. Zhu. BLEU: a method for automatic evaluation of machine translation. In ACL, pages 311–318, 2002. 6 [24] H. Pirsiavash, C. Vondrick, and A. Torralba. why in images. arXiv.org, jun 2014. 2 Inferring the [25] V. Ramanathan, A. Joulin, P. Liang, and L. Fei-Fei. Link- ing People in Videos with “Their” Names Using Coreference Resolution. In ECCV, pages 95–110. 2014. 2 [26] V. Ramanathan, P. Liang, and L. Fei-Fei. Video event under- standing using natural language descriptions. In ICCV, 2013. 1 [27] A. Rohrbach, M. Rohrbach, N. Tandon, and B. Schiele. A dataset for movie description. In CVPR, 2015. 2, 5 [28] P. Sankar, C. V. Jawahar, and A. Zisserman. Subtitle-free Movie to Script Alignment. In BMVC, 2009. 2 [29] A. Schwing, T. Hazan, M. Pollefeys, and R. Urtasun. Effi- cient Structured Prediction with Latent Variables for General Graphical Models. In ICML, 2012. 6 [30] J. Sivic, M. Everingham, and A. Zisserman. “Who are you?” - Learning person specific classifiers from video. CVPR, pages 1145–1152, 2009. 2 [31] I. Sutskever, O. Vinyals, and Q. V. Le. Sequence to sequence learning with neural networks. In NIPS, 2014. 4 [32] C. Szegedy, W. Liu, Y. Jia, P. Sermanet, S. Reed, D. Anguelov, D. Erhan, V. Vanhoucke, and A. Rabi- novich. Going deeper with convolutions. arXiv preprint arXiv:1409.4842, 2014. 5 [33] M. Tapaswi, M. Bauml, and R. Stiefelhagen. Book2Movie: Aligning Video scenes with Book chapters. In CVPR, 2015. 2 [34] M. Tapaswi, M. Buml, and R. Stiefelhagen. Aligning Plot Synopses to Videos for Story-based Retrieval. IJMIR, 4:3– 16, 2015. 1, 2, 6 [35] S. Venugopalan, H. Xu, J. Donahue, M. Rohrbach, R. J. Mooney, and K. Saenko. Translating Videos to Natural Language Using Deep Recurrent Neural Networks. CoRR abs/1312.6229, cs.CV, 2014. 1, 2 [36] O. Vinyals, A. Toshev, S. Bengio, and D. Erhan. Show and tell: A neural image caption generator. In arXiv:1411.4555, 2014. 1, 2 [37] K. Xu, J. Ba, R. Kiros, K. Cho, A. Courville, R. Salakhut- dinov, R. Zemel, and Y. Bengio. Show, attend and tell: Neural image caption generation with visual attention. In arXiv:1502.03044, 2015. 2 [38] B. Zhou, A. Lapedriza, J. Xiao, A. Torralba, and A. Oliva. Learning Deep Features for Scene Recognition using Places Database. In NIPS, 2014. 5, 7
Title: Stable and low-precision training for large-scale vision-language models: Summary: We introduce new methods for 1) accelerating and 2) stabilizing training for large language-vision models. 1) For acceleration, we introduce SwitchBack, a linear layer for int8 quantized training which provides a speed-up of 13-25% while matching the performance of bfloat16 training within 0.1 percentage points for the 1B parameter CLIP ViT-Huge -- the largest int8 training to date. Our main focus is int8 as GPU support for float8 is rare, though we also analyze float8 training through simulation. While SwitchBack proves effective for float8, we show that standard techniques are also successful if the network is trained and initialized so that large feature magnitudes are discouraged, which we accomplish via layer-scale initialized with zeros. 2) For stability, we analyze loss spikes and find they consistently occur 1-8 iterations after the squared gradients become under-estimated by their AdamW second moment estimator. As a result, we recommend an AdamW-Adafactor hybrid which avoids loss spikes when training a CLIP ViT-Huge model and outperforms gradient clipping at the scales we test. g for large-scale vision-language models # Mitchell Wortsman∗1 # Tim Dettmers∗1 # Luke Zettlemoyer12 # Ari Morcos†2 Ali Farhadi†1 # Ludwig Schmidt†134 # Abstract We introduce new methods for 1) accelerating and 2) stabilizing training for large language-vision models. 1) For acceleration, we introduce SwitchBack, a lin- ear layer for int8 quantized training which provides a speed-up of 13-25% while matching the performance of bfloat16 training within 0.1 percentage points for the 1B parameter CLIP ViT-Huge—the largest int8 train- ing to date. Our main focus is int8 as GPU support for float8 is rare, though we also analyze float8 train- ing through simulation. While SwitchBack proves effective for float8, we show that standard techniques are also successful if the network is trained and initial- ized so that large feature magnitudes are discouraged, which we accomplish via layer-scale initialized with zeros. 2) For stabilization, we analyze loss spikes and find they consistently occur 1-8 iterations after the squared gradients become under-estimated by their AdamW second moment estimator. As a result, we rec- ommend an AdamW-Adafactor hybrid which avoids loss spikes when training a CLIP ViT-Huge model and outperforms gradient clipping at the scales we test. # Introduction Large models trained on large datasets have recently led to multiple breakthroughs in machine learning 1University of Washington. 2Meta AI Research, FAIR Team. 3Allen Institute for AI. 4LAION. ∗ Equal contribution. † Equal senior contribution. such as GPT-3 [5] and PaLM [11]. While many com- ponents are necessary for successful large-scale train- ing, two critical elements are training speed and sta- bility. To enable further progress, we must ensure that 1) training is fast—the model should be able to see a lot of data even if it is large, and 2) train- ing is stable—large models should not suffer from loss spikes which degrade performance. We study these two directions in the context of contrastive language-image pre-training (CLIP) [46]. We exam- ine CLIP-style models because of their importance in computer vision: CLIP-style models reach state-of- the-art performance on a wide range of image classi- fication tasks [46, 65, 44, 7] and underlie image gen- eration methods such as DALLE·2 [49] and Stable Diffusion [51]. Our contributions towards fast train- ing and stable training are as follows. Towards fast training, we introduce SwitchBack, a linear layer for quantized training with int8 precision which matches the performance of the bfloat16 [63] baseline within 0.1 percentage points for CLIP ViT- Huge—a larger model than considered in the original CLIP paper. Linear layers account for the majority of the compute in standard transformer models, usually more than 90%, comprising the key, query, value, and out projection of the attention blocks as well as the multilayer perceptron. We perform all linear layers in low-precision (int8) while retaining other layers, such as layer norms, in higher precision. With this setup, we observe end-to-end speedups between 13 and 25% for CLIP ViT-Huge training: 25% compared to a stan- wu a w ° EE bfloat16 baseline —A- LLM.int8() baseline ~@ SwitchBack int8 FS a ES ° Zero-shot ImageNet accuracy ES fs) EE bfloatl6é baseline “Ae fp8 tensor-wise baseline —@- SwitchBack fp8 N is) Zero-shot ImageNet accuracy b w 5 3$ i} ViT-Base ViT-Large Model size ViT-Huge ViT-Base ViT-Large Model size ViT-Huge Figure 1: We introduce SwitchBack, a linear layer for low-precision training. (Left) SwitchBack for int8 training matches the zero-shot ImageNet [15] accuracy of standard bfloat16 training within 0.1 percentage point for CLIP ViT-Huge [46, 20] and outperforms LLM.int8() [17]. (Right) For float8 (fp8) training [40], a baseline which uses tensor-wise quantization diverges for large models while SwitchBack matches the baseline. In these large-model, small-data experiments, our focus is on comparing methods and not final model accuracy, so we use short runs which makes it feasible to run many experiments. dard linear layer implemented using the PyTorch [43] autograd python module and 13% compared to the standard PyTorch layer which includes CUDA and C++ optimizations that happen in the background and which are difficult to replicate for custom layers. SwitchBack starts from the observation that quan- tization noise grows with the inner dimension in a matrix multiplication. For CLIP training, the weight gradient computation involves a large inner dimension because CLIP training requires a large batch size [44]. Hence SwitchBack uses 16 bit precision matrix multi- plication for the weight gradient computation while using int8 multiplications for the forward pass and layer input gradient computations. This approach leads to large accuracy improvements compared to LLM.int8() [17] (Figure 1). We provide open-source Triton [57] kernels for Switchback to enable future work on efficient quantization schemes. Besides int8 training, we also study large-scale 8-bit float (fp8) [40] training. We do not have access to hardware that supports fp8 data types, which is cur- rently more rare than int8, so we use an accurate simulation of fp8 computation. SwitchBack also out- performs straightforward 8-bit float (fp8) baselines because tensor-wise quantized baselines diverge at >420M scale (Figure 1). However, we demonstrate that these methods can achieve high accuracy if the network is trained while keeping feature magnitudes small, which we accomplish via layer-scale [58] initial- ized with zeros. Towards stable training, we find that loss spikes occur in CLIP training when the AdamW [37] sec- ond moment estimator becomes out-of-date in the patch embedding [20] layer. In particular, the learn- ing signal changes so that the moving averages of squared gradients underestimates their true magni- Indeed, in the absence of stability interven- tude. tions, we show that loss spikes can be predicted by examining this ratio of the squared gradients to their moving average. We therefore recommend a AdamW- AdaFactor [54] hybrid, which we refer to as Sta- bleAdamW as it removes instabilities at the scales we consider and outperforms gradient clipping. Con- cretely, StableAdamW is AdamW with the update clipping technique introduced in AdaFactor. Update clipping tracks the average ratio of the gradient square to the second moment estimator and lowers the learn- ing rate when the ratio is large. The remainder of this paper is organized as follows: 2 Section 2 focuses on low-precision training while Sec- tion 3 stabilizes training by reducing loss spikes. # 8-bit training This section develops and compares methods for eight- bit training of languge-vision transformer models. First, Section 2.1 discusses preliminaries and related work. Next, Section 2.2 introduces and tests Switch- Back, a linear layer for int8 and float8 training. Fi- nally, Section 2.3 develops alternatives to SwitchBack which can be used for float8. # 2.1 Preliminaries and related work Neural networks today typically use 16-bit operations for training [39] in either the float16 or bfloat16 for- mat [63]. Floating point formats use a subset of bits to represent the exponent while the remainder spec- ifies the fraction (often referred to as the mantissa). The float16 format uses 5 bits for the exponent while bfloat16 uses 8 and therefore covers a larger range— float16 has a range of (5.96·10−8, 65504) while bfloat16 has a range of (10−38, 3 · 1038). Most floating point formats also have denormalized numbers which allow for a “soft underflow” which gets exponentially closer to 0.0f for each additional bit in the mantissa. To pre- vent underflows float16 mixed precision training [39] has been developed which works as follows. The loss of a mini-batch is multiplied by a loss scalar to scale the loss and following backpropagation gradients into the representable range of fp16. This loss scaling is undone by rescaling the weight gradients before the optimizer updates fp32 main weights with the fp16 gradients. In PyTorch [43], the loss scalar is initialized to 65536. Everytime an Inf/NaN is encountered, the update is skipped and the loss scalar is halved. If no Inf/NaN are encountered for 2k iterations, the scalar is doubled. When the loss scalar becomes too low in float16 training the loss slowly diverges. This was observed by Cherti et al. [9] when training ViT-Huge CLIP models and remedied by switching to bfloat16. An- other instance of float16 creating issues at scale was the training of OPT [74] and BLOOM models [52]. Indeed, many obstacles faced during the OPT project could have been alleviated by using bfloat16 [73]. Sim- ilarly, all float16 training runs for BLOOM ended in divergence, only after using bfloat16 was the training stable. However, fast bfloat16 support is only avail- able on TPUs, or GPUs developed with or after the Algorithm 1 PyTorch pseudo-code for SwitchBack class SwitchBackMatmul(autograd.Function): @staticmethod def forward(ctx, X, W): # X [b, n] inputs # W [n, m] weights # save tensors in ctx ctx.save_for_backward = X, W X_int8, state_X = row-wise_quantize(X) W_int8, state_W = tensor-wise_quantize(W) # Return output return matmul_int8_and_dequanitze( X_int8, W_int8.t(), state_X, state_W ) @staticmethod def backward(ctx, G): # G [b, m] gradient to output # Recover tensors from ctx X, W = ctx.save_for_backward G_rowwise = rowwise_quantize(G) W_int8, state_W = tensor-wise_quantize_transpose(W) # Use 8bit matmul only for X_gradient X_gradient = matmul_int8_and_dequanitze( G_int8, W_int8.t(), state_X, state_W ) W_gradient = matmul_fp16(G.t(), X) return X_gradient, W_gradient class SwitchBackLinear(nn.Linear): def forward(self, X): return SwitchBackMatmul.apply(X, self.weight) NVIDIA Ampere series (2021 or later). While 16 bit training is the standard today, hardware support for 8 bit operations are becoming more com- mon. Hopper GPUs support float8 (fp8) [40] and Ampere GPUs support int8. However, it is currently (2023) very difficult to attain Hopper GPUs. Moreover, while int8 and int4 are used for inference [17, 66, 16], and there is earlier work exploring 8 bit training for convnets [61, 79, 10], these formats are not commonly used for training transformer models at scale. The CLIP ViT-Huge models we train have 1B parame- ters including the image and text towers which is 40x larger than a standard ResNet-50 (23M) [28], and quantization is more challenging for large tensors [17]. Additional related work on quantization of large scale models (larger than BERT-large) and low-precision training and be found in Appendix A. # 2.2 SwitchBack # 2.2.1 Method Overview. A linear layer consists of three matrix multiplications—one in the forward pass to compute 3 outputs and two in the backwards pass to compute gradients for the input and weights. Our SwitchBack layer uses 8 bit precision for the first two matrix multiplies but switches back to higher precision for the weight gradient. We compute the weight gradient in higher precision because this matrix multiplication involves dot prod- ucts between vectors which have a length of batch size times sequence length. As CLIP training requires large batch sizes [46, 44], this inner dimension of batch size times sequence length is much larger than for the other matrix multiplies. As we show in Appendix C, variance due to quantization increases with the inner dimension of the matrix multiply. This modification is what differentiates SwitchBack from LLM.int8(), allowing SwitchBack to match the bfloat16 baseline (Figure 1). Notation. A standard linear layer is comprised of inputs X ∈ Rb×n, weights W ∈ Rm×n, and outputs Y ∈ Rb×m. In the forward pass, outputs are com- puted as Y = XW ⊤. In the backwards pass the layer receives gradients of the loss with respect to Y , which we denote ˙Y . Then, gradients to inputs ˙X are com- puted via ˙X = ˙Y W while gradients to the weights ˙W are computed via ˙W = ˙Y ⊤X. For linear layers in a transformer [60], b is batch size times sequence length, while n and m are small multiples of the embedding dimension. Quantization. For the matrix multiplies in 8 bit precision we use quantization. There are a multiple quantization techniques to choose from and we re- lease code for all these alternatives. However, we find the best trade-off of simplicity and performance is from using i) row-wise quantization [31] for the in- puts and gradients and ii) tensor-wise quantization for the weights. Additional information on quanti- zation methods is provided by Dettmers et al. [17] but we summarize below. Using int8 as an example, which can represent integers from −127 to 127, we now define row-wise and tensor wise quantization. For a matrix X with rows x1, ..., xb, row-wise quantization Qrow is given by x1 ... xn = round 127 absmax(x1) · x1 ... absmax(xb) · xb 127 (1) # Qrow while tensor-wise quantization Qtensor is given by Qtensor (X) = round 127 absmax (X) · X , (2) ViT-Base model ViT-Huge model ViT-Base model ViT-Huge model 6 6 5 5 PAenetnnpel 5 5 4 heowtmahene 4 an v4 a un 4 a as a as ° ° ° Ss S3 Ss 2 2 2 1 2 1 1 0 1 0 0 5000 10000 15000 20000 0 5000 10000 15000 20000 0 — 5000 10000 15000 20000 0 5000 10000 15000 20000 Iteration Iteration —— bfloatl6 baseline —— SwitchBack int8 —— LLM.int8() baseline Iteration Iteration —— bfloat16 baseline — fp8 tensor-wise baseline —— SwitchBack fp8 a ° 53 Figure 2: Loss curves for the CLIP ViT-Base and CLIP ViT-Huge models evaluated in Figure 1. The left two plots display results for int8 training while the right two plots display results for float8 (fp8) training. where absmax is the maximum of the absolute value. Importantly, when applying Qrow we also save the row-wise absolute maximums so that we can use them later for dequantization. We refer to this as the quantization state, or state, for short, so staterow(X) = [absmax(x1), ..., absmax(xb)]⊤ ∈ Rb×1. Equivalently, for tensor-wise quantization we only need to store the tensor-wise absolute maximum so statetensor(X) = absmax(X) ∈ R. and quantization we fuse both operations, meaning we load the required data once from slow DRAM into fast SRAM/shared memory and then perform both operation in this cached memory – this is crit- ical for achieving speedups. We call this operation tensor-wise quantize transpose, which is a fused tensor-wise quantize and transpose operation. Putting the pieces together, the result is Algorithm 1. Since only the matrix multiply occurs in int8 precision we need to dequantize the outputs back to the original floating point precision. Consequently, the forward pass with quantization and dequantization becomes statetensor(W) Toyz Staterow(X) * Qrow (X) Qrensor (W) | eee int8 matmul (3) where ∗ denotes elementwise-multiplication, which in this case is broadcasted so that row i of the matrix Qrow (X) Qtensor (W )⊤ is multiplied by element i of staterow(X). As mentioned previously, we use row-wise quantization for the inputs and gradients and tensor-wise quanti- zation for the weights. We find that using row-wise quantization for both matrices increases complexity at a negligible or no performance increase. As such, we use this simpler approach. Variants. While Algorithm 1 is the most straightfor- ward version of SwitchBack, we also present two al- ternative versions—SwitchBackM and SwitchBackQ— and release triton [57] implementations for all three via the bitsandbytes library [18]. Appendix B contains pseudocode. SwitchBackM (Algorithm 3) is a memory efficient version of SwitchBack which only saves 8 bit tensors for the backwards pass—we recommend its use when memory is limited. The small downside of SwitchBackM is that it requires an additional de- quantize operation during the backwards pass which increases the runtime overhead. For CLIP ViT-Huge we observed only a negligible accuracy differences be- tween SwitchBack and SwitchBackM. In addition, we present SwitchBackQ (Algorithm 4) which uses row- wise and column-wise quantization for the weights instead of tensor-wise. While we did not observe this to improve accuracy at the scales we consider, it’s possible that it will perform better than SwitchBack at larger scale. For SwitchBackQ, the forward pass is given by The last detail in our algorithm is hardware specific. NVIDIA GPUs, which we use in this work, do not implement the int8/float8 operation AB for matrices A and B and only ABT is implemented. As such, it is necessary to transpose the weight matrix in the back- ward pass. To reduce the overhead of transposition 1 OTe statesow(X)staterow(W)! * Qrow (X) Qrow (W) | eE>_>_S_——$_S int8 matmul (4) where ∗ is an elementwise product. Again, we append transpose to a function in Algorithm 4 to mean that 4 Standard fp16 (sum of parts) 50 SwitchBack int8 (sum of parts) Average fp16 matmul Average int8 matmul 40 Average quantize operation a £30 z 5 20 10 0 linear layer, batch * sdquence length = 32k Unear layer summary, varying dimensions —s— batch * sequence length = 16384 —*— batch * sequence length = 32768 —* batch * sequence length = 65536 —e— batch * sequence length = 131072 1024 2048 dim —a+ —e- # =i # =F +9) 4096 Figure 3: (Left) Individually profiling operations which constitute a forward and backward pass in a linear layer for i) SwitchBack using triton kernels and ii) an fp16 baseline using torch.matmul. Times are averaged over a linear layer from dim to 4 · dim and a linear layer from 4 · dim to dim—representative of the linear layers in a transformer MLP. (Right) The % speedup of SwitchBack over a standard fp16 linear layer when all operations in Figure 3 (left) are summed. the operation is fused with a transpose. float8. While the explanation so far has used int8 as an example, the code for SwitchBack and float8 (fp8) is nearly identical. The only modification is that operations such as round(127x/absmax(x)) are replaced by float8cast(x/absmax(x)) where we simu- late float8cast through bitsandbytes by rounding to the exact values of the float8 data type. This simu- lation improves on the simulation of [40] which only clips the input tensors into the representable range of the float8 data type, but not the exact values of the float8 data type. This simulation theoretically matches float8 training, but we are unable to per- form real float8 training because we lack the hardware that supports float8 arithmetic. As such, we perform arithmetic in 16-bit with exact float8 values. For our int8 experiments we conduct the multiplications in int8 using A100 GPUs—we perform real int8 training without any simulation. or approximately 2.9e20 FLOPs per training run.After training on LAION-2B we evaluate the models zero- shot on ImageNet [15] using the 80 prompt templates from CLIP [46]. We use batch size 16384 (per-gpu batch size of 256) and train for a total of 20k iterations. The first 5k iter- ations are linear warmup while the remaining 15k are cosine decay. Training and evaluation are conducted with the OpenCLIP library [29] with learning rate 2e-3, weight decay 0.2, and batch-size 16384 using the optimizer described in Section 3.5. # 2.2.3 Results We test two main questions: (1) can we replicate 16- bit performance with SwitchBack and (2) can we get speedups. To test (1) we train CLIP models with SwitchBack across multiple scales with both int8 and float8 precision (Figures 1 and 2). To test (2) we profile operations in an individual linear layer and also measure end-to-end training speed. # 2.2.2 Experimental setup To evaluate SwitchBack we train CLIP [46] visual transformer [20] models on LAION-2B [53]. Typi- cally CLIP training, especially at ViT-Huge scale, is prohibitively expensive. Our goal is not high final accuracy but rather to contrast different methods for low-precision training. To enable running multiple experiments, we therefore only train for a small num- ber of samples seen—380 million images—and use patch-dropout 0.5 [35]. We note that the experiment is still very expensive, corresponding to roughly 300 epochs of ImageNet training in terms of samples seen, Accuracy. We find that SwitchBack can match stan- dard 16-bit training performance and outperform base- lines for both a) int8 precision and b) float8 precision. For our int8 experiments (Figures 1 and 2 left), we contrast the performance of i) the standard baseline which uses mixed-precision bfloat16, ii) the matrix multiplication kernels from LLM.int8() [17], which is equivalent to SwitchBackQ (Algorithm 4) if the weight gradient multiplication was also performed in int8 using row- and column-wise quantization, and iii) SwitchBack. SwitchBack has a negligible accuracy 5 25 —2— batch * sequence length = 16384 = batch * sequence length = 32768 — batch * sequence length = 65536 a 20 batch * sequence length = 131072 15 1024 2048 dim 4096 25 + —@- speedup over baseline (torch.autograd Linear) “l- speedup over pytorch optimized linear 20 S gis o ey 3 _— 2 10 aes 2 = a § 4} === of me ViT-Base ViT-Large ViT-Huge # Quantization overhead Figure 4: (Left) Measuring the % of time occupied by quantize operations for a SwitchBack linear layer, which is usually less than 20% and decreases with dim. (Right) Benchmarking speedups for end-to-end CLIP training on a single node (with 4 A100 GPUs, per-GPU batch size 256, and gradient checkpointing) for various model sizes when replacing all linear operations in the transformer with SwitchBack (i.e., key, query, value, and out projections as well as the MLP). speedups reported over i) a custom linear layer implemented with torch.autograd (Algorithm 5), which matches our implementation of SwitchBack that uses torch.autograd, and ii) using the standard PyTorch nn.Linear which includes additional background C++/CUDA optimizations which we do not replicate. LLM.int8() [17] does not provide speed-ups over the torch.autograd or nn.Linear baseline at this scale—we compare the speed of SwitchBack and LLM.int8() in Figure 13. drop of 0.1 percentage points compared to the bfloat16 baseline for CLIP ViT-Huge. In contrast, there is a drop of 5.9 percentage points when training with LLM.int8(). Section C details our hypothesis for why LLM.int8() fails to replicate 16-bit performance for CLIP training. For our simulated float8 training experiments (Fig- ures 1 and 2 right), we contrast the performance of i) the standard baseline which uses mixed-precision bfloat16, ii) a baseline which uses tensor-wise quan- tization for all matrices, that is the weights, inputs, and gradients, and iii) SwitchBack. SwitchBack has a negligible accuracy drop of 0.1 percentage points from the bfloat16 baseline for CLIP ViT-Huge. In contrast, training diverges for the baseline that uses tensor-wise quantization for all matrices. Figure 3 (right) displays the % speedup of Switch- Back over a standard fp16 layer when all opera- tions in Figure 3 (left) are summed. Overall, the advantage of SwitchBack is greater for larger dim and batch size ∗ sequence length. Overall, the speedup ranges from 5% to 35%. We see a bump at dim = 1280 because standard PyTorch matmuls do not have op- timized kernels for matrices of this size while we use triton’s autotune feature which provides fine-grained optimized kernels for matrices of any size. Our kernels are easy to modify as they are written in Triton [57], and the code to run the benchmarks and produce Figure 3 is open sourced. In doing so, we invite the community to further improve the kernels and provide a benchmark for measuring this progress. Due to com- putational constraints we have not tested dim > 4096 and it’s possible the kernels require additional tuning to perform well at that scale. Speed. We now test the speedups offered by Switch- Back by first examining individual operations and then end-to-end training. We profile all of the operations which constitute a forward and backward pass for a single linear layer in Figure 3 (left) for both SwitchBack and the baseline. For SwitchBack we profile our custom triton kernels and for the baseline we profile torch.matmul. Overall, we observe that int8 multiplies occupy just over half the time as standard fp16 matmuls, and that quantize operations are roughly an order of magnitude less time than a matmul. Note that our int8 matmuls are fused with the dequantize operation. One downside of SwitchBack is that it requires quan- tize operations. However, it is already evident from Figure 3 that quantize operations occupy a small amount of time compared to matmuls. This is high- lighted by Figure 4 (left) which displays the fraction of time occupied by quantize operations relative to matmuls for SwitchBack linear layers. Quantize oper- ations occupy at most 25% of the time, this fraction decreases to around 10% or below for large dim. We now conduct end-to-end speed tests for CLIP training on a single node with 4x A100 GPUs (Fig- 6 ViT-Large model 10 0 8 0.5 S| n 6 wn S 4 2 i} 2500 5000 7500 10000 12500 15000 17500 20000 Iterations — i) bfloatl6 baseline — ii) fp8 tensor quantize — iii) fp8 tensor + grad clip — iv) fp8 tensor + KQ Layernorm —— v) fp8 tensor + zero-init layerscale standard at init standard final zero-init layer scale at init zero-init layer scale final $eee Average feature magnitude i} 10 20 30 Transformer block index Figure 5: (Left) Training CLIP ViT-Large models with simulated fp8 precision using tensor-wise quantization for the inputs, weights, and gradients. All methods we try diverge except for using zero-init layerscale [58], which multiplies the output of each self-attention or mlp block with a learnable vector initialized to zero. (Right) Examining feature magnitudes (i.e., the average absolute value of the output for transformer block k) for CLIP ViT-Huge at the beginning (init) and end of training. This suggest why zero-init layer scale enables float8 training—zero-init layer scale prevents high feature magnitudes which may cause issues for low precision training [17]. Without the intervention, the average feature magnitude becomes large for later blocks. ure 4, right). This is in contrast with the speedup measurements so far in this which have measured indi- vidual layers independently. We benchmark speedups relative to using i) a baseline linear layer which we implement in PyTorch with torch.autograd.linear (Al- gorithm 5) and ii) the PyTorch optimized linear layer nn.Linear. In both cases the speedups increase when going from CLIP ViT-Base to CLIP ViT-Huge. How- ever, there is an additional ∼12.5% speedup when comparing SwitchBack to the baseline linear layer which uses torch.autograd. We believe this comparison is fair because SwitchBack is also implemented using torch.autograd, while the standard PyTorch nn.Linear layer has additional C++ and CUDA optimizations that we do not implement. We hope to collabo- rate with the PyTorch team to realize the additional ∼12.5% speedup. Finally, we note that the kernels from LLM.int8() [17] do not provide speedups over fp16 at the scale we consider. discourages large feature magnitudes. We accomplish via layer-scale [58] initialized to zero. We use the bitsandbytes library [18] to simulate float8 training using the fp8 types from Micikevicius et al. [40]. We use tensor-wise quantization for the inputs, weights, and gradients, so that all operations occur in simulated float8. In our simulation, we represent each value only with the exact values representable by float8, but we perform computations in float16 precision. We believe that tensor-wise quantization approximates the removal of quantize operations en- tirely. This is because, as we show in Appendix B.2 (Figure 14), the maximum of these tensors tends to evolve smoothly. Consequently, using a moving aver- age for a maximum which is divided directly in the matmul is similar to tensor-wise quantization. # 2.3 Float8 training by reducing feature magnitude Layer-scale, introduced by Touvron et al. [58], scales each self-attention and MLP block output hidden state by a learnable vector of shape embed dim. A pre-norm transformer block with layer-scale tensors γ1 and γ2 is defined as We find that SwitchBack is necessary for high accu- racy int8 training. However, this section develops other interventions which enable float8 training with- out SwitchBack. We show that high accuracy can be achieved via float8 training with tensor-wise quantiza- tion for the inputs, weights, and gradients, so long as the network is initialized and trained in a way which # x′ k = xk + γ1 ∗ self attention(norm1(xk)) xk+1 = x′ k + γ2 ∗ mlp(norm2(x′ k + γ2 ∗ mlp(norm2(x′ k)), (6) where ∗ is broadcasted elementwise multiplication. Typically, layers are initialized so that they approx- imately preserve the variance of their inputs, and inputs have approximately unit variance [26, 27]. How- 7 (5) ever, when combined with residual connections this can lead to higher norms in deeper networks. Consequently, researchers have proposed initialization and scaling schemes which remedy this issue [1, 72, 4, 19]. Layer-scale with initialization 0 is an example of one such scheme—at initialization the transformer is an identity function. While γ1, γ2 are typically initialized as vectors of 10−4 or 10−6, we use 0 for simplicity. Figure 5 (right) demonstrates that the layer-scale intervention is successful at controlling the average magnitude output. Without the intervention, the av- erage feature magnitude E[abs(xk)] becomes high for later blocks. Previous work [17] has shown that large feature magnitudes result in issues for low precision training. Results for simulated fp8 training are shown in Fig- ure 5 (left) for ViT-Large. We find that all fp8 runs diverge except for when we use layer-scale initialized to zero. Concretely, Figure 5 compares i) the base- line which uses bfloat16 training, ii) using fp8 with tensor-wise quantization and no further modifications, which slowly diverges, iii) adding gradient clipping to ii), which also diverges, iv) adding KQ layernorm [14] to ii), which also diverges, and v) using zero-init lay- erscale, which trains without diverging. While there is a difference still between fp8 and bfloat16 training, this is primarily because of layerscale. Moreover, we believe that with hyperparameter tuning layerscale would match standard training in terms of accuracy. # 3 Stability We now switch focus from accelerating learning by reducing precision to addressing instabilities which can arise during training. Section 3.1 reviews pre- liminaries and related work while Section 3.2 details the experimental setup. Next, Section 3.3 examines trends for training instability, finding loss spikes to increase with model scale but decrease with lower AdamW β2. Then, Section 3.4 finds that loss spikes arise in our setting due to an out-of-date AdamW second moment estimator leading Section 3.5 to adopt and tests a fix developed in the context of AdaFac- tor [54]. Finally, Section 3.6 connects loss spikes to low precision training. 8 # 3.1 Preliminaries and related work Loss spikes can emerge when scaling up models [8, 25, 14, 69, 71, 54, 74]. These instabilities may slow learn- ing, or even destabilize training completely. Various solutions have been proposed, including freezing the embedding layer [8], adding additional layer normal- ization [14, 25], or reparametrizing the weights [69]. In our work we investigate instabilities which arise during CLIP training. Unlike the instabilities ob- served in [14, 69] which lead to a slow divergence, we study fast loss spikes. Our results indicate that these spikes arise when the second moment estimator is out of date for early layers. While our analysis and methods build directly on Shazeer and Stern [54] (AdaFactor), there are In contrast with Shazeer important differences. and Stern [54], who only observe instabilities with- out warmup, we observe instabilities despite a long warmup period. Moreover, in contrast with Shazeer and Stern [54] we find that an out-of-date second mo- ment estimator is primarily an issue for the (patch) embedding layer, and measure how well loss spikes are predicted by this event. Finally, we note that researchers have moved away from AdaFactor in its original formulation for large-scale training [47, 11, 70], finding AdaFactor to under-perform AdamW [47]. We believe this is due to the factored second moment or absence of first moment. This is why our focus is AdamW [37] which is the de facto standard optimizer for transformers. After the initial version of this paper we became aware of Cohen et al. [12] which offers a general and princi- pled treatment of fast loss spikes, and which we rec- ommend to readers. Moreover, we direct the reader’s attention to the concurrent work of [41]. # 3.2 Experimental setup As in Section 2, we train ViT CLIP models on LAION [53] using OpenCLIP [29] and evaluate them zero-shot on ImageNet. Since we are not interested in final performance and instead interested in study- ing instability—even for very large models—we use a short run which allows us to conduct multiple ex- periments. Concretly, we use patch-dropout 0.5 [35] and 20k iterations. The first 5k iterations are linear warmup while the remainder are cosine decay [36]. We follow the CLIP paper [46] in that i) we do not use ViT-Base model ViT-Large model ViT-Huge model 10 10 10 8 8 8 wo 6 wo 6 wo 6 3 3 3 a4 a4 a4 2 2 2 0 fy 5000 10000 15000 20000 fy 5000 10000 15000 20000 fy 5000 10000 15000 20000 Iteration Iteration Iteration beta2 = 0.99 beta2 = 0.98 beta2 = 0.95 beta2 = 0.9 beta2 = 0.5 Figure 6: Loss spikes increase with model size for fixed learning rate and batch size. Reducing AdamW β2 from its default in PyTorch of 0.999 mitigates loss spikes. Reducing β2 too much slows training. o Base model, batch size = 4096 Base model, batch size = 16384 9 Base model, batch size = 65536 1 1 1 8 8 8 3 3 3 4 4 4 2 2 2 fy 5000 10000 15000 20000 0 5000 10000 15000 20000 fy 5000 10000 15000 20000 Iteration Iteration Iteration —— beta2 = 0.99 —— beta2 = 0.98 —— beta2 = 0.95 —— beta2 = 0.9 — beta2 =0.5 Figure 7: Loss spikes increase with batch size for fixed learning rate and model size. Reducing AdamW β2 from its default in PyTorch of 0.999 mitigates loss spikes. Reducing β2 too much slows training. Base model, LR = 5e-4 Base model, LR = 2e-3 Base model, LR = 5e-3 10 10 10 8 8 8 — feesiapeseseeee B 6 8 6 B 6 3 3 3 4 4 4 2 2 2 0 5000 10000 15000 20000 0 5000 10000 15000 20000 0 5000 10000 15000 20000 Iteration Iteration Iteration — beta2=0.99 -— beta2=0.98 — beta2=0.95 -—— beta2=0.9 -— beta2=05 Figure 8: Loss spikes increase with learning rate for fixed batch size and model size. Reducing AdamW β2 from its default in PyTorch of 0.999 mitigates loss spikes. Reducing β2 too much slows training. 9 gradient clipping unless otherwise mentioned1, though we do clip the logit scale parameter, and ii) we add a layer-norm after the patch embedding and before the main transformer. Unless otherwise mentioned, experiments use batch size 16384 (per-gpu batch size of 256), learning rate 2e-3 and weight decay 0.2. We initially tried adding a layer-norm before the patch embedding as in [34], but removed this as we found it to hurt performance at CLIP ViT-Huge scale. # 3.3 Loss spikes increase with model size, batch size, and learning rate We begin our studying of loss spikes by observing how their presence varies when changing model size, batch size, and learning rate. The following sections build on these observations—in particular the finding that lowering the AdamW β2 hyperparameter removes spikes entirely. We find that loss spikes increase when increasing model size (Figure 6), batch size (Figure 7), or learning rate (Figure 3). However, we also find that loss spikes can be avoided by reducing the β2 hyperparameter for in AdamW. On the other hand, if β2 is reduced too much then learning is slowed which results in worse performance [50]. # 3.4 On β2 and an out-of-date second moment estimator Based on the observation in the previous section that lowering β2 reduces spikes, this section traces the cause of loss spikes to an out-of-date second moment estimator in the patch embedding layer. Overview. Adaptive optimizers such as Ada- Grad [22], Adam [33], or AdaFactor [54] scale the update differently for each individual parameter. This is often conceptualized a per-parameter learning rate. For instance, in Adam/AdamW, per-parameter up- dates are scaled by the inverse root of the exponential moving average of squared gradients (see the code for AdamW in Algorithm 2, ignoring for now the modifications in pink which we discuss in Section 3.5). This adaptivity can be a very useful tool for accel- erating training, but can also cause issues when the 1It is possible that CLIP is trained with gradient clipping despite not mentioning it in the paper. However, this baseline follows the OpenCLIP library [29], which does not use gradient clipping by default since it follows what is mentioned in Radford et al. [46]. 10 learning signal changes. Concretely, exponential mov- ing averages can become out of date causing updates to be scaled by a value that is too large. This issue is discussed in Section 5 of Shazeer and Stern [54], and we summarize below. # Algorithm 2 StableAdamW 81, 82, €) ({a:}f9, 81, 82, €) Vvo,uo = 0 fort=1toT do n= VEOH) apply correction term to debias moving avg. * 1-g!? By = 61> oe * 1-pt? Bg = Bo- a update moving averages Y= Biv +(1- bi) oe ue = Bou—1 + (1 — Bo) 9? for implementation convenience, the steps below occur independently for each tensor RMG, = VE [97 /ui] update parameters me = a4/max (1, RMS;) 4 = O-1 — MAO—1 — MVE / (Jie + €) As in Algorithm 2, let up = {uzj}%_, denote the exponential moving average (EMA) of squared gra- dients g? = {9 }i_ for neural network parameters 6 € R”. Ignoring the bias correction term?, at each iteration t, uw, is updated as B2u,—1 + (1— G2)g? where B is referred to as the decay for the EMA. Then, he update is scaled by 1/ (Vie + €), where € is a small value added numerical stability. Often the ratio v,/ (fue + €) is thought of as signal-to-noise ratio of he gradient over time. H ing signal changes and u; ceases to be a good es: or the running average of g?. Consider the case where he gradient magnitudes have been historically very small for some parameters so 1/ (\/w +) is large for those parameters. If, then, at iteration t those arameters suddenly receive a larger gradient signal he update can be catastrophically big. We refer to he scenario as the stuck-in-the-past scenario. owever, this method can break down when the learn- imator Overall, if β2 is too small then convergence may be slowed [50]. If β2 is too large then ut can become 2In practice, the EMA is debiased with a correction term. Algorithm 2 follows AdaFactor section 7.1 in applying the correction term to β1, β2. Adam is often written with the correction term applied to vt, ut but they are equivalent [54]. === RMS spike preceeding loss spike —— beta2 = 0.98 — beta2 =0.9 2500 3000 visual conv {weight RMS PNWA Iteration # Loss Figure 9: The learning signal can change so that the AdamW second moment estimator ut is out-of-date and underestimates the squared gradients g2 t /ut] is far from 1. This figure observes a predictive relationship between the event of an RMS spike and a loss spike— we observe a spike in RMSt 1-8 iterations before a loss spike. For lower β2, RMSt does not deviate far from 1. This result looks at RMSt for the patch embedding layer only. This predictive relationship is further examined in Figures 16 to 21 of Appendix D. out-of-date and no longer a good estimator for g2 t , resulting in per-parameter scaling that is too large. Measurement. We now discuss measurement of he aforementioned stuck-in-the-past scenario and search for a predictive relationship between this event and a loss spike. We follow Shazeer and Stern [54] and measure the following root-mean-square quantity, RMS, = /E[g?7/u]. If wu: is a good estimator for g? then the aggregate quantity RMS, will be around . The stuck-in-the-past scenario described above corresponds to an RMS; > 1. As illustrated in Figures 6-8, we observe instability for high β2 in our experiments even though we have 5k iterations of warm-up. While Shazeer and Stern [54] first recognize the out-of-date second moment estimator issue, in their experimental setting they only observe instability without warm-up. We now aim to establish a predictive relationship be- tween the stuck-in-the-past scenario and loss spikes. We present initial results in Figure 9, where we ex- amine RMSt for the the visual transformer patch embedding layer, visual.conv1.weight. This means that the expectation is computed over parameters in visual.conv1.weight only. This figure illustrates a few important findings: i) loss spikes tend to follow 1-8 iterations after an RMS spike, ii) loss spikes slow learning as recovery time is required, and iii), RMSt stays around 1 for lower β2. the embedding layer in Section D through Figures 16, 17, 18, 19, 20, and 21. For analysis purposes, we define a heuristic to characterize loss and RMS spikes in visual.conv1.weight. We then show that 28 out of 30 detected loss spikes follow an RMS spike by 1-8 iterations, while the probability that a loss spike follows an RMS spike by chance is only 1%. Moreover, we find that the same predictive relationship does not exist for the RMS in other transformer layers. # 3.5 StableAdamW: AdamW with up- date clipping from AdaFactor This Section develops and tests StableAdamW (Al- gorithm 2), an AdamW-Adafactor hybrid. To stabilize training, the AdaFactor optimizer divides the learning rate for iteration t by 1/ max(RMSt, 1).3 They refer to this as update clipping. The effect is to slow training when ut is no longer a good estimator for g2 t . As discussed in Section 3.4, our stability issues can be traced to an out-of-date ut which is what led Shazeer and Stern [54] to update clipping, even though their stability issues are also solved with warm-up. There- fore, we port update clipping to the standard AdamW optimizer with d = 1 and refer to the resulting AdamW-Adafactor hybrid as StableAdamW (Algo- rithm 2). A modification we make is to compute As this is just one example, we further elaborate on the predictive relationship between an RMS spike in 3They actually introduce a hyperparameter d and use 1/ max(RMSt/d, 1), but recommend setting d = 1 which we follow. 11 ViT-Huge, Beta2 = 0.99 10 — default 8 — + grad clipping — + update clipping (= StableAdamw) 6 4 2 0 0 2500 5000 7500 1000012500150001750020000 Iteration ViT-Huge a 58.0 > fs) i 5 & 57.5 8 @ 57.0 a 56.5 8 £ 56.0 —® default Sess = + grad clipping o —t- + update clipping (= StableAdamw) £ 55.0 - g 05 O08 09 0.95 0.98 0.99 0.995 Beta2 # n g s Figure 10: Adding update clipping to AdamW mitigates loss spikes and outperforms other interventions such as gradient clipping with norm 1. Code for the AdamW-AdaFactor hybrid we recommend of AdamW + update clipping is in Algorithm 2. The left plot shows loss curves for β2 = 0.99 while the right displays accuracy ablating over β2. and divide learning rate by max(RMSt, 1) indepen- dently for each tensor, which is for implementation convenience. This means that the expectation will be computed independently for each layer to produce a different RMSt. We now test how StableAdamW compares with other stability interventions such as gradient clipping4 or lowering β2. These results, presented in Figure 10 find that StableAdamW (i.e., AdamW + update clipping) outperforms these aforementioned interventions for CLIP ViT-Huge. While gradient clipping and update clipping both remove instability, update clipping per- forms better in terms of zero-shot ImageNet accuracy. With update or gradient clipping, higher β2 such as 0.99 tends to perform better. Appendix E provides further commentary and imple- mentation considerations for StableAdamW. with spikes in the activations (i.e., features) and gradi- ents. As we’ve previously seen (Figure 5), high feature magnitudes can pose challenges for low-precision train- ing. Moreover, the spikes in the gradient are so large that Inf/NaN values occur, which results in the loss scalar [40] dropping many times. There are a few takeaways from this observation.First, reducing loss spikes is an important step to enabling low-precision training. Second, spikes in gradient magnitude can be transient and therefore we may be adjusting the loss scalar too often—if using the PyTorch default loss scalar, thousands of iterations would be required before the loss scalar recovered to its value before this event. Finally, the layers highlighted in this figure are the main layers where Inf/NaN are encountered. Concretely, while we only track every tenth block, we never observe any Inf/NaN for any transformer block greater than 0. However, with the PyTorch default loss scalar an Inf/NaN in a single layer will skip the update for the whole network. # 3.6 Loss spikes and the loss scalar This final Section ties the low precision training re- sults 2 with our investigation into stability. Overall we find that loss spikes can co-occur with large activa- tions and gradients. Large activations and gradients may cause issues during low precision training due to a more limited representible range. Therefore, reduc- ing loss spikes is an important step for successful low precision training. Supporting data is illustrated by Figure 11, in which an RMS spike precedes a loss spikes which coincides 4We clip at global norm 1. We observed instability when trying 2 instead of 1. We did not tune this further, but note that 1.0 is standard in, e.g., PaLM [11], and Scaling Vision Transformers [70]. This motivates the loss scalar that we use in our exper- iments when one is required (except for in Figure 11). We use a loss scalar which i) checks for Inf/NaN at the individual tensor level and skips the update at the tensor level—not globally, and ii) remains fixed at its initial value. This scalar allows fp16 mixed precision training for CLIP models at ViT-Huge scale where previously the scalar became too low and training diverged [9]. We also believe an adaptive block-wise scalar as in Ramesh et al. [48] would remedy this issue. One interesting remark is that often when we observe an Inf/NaN, it is in the patch embedding layer. Therefore, in the case where Inf/NaN’s happen frequently it recovers the stability solution of Chen et al. [8] which is to 12 26 i Vvisual.transformer.resblocks.20 H L x 30 H 24 H 5 os £ : a i 8 Eos : $22 i 8 2 g H a 2 20 | 20 { } ° | weary 1s j 18 a a! ee EE re 2900 2925 2950 2975 3000 2900 2925 2950 2975 3000 2900 2925 2950 2975 3000 Iteration Iteration Iteration 6 [lisual.convi.weight 9 [visual.class_embedding 10° {Visual.transformer.resblocks.0.attn.in_proj_weight i x x ] i é é | wv 4 Hl § 5 107? ‘ 2 i 8 107 ic i 3 3 2 id © 9-2 6 § 10 ; WM Lf a0 0 2900 2925 2950 2975 3000 2900 2925 2950 2975 3000 2900 2925 2950 2975 3000 Iteration Iteration Iteration --- RMS spike in embedding layer which preceeds loss spike | --~ Inf gradient causing grad scaler decrease Figure 11: Avoiding loss spikes is helpful for low precision training. As shown in this figure, loss spikes can coincide with with activation spikes and gradient spikes. Large activations/gradients can cause issues during low precision training due to a more limited representible range [17]. freeze the embedding layer. As a final remark, we note that loss spikes do not always cause the loss scalar to drop, and emphasize the loss scalar can drop for various other reasons than spikes. Figure 11 is just an existence example that loss spikes can result in activation spikes and Inf/NaN gradients. # Acknowledgements For insightful discussions we thank Romain Beaumont, Yair Carmon, Mehdi Cherti, Brian Cheung, Alex Fang, Gabriel Ilharco, Jenia Jitsev, LAION, Sarah Pratt, Christoph Schuhmann, Ross Whightman, and Sho Yaida. We thank Emad Mostaque and stability.ai for compute resources. This work is in part supported by NSF IIS 1652052, IIS 17303166, DARPA N66001-19-2-4031, DARPA W911NF- 15-1-0543 and gifts from Allen Institute for Artificial In- telligence. # 4 Conclusion In summary, we have shared experiments in accelerat- ing and stabilizing large multi-modal model training which we believe will be useful to the community. Moreover, we have shared resources such as triton kernels to enable building and improving on our work. We believe the main limitation of our work is that it is non-exhaustive. For instance, we only simulate float8 training. Second, we do not examine the im- pact on stability of width scalings for initialization and training hyperparameters such as those examined by [19]. Finally, a limitation is that the checkpoints we produce have low accuracy. This is due to the limited compute budget that we use – our aim was to study loss spikes across multiple trials at scale and not attain competitive model performance. A redeem- ing aspect is that our early exploration informed the training hyperparameters which produced the highest accuracy open-source CLIP model so far [64]. References [1] Thomas Bachlechner, Bodhisattwa Prasad Majumder, Henry Mao, Gary Cottrell, and Julian McAuley. Rezero is all you need: Fast convergence at large depth. In Uncertainty in Artificial Intelligence, pages 1352–1361. PMLR, 2021. [2] Haoli Bai, Wei Zhang, Lu Hou, Lifeng Shang, Jing Jin, Xin Jiang, Qun Liu, Michael R. Lyu, and Irwin King. Binarybert: Pushing the limit of bert quantization. ArXiv, abs/2012.15701, 2021. [3] Charlie Blake, Douglas Orr, and Carlo Luschi. Unit scaling: Out-of-the-box low-precision training. arXiv preprint arXiv:2303.11257, 2023. [4] Andy Brock, Soham De, Samuel L Smith, and Karen Simonyan. High-performance large-scale image recognition without normalization. In International Conference on Machine Learning, pages 1059–1071. PMLR, 2021. 13 [5] 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, et al. Language models are few-shot learners. In Advances in Neural Information Processing Systems (NeurIPS), 2020. https://arxiv.org/abs/2005.14165. [6] L´eopold Cambier, Anahita Bhiwandiwalla, Ting Gong, Oguz H. Elibol, Mehran Nekuii, and Han- lin Tang. Shifted and squeezed 8-bit floating point format for low-precision training of deep neural net- works. 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=Bkxe2AVtPS. [7] Xiangning Chen, Chen Liang, Da Huang, Esteban Real, Kaiyuan Wang, Yao Liu, Hieu Pham, Xuanyi Dong, Thang Luong, Cho-Jui Hsieh, et al. Symbolic discovery of optimization algorithms. arXiv preprint arXiv:2302.06675, 2023. [8] Xinlei Chen, Saining Xie, and Kaiming He. An empir- ical study of training self-supervised vision transform- ers. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 9640–9649, 2021. [9] Mehdi Cherti, Romain Beaumont, Ross Wightman, Mitchell Wortsman, Gabriel Ilharco, Cade Gor- don, Christoph Schuhmann, Ludwig Schmidt, and Jenia Jitsev. Reproducible scaling laws for con- arXiv preprint trastive language-image learning. arXiv:2212.07143, 2022. [10] Minsik Cho, Keivan A Vahid, Saurabh Adya, and Mohammad Rastegari. Dkm: Differentiable k-means clustering layer for neural network compression. arXiv preprint arXiv:2108.12659, 2021. [11] Aakanksha Chowdhery, Sharan Narang, Jacob De- vlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sut- ton, Sebastian Gehrmann, et al. Palm: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311, 2022. [12] Jeremy M Cohen, Behrooz Ghorbani, Shankar Kr- ishnan, Naman Agarwal, Sourabh Medapati, Michal Badura, Daniel Suo, David Cardoze, Zachary Nado, George E Dahl, et al. Adaptive gradient methods at the edge of stability. arXiv preprint arXiv:2207.14484, 2022. [13] Matthieu Courbariaux, Yoshua Bengio, and Jean- Pierre David. Binaryconnect: Training deep neural networks with binary weights during propagations. In Corinna Cortes, Neil D. Lawrence, Daniel D. Lee, 14 Masashi Sugiyama, and Roman Garnett, editors, Ad- vances in Neural Information Processing Systems 28: Annual Conference on Neural Information Processing Systems 2015, December 7-12, 2015, Montreal, Quebec, Canada, pages 3123–3131, 2015. URL https: //proceedings.neurips.cc/paper/2015/hash/ 3e15cc11f979ed25912dff5b0669f2cd-Abstract. html. [14] Mostafa Dehghani, Josip Djolonga, Basil Mustafa, Piotr Padlewski, Jonathan Heek, Justin Gilmer, Andreas Steiner, Mathilde Caron, Robert Geirhos, Ibrahim Alabdulmohsin, et al. Scaling vision trans- formers to 22 billion parameters. arXiv preprint arXiv:2302.05442, 2023. [15] Jia Deng, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. Imagenet: A large-scale hierarchical image database. In Conference on Computer Vision and Pattern Recognition, 2009. https://ieeexplore. ieee.org/document/5206848. [16] Tim Dettmers and Luke Zettlemoyer. The case for 4-bit precision: k-bit inference scaling laws. arXiv preprint arXiv:2212.09720, 2022. [17] Tim Dettmers, Mike Lewis, Younes Belkada, and Luke Zettlemoyer. Llm. int8 (): 8-bit matrix mul- tiplication for transformers at scale. arXiv preprint arXiv:2208.07339, 2022. [18] Tim Dettmers, Mike Lewis, Sam Shleifer, and Luke Zettlemoyer. 8-bit optimizers via block-wise quan- tization. 9th International Conference on Learning Representations, ICLR, 2022. [19] Emily Dinan, Sho Yaida, and Susan Zhang. Effective theory of transformers at initialization. arXiv preprint arXiv:2304.02034, 2023. [20] Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszko- reit, and Neil Houlsby. An image is worth 16x16 words: Transformers for image recognition at scale. In International Conference on Learning Representa- tions (ICLR), 2021. https://arxiv.org/abs/2010. 11929. [21] Mario Drumond, Tao Lin, Martin Jaggi, and Babak Falsafi. Training dnns with hybrid block floating point. In Samy Bengio, Hanna M. Wallach, Hugo Larochelle, Kristen Grauman, Nicol`o Cesa-Bianchi, and Roman Garnett, editors, Advances in Neu- ral Information Processing Systems 31: Annual Conference on Neural Information Processing Systems 2018, NeurIPS 2018, December 3-8, 2018, Montr´eal, Canada, pages 451–461, 2018. URL https: //proceedings.neurips.cc/paper/2018/hash/ 6a9aeddfc689c1d0e3b9ccc3ab651bc5-Abstract. html. [22] John Duchi, Elad Hazan, and Yoram Singer. Adaptive subgradient methods for online learning and stochas- tic optimization. Journal of machine learning re- search, 12(7), 2011. [23] Angela Fan, Pierre Stock, Benjamin Graham, Edouard Grave, R´emi Gribonval, Herve Jegou, and Armand Joulin. Training with quantization noise for extreme model compression. arXiv preprint arXiv:2004.07320, 2020. [24] Elias Frantar, Saleh Ashkboos, Torsten Hoefler, and Dan Alistarh. Gptq: Accurate post-training quanti- zation for generative pre-trained transformers. arXiv preprint arXiv:2210.17323, 2022. [25] Justin Gilmer, Andrea Schioppa, and Jeremy Co- Intriguing properties of transformer training hen. instabilities. To appear. [26] Xavier Glorot and Yoshua Bengio. Understanding the difficulty of training deep feedforward neural networks. In Proceedings of the thirteenth international confer- ence on artificial intelligence and statistics, pages 249–256. JMLR Workshop and Conference Proceed- ings, 2010. [27] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Delving deep into rectifiers: Surpassing human-level performance on imagenet classification. In Proceedings of the IEEE international conference on computer vision, pages 1026–1034, 2015. [28] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Deep residual learning for image recognition. In Conference on Computer Vision and Pattern Recogni- tion (CVPR), 2016. https://arxiv.org/abs/1512. 03385. [29] Gabriel Ilharco, Mitchell Wortsman, Ross Wight- man, Cade Gordon, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, Hongseok Namkoong, John Miller, Hannaneh Hajishirzi, Ali Farhadi, and Ludwig Schmidt. Openclip, July 2021. URL https: //doi.org/10.5281/zenodo.5143773. If you use this software, please cite it as below. [30] Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, Matthew Tang, Andrew Howard, Hartwig Adam, and Dmitry Kalenichenko. Quantization and training of neural networks for efficient integer-arithmetic- only inference. arxiv e-prints, art. arXiv preprint arXiv:1712.05877, 2017. [31] Daya Khudia, Jianyu Huang, Protonu Basu, Sum- mer Deng, Haixin Liu, Jongsoo Park, and Mikhail Smelyanskiy. Fbgemm: Enabling high-performance low-precision deep learning inference. arXiv preprint arXiv:2101.05615, 2021. [32] Sehoon Kim, Amir Gholami, Zhewei Yao, Michael W Mahoney, and Kurt Keutzer. I-bert: Integer-only bert quantization. In International conference on machine learning, pages 5506–5518. PMLR, 2021. [33] Diederik P Kingma and Jimmy Ba. Adam: A method for stochastic optimization. In International Con- ference on Learning Representations (ICLR), 2014. https://arxiv.org/abs/1412.6980. [34] Manoj Kumar, Mostafa Dehghani, and Neil Houlsby. Dual patchnorm. arXiv preprint arXiv:2302.01327, 2023. [35] Yanghao Li, Haoqi Fan, Ronghang Hu, Christoph Feichtenhofer, and Kaiming He. Scaling language- image pre-training via masking. arXiv preprint arXiv:2212.00794, 2022. [36] Ilya Loshchilov and Frank Hutter. Sgdr: Stochas- tic gradient descent with warm restarts. In In- ternational Conference on Learning Representations (ICLR), 2016. https://arxiv.org/abs/1608.03983. [37] Ilya Loshchilov and Frank Hutter. Decoupled weight decay regularization. In International Conference on Learning Representations (ICLR), 2019. https: //openreview.net/forum?id=Bkg6RiCqY7. [38] Naveen Mellempudi, Sudarshan Srinivasan, Dipankar Das, and Bharat Kaul. Mixed precision training with 8-bit floating point. CoRR, abs/1905.12334, 2019. URL http://arxiv.org/abs/1905.12334. [39] Paulius Micikevicius, Sharan Narang, Jonah Al- ben, Gregory Diamos, Erich Elsen, David Garcia, Boris Ginsburg, Michael Houston, Oleksii Kuchaiev, Ganesh Venkatesh, et al. Mixed precision training. arXiv preprint arXiv:1710.03740, 2017. [40] Paulius Micikevicius, Dusan Stosic, Neil Burgess, Marius Cornea, Pradeep Dubey, Richard Grisenth- waite, Sangwon Ha, Alexander Heinecke, Patrick Judd, John Kamalu, et al. Fp8 formats for deep learning. arXiv preprint arXiv:2209.05433, 2022. [41] Igor Molybog, Peter Albert, Moya Chen, Zachary DeVito, David Esiobu, Naman Goyal, Punit Singh Koura, Sharan Narang, Andrew Poulton, Ruan Silva, et al. A theory on adam instability in large-scale machine learning. arXiv preprint arXiv:2304.09871, 2023. 15 [42] Gunho Park, Baeseong Park, Se Jung Kwon, Byeong- wook Kim, Youngjoo Lee, and Dongsoo Lee. nuqmm: Quantized matmul for efficient inference of large- scale generative language models. arXiv preprint arXiv:2206.09557, 2022. [43] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, et al. Pytorch: An imperative style, high- performance deep learning library. In Advances in Neural Information Processing Systems (NeurIPS), 2019. https://arxiv.org/abs/1912.01703. [44] Hieu Pham, Zihang Dai, Golnaz Ghiasi, Hanxiao Liu, Adams Wei Yu, Minh-Thang Luong, Mingxing Tan, and Quoc V. Le. Combined scaling for zero- shot transfer learning, 2021. https://arxiv.org/ abs/2111.10050. [45] Haotong Qin, Ruihao Gong, Xianglong Liu, Xiao Bai, Jingkuan Song, and Nicu Sebe. Binary neural networks: A survey. CoRR, abs/2004.03333, 2020. URL https://arxiv.org/abs/2004.03333. [46] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sas- try, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, and Ilya Sutskever. Learning transferable visual models from natural language su- pervision. In International Conference on Machine Learning (ICML), 2021. https://arxiv.org/abs/ 2103.00020. [47] Jack W Rae, Sebastian Borgeaud, Trevor Cai, Katie Millican, Jordan Hoffmann, Francis Song, John Aslanides, Sarah Henderson, Roman Ring, Susannah Young, et al. Scaling language models: Methods, anal- ysis & insights from training gopher. arXiv preprint arXiv:2112.11446, 2021. [48] Aditya Ramesh, Mikhail Pavlov, Gabriel Goh, Scott Gray, Chelsea Voss, Alec Radford, Mark Chen, and Ilya Sutskever. Zero-shot text-to-image generation. In International Conference on Machine Learning, pages 8821–8831. PMLR, 2021. [49] Aditya Ramesh, Prafulla Dhariwal, Alex Nichol, Casey Chu, and Mark Chen. Hierarchical text- conditional image generation with clip latents. arXiv preprint arXiv:2204.06125, 2022. [50] Sashank J Reddi, Satyen Kale, and Sanjiv Kumar. On the convergence of adam and beyond. arXiv preprint arXiv:1904.09237, 2019. [51] Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser, and Bj¨orn Ommer. High- resolution image synthesis with latent diffusion mod- In Proceedings of the IEEE/CVF Conference els. 16 on Computer Vision and Pattern Recognition, pages 10684–10695, 2022. [52] Teven Le Scao, Angela Fan, Christopher Akiki, El- lie Pavlick, Suzana Ili´c, Daniel Hesslow, Roman Castagn´e, Alexandra Sasha Luccioni, Fran¸cois Yvon, Matthias Gall´e, et al. Bloom: A 176b-parameter open- access multilingual language model. arXiv preprint arXiv:2211.05100, 2022. [53] Christoph Schuhmann, Romain Beaumont, Richard Vencu, Cade Gordon, Ross Wightman, Mehdi Cherti, Theo Coombes, Aarush Katta, Clayton Mullis, Mitchell Wortsman, et al. Laion-5b: An open large- scale dataset for training next generation image-text models. arXiv preprint arXiv:2210.08402, 2022. [54] Noam Shazeer and Mitchell Stern. Adafactor: Adap- tive learning rates with sublinear memory cost. In International Conference on Machine Learning, pages 4596–4604. PMLR, 2018. [55] Sheng Shen, Zhen Dong, Jiayu Ye, Linjian Ma, Zhewei Yao, Amir Gholami, Michael W Mahoney, and Kurt Keutzer. Q-bert: Hessian based ultra low precision quantization of bert. In Proceedings of the AAAI Conference on Artificial Intelligence, vol- ume 34, pages 8815–8821, 2020. [56] Xiao Sun, Jungwook Choi, Chia-Yu Chen, Naigang Wang, Swagath Venkataramani, Vijayalakshmi Srinivasan, Xiaodong Cui, Wei Zhang, and Kailash Gopalakrishnan. Hybrid 8-bit floating point (HFP8) training and inference for deep neural networks. In Hanna M. Wallach, Hugo Larochelle, Alina Beygelzimer, Florence d’Alch´e-Buc, Emily B. Fox, and Roman Garnett, editors, Advances in Neural Information Processing Systems 32: Annual Confer- ence on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada, pages 4901–4910, 2019. URL https: //proceedings.neurips.cc/paper/2019/hash/ 65fc9fb4897a89789352e211ca2d398f-Abstract. html. [57] Philippe Tillet, Hsiang-Tsung Kung, and David Cox. Triton: an intermediate language and compiler for tiled neural network computations. In Proceedings of the 3rd ACM SIGPLAN International Workshop on Machine Learning and Programming Languages, pages 10–19, 2019. [58] Hugo Touvron, Matthieu Cord, Alexandre Sablay- rolles, Gabriel Synnaeve, and Herv´e J´egou. Going deeper with image transformers. In Proceedings of the IEEE/CVF International Conference on Computer Vision, pages 32–42, 2021. [59] Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timoth´ee Lacroix, Baptiste Rozi`ere, Naman Goyal, Eric Ham- bro, Faisal Azhar, et al. Llama: Open and effi- cient foundation language models. arXiv preprint arXiv:2302.13971, 2023. [60] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. Advances in neural information processing sys- tems, 30, 2017. [61] Naigang Wang, Jungwook Choi, Daniel Brand, Chia-Yu Chen, and Kailash Gopalakrishnan. Training deep neural networks with 8-bit float- ing point numbers. In S. Bengio, H. Wallach, H. Larochelle, K. Grauman, N. Cesa-Bianchi, and R. Garnett, editors, Advances in Neural Infor- mation Processing Systems, volume 31. Curran Associates, Inc., 2018. URL https://proceedings. neurips.cc/paper_files/paper/2018/file/ 335d3d1cd7ef05ec77714a215134914c-Paper.pdf. [62] Naigang Wang, Jungwook Choi, Daniel Brand, Chia-Yu Chen, and Kailash Gopalakrishnan. Train- ing deep neural networks with 8-bit floating point numbers. In Samy Bengio, Hanna M. Wallach, Hugo Larochelle, Kristen Grauman, Nicol`o Cesa-Bianchi, and Roman Garnett, editors, Advances in Neural Information Processing Systems 31: Annual Con- ference on Neural Information Processing Systems 2018, NeurIPS 2018, December 3-8, 2018, Montr´eal, URL https: Canada, pages 7686–7695, 2018. //proceedings.neurips.cc/paper/2018/hash/ 335d3d1cd7ef05ec77714a215134914c-Abstract. html. efficient post-training quantization for large language models. arXiv preprint arXiv:2211.10438, 2022. [67] Zhewei Yao, Reza Yazdani Aminabadi, Minjia Zhang, Xiaoxia Wu, Conglong Li, and Yuxiong He. Zero- quant: Efficient and affordable post-training quan- tization for large-scale transformers. arXiv preprint arXiv:2206.01861, 2022. [68] Aohan Zeng, Xiao Liu, Zhengxiao Du, Zihan Wang, Hanyu Lai, Ming Ding, Zhuoyi Yang, Yifan Xu, Wendi Zheng, Xiao Xia, et al. Glm-130b: An open bilingual pre-trained model. arXiv preprint arXiv:2210.02414, 2022. [69] Shuangfei Zhai, Tatiana Likhomanenko, Etai Littwin, Dan Busbridge, Jason Ramapuram, Yizhe Zhang, Jiatao Gu, and Josh Susskind. Stabilizing trans- former training by preventing attention entropy col- lapse. arXiv preprint arXiv:2303.06296, 2023. [70] Xiaohua Zhai, Alexander Kolesnikov, Neil Houlsby, and Lucas Beyer. Scaling vision transformers, 2021. https://arxiv.org/abs/2106.04560. [71] Xiaohua Zhai, Basil Mustafa, Alexander Kolesnikov, and Lucas Beyer. Sigmoid loss for language image pre-training. arXiv preprint arXiv:2303.15343, 2023. [72] Hongyi Zhang, Yann N Dauphin, and Tengyu Ma. Fixup initialization: Residual learning without nor- malization. arXiv preprint arXiv:1901.09321, 2019. [73] Susan Zhang. Open pretrained transformers lec- https://www.youtube.com/watch?v= ture, 2023. p9IxoSkvZ-M. [74] Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen, Christopher Dewan, Mona Diab, Xian Li, Xi Victoria Lin, et al. Opt: Open pre-trained transformer language models. arXiv preprint arXiv:2205.01068, 2022. [63] Shibo Wang and Pankaj Kanwar. to high performance 2019. Bfloat16: on cloud https://cloud.google. The tpus. com/blog/products/ai-machine-learning/ bfloat16-the-secret-to-high-performance-on-cloud-tpus. secret [64] Mitchell Wortsman. with openclip, 2023. giant-openclip/. Reaching 80% accuracy https://laion.ai/blog/ [75] Wei Zhang, Lu Hou, Yichun Yin, Lifeng Shang, Xiao Chen, Xin Jiang, and Qun Liu. Ternarybert: Distillation-aware ultra-low bit bert. In EMNLP, 2020. [65] Mitchell Wortsman, Gabriel Ilharco, Samir Ya Gadre, Rebecca Roelofs, Raphael Gontijo-Lopes, Ari S Mor- cos, Hongseok Namkoong, Ali Farhadi, Yair Car- mon, Simon Kornblith, et al. Model soups: averag- ing weights of multiple fine-tuned models improves accuracy without increasing inference time. In In- ternational Conference on Machine Learning, pages 23965–23998. PMLR, 2022. [66] Guangxuan Xiao, Ji Lin, Mickael Seznec, Julien De- mouth, and Song Han. Smoothquant: Accurate and [76] Changsheng Zhao, Ting Hua, Yilin Shen, Qian Lou, and Hongxia Jin. Automatic mixed-precision quantization search of bert. arXiv preprint arXiv:2112.14938, 2021. [77] Kang Zhao, Sida Huang, Pan Pan, Yinghan Li, Yingya Zhang, Zhenyu Gu, and Yinghui Xu. Dis- tribution adaptive int8 quantization for training cnns. In Proceedings of the Thirty-Fifth AAAI Conference on Artificial Intelligence, 2021. 17 [78] Chenzhuo Zhu, Song Han, Huizi Mao, and William J. Dally. Trained ternary quantization. In 5th Interna- tional Conference on Learning Representations, ICLR 2017, Toulon, France, April 24-26, 2017, Confer- ence Track Proceedings. OpenReview.net, 2017. URL https://openreview.net/forum?id=S1_pAu9xl. [79] Feng Zhu, Ruihao Gong, Fengwei Yu, Xianglong Liu, Yanfei Wang, Zhelong Li, Xiuqi Yang, and Junjie Yan. Towards unified int8 training for convolutional neural network. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 1969–1979, 2020. 18 # A Additional Related Work on Quantization The literature on training neural networks in low-bit precision is vast. The main differentiating factor of our work is that we train relatively large models – in fact, we train the largest 8-bit vision transformers to date. The literature agrees that quantization of very large networks is more difficult than for smaller networks [18, 17, 66, 24]. As such, we divide our related work into three parts: (1) large-scale low-precision neu- ral network (larger than BERT-large), and (2) low- precision training of smaller networks. Large-scale Low-precision Neural Networks. Our work is currently the only work that does low- precision (8-bit and below) training of very large net- works with more than 230M parameters. Other re- lated work studies inference at scale. SmoothQuant [66], ZeroQuant [67], NuQmm [42], and LLM.int8() [17] study inference with Int8 matrix multiplication. Another line of work studies large models inference with more than 250M parameters by considering 16- bit inputs and k-bit weights [16, 24, 68]. Small Scale Low-precision Training Training of small-scale low-precision neural networks can take many shapes and forms, such as quantization for in- teger only devices, quantization for mobile device, or quantization to accelerate training. One way to break up these directions is through the data type used and the neural network trained. One major direction is to quantize convolutional neural networks often for fast and memory efficient usage on edge devices [78, 6, 13, 79, 23, 77, 30]. Further work in this area is discussed in the survey by [45]. Another line of work is centered around 8-bit float data types which can be used to accelerate training of neural networks [21, 56, 62, 38, 3]. Lastly, a common application is to finetune (similar to training) BERT models to par- ticular datasets. This not only decreases the model footprint and increases inference speed but adjusts the model to new data [2, 32, 75, 55, 76]. # B Additional code and figures # B.1 Additional Code This Section provides additional pseudocode: • Algorithm 3 is the memory effecient variant of SwitchBack. • Algorithm 4 is the variant of SwitchBack which uses row- and column-wise quantization for the weights. • Algorithm 5 is a standard linear layer imple- mented with torch.autograd. These implementations can be found at https: //github.com/TimDettmers/bitsandbytes/ blob/main/bitsandbytes/nn/triton_based_ modules.py. To use in OpenCLIP training (https://github.com/mlfoundations/open_clip), add the argument: • --use-bnb-linear SwitchBackLinearGlobal for Algorithm 1. • --use-bnb-linear SwitchBackLinearGlobalMemEfficient for Algorithm 3. • --use-bnb-linear SwitchBackLinearVectorwise for Algorithm 4. • --use-bnb-linear StandardLinear for Algo- rithm 5. # B.2 Additional Figures This section presents additional figures. • Figure 12 presents a more fine-grained version of Figure 3. • Figure 13 compares the speed-up of SwitchBack compared to LLM.int8(). • Figure 14 shows the mean and max for the gra- dient and activation (i.e., feature) throughout training. • Figure 15 shows that using a schedule for β2 of the form 1 − iteration−λ does not improve accuracy. # C Analysis Consider a matrix multiplication U V for U ∈ Rn×k and V ∈ Rk×m. This matmul consists of computing inner products between vectors of length k. This section shows that error due to quantization increases with k. This suggests why SwitchBack may achieve high accuracy, as we avoid quantizing matmuls for which k is very large. For the weight gradient computation, which we leave in high precision, k is 19 an Standard fpi6 (sum of parts) so Uinear layer, batch * sdquence length = 32k, 35 {Uinear layer summary, varying dimensions —e— SwitchBack int8 (sum of parts) “k- Matmul XW (standard) 30 Matmul GW (standard) 40 . Matmul G*TX (both) a $25 Int8 Matmul XW (switchback) E 30 3 Int8 Matmul GW (switchback) o g 20 Row-wise quantize X (switchback) € 20 ra si : . s 15 Row-wise quantize G (Switchback) ° —s— batch * sequence length = 16384 —+- Tensor quantize W (switchback) Jensor quantize and 10 10 —*— batch * sequence length = 32768 —= transpose W (switchback) -_ —*— batch * sequence length = 65536 0 ee 5 —* batch * sequence length = 131072 1024 2048 4096 1024 2048 4096 dim dim Figure 12: A more fine-grained version of Figure 3. To reproduce this figure see https://github.com/TimDettmers/ bitsandbytes/tree/main/benchmarking/switchback. “A> speedup over LLM.int8() 54.0 * ViT-Base ViT-Large ViT-Huge Figure 13: Benchmarking speedups of SwitchBack compared to LLM.int8() [17] for end-to-end CLIP training on a single node (with 4 A100 GPUs, per-GPU batch size 128, and gradient checkpointing) for various model sizes when replacing all linear operations in the transformer (i.e., key, query, value, and out projections as well as the MLP). 20 # ViT-Huge, no layer scale ViT-Huge, no layer scale 5 10 8 [enema Bf -——~—}+—_}| | re] 5 i el : 2 10-7 3 = 10-2 0 2500 5000 7500 10000 12500 15000 17500 20000 Iteration ViT-Huge, layer scale init 0 § 10-7 1 3 2 10 z : 2 io- 10-7 a = 10-2 0 2500 5000 7500 10000 12500 15000 17500 20000 Iteration ViT-Large, no layer scale S ) 5 RI | w 10-5 — == es es z i f f A 2 10-7 3 = 10-2 0 2500 5000 7500 10000 12500 15000 17500 20000 Iteration ViT-Large, layer scale init 0 § 10-7 = 8 2 10-5 z A S 10-7 a = 10-2 0 2500 5000 7500 10000 12500 15000 17500 20000 Iteration — Block .0max = — Block10max 10? 2 s* 101 10° at it t | B92 3 3 § 2 2 5 : 0 2500 ©5000 ©7500 10000 12500 15000 17500 20000 Iteration # ViT-Huge, layer scale init 0 3 10? 2 yl 10% 0 t H " 10 — 1} io ee | + | i972 i een 8 3 2 2 5 5 5 s & - 0 2500 ©5000 ©7500 10000 12500 15000 17500 20000 Iteration ViT-Large, no layer scale 10? 10? 10% 10° —- | | + + 4 B19 3 # xy 8 2 2 z 5 : 0 2500 ©5000 ©7500 10000 12500 15000 17500 # Iteration # scale init 0 ViT-Large, layer 3 10? 8 2 x 3 2 10% z 5 0 5 lo eerie | % [lee { | | < ; | | t | 8 192 t 1 4 F 0 2500 ©5000 ©7500 10000 12500 15000 17500 # Iteration # Block .0 mean # Block 10 mean =—— # = —— Block 20 mean # Block20max # Block 30 max # Block 30 mean Figure 14: The mean and max for (left) the gradient to the MLP weight and (right) the output of a transformer block throughout training. Different rows correspond to different choice of model size and layer scale. 21 20000 20000 # Algorithm 3 Memory efficient SwitchBackM class SwitchBackMMatmul(autograd.Function): @staticmethod def forward(ctx, X, W): # X [b, n] inputs # W [n, m] weights X_int8, state_X = row-wise_quantize(X) del X W_int8, state_W = tensor-wise_quantize(W) # save tensors in ctx ctx.save = X_int8, state_X, W_int8, state_W # Return output return matmul_int8_and_dequanitze( X_int8, W_int8.t(), state_X, state_W ) @staticmethod def backward(ctx, G): # G [b, m] gradient to output # Recover tensors from ctx X_int8, state_X, W_int8, state_W = ctx.save X = dequantize_row-wise(X_int8, state_X) del X_int8 W_gradient = matmul_fp16(G.t(), X) del X G_int8 = row-wise_quantize(G) del G W_int8 = W_int8.t().contiguous() # Use 8bit matmul only for X_gradient X_gradient = matmul_int8_and_dequanitze( G_int8, W_int8.t(), state_X, state_W ) return X_gradient, W_gradient Algorithm 4 SwitchBack with row-wise and column- wise quantization for the weights SwitchBackQ class SwitchBackQMatmul(autograd.Function): @staticmethod def forward(ctx, X, W): # X [b, n] inputs # W [n, m] weights # save tensors in ctx ctx.save_for_backward = X, W X_int8, state_X = row-wise_quantize(X) W_int8, state_W = row-wise_quantize(W) # Return output return matmul_int8_and_dequanitze( X_int8, W_int8.t(), state_X, state_W ) @staticmethod def backward(ctx, G): # G [b, m] gradient to output # Recover tensors from ctx X, W = ctx.save_for_backward G_rowwise = rowwise_quantize(G) W_int8, state_W = column-wise_quantize_transpose(W) # Use 8bit matmul only for X_gradient X_gradient = matmul_int8_and_dequanitze( G_int8, W_int8.t(), state_X, state_W ) W_gradient = matmul_fp16(G.t(), X) return X_gradient, W_gradient class SwitchBackQLinear(nn.Linear): class SwitchBackQLinear(nn.Linear): def forward(self, X): return SwitchBackQMatmul.apply(X, self.weight) # class SwitchBackMLinear(nn.Linear): # def forward(self, X): # return SwitchBackMMatmul.apply(X, self.weight) batch size times sequence length, which is often ≈ 32000 in our experiments. For the other operations which comprise a matmul, k is less than 4 · embed dim which is ≤ 8000 in our experiments. These dimensions are standard for CLIP training experiments [46, 9]. vative because we do not assume the variance of ϵi, ξi increase with k, though in practice we believe they would as the absmax of u and v increases with k. # C.1 Analyzing variance due to quanti- zation for inner products We first examine the variance of ˆuiˆvi. By using that all random variable are mean centered, this variance is given by, This section measures the variance due to quantization for the inner product between u and v. Let u, v be vectors of length k vectors with each element drawn i.i.d. from a distribution with mean 0. Let ui have variance σ2 Next, let ˆu and ˆv be the quantized versions of u and v, respectively. We model quantization error as ˆui = ui + ϵi and ˆvi = vi + ξi where ϵi, ξi are i.i.d. mean centered random variables with variance σ2 q . Var(a;d;) = E [(a6;)" (7) = E[((ui + &)- (wi + &))?] E |(uju; + ev; + &ui t ei) | EE [uzu? + e?u? + €7u? 4 | Var(uivi) + o9(02 +03 +07). (8) (9) i + ξ2 q (σ2 i u2 u + σ2 (10) (11) The aim of this section is to show that variance due to quantization grows with k. Our analysis is conser- Next, we use linearity of variance for independent random variables to calculate Var (⟨ˆu, ˆv⟩). This is 22 Algorithm 5 A standard linear layer implemented with torch.autograd class StandardLinearMatmul(autograd.Function): @staticmethod def forward(ctx, X, W): # X [b, n] inputs # W [n, m] weights # save tensors in ctx ctx.save_for_backward = X, W # Return output return torch.matmul(X, W.t()) @staticmethod def backward(ctx, G): # G [b, m] gradient to output # Recover tensors from ctx X, W = ctx.save_for_backward X_gradient = torch.matmul(G, W) W_gradient = torch.matmul(G.t(), X) return X_gradient, W_gradient class StandardLinear(nn.Linear): # def forward(self, X): return StandardLinearMatmul.apply(X, self.weight) given by, k Var ((a, 6)) = Ss Var(ti;6;) (12) i=1 k k = Ss Var(ujui) + Ss oa(on +05 +07) i=1 i=1 (13) (13) = Var (⟨u, v⟩) + k · σ2 q (σ2 u + σ2 v + σ2 q ). (14) # C.2 Takeaways We have shown that for inner products with length k vectors, variance due to quantization increases with k. This means the variance of output units/features due to quantization increases with k which can thought of making the outputs more noisy. Noise compounds throughout the network and will eventually drown out useful signal—for large k the network features or gradient will no longer lead to effective learning. # C.3 Why LLM.int8() fails: LLMs vs CLIP models This Section details our hypothesis for why Switch- Back outperforms LLM.int8() for CLIP training, which is conditioned on the analysis in Section C.1 being a good model for training. 23 ie ViT-Huge © 58.0 3 th % 57.5 ——o oO @ 57.0 3 om 56.5 oO = 56.0 2 2 55.5 —t- + update clipping n —® + update clipping + beta2 warmup £ 55.014 1 1 1 Ky 0.98 0.985 0.99 0.995 Beta2 Figure 15: We try a schedule for β2 which is used in AdaFactor [54] and PaLM [11] and refer to the experiment as β2 warmup. This means that β2 at iteration k is 1 − iteration−λ. In this Figure we try λ = 0.45, 0.5, 0.65 and show on the x-axis β2 at the final iteration. This β2 warm- up does not improve accuracy in our setting. From our analysis we have shown that the variance in the output features increases with the size of the inner products of a quantized matrix multiplication com- pared to the full precision matrix multiplication. As such, we may have different failure modes for trans- formers pretrained on text, such as GPT-3 [5] or LLaMA [59], compared to CLIP models [46]. Pretrained large language models (LLMs) tend to have larger weight matrices relative to their batch sizes when compared to CLIP models. CLIP models per- form best when the batch size is large [46, 44, 9]. As a consequence, LLMs and CLIP models have their most noisy operations for different matrix multiplications. LLMs are most noisy in the forward pass XW T and during layer-to-layer back propagation ˙YkWk = ˙Xk−1 where inner product dimension are large, for example, they are 32768 and 8192 for the output projection of LLaMA 65B, 32768 and 8192. While the weight gradi- ent inner product size is determined by the per-GPU batch size, which is 2048 for LLaMA [59] (4M tokens per full batch distributed across 2048 GPUs). As such, if the quantization produces the same variance in quantization errors, then the weight gradient in LLM int8 training is between 4x and 16x less noisy if the analysis in Section C.1 is a good model for training. For CLIP training with ViT-Huge, we have a batch size of 65536 per GPU (256x images of size 224x224 inputs with patch size 14x14, leading to 16x16 patches for each images, resulting in 65536 patches per GPU). The dimensions for the weight matrices are 1280×5120. As such, analogous to above for the LLaMA LLM, the weight gradient in CLIP models is between 51.2x to 12.8x more noisy compared to the forward and layer- to-layer backpropagation operations if the analysis in Section C.1 is a good model for training. Notice that the CLIP weight gradient is twice as noisy compared to the most noisy LLaMA 65B operations if we assume that all quantization operations have the same error variance. As such, low-precision LLM training and CLIP re- quires high-precision quantization routines for differ- ent parts of the training. This also gives the reason why we believe LLM.int8() fails despite replicating inference performance – the weight gradient in CLIP training is a highly noisy operation which might not give enough signal to SGD to converge to a local minimum. # D RMS Spikes precede Loss Spikes This section further elaborate on the predictive re- lationship between an RMS spike in the embedding layer and a loss spike as in Figure 9. We define a heuristic to characterize loss and RMS spikes which we use for analysis. We determined these heuristics by checking if they qualitatively coincided with what appeared to be a loss spike. We display results in this Section so that the reader can also evaluate if these heuristics appear reasonable. We define RMS spikes events as {t : RMSt ≥ 2.3} while loss spike events are defined as the set of t where loss at time t exceeds the running mean by 3.2 times the running standard deviation. Finally, we ignore the first 1000 iterations when learning rate is low. We also deduplicate the RMS and loss spikes iterations as follows: multiple spikes over a short time interval of 10 iterations are only counted as one spike and start at the earliest time. Moreover, we only count a loss spike if there are multiple deviations in an interval of 10, which indicates that loss has meaningfully spiked. Our results are as follows: • Figure 16 observes that out of 15 total loss spikes for ViT-Huge across different β2, 14 out of 15 come 1-8 iterations after an RMS spike in the patch embedding layer (module.conv1.weight). With only 76 total RMS spike events, the proba- bility that a loss spike follows 1-8 iterations after an RMS spike by chance is < 1%. • Figure 17 repeats this analysis for ViT-Large, wherein 13 out of 15 loss spikes follow an RMS spike by 1-8 iterations. The probability that a loss spike follows an RMS spike by chance is 1.0%. • Figure 18 zooms in on Figure 16 to show addi- tional detail. • Figures 19 and 20 examine the cases where loss spikes fail to be detected in Figures 16 and 17, finding them to mainly be issues with the heuris- tic identifying loss spikes, i.e., false positive loss spikes. • Finally, Figure 21 repeats Figure 16 but examines the RMS of a random layer in the middle of the transformer—not the patch embedding layer. In this case, none of the loss spikes follow RMS spikes. # E StableAdamW continued # E.1 Q&A This Section asks and answers a series of questions the reader may have concerning Section 3.5. • First, why not just use AdaFactor? The answer is that the community has moved away from AdaFactor [11] as they find that AdaFactor under- performs AdamW at scale [47]. We believe this is likely due to the factored moments, and not other features such as update-clipping. The goal of this work is to advocate using a hybrid. We tried porting other features from AdaFactor to AdamW such as the β2 schedule but did not find them to help (Figure 15). Moreover, while PaLM uses an AdaFactor-AdamW hybrid, we believe they don’t use update clipping. • Another question is, why not use an optimizer such as Lion [7] which does not divide updates by any value, and is therefore immune to the stuck-in-the-past scenario. We believe this may be a promising path forward. However, while we observe that Lion outperforms AdamW at small scale, Lion still slightly under-performs AdamW for CLIP ViT-Huge scale in our experiments.5 5This may be out of date, track the latest https://github. com/mlfoundations/open_clip/pull/432. 24 • A final question is, why consider g2 t in the numer- t ? We also ator for computing RMSt and not v2 tried v2 t and found the performance worse. # E.2 Implementation considerations To prevent divide by 0 issues when computing RMS, we compute RMS, = \/E [g?/maximum(w;, €2)] where € is the AdamW hyperparamer for which we use le-6 and maximum is an elementwise maximum. This is instead of RMS; = \/E [9g?/uz]- 25 10.0 ViT-Huge, Beta2 = 0.99 [irHuge, Beta2 = 0.99] — Loss Loss spike 1-8 iterations after RMS spike (7 out of 7) Loss spike not 1-8 iterations after RMS spike (0 out of 7) Loss wu ° oO 2500 5000 7500 10000 12500 15000 17500 20000 (ViT-Huge, Beta2 = 0.99 A A ir Huge, Beta. —— RMS (visual.conv1.weight) RMS spike (total 25) oO 2500 5000 7500 10000 12500 15000 17500 20000 t (ViT-Hi , Beta2 = 0.98 ; Wittluge, Beta2 = 0.98) — Loss 75 : a : __, Loss spike 1-8 iterations 6 5.0 : after RMS spike (7 out of 8) - : : Loss spike not 1-8 iterations 2.5 : “* after RMS spike (1 out of 8) 0.0 + jt + t t + i 7 1 0 2500 5000 7500 10000 12500 15000 17500 20000 ViT-Huge, Beta2 = 0.98 = = —— RMS (visual.conv1.weight) RMS spike (total 41) wn = a2 oO oO 2500 5000 7500 10000 12500 15000 17500 20000 10.0 ViT-Huge, Beta2 = 0.95 1s — Loss vn Loss spike 1-8 iterations Q so “*" after RMS spike (0 out of 0) 3 4 4 . Loss spike not 1-8 iterations 2.5 “*** after RMS spike (0 out of 0) 0.0 oO 2500 5000 7500 10000 12500 15000 17500 20000 ViT-Hi , Beta2 = 0.95 . . 4 MitHuge, Beta? = 0.95) — RMS (visual.conv1 weight) RMS spike (total 10) oO 2500 5000 7500 10000 12500 15000 17500 20000 (ViT-Huge, Beta2 = 0.9 iT-Huge, Beta: Loss Loss spike 1-8 iterations a 6 5.0 “*** after RMS spike (0 out of 0) - Loss spike not 1-8 iterations 2.5 “* after RMS spike (0 out of 0) 0.0 2500 5000 7500 10000 12500 15000 17500 20000 ViT-Huge, Beta2 = 0.9 — 4 —— RMS (visual.conv1.weight) o RMS spike (total 0) = ia ; pain : : : O O 2500 5000 7500 10000 12500 15000 17500 20000 Iteration Figure 16: Observing a predictive relation between RMS spikes and loss spikes. For CLIP ViT-Huge and multiple β2 values, we use heuristics (Appendix D) to automatically identify loss spikes which we use for analysis. Out of 15 total loss spikes, 14 follow an RMS spike in the patch embedding layer (RMS > 2.3) by 1-8 iterations. We show loss spikes which are identified by our heuristic. We use green if they follow an RMS spike and otherwise use red. An RMS Spike indicates that the second moment estimator is out of date (see Section 3.4 and Shazeer and Stern [54]). The chance that a loss spike follows 1-8 iterations after an RMS spike by chance is < 1%. 26 10.0 Loss wu ° Loss wu ° Loss wu ° RMS tT [Vit-Large, Beta2 = 0.99 —— Loss Loss spike 1-8 iterations after RMS spike (9 out of 10) Loss spike not 1-8 iterations after RMS spike (1 out of 10) 7500 10000 12500 15000 17500 20000 ViT-Large, Beta2 = 0.99 —— RMS (visual.conv1.weight) RMS spike (total 52) oO 2500 5000 7500 10000 12500 15000 17500 20000 (ViT-Large, Beta2 = 0.98 — Loss Loss spike 1-8 iterations after RMS spike (4 out of 4) Loss spike not 1-8 iterations after RMS spike (0 out of 4) Ne an | 0 2500 5000 7500 10000 12500 15000 17500 20000 7 T 1 1 ViT-Large, Beta2 = 0.98 n n [rtarge, Beta? = 0:98) — RMS (visual.conv1.weight) RMS spike (total 29) oO 2500 5000 7500 10000 12500 15000 17500 20000 ViT-Large, Beta2 = 0.95 —— Loss Loss spike 1-8 iterations after RMS spike (0 out of 1) Loss spike not 1-8 iterations after RMS spike (1 out of 1) ne neeennenieerranreremmeneemenaa| 0 2500 5000 7500 10000 12500 15000 17500 20000 \ViT-Large, Beta2 = 0.95 Fi : i-Large, Beta: —— RMS (visual.conv1.weight) RMS spike (total 15) oO 2500 5000 7500 10000 12500 15000 17500 20000 ViT-Le , Beta2 = 0.9 i-Large, Beta: Loss Loss spike 1-8 iterations after RMS spike (0 out of 0) Loss spike not 1-8 iterations after RMS spike (0 out of 0) ae ES 2500 5000 7500 10000 12500 15000 17500 20000 Vit-Large, Beta2 = 0.9 = = —— RMS (visual.conv1.weight) RMS spike (total 1) 0 2500 5000 7500 10000 12500 15000 17500 20000 Iteration Figure 17: Observing a predictive relation between RMS spikes and loss spikes. For CLIP ViT-Large and multiple β2 values, we use heuristics (Appendix D) to automatically identify loss spikes which we use for analysis. Out of 15 total loss spikes, 13 follow an RMS spike in the patch embedding layer (RMS > 2.3) by 1-8 iterations. We show loss spikes which are identified by our heuristic. We use green if they follow an RMS spike and otherwise use red. An RMS Spike indicates that the second moment estimator is out of date (see Section 3.4 and Shazeer and Stern [54]). The chance that a loss spike follows 1-8 iterations after an RMS spike by chance is 1.0%. 27 a 2 - 10.0 (ViT-Huge, Beta2 = 0.99 - > — Loss 75 Loss spike 1-8 iterations 5.0 * after RMS spike Loss spike not 1-8 iterations 4 2.5 * after RMS spike 0.0 2 ; t t 2 ; ; s— ; 2800 3000 3200 3400 3600 3800 4000 4200 |ViT-Hi , Beta2 = 0.99 4 ee —— RMS (visual.conv1.weight) RMS spike vn = c2 o+ 2800 3000 3200 3400 3600 3800 4000 4200 Iteration Figure 18: Zooming in on a section of Figure 16. a 2 - 10.0 (ViT-Huge, Beta2 = 0.98 Z 75 : — Loss Loss spike 1-8 iterations 5.0 “""" after RMS spike Loss spike not 1-8 iterations | 2.5 “""" after RMS spike 0.0 4000 4050 4100 4150 4200 4250 4300 4350 ViT-Hi , Beta2 = 0.98 4 [itHuge, Beta2 = 0.98) — RMS (visual.conv1.weight) RMS spike wn = a2 0 4000 4050 4100 4150 4200 4250 4300 4350 Iteration Figure 19: Examining the “failure” case in Figure 16. We believe this is not really a failure as the non-predicted red loss spike does not really appear to be a spike at all. However, adjusting our heuristic led to the issue of true spikes not being identified. 28 10.0 ViT-Large, Beta2 = 0.99 1s = —— Loss Loss spike 1-8 iterations “after RMS spike Loss spike not 1-8 iterations -| “*" after RMS spike 5600 5650 5700 5750 5800 5850 5900 5950 6000 ViT-Le , Beta2 = 0.99 4 [tlarge, Beta2 = 0.99] — RMS (visual.conv1.weight) wv RMS spike = a2 oO 5600 5650 5700 5750 5800 5850 5900 5950 6000 10.0 ViT-Large, Beta2 = 0.95 15 = —— Loss : Loss spike 1-8 iterations 50 : “after RMS spike Rn. Loss spike not 1-8 iterations | 25 : “"** after RMS spike 0.0 4500 4550 4600 4650 4700 4750 ViT-Le , Beta2 = 0.95 4 [Mttarge, Beta? = 0.95) — RMS (visual. conv1.weight) wv RMS spike = a2 oO 4500 4550 4600 4650 4700 4750 Iteration u a 4 u 2 - Figure 20: Examining the “failure” cases in Figure 17. We believe these to primarily issues with our heuristic, but adjusting our heuristic led to other issues such as true spikes not being identified. 10.0 ViT-Huge, Beta2 = 0.99 15 [irHuge, Beta2 = 0.99] — Loss a Loss spike 1-8 iterations % 50 after RMS spike (0 out of 7) 4 Loss spike not 1-8 iterations 25 “""" after RMS spike (7 out of 7) 0.0 0 2500 5000 7500 10000 12500 15000 17500 20000 ViT-Hi , Beta2 = 0.99 4 (VitHuge, Beta? = 0.99) —— RMS (block.20.attn.in_proj) a RMS spike (total 7) = a2 0 0 2500 5000 7500 10000 12500 15000 17500 20000 10.0 1 [ViT-Huge, Beta2 = 0.98 Loss 75 : a : Loss spike 1-8 iterations % 50 : after RMS spike (0 out of 8) 4 : Loss spike not 1-8 iterations 2.5 : “""* after RMS spike (8 out of 8) 0.0 + 0 2500 5000 7500 10000 12500 15000 17500 20000 { ViT-Huge, Beta2 = 0.98 4 \ [rHuge, Beta? = 0.98) —— RMS (block.20.attn. in_proj) wv RMS spike (total 4) = ia oO 2500 5000 7500 10000 Iteration 12500 15000 17500 20000 Figure 21: This figure repeats part of Figure 16 but examines the RMS of a random layer in the middle of the transformer—blocks.20.attn.in proj—not the patch embedding layer. RMS spikes no longer precede loss spikes. 29
Title: How Close is ChatGPT to Human Experts? Comparison Corpus, Evaluation, and Detection: Summary: The introduction of ChatGPT has garnered widespread attention in both academic and industrial communities. ChatGPT is able to respond effectively to a wide range of human questions, providing fluent and comprehensive answers that significantly surpass previous public chatbots in terms of security and usefulness. On one hand, people are curious about how ChatGPT is able to achieve such strength and how far it is from human experts. On the other hand, people are starting to worry about the potential negative impacts that large language models (LLMs) like ChatGPT could have on society, such as fake news, plagiarism, and social security issues. In this work, we collected tens of thousands of comparison responses from both human experts and ChatGPT, with questions ranging from open-domain, financial, medical, legal, and psychological areas. We call the collected dataset the Human ChatGPT Comparison Corpus (HC3). Based on the HC3 dataset, we study the characteristics of ChatGPT's responses, the differences and gaps from human experts, and future directions for LLMs. We conducted comprehensive human evaluations and linguistic analyses of ChatGPT-generated content compared with that of humans, where many interesting results are revealed. After that, we conduct extensive experiments on how to effectively detect whether a certain text is generated by ChatGPT or humans. We build three different detection systems, explore several key factors that influence their effectiveness, and evaluate them in different scenarios. The dataset, code, and models are all publicly available at https://github.com/Hello-SimpleAI/chatgpt-comparison-detection. # How Close is ChatGPT to Human Experts? Comparison Corpus, Evaluation, and Detection Biyang Guo1†∗, Xin Zhang2∗, Ziyuan Wang1∗, Minqi Jiang1∗, Jinran Nie3∗ Yuxuan Ding4, Jianwei Yue5, Yupeng Wu6 1AI Lab, School of Information Management and Engineering Shanghai University of Finance and Economics 2Institute of Computing and Intelligence, Harbin Institute of Technology (Shenzhen) 3School of Information Science, Beijing Language and Culture University 4School of Electronic Engineering, Xidian University 5School of Computing, Queen’s University, 6Wind Information Co., Ltd # Abstract The introduction of ChatGPT2 has garnered widespread attention in both academic and industrial communities. ChatGPT is able to respond effectively to a wide range of human questions, providing fluent and comprehensive answers that significantly surpass previous public chatbots in terms of security and usefulness. On one hand, people are curious about how ChatGPT is able to achieve such strength and how far it is from human experts. On the other hand, people are starting to worry about the potential negative impacts that large language models (LLMs) like ChatGPT could have on society, such as fake news, plagiarism, and social security issues. In this work, we collected tens of thousands of comparison responses from both human experts and ChatGPT, with questions ranging from open-domain, financial, medical, legal, and psychological areas. We call the collected dataset the Human ChatGPT Comparison Corpus (HC3). Based on the HC3 dataset, we study the characteristics of ChatGPT’s responses, the differences and gaps from human experts, and future directions for LLMs. We conducted comprehensive human evaluations and linguistic analyses of ChatGPT-generated content compared with that of humans, where many interesting results are revealed. After that, we conduct extensive experiments on how to effectively detect whether a certain text is gener- ated by ChatGPT or humans. We build three different detection systems, explore several key factors that influence their effectiveness, and evaluate them in differ- ent scenarios. The dataset, code, and models are all publicly available at https: //github.com/Hello-SimpleAI/chatgpt-comparison-detection. # 1 Introduction Since its dazzling debut in November 2022, OpenAI’s ChatGPT has gained huge attention and wide discussion in the natural language processing (NLP) community and many other fields. According to OpenAI, ChatGPT is fine-tuned from the GPT-3.5 series with Reinforcement Learning from Human Feedback (RLHF; [7, 32]), using nearly the same methods as InstructGPT [25], but with slight differences in the data collection setup. The vast amount of knowledge in GPT-3.5 and the meticulous fine-tuning based on human feedback enable ChatGPT to excel at many challenging NLP ∗Equal Contribution. Project Lead. Corresponding to guo_biyang@163.com Each author has made unique contributions to the project. 2Launched by OpenAI in November 2022. https://chat.openai.com/chat † + tasks, such as translating natural language to code [5], completing the extremely masked text [15] or generating stories given user-defined elements and styles [40], let alone typical NLP tasks like text classification, entity extraction, translation, etc. Furthermore, the carefully collected human-written demonstrations also make ChatGPT able to admit its mistakes, challenge incorrect premises and reject even inappropriate requests, as claimed by OpenAI3. The surprisingly strong capabilities of ChatGPT have raised many interests, as well as concerns: On the one hand, people are curious about how close is ChatGPT to human experts. Different from previous LLMs like GPT-3 [4], which usually fails to properly respond to human queries, InstructGPT [25] and the stronger ChatGPT have improved greatly in interactions with humans. Therefore, ChatGPT has great potential to become a daily assistant for general or professional consulting purposes [20, 21]. From the linguistic or NLP perspectives, we are also interested in where are the remaining gaps between ChatGPT and humans and what are their implicit linguistic differences [14, 18]. On the other hand, people are worried about the potential risks brought by LLMs like ChatGPT. With the free preview demo of ChatGPT going virus, a large amount of ChatGPT-generated content crowded into all kinds of UGC (User-Generated Content) platforms, threatening the quality and reliability of the platforms. For example, Stack Overflow, the famous programming question- answering website, has temporarily banned ChatGPT-generated content4, because it believes "the average rate of getting correct answers from ChatGPT is too low, the posting of answers created by ChatGPT is substantially harmful to the site and to users who are asking and looking for correct answers". Many other applications and activities are facing similar issues, such as online exams [33] and medical analysis [20]. Our empirical evaluation of ChatGPT on legal, medical, and financial questions also reveals that potentially harmful or fake information can be generated. Considering the opaqueness of ChatGPT and the potential social risks associated with model misuse, we make the following contributions to both the academy and society: 1. To facilitate LLM-related research, especially the study on the comparison between humans and LLMs, we collect nearly 40K questions and their corresponding answers from human experts and ChatGPT, covering a wide range of domains (open-domain, computer science, finance, medicine, law, and psychology), named as the Human ChatGPT Comparison Corpus (HC3) dataset. The HC3 dataset is a valuable resource to analyze the linguistic and stylist characteristics of both humans and ChatGPT, which helps to investigate the future improvement directions for LLMs; 2. We conduct comprehensive human evaluations as well as linguistic analysis on human/ChatGPT-generated answers, discovering many interesting patterns exhibited by humans and ChatGPT. These findings can help to distinguish whether certain content is generated by LLMs, and also provide insights about where language models should be heading in the future; 3. Based on the HC3 dataset and the analysis, we develop several ChatGPT detecting models, targeting different detection scenarios. These detectors show decent performance in our held-out test sets. We also conclude several key factors that are essential to the detector’s effectiveness. 4. We open-source all the collected comparison corpus, evaluations, and detection models, to facilitate future academic research and online platform regulations on AI-generated content. # 2 Human ChatGPT Comparison Corpus (HC3) ChatGPT is based on the GPT-3.5 series, which is pre-trained on the super-large corpus, consisting of web-crawled text, books, and codes, making it able to respond to all kinds of questions. Therefore, we are curious how will a human (especially an expert) and ChatGPT respond to the same question respectively. Inspired by [1], we also want to evaluate whether ChatGPT can keep honest (not fabricate information or mislead the user), harmless (shouldn’t generate harmful or offensive content), # 3https://openai.com/blog/chatgpt/ 4https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned 2 HC3-English All 24322 58546 26903 reddit_eli5 open_qa wiki_csai medicine finance 17112 1187 842 1248 3933 51336 1187 842 1248 3933 16660 3561 842 1337 4503 ELI5 dataset [10] WikiQA dataset [39] Crawled Wikipedia (A.1) Medical Dialog dataset [6] FiQA dataset [23] HC3-Chinese All 12853 22259 17522 open_qa baike nlpcc_dbqa medicine finance psychology law 3293 4617 1709 1074 689 1099 372 7377 4617 1709 1074 1572 5220 690 3991 4617 4253 1074 1983 1099 505 WebTextQA & BaikeQA [38] Crawled BaiduBaike (A.1) NLPCC-DBQA dataset [8] Medical Dialog dataset [6] ChineseNlpCorpus (A.1) from Baidu AI Studio (A.1) LegalQA dataset (A.1) Table 1: Meta-information of the HC3 dataset. The English (resp. Chinese) contains 5 (resp. 7) splits. and how helpful (provide concrete and correct solutions to the user’s question) it is compared to human experts. Taking these into account, we decided to collect a comparison corpus that consists of both human and ChatGPT answers to the same questions. We believe such a comparison corpus can be a valuable and interesting source to study the nature of the language of both humans and language models. # 2.1 Human Answers Collection Inviting human experts to manually write questions and answers is tedious and unaffordable for us to collect a large amount of data, therefore we construct the comparison dataset mainly from two sources: • Publicly available question-answering datasets, where answers are given by experts in specific domains or the high-voted answers by web users; • Wiki text. We construct question-answer pairs using the concepts and explanations from wiki sources like Wikipedia5 and BaiduBaike6. The split-data source mapping is shown in Table 1, and please refer to Appendix A.1 for further detailed information. # 2.2 ChatGPT Answers Collection Based on the collected human question-answering datasets, we use ChatGPT to generate answers to these questions. Since the ChatGPT is currently only available through its preview website, we manually input the questions into the input box, and get the answers, with the aid of some automation testing tools. Answers by ChatGPT can be influenced by the chatting history, so we refresh the thread for each question. To make the answer more aligned with human answers, we add additional instructions to ChatGPT for specific datasets. For example, the human answers from the reddit-eli5 dataset split are under the context of "Explain like I’m five", therefore we use this context to instruct ChatGPT by adding "Explain like I’m five" at the end of the original question. More detail can be found in the Appendix. 5https://www.wikipedia.org/ 6https://baike.baidu.com/ 3 ChatGPT can generate different answers given the same question in different threads, which is perhaps due to the random sampling in the decoding process. However, we found the differences can be very small, thereby we only collect one answer for most questions. # 2.3 Human ChatGPT Comparison Corpus (HC3) For each question, there can be more than one human/ChatGPT answer, therefore we organize the comparison data using the following format: 1 { 2 3 4 5 } " question ": " Q1 " , " human_answers ": [" A1 " , " A2 "] , " chatgpt_answers ": [" B1 "] Overall, we collected 24, 322 questions, 58, 546 human answers and 26, 903 ChatGPT answers for the English version, and 12, 853 questions, 22, 259 human answers and 17, 522 ChatGPT answers for the Chinese version. The meta-information of each dataset split is illustrated in Table 1. # 3 Human Evaluation & Summarization In this section, we invite many volunteer testers and conduct extensive human evaluations from different aspects. After the human evaluation, we make our collected comparison corpus available to the volunteers and ask them to manually conclude some characteristics. We then summarize the feedback from the volunteers combined with our observations. # 3.1 Human Evaluation The human evaluation is divided into the Turing test and the Helpfulness Test. The Turing Test [34] is a test of a machine’s ability to exhibit intelligent behavior that is indistinguishable from a human. We invite 17 volunteers, divided into two groups: 8 experts (who are frequent users of ChatGPT) and 9 amateurs (who have never heard of ChatGPT). This is because people who are familiar with ChatGPT may have memorized some patterns exhibited by ChatGPT, helping them to easily distinguish the role. We designed four types of evaluations, using different query formats or testing groups. We introduce the specific evaluation design and results in the following parts: A. Expert Turing Test, Paired Text (pair-expert) The pair-expert test is conducted in the expert group. Each tester is required to do a series of tests, each test containing one question and a pair of answers (one from humans and another from ChatGPT). The tester needs to determine which answer is generated by ChatGPT. B. Expert Turing Test, Single Text (single-expert) The single-expert test is also conducted in the expert group. Each tester is required to do a series of tests, each test containing one question and a single answer randomly given by humans or ChatGPT. The tester needs to determine whether the answer is generated by ChatGPT. C. Amateur Turing Test, Single Text (single-amateur) The single-amateur test is conducted in the amateur group. Each tester is required to do a series of tests, each test containing one question and a single answer randomly given by humans or ChatGPT. The tester needs to determine whether the answer is generated by ChatGPT. D. Helpfulness Test (helpfulness) We are also curious about how helpful are the answers from ChatGPT compared with humans’ answers to one question. Note that helpfulness is a very subjective metric, which can be influenced by many factors, including emotion, tester personality, personal preference, etc. Therefore, simply providing more accurate information or a more detailed analysis may not always lead to a more helpful answer. The helpfulness test is conducted in the expert group. Each tester is required to do a series of tests, each containing one question and a pair of answers (one from human and another from ChatGPT). 4 Human Evaluation (En) Pair-expert Single-expert Single-amateur Helpfulness All 0.90 0.81 0.48 0.57 reddit_eli5 open_qa wiki_csai medical finance 0.97 0.98 0.97 0.97 0.79 0.94 0.78 0.61 0.97 0.73 0.57 0.34 0.39 0.50 0.58 0.59 0.72 0.71 0.23 0.60 # Human Evaluation (Zh) Pair-expert Single-expert Single-amateur Helpfulness All 0.93 0.86 0.54 0.54 open_qa baike nlpcc_dbqa medicine finance psychology law 1.00 0.76 1.00 0.93 0.86 1.00 1.00 0.92 0.64 0.90 0.93 0.84 1.00 0.77 0.47 0.60 0.13 0.57 0.84 0.60 0.56 0.50 0.60 0.63 0.30 0.75 0.67 0.56 Table 2: Human evaluations of ChatGPT generated answers for both English and Chinese. Each tester is asked to pretend that the question is proposed by him/herself, and needs to determine which answer is more helpful to him/her. Settings. We sample around 30 <question, human_answer, chatgpt_answer> triplets from each split (i.e., reddit_eli5, wikipedia, medical, etc.) as the samples for the human evaluation. We allocate 2-5 testers for each split and report their average results. For all Turing tests, we report the proportion that ChatGPT-generated answer is correctly detected by testers. For the helpfulness test, we report the proportion that ChatGPT-generated answer is considered to be more helpful. Results. Several conclusions can be drawn from the results shown in Table 2. Comparing the results of pair-expert and single-expert, we can find that it is easier to distinguish ChatGPT- generated content when providing a comparison pair than only providing a single answer. Com- paring the results of single-expert and single-amateur, we can find that the accuracy of experts is much higher than that of amateurs. The helpfulness test gives the proportion of questions that volunteers think the ChatGPT answer is more helpful to them. Surprisingly, results show that ChatGPT’s answers are generally considered to be more helpful than humans’ in more than half of questions, especially for finance and psychology areas. By checking the specific answers in these domains, we find that ChatGPT can usually provide more concrete and specific suggestions. However, ChatGPT performs poorly in terms of helpfulness for the medical domain in both English and Chinese. The ChatGPT often gives lengthy answers to medical consulting in our collected dataset, while human experts may directly give straightforward answers or suggestions, which may partly explain why volunteers consider human answers to be more helpful in the medical domain. # 3.2 Human Summarization After the above evaluations, we open our collected HC3 dataset to the volunteers where they can freely browse the comparison answers from humans and ChatGPT. All dataset splits are allocated to different volunteers, and each volunteer is asked to browse at least 100 groups of comparison data. After that, we ask them to summarize the characteristics of both human answers and ChatGPT answers. Eventually, we received more than 200 feedbacks, and we summarize these findings as follows: 5 # Distinctive Patterns of ChatGPT (a) ChatGPT writes in an organized manner, with clear logic. Without loss of generality, ChatGPT loves to define the core concept in the question. Then it will give out detailed answers step by step and offers a summary at the end, following the deduction and summary structure; (b) ChatGPT tends to offer a long and detailed answer. This is the direct product of the Reinforcement Learning with Human Feedback, i.e. RLHF, and also partly related to the pattern (a) unless you offer a prompt such as "Explain it to me in one sentence"; (c) ChatGPT shows less bias and harmful information. ChatGPT is neutral on sensitive topics, barely showing any attitude towards the realm of politics or discriminatory toxic conversations; (d) ChatGPT refuses to answer the question out of its knowledge. For instance, ChatGPT cannot respond to queries that require information after September 2021. Sometimes ChatGPT also refuses to answer what it believes it doesn’t know. It is also RLHF’s ability to implicitly and automatically determine which information is within the model’s knowledge and which is not. (e) ChatGPT may fabricate facts. When answering a question that requires professional knowledge from a particular field, ChatGPT may fabricate facts in order to give an answer, though [25] mentions that InstructGPT model has already shown improvements in truthful- ness over GPT-3. For example, in legal questions, ChatGPT may invent some non-existent legal provisions to answer the question. This phenomenon warns us to be extra careful when using ChatGPT for professional consultations. Additionally, when a user poses a question that has no existing answer, ChatGPT may also fabricate facts in order to provide a response. Many of the conclusions mentioned above like (b),(c),(d) are also discussed in [12] by Fu et al. # Major Differences between Human and ChatGPT (a) ChatGPT’s responses are generally strictly focused on the given question, whereas humans’ are divergent and easily shift to other topics. In terms of the richness of content, humans are more divergent in different aspects, while ChatGPT prefers focusing on the question itself. Humans can answer the hidden meaning under the question based on their own common sense and knowledge, but the ChatGPT relies on the literal words of the question at hand; (b) ChatGPT provides objective answers, while humans prefer subjective expressions. Generally, ChatGPT generates safer, more balanced, neutral, and informative texts compared to humans. As a result, ChatGPT is excellent at interpreting terminology and concepts. On the other hand, human answers are more specific and include detailed citations from sources based on legal provisions, books, and papers, especially when providing suggestions for medical, legal, and technical problems, etc.; (c) ChatGPT’s answers are typically formal, meanwhile humans’ are more colloquial. Humans tend to be more succinct with full of oral abbreviations and slang such as "LOL", "TL;DR", "GOAT" etc. Humans also love to apply humor, irony, metaphors, and exam- ples, whereas ChatGPT never uses antiphrasis. Additionally, human communication often includes the "Internet meme" as a way to express themselves in a specific and vivid way; (d) ChatGPT expresses less emotion in its responses, while human chooses many punctu- ation and grammar feature in context to convey their feelings. Human uses multiple exclamation mark(’!’), question mark(’?’), ellipsis(’...’) to express their strong emotion, and use various brackets(’(’, ’)’, ’[’, ’]’) to explain things. By contrast, ChatGPT likes to use conjunctions and adverbs to convey a logical flow of thought, such as "In general", "on the other hand", "Firstly,..., Secondly,..., Finally" and so on. Overall, these summarised features indicate that ChatGPT has improved notably in question- answering tasks for a wide range of domains. Compared with humans, we can imagine ChatGPT as a conservative team of experts. As a "team", it may lack individuality but can have a more comprehensive and neutral view towards questions. 6 English avg. len. vocab size density Chinese avg. len. vocab size human ChatGPT All 142.50 198.14 79157 66622 2.33 1.41 All 102.27 115.3 75483 45168 human ChatGPT reddit_eli5 134.21 194.84 55098 44926 2.46 1.38 nlpcc_dbqa 24.44 78.21 10621 11971 human ChatGPT open_qa 35.09 131.68 9606 16251 23.06 10.40 open_qa 93.68 150.66 40328 26451 human ChatGPT wiki_csai 229.34 208.33 15859 9741 8.21 5.55 baike 112.25 77.19 28966 14041 human ChatGPT medicine 92.98 209.61 11847 7694 10.42 3.00 medicine 92.34 165.41 9855 7211 human ChatGPT finance 202.07 226.01 25500 21411 3.21 2.41 finance 80.76 120.84 2759 4043 human ChatGPT - - - - - - - - psychology 254.82 164.53 16160 5897 human ChatGPT - - - - - - - - law 28.77 143.76 2093 3857 density 5.75 3.05 25.43 8.96 13.13 5.35 5.59 3.94 9.94 4.06 5.05 4.94 5.77 3.26 19.55 7.21 Table 3: Average answer length, vocabulary size and density comparisons on our corpus. # 4 Linguistic Analysis In this section, we analyze the linguistic features of both humans’ and ChatGPT’s answers, and try to find some statistical evidence for the characteristics concluded in Section 3. # 4.1 Vocabulary Features In this part, we analyze the vocabulary features of our collected corpus. We are interested in how humans and ChatGPT differ in the choice of words when answering the same set of questions. Since the number of human/ChatGPT answers is unbalanced, we randomly sample one answer from humans and one answer from ChatGPT during our statistical process. We calculated the following features: average length (L), which is the average number of words in each question; vocab size (V ), the number of unique words used in all answers; we also propose another feature called density (D), which is calculated by D = 100 × V /(L × N ) where N is the number of answers. Density measures how crowded different words are used in the text. For example, if we write some articles that add up to 1000 words, but only 100 different words are used, then the density is 100 × 100/1000 = 10. The higher the density is, the more different words are used in the same length of text. In Table 3, we report the vocabulary features for both English and Chinese corpus. Looking at both features of average length and vocab size, we can see that: compared to ChatGPT, human answers are relatively shorter, but a larger vocabulary is used. This phenomenon is particularly obvious in the Chinese open_qa split and the medical splits in both languages, where the average length of ChatGPT is nearly twice longer than that of humans, but the vocab size is significantly smaller. This phenomenon is also reflected by the density factor. The word density of humans is greater than ChatGPT’s in every split, which further reveals that humans use a more diverse vocabulary in their expressions. # 4.2 Part-of-Speech & Dependency Analysis In this part, we compare the occurrences of different part-of-speech (POS) tags and the characteristics of the dependency relations. # 4.2.1 Part-of-Speech Figure 1 illustrates the comparisons between humans and ChatGPT in terms of POS usage. In HC3-English, ChatGPT uses more NOUN, VERB, DET, ADJ, AUX, CCONJ and PART words, while using less ADV and PUNCT words. 7 Part-of-Speech Comparison (En) & (3 Human Wz ChatGPT 3 a 8 Proportion (%) 0301 0204 0200 » pr Part-of-Speech Comparison (Zh) (3 Human 2 ChatGPT Proportion (%) a 8 2624 2324 1248 0908 9407 ee Stee 2493 00090 0000 A yy ye e . » & wars . «d AF eo Feo co oe _ cont™ cot w WS oe SS io Oh WH gy’ yo Figure 1: Part-of-Speech distribution comparison between ChatGPT and human answers. Results are sorted by POS proportion of human answers. The upper figure is for the HC3-English dataset and the lower is for the HC3-Chinese dataset. A high proportion of nouns (NOUN) often indicates that the text is more argumentative, exhibiting informativeness and objectivity [24]. Accordingly, adposition (ADP) and adjective (ADJ) words also tend to appear more frequently [11]. The frequent co-occurrence of conjunctions (CCONJ) along with nouns, verbs, and adposition words indicates that the structure of the article and the relationships of cause-and-effect, progression, or contrast are clear. The above are also typical characteristics in academic papers or official documents [29]. We believe the RLHF training process has a great influence on ChatGPT’s writing style, which partly explains the difference in the POS tags distribution. # 4.2.2 Dependency Parsing Dependency parsing is a technique that analyzes the grammatical structure of a sentence by identifying the dependencies between its words. We parse the answers in the corpus and compare the proportion of different dependency relations and their corresponding dependency distances. Figure 2 shows the comparison between humans and ChatGPT in HC3-English. Due to the limited space, the Chinese version is placed in the Appendix A.2. The comparison of dependency relations exhibits similar characteristics to that of POS tags, where ChatGPT uses more determination, conjunction, and auxiliary relations. In terms of the dependency distance, ChatGPT has much longer distances for the punct and dep relations, which is perhaps due to the fact that CharGPT tends to use longer sentences. However, ChatGPT has obviously shorter conj relations. According to the analysis of POS tags, ChatGPT usually uses more conjunctions than humans to make the content more logical, this may explain why the conj relations of ChatGPT are relatively shorter than humans. # 4.3 Sentiment Analysis Humans are emotional beings, it is natural that our emotions are reflected in our words, to some extent. ChatGPT is learned on large-scale human-generated text, but it is further fine-tuned with human instructions. Therefore we are curious how "emotional" ChatGPT is compared with humans. We use a multilingual sentiment classification model7 fine-tuned on Twitter corpus [2] to conduct sentiment analysis for both English and Chinese comparison data. Note that deep learning-based models can be greatly influenced by some indicating words (such as "but" and "sorry" can easily # 7https://huggingface.co/cardiffnlp/twitter-xlm-roberta-base-sentiment 8 Dependency Relation Comparison (En) Human Zl ChatcPt Proportion %) 097 087 04 5 09s a3 0 i Fgh FPA gather Myo OF oH PO adh gtgs™ HM AE? po OO ooh th PO OE heh aD os oP Fo, PR GPP we F ots c o Dependency Distance Comparison (En) 1 Human e ZH ChatcPt Proportion (%) 2ha ‘4 290 201 223 ge EA Mo a tl thle H sho othe gOS othe oO a oth goAh® Sa TA oo Figure 2: Top-30 dependency relations (upper) and corresponding dependency distances (lower) comparison between human and ChatGPT answers in HC3-English. Results are sorted by relations proportion of human answers. (a) Sentiment distribution of HC3-English (b) Sentiment distribution of the HC3-Chinese 2 « Figure 3: Proportions of three kinds of sentiments (neutral, positive, and negative) in our corpus. fool the classifier to predict the "negative" label), making the predictions biased [16]. Therefore, the sentiment given by the classifier is only a reference to the true sentiment behind the text. Figure 3 shows the comparison of the sentiment distribution of humans and ChatGPT. Several findings can be drawn from the results: First, we find that the proportion of neutral emotions is the largest for both humans and ChatGPT, which is in line with our expectations. However, ChatGPT generally expresses more neutral sentiments than humans. Then, the proportion of negative emotions is significantly higher than that of positive emotions. Notably, humans express significantly more negative emotions than ChatGPT. The proportion of humans’ positive emotions is also slightly higher than that of ChatGPT. Overall, ChatGPT is less emotional than humans, though it is not completely emotionless. # 4.4 Language Model Perplexity The perplexity (PPL) is commonly used as a metric for evaluating the performance of language models (LM). It is defined as the exponential of the negative average log-likelihood of the text under 9 (a) English text ppl (b) English sent ppl (c) Chinese text ppl (d) Chinese sent ppl < 5 & Figure 4: PPL distributions on both English and Chinese data, as well as both text and sentence levels. the LM. A lower PPL indicates that the language model is more confident in its predictions, and is therefore considered to be a better model. The training of LMs is carried out on large-scale text corpora, it can be considered that it has learned some common language patterns and text structures. Therefore, we can use PPL to measure how well a text conforms to common characteristics. We use the open-source GPT-2 small8 (Wenzhong-GPT2-110M9 for Chinese) model to compute the PPL (both text-level and sentence-level10 PPLs) of the collected texts. The PPL distributions of text written by humans and text generated by ChatGPT are shown in Figure 4. It is clearly observed that, regardless of whether it is at the text level or the sentence level, the content generated by ChatGPT has relatively lower PPLs compared to the text written by humans. ChatGPT captured common patterns and structures in the text it was trained on, and is very good at reproducing them. As a result, text generated by ChatGPT have relatively concentrated low PPLs. Humans have the ability to express themselves in a wide variety of ways, depending on the context, audience, and purpose of the text they are writing. This can include using creative or imaginative elements, such as metaphors, similes, and unique word choices, which can make it more difficult for GPT2 to predict. Therefore, human-written texts have more high-PPL values, and show a long-tailed distribution, as demonstrated in Figure 4. # 5 ChatGPT Content Detection AI-generated content (AIGC) is becoming increasingly prevalent on the internet, and it can be difficult to distinguish it from human-generated content, as shown in our human evaluation (sec 3.1). Therefore, AIGC detectors are needed to help identify and flag content that has been created by a machine, to reduce the potential risks to society caused by improper or malicious use of AI models, and to improve the transparency and accountability of the information that is shared online. In this section, we conduct several empirical experiments to investigate the ChatGPT content detection systems. Detecting AI-generated content is a widely studied topic [19, 27]. Based on these [30, 13, 27], we establish three different types of detection systems, including machine learning-based and deep learning-based methods, and evaluate them on different granularities and data sources. Detailed results and discussions are provided. # 5.1 Methods Detection of machine-generated text has been gaining popularity as text generation models have advanced in recent years[19, 27]. Here, we implement three representative methods from classic machine learning and deep learning, i.e, a logistic regression model trained on the GLTR Test-2[13] features, a deep classifier for single-text detection and a deep classifier for QA detection. The deep classifiers for both single-text and QA are based on RoBERTa [22], a strong pre-trained Transformer [35] model. In fact, algorithms for OOD detection or anomaly detection [17] can also be applied to develop ChatGPT content detectors, which we leave for future work. 8https://huggingface.co/gpt2 9https://huggingface.co/IDEA-CCNL/Wenzhong-GPT2-110M 10For English text, we used NLTK[3] for sentence segmentation (HarvestText for Chinese). 10 it fil 4 TestSets sentences (raw) —— full text (raw) —tter , full text (filtered) —solit_, sentences (filtered) Figure 5: The experiment design for the training and testing of detectors. Different dataset versions are generated through filtering or splitting. GLTR. [13] studied three tests to compute features of an input text. Their major assumption is that to generate fluent and natural-looking text, most decoding strategies sample high probabilities tokens from the head of the distribution. We select the most powerful Test-2 feature, which is the number of tokens in the Top-10, Top-100, Top-1000, and 1000+ ranks from the LM predicted probability distributions. And then a logistic regression model is trained to finish the classification. RoBERTa-sinlge. A deep classifier based on the pre-trained LM is always a good choice for this kind of text classification problem. It is also investigated in many studies and demo systems [30, 9, 27]. Here we fine-tune the RoBERTa [22] model. RoBERTa-QA. While most content detectors are developed to classify whether a single piece of text is AI-generated, we claim that a detector that supports inputting both a question and an answer can be quite useful, especially for question-answering scenarios. Therefore, we decide to also build a QA version detector. The RoBERTa model supports a text pair input format, where a separating token is used to join a question and its corresponding answer. # Implementation Details For the LM used by GLTR, we use gpt2-small [28] for English, and Wenzhong-GPT2-110M released by [36] for Chinese, it is the same with sec. 4.4. For RoBERTa-based deep classifiers, we use roberta-base11 and hfl/chinese-roberta-wwm-ext12 checkpoints for English and Chinese, respectively. All the above models are obtained from huggingface transformers [37]. We train the logistic regression model by sklearn [26] on the GLTR Test-2 features from trainset, and search hyper-params following the code of [27]. The RoBERTa-based detectors are trained by the facilities of transformers. Specifically, we use the AdamW optimizer, setting batch size to 32 and learning rate to 5e − 5. We finetune models by 1 epoch for English, and 2 epochs for Chinese. # 5.3 Experiment Design The HC3 dataset consists of questions and their corresponding human/ChatGPT answers. We extracted all the <question, answer> pairs, and assigned label 0 to pairs with human answers and label 1 to pairs with ChatGPT answers. Simply using the original answers from humans and ChatGPT to train a binary classifier is the most straightforward way. However, there might be some issues by doing so: • First, based on the observations in Section 3, both human answers and ChatGPT answers may contain some obvious indicating words that may influence the effectiveness of models; • Second, users may want to detect whether a single sentence is generated by ChatGPT, instead of the full text. This can be quite difficult for a classifier that is only trained on full texts; • Third, taking the corresponding question of the answer into account may help the detector to make a more accurate judgment, compared with only considering the answer itself. This # 11https://huggingface.co/roberta-base 12https://huggingface.co/hfl/chinese-roberta-wwm-ext 11 can be widely applied to many QA platforms (like Quora, Stack Overflow, and Zhihu) to find out which answer below a certain question is generated by AI. Therefore, we design different groups of experiments to study these key questions: • How will the indicating words influence the detector? • Is it more challenging for the ChatGPT detectors to detect sentence-level content? Is it harder to train a sentence-level classifier? • Can the corresponding question help detectors detect the origin of the answer more accurately? Figure 5 shows how we generate different types of training and testing sets. Specifically, we use the collected raw corpus to construct the first train-test sets (the "full text (raw)" in the figure), which we call the raw-full version. Then we filter away the indicated words in the text to obtain the filtered-full version. By splitting the full text into sentences, we obtain the raw-sent version and the filtered-sent version. We also combine the full text and the sentences into a mixed version, namely the raw-mix and filtered-mix version. Overall, we have six different versions of training and testing sets. Evaluating a model’s performance on version B’s testing set which is trained on version A’s training set can be seen as an out-of-distribution (OOD) generalization evaluation, which is more challenging since it requires the model to be robust when facing sample style changes. # 5.4 Results Following the above experiment design, we conduct comprehensive empirical studies on all kinds of derived corpus. Table 4 shows the test F1 scores. English Chinese Test → full raw sent mix full filtered sent mix Avg. full raw sent mix full filtered sent mix Train ↓ RoBERTa raw full sent mix 99.82 99.40 99.44 81.89 84.67 98.43 98.56 98.31 98.47 99.72 81.00 99.24 98.47 99.32 98.37 84.07 98.59 98.51 88.53 98.78 98.74 98.79 97.76 97.70 83.64 95.75 95.68 86.32 96.11 96.04 98.57 97.68 97.65 82.77 95.31 95.27 85.85 95.77 95.73 filtered full sent mix 99.82 96.97 96.28 87.17 89.05 97.22 97.19 96.43 96.41 99.79 86.60 99.09 98.43 99.45 98.37 88.67 98.53 98.53 91.85 97.91 97.58 98.25 96.60 97.43 91.04 92.81 94.09 92.30 93.47 94.68 98.14 97.94 97.66 91.15 95.86 95.61 92.48 96.26 96.01 Train ↓ GLTR Test-2 raw full sent mix 98.26 86.26 95.97 71.58 76.15 88.18 87.96 86.45 87.81 98.22 70.19 87.72 88.23 96.13 86.24 75.23 88.19 87.73 81.61 87.76 90.06 89.61 84.49 86.45 44.02 71.79 70.85 53.72 74.01 73.59 85.89 84.06 84.94 43.58 70.29 69.14 53.62 72.90 72.14 filtered full sent mix 98.31 84.00 95.36 70.91 75.65 88.25 87.71 86.73 87.97 98.30 69.48 85.68 88.35 95.60 86.56 74.72 87.99 87.92 81.23 87.00 90.02 89.46 84.56 86.30 58.69 71.85 71.00 64.52 74.07 73.70 86.51 84.22 84.98 55.45 70.59 69.45 62.18 73.18 72.40 Avg. 89.32 96.40 96.35 93.89 95.49 95.91 61.74 76.26 76.19 69.47 76.41 76.31 Table 4: F1 scores (%) of different models on each testset, average of each language are reported. # 5.4.1 Which detector(s) is more useful? ML-based or DL-based? and Why? According to Table 4, we can derive following conclusions: Firstly, the robustness of RoBERTa-based-detector is better than GLTR. The F1-scores of RoBERTa decrease slightly (1.5-2% in English datasets and 2-3% in Chinese datasets) when sentences are split by comparing the leading diagonal elements in raw→raw and filtered→filtered. In contrast, the GLTR reduces significantly by over 10% in English datasets, and above 15% in Chinese datasets. Above all, the RoBERTa-based-detector is more robust with anti-interference character. In contrast, the GLTR reduces significantly by over 10% in English datasets, above 15% in Chinese datasets. Above all, the RoBERTa-based-detector is more robust with anti-interference character. Secondly, RoBERTa-based-detector is not affected by indicating words. The F1-scores of RoBERTa only slightly decreased by 0.03% in English full dataset, and 0.65% in Chinese full dataset, as seen in the minus of relevant leading diagonal elements in raw→raw versus filtered→filtered. On the contrary, evaluations based on GLTR decrease by up to 3.1% on Chinese datasets, though tiny rise on English datasets, indicating that GLTR is sensitive to indicating words, easily influenced by the patterns of ChatGPT. 12 Lastly, RoBERTa-based-detector is effective in handling Out-Of-Distribution scenarios. When compared to the original model, it demonstrates a significant decrease in performance on GLTR’s OOD test datasets, with a drop of up to 28.8% on English datasets(filtered-full→filtered-full − filtered-full→filtered-sent) and 45.5% on Chinese datasets(raw-full→raw-full − raw-full→raw-sent). However, RoBERTa maintains consistent performance with F1-scores varying by no more than 19%. # 5.4.2 How will the indicating words influence the detector? We first collected a bunch of indicating words for both humans and ChatGPT. For example, ChatGPT’s indicating words (or phrases) include "AI assistant", "I’m sorry to hear that", and "There’re a few steps...", etc. and humans’ indicating words may include "Hmm", "Nope", "My view is", etc. In the filtered version, we remove all sentences in the answers that contain the indicating words for both humans and ChatGPT. According to Table 4, removing the indicating words helps the models trained on full-text to per- form better across different content granularities. For example, the RoBERTa-filter-full performs significantly better than RoBERTa-raw-full in terms of sentence-level and mix-level evaluations, improving more than 3% F1 scores on average. However, the filtering may slightly hurt the per- formances of the models trained on sentences. This may be because the indicating words play a bigger part in the sentence-level text compared with the full text. Removing the indicating words may make some sentences literally unable to be distinguished. # 5.4.3 Which granularity is more difficult to detect? Full-text or sentence? Through the extensive experimental results in Table 5, we conclude that detecting ChatGPT gener- ated texts is more difficult in a single sentence than in a full text. This conclusion can be proved by the following two points: First, our results show that both English and Chinese sentence-based detectors (i.e., raw-sent and filtered-sent versions) achieve satisfactory results w.r.t. the testing task of detecting either ChatGPT generated paragraphs or sentences, whereas the opposite is not true——raw-full and filtered-full are relatively inferior when detecting ChatGPT generated sentences. In other words, detectors trained on "hard samples" (i.e., sentence corpus) are much easier to solve simple task (i.e., detecting full corpus), while "simple samples" (i.e., full corpus) may be less useful for solving more difficult task (i.e., sentence corpus). Second, we observe that although both full and sentence corpus are provided in the raw-mix and filtered-mix versions, it is still more difficult for them to detect single sentences generated by ChatGPT. This is even more obvious for the Chinese corpus, where the F1-score of raw-mix trained on the Chinese corpus is 94.09% for testing raw sentence answers, compared to that 97.43% for testing raw full answers. Similar results can be observed for the filtered corpus, where F1-score of filtered-mix is 95.61% for testing filtered sentence answers, compared to its F1-score of 97.66% for testing filtered full answers. One possible explanation is that the expression pattern of ChatGPT is more obvious (therefore more easily detected) when paragraphs of text are provided, whereas it is more difficult to detect generated single sentences. English Chinese Test → Train ↓ full raw sent mix full filtered sent mix Avg. full raw sent mix full filtered sent mix full-raw sent-raw mix-raw 99.82 99.40 99.44 81.89 84.67 98.43 98.56 98.31 98.47 99.72 81.00 99.24 98.47 99.32 98.37 84.07 98.59 98.51 88.53 98.78 98.74 98.79 97.76 97.70 83.64 95.75 95.68 86.32 96.11 96.04 98.57 97.68 97.65 82.77 95.31 95.27 85.85 95.77 95.73 full-filtered sent-filtered mix-filtered 99.82 96.97 96.28 87.17 89.05 97.22 97.19 96.43 96.41 99.79 86.60 99.09 98.43 99.45 98.37 88.67 98.53 98.53 91.85 97.91 97.58 98.25 96.60 97.43 91.04 92.81 94.09 92.30 93.47 94.68 98.14 97.94 97.66 91.15 95.86 95.61 92.48 96.26 96.01 Avg. 89.32 96.40 96.35 93.89 95.49 95.91 Table 5: F1 scores (%) of RoBERTa models at full & sent & mix mode. 13 5.4.4 Which corpus is more helpful for model training? Full-text, sentence, or mix of the two? We find that both English and Chinese RoBERTa-based detectors are more robust when fine- grained corpus data is available in model training. The sentence-based detectors outperform full-based detectors w.r.t. F1-scores, while the latter can be significantly improved when the sentence corpus is injected in model training, as we observe that mix-based detectors also achieve satisfactory results. For English corpus, raw-full only achieves 81.89% F1-score for testing sentence answers, while raw-sent is significantly better with 98.43% F1-score, as shown in Table 5. Moreover, the relatively inferior detection performance can be improved by injecting sentence answers into the detector, where we find that raw-mix can also obtain significant improvement (with 98.31% F1-score) over the detectors trained on only full answers. Similar conclusions can be acquired for the filtered versions, where both filtered-sent and filtered-mix significantly outperform filtered-full version w.r.t. F1-score, which holds for both English and Chinese corpus. We indicate that the above conclusions could also hold for other types of detectors like GLTR Test-2 feature-based detectors, as is shown in Table 4. For GLTR Test-2, the average performance of F1- score of raw-full and filtered-full is 61.74% and 69.47%, respectively, compared to that of raw-sent 76.26% and filtered-sent 76.41%, where the performance of detectors trained on the mixed corpus is close to the sentence-based versions. Taking into account the conclusions of the previous paragraph about the detection difficulty between full and sentence answers, we indicate that the fine-grained corpus is helpful for distinguishing ChatGPT generated texts, as it additionally provides guidance and hints in model training for detecting the subtle patterns of ChatGPT hidden in single sentences. # 5.4.5 Will a QA-style detector be more effective than a single-text detector? Table 6 demonstrates the results of both raw-full and filtered-full models across all test datasets. On English datasets, the QA model’s F1-scores are superior to that of the single model, except for two full test datasets, where it averages 97.48% F1-scores and surpasses single model by 5.63%. There exist some differences in Chinese datasets, where the single model outperforms QA in raw-full train dataset. However, the QA model still yields the best evaluation at 94.22%. In conclusion, the QA model is generally more effective than the single model and is suitable for filtered scenarios. And the QA training makes models more robust to the sentence inputs. English Chinese Test → full raw sent mix full filtered sent mix Avg. full raw sent mix full filtered sent mix Train → raw - full Single QA 99.82 81.89 84.67 99.84 92.68 93.70 99.72 81.00 84.07 99.75 92.34 93.46 88.53 95.30 98.79 83.64 86.32 98.99 80.56 83.85 98.57 82.77 85.85 98.73 80.24 83.89 Train → filtered - full Single QA 99.82 87.17 89.05 99.70 96.14 96.64 99.79 86.60 88.67 99.70 96.07 96.61 91.85 97.48 98.25 91.04 92.30 97.29 92.10 93.01 98.14 91.15 92.48 97.18 92.40 93.31 Avg. 89.32 87.71 93.89 94.22 Table 6: F1 scores (%) of RoBERTa models trained with QA & Single settings. 5.4.6 Which data sources are more difficult for the ChatGPT detectors? and What are the conditions that make it easier to detect ChatGPT? As shown in Table 7, the evaluation results based on filtered-full model are separated by various sources in our HC3 dataset. On the English datasets, the F1-scores for human answers are slightly higher than those for ChatGPT without any exceptions, regardless of whether RoBERTa or GLTR is used on full-text test datasets. However, the F1-scores for ChatGPT are highly inconsistent on transferring test datasets particu- larly open-qa dataset with varying performance. In terms of data resource, reddit-eli5 and finance-en has higher values, while wiki-csai poses a challenge for detectors. 14 On the Chinese datasets, the F1-scores of humans and ChatGPT are comparable with no significant difference. This suggests that the difficulty in detecting ChatGPT depends on the data source. It is observed that open-qa and baike have better performance, whereas the nlpcc-dbqa has lower performance. Above all, the evaluations on Chinese dataset show more stability on transferring test dataset compared to the English datasets. Furthermore, it’s evident that the F1-scores of ChatGPT are lower than those of human answers, regardless of whether the dataset is English or Chinese. This indicates that ChatGPT’s detector relies more heavily on In-Distribution models. Model Test F1-hu F1-ch F1-hu F1-ch F1-hu F1-ch F1-hu F1-ch F1-hu F1-ch # English finance medicine open_qa reddit_eli5 wiki_csai RoBERTa GLTR full sent full sent 99.34 78.84 97.50 46.60 99.28 85.84 97.37 75.26 99.69 84.06 98.28 45.41 99.62 80.45 97.96 61.72 99.53 70.74 92.68 42.01 98.60 26.78 82.20 17.81 100.00 77.27 98.22 38.12 100.00 93.31 99.40 87.05 96.59 68.91 95.76 39.24 96.37 84.12 95.72 76.94 # Chinese finance law open_qa nlpcc_dbqa baike RoBERTa GLTR full sent full sent 98.87 95.00 86.67 36.91 97.99 80.46 80.42 32.80 97.78 93.77 82.41 33.99 98.50 86.23 88.89 46.22 98.75 91.17 85.75 36.45 99.33 93.77 93.15 75.21 97.42 90.10 77.25 46.39 95.42 63.29 69.78 27.50 94.61 86.08 81.62 48.10 93.99 88.88 77.91 71.72 Table 7: Human (F1-hu) and ChatGPT (F1-ch) detection F1 scores (%) w.r.t. different data source, models are trained on filtered full text, tested on filtered full and sent. On HC3-Chinese, we omitted the results of medicine and psychology domains, which are similar to finance and open_qa, respectively. # 6 Conclusion In this work, we propose the HC3 (Human ChatGPT Comparison Corpus) dataset, which consists of nearly 40K questions and their corresponding human/ChatGPT answers. Based on the HC3 dataset, we conduct extensive studies including human evaluations, linguistic analysis, and content detection experiments. The human evaluations and linguistics analysis provide us insights into the implicit differences between humans and ChatGPT, which motivate our thoughts on LLMs’ future directions. The ChatGPT content detection experiments illustrate some important conclusions that can provide beneficial guides to the research and development of AIGC-detection tools. We make all our data, code, and models publicly available to facilitate related research and applications at https://github.com/Hello-SimpleAI/chatgpt-comparison-detection. # 7 Limitations Despite our comprehensive analysis of ChatGPT, there are still several limitations in the current paper, which will be considered for improvement in our future work: 1. Despite our efforts in data collection, the amount and range of collected data are still not enough and the data from different sources are unbalanced, due to limited time and resources. To make more accurate linguistic analyses and content detection, more data with different styles, sources, and languages are needed; 2. Currently, all the collected ChatGPT answers are generated without special prompts. Therefore, the analysis and conclusions in this paper are built upon ChatGPT’s most general style/state. For example, using special prompts such as "Pretending you are Shakespeare..." can generate content that bypasses our detectors or make the conclusions in this paper untenable; 15 3. ChatGPT (perhaps) is mainly trained on English corpus while less on Chinese. Therefore, the conclusions drawn from the HC3-Chinese dataset may not always be precise. # Acknowledgments We would like to thank the volunteers that participated in our human evaluations, many of them are our good friends and dear family members. We would like to thank Junhui Zhu (BLCU-ICALL) for the valuable discussions on linguistic analysis. Biyang Guo would like to thank Prof. Hailiang Huang and Prof. Songqiao Han (AI Lab, SUFE) for providing insightful feedback on the topics and directions for this project. Xin Zhang would like to thank Yu Zhao (NeXt, NUS and CIC, TJU) for sharing the OpenAI account. Finally, we thank all team members of this project for their unique contributions. We together make this possible. 16 # References [1] Amanda Askell, Yuntao Bai, Anna Chen, Dawn Drain, Deep Ganguli, Tom Henighan, Andy Jones, Nicholas Joseph, Ben Mann, Nova DasSarma, et al. A general language assistant as a laboratory for alignment. arXiv preprint arXiv:2112.00861, 2021. [2] Francesco Barbieri, Luis Espinosa Anke, and Jose Camacho-Collados. Xlm-t: Multilingual language models in twitter for sentiment analysis and beyond. In Proceedings of the Language Resources and Evaluation Conference, pages 258–266, Marseille, France, June 2022. European Language Resources Association. [3] Steven Bird, Ewan Klein, and Edward Loper. Natural Language Processing with Python: Analyzing Text with the Natural Language Toolkit. O’Reilly Media, Inc., 2009. [4] 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. [5] 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. [6] Shu Chen, Zeqian Ju, Xiangyu Dong, Hongchao Fang, Sicheng Wang, Yue Yang, Jiaqi Zeng, Ruisi Zhang, Ruoyu Zhang, Meng Zhou, Penghui Zhu, and Pengtao Xie. Meddialog: a large-scale medical dialogue dataset. arXiv preprint arXiv:2004.03329, 2020. [7] Paul F. Christiano, Jan Leike, Tom B. Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep reinforcement learning from human preferences. neural information processing systems, 2017. [8] Nan Duan. Overview of the nlpcc-iccpol 2016 shared task: Open domain chinese question answering. In Natural Language Understanding and Intelligent Applications, pages 942–948, Cham, 2016. Springer International Publishing. [9] Tiziano Fagni, Fabrizio Falchi, Margherita Gambini, Antonio Martella, and Maurizio Tesconi. Tweepfake: About detecting deepfake tweets. Plos one, 16(5):e0251415, 2021. [10] Angela Fan, Yacine Jernite, Ethan Perez, David Grangier, Jason Weston, and Michael Auli. ELI5: long form question answering. In Anna Korhonen, David R. Traum, and Lluís Màrquez, editors, Proceedings of the 57th Conference of the Association for Computational Linguistics, ACL 2019, Florence, Italy, July 28- August 2, 2019, Volume 1: Long Papers, pages 3558–3567. Association for Computational Linguistics, 2019. [11] Zhihui Fang. The language demands of science reading in middle school. International journal of science education, 28(5):491–520, 2006. [12] Yao Fu, Hao Peng, and Tushar Khot. How does gpt obtain its ability? tracing emergent abilities of language models to their sources. Yao Fu’s Notion, Dec 2022. [13] Sebastian Gehrmann, Hendrik Strobelt, and Alexander Rush. GLTR: Statistical detection and visualization of generated text. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics: System Demonstrations, pages 111–116, Florence, Italy, July 2019. Association for Computational Linguistics. [14] Ariel Goldstein, Zaid Zada, Eliav Buchnik, Mariano Schain, Amy Price, Bobbi Aubrey, Samuel A Nastase, Amir Feder, Dotan Emanuel, Alon Cohen, et al. Shared computational principles for language processing in humans and deep language models. Nature neuroscience, 25(3):369–380, 2022. [15] Biyang Guo, Yeyun Gong, Yelong Shen, Songqiao Han, Hailiang Huang, Nan Duan, and Weizhu Chen. Genius: Sketch-based language model pre-training via extreme and selective masking for text generation and augmentation. arXiv preprint arXiv:2211.10330, 2022. [16] Biyang Guo, Songqiao Han, and Hailiang Huang. Selective text augmentation with word roles for low-resource text classification. arXiv preprint arXiv:2209.01560, 2022. [17] Songqiao Han, Xiyang Hu, Hailiang Huang, Minqi Jiang, and Yue Zhao. Adbench: Anomaly detection benchmark. Advances in Neural Information Processing Systems (NeurIPS), 2022. 17 [18] Jennifer Hu, Sammy Floyd, Olessia Jouravlev, Evelina Fedorenko, and Edward Gibson. A fine-grained comparison of pragmatic language understanding in humans and language models. arXiv preprint arXiv:2212.06801, 2022. [19] Ganesh Jawahar, Muhammad Abdul-Mageed, and Laks Lakshmanan, V.S. Automatic detection of machine generated text: A critical survey. In Proceedings of the 28th International Conference on Computational Linguistics, pages 2296–2309, Barcelona, Spain (Online), December 2020. International Committee on Computational Linguistics. [20] Katharina Jeblick, Balthasar Schachtner, Jakob Dexl, Andreas Mittermeier, Anna Theresa Stüber, Johanna Topalis, Tobias Weber, Philipp Wesp, Bastian Sabel, Jens Ricke, et al. Chatgpt makes medicine easy to swallow: An exploratory case study on simplified radiology reports. arXiv preprint arXiv:2212.14882, 2022. [21] Michael R King. The future of ai in medicine: a perspective from a chatbot, 2022. [22] Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. Roberta: A robustly optimized BERT pretraining approach. CoRR, abs/1907.11692, 2019. [23] Macedo Maia, Siegfried Handschuh, Andr’e Freitas, Brian Davis, Ross McDermott, Manel Zarrouk, and Alexandra Balahur. Www’18 open challenge: Financial opinion mining and question answering. In Companion Proceedings of the The Web Conference 2018, WWW ’18, page 1941–1942, Republic and Canton of Geneva, CHE, 2018. International World Wide Web Conferences Steering Committee. [24] William Nagy and Dianna Townsend. Words as tools: Learning academic vocabulary as language acquisition. Reading research quarterly, 47(1):91–108, 2012. [25] Long Ouyang, Jeff Wu, Xu Jiang, Diogo Almeida, Carroll L Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, et al. Training language models to follow instructions with human feedback. arXiv preprint arXiv:2203.02155, 2022. [26] F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel, P. Prettenhofer, R. Weiss, V. Dubourg, J. Vanderplas, A. Passos, D. Cournapeau, M. Brucher, M. Perrot, and E. Duchesnay. Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12:2825–2830, 2011. [27] Jiameng Pu, Zain Sarwar, Sifat Muhammad Abdullah, Abdullah Rehman, Yoonjin Kim, Paran- tapa Bhattacharya, Mobin Javed, and Bimal Viswanath. Deepfake text detection: Limitations and opportunities. In Proc. of IEEE S&P, 2023. [28] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9, 2019. [29] Mary J Schleppegrell. The language of schooling: A functional linguistics perspective. Rout- ledge, 2004. [30] Irene Solaiman, Miles Brundage, Jack Clark, Amanda Askell, Ariel Herbert-Voss, Jeff Wu, Alec Radford, Gretchen Krueger, Jong Wook Kim, Sarah Kreps, et al. Release strategies and the social impacts of language models. arXiv preprint arXiv:1908.09203, 2019. [31] SophonPlus. Chinesenlpcorpus. https://github.com/SophonPlus/ChineseNlpCorpus, 2019. [32] Nisan Stiennon, Long Ouyang, Jeffrey Wu, Daniel M. Ziegler, Ryan Lowe, Chelsea Voss, Alec Radford, Dario Amodei, and Paul F. Christiano. Learning to summarize from human feedback. neural information processing systems, 2020. [33] Teo Susnjak. Chatgpt: The end of online exam integrity? arXiv preprint arXiv:2212.09292, 2022. [34] Alan M Turing. Computing machinery and intelligence. In Parsing the turing test, pages 23–65. Springer, 2009. [35] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017. 18 [36] Junjie Wang, Yuxiang Zhang, Lin Zhang, Ping Yang, Xinyu Gao, Ziwei Wu, Xiaoqun Dong, Junqing He, Jianheng Zhuo, Qi Yang, Yongfeng Huang, Xiayu Li, Yanghan Wu, Junyu Lu, Xinyu Zhu, Weifeng Chen, Ting Han, Kunhao Pan, Rui Wang, Hao Wang, Xiaojun Wu, Zhongshen Zeng, Chongpei Chen, Ruyi Gan, and Jiaxing Zhang. Fengshenbang 1.0: Being the foundation of chinese cognitive intelligence. CoRR, abs/2209.02970, 2022. [37] Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Clement Delangue, Anthony Moi, Pierric Cistac, Tim Rault, Remi Louf, Morgan Funtowicz, Joe Davison, Sam Shleifer, Patrick von Platen, Clara Ma, Yacine Jernite, Julien Plu, Canwen Xu, Teven Le Scao, Sylvain Gugger, Mariama Drame, Quentin Lhoest, and Alexander Rush. Transformers: State-of-the-art natural language processing. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations, pages 38–45, Online, October 2020. Association for Computational Linguistics. [38] Bright Xu. Nlp chinese corpus: Large scale chinese corpus for nlp, September 2019. [39] Yi Yang, Scott Wen-tau Yih, and Chris Meek. Wikiqa: A challenge dataset for open-domain question answering. In Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing. ACL - Association for Computational Linguistics, September 2015. [40] Lili Yao, Nanyun Peng, Ralph Weischedel, Kevin Knight, Dongyan Zhao, and Rui Yan. Plan- and-write: Towards better automatic storytelling. In Proceedings of the AAAI Conference on Artificial Intelligence, volume 33, pages 7378–7385, 2019. # A Appendix # A.1 HC3 Dataset Splits Creation We create 5 and 7 splits for HC3 English and Chinese, respectively. Most of the data come from the publicly available Question-Answering (QA) datasets, where details are listed in the following. For these QA data, we directly input the questions to ChatGPT and collect at least one answer. We also crawled some wiki concepts and explanations from Wikipedia and BaiduBaike, where explanations are treated as human expert answers and concepts are used to construct the questions, details ref to bellow paragraphs. For HC3-English, we create five dataset splits: 1. reddit_eli5. Sampled from the ELI5 dataset [10]. 2. open_qa. Sampled from the WikiQA dataset [39]. 3. wiki_csai. We collected the descriptions of hundreds of computer science-related concepts from Wikipedia13 as the human experts’ answers to questions like "Please explain what is <concept>?" 4. medicine. Sampled from the Medical Dialog dataset [6]. 5. finance. Sampled from the FiQA dataset [23], which is built by crawling StackExchange14 posts under the Investment topic. For HC3-Chinese, we create seven dataset splits: 1. open_qa. Sampled from the WebTextQA and BaikeQA corpus in [38]. 2. baike. We collected the descriptions of more than a thousand information science-related concepts from BaiduBaike15 as the human experts’ answers to questions like "我有一个计 算机相关的问题,请用中文回答,什么是<concept>" 3. nlpcc_dbqa. Sampled from the NLPCC-DBQA dataset [8]. 4. medicine. Sampled from the Medical Dialog dataset [6]. 5. finance. Sampled from the FinanceZhidao dataset [31]. # 13https://www.wikipedia.org/ 14https://stackexchange.com/ 15https://baike.baidu.com/ 19 6. psychology Sampled from a public Chinese Psychological Question Answering Dataset16. 7. law. Sampled from the LegalQA dataset17. # A.2 Additional Results Here we demonstrate the additional results of dependency relations for the Chinese corpus, as is shown in Figure 6. The conclusion is basically consistent with the main paper. Dependency Relation Comparison (Zh) = Human a Chacet Proportion (%) 422 05 093 01 992 241 Ot emt oat 04 our et ops ome ome ome aah) ae? Sep Ko oc? eRe ga ah ab clad ed gh eked coh aod aes? gu add® ga” aaba® agem™ er 9 oF ve 88 a gcor* cot? Ao Le 8 FB ho Fe? coARecO? oro gi S BE 9 arhee™ oe” wrth oy 08 oat Sach ae? soo r eA oO AB | cele geo ot oO eg oO stint oe a ot oe oot o Be of po PSO GIT ot ge eae ot ee om s Dependency Distance Camparisan (Zh) = Human “ ZB ChatcPt Proportion (%) sa0 ino tno ino 49 140 SF eoPeshd Be 89a) cash oO eo? at, eet re ae ee ees ye 8 Moe cca 90 hOB SHO od gr eo dd™ Sah aie? oo ge oe we © of oot hittanogir ot J oe coal ot oe oe ON ge Se Figure 6: Top-30 dependency relations (upper) and corresponding dependency distances (lower) comparison between human and ChatGPT answers in the HC3-Chinese. Results are sorted by relations proportion of human answers. Other detailed results, including vocabulary features, sentiment analyses, and dependency parsing results for each data source are all available at our project GitHub repository at https://github. com/Hello-SimpleAI/chatgpt-comparison-detection. # A.3 Human Evaluations Examples For evaluation examples of our human evaluations, please visit our project GitHub repository at https://github.com/Hello-SimpleAI/chatgpt-comparison-detection. 16https://aistudio.baidu.com/aistudio/datasetdetail/38489 17https://github.com/siatnlp/LegalQA 20
Title: Multi-task curriculum learning in a complex, visual, hard-exploration domain: Minecraft: Summary: An important challenge in reinforcement learning is training agents that can solve a wide variety of tasks. If tasks depend on each other (e.g. needing to learn to walk before learning to run), curriculum learning can speed up learning by focusing on the next best task to learn. We explore curriculum learning in a complex, visual domain with many hard exploration challenges: Minecraft. We find that learning progress (defined as a change in success probability of a task) is a reliable measure of learnability for automatically constructing an effective curriculum. We introduce a learning-progress based curriculum and test it on a complex reinforcement learning problem (called "Simon Says") where an agent is instructed to obtain a desired goal item. Many of the required skills depend on each other. Experiments demonstrate that: (1) a within-episode exploration bonus for obtaining new items improves performance, (2) dynamically adjusting this bonus across training such that it only applies to items the agent cannot reliably obtain yet further increases performance, (3) the learning-progress based curriculum elegantly follows the learning curve of the agent, and (4) when the learning-progress based curriculum is combined with the dynamic exploration bonus it learns much more efficiently and obtains far higher performance than uniform baselines. These results suggest that combining intra-episode and across-training exploration bonuses with learning progress creates a promising method for automated curriculum generation, which may substantially increase our ability to train more capable, generally intelligent agents. # Multi-task curriculum learning in a complex, visual, hard-exploration domain: Minecraft Ingmar Kanitscheider,∗,† Joost Huizinga†, David Farhi, William Hebgen Guss, Brandon Houghton, Raul Sampedro, Peter Zhokhov, Bowen Baker, Adrien Ecoffet, Jie Tang, Oleg Klimov, Jeff Clune† OpenAI # Abstract An important challenge in reinforcement learning is training agents that can solve a wide variety of tasks. If tasks depend on each other (e.g. needing to learn to walk before learning to run), curriculum learning can speed up learning by focusing on the next best task to learn. We explore curriculum learning in a complex, visual domain with many hard exploration challenges: Minecraft. We find that learning progress (defined as a change in success probability of a task) is a reliable measure of learnability for automatically constructing an effective curriculum. We introduce a learning-progress based curriculum and test it on a complex reinforcement learning problem (called “Simon Says”) where an agent is instructed to obtain a desired goal item. Many of the required skills depend on each other. Experiments demonstrate that: (1) a within-episode exploration bonus for obtaining new items improves performance, (2) dynamically adjusting this bonus across training such that it only applies to items the agent cannot reliably obtain yet further increases performance, (3) the learning-progress based curriculum elegantly follows the learning curve of the agent, and (4) when the learning-progress based curriculum is combined with the dynamic exploration bonus it learns much more efficiently and obtains far higher performance than uniform baselines. These results suggest that combining intra-episode and across-training exploration bonuses with learning progress creates a promising method for automated curriculum generation, which may substantially increase our ability to train more capable, generally intelligent agents.1 ∗Contribution Statement: Ingmar Kanitscheider, Joost Huizinga and Jeff Clune conceived the project, provided guidance and wrote the manuscript. Ingmar Kanitscheider designed and ran the experiments. David Farhi, William Hebgen Guss, Brandon Houghton and Peter Zhokhov designed and tested the "Simon Says" task and the static exploration bonus. All authors worked on building out Minecraft as an RL environment. Ingmar Kanitscheider (joost@openai.com), Jeff Clune (jeffclune@openai.com) # †Corresponding 1This is an experiment in sharing "partial work", meaning research that sheds light on a subject, but is not as complete as we would make it were we planning on publishing it as "complete work" in a peer-reviewed venue. Due to other priorities, we do not plan to do all that would be required for that level of scientific rigor. We thus faced a choice: either share it "as is", or not share it at all. We chose the former. We acknowledge much is missing, such as a more thorough literature review, experimental comparisons to other methods, ablations, etc. Nevertheless we believe that our results provide meaningful insights to the machine learning community. Our motivation is to share what we discovered, while minimizing the overhead in time and compute resources required to share the work. # Introduction An important challenge in reinforcement learning (RL) is to train agents that can solve a wide variety of tasks. Tasks often vary in difficulty and depend on each other, such that learning easier tasks first may help with learning more difficult tasks later. Just as human children crawl before they can walk, and walk before they can run, interesting use cases for RL agents have difficulty hierarchies we would like to exploit: Learning first how to write syntactically correct code might help an agent to later learn how to fix semantic errors in a program. Learning first how to solve high school physics problems likely helps learn college-level physics. Such dependencies particularly exist in RL, where the problem of exploration may prevent a policy from experiencing any useful gradient on a hard task before it has mastered a prerequisite task. If the goal is to pass a set of unit tests in a programming domain, an agent will not get any useful feedback if it always fails all unit tests because it is unable to write syntactically correct code. Side-stepping exploration by collecting human demonstrations can be an option, but in many domains of interest it might be difficult or impossible to collect enough high-quality data to reach expert-human-level performance. Furthermore, if the model relies purely on imitating humans its maximum performance will be limited by the best demonstrations in our data set, and even the combination of all the best demonstrations that humanity has to offer probably will not move the model far beyond human performance. In the following we assume that we’re given a collection of RL tasks, each of which consists of a reward function (that defines the goal of the task) and an environment distribution. A naive solution to learning all tasks would be to attempt to learn all tasks simultaneously by uniformly sampling tasks irrespective of the dependencies between them. This solution ensures that the agent experiences a useful gradient as long as some of the tasks are learnable given the agent’s current skill level. However, if the fraction of learnable tasks at any moment is very small, it is computationally very inefficient, as the agent spends a lot of time on tasks where it does not actually learn anything. A more efficient alternative is to build a curriculum that narrows the distribution of tasks being trained on to those that are currently learnable. Which tasks are learnable at a given point in time, or in what order tasks are most easily learnable, is typically not known in advance. As such, the present paper explores methods for how we can infer learnability on the fly and build an automatic curriculum over tasks. In particular, our goal was to, given a set of tasks of varying difficulty, learn as many tasks as fast and compute-efficient as possible. This project focused specifically on tasks with identical environment distributions, but different reward functions. Having tasks with different goals but the same environment distribution is a natural setting for the powerful models we wish to create, as the real world presents a diverse but fixed environment distribution in which we would want the model to perform many different tasks. The same is true for our current generation of models, which generally have to learn many different tasks (e.g. write different programs, summarize different books, answer different questions, generate different images) in a universal environment such as vision or language. A curriculum only helps if mastering one task makes another task easier to learn. However, in a goal-conditioned setup, even when tasks are learned in the "correct" order, meaning that easier tasks are learned before the harder tasks that depend on them, it can be difficult to learn the harder tasks. One problem is that the agent does not know the relationship between different tasks, meaning that if the agent is given the goal for a task that it hasn’t learned yet, it does not know which of its previously learned behaviors might help it achieve that goal. Another problem is that, even if the agent did know exactly which of the previously learned tasks is related to the task it is currently trying to solve, the behavior on that previously learned task may not generalize to the current task (meaning that executing the behavior learned on the previous task does not result in any zero-shot performance on the current task), because the tasks are too different. For example, even if the agent has learned to write syntactically correct code and is executing that behavior frequently, it may never write a program that passes a particular unit-test when that unit-test is selected as the current task and thus be unable to learn to write a program for it. We find that adding a goal-independent exploration bonus that rewards all tasks the agent has not yet learned helps the agent learn new tasks. We have developed and evaluated these curriculum learning methods in a Minecraft environment based on the MineRL platform[1]. Minecraft is a well-thought-out visual world with rudimentary physics, which has the potential to allow our agents to learn many useful skills such as visual processing, spatial awareness, inferring causality and conducting experiments. Most relevant to 2 curriculum learning in particular, Minecraft features a large tech-tree with many dependencies, making it relatively straightforward to define tasks of varying difficulty that depend on each other to varying degrees. In our experiment, in each task the agent is asked to obtain one out of 107 Minecraft items on command ("Simon Says"), some of which are deep into the tech tree (Figure 4). Our key results are: • Uniform sampling does not learn many tasks, and learning flatlines at a low level (Figure 1, red). • An exploration bonus (as an auxiliary reward) to perform tasks unrelated to the current goal (a.k.a. curiosity search [2, 3]) substantially improves performance (Figure 1, green). • Adding an additional across-training diversity pressure (similar to novelty search [4] and intrinsic motivation [5]) by removing the exploration bonus dynamically for items the agent can already reliably obtain further improves performance (Figure 1, yellow). • Adding a learning progress curriculum increases performance even more (Figure 1, dark dotted blue). A video of a successful agent obtaining challenging items high up in the tech tree can be viewed at https://youtu.be/MFDudOvn3oc. • With the learning progress curriculum, the sampling of tasks elegantly follows the learning curve of the agent, focusing learning on the frontier of the agent’s skill set as that skill set expands (Figure 3, bidirectional learning-progress curriculum). • Looking for any learning change (including performance drops) (Figure 1, dark dotted blue) prevents the catastrophic forgetting of previously learned tasks that otherwise occurs when you only measure learning improvements (Figure 1, light solid blue), hurting overall performance. 90 Items discovered (p(Success) > 0.05) ie) 10000 20000 30000 40000 50000 Optimization step — uniform, # no exploration bonus =--- uniform, fixed exploration bonus —-- # trees —— # dynamic exploration bonus bidirectional learning progress curriculum unidirectional learning progress curriculum uniform, Figure 1: Number of discovered “Simon Says” target items (out of a total of 107 items) as a function of optimization steps for each of the training schemes we explore. Our goal was to maximize the number of items the agent is able to obtain and not to focus on obtaining high success probabilities; we therefore classify items with success probability larger than 5% as discovered3. The bidirectional learning progress curriculum discovers the largest number of items, followed by uniform sampling with dynamic exploration bonus, uniform sampling with fixed exploration bonus and uniform sampling without any exploration bonus. The unidirectional learning progress curriculum at times discovers almost as many items as the bidirectional learning progress curriculum, but undergoes cycles where it forgets and rediscovers a large fraction of discovered items. We found inter-run variation to be low, and each run was expensive (21d on 32 GPUs), so we only plot one run per treatment. 3 uniform no exploration bonus uniform bidirectional unidirectional dynamic exploration bonus learning progress curriculum learning progress curriculum uniform fixed exploration bonus Figure 2: Conditional success probabilities of individual "Simon Says" target items under each treatment. Items are ordered according to the order in which the bidirectional learning-progress curriculum learns to collect the items. We only show items that are discovered by at least one of the treatments. The bidirectional learning progress curriculum discovers a super set of items discovered by other treatments. uniform uniform uniform bidirectional no exploration bonus fixed exploration bonus dynamic exploration bonus learning progress curriculum learning progress curriculum 0 20000 40000 o. 20000 400000 20000 © 400000 20000 © 40000 o. 20000 40000 unidirectional Figure 3: Probability of sampling individual “Simon Says” target items under each treatment. Items are ordered as in Figure 2. The learning progress curricula accurately track, and thus sample, items whose success probability changes (for bidirectional-learning progress) or increases (for unidirectional-learning progress) the most. # 2 Methods # 2.1 Learning progress curriculum First, we identify the conditions where we expect curriculum learning to work much better than uniform sampling: assume we are given a long list of mutually dependent and progressively more difficult RL tasks T1, ..., TN . We further assume that a policy that has mastered Ti can learn Ti+1, but not Ti+2. An agent can therefore learn all tasks if they are presented in this order. However, learning all tasks under uniform sampling is much harder, because only every 1/N -th rollout is sampled from a learnable task. At a minimum, if it takes at least H samples per batch from task T to learn it, 3We found that the 5% threshold clearly shows the differences between the different treatments within 50,000 optimizers steps, but we expect that similar results could be obtained for higher success-probability thresholds given sufficient additional training. 4 ES bowl anvil iron leggings activator rail clock lapis block eal block bucket yon ore compass ‘old block diemond axe cauldron dropper diamond block dirt cobblestone wall chest minecart iron shovel jukebox diamond boots dye furnace flint and steel iron sword noteblock golden boots diamond chestplate lever furnace minecart iron trapdoor _ piston golden chestplate diamond helmet gravel stone heavy weighted PP leaves golden helmet diamond hoe ladder stone axe hopper minecart tedstone block golden hoe diamond legginy stone hoe hopper minecart rail redstone torch _ golden leggings diamond pickaxe iron axe shears golden pickaxe diamond shovel sapling stone shovel iron bars shield golden rail diamond sword sign stone slab iron block taligrass golden shovel obsidian stick stone sword iron boots trapped chest golden sword trapdoor torch iron chestplate, tripuire hook light weighted PP wheat seeds iron door web wooden axe iron helmet wooden button iron hoe wooden door weodenlhios (Success) > 0.05 Saath 0.0 < p(Success) < 0.05 wooden shovel p(Success) = 0 wooden slab wooden sword Figure 4: Set of 107 "Simon Says" Minecraft items that the agent is tasked to obtain. The left-most column contains items the agent can obtain at the surface without mining. The remaining items are grouped by the mining resource ("stone", "coal", "iron", "lapis", "redstone", "gold", "diamond") that is required to craft them. From left to right, item categories are roughly ordered by how difficult they are to obtain. Difficulty is mainly determined by how deep they are in the Minecraft tech tree and by how rare they are to find. The highlighted items are prerequisite items for downstream items, and thus represent essential stepping stones in the curriculum. The color code indicates the final success probability of our best treatment (the bidirectional learning progress curriculum, presented below). The agent obtains 82 items with success probability > 0.05, 4 items have non-zero success probability below 0.05, and 27 items have zero success probability. In comparison, a naive baseline (uniform sampling only) obtains only 17 items with success probability > 0.05. we will need to collect N times more samples (i.e. train with an N -times larger batch size) when performing uniform sampling just to ensure that we get H samples from task T per batch. In addition, the non-learnable tasks may add additional noise to each batch without providing any signal, meaning an even larger than N -times larger batch size may be needed. The optimal curriculum is therefore much more compute efficient than uniform sampling. A key requirement of designing an automatic curriculum is to infer which new task may be learnable given the current skill a priori. A common approach is to use success probability as a proxy for learnability. Typically, one defines a lower success probability threshold below which tasks are considered too hard and an upper success probability threshold above which tasks are considered too easy and one would predominantly sample tasks between these two thresholds [6, 7, 8]. However, this approach has several shortcomings: First, if the initial state of the environment is randomized, the agent may have intermediate success probability on a task solely because the task is too easy from some initial states and too hard (or even impossible) from others, thus preventing the agent from improving any further. In Minecraft, for example, it is only possible to collect jungle planks when starting in a jungle biome. If the agent only starts in the jungle 20% of the time, its success probability for jungle planks would be capped at 20%, even if it perfectly learned the task. Second, success probability thresholds that correlate well with learnability might in general depend on the task, the initial state of the environment and the learning stage of the agent. Finally, stochastic environments (i.e. environments with a stochastic transition function) can have a similar disconnect between success probability and learnability as environments with random initial states: An easy-to-learn task may be capped at an intermediate success probability because of an uncontrollable stochastic event that prevents the agent from succeeding reliably. Selecting tasks with intermediate success probability might therefore select tasks where the agent cannot learn anything new. Instead, we infer learnability of tasks by measuring learning progress, i.e. the recent change in success probability for each task. Given such a measure, the curriculum predominantly samples tasks with large learning progress. We explore sampling based on a bidirectional learning progress measure 5 (that tracks both increases and decreases in success probability) and a unidirectional measure (that only tracks increases in success probability). The advantage of sampling based on the bidirectional measure is that it not only samples novel tasks when they start showing learning progress, but also samples tasks that are being forgotten. # 2.2 Learning progress inference When designing a process to infer learning progress from empirical measurements of successes and failures on a given task it is important to consider the parameters that influence the accuracy of a learning progress estimator. In particular, as learning progress is measured in terms of how the success probability changes over time, it is important to pick the appropriate time scale ∆t over which the before/after change in success probability is measured. Consider the following example of a task whose true success probability (black) increases over time (Figure 5, left). 1 ae pronabiiy ? — empirical 1 — True slope f —— (at*) prediction — Measured probability i 5 Be | --- infertedstope: smatat g 2 | w-= Inferred slope: middle at / 3 5 1S | ~~~ inferred stope: large at / $ R 3 : ; 8 3 a a a 4 3 8 3 2 3 g 8 g g g g a g 3B 0 ° Time it Figure 5: Inference of learning progress on an example fictional problem from the slope of the measured success probability curve. We would like to infer the true learning progress at t = 0 (vertical dotted black line), which we define as the slope of the success probability curve (solid red line), from the success probabilities measured at time snapshots t and t − ∆t. However, we only have access to a history (up to t) of noisy measurements of success probability (jagged grey line; the measurements here are sampled from a binomial distribution with the success probability p equal to the value of the true probability - the black line - at time t and n, the number of samples, set to 200): If we choose ∆t too small, we end up measuring the slope of the noise (dashed yellow line) instead of the slope of the underlying trend (with different noise the slope of yellow could have actually been sharply negative!); the variance of our estimator is too high. If we choose ∆t too large we do not fully capture recent changes in the slope (light blue); our estimator is biased (in the statistical sense: the error is non-zero even with infinite data). An intermediate ∆t gives us a good trade-off between bias and variance (dashed dark blue line). Indeed, resampling from the binomial many times (each sample being noisy owing to the small sample size) shows that the expected square error is minimal for intermediate values of ∆t (Figure 5, middle, blue) and we can show analytically that this is in general true for any curved success probability curve (Figure 5, middle, orange and Appendix A.1). Besides picking the right time scale, we can improve the reliability of our learning progress estimator by calculating it based on the success probability measurements of all previous time steps, rather than just two snapshots in time. We can implement this by replacing the snapshots with two exponential mean average (EMA) processes with different time scales. In particular, the first EMA represents a "fast success probability" pfast estimate for each task (Figure 5, right, red). We then smooth pfast with a second, identical EMA to obtain a "slow success probability" estimate pslow (green). From there, we define learning progress as the difference between the fast and slow success probability estimates (Figure 5, right, yellow). This learning progress estimate increases after the success probability curves upward (meaning the agent is going from no learning progress to increasing learning progress), flattens after the success probability reaches a linear upward trend (meaning learning progress is happening at a steady pace), and finally goes down to zero again after the measured success probability converges (meaning no further learning progress is happening because the agent has learned everything there is to learn on this task). Note that learning progress does not perfectly follow the derivative of the success probability, but is delayed because it is calculated from two EMA processes which themselves are delayed estimates of the success probability. In practice, we are able to correct for this temporal delay, as explained in detail below. Based on this definition of 6 learning progress, we further define bidirectional and unidirectional learning progress as the absolute and rectified difference, respectively, between fast and slow success probability. If pfast is larger than pslow, as in Figure 5, right, the two measures are identical. We can improve the curriculum further by putting additional focus on tasks that have not only high learning progress, but also a low success probability. The rationale is as follows: Our goal is to learn as many tasks as possible, as opposed to learning a few tasks very well. We thus care much more about an improvement from 0.01% to 5% in a new task than we do about moving a task we already perform well on from 95% to 99.99% reliability (this is the same reason why we chose a 5% threshold for the purpose of evaluation). Since low success probability tasks are more likely to be novel, putting particular focus on them helps to expand the set of learned tasks. In addition, low success probability tasks are also harder to learn because the agent observes fewer successes. Sampling hard tasks more often increases the number of successes and therefore helps to mitigate the exploration problem. While our focus on low-probability tasks may seem reminiscent of the fixed success-probability-threshold methods discussed above, it avoids the false positives when selecting tasks solely based on success thresholds because it excludes tasks without learning progress. We implement this focus by applying a reweighting function to pfast and pslow before computing learning progress. The reweighting function we use magnifies learning progress in tasks with low success probability at the expense of learning progress in tasks with high success probability. However, tasks without learning progress are still mapped to zero learning progress, no matter the success probability (see Appendix A.2 for details). In the fictional example above, reweighted learning progress is given by the blue curve in Figure 5, right. The figure illustrates that this reweighting can also compensate for the temporal delay that we observed with the regular learning progress estimate because success probabilities will be lowest right when the agent starts to learn a particular task. Reweighting is applied in the same way for bidirectional and unidirectional learning progress. As a last step, we use a sampling function that focuses 90% of sampling weight on roughly 20% of tasks with the largest reweighted learning progress. This sampling function was designed to strike a balance between focusing only on the tasks with the highest learning probability, which can cause catastrophic forgetting of all other tasks, and uniformly sampling all tasks, which would waste a lot of computation on tasks where no learning progress is observed (see Appendix A.3). In conclusion, by taking the difference between a fast and slow estimate of the measured success probability we obtain an accurate, but delayed, estimate of learning progress (Figure 5, yellow). By reweighing this estimate towards tasks with low success probability we compensate for the delay and put the majority of focus on exactly those tasks that are currently learnable, but have not been learned yet (Figure 5, blue). Taking 90% of our samples from the tasks that score within the top 20% of this reweighed learning-progress metric thus ensures that our curriculum always pushes on the frontier of the currently learnable tasks that have not been learned (well) yet. # 2.3 Curricula over goal-conditioned tasks A key requirement of curriculum learning (at least using current RL methods) is that the agent achieves a small success probability (within available/reasonable compute) on a new task after mastering a previous task. However, if tasks differ by goals that are given as observations to the agent, the agent may not know how to interpret the new goal observation and may just display random behavior instead of the behavior of a prerequisite task. In addition, obtaining useful feedback in a goal-conditioned setup is much harder than learning unconditional tasks because the agent only experiences a positive reward for completing the new task in episodes where the goal matches the task. The success probability of the new task is therefore suppressed by the background probability of sampling the corresponding goal, which makes the task difficult to learn. We can encourage the discovery of new goals by combining the goal-conditioned main reward with a goal-independent exploration bonus for all of the curriculum tasks, even if they are unrelated to the current goal. This exploration bonus helps the agent to explore the environment when given an unknown goal, thus increasing the chances of success. In our Minecraft experiment, where a new goal corresponds to collecting a new item, for each item in the set of potential goal items, we provide a reward the first few times the agent collects that item in an episode, regardless of the currently selected goal. Specifically, the agent receives a reward of 0.5N for the N -th collection of the same item, i.e. the reward decays with a factor of 0.5 for each subsequent collection. In addition, the agent 7 only receives a reward for a subsequent collection of item X if N is larger than the number of items X in its inventory at any previous time during the episode (this constraint prevents the agent from just racking up reward by dropping and picking up items). The exploration bonus therefore incentivizes the agent to constantly collect or craft new items that it hasn’t held previously during the episode. This idea of encouraging an agent to do as many new, different things within an episode is similar to previous work in Curiosity Search [2, 3]. The exploration bonus is combined with the main reward by simply summing the two rewards, meaning they have to be carefully balanced: the agent may favor the exploration bonus over the main reward if the exploration bonus is too high or not gain any benefits from the exploration bonus when it is too low. In addition, this balance will have to change as the curriculum advances; at the start of training it is fine for the agent to get an exploration bonus for all of the easy tasks, but as the curriculum moves towards harder tasks it becomes increasingly likely that the agent will spend most of the limited time it has per episode collecting reward by obtaining the exploration bonus for all easy items rather than attempting to complete the hard task selected by the curriculum. In our experiments, this balance is maintained across training by a second curriculum that successively removes already-learned goals from the exploration bonus. We call this curriculum-based exploration bonus the "dynamic exploration bonus". In our Minecraft experiment, we implement the dynamic exploration bonus in the following way: Using exponential mean averaging (EMA), we keep track of the individual success probabilities in the main, goal-conditioned, task. Only items for which the agent has a success probability smaller than 0.1 are included in the set of items rewarded by the exploration bonus (called "exploration set"). Thus, as the agent improves its performance over training, items are successively removed from the exploration set, but are added back if the performance on the corresponding task drops again below 0.1. The dynamic exploration reward can be seen as an implementation of across-training diversity pressure similar to previous work in Novelty Search [4] and Intrinsic Motivation [5]. # 2.4 "Simon Says" task We study curriculum learning on a set of goal-conditioned Minecraft tasks, in which the agent is tasked to collect one out of a set of 107 items from the Minecraft tech tree (Figure 4)4. Some items (such as "dirt") can be very easily obtained, while other items (such as "diamond") are rare and also require first obtaining many other resources and crafting required tools. The agent observes the target item as a one-hot encoding. It has 5 minutes (1500 time steps) to complete the task and obtains a reward of +1 upon success. After each success or failure a new task is selected without resetting the world or respawning the agent. Tasks may be sampled uniformly or from a distribution that is determined by a curriculum. The maximum episode length is 30 minutes (9000 time steps), but the episode is terminated prema- turely if the agent has failed two consecutive tasks or dies of other causes, such as drowning, falling off a cliff or falling in lava. After an episode ends, a new episode is started in a new environment, but the agent has a 50% chance to retain the inventory from the end of the previous episode. In preliminary experiments, we found that this "inventory inheritance" leads to slightly faster learning, as the agent does not always have to gather all the necessary prerequisite items from scratch when trying to learn how to obtain difficult items deep in the tech tree. Because each run was computationally expensive (21d on 32 GPUs) we only plot one run per treatment, but we found inter-run variation to be low. # 3 Results: Evaluation on Minecraft "Simon Says" # 3.1 Uniform sampling without exploration bonus In the standard Simon Says task, the agent only experiences a positive reward for obtaining an item if the item corresponds to the goal of the task. This makes all but the easiest tasks difficult to learn, because the success probability of the task is suppressed by the probability of sampling the corresponding goal and because there is no other exploration bonus. As expected, the results with this 4In addition to the 107 items displayed in Figure 4, the target set also contains 6 additional items that we later realized were impossible for the agent to obtain. 8 method are poor: the agent only learns to obtain 17 out of 107 tasks (Figure 1, red line). Note that we say that the agent has "learned" a task if it achieves a success probability of at least 5%. Worse, the plot shows that learning plateaued early and does not improve over time. The agent only discovers a subset of items that can be obtained on the surface, such as "dirt", "sapling" and a number of wooden tools (Figure 2, 1st from left). # 3.2 Uniform sampling with fixed exploration bonus To support exploration of harder tasks, we add the exploration bonus over all items in the Simon Says 107 set. The exploration bonus is added to the main Simon Says reward with a coefficient that was tuned to each condition. For uniform sampling without curriculum we found in preliminary experiments that a coefficient of 0.05 performs best. Adding the exploration bonus increases the number of explored items at convergence from 17 to 43 (see Figure 1, dotted green line). The agent discovers almost all surface items, learns to mine underground, learns to craft stone tools, and even discovers how to create a few iron tools such as "iron ingot", "heavy weighted pressure plate", "tripwire hook" and "iron shovel" (Figure 2, 2nd from left). # 3.3 Uniform sampling with dynamic exploration bonus However, while the exploration bonus helps the agent in solving a larger number of tasks, it actually can make it hard to learn to collect harder items that are deeper in the tech tree. The reason is that the exploration bonus equally rewards items that the agent already knows how to obtain (but has not yet obtained this episode) and items that the agent still needs to learn how to get. When given a hard-to-obtain goal that the agent has not learned yet, it may be more rewarding to collect easy-to-obtain and previously learned items in order to collect their exploration bonus, therefore "distracting" the agent from the task it is currently supposed to complete. One straightforward solution to this problem is to provide an exploration bonus only for those items that the agent does not yet reliably know how to obtain. This allows us to include the exploration bonus only when it is useful, namely for learning how to obtain new items, without distracting the agent. The "dynamic exploration bonus" implements exactly this idea by removing items whose goal- conditioned success probability in the main Simon-Says task is larger than 0.1. As we only give an exploration bonus for hard items that the agent rarely gets, we can increase the coefficient of the exploration bonus without increasing the extent to which the agent gets distracted by easy items. In preliminary experiments we found that a coefficient of 0.5 performed best. The dynamic exploration bonus further increases the number of explored items at convergence to about 70 (see Figure 1, dashed yellow line). From within the target set, the agent discovers all surface items, all stone items, most iron items and most redstone items (Figure 2, 3rd from left). Conceptually, the dynamic exploration bonus and the conditional Simon Says reward interleave in the following way: At first, the exploration bonus incentivizes the agent to learn how to obtain an item unconditionally, i.e. irrespective of the current Simon Says task. As the unconditional success probability increases, so does the conditional success probability, that is, the success probability when the new item corresponds to the goal. Once the conditional success probability surpasses 0.1, the item is removed from the exploration set and is only rewarded through the main Simon Says reward (i.e. only when given the task where the item corresponds to the goal). The agent can then solidify the association between the observed Simon Says task label and the task. # 3.4 Learning progress curriculum In this treatment we sample Simon Says tasks using the learning progress curriculum instead of uniform sampling. As in the previous section, we remove easy items from the exploration set using the dynamic exploration bonus and we again set the overall coefficient of the exploration bonus to 0.5. The learning progress curriculum improves task learning by two mechanisms: First, by focusing on Simon Says tasks with the largest learning progress it supports learning the conditional association between task label and task. Second, the curriculum interacts with the exploration bonus to facilitate the unconditional discovery of novel items. If learning progress is made on an item such that the 9 curriculum frequently samples it, the agent is likely to obtain it more often and, if that item is a prerequisite for any dependent items, the agent is now more frequently in a position where it actually has this prerequisite item and is thus able to collect the dependent items. We tested both the bidirectional and unidirectional versions of the learning progress curriculum (described above). With the bidirectional learning progress curriculum, the agent discovers 82 items (see Figure 1, dotted blue line). The agent discovers all surface items, all stone items, most iron items, most redstone items, half of the golden items and a few diamond items (Figure 2, 2nd from right). With the unidirectional learning progress curriculum, the agent discovers 79 items (see Figure 1, solid light blue line and Figure 2, 1st from right), which is almost as many as the bidirectional learning progress treatment, but training in the unidirectional treatment is unstable because of many cycles of forgetting and rediscovery (see next section). Both curricula accurately sample items for which success probability changes or increases the most (compare Figure 2, 1st and 2nd from right with Figure 3, 1st and 2nd from right). With both the bidirectional and unidirectional learning-progress curricula, the interaction between the dynamic exploration bonus and the conditional Simon Says reward is similar to the interaction between the dynamic exploration bonus and uniform sampling. However, with the learning progress curricula the learning of the conditional association (performing the task when asked) is more focused and accelerated, because the learning progress curriculum detects the increase in conditional success probability and consequently focuses on that task, which means there will be many more rollouts where the task is also the current goal and thus many more positive examples from which the agent can learn the association. # 3.5 Mitigating catastrophic forgetting by tracking bidirectional learning progress A curious phenomenon of the unidirectional learning progress curriculum is that it goes through cycles where the number of discovered items drop sharply, before it again recovers. These cycles are caused by catastrophic forgetting owing to correlations in learning progress between groups of items. As an example, let us consider a case where, after having discovered underground items, the agent improves its success probability for a surface item such as "sapling". The unidirectional learning progress curriculum samples "sapling" more often which causes the agent to spend more time at the surface, which in turn causes the agent to also improve its success probability for other surface items (they are easier because the agent is already on the surface), creating a positive feedback loop. Meanwhile, success probabilities for underground items decrease because the agent spends less time underground and thus forgets (catastrophically) how to perform such tasks. The bidirectional learning progress curriculum would immediately increase its sampling of underground items in order to prevent those tasks from being forgotten, which would prevent catastrophic forgetting and thus cycles from appearing. In contrast, the unidirectional learning progress curriculum does not increase the sampling of underground items when their success probabilities are decreasing. As a consequence, it enters a period where it exclusively focuses on surface items and generally these periods last long enough for the agent to almost completely forget how to obtain underground items when asked. Since only 24 out of the 107 potential goals are surface items, this causes a large drop in the number of discovered items. However, after about 1000-2000 optimizers steps, the curriculum notices positive learning progress on the underground items again, allowing it to rediscover underground items, and the number of discovered items recovers (Figure 1, solid light blue line). Interestingly, much of the ability to perform these skills is still latent in the network, as its performance recovery is swift. Neural networks in general and RL agents in particular are subject to catastrophic forgetting if the data distribution changes during learning. The easiest method to mitigate catastrophic forgetting is to sample the data i.i.d. (i.e. uniform sampling of discrete tasks), whereas a curriculum might cause the agent to forget early tasks. The success of the bidirectional learning progress curriculum shows that monitoring previous tasks and resampling them if their performance drops can be a powerful method to mitigate catastrophic forgetting. As shown in Figure 3, 2nd from right, only sporadic resampling of old tasks is sufficient, which is much more compute efficient and has better scaling properties than iid sampling of all previously learned tasks. 10 # 4 Related work Automated curriculum learning There is an extensive literature on training neural networks with a curriculum [9], see [10] for an overview. More recently, automated curricula have been studied extensively in the context of RL in [11, 12, 13, 14, 6, 7, 8, 15, 16, 17, 18, 19]. Generally, tasks are selected based on success probability or reward thresholds [6, 7, 8, 16] or regret [17, 18]. Static- threshold-based methods present an intuitive starting point for a curriculum, but have the downside that they are difficult or even impossible to tune, as discussed previously (Sec. 3.4). Regret-based methods calculate per-task regret by subtracting the average return over several rollouts on that task from the maximum (known) return on that task, and then preferrably select tasks where regret is high, with the theory being that there is still a lot to learn on tasks where regret is high [17, 18]. In the presence of environmental stochasticity, this scheme may select more stochastic, less learnable tasks at the expense of less stochastic, more learnable tasks, because the maximum return may have been obtained under particularly lucky conditions such that the average return will always be much lower, despite there being nothing left to learn. Learning-progress-based curricula, like the method in this paper, have the potential to address these issues, as discussed next. Learning progress was first proposed as a curiosity signal that incentivizes agents to explore novel states in stochastic environments [20, 21, 22]. Later, in [23, 13, 14] learning progress was used as a measure to select tasks in a curriculum. The novel contributions of our work are to systematically study how learning progress can be measured reliably, to apply learning progress curricula on hard problems that require RL at scale, and to show how learning progress curricula over goals can be combined with a dynamic, goal-independent exploration bonus. Curiosity Search The static exploration bonus we examined incentivizes the agent to obtain items that it has not obtained in the current episode, and is thus a method for encouraging within-episode exploration. Within episode exploration has previously been explored in the Curiosity Search work by [2, 3], who demonstrated that it effectively encourages agents to explore their environment, though they also demonstrated the downside of having to explore the entire environment in every episode when trying to perform deep exploration. Intrinsic motivation The dynamic exploration bonus, on the other hand, changes over training and encourages the agent to obtain different items, not within a single episode, but across episodes. Exploration across episodes has been extensively studied in the form of count-based exploration (e.g. [5]), where the algorithm tracks the number of times each state has been visited over training and provides a bonus reward to the agent for visiting each state that is inverse proportional to the number of times that state has been visited. [24] adapted count-based exploration to work in state-spaces that are too large to keep individual counts, and they demonstrated some success in deeply exploring sparse reward environments. However, later work [25, 26] hypothesized that unconditional count- based exploration methods can suffer from detachment, where the agent consumes all the intrinsic reward towards one or more states and forgets how to return to those states, and derailment, where the exploratory mechanism of the algorithm can prevent the agent from returning to a previously visited state. Our bidirectional learning-progress curriculum avoids detachment by immediately increasing the sampling rate of any goal where success probabilities are declining, thus reducing the probability that the agent forgets how to visit a previous "state", as well as by reintroducing items back into the exploration bonus reward set if their success probability ever drops too low, thus ensuring that the agent can always recover. The learning-progress curriculum does not address derailment as explicitly, but the underlying dynamic exploration reward does in effect reduce derailment by removing learned items from the exploration bonus; while the agent is in a state where it does not have the necessary prerequisites to obtain any of the items still in exploration bonus reward set, it is incentivized to first obtain the necessary prerequisites (without taking exploratory actions), before focusing on exploratory actions again. # 5 Discussion, Conclusion, and Future Work We have introduced a learning-progress curriculum with a dynamic exploration bonus that adapts to the current skill level of the agent. Experiments were conducted on the Minecraft "Simon Says" tasks. We first showed that uniform sampling with no exploration bonus performs poorly, obtaining only 17 tasks and hitting a ceiling at that level where additional training produces no new learning. We then showed that combining the main goal-dependent reward with a static goal-independent 11 exploration bonus increases the number of learned tasks from 17 to 43. Dynamically adjusting the exploration bonus to only include tasks with low success probability further increases the number of learned tasks to 70. Sampling tasks using the bidirectional learning progress curriculum instead of uniform sampling further increases the number of solved tasks to 82. Moreover, the sampling of tasks elegantly follows the learning curve of the agent, focusing learning on the frontier of the agent’s skill set as that skill set expands. In addition, the bidirectional learning progress curriculum, which tracks both tasks with improvements and deterioration in performance, effectively mitigates catastrophic forgetting (which we see in the unidirectional learning-progress curriculum) by resampling tasks that are at risk of being forgotten. There are various ways in which the learning progress curriculum could be expanded in future work. First, while the current method was designed under the assumption that explicit task labels are available, it could be made more general by developing methods that can dynamically group tasks into clusters over which learning progress is averaged. Second, if the number of tasks becomes too large it becomes computationally expensive to faithfully estimate learning progress for each task. A promising future direction would be to estimate learning progress over large tasks spaces using function approximation or, relatedly, generate environments that are expected to feature high learning progress via a neural network environment generator. # Acknowledgments We thank Ilge Akkaya, Bob McGrew, Reiichiro Nakano, Matthias Plappert and John Schulman for discussions, support and feedback on this manuscript. # References [1] William H Guss, Brandon Houghton, Nicholay Topin, Phillip Wang, Cayden Codel, Manuela Veloso, and Ruslan Salakhutdinov. Minerl: A large-scale dataset of minecraft demonstrations. arXiv preprint arXiv:1907.13440, 2019. [2] Christopher Stanton and Jeff Clune. Curiosity search: producing generalists by encouraging individuals to continually explore and acquire skills throughout their lifetime. PloS one, 11(9):e0162235, 2016. [3] Christopher Stanton and Jeff Clune. Deep curiosity search: Intra-life exploration improves performance on challenging deep reinforcement learning problems. arXiv preprint arXiv:1806.00553, 2018. [4] Joel Lehman and Kenneth O Stanley. Abandoning objectives: Evolution through the search for novelty alone. Evolutionary computation, 19(2):189–223, 2011. [5] Alexander L Strehl and Michael L Littman. An analysis of model-based interval estimation for markov decision processes. Journal of Computer and System Sciences, 74(8):1309–1331, 2008. [6] Rui Wang, Joel Lehman, Jeff Clune, and Kenneth O Stanley. Paired open-ended trailblazer (poet): Endlessly generating increasingly complex and diverse learning environments and their solutions. arXiv preprint arXiv:1901.01753, 2019. [7] Rui Wang, Joel Lehman, Aditya Rawal, Jiale Zhi, Yulun Li, Jeffrey Clune, and Kenneth Stanley. Enhanced poet: Open-ended reinforcement learning through unbounded invention of learning challenges and their solutions. In International Conference on Machine Learning, pages 9940–9951. PMLR, 2020. [8] OpenAI, Ilge Akkaya, Marcin Andrychowicz, Maciek Chociej, Mateusz Litwin, Bob McGrew, Arthur Petron, Alex Paino, Matthias Plappert, Glenn Powell, Raphael Ribas, et al. Solving rubik’s cube with a robot hand. arXiv preprint arXiv:1910.07113, 2019. [9] Jeffrey L Elman. Learning and development in neural networks: The importance of starting small. Cognition, 48(1):71–99, 1993. [10] Yoshua Bengio, Jérôme Louradour, Ronan Collobert, and Jason Weston. Curriculum learning. Proceedings of the 26th annual international conference on machine learning, pages 41–48, 2009. [11] Sainbayar Sukhbaatar, Emily Denton, Arthur Szlam, and Rob Fergus. Learning goal embeddings via self-play for hierarchical reinforcement learning. arXiv preprint arXiv:1811.09083, 2018. [12] Carlos Florensa, David Held, Xinyang Geng, and Pieter Abbeel. Automatic goal generation for rein- forcement learning agents. In International conference on machine learning, pages 1515–1528. PMLR, 2018. [13] Tambet Matiisen, Avital Oliver, Taco Cohen, and John Schulman. Teacher–student curriculum learning. IEEE transactions on neural networks and learning systems, 31(9):3732–3740, 2019. 12 [14] Rémy Portelas, Cédric Colas, Katja Hofmann, and Pierre-Yves Oudeyer. Teacher algorithms for curriculum learning of deep rl in continuously parameterized environments. In Conference on Robot Learning, pages 835–853. PMLR, 2020. [15] Yunzhi Zhang, Pieter Abbeel, and Lerrel Pinto. Automatic curriculum learning through value disagreement. Advances in Neural Information Processing Systems, 33, 2020. [16] Andres Campero, Roberta Raileanu, Heinrich Küttler, Joshua B Tenenbaum, Tim Rocktäschel, and Edward Grefenstette. Learning with amigo: Adversarially motivated intrinsic goals. arXiv preprint arXiv:2006.12122, 2020. [17] Michael Dennis, Natasha Jaques, Eugene Vinitsky, Alexandre Bayen, Stuart Russell, Andrew Critch, and Sergey Levine. Emergent complexity and zero-shot transfer via unsupervised environment design. arXiv preprint arXiv:2012.02096, 2020. [18] Izzeddin Gur, Natasha Jaques, Kevin Malta, Manoj Tiwari, Honglak Lee, and Aleksandra Faust. Adversarial environment generation for learning to navigate the web. arXiv preprint arXiv:2103.01991, 2021. [19] OpenAI, Matthias Plappert, Raul Sampedro, Tao Xu, Ilge Akkaya, Vineet Kosaraju, Peter Welinder, Ruben D’Sa, Arthur Petron, Henrique Ponde de Oliveira Pinto, et al. Asymmetric self-play for automatic goal discovery in robotic manipulation. arXiv preprint arXiv:2101.04882, 2021. [20] Jürgen Schmidhuber. Curious model-building control systems. In Proc. international joint conference on neural networks, pages 1458–1463, 1991. [21] Pierre-Yves Oudeyer, Frederic Kaplan, and Verena V Hafner. Intrinsic motivation systems for autonomous mental development. IEEE transactions on evolutionary computation, 11(2):265–286, 2007. [22] Kuno Kim, Megumi Sano, Julian De Freitas, Nick Haber, and Daniel Yamins. Active world model learning with progress curiosity. In International Conference on Machine Learning, pages 5306–5315. PMLR, 2020. [23] Alex Graves, Marc G Bellemare, Jacob Menick, Remi Munos, and Koray Kavukcuoglu. Automated curriculum learning for neural networks. In international conference on machine learning, pages 1311– 1320. PMLR, 2017. [24] Marc G Bellemare, Sriram Srinivasan, Georg Ostrovski, Tom Schaul, David Saxton, and Remi Munos. Unifying count-based exploration and intrinsic motivation. arXiv preprint arXiv:1606.01868, 2016. [25] Adrien Ecoffet, Joost Huizinga, Joel Lehman, Kenneth O Stanley, and Jeff Clune. Go-explore: a new approach for hard-exploration problems. arXiv preprint arXiv:1901.10995, 2019. [26] Adrien Ecoffet, Joost Huizinga, Joel Lehman, Kenneth O. Stanley, and Jeff Clune. First return, then explore. Nature, 590(7847):580–586, Feb 2021. [27] Lasse Espeholt, Hubert Soyer, Remi Munos, Karen Simonyan, Vlad Mnih, Tom Ward, Yotam Doron, Vlad Firoiu, Tim Harley, Iain Dunning, et al. Impala: Scalable distributed deep-rl with importance weighted actor-learner architectures. In International Conference on Machine Learning, pages 1407–1416. PMLR, 2018. [28] John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. Proximal policy optimization algorithms. arXiv preprint arXiv:1707.06347, 2017. [29] John Schulman, Philipp Moritz, Sergey Levine, Michael Jordan, and Pieter Abbeel. High-dimensional continuous control using generalized advantage estimation. arXiv preprint arXiv:1506.02438, 2015. # A Appendix # A.1 Optimal ∆t for estimating learning progress: Let us model success probability as an i.i.d stochastic process x(t) with mean y(t) and variance o°(t). Learning progress is given by the derivative of the mean, j1'(t). We want to estimate learning progress j’(t) by averaging n samples from x(t) and from x(t — At) and calculating the difference quotient: The expected square error of this estimator a) nda we Xi wi(t=Ab) jg given by: en? = 277 +4 ul" (tA? + O(At*) (1) nae” gh WP 7 where 6? = 3 (0°(t) +0°(t — At)) is the average variance and j:”(t) is the second derivative (curvature) of the mean. The notation O(At?) means that we assume At to be small and that we 13 neglect terms of third order and higher. The curve (1) corresponds to the orange curve in Figure 5, middle. 1 4 The optimal Az that minimizes the square error in (1) is given by (At)op: = (far) "Tf we increase the number of measurements n, our estimate of success probability becomes more accurate and we can afford a smaller At. If the curvature j.’’(t) increases (i.e. the success probability curve has high curvature), we need to choose a smaller At to keep the bias of our estimator in check. If the average variance G” gets larger, we need to increase At to keep the variance of our estimator in check. The optimum exists if and only if ju’”(t) is non-zero. # Proof of (1): Since we know the means and variances of the samples of x(t) and (t — At) we can also calculate a a c. =i aj (t— soe the mean and variance of the estimator ju/(t) = Lisl) Eom watt At) , because the latter is just defined by a linear combination of x;(t) and x;(t — At). For the mean we find: syy\ _ £Xi (wilt) — 2D w(t At) _ p(t) — p(t — Ad) wo At At This means that our estimator is an unbiased estimator of the finite difference quotient, but not of the derivative j.'(t) (which we obtain in the limit At + 0). We can calculate the relationship between the two by Taylor-expanding to second order in At: p(t — At) = p(t) — p/(t)At+ SH AP + O(At?) The O(∆t3)-notation means that we are neglecting 3rd and high-order terms in ∆t, because we assume ∆t to be small. Plugging this expression in our expression for the mean yields: (i(t)) = ul) — Sul (At + O(AP) This expression means that the bias of our estimator is determined (to first order) by the second derivative of the mean. Note also that the neglected terms are now of 2nd order and higher, because we have divided by ∆t. For the variance we find: ay yy, Varvi(t) + 7, Varai(t— At) — 40(t) + 4o(t — At) n At? At? Var ji’ (t) To arrive at this expression we have made use of several facts and assumptions: Since all samples from x(t) and x(t−∆t) are uncorrelated we can simply add the variances. Second, if one multiplies/divides a random variable by a constant, its variance gets multiplied/divided by the square of the same constant. Using our expression for the average variance, ¯σ2 = 1 by: * 2a? Var pi! (t) = ——5 u(t) = Ap The expected square error of our estimator is given by the sum of the square of the bias and the variance: R 2 B 2a? 1 : er? = ((#") - H(t) + Var fl(t) = oy + GH" (WPAP + Ot), 14 which completes our proof. # A.2 Reweighting of learning progress towards small success probabilities For each task we use EMAs with different time scales to obtain a "fast" and a "slow" measure of success probability, pfast and pslow. Our bidirectional learning progress measure is given by LP = |f (pfast) − f (pslow)|, where we use the reweighting function f (p) = (1 − pθ)p p + pθ(1 − 2p) with parameter pθ = 0.1. The reweighting function magnifies differences in small probabilities, an effect that is illustrated in Figure 6: A probability difference between p = 0.1 and p = 0.2 (dotted red lines) leads to a much larger difference in reweighted probabilities than a probability difference between p = 0.6 and p = 0.7 (dotted blue lines). T T T T T T 0.0 0.2 0.4 0.6 0.8 1.0 p Figure 6: Reweighting of probabilities before calculating learning progress # A.3 Conversion of reweighted learning progress measure to sampling weight When converting reweighted learning progress to sampling weight (i.e. unnormalized sampling probability) we choose a sampling function that focuses on roughly 10% of tasks with the largest reweighted learning progress, but also prevents overfitting to just one or two tasks. The algorithm is as follows: • Z-score the reweighted learning progress (subtract mean and divide by standard deviation) 15 • Apply a sigmoid to the result. The sigmoid is centered on 90% quantile of the normal distribution (Figure 7). The saturation of the sigmoid for large learning progress prevents sampling from just focusing on one or two tasks. • Normalize resulting weights to sampling probabilities. If the reweighted LP measures were Gaussian-distributed, the above algorithm would focus on sampling the top 10% of tasks. In practice the LP measures often deviate from Gaussianity and we see the curriculum sometimes focus on a larger or smaller percentage of tasks. 1.0} Normal distr —— Sampling weight 0.8 5 0.6 5 0.4 0.2 4 0.0 5 r 1 T 3 2 #«-1 0 1 2 3 Z-scored distorted learning progress Figure 7: Sigmoid sampling function applied to z-scored reweighted learning progress # A.4 Experiment details # A.4.1 Environment The Minecraft environment the agents interacts with is based on MineRL [1]. At each time step, the agent observes a 64x64 RGB video frame of the player’s point-of-view and a set of features about the game-state: player inventory, health, food, saturation, experience point and the item in the main hand and off hand. In addition, the agent observes the id of the current goal item and the items in the exploration set. The main actions of the agent are "attack", "back", "forward", "jump", "left", "right", "sneak", "sprint" and "use" as well as control of the camera. We also provided the agent with special actions to craft, equip and place specific items without using the GUI interface (items that could not be crafted, equipped or placed in a given game state were masked out using an action mask). We used a “frame skip” of 4, i.e. every action by the policy, except “place”, “craft”, “equip” and camera actions, was repeated for 4 consecutive time steps in the MineRL environment before the policy could sample a new action. Given that the Minecraft environment runs at 20 frames per second, this allows the agent to choose a different action every 200 milliseconds, close to the typical human reaction time of 250 milliseconds. Finally, we added a "channel attack" action that had the effect of repeating the "attack" action for a fixed number of policy time steps (the precise number depended on which tool the agent was holding in its main hand at the time the “channel attack” action was taken, with 16 better tools taking fewer steps, because better tools require fewer consecutive attack actions to break a block), which made it easier for the agent to learn how to mine resources. # A.4.2 Policy and Optimization details The policy and value function networks shared the same architecture and weights. Visual observations were processed using an enlarged version of the IMPALA convnet [27]: the number of filters of the 3 modules were 64, 128 and 128, respectively, instead of 16, 32 and 32 as in the original IMPALA convnet. The convnet was followed by a fully connected layer of size 512. Feature observations were embedded linearly (inventory observations) or using one-hot encoding (all other feature observations) in a 512-dimensional embedding space. We then summed all visual and feature embeddings and processed it through an LSTM layer and another fully connected layer of size 512. The network output was given by a linear, factorial action head for the policy and a linear layer for the value function. Optimization was performed using Proximal Policy Optimization [28] and General Advantage Estimation [29]. # A.5 Optimization hyperparameters Buffer size Mini-batch size Learning rate PPO clipping parameter Entropy coefficient γ GAE parameter λ BPTT truncation length (student) max episode length 209,728 3,264 x 10 time steps 3 · 10−5 0.2 0.01 0.999 0.95 10 9000 EMA time scale of learning progress curriculum 1250 optimization steps ∼ 17180 policy frames 1 optimization step 17
Title: WARP: Word-level Adversarial ReProgramming: Summary: Transfer learning from pretrained language models recently became the dominant approach for solving many NLP tasks. A common approach to transfer learning for multiple tasks that maximize parameter sharing trains one or more task-specific layers on top of the language model. In this paper, we present an alternative approach based on adversarial reprogramming, which extends earlier work on automatic prompt generation. Adversarial reprogramming attempts to learn task-specific word embeddings that, when concatenated to the input text, instruct the language model to solve the specified task. Using up to 25K trainable parameters per task, this approach outperforms all existing methods with up to 25M trainable parameters on the public leaderboard of the GLUE benchmark. Our method, initialized with task-specific human-readable prompts, also works in a few-shot setting, outperforming GPT-3 on two SuperGLUE tasks with just 32 training samples. # WARP: Word-level Adversarial ReProgramming Karen Hambardzumyan1, Hrant Khachatrian1,2, Jonathan May3 1YerevaNN, 2Yerevan State University, 3Information Sciences Institute, University of Southern California mahnerak@yerevann.com, hrant@yerevann.com, jonmay@isi.edu # Abstract Transfer learning from pretrained language models recently became the dominant ap- proach for solving many NLP tasks. A com- mon approach to transfer learning for multiple tasks that maximize parameter sharing trains one or more task-specific layers on top of the language model. In this paper, we present an alternative approach based on adversarial re- programming, which extends earlier work on automatic prompt generation. Adversarial re- programming attempts to learn task-specific word embeddings that, when concatenated to the input text, instruct the language model to solve the specified task. Using up to 25K trainable parameters per task, this approach outperforms all existing methods with up to 25M trainable parameters on the public leader- board of the GLUE benchmark. Our method, initialized with task-specific human-readable prompts, also works in a few-shot setting, out- performing GPT-3 on two SuperGLUE tasks with just 32 training samples. A recent alternative is based on so called adapters (Houlsby et al., 2019; Pfeiffer et al., 2021), a technique that adds new weights at every layer of the pretrained language model while the original parameters are kept frozen. This enables a smaller set of task-specific parameters while achieving results comparable to the fine-tuning ap- proach. Another approach of leveraging pretrained lan- guage models for downstream tasks, introduced by Radford et al. (2019), provides “task descrip- tions” without using any labeled examples. GPT- 3 (Brown et al., 2020) demonstrates impressive few-shot learning performance with priming: by providing the language model a few inputs and outputs (“analogies”) as a context. The language model contextually “learns” from these examples and outputs the answer with a single forward pass without any trainable parameters. These methods, however, require huge language models (1.5B and 175B parameters, respectively). # Introduction Language model pretraining has had a tremendous impact on solving many natural language process- ing tasks (Peters et al., 2018; Radford et al., 2018; Devlin et al., 2019; Liu et al., 2019). The most popular two approaches take a pretrained model and use a straightforward supervised learning ob- jective. In the first approach, the parameters of the language model are frozen and a task-specific head is trained on top of them (Peters et al., 2018). The second approach fine-tunes all model param- eters (Radford et al., 2018). The latter can some- times yield better results (Peters et al., 2019), while the first one usually offers better stability for smaller datasets. The approach based on frozen features does not require storing task-specific lan- guage models. The success of task reformulation-based ap- proaches suggest that language models are capa- ble of solving various natural language processing tasks given a well-crafted prompt. We hypothesize that it is possible to find such prompts. In other words, we can discover extra tokens that, when added to the input, can exploit language model ca- pabilities better than the manually-designed ones. In this paper, we introduce a novel technique to find optimal prompts. We call our method WARP: Word-level Adversarial RePrograming1. The method is inspired by adversarial reprogramming (Elsayed et al., 2019) — a method of adding ad- versarial perturbations to an input image that re- programs a pretrained neural network to perform classification on a task other than the one it was originally trained for. 1Our implementation is publicly available at: https: //github.com/YerevaNN/WARP Figure 1: An example of an adversarial program that causes Inception V3 ImageNet model to function as an MNIST classifier, from Elsayed et al. (2019) We show that our method, using up to 25K trainable parameters per task, achieves 81.6 test score on the GLUE Leaderboard, outperforming all the other submissions that use up to three or- ders of magnitude more trainable parameters. We show that it is possible to inject knowledge into WARP models using manually designed initializa- tion of the prompt, which is especially useful on tasks with a small number of examples. More- over, WARP shows impressive few-shot perfor- mance on two tasks from the SuperGLUE bench- mark with just 32 examples, outperforming GPT-3 results. Finally, we discuss the advantages of our method in real-life applications. # 2 Related Work # 2.1 Towards Fewer Trainable Parameters Jiao et al. (2020) show that knowledge distillation may help reduce the size of their model 7.5 times while almost preserving the performance, but fine- tuning such models still requires storage of sepa- rate task-specific models. As seen in Section 6, this approach does not scale when we want to ap- ply it to many tasks at once. Another approach, called Adapters (Houlsby et al., 2019; Pfeiffer et al., 2021), introduces new task-specific parameters that are added at every layer of the Transformer network. Only these newly initialized weights are trained, which allows separation of general and task-specific knowl- edge. In contrast, our method does not inject task- specific knowledge inside the body of the pre- trained language model. Instead, it focuses on learning task-specific input-level prompts. ee negative positive Q Qi eA_lovely film... Fea (> 13% 87% s 2] Q @A_pretentious_mess_... 21% e) Q Two_hours_of_junk. > 90% 10% Exceeds_expectations. ese) Gese) Figure 2: WARP adds a few trainable embeddings around the input, which causes the masked language model to predict the sentiment of the sentence. # 2.2 Task Reformulation In GPT-2, Radford et al. (2019) introduce a com- pletely unsupervised way for transferring knowl- edge to downstream tasks by reformulating vari- ous natural language understanding tasks into lan- guage modeling problems. This approach does not make use of the available training examples. Brown et al. (2020) demonstrate an effective few- shot transfer by reformulating downstream tasks into input-output analogies in the context without a need for further fine-tuning. Nonetheless, the number of training examples is limited to the con- text size and is not scalable to a traditional super- vised learning scenario. Schick and Sch¨utze (2021b) show the effec- tiveness of reformulating a number of tasks into Cloze-style tasks by fine-tuning masked language models (Devlin et al., 2019). The method, called Pattern Exploited Training (PET), addition- ally uses training samples and performs few-shot learning even without huge models such as GPT-3. Our method is also based on masked lan- guage models, but unlike PET, we focus on find- ing the best prompt using the training examples. This eliminates the need for manually-designed prompts, however, our method can also benefit from similar prior knowledge about the task by careful initialization of the prompts. # 2.3 Adversarial Reprogramming Adversarial Reprogramming (Elsayed et al., 2019) demonstrates the reprogramming of pretrained Im- ageNet classifiers by adding input-level adversar- ial perturbations to make them perform well on MNIST and CIFAR-10 image classification tasks. The adversarial perturbation is designed to be im- age padding added to the original input, as illus- Loss oy ‘ LOLOOO|+ isin [OOO IO OO OF} contedition 4 {O|OO Oj} ick MLM Head wio decoder Transformer / Encoder | fer J jor for [Ter | I Jer | O} JO} JO} JO} JO} JO} JO} JO} JO] JO} JO] JO} |O] JO} JO O} JO} JO} JO} JO} JO} JO} JO} JO] JO} JO] JO} |O] JO} JO O} [Q} [CQ] [Q} [CQ] LQ} [Q} [EQ] [QJ LQ} [EQ] LQ} LQ} LQ} tO j f j f j f j ft j t ( t j fF [CLS] [P_1] _Oil _prices | _rise [P_2] [P_3] | [MASK] | [P_4] Oil _prices fall _back [P_5] [SEP] Figure 3: Illustration of WARP. The prompt tokens [P 1], [P 2], ..., [P N] are inserted before, between, and after the sentences. Only the prompt and class embeddings are trainable (colored in green). The masked language modeling Head is applied without the decoder; instead, the matrix of [V 1], [V 2], ..., [V N] is applied as a linear layer. Finally, a regular task-specific loss is computed on the resulting logits. trated in Figure 1. Then the perturbation param- eter is trained to optimize the target classification task objective using the annotated image data. While in the case of image classification it is not obvious why adversarial reprogramming should ever work, e.g. why a network trained on Ima- geNet should have the capacity to solve MNIST when surrounded with a particular bitmap, for NLP tasks, there is more intuition. Many NLP tasks can be reformulated as language models, a shared space for both program and data. Adversarial reprogramming has been adapted to text classification tasks with LSTM networks in (Neekhara et al., 2019). They operate in the vo- cabulary space and reprogram a model trained for one task to perform another task. More recently, AutoPrompt (Shin et al., 2020a) attempts to find prompts for large language models automatically without adding any parameters to the model. Un- like AutoPrompt, we perform gradient-based opti- mization in the space of word embeddings which gives our model more degrees of freedom and eventually better performance on the downstream tasks (Section 6.2). In a more general sense, guiding an NLP model with special tokens appended to the input is an even older idea. In particular, multilingual neu- ral machine translation models use special tokens in the input to control the target language (Ha et al., 2016; Johnson et al., 2017) or politeness of the translation (Sennrich et al., 2016). Another method to reprogram a BERT-based model is pro- posed by Artetxe et al. (2020), where a model tuned on an English version of a particular task is transformed to work in another language by changing only the embedding matrices. In parallel work, Li and Liang (2021) propose a similar method and successfully apply it on two text generation tasks. Apart from the dif- ferent types of tasks and our characterization of the task as a form of Adversarial Reprogramming, the main difference between their approach and ours is that they use an additional parameteriza- tion trick to stabilize the training. # 3 WARP We follow a setup similar to Elsayed et al. (2019) with some NLP-specific modifications depicted in Figure 2. Our goal is to find the best prompt that will make a pretrained masked language model pre- dict the desired answer (verbalizer token) for a training example’s masked token2. We search for such prompts in the (continuous) embedding space. In other words, we want to find parameters Θ = {ΘP , ΘV } for prompt and verbalizer embed- 2This approach can be easily extended to autoregressive language modeling. dings, respectively, such that: Θ∗ = arg max Θ (− log PΘ(y|x)) and the probabilities are given by: exp OY f (Tor (x) d exp OF f (Tor (x)) iEC Po(ylz) where TΘP (x) is the template that inserts the prompt embeddings ΘP into predefined positions, C is the set of classes, and f (x) is the masked language model output (without the last decoder layer, which is simply the transposed word embed- ding matrix). Both ΘP and ΘV are vectors in the same embeddings space as the word embeddings. In Figure 2, the template TΘP (x) prepends ΘP 1 and appends ΘP 3 , ΘP 4 parameters to the word embeddings and uses ΘV + and ΘV − to calculate the probabilities on the masked token position for pos- itive and negative classes. # 3.1 Method Similar to Elsayed et al. (2019), we employ stochastic gradient descent to find the best adver- sarial perturbation on the text that will minimize the task objective. First, we insert special prompt tokens [P 1], [P 2], ... [P K] and an additional [MASK] token into the input sequence. These to- kens might be placed before or after the sentences, depending on the prompt template. We set the optimization objective to a cross- entropy loss between the head output of the masked language model and the verbalizer tokens [V 1], [V 2], ..., [V C] for classes 1...C ac- cordingly. The only trainable parameters are the word em- beddings for [P 1], ..., [P K] and [V 1], ... [V C]. In case we want to train models for mul- tiple tasks, these are the only task-specific param- eters we need to store. The entire “body” of the large language model (all attention layers, feed- forward layers, and all other word embeddings) remains untouched. Note that, unlike most adversarial attacks, we do not update the embeddings of the original to- kens of the input. This follows the intuition from Elsayed et al. (2019), when the pixels of MNIST or CIFAR images are left untouched, and only padding pixels are updated. We train these parameters by minimizing the loss on the training set of the downstream task. # Implementation Details WARP is implemented in the AllenNLP frame- work. For all the GLUE benchmark tasks we use the roberta-large (Liu et al., 2019) model from the PyTorch implementation of huggingface transformers (Wolf et al., 2020) library. For the few-shot experiments, we use albert-xxlarge-v2 in order to directly compare to iPET (Schick and Sch¨utze, 2021b). For the GLUE and SuperGLUE tasks we use dataset loaders and metrics implementations from the huggingface datasets library. The prompt tokens are initialized either with word embeddings of [MASK] or similar to the vectors from the word embedding layer. For the answer prompts, we use the masked language model head, which usually consists of a feed- forward network and a decoder on top of it, where the weights of the decoder are shared with the word embeddings used for the input. We calcu- late the softmax over the verbalizer tokens [V 1], ... [V C]. We choose the Adam optimizer with a slanted triangular schedule for the learning rate with 6% warm-up steps and train for 10-20 epochs on each task. Each batch consists of examples containing at most 1024 tokens and 8 examples. In order to speed up the training, we disable the dropout of the pretrained language model. All the experiments are performed on two Titan Vs and two RTX 3080 GPUs, with mixed precision train- ing. In practice, WARP is 2.5-3 times faster than regular fine-tuning and 2 times slower than frozen- features experiments in terms of epoch duration with the same batch sizes. Details about the hyperparameters can be found in the Supplementary material. # 4 Experiments on GLUE Following prior work, we evaluate our method on the GLUE Benchmark (Wang et al., 2019b), which consists of 9 natural language understanding tasks. Generally, we perform single-task WARP training, with early stopping and model selection using the original validation sets, if not stated otherwise. # 4.1 Tasks Almost all the tasks from the GLUE Benchmark are either sentence classification or sentence pair classification tasks, so WARP requires very few modifications to adapt to each of the tasks. QNLI 91.2 99.2 95.4 92.7 90.5 90.4 87.7 88.3 92.4 93.5 QQP 59.5 / 80.4 76.2 / 90.8 74.3 / 90.2 72.1 / 89.3 71.2 / 89.2 71.6 / 89.1 71.3 / 89.2 70.4 / 88.0 71.5 / 89.4 68.6 / 87.7 RTE SST MRPC 93.6 93.2 88.2 70.1 66.4 70.0 66.6 63.6 71.6 84.3 97.8 86.3 / 80.8 97.5 94.0 / 92.0 96.7 92.3 / 89.8 94.9 89.3 / 85.4 93.5 88.9 / 84.8 93.1 87.3 / 82.6 92.6 86.4 / 81.2 91.1 89.0 / 84.9 94.3 88.7 / 84.3 96.3 88.2 / 83.9 CoLA 66.4 71.5 67.8 60.5 52.1 51.1 44.1 55.6 59.2 53.9 STS-B 92.7 / 92.6 92.9 / 92.6 92.2 / 91.9 87.6 / 86.5 87.1 / 85.8 85.0 / 83.7 81.9 / 80.4 85.6 / 84.6 87.3 / 86.1 89.5 / 88.8 AVG 87.1 90.8 88.1 80.5 78.3 78.1 75.9 77.4 80.2 81.6 # 3 · 109 355 · 106 355 · 106 110 · 106 67 · 106 15 · 106 14 · 106 1.2 · 106 < 25K Table 1: Test set results on GLUE Benchmark. The results are obtained from the GLUE Evaluation server. The subscript next to TinyBERT corresponds to the number of layers in the model. WARP for RTE, STS-B and MRPC are intialized from the MNLI parameters. Results for WNLI are not shown, although they are counted in the averaged GLUE score (AVG column). The last column # shows the number of trainable parameters. WARP’s average performance is higher than all models with up to three orders of magnitude more trainable parameters. Fully fine-tuned RoBERTa and the current state-of-the-art method (DeBERT) score higher by 6.5 and 9.2 points, respectively. SST-2 (Sentence Sentiment Treebank, Socher et al., 2013) is a single sentence binary classifica- tion task. For the prompt, we put a [MASK] token after the sentence, and the trainable prompt tokens are both appended and prepended to the sentence. CoLA (Corpus of Linguistic Acceptability, Warstadt et al., 2019) is a single sentence classifi- cation task as well, so we treat both the same way with the only difference that as a validation metric we use accuracy for SST-2, and Matthew’s corre- lation for CoLA. mark, Cer et al., 2017), unlike the other tasks in the benchmark, is formulated as a regression task. The prompt pattern is the same, but instead of in- troducing new embeddings for [V 1], [V 2], ..., [V C] verbalizer tokens, we add a regres- sion head to the last hidden state of MLM head and use Mean Squares Error optimization objec- tive, similar to (Liu et al., 2019). Pearson Cor- relation is used as the validation metric. During inference, we clip the scores within [1, 5]. MNLI (MultiNLI, Multi-Genre Natural Lan- guage Inference, Williams et al., 2018), QNLI (Question Natural Language Inference, Rajpurkar et al., 2016) and RTE (Recognizing Textual En- tailment, Dagan et al., 2006; Bar Haim et al., 2006; Giampiccolo et al., 2007; Bentivogli et al., 2009) are sentence pair classification tasks. Sim- ilar to Schick and Sch¨utze (2021a), we may have prompt tokens before, after and between the two sentences, but the [MASK] token is always put be- tween the sentences. For MNLI, we use matched accuracy as a validation metric and use the same model for the mismatched version. In our few-shot attempt for the RTE task, we use a different train- ing and evaluation setup discussed in Section 5.2. QQP (Quora Question Pairs4) and MRPC (Mi- crosoft Research Paraphrase Corpus, Dolan and Brockett, 2005) follow the same prompt pattern as NLI tasks. As a validation metric F1 score is used. STS-B (Semantic Textual Similarity Bench- 4https://www.quora.com/q/quoradata/First-Quora- Dataset-Release-Question-Pairs and train models for MRPC, STS-B, and RTE tasks initialized with the parameters from the best MNLI model but do not apply any task-specific tricks to WNLI (Winograd Schema Challenge NLI, Levesque et al., 2011) and always predict the majority label. # 4.2 Results Table 1 presents the results on the test set obtained from the GLUE evaluation server. Besides our best WARP models, we also include the human baselines, current state-of-the-art model (He et al., 2020), the regular fine-tuned pretrained model we use, and also include relatively small language models, including (Jiao et al., 2020), (Clark et al., 2020), (Houlsby et al., 2019). With the GLUE Score, WARP outperforms all the models that train less than 25 million parame- ters on the leaderboard. We explain the relatively strong WARP results on textual entailment tasks by the easier reformulation of such tasks. Like- wise, we explain the relatively weak performance on CoLA by the difficulties of reformulating the train size Fine-Tuning Adapters Linear Classifier WARP0 WARP1 WARP2 WARP4 WARP8 WARPinit WARP20 WARPMNLI MNLI 392702 90.2 90.4 64.2 70.9 83.9 85.4 86.9 87.6 86.8 88.2 QNLI 104743 94.7 94.7 78.1 78.8 87.6 88.0 92.4 93.0 90.4 93.5 QQP 363846 92.2 88.5 74.9 77.1 81.6 81.5 83.1 83.8 83.6 84.5 RTE 2490 86.6 83.4 59.2 72.2 72.6 69.7 68.2 72.9 80.1 75.8 86.3 SST 67349 96.4 96.3 88.4 89.8 93.8 94.3 95.9 95.4 96.0 96.0 MRPC 3668 90.9 92.9 82.5 83.8 84.7 85.3 85.0 85.6 86.0 90.8 91.2 CoLA 8551 68.0 67.4 48.9 32.8 46.1 54.4 56.0 57.4 51.7 60.6 STS-B 5749 92.4 92.5 71.8 73.8 80.4 80.8 75.5 81.0 86.9 88.6 91.0 AVG 88.9 88.3 71.0 72.4 78.8 79.9 80.4 82.1 82.7 84.8 86.4 # 355 · 106 3 · 106 ≤ 3072 ≤ 3072 ≤ 4096 ≤ 5120 ≤ 7168 < 11K < 11K < 25K < 25K Table 2: Dev set results on GLUE tasks. The last column shows the number of trainable parameters only. WARPi corresponds to WARP training with prompt consisting of i prompt tokens. WARPMNLI corresponds to WARP training initialized with the best MNLI parameters. All the models are based on pretrained roberta-large, and for Adapters and WARP-based approaches require to store 355 · 106 frozen parameters shared across all the GLUE tasks. We show the primary validation metric for each task, described at Subsection 4.1. The AVG column shows the average of shown metrics and is not comparable to the Test server GLUE Score. The number of parameters for WARP methods may vary because of a difference in the number of classes. Underlined numbers correspond to our GLUE submission. # task into a Cloze task. To further analyze WARP, we conduct several experiments and focus on dev set results. In order to directly compare WARP with existing methods, we report in Table 2 different methods that use RoBERTa, including fine-tuning, linear classifiers on top, AutoPrompt, and Adapters.5 For WARP experiments, we compare performance with dif- ferent numbers of prompt tokens. The WARP0 model does not introduce any prompt parameters. The only difference between WARP0 and Linear Classifier is that for WARP0, [MASK] is added to the input of each sample, and we get sentence representations from the MLM head at the masked position. By contrast, in the case of the Linear Classifier, we use the average of non-special token embeddings as sentence repre- sentations. As we can see, pooling with MLM is significantly better. it can be initialized with manual prompts. In addition to the regular models where we initial- ize with [MASK] tokens, we performed a run on the GLUE datasets with the same prompt [CLS] “S1”? [MASK]. “S2”! [SEP] for all the tasks (without S2 for single-sentence tasks). We denote these results as WARPinit in Table 2. WARPinit outperforms WARP8 on tasks with relatively few training examples — RTE, MRPC and STS- B, which indicates its potential in the low-data regime. # 5 Few-Shot Experiments The fact that WARP can be initialized using man- ually designed natural prompts suggests that we can similarly benefit from such human attribution similar to iPET (Schick and Sch¨utze, 2021b), es- pecially in scenarios with limited training data. Table 2 shows that, as we decrease the num- ber of trainable prompt parameters, the perfor- mance decreases, but the model still works. Simi- lar behavior was observed by Elsayed et al. (2019) in experiments with different padding parameter sizes. However, in contrast to WARP, the num- ber of trainable parameters in that work are much greater than the size of the input. An important benefit of using WARP is that 5Unlike in Table 2, Adapters in Table 1 are built on bert-large-uncased model. # 5.1 Setup For our few-shot experiments we build WARP on top of ALBERT (Lan et al., 2020), the same pretrained model used by PET and iPET. To initialize WARP prompts, we use the same Prompt-Verbalizer Patterns (PVP) from Schick and Sch¨utze (2021b): the embeddings for [P 1], [P N] are initialized with PVP’s [P 2]... and embeddings prompt for [V 1], [V 2]... [V C] are initialized with verbalizer token embeddings for their corre- sponding classes. Unlike roberta-large, the alberta-xxlarge-v2 uses word embeddings of size 128 (8 times smaller than RoBERTa). # 5.2 Tasks In order to compare with GPT-3, PET, and iPET, we use two tasks from FewGLUE (Schick and Sch¨utze, 2021b), which is a few-shot subset of the SuperGLUE benchmark (Wang et al., 2019a) con- sisting of 32 examples for each task. The dataset also provides 20000 additional unlabeled exam- ples, however, we do not make use of them and work in a purely supervised setup. CB: CommitmentBank (de Marneffe et al., 2019) is a textual entailment task which we treat like the other sentence pair classification tasks. To initialize the prompt we use the template [CLS] “h”? [MASK]. “p” [SEP] . We also initialize [V 1], [V 2], [V 3] token embed- dings with yes, no and maybe (respec- tively for entailment, contradiction and neutral). RTE: Unlike experiments on the RTE task for the full-sized training in the GLUE benchmark, we do not initialize the model with vectors from MNLI. Instead, the prompt is initialized exactly the same way as in the CB task. The only differ- ence is that we have only the two tokens [V 1] and [V 2] initialized with yes and instead (for entailment and not entailment, re- spectively). # 5.3 Model Selection Although all trainable parameters are manually initialized in this setup, different random seeds can yield different results because of the order the training examples appear during an epoch. In the few-shot setup we cannot access the orig- inal validation set. Thus, we disable early stopping and simply pick the last checkpoint. In order to find the best initial learning rate, we conduct 20 runs of WARP with the same learn- ing rate each time by randomly choosing 16 train- ing examples and taking the rest for a development set. We repeat this for all candidate learning rates and choose the one with the best average valida- tion performance across all the random seeds. Finally, in order to eliminate the effect of dif- ferent random seeds, we build an ensemble model from 20 WARP runs using simple majority vote. v e d t s e t Model GPT-3 Small GPT-3 Med GPT-3 PET (ALBERT) iPET (ALBERT) WARPinit (ALBERT) GPT-3 PET (ALBERT) iPET (ALBERT) WARPinit (ALBERT) CB F1 / Acc. 26.1 / 42.9 40.4 / 58.9 57.2 / 82.1 59.4 / 85.1 92.4 / 92.9 84.0 / 87.5 52.0 / 75.6 60.2 / 87.2 79.9 / 88.8 70.2 / 82.4 RTE Acc. 52.3 48.4 72.9 69.8 74.0 71.8 69.0 67.2 70.8 69.1 Table 3: Results on SuperGLUE benchmark. The re- sults for the test set are obtained from SuperGLUE evaluation server. We only show systems performing in a similar few-shot training setup using 32 examples. # 5.4 Results As seen in Table 3, WARP outperforms PET and GPT-3 baselines, but stays behind iPET on both tasks. GPT-3 has 170B parameters, but none of them is being trained for the given tasks. PET and iPET have 255M parameters, and all of them are trained for these tasks. Additionally, they lever- age unlabeled examples using distillation. WARP has roughly the same 255M parameters, but only 1024 of them are trained for any single model. An ensemble of 20 WARP models has slightly more than 20K trainable parameters. # 6 Discussion # Interpreting tokens learned by WARP WARP learns prompt embeddings in a continuous space. In this section, we explore those embed- dings by looking at the nearby token vectors. Ta- ble 6 in the Supplementary material lists the clos- est tokens (in terms of cosine similarity) to the learned embeddings. All GLUE tasks are initial- ized with [MASK] token, except for RTE, MRPC, and STS-B, which are initialized from the pre- trained MNLI model. The prompt tokens of the solutions for those three tasks are quite close to the ones from the MNLI solution. We have seen similar behavior on SuperGLUE experiments with manual initializations. The solution for CoLA (which is one of the worst-performing tasks) is close to the initialized point. We do not see any prompt tokens that are mean- ingful in the context of the tasks. As expected, the verbalized tokens are more interpretable. For . 3 8 < — WARPio —— WARP init — AutoPrompt ---- Manual 0.3 4 — Fine-Tuning ; : , 10! 102 10° Number of Training Instances Figure 4: The effect of the training data size for SST-2 task (dev set). Horizontal axis is the number of training examples. Solid lines represent median over 10 runs, and the error bars show minimum and maximum per- formance. All methods use roberta-large model. The results for AutoPrompt and fine-tuning are taken from (Shin et al., 2020b) . example, the embedding for the “contradiction” class of MNLI is close to the token “Unless”. The embeddings for “negative” and “positive” classes of SST-2 task are close to “defective” and “im- portant”, respectively. Other verbalized tokens are non-interpretable (e.g. “470” or word pieces with non-Latin characters). # 6.2 Comparison with AutoPrompt AutoPrompt (Shin et al., 2020b) learns a prompt for the given task in the finite space of vocabu- lary tokens. Their best version uses 3 or 6 prompt tokens and reaches 91.2% accuracy on the devel- opment set of SST-2. The search space of WARP is significantly larger, which allows WARP to get better performance with just a single prompt token (93.8%). AutoPrompt does not achieve meaningful re- sults on RTE or CB tasks. WARP succeeds on both without manual initialization. Moreover, with manual initialization, WARP gets good per- formance on both tasks even with just 32 examples (Table 3). Figure 4 shows the dependence of the accu- racy on SST-2 development set from the number of training samples. Both WARP and AutoPrompt use 10 prompt tokens. With a few hundred train- ing samples or fewer, the difference between the two algorithms is not significant. WARP starts to perform better with more training samples. Approach # of parameters to store Linear probing M+ ECN Full fine-tuning MN Single layer M+NE(E+C) TinyBERT MoN Adapters M+NEE' WARP M+NE(C+K) Table 4: The number of parameters to be stored to serve N text classification tasks with at most C classes each, using a pretrained language model with / parameters. E is the dimension of embeddings (1024 in the case of RoBERTa). In TinyBERT, Mo can be up to 10 times less than M. In Adapters, E’ is roughly equal to E, as the number of layers to which adapters are attached roughly compensates the smaller size of the bottleneck layer. In WARP, K is the number of prompts (usually fewer than 10). Shin et al. (2020b) include results with a manu- ally designed prompt6 which performs pretty well (shown as a dashed line). We also compare with the manually initialized7 version of WARP, which performs very well with just 100 examples. # 6.3 Real-world applications The importance of NLP systems like WARP can be demonstrated by the following application. Suppose we want to build a system that needs to serve N >> 1 classification tasks simultaneously. Let the number of classes for each task be bounded by C. The system can be based on a large pre- trained language model with M parameters, using word embedding size E. How many parameters should the system store in the device memory to be able to serve all N tasks? If we take the approach with frozen features, we can reuse M parameters for all tasks and store ad- ditional ECN task-specific parameters. This is optimal in terms of storage but will not perform well. The other extreme is to fine-tune the whole model for each task and store at least M N pa- rameters. Table 4 shows the trade-offs offered by the other solutions. Methods like TinyBERT de- crease the number of parameters from M N by only M . WARP, on the other hand, needs to store only M + N E(C + K) parameters, where K is the number of trainable prompt tokens. 6 SENT. this movie was and “fantastic” as verbalizer tokens . as a prompt, and “terrible” 7 SENT, and finally, the movie overall was very as a prompt, and “good” and “bad” as verbalizer tokens ! In practice, WARP additionally allows perform- ing inference on inputs for different tasks in paral- lel, using samples of multiple tasks in the same batch. Every input sentence can be concatenated with task-specific pretrained prompts in advance. Then, the forward pass of the network is identical for all tasks. The final task-specific linear layers can be concatenated to form a single large linear layer with at most N C output neurons. This approach can be especially useful in the systems that provide machine learning models as a service. By storing one copy of a pretrained lan- guage model, it is possible to serve a large number of user-specific models in parallel with little over- head. # 7 Conclusion In this paper we have proposed an alternative way to transfer knowledge from large pretrained lan- guage models to downstream tasks by appending carefully optimized embeddings to the input text. The method outperforms existing methods with significantly more trainable parameters on GLUE benchmark tasks and shows an impressive perfor- mance in a few-shot setting on two SuperGLUE tasks. On the sentiment analysis task, the perfor- mance is comparable to the fully fine-tuned lan- guage models. This method can save a lot of storage in software applications designed to serve large numbers of sentence classification tasks. # Acknowledgments This work is based in part on research sponsored by Air Force Research Laboratory (AFRL) under agreement number FA8750-19-1-1000. The U.S. Government is authorized to reproduce and dis- tribute reprints for Government purposes notwith- standing any copyright notation therein. The views and conclusions contained herein are those of the authors and should not be interpreted as necessarily representing the official policies or en- dorsements, either expressed or implied, of Air Force Laboratory, DARPA or the U.S. Govern- ment. The work was supported by the RA Science Committee, in the frames of the research project No. 20TTAT-AIa024. Most experiments were per- formed on GPUs donated by NVIDIA. # References Mikel Artetxe, Sebastian Ruder, and Dani Yogatama. 2020. On the cross-lingual transferability of mono- lingual representations. In Proceedings of the 58th Annual Meeting of the Association for Computa- tional Linguistics, pages 4623–4637, Online. Asso- ciation for Computational Linguistics. Roy Bar Haim, Ido Dagan, Bill Dolan, Lisa Ferro, Danilo Giampiccolo, Bernardo Magnini, and Idan Szpektor. 2006. The second PASCAL recognising textual entailment challenge. Luisa Bentivogli, Ido Dagan, Hoa Trang Dang, Danilo Giampiccolo, and Bernardo Magnini. 2009. The fifth PASCAL recognizing textual entailment chal- lenge. T. Brown, B. Mann, Nick Ryder, Melanie Subbiah, J. Kaplan, Prafulla Dhariwal, Arvind Neelakan- tan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, G. Kr¨uger, T. Henighan, R. Child, Aditya Ramesh, D. Ziegler, Jeffrey Wu, Clemens Winter, Christopher Hesse, Mark Chen, E. Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, J. Clark, Christopher Berner, Sam McCandlish, A. Radford, Ilya Sutskever, and Dario Language models are few-shot Amodei. 2020. learners. ArXiv, abs/2005.14165. Daniel Cer, Mona Diab, Eneko Agirre, I˜nigo Lopez- Gazpio, and Lucia Specia. 2017. SemEval-2017 task 1: Semantic textual similarity multilingual and In Proceedings crosslingual focused evaluation. of the 11th International Workshop on Semantic Evaluation (SemEval-2017), pages 1–14, Vancou- ver, Canada. Association for Computational Lin- guistics. Kevin Clark, Minh-Thang Luong, Quoc Le, and Christopher D. Manning. 2020. Pre-training trans- formers as energy-based cloze models. In Proceed- ings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 285–294, Online. Association for Computational Linguistics. Ido Dagan, Oren Glickman, and Bernardo Magnini. 2006. The PASCAL recognising textual entailment challenge. In Machine learning challenges. evalu- ating predictive uncertainty, visual object classifica- tion, and recognising tectual entailment, pages 177– 190. Springer. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. BERT: Pre-training of deep bidirectional transformers for language under- In Proceedings of the 2019 Conference standing. of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 4171–4186, Minneapolis, Minnesota. Associ- ation for Computational Linguistics. William B Dolan and Chris Brockett. 2005. Auto- matically constructing a corpus of sentential para- phrases. In Proceedings of the International Work- shop on Paraphrasing. Gamaleldin F. Elsayed, Ian Goodfellow, and Jascha Sohl-Dickstein. 2019. Adversarial reprogramming of neural networks. In International Conference on Learning Representations. Danilo Giampiccolo, Bernardo Magnini, Ido Dagan, and Bill Dolan. 2007. The third PASCAL recog- nizing textual entailment challenge. In Proceedings of the ACL-PASCAL workshop on textual entailment and paraphrasing, pages 1–9. Association for Com- putational Linguistics. Thanh-Le Ha, Jan Niehues, and Alexander Waibel. 2016. Toward multilingual neural machine transla- tion with universal encoder and decoder. Pengcheng He, Xiaodong Liu, Jianfeng Gao, and Weizhu Chen. 2020. DeBERTa: Decoding- enhanced bert with disentangled attention. arXiv preprint arXiv:2006.03654. N. Houlsby, Andrei Giurgiu, Stanislaw Jastrzebski, Bruna Morrone, Quentin de Laroussilhe, Andrea Gesmundo, Mona Attariyan, and S. Gelly. 2019. In Parameter-efficient transfer learning for nlp. ICML. Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li, Fang Wang, and Qun Liu. 2020. TinyBERT: Distilling BERT for natural lan- guage understanding. In Findings of the Association for Computational Linguistics: EMNLP 2020, pages 4163–4174, Online. Association for Computational Linguistics. Melvin Johnson, Mike Schuster, Quoc V. Le, Maxim Krikun, Yonghui Wu, Zhifeng Chen, Nikhil Thorat, Fernanda Vi´egas, Martin Wattenberg, Greg Corrado, Macduff Hughes, and Jeffrey Dean. 2017. Google’s multilingual neural machine translation system: En- abling zero-shot translation. Transactions of the As- sociation for Computational Linguistics, 5:339–351. Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu Soricut. 2020. ALBERT: A lite BERT for self-supervised In Interna- learning of language representations. tional Conference on Learning Representations. Hector J Levesque, Ernest Davis, and Leora Morgen- stern. 2011. The Winograd schema challenge. In AAAI Spring Symposium: Logical Formalizations of Commonsense Reasoning, volume 46, page 47. Prefix- Tuning: Optimizing continuous prompts for genera- tion. arXiv preprint arXiv:2101.00190. Y. Liu, Myle Ott, Naman Goyal, Jingfei Du, Man- dar Joshi, Danqi Chen, Omer Levy, M. Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. RoBERTa: A robustly optimized BERT pretraining approach. ArXiv, abs/1907.11692. Marie-Catherine de Marneffe, Mandy Simons, and Ju- dith Tonhauser. 2019. The CommitmentBank: In- vestigating projection in naturally occurring dis- Proceedings of Sinn und Bedeutung, course. 23(2):107–124. Paarth Neekhara, Shehzeen Hussain, Shlomo Dubnov, and Farinaz Koushanfar. 2019. Adversarial repro- gramming of text classification neural networks. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Lan- guage Processing (EMNLP-IJCNLP), pages 5216– 5225, Hong Kong, China. Association for Computa- tional Linguistics. Matthew Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, and Luke Zettlemoyer. 2018. Deep contextualized word rep- In Proceedings of the 2018 Confer- resentations. ence of the North American Chapter of the Associ- ation for Computational Linguistics: Human Lan- guage Technologies, Volume 1 (Long Papers), pages 2227–2237, New Orleans, Louisiana. Association for Computational Linguistics. Matthew E. Peters, Sebastian Ruder, and Noah A. Smith. 2019. To tune or not to tune? adapting pre- trained representations to diverse tasks. In Proceed- ings of the 4th Workshop on Representation Learn- ing for NLP (RepL4NLP-2019), pages 7–14, Flo- rence, Italy. Association for Computational Linguis- tics. Jonas Pfeiffer, Aishwarya Kamath, Andreas R¨uckl´e, Kyunghyun Cho, and Iryna Gurevych. 2021. AdapterFusion: Non-destructive task composition In Proceedings of the 16th for transfer learning. Conference of the European Chapter of the Associ- ation for Computational Linguistics: Main Volume, pages 487–503, Online. Association for Computa- tional Linguistics. Alec Radford, Karthik Narasimhan, Tim Salimans, and Improving language under- Ilya Sutskever. 2018. standing by generative pre-training. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, and Percy Liang. 2016. SQuAD: 100,000+ questions for machine comprehension of text. In Proceedings of the 2016 Conference on Empirical Methods in Natu- ral Language Processing, pages 2383–2392, Austin, Texas. Association for Computational Linguistics. Timo Schick and Hinrich Sch¨utze. 2021a. Exploiting cloze-questions for few-shot text classification and In Proceedings of the natural language inference. 16th Conference of the European Chapter of the As- sociation for Computational Linguistics: Main Vol- ume, pages 255–269, Online. Association for Com- putational Linguistics. Timo Schick and Hinrich Sch¨utze. 2021b. It’s not just size that matters: Small language models are also few-shot learners. In Proceedings of the 2021 Con- ference of the North American Chapter of the Asso- ciation for Computational Linguistics: Human Lan- guage Technologies, pages 2339–2352, Online. As- sociation for Computational Linguistics. Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016. Controlling politeness in neural machine In Proceedings of translation via side constraints. the 2016 Conference of the North American Chap- ter of the Association for Computational Linguistics: Human Language Technologies, pages 35–40, San Diego, California. Association for Computational Linguistics. Taylor Shin, Yasaman Razeghi, Robert L. Logan IV, Eric Wallace, and Sameer Singh. 2020a. Auto- Prompt: Eliciting Knowledge from Language Mod- els with Automatically Generated Prompts. In Pro- ceedings of the 2020 Conference on Empirical Meth- ods in Natural Language Processing (EMNLP), pages 4222–4235, Online. Association for Compu- tational Linguistics. Taylor Shin, Yasaman Razeghi, Robert L. Logan IV, Eric Wallace, and Sameer Singh. 2020b. Auto- Prompt: Eliciting Knowledge from Language Mod- els with Automatically Generated Prompts. In Pro- ceedings of the 2020 Conference on Empirical Meth- ods in Natural Language Processing (EMNLP), pages 4222–4235, Online. Association for Compu- tational Linguistics. Richard Socher, Alex Perelygin, Jean Wu, Jason Chuang, Christopher D Manning, Andrew Ng, and Christopher Potts. 2013. Recursive deep models for semantic compositionality over a sentiment tree- bank. In Proceedings of EMNLP, pages 1631–1642. Alex Wang, Yada Pruksachatkun, Nikita Nangia, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R. Bowman. 2019a. SuperGLUE: A stickier benchmark for general-purpose language understanding systems. In NeurIPS. Alex Wang, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R. Bowman. 2019b. GLUE: A multi-task benchmark and analysis plat- form for natural language understanding. In Inter- national Conference on Learning Representations. Alex Warstadt, Amanpreet Singh, and Samuel R. Bow- man. 2019. Neural network acceptability judg- ments. Transactions of the Association for Compu- tational Linguistics, 7:625–641. Adina Williams, Nikita Nangia, and Samuel Bowman. 2018. A broad-coverage challenge corpus for sen- tence understanding through inference. In Proceed- ings of the 2018 Conference of the North American Chapter of the Association for Computational Lin- guistics: Human Language Technologies, Volume 1 (Long Papers), pages 1112–1122, New Orleans, Louisiana. Association for Computational Linguis- tics. Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Clement Delangue, Anthony Moi, Pier- ric Cistac, Tim Rault, Remi Louf, Morgan Funtow- icz, Joe Davison, Sam Shleifer, Patrick von Platen, Clara Ma, Yacine Jernite, Julien Plu, Canwen Xu, Teven Le Scao, Sylvain Gugger, Mariama Drame, Quentin Lhoest, and Alexander Rush. 2020. Trans- formers: State-of-the-art natural language process- ing. In Proceedings of the 2020 Conference on Em- pirical Methods in Natural Language Processing: System Demonstrations, pages 38–45, Online. As- sociation for Computational Linguistics. # A Hyperparameters For each of the tasks, we performed hyperparam- eter search in the following space: • Learning rate is chosen from the set {10−2, 3 · 10−3, 10−3, 3 · 10−4, 10−4, 3 · 10−5}, • Number of epochs is chosen as either 10 or 20. This determines the behavior of the slanted triangular learning rate scheduler. • Initialization is performed either with the embedding of the [MASK] token, or ran- domly initialized from a normal distribution, with the mean and variance taken from the matrix of RoBERTa’s word embeddings. The hyperparameter search took roughly 4 days on two Titan V GPUs. The final choices for each task are shown in Table 5. Initialization with [MASK] performed better than the random initial- ization. We disable all dropouts inside Transformer. We use huggingface implementation of AdamW op- timizer with weight decay disabled. The gradi- ent is normalized to the value 1.0. For the batch sampling we use bucketing with padding noise of 0.1. In order to use the device memory more ef- fectively, we also set maximum number of tokens per batch to 2048. The maximum sequence length is truncated to 512 tokens. We enable mixed preci- sion and pad all sequence lengths to the multiples of 8 for the effective usage of TensorCores8. 8https://docs.nvidia.com/deeplearning/performance/mixed- precision-training/index.html Task MNLI QNLI QQP RTE SST-2 MRPC CoLA STS-B Learning rate Epochs 0.001 0.001 0.0003 0.001 0.003 0.001 0.001 0.001 10 10 20 20 20 20 20 20 Init. [MASK] [MASK] [MASK] MNLI [MASK] MNLI [MASK] MNLI Table 5: Hyperparameters of our best-performing mod- els. [MASK] means the prompts are intialized with the word embedding of same token, and MNLI means the prompt is initialized with the prompts of out best MNLI run. # B Learned Tokens Table 6 lists the closest vocabulary words to the learned embeddings. Most tasks have two input sentences, so the prompts consist of three parts: one is added before the first sentence, the sec- ond one is added between the sentences and the third one is appended next to the second sentence. For the single-sentence tasks, the second and third parts of the prompt are simply concatenated. Each task has trainable verbalizer tokens, one per output class. The prompts of RTE, MRPC and STS-B are pretty similar to MNLI’s prompts, as the mod- els for these tasks were initialized from pretrained MNLI models. The other tasks were initialized with [MASK] tokens. The final model for CoLA didn’t move too far from its initialization. MNLI QNLI QQP Prompts Verbalizers Prompts Verbalizers Prompts before between after entailment neutral contradiction before between after entailment not entailment before between A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A- Tomorrow Ale .aGj *. MUCH irin [/ a (@ [MASK] dL aHJ E [MASK] aKH <!– informing inyl entit dim categories gomery Unless *. neigh [MASK] U {{ aG—aG— [MASK] olitan pronouns [MASK] [MASK] [MASK] @@@@ [MASK] Choi [MASK] VIDE 470 resembling swarm Paramount Calm Membership derive rics [MASK] alias iary [MASK] omnip [MASK] [MASK] [MASK] sham RTE SST-2 MRPC Verbalizers Prompts Verbalizers Prompts Verbalizers Prompts Verbalizers after not duplicate duplicate before between after entailment not entailment before between after negative positive before between after entailment neutral before between [MASK] forb [MASK] Firefly THEY ende sugg A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A- Tomorrow ALE .aGj *. MUCH irin [/ a (@ [MASK] aHJ femin [MASK] aK ahiahi informing # entit OOOO e! blames choes charms sorely ”... akijakij a afe Pae charred masked [MASK] Fall babys smartest ik / dL forums bio mang A+- defective important A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A- Tomorrow rison .aGj *. MUCH irin [/ a jay [MASK] dL aHJ femin [MASK] .? > informing # entit OOOO categories gomery CoLA STS-B Prompts Verbalizers Prompts after unacceptable acceptable before [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] [MASK] additionally o A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A- [MASK] Kers irin [/ a (@ [MASK] dL AhAHAhAH femin [MASK] aKH A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A- repertoire inyl Idea dim Tomorrow Ale .aGj Table 6: The closest words to the prompt and verbalizer token embeddings for the best model for each task. We use cosine distance to measure the distance. [MASK] tokens highlighted in bold indicate the positions we use to output the prediction.
Title: PRIMERA: Pyramid-based Masked Sentence Pre-training for Multi-document Summarization: Summary: We introduce PRIMERA, a pre-trained model for multi-document representation with a focus on summarization that reduces the need for dataset-specific architectures and large amounts of fine-tuning labeled data. PRIMERA uses our newly proposed pre-training objective designed to teach the model to connect and aggregate information across documents. It also uses efficient encoder-decoder transformers to simplify the processing of concatenated input documents. With extensive experiments on 6 multi-document summarization datasets from 3 different domains on zero-shot, few-shot and full-supervised settings, PRIMERA outperforms current state-of-the-art dataset-specific and pre-trained models on most of these settings with large margins. The code and pre-trained models can be found at \url{https://github.com/allenai/PRIMER}. # PRIMERA: Pyramid-based Masked Sentence Pre-training for Multi-document Summarization # Wen Xiao†∗ Iz Beltagy‡ Giuseppe Carenini† Arman Cohan‡§ †University of British Columbia, Vancouver, Canada ‡Allen Institute for AI, Seattle, WA, USA §Paul G. Allen School of Computer Science & Engineering, University of Washington {xiaowen3,carenini}@cs.ubc.ca, {beltagy,armanc}@allenai.org # Abstract We introduce PRIMERA, a pre-trained model for multi-document representation with a fo- cus on summarization that reduces the need for dataset-specific architectures and large amounts of fine-tuning labeled data. PRIMERA uses our newly proposed pre-training objective designed to teach the model to connect and ag- gregate information across documents. It also uses efficient encoder-decoder transformers to simplify the processing of concatenated input documents. With extensive experiments on 6 multi-document summarization datasets from 3 different domains on zero-shot, few-shot and full-supervised settings, PRIMERA outper- forms current state-of-the-art dataset-specific and pre-trained models on most of these set- tings with large margins.1 General-Purpose Pre-trained Models Task-Specific Pre-trained Models Single-doc ‘Summarization w! Entity Pyramid ct for multi-doc input, Multi-doc PRIMERA ) summarization Figure 1: PRIMERA vs existing pretrained models. have shown the advantages of pretraining and trans- fer learning for generation and summarization (Raf- fel et al., 2020; Lewis et al., 2020; Beltagy et al., 2020; Zaheer et al., 2020). Yet, existing pretrained models either use single-document pretraining ob- jectives or use encoder-only models that do not work for generation tasks like summarization (e.g., CDLM, Caciularu et al., 2021). 1 # 1 Introduction Multi-Document Summarization is the task of generating a summary from a cluster of re- lated documents. State-of-the-art approaches to multi-document summarization are primarily ei- ther graph-based (Liao et al., 2018; Li et al., 2020; Pasunuru et al., 2021), leveraging graph neural net- works to connect information between the docu- (Liu and Lapata, 2019a; ments, or hierarchical Fabbri et al., 2019; Jin et al., 2020), building inter- mediate representations of individual documents and then aggregating information across. While ef- fective, these models either require domain-specific additional information e.g. Abstract Meaning Representation (Liao et al., 2018), or discourse graphs (Christensen et al., 2013; Li et al., 2020), or use dataset-specific, customized architectures, mak- ing it difficult to leverage pretrained language mod- els. Simultaneously, recent pretrained language models (typically encoder-decoder transformers) Therefore, we argue that these pretrained models are not necessarily the best fit for multi-document summarization. Alternatively, we propose a simple pretraining approach for multi-document summa- rization, reducing the need for dataset-specific ar- chitectures and large fine-tuning labeled data (See Figure 1 to compare with other pretrained mod- els). Our method is designed to teach the model to identify and aggregate salient information across a “cluster” of related documents during pretrain- ing. Specifically, our approach uses the Gap Sen- tence Generation objective (GSG) (Zhang et al., 2020), i.e. masking out several sentences from the input document, and recovering them in or- der in the decoder. We propose a novel strategy for GSG sentence masking which we call, En- tity Pyramid, inspired by the Pyramid Evaluation method (Nenkova and Passonneau, 2004). With Entity Pyramid, we mask salient sentences in the entire cluster then train the model to generate them, encouraging it to find important information across documents and aggregate it in one summary. ∗Work mainly done during an internship at AI2. 1The code and pre-trained models can be found at https: //github.com/allenai/PRIMER We conduct extensive experiments on 6 multi- document summarization datasets from 3 differ- ent domains. We show that despite its simplic- Sent1 Sent 2 mn in Documents c c ~ Masked Sentence <s> 's <is> tokens and attention, ildfires|| have ||burned in| Colorado with Other tokens Attention attention only. al Attention Local Attention Longformer Encoder Decoder (LED) Tokens with Selected Local Attention special [sent masked jem | | ll ere | join | [sent mask]| | Six | wildfires) were| |.) |<doc-sep> ||Wildfires continued) ...| |[sent mask]| |<doc-sep> | |The| | Buffalo | |...| | <doc-sep> | </s> w/ Global w/ Global “———*———_ w/Giobal Doc 1 Attention Doc 2 Attention Doc 3 Attention { <s>| are separated with <doc-sep> they are assigned global except for <s> have local sentences are replaced with a mask] token # sentences Figure 2: Model Structure of PRIMERA. ity, PRIMERA achieves superior performance com- pared with prior state-of-the-art pretrained models, as well as dataset-specific models in both few-shot and full fine-tuning settings. PRIMERA performs particularly strong in zero- and few-shot settings, significantly outperforming prior state-of-the-art up to 5 Rouge-1 points with as few as 10 examples. Our contributions are summarized below: 1. We release PRIMERA, the first pretrained gener- ation model for multi-document inputs with focus on summarization. 2. We propose Entity Pyramid, a novel pretraining strategy that trains the model to select and aggre- gate salient information from documents. 3. We extensively evaluate PRIMERA on 6 datasets from 3 different domains for zero-shot, few-shot and fully-supervised settings. We show that PRIMERA outperforms current state-of-the-art on most of these evaluations with large margins. them with an encoder-decoder transformer model. Since the concatenated sequence is long, instead of more standard encoder-decoder transformers like BART (Lewis et al., 2020) and T5 (Raffel et al., 2020), we use the Longformer-Encoder-Decoder (LED) Model (Beltagy et al., 2020), an efficient transformer model with linear complexity with respect to the input length.2 LED uses a sparse local+global attention mechanism in the encoder self-attention side while using the full attention on decoder and cross-attention. When concatenating, we add special document separator tokens (<doc-sep>) between the doc- uments to make the model aware of the document boundaries (Figure 2). We also assign global at- tention to these tokens which the model can use to share information across documents (Caciularu et al., 2021) (see §5 for ablations of the effective- ness of this input structure and global attention). # 2 Model # 2.2 Pretraining objective In this section, we discuss our proposed model PRIMERA, a new pretrained general model for multi-document summarization. Unlike prior work, PRIMERA minimizes dataset-specific modeling by simply concatenating a set of documents and pro- cessing them with a general efficient encoder- decoder transformer model (§2.1). The underlying transformer model is pretrained on an unlabeled multi-document dataset, with a new entity-based sentence masking objective to capture the salient in- formation within a set of related documents (§2.2). In summarization, task-inspired pretraining ob- jectives have been shown to provide gains over general-purpose pretrained transformers (PEGASUS; Zhang et al., 2020). In particular, PE- GASUS introduces Gap Sentence Generation (GSG) as a pretraining objective where some sentences are masked in the input and the model is tasked to gen- erate them. Following PEGASUS, we use the GSG objective, but introduce a new masking strategy designed for multi-document summarization. As in GSG, we select and mask out m summary-like sen- tences from the input documents we want to sum- marize, i.e. every selected sentence is replaced by a # 2.1 Model Architecture and Input Structure Our goal is to minimize dataset-specific modeling to leverage general pretrained transformer models for the multi-document task and make it easy to use in practice. Therefore, to summarize a set of related documents, we simply concatenate all the documents in a single long sequence, and process 2We use LED and not other efficient transformers like Bigbird-PEGASUS (Zaheer et al., 2020) for two reasons, the first is that BigBird’s global attention can’t be assigned to indi- vidual tokens in the middle of the sequence, which is important for the representation of long documents as shown in Caci- ularu et al. (2021). Second, because pretrained checkpoints are available for LED, while BigBird-PEGASUS released the already fine-tuned checkpoints. Document #1 Wildfires have burned across tens of thousands of acres of parched terrain in Colorado, spurring thousands of evacuations ...(0.107)..., res- idents have sought shelter in middle schools, and local officials fear tourists usually drawn to the region for the summer may not come. Document #2 ... In Colorado’s southwest, authorities have shuttered the San Juan National Forest in southwestern Colorado and residents of more than 2,000 homes were forced to evacuate.(0.187) No homes had been destroyed ... “Under current conditions, one abandoned campfire or spark could cause a catastrophic wildfire, ..., with human life and property,” said San Juan National Forest Fire Staff Officer Richard Bustamante... Document #3 The Buffalo Fire west of Denver is ... Several wildfires in Col- orado have prompted thousands of home evacuations ...(0.172)... Nearly 1,400 homes have been evacuated in Summit County, Colorado, ...(0.179)... “Under current conditions, one abandoned campfire or spark could cause a catastrophic wildfire, ... , with human life and property,” said Richard Bustamante, SJNF forest fire staff officer ... Entities with High Frequency Colorado, 416, Tuesday, Wildfires, San Juan National Forest,... Figure 3: An example on sentence selection by Princi- ple vs our Entity Pyramid strategy. Italic text in red is the sentence with the highest Principle ROUGE scores, which is thereby chosen by the Principle Strategy. Most frequent entity ’Colorado’ is shown with blue, followed by the Pyramid ROUGE scores in parenthesis. The fi- nal selected sentence by Entity Pyramid strategy is in italic. which is a better pseudo-summary than the ones selected by the Principle strategy. single token [sent-mask] in the input, and train the model to generate the concatenation of those sentences as a “pseudo-summary” (Figure 2). This is close to abstractive summarization because the model needs to reconstruct the masked sentences using the information in the rest of the documents. The key idea is how to select sentences that best summarize or represent a set of related in- put documents (which we also call a “cluster”), not just a single document as in standard GSG. Zhang et al. (2020) use three strategies - Random, Lead (first m sentences), and “Principle”. The “Principle” method computes sentence salience score based on ROUGE score of each sentence, si, w.r.t the rest of the document (D/{si}), i.e. Score(si) = ROUGE(si, D/{si}). Intuitively, this assigns a high score to the sentences that have a high overlap with the other sentences. However, we argue that a naive extension of such strategy to multi-document summarization would be sub-optimal since multi-document inputs typically include redundant information, and such strategy would prefer an exact match between sen- tences, resulting in a selection of less representative information. For instance, Figure 3 shows an example of sen- tences picked by the Principle strategy (Zhang et al., 2020) vs our Entity Pyramid approach. The figure shows a cluster containing three news articles dis- cussing a wildfire happened in Corolado, and the pseudo-summary of this cluster should be related to the location, time and consequence of the wild- fire, but with the Principle strategy, the non-salient sentences quoting the words from an officer are assigned the highest score, as the exact same sen- tence appeared in two out of the three articles. In comparison, instead of the quoted words, our strat- egy selects the most representative sentences in the cluster with high frequency entities. To address this limitation, we propose a new masking strategy inspired by the Pyramid Evalua- tion framework (Nenkova and Passonneau, 2004) which was originally developed for evaluating sum- maries with multiple human written references. Our strategy aims to select sentences that best rep- resent the entire cluster of input documents. # 2.2.1 Entity Pyramid Masking Pyramid Evaluation The Pyramid Evaluation method (Nenkova and Passonneau, 2004) is based on the intuition that relevance of a unit of informa- tion can be determined by the number of references (i.e. gold standard) summaries that include it. The unit of information is called Summary Content Unit (SCU); words or phrases that represent single facts. These SCUs are first identified by human annota- tors in each reference summary, and they receive a score proportional to the number of reference sum- maries that contain them. A Pyramid Score for a candidate summary is then the normalized mean of the scores of the SCUs that it contains. One advantage of the Pyramid method is that it directly assesses the content quality. Entity Pyramid Masking Inspired by how con- tent saliency is measured in the Pyramid Evalua- tion, we hypothesize that a similar idea could be applied in multi-document summarization to iden- tify salient sentences for masking. Specifically, for a cluster with multiple related documents, the more documents an SCU appears in, the more salient that information should be to the cluster. Therefore, it should be considered for inclusion in the pseudo- summary in our masked sentence generation objec- tive. However, SCUs in the original Pyramid Eval- uation are human-annotated, which is not feasible for large scale pretraining. As a proxy, we explore leveraging information expressed as named entities, since they are key building blocks in extracting in- formation from text about events/objects and the relationships between their participants/parts (Ju- rafsky and Martin, 2009). Following the Pyramid Extract Entities Entity Pyramid Estimation Sentence Selection Sentences with Cluster Sentences . Entity 4 Entity? ROUGE Doc 1: {Entity 1, Entity 2, Entity 6} frequency: 4 y Doc 1 Sent 9.407 to mask out Entity 1 Doc2 Sent10 0.142 Doc 1: Sent 2, _ Entity 2 Sent 6, Poe a:fenity 1 Entiy 2 Eni frequency: 3 Doc 4 Sent2 0.110 ty 5, Entity 7 : - “oO Entity 2| [Entity 3 Sentences wih Cluster] _|Doc2: Sent 10, » => Entity 3 Entity 2 ROUGE [Doc TSent2 0.200 frequency: 2 Entity 4] [entity s Doc? Sens 0.180 Doc 3: Entity 4 Doc3Sent3 0.015 Doe 4: / : Sentences with — Cluster frequency: 1 ia y y Entity 5 Entity3 ROUGE Figure 4: The Entity Pyramid Strategy to select salient sentences for masking. Pyramid entity is based on the frequency of entities in the documents. The most representative sentence are chosen based on Cluster ROUGE for each entity with frequency > 1, e.g. Sentence 10 in Document 2 for Entity 1. Algorithm 1 Entity Pyramid Sentence Selection Input: Document cluster Input: List of entities w/ frequency > 1. N length of the list Input: m number of sentences to select Output: List of sentences to mask 1: E ← sort entities by frequency, descending 2: selected = [] 3: for i ← 1 to |E| do 4: SentCand ← all sentences in the cluster containing E[i] 5: 6: 7: 8: 9: 10: end for 11: Return selected cur_sent = arg maxs∈SentCand Score(s) selected.append(cur_sent) if |selected| == m then framework, we use the entity frequency in the clus- ter as a proxy for saliency. Concretely, as shown in Fig. 4, we have the following three steps to select salient sentences in our masking strategy: 1. Entity Extraction. We extract named entities using SpaCy (Honnibal et al., 2020).3 2. Entity Pyramid Estimation. We then build an Entity Pyramid for estimating the salience of en- tities based on their document frequency, i.e. the number of documents each entity appears in. 3. Sentence Selection. Similar to the Pyramid eval- uation framework, we identify salient sentences with respect to the cluster of related documents. Al- gorithm 1 shows the sentence selection procedure. As we aim to select the entities better representing the whole cluster instead of a single document, we first remove all entities from the Pyramid that ap- pear only in one document. Next, we iteratively se- lect entities from top of the pyramid to bottom (i.e., 3Note that entity information is only used at pretraining time. This is unlike some prior work (e.g. Pasunuru et al. (2021)) that utilize additional information (like named entities, coref, discourse, or AMR) at fine-tuning and inference time. highest to lowest frequency), and then select sen- tences in the document that include the entity as the initial candidate set. Finally, within this candidate set, we find the most representative sentences to the cluster by measuring the content overlap of the sen- tence w.r.t documents other than the one it appears in. This final step supports the goal of our pre- training objective, namely to reconstruct sentences that can be recovered using information from other documents in the cluster, which encourages the model to better connect and aggregate information across multiple documents. Following Zhang et al. (2020) we use ROUGE scores (Lin, 2004) as a proxy for content overlap. For each sentence s;, we specifically define a Cluster ROUGE score as Score(s;) = DX {doc €C,5i¢ doc;} ROUGE(s;, doc;) Where C is the cluster of related documents. Note that different from the importance heuristic defined in PEGASUS (Zhang et al., 2020), Entity Pyramid strategy favors sentences that are repre- sentative of more documents in the cluster than the exact matching between fewer documents (See Figure 3 for a qualitative example.) . The benefit of our strategy is shown in an ablation study (§5). # 3 Experiment Goals We aim to answer the following questions: • Q1: How does PRIMERA perform, compared with existing pre-trained generation models in zero- and few-shot settings? See §4.2. • Q2: How does PRIMERA perform, compared with current state-of-the-art models, in the fully supervised setting? See §4.5. • Q3: How much is the contribution of each compo- nent in PRIMERA, i.e. input structure, pretraining, and masking strategy? See §5. • Q4: What is the effect of our entity pyramid Dataset #Examples #Doc/C Lensrc Lensumm Newshead (2020) 360K 3.5 1734 Multi-News (2019) Multi-Xscience (2020) Wikisum* (2018) WCEP-10 (2020) DUC2004 (2005) arXiv (2018) 56K 40K 1.5M 10K 50 214K 2.8 4.4 40 9.1 10 5.5 1793 700 2238 3866 5882 6021 - 217 105 113 28 115 272 Table 1: The statistics of all the datasets we explore in this paper. *We use subsets of Wikisum (10/100, 3200) for few-shot training and testing only. strategy, compared with the strategy used in PEGA- SUS? See §5. • Q5: Is PRIMERA able to capture salient informa- tion and generate fluent summaries? See §6. With these goals, we explore the effectiveness of PRIMERA quantitatively on multi-document sum- marization benchmarks, verify the improvements by comparing PRIMERA with multiple existing pre- trained models and SOTA models, and further vali- date the contribution of each component with care- fully controlled ablations. An additional human evaluation is conducted to show PRIMERA is able to capture salient information and generate more fluent summaries. # 4 Experiments # 4.1 Experimental Setup Implementation the (Belt- Longformer-Encoder-Decoder agy et al., 2020) large as our model initialization, The length limits of input and output are 4096 and 1024, respectively, with sliding window size as w = 512 for local attention in the input. (More implementation details of pretraining process can be found in Appx §A) Pretraining corpus For pretraining, our goal is to use a large resource where each instance is a set of related documents without any ground-truth summaries. The Newshead dataset (Gu et al., 2020) (row 1, Table 1) is an ideal choice; it is a relatively large dataset, where every news event is associated with multiple news articles. Evaluation Datasets We evaluate our approach on wide variety of multi-document summarization datasets plus one single document dataset from various domains (News, Wikipedia, and Scientific literature). See Table 1 for dataset statistics and Appx. §B for details of each dataset. Evaluation metrics previous Following works (Zhang et al., 2020), we use ROUGE scores (R-1, -2, and -L), which are the standard evaluation metrics, to evaluate the downstream task of multi-document summarization.4 For better readability, we use AVG ROUGE scores (R-1, -2, and -L) for evaluation in the few-shot setting. # 4.2 Zero- and Few-shot Evaluation Many existing works in adapting pretrained models for summarization require large amounts of fine- tuning data, which is often impractical for new domains. In contrast, since our pretraining strategy is mainly designed for multi-document summariza- tion, we expect that our approach can quickly adapt to new datasets without the need for significant fine-tuning data. To test this hypothesis, we first provide evaluation results in zero and few-shot set- tings where the model is provided with no, or only a few (10 and 100) training examples. Obtaining such a small number of examples should be viable in practice for new datasets. Comparison To better show the utility of our pre- trained models, we compare with three state-of-the- art pretrained generation models: BART (Lewis et al., 2020)5, PEGASUS (Zhang et al., 2020) and Longformer-Encoder-Decoder(LED) (Beltagy et al., 2020). These pretrained models have been shown to outperform dataset-specific models in summarization (Lewis et al., 2020; Zhang et al., 2020), and because of pretraining, they are ex- pected to also work well in the few-shot settings. As there is no prior work doing few-shot and zero- shot evaluations on all the datasets we consider, and also the results in the few-shot setting might be influenced by sampling variability (especially with only 10 examples) (Bragg et al., 2021), we run the same experiments for the compared mod- els five times with different random seeds (shared with all the models), with the publicly available checkpoints .6 Similar to Pasunuru et al. (2021), the inputs of all the models are the concatenations of the docu- ments within the clusters (in the same order), each document is truncated based on the input length limit divided by the total number of documents so 4We use https://github.com/google-research/google- research/tree/master/rouge with default stemmer settings. 5Pilot experiments comparing BART and T5 showed BART to outperform T5 on the few-shot evaluation of Multi- News (with AVG ROUGE of 23.5/26.4 (T5) v.s. 25.2/26.7 (BART) for 10/100 training examples, respectively). Thus, we are using BART as one of the baselines. 6Checkpoints from https://huggingface.co/models Models Multi-News(256) Multi-XSci(128) WCEP(50) WikiSum(128) arXiv(300) DUC2004 (128) Rl R2 RL RI R2 RL RI R2 RL RI R2 RL RI R2 RL RI R2 RL PEGASUS«(Zhang et al. 2020) 36.5 10.5 18.7 Se 8 66 ITT PEGASUS (our run) 32.0 10.1 16.7 276 46 15.3 332 12.7 238 246 5.5 15.0 295 7.9 17.1 327 74 17, BART (our run) 273.62 15.1 189 26 12.3 20.2 57 153 216 5.5 15.0 292 7.5 169 241 40 153 LED (our run) 173. 3.7 104 1446 19 99 188 54 147 105 24 86 150 31 108 166 3.0 12, PRIMERA (our model) 42.0 13.6 208 291 46 15.7 28.0 103 209 280 80 180 346 94 183 351 7.2 179 Table 2: Zero-shot results. The models in the first block use the full-length attention (O(n”)) and are pretrained on the single document datasets. The numbers in the parenthesis following each dataset indicate the output length limit set for inference. PEGASUS means results taken exactly from PEGASUS (Zhang et a ., 2020), where available. # AVG ROUGE Multi-News Multi-Xscience Wikisum 1s{ 16 14} N 8 12 a 10} S ° 100 0 10 100 10 6 Number of Training Examples WCEP arXiv DUC2004 Ours BART PEGASUS LED 100 10 100 20 Figure 5: The AVG ROUGE scores (R-1, R-2 and R-L) of the pretrained models with 0, 10 and 100 training data with variance. All the results of few-shot experiments (10 and 100) are obtained by the average of 5 random runs (with std, and the same set of seeds shared by all the models). Note that DUC2004 only has 50 examples, we use 20/10/20 for train/valid/test in the few-shot experiments. that all documents are represented in the input. 7 To preserve the same format as the correspond- ing pretrained models, we set the length limit of output for BART and PEGASUS exactly as their pretrained settings on all of the datasets (except for the zero-shot experiments, the details can be found in Sec.4.3). Regarding length limit of in- puts, we tune the baselines by experimenting with 512, 1024, 4096 on Multi-News dataset in few-shot setting (10 data examples), and the model with length limit 512(PEGASUS)/1024(BART) achieves the best performance, thus we use this setting (de- tailed experiment results for different input lengths can be found in Appx. §C.1). We use the same length limit as our model for the LED model, i.e. 4096/1024 for input and output respectively, for all the datasets. 4.3 Zero-Shot Results For zero-shot8 abstractive summarization experi- ments, since the models have not been trained on the downstream datasets, the lengths of generated summaries mostly depend on the pretrained set- tings. Thus to better control the length of gener- ated summaries and for a fair comparison between all models, following Zhu et al. (2021), we set the 7Pilot experiments show simple truncation results in infe- rior performance, which is in line with Pasunuru et al. (2021). 8For clarity, by zero-shot we mean using the pretrained model directly without any additional supervision. length limit of the output at inference time to the av- erage length of gold summaries.9 Exploring other approaches to controlling length at inference time (e.g., Wu et al., 2021) is an orthogonal direction, which we leave for future work. Table 2 shows the performance comparison among all the models. Results indicate that our model achieves substantial improvements com- pared with all the three baselines on most of the datasets. As our model is pretrained on clusters of documents with longer input and output, the benefit is stronger on the dataset with longer summaries, e.g. Multi-News and arXiv. Comparing PEGASUS and BART models, as the objective of PEGASUS is designed mainly for summarization tasks, not surprisingly it has relatively better performances across different datasets. Interestingly, LED un- derperforms other models, plausibly since part of the positional embeddings (1k to 4k) are not pre- trained. Encouragingly, our model performs the best, demonstrating the benefits of our pretraining strategy for multi-document summarization. # 4.4 Few Shot Evaluation Compared with the strict zero-shot scenario, few- shot experiments are closer to the practical scenar- ios, as it is arguably affordable to label dozens of examples for almost any application. 9In practice, it is reasonable to assume knowing the approx- imate length of the expected summary for a given task/domain. We fine-tune all of the four models on different subsets with 10 and 100 examples, and the results are shown in Figure 5. (hyperparameter settings in Appx. §D.1) Since R-1, -2, and -L show the same trend, we only present the average of the three metrics in the figure for brevity (full ROUGE scores can be found in Appx. Table 8) To show the generality, all the results of few-shot experiments are the average over 5 runs on different subsets (shared by all the models). The result of each run is obtained by the ‘best’ model chosen based on the ROUGE scores on a randomly sampled few-shot validation set with the same number of examples as the training set, which is similar with Zhang et al. (2020). Note that their reported best models have been selected based on the whole validation set which may give PEGA- SUS some advantage. Nevertheless, we argue that sampling few-shot validation sets as we do here is closer to real few-shot scenarios (Bragg et al., 2021). Our model outperforms all baselines on all of the datasets with 10 and 100 examples demonstrat- ing the benefits of our pretraining strategy and in- put structure. Comparing the performances of our model with the different number of training data fed in, our model converges faster than other mod- els with as few as 10 data examples. # 4.5 Fully Supervised Evaluation To show the advantage of our pretrained model when there is abundant training data, we also train the model with the full training set (hyperparame- ter settings can be found in Appx. §D.2). Table 3 shows the performance comparison with previous state-of-the-art10, along with the results of previous SOTA. We observe that PRIMERA achieves state- of-the-art results on Multi-News, WCEP, and arXiv, while slightly underperforming the prior work on Multi-XScience (R-1). One possible explanation is that in Multi-XScience clusters have less over- lapping information than in the corpus on which PRIMERA was pretrained. In particular, the source documents in this dataset are the abstracts of all the publications cited in the related work paragraphs, which might be less similar to each other and the target related work(i.e., their summary) . PRIMERA 9We re-evaluate the generated summaries of the models from Lu et al. (2020) for Multi-XScience, as we use a different version of ROUGE. 10Due to the lack of computational resources, we do not train the model on Wikisum. Datasets Previous SOTA PRIMERA R-1 R-2 R-L R-1 R-2 R-L Multi-News Multi-XScience 33.9 WCEP arXiv 49.2 19.6 24.5 49.9 21.1 25.9 7.4 18.0 35.4 15.1 25.6 46.1 25.2 37.9 46.6 19.6 41.8 47.6 20.8 42.6 6.8 18.2 31.9 Table 3: Fully supervised results. Previous SOTA are from Pasunuru et al. (2021) for Multi-News, Lu et al. (2020) for Multi-XScience11, Hokamp et al. (2020) for WCEP, and Beltagy et al. (2020) for arXiv. (a) Ablation on Struct. & Pre-train (b) Entity Pyramid V.S. PEGASUS 27 27.5 25.0 26 wy 22.5 25 3 20.0 ao 24 Sirs < 23 15.0 —- LED 12.5:—+~ LeD+struct. 22) —-— Entity Pyramid —+— Ours(LED+struct. +pre-train) —s— PEGASUS masking strategy 10.0 2 0) 10 100 0 10 160 Number of Training Examples Figure 6: Ablation study with the few-shot setting on the Multi-News dataset regarding to (a) input Structure (<doc-sep> tokens between documents and global attention on them) and pretraining, (b) pretraining us- ing PEGASUS vs our approach. outperforms the LED model (State-of-the-art) on the arXiv dataset while using a sequence length 4x shorter (4K in PRIMERA v.s. 16K in LED), further showing that the pretraining and input structure of our model not only works for multi-document sum- marization, but can be also effective for summariz- ing single documents having multiple sections. # 5 Ablation Study We conduct ablation studies on the Multi-News dataset in few-shot setting, to validate the contribu- tion of each component in our pretrained models. Input structure: In Figure 6 (a) we observe the effectiveness of both pretraining and the input struc- ture (<doc-sep> tokens between documents and global attention on them). Sentence masking strategy: To isolate the effect of our proposed pretraining approach, we compare with a model with exactly the same architecture when pretrained on the same amount of data but using the PEGASUS (Zhang et al., 2020) masking strategy instead of ours. In other words, we keep all the other settings the same (e.g., data, length limit of input and output, pretraining dataset, in- put structure, as well as the separators) and only modify the pretraining masking strategy. We run the same experiments under zero-/few-shot scenar- ios on the Multi-News dataset as in §4.2, and the results are shown in Figure 6 (b). The model pre- trained with our Entity Pyramid strategy shows a clear improvement under few-shot scenarios. # 6 Human Evaluation We also conduct human evaluations to validate the effectiveness of PRIMERA on DUC2007 and TAC2008 (Dang and Owczarzak, 2008) datasets in the few-shot setting (10/10/20 examples for train/valid/test). Both datasets consist of clusters of news articles, and DUC2007 contains longer inputs (25 v.s. 10 documents/cluster) and summaries (250 v.s. 100 words). Since the goal of our method is to enable the model to better aggregate information across documents, we evaluate the content quality of the generated summaries following the original Pyramid human evaluation framework (Nenkova and Passonneau, 2004). In addition, we also evalu- ate the fluency of generated summaries following the DUC guidelines.12 Settings Three annotators13 are hired to do both Pyramid Evaluation and Fluency evaluation, they harmonize the standards on one of the examples. Specifically, for each data example, we provide three anonymized system generated summaries, along with a list of SCUs. The annotators are asked to find all the covered SCUs for each summary, and score the fluency in terms of Grammaticality, Referential clarity and Structure & Coherence, ac- cording to DUC human evaluation guidelines, with a scale 1-5 (worst to best). They are also suggested to make comparison between three generated sum- maries into consideration when scoring the fluency. To control for the ordering effect of the given sum- maries, we re-order the three summaries for each data example, and ensure the chance of their ap- pearance in different order is the same (e.g. BART appears as summary A for 7 times, B for 7 times and C for 6 times for both datasets). The instruction for human annotation can be found in Figure 7 and Figure 8 in the appendix. Annotators were aware that annotations will be used solely for computing aggregate human evaluation metrics and reporting in the scientific paper. Compared Models We compare our model with LED and PEGASUS in human evaluations. Be- 12https://www-nlpir.nist.gov/projects/ duc/duc2007/quality-questions.txt 13We recruited expert annotators with payment above aver- age of the participants’ demographics. Model DUC2007(20) Sr R P F Sr TAC2008(20) R P F PEGASUS LED PRIMERA 6.0 2.5 2.4 2.4 8.7 9.1 9.4 9.1 9.6 3.9 4.0 3.8 6.9 7.1 10.8 8.4 12.5 5.1 5.0 5.0 8.5 8.9 10.0 9.3 Table 4: Pyramid Evaluation results: Raw scores Sr, (R)ecall, (P)recision and (F)-1 score. For readability, Recall, Precision and F-1 scores are multiplied by 100. Model DUC2007(20) TAC2008(20) Gram. Ref. Str.&Coh. Gram. Ref. Str.&Coh. PEGASUS 4.45 4.35 4.35 4.50 LED 4.70 4.65 PRIMERA 1.95 3.20 3.70 4.40 4.20 3.10 3.80 4.40 4.45 3.20 2.55 4.10 Table 5: The results of Fluency Evaluation on two datasets, in terms of the Grammaticality , Referential clarity and Structure & Coherence. cause PEGASUS is a task-specific model for ab- stractive summarization, and LED has the same architecture and length limits as our model with the parameters inherited from BART, which is more comparable with our model than vanilla BART. Pyramid Evaluation Both TAC and DUC datasets include SCU (Summary Content Unit) an- notations and weights identified by experienced annotators. We then ask 3 annotators to make a binary decision whether each SCU is covered in a candidate summary. Following Nenkova and Pas- sonneau (2004), the raw score of each summary is then computed by the sum of weights of the cov- ered SCUs, i.e. Sp = Yoooy wil (SCU;), where I(SCU;) is an indicator function on whether SCU; is covered by the current summary, and w; is the weight of SCUj. In the original pyramid evalua- tion, the final score is computed by the ratio of 5; to the maximum possible weights with the same number of SCUs as in the generated summaries. However, the total number of SCUs of generated summaries is not available in the simplified anno- tations in our design. To take consideration of the length of generated summaries and make a fair com- parison, instead, we compute Recall, Precision and F-1 score regarding lengths of both gold references and system generated summaries as R= Sr len(gold) ; P= Sr len(sys) ; F1= 2 · R · P (R + P ) Fluency Evaluation Fluency results can be found in Table 5, and PRIMERA has the best perfor- mance on both datasets in terms of all aspects. Only for Grammaticality PRIMERA’s top performance is matched by PEGASUS. # 7 Related Work Neural Multi-Document Summarization These models can be categorized into two classes, graph-based models (Yasunaga et al., 2017; Liao et al., 2018; Li et al., 2020; Pasunuru et al., 2021) and hierarchical models (Liu and Lapata, 2019a; Fabbri et al., 2019; Jin et al., 2020). Graph-based models often require auxiliary information (e.g., AMR, discourse structure) to build an input graph, making them reliant on auxiliary models and less general. Hierarchical models are another class of models for multi-document summarization, examples of which include multi-head pooling and inter-paragraph attention (Liu and Lapata, 2019a), MMR-based attention (Fabbri et al., 2019; Mao et al., 2020), and attention across representations of different granularity (words, sentences, and documents) (Jin et al., 2020). Prior work has also shown the advantages of customized optimization in multi-document summarization (e.g., RL; Su et al., 2021). Such models are often dataset-specific and difficult to develop and adapt to other datasets or tasks. Pretrained Models for Summarization Pre- trained language models have been successfully applied to summarization, e.g., BERTSUM (Liu and Lapata, 2019b), BART (Lewis et al., 2020), T5 (Raffel et al., 2020). Instead of regular language modeling objectives, PEGASUS (Zhang et al., 2020) introduced a pretraining objective with a focus on summarization, using Gap Sentence Generation, where the model is tasked to generate summary- worthy sentences, and Zou et al. (2020) proposed different pretraining objectives to reinstate the orig- inal document, specifically for summarization task as well. Contemporaneous work by Rothe et al. (2021) argued that task-specific pretraining does not always help for summarization, however, their experiments are limited to single-document sum- marization datasets. Pretraining on the titles of HTMLs has been recently shown to be useful for few-shot short-length single-document summariza- tion as well (Aghajanyan et al., 2021). Goodwin et al. (2020) evaluate three state-of-the-art models (BART, PEGASUS, T5) on several multi-document summarization datasets with low-resource settings, showing that abstractive multi-document summa- rization remains challenging. Efficient pretrained transformers (e.g., Longformer (Beltagy et al., 2020) and BigBird (Zaheer et al., 2020) that can process long sequences have been also proven suc- cessful in summarization, typically by the ability to process long inputs, connecting information across the entire sequence. CDLM (Caciularu et al., 2021) is a follow-up work for pretraining the Longformer model in a cross-document setting using global at- tention on masked tokens during pretraining. How- ever, this model only addresses encoder-specific tasks and it is not suitable for generation. In this work, we show how efficient transformers can be pretrained using a task-inspired pretraining objec- tive for multi-document summarization. Our pro- posed method is also related to the PMI-based to- ken masking Levine et al. (2020) which improves over random token masking outside summariza- tion. # 8 Conclusion and Future Work In this paper, we present PRIMERA a pre-trained model for multi-document summarization. Unlike prior work, PRIMERA minimizes dataset-specific modeling by using a Longformer model pretrained with a novel entity-based sentence masking ob- jective. The pretraining objective is designed to help the model connect and aggregate informa- tion across input documents. PRIMERA outper- forms prior state-of-the-art pre-trained and dataset- specific models on 6 summarization datasets from 3 different domains, on zero, few-shot, and full fine-tuning setting. PRIMERA’s top performance is also revealed by human evaluation. In zero-shot setting, we can only control the output length of generated summaries at inference time by specifying a length limit during decoding. Exploring a controllable generator in which the de- sired length can be injected as part of the input is a natural future direction. Besides the summarization task, we would like to explore using PRIMERA for other generation tasks with multiple documents as input, like multi-hop question answering. # Ethics Concern While there is limited risk associated with our work, similar to existing state-of-the-art generation mod- els, there is no guarantee that our model will always generate factual content. Therefore, caution must be exercised when the model is deployed in prac- tical settings. Factuality is an open problem in existing generation models. # References Armen Aghajanyan, Dmytro Okhonko, Mike Lewis, Mandar Joshi, Hu Xu, Gargi Ghosh, and Luke Zettlemoyer. 2021. HTLM: hyper-text pre-training CoRR, and prompting of abs/2107.06955. Iz Beltagy, Matthew E. Peters, and Arman Cohan. 2020. Longformer: The long-document transformer. CoRR, abs/2004.05150. Jonathan Bragg, Arman Cohan, Kyle Lo, and Iz Belt- agy. 2021. Flex: Unifying evaluation for few-shot nlp. arXiv preprint arXiv:2107.07170. Avi Caciularu, Arman Cohan, Iz Beltagy, Matthew Pe- ters, Arie Cattan, and Ido Dagan. 2021. CDLM: In Findings Cross-document language modeling. of the Association for Computational Linguistics: EMNLP 2021, pages 2648–2662, Punta Cana, Do- minican Republic. Association for Computational Linguistics. Janara Christensen, Mausam, Stephen Soderland, and Towards coherent multi- Oren Etzioni. 2013. In Proceedings of the document summarization. 2013 Conference of the North American Chapter of the Association for Computational Linguistics: Hu- man Language Technologies, pages 1163–1173, At- lanta, Georgia. Association for Computational Lin- guistics. Arman Cohan, Franck Dernoncourt, Doo Soon Kim, Trung Bui, Seokhwan Kim, Walter Chang, and Na- zli Goharian. 2018. A discourse-aware attention model for abstractive summarization of long docu- In Proceedings of the 2018 Conference of ments. the North American Chapter of the Association for Computational Linguistics: Human Language Tech- nologies, Volume 2 (Short Papers), pages 615–621, New Orleans, Louisiana. Association for Computa- tional Linguistics. Hoa Trang Dang. 2005. Overview of duc 2005. In Pro- ceedings of the document understanding conference, volume 2005, pages 1–12. Hoa Trang Dang and Karolina Owczarzak. 2008. Overview of the tac 2008 update summarization task. Theory and Applications of Categories. Alexander Fabbri, Irene Li, Tianwei She, Suyi Li, and Dragomir Radev. 2019. Multi-news: A large-scale multi-document summarization dataset and abstrac- tive hierarchical model. In Proceedings of the 57th Annual Meeting of the Association for Computa- tional Linguistics, pages 1074–1084, Florence, Italy. Association for Computational Linguistics. Sebastian Gehrmann, Yuntian Deng, and Alexander Rush. 2018. Bottom-up abstractive summarization. the 2018 Conference on Em- In Proceedings of pirical Methods in Natural Language Processing, pages 4098–4109, Brussels, Belgium. Association for Computational Linguistics. Demian Gholipour Ghalandari, Chris Hokamp, Nghia The Pham, John Glover, and Georgiana Ifrim. 2020. A large-scale multi-document summarization dataset from the Wikipedia current events portal. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 1302–1308, Online. Association for Computational Linguistics. Travis Goodwin, Max Savery, and Dina Demner- Fushman. 2020. Flight of the PEGASUS? compar- ing transformers on few-shot and zero-shot multi- In Proceed- document abstractive summarization. ings of the 28th International Conference on Com- putational Linguistics, pages 5640–5646, Barcelona, Spain (Online). International Committee on Compu- tational Linguistics. Xiaotao Gu, Yuning Mao, Jiawei Han, Jialu Liu, You Wu, Cong Yu, Daniel Finnie, Hongkun Yu, Jiaqi Zhai, and Nicholas Zukoski. 2020. Generating rep- In Proceed- resentative headlines for news stories. ings of The Web Conference 2020, WWW ’20, page 1773–1784, New York, NY, USA. Association for Computing Machinery. Chris Hokamp, Demian Gholipour Ghalandari, Nghia The Pham, and John Glover. 2020. Dyne: Dynamic ensemble decoding for multi-document summarization. CoRR, abs/2006.08748. Ines Montani, Sofie Van Lan- deghem, spaCy: and Adriane Boyd. 2020. Industrial-strength Natural Language Processing in Python. Hanqi Jin, Tianming Wang, and Xiaojun Wan. 2020. Multi-granularity interaction network for extractive and abstractive multi-document summarization. In Proceedings of the 58th Annual Meeting of the Asso- ciation for Computational Linguistics, pages 6244– 6254, Online. Association for Computational Lin- guistics. Dan Jurafsky and James H. Martin. 2009. Speech and language processing : an introduction to natural language processing, computational linguistics, and speech recognition. Pearson Prentice Hall, Upper Saddle River, N.J. Yoav Levine, Barak Lenz, Opher Lieber, Omri Abend, Kevin Leyton-Brown, Moshe Tennenholtz, and Yoav Shoham. 2020. Pmi-masking: Princi- pled masking of correlated spans. arXiv preprint arXiv:2010.01825. Mike Lewis, Yinhan Liu, Naman Goyal, Mar- jan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Veselin Stoyanov, and Luke Zettlemoyer. 2020. BART: Denoising sequence-to-sequence pre- training for natural language generation, translation, and comprehension. In Proceedings of the 58th An- nual Meeting of the Association for Computational Linguistics, pages 7871–7880, Online. Association for Computational Linguistics. Wei Li, Xinyan Xiao, Jiachen Liu, Hua Wu, Haifeng Wang, and Junping Du. 2020. Leveraging graph to improve abstractive multi-document summariza- In Proceedings of the 58th Annual Meeting tion. of the Association for Computational Linguistics, pages 6232–6243, Online. Association for Compu- tational Linguistics. Kexin Liao, Logan Lebanoff, and Fei Liu. 2018. Ab- stract Meaning Representation for multi-document In Proceedings of the 27th Inter- summarization. national Conference on Computational Linguistics, pages 1178–1190, Santa Fe, New Mexico, USA. As- sociation for Computational Linguistics. Chin-Yew Lin. 2004. ROUGE: A package for auto- matic evaluation of summaries. In Text Summariza- tion Branches Out, pages 74–81, Barcelona, Spain. Association for Computational Linguistics. Peter J. Liu*, Mohammad Saleh*, Etienne Pot, Ben Goodrich, Ryan Sepassi, Lukasz Kaiser, and Noam Shazeer. 2018. Generating wikipedia by summariz- ing long sequences. In International Conference on Learning Representations. Yang Liu and Mirella Lapata. 2019a. Hierarchical transformers for multi-document summarization. In the Proceedings of Association for Computational Linguistics, pages 5070–5081, Florence, Italy. Association for Compu- tational Linguistics. Yang Liu and Mirella Lapata. 2019b. Text summariza- In Proceedings of tion with pretrained encoders. the 2019 Conference on Empirical Methods in Nat- ural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 3730–3740, Hong Kong, China. Association for Computational Linguistics. Yao Lu, Yue Dong, and Laurent Charlin. 2020. Multi- XScience: A large-scale dataset for extreme multi- document summarization of scientific articles. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 8068–8074, Online. Association for Computa- tional Linguistics. Yuning Mao, Yanru Qu, Yiqing Xie, Xiang Ren, and Jiawei Han. 2020. Multi-document summarization with maximal marginal relevance-guided reinforce- In Proceedings of the 2020 Con- ment learning. ference on Empirical Methods in Natural Language Processing (EMNLP), pages 1737–1751, Online. As- sociation for Computational Linguistics. Ani Nenkova and Rebecca Passonneau. 2004. Evaluat- ing content selection in summarization: The pyra- In Proceedings of the Human Lan- mid method. guage Technology Conference of the North Ameri- can Chapter of the Association for Computational Linguistics: HLT-NAACL 2004, pages 145–152, Boston, Massachusetts, USA. Association for Com- putational Linguistics. Ramakanth Pasunuru, Mengwen Liu, Mohit Bansal, Sujith Ravi, and Markus Dreyer. 2021. Efficiently summarizing text and graph encodings of multi- document clusters. In Proceedings of the 2021 Con- ference of the North American Chapter of the Asso- ciation for Computational Linguistics: Human Lan- guage Technologies, pages 4768–4779, Online. As- sociation for Computational Linguistics. Colin Raffel, Noam Shazeer, Adam Roberts, Kather- ine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. 2020. Exploring the limits of transfer learning with a unified text-to- text transformer. Journal of Machine Learning Re- search, 21(140):1–67. Sascha Rothe, Joshua Maynez, and Shashi Narayan. 2021. A thorough evaluation of task-specific pre- In Proceedings of the training for summarization. 2021 Conference on Empirical Methods in Natural Language Processing, pages 140–145, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. Andy Su, Difei Su, John M Mulvey, and H Vincent Poor. 2021. Pobrl: Optimizing multi-document sum- marization by blending reinforcement learning poli- cies. arXiv preprint arXiv:2105.08244. Chien-Sheng Wu, Linqing Liu, Wenhao Liu, Pontus Stenetorp, and Caiming Xiong. 2021. Controllable abstractive dialogue summarization with sketch su- pervision. In Findings of the Association for Com- putational Linguistics: ACL-IJCNLP 2021, pages 5108–5122, Online. Association for Computational Linguistics. Michihiro Yasunaga, Rui Zhang, Kshitijh Meelu, Ayush Pareek, Krishnan Srinivasan, and Dragomir Radev. 2017. Graph-based neural multi-document summarization. In Proceedings of the 21st Confer- ence on Computational Natural Language Learning (CoNLL 2017), pages 452–462, Vancouver, Canada. Association for Computational Linguistics. Manzil Zaheer, Guru Guruganesh, Kumar Avinava Dubey, Joshua Ainslie, Chris Alberti, Santiago On- tanon, Philip Pham, Anirudh Ravula, Qifan Wang, Li Yang, and Amr Ahmed. 2020. Big bird: Trans- In Advances in formers for longer sequences. Neural Information Processing Systems, volume 33, pages 17283–17297. Curran Associates, Inc. Jingqing Zhang, Yao Zhao, Mohammad Saleh, and Peter Liu. 2020. PEGASUS: Pre-training with ex- tracted gap-sentences for abstractive summarization. In Proceedings of the 37th International Conference on Machine Learning, volume 119 of Proceedings of Machine Learning Research, pages 11328–11339. PMLR. Chenguang Zhu, Ziyi Yang, Robert Gmyr, Michael Zeng, and Xuedong Huang. 2021. Leveraging Lead Bias for Zero-Shot Abstractive News Summarization, page 1462–1471. Association for Computing Ma- chinery, New York, NY, USA. Yanyan Zou, Xingxing Zhang, Wei Lu, Furu Wei, and Ming Zhou. 2020. Pre-training for abstractive doc- ument summarization by reinstating source text. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 3646–3660, Online. Association for Computa- tional Linguistics. # A Implementation details of pre-training As summarization task has a higher compression ratio, defined as len(Summary)/len(Input), 12% for Multi-News dataset and 15% for Multi-Xscience dataset), we use 15% as the ratio of masked sen- tences for generation. In addition to this 15% masked sentences, following PEGASUS (Zhang et al., 2020), we also copy an additional 15% of the input sentences to the output without masking them in the input. This allows the model to also learn to copy information from the source directly and found to be useful by Zhang et al. (2020). We pretrain the model for 100K steps, with early stopping, batch size of 16, Adam optimizer with a learning rate of 3e−5 following Beltagy et al. (2020), with 10K warmup steps and linear decay. The pretraining process takes likely 7 days on 4 A100 GPUs. As the backbone of PRIMERA is the Longformer Encoder Decoder model (LED), it has the same number of parameters with LED (447M). # B Detailed Description on the Evaluation Datasets The details of evaluation datasets can be found below. Multi-News (Fabbri et al., 2019): A multi- document dataset with summaries written by pro- fessional editors from the newser.com. Wikisum (Liu* et al., 2018) Each summary is a Wikipedia article, and the source documents are either citations in the reference section or the Web Search results of section titles.14 In our experi- ments, we use the data crawled by Liu and Lapata (2019a). WCEP (Gholipour Ghalandari et al., 2020) is built based on news events from Wikipedia Current Events Portal and the references are obtained simi- lar to Wikisum. There are at most 100 documents within each cluster in the original dataset, thus we 14Due to the large size of the dataset, we evaluate all the models on the first 3200 data in the test set. And in the few- shot experiments, we randomly choose few examples (10 or 100) from the training set and validation set. remove all the duplicates and only keep up to 10 documents for each cluster based on the relevance score in the original dataset, which is similar to the WCEP-10 variant in the original paper. Multi-X-Science (Lu et al., 2020) a multi- document summarization dataset created from sci- entific articles, the summaries are paragraphs of related work section, while source documents in- clude the abstracts of the query and referred papers. DUC benchmarks (Dang, 2005) include multi- document summarization datasets in the news domain, with 10-30 documents and 3-4 human- written summaries per cluster. Since these datasets are small, we use them primarily for a few-shot evaluation. We use DUC2003 for training (only one of the reference summaries for each document is used for training) and DUC2004 as test. ArXiv (Cohan et al., 2018) is a single document summarization dataset in the scientific paper do- main. Each document is a scientific paper, and the summary is the corresponding abstract. As each scientific paper consists of multiple sections, we treat each section as a separate document within a cluster in our experiments. This is to evaluate our model’s effectiveness on summarizing single documents having multiple sections. # C Details on Compared models The details of compared models in the zero-/few- shot setting can be found below. BART (Lewis et al., 2020) an encoder-decoder transformer model pretrained on the objective of reconstructing the corrupted documents in multiple ways, e.g. Token Deletion, Text Infilling, Sentence Rotation and etc. PEGASUS (Zhang et al., 2020) a pretrained model designed for abstractive summarization as the downstream task, especially for the single doc- ument input. It is trained on the objective of Gap Sentence Generation on C4 (Raffel et al., 2020) and Hugenews datasets (Note that the pretraining data size in PEGASUS is magnitudes larger than ours). As it is only evaluated on one multi-document summarization dataset (Multi-news), we rerun the model on all the datasets. To verify the quality of our reproduction, the average ROUGE scores of our re-run model vs. (the ones reported on the paper) with 10 examples and 100 examples fed are 23.81 ± 0.79 vs. (24.13) and 25.86 ± 0.41 vs. (25.48), with minor differences plausibly resulting from different samplings. Length Limit BART PEGASUS R-1 R-2 R-L R-1 R-2 R-L 512 1024 4096 - 39.0 12.1 20.3 42.3 13.7 19.7 37.6 10.7 18.8 8.7 17.6 37.9 11.0 17.5 34.9 - - Table 6: The ROUGE score (R-1/R-2/R-3) for pre- trained models (BART and PEGASUS) with different input length limit in few-shot setting (10 data example) on the multi-news dataset. The results are the average over 5 runs on different subsets (the same seeds shared with all the other models in this paper). Longformer Encoder-Decoder (LED) (Beltagy et al., 2020) is the initial state of our model before pretraining. The parameters of LED are inherited from the BART model, and to enable the model to deal with longer input, the position embeddings are repeatedly copied from BART’s 1K position embeddings. It is different from our model with re- spect to both pretraining and input structure (docu- ment separators and global attentions), with global attention on the (<s>) token only and no document separators. # C.1 Detailed Experiment for Input Length Limit We run an experiment to select the proper length limit for compared pretrained models, i.e. BART and PEGASUS. Specifically, we train both models with different input length limits (512/1024/4096) in the few-shot setting (with 10 data examples) on the multi-news dataset. Similar as the few-shot experiments described in §4.2, we train each model with each specific input length limit for 5 times on different subsets, which are shared by all the models. As shown in Table 6, BART with length limit 1024 performs the best and PEGASUS with length limit 512 performs the best, thus in all our experiments, we use 1024 as the input length limit for BART and 512 for PEGASUS. # D Hyperparameters in Few-shot and Full Supervised Experiments # D.1 Few-shot Experiments We use Adam as the optimizer with linear sched- uled learning rate 3e − 5 for BART, LED and our model, and use the default optimization settings of the few-shot experiments from Zhang et al. (2020), i.e. AdaFactor optimizer with scheduled learning rate 5e − 4. For all the experiments with 10 exam- ples, the batch size is 10, the models are trained for 200 steps, with warm-up as 20 steps. For the experiments with 100 examples, we use the same batch size, with the total step and warm-up step set to be 1000 and 100, respectively. # D.2 Fully Supervised Experiments We use Adam as the optimizer with linear sched- uled learning rate 3e − 5, and batch size as 16 for all the datasets in the full supervised experiments. The number of steps and warm-up steps are set based on the size of the datasets. The details can be found in Table 7 Dataset Total Steps Warmup Steps Multi-News Multi-XScience WCEP arXiv 25k 20k 5k 40k 2.5k 2k .5k 4k Table 7: Details of total steps and warm-up steps used in the Full Supervised experiments. # E Detailed Results in Few-shot Setting The exact ROUGE scores in Figure 5 are shown in Table 8. Model 0 Examples 10 Examples 100 Examples Multi-News PEGASUS BART LED Ours 31.97/10.06/16.74 26.10/8.98/13.06 16.60/4.78/9.05 39.09/13.91/19.19 39.02/12.10/20.32 42.30/13.74/19.71 38.86/12.48/18.82 44.02/15.54/22.03 42.99/13.50/21.10 44.23/14.77/21.02 44.45/14.85/21.16 46.01/16.76/22.91 Multi-Science PEGASUS BART LED Ours 27.33/4.77/15.04 15.21/3.49/8.61 11.79/2.47/6.86 26.90/4.98/14.09 28.14/4.68/15.49 27.80/4.74/14.90 26.57/4.05/15.36 28.36/4.73/15.29 28.01/4.09/15.89 31.17/5.32/16.45 29.46/4.85/16.32 31.25/5.43/16.84 Wikisum PEGASUS BART LED Ours PEGASUS BART LED Ours PEGASUS BART LED Ours 23.67/5.37/14.17 15.80/4.60/9.13 8.70/2.34/5.78 17.79/5.02/10.90 27.69/10.85/20.03 7.11/3.41/5.32 5.69/2.19/4.32 13.50/5.30/10.11 29.76/7.94/17.27 23.26/7.57/12.01 13.94/3.76/8.35 29.14/8.64/15.82 23.44/6.44/16.21 28.95/9.88/20.80 26.53/9.30/19.95 31.10/13.26/23.39 WCEP 35.60/14.84/26.84 37.46/15.82/28.70 36.29/15.04/27.80 38.97/17.55/30.64 arXiv 33.10/8.52/19.40 32.53/8.70/17.98 36.51/11.16/20.68 41.13/13.81/23.02 28.50/9.83/21.33 32.97/13.81/25.01 34.15/16.03/26.75 36.05/17.85/27.81 42.09/19.93/33.04 41.34/19.19/32.58 41.83/19.46/32.92 42.96/20.53/33.87 36.38/9.55/20.83 37.62/10.78/20.99 41.00/13.74/22.34 43.42/15.85/24.07 Table 8: Detailed ROUGE scores (R-1/R-2/R-L) on all the datasets in the few-shot setting (corresponds to Fig- ure 5) # F Detailed Analysis on Fully Supervised Experiments To show the advantage of our pre-trained model when there is sufficient data, we also train the model with the full training set, and the results can be found in Table 9-1215, along with the re- sults from previous works. Differently from the zero-/few-shot experiments, here we report the state-of-the-art results on different datasets, as they were presented in the corresponding original pa- pers. Since we use the same train/valid/test set as in those prior works, we can perform a fair com- parison , without re-running all those extremely time-consuming experiments . Overall, our model achieves state-of-the-art on Multi-News (see Table 9 , WCEP dataset (see Ta- ble 11) and arXiv dataset (see Table 12). Models PEGASUS (Zhang et al., 2020) BART-Long-Graph (Pasunuru et al., 2021) BART-Long-Graph(1000) (Pasunuru et al., 2021) BART-Long(1000) (Pasunuru et al., 2021) Ours ROUGE-1 ROUGE-2 ROUGE-L 18.72 19.04 18.99 19.50 21.05 47.52 49.03 49.24 49.15 49.94 24.91 24.04 23.97 24.47 25.85 Table 9: ROUGE scores of the previous models and our fully supervised model on the Multi-News dataset. The results of PEGASUS is from Zhang et al. (2020), and the other results are from Pasunuru et al. (2021) Multi-News The experiment results on Multi- News dataset can be found in Table 9. Specifically, the PEGASUS model (Zhang et al., 2020) is pre- trained on a large-scale single-document dataset with the Gap Sentence Generation objective, which is the same as ours, but with a different mask- ing strategy, BART-Long (Pasunuru et al., 2021) uses the same model structure as ours , and BART- Long-Graph (Pasunuru et al., 2021) additionally has discourse graph injected. Comparing the re- sults with the BART-Long model, our model is around 1 ROUGE point higher, which may result from either better model structure or pre-training. Interestingly, in one of the ablation studies in Pa- sunuru et al. (2021), they find that the BART-Long model achieves its best performance with the length limit of 1000, and no further improvement is found when the length limit is greater than that. Thus we may conclude the gap between the performances is mainly from our design on the model, i.e. the doc- ument separators, proper global attention as well as the pre-training on a multi-document dataset. 15Due to the lack of computational resources, we do not train the model on Wikisum. Models R1 R2 RL* LEAD BERTABS BART SCIBERTABS SOTA(Pointer Generator) LEAD(ours) Ours 27.46 31.56 32.83 32.12 34.11 26.49 31.93 4.57 5.02 6.36 5.59 6.76 4.26 7.37 - - - - 18.2 14.70 18.02 Table 10: ROUGE scores of the previous models and our fully supervised model on the Multi-Xscience dataset. All the results are from Lu et al. (2020). * The ROUGE-L is not comparable as we have different set- tings on the settings of evaluation, see the gap between LEAD and LEAD(ours). Models R1 R2 RL BERTREG (Gholipour Ghalandari et al., 2020) 35.0 13.5 25.5 SUBMODULAR+ABS(Gholipour Ghalandari et al., 2020) 30.6 10.1 21.4 35.4 15.1 25.6 DynE (Hokamp et al., 2020) 46.08 25.21 37.86 Ours Table 11: ROUGE scores of the previous models and our fully supervised model on the WCEP dataset. WCEP As for the WCEP dataset, BERTREG (Gholipour Ghalandari et al., 2020) is a Regression- based sentence ranking system with BERT em- bedding, which is used as extractive summariza- tion method, while Submodular+Abs is a simple two-step abstractive summarization model with a submodular-based extractive summarizer followed by a bottom-up abstractive summarizer (Gehrmann et al., 2018). DynE is a BART-based abstractive approach, which is to ensemble multiple input, al- lowing single document summarization models to be directly leveraged on the multi-document sum- marization task. Our model outperforms all the models by a large margin, including the SOTA model DynE, and it may indicate that the plain structure is more effective than purely ensembling the output of single documents. arXiv In addition to the experiments on multi- document summarization datasets, we also com- pare our fully supervised model with previous works on the arXiv dataset, with each section treated as a single document. All the models to be compared with are based on pre-trained mod- els, and Bigbird-PEGASUS and LED utilize the pre-training of PEGASUS (Zaheer et al., 2020) and BART (Lewis et al., 2020), respectively. However, both Bigbird and LED apply more efficient atten- tions, which make the models able to take longer Models R1 R2 RL PEGASUS (1K) Bigbird-PEGASUS (3k) LED(4K) LED(16K) Ours(4k) 44.21 46.63 44.40 46.63 47.58 16.95 19.02 17.94 19.62 20.75 38.83 41.77 39.76 41.83 42.57 Table 12: ROUGE scores of the previous models and our fully supervised model on the arXiv dataset. The re- sult of PEGASUS and BigBird-PEGASUS are from (Za- heer et al., 2020), and the results of LED are from (Belt- agy et al., 2020). The number in the parenthesis indi- cates the length limit of the input. input (3k for BigBird, 4K and 16k for LED). Our model has a better performance than all the models, including LED(16K), which allows for the input 4 times longer than ours. It is worth mentioning that LED(4K) has the same structure as our model, with the same length limit of the input, and with the pre-training on multi-document datasets, our model is more than 3 ROUGE point better than it, which shows that the strategy not only works for multi-document summarization but can also effec- tively improve single-document summarization for long documents. # G Examples of Generated Summaries We show an example (from Multi-News) of gener- ated summaries by PRIMERA and compared mod- els trained with different number of examples in Table 13. And we show an example from DUC2007 (which is one of the examples used for human eval- uation) with generated summaries by PRIMERA and two compared models in Table 14, with all the models trained on 10 data examples from DUC2007. # H Software and Licenses Our code is licensed under Apache License 2.0. Our framework dependencies are: HuggingFace Datasets16, Apache 2.0 • NLTK 17, Apache 2.0 • Numpy18, BSD 3-Clause "New" or "Revised" • Spacy19, MIT 16https://github.com/huggingface/ datasets/blob/master/LICENSE # 17https://github.com/nltk/nltk 18https://github.com/numpy/numpy/blob/ main/LICENSE.txt 19https://github.com/explosion/spaCy/ Transformers20, Apache 2.0 • Pytorch21, Misc • Pytorch Lightning 22,Apache 2.0 • Longformer23, Apache 2.0 • ROUGE 24, Apache 2.0 # I Annotation Instructions for Human Evaluation Figure 7 and Figure 8 shows the annotation instruc- tion for human annotators. # blob/master/LICENSE # 20https://github.com/huggingface/ # transformers/blob/master/LICENSE 21https://github.com/pytorch/pytorch/ blob/master/LICENSE # 22https://github.com/PyTorchLightning/ # pytorch-lightning/blob/master/LICENSE # 23https://github.com/allenai/ longformer/blob/master/LICENSE 24https://github.com/google-research/ google-research/tree/master/rouge Instruction on Human Annotations Overview: 1- Content quality The goal of this evaluation is to assess the content quality of a system generated summary based on human-written reference summaries. We will be using the Pyramid evaluation framework (Nenokva and Passonneau, 2004): https://aclanthology.org/N04-1019. The evaluation works like this. There are 3 things provided for each evaluation example: 1- The original documents 2- System generated summaries 3- A set of "information nuggets" or "facts" in the human-reference summaries. These are pre-annotated in the dataset and are atomic short phrases that refer to a specific piece of information in the documents. For example "Britain opted out of Euro system." is an information nugget. For annotation, we will simply go through the list of information nuggets and check if they appear in the system generated summary. A summary is considered good if it includes many of the information nuggets. 1. Documents (40 examples in total) a. Information nuggets: https://docs.google.com/spreadsheets/d/1BRbv-aaVpNDWTKOhQBGYABYzhK WAhk6cGnD5ROlyquY/edit?usp=sharing b. Three summaries, A, B and C: See below 2. Annotations: a. For each summary, check all the information in the information checklist in the following way, i. If the information is covered in the summary, check the corresponding checkbox ii. | Otherwise, leave it blank. 2- Fluency: There are multiple candidate summaries (3) for each system and we would like to rank the summaries from most most fluent to least. Specifically, for each summary, answer the following questions: Figure 7: Annotation instruction for human annotators. 1. Grammaticality - The summary should have no datelines, system-internal formatting, capitalization errors or obviously ungrammatical sentences (e.g., fragments, missing components) that make the text difficult to read. 5. Very Good 4. Good 3. Barely Acceptable 2. Poor 1. Very Poor 2. Referential clarity - It should be easy to identify who or what the pronouns and noun phrases in the summary are referring to. If a person or other entity is mentioned, it should be clear what their role in the story is. So, a reference would be unclear if an entity is referenced but its identity or relation to the story remains unclear. 5. Very Good 4. Good 3. Barely Acceptable 2. Poor 1. Very Poor 3. Structure and Coherence - The summary should be well-structured and well-organized. The summary should not just be a heap of related information, but should build from sentence to sentence to a coherent body of information about a topic. 5. Very Good 4. Good 3. Barely Acceptable 2. Poor 1. Very Poor When assigning scores to each summary, please assign the scores relative to other summaries for that document set. Figure 8: Annotation instruction for human annotators. Model Summaries PRIMERA-0 BALTIMORE (AP) — The U.S. Coast Guard says it’s looking for a man who has cost the service about $500,000 after responding to nearly 30 of his fake distress calls.. The Coast Guard also said such false distress alerts detract from their ability to respond to actual alerts.Anyone with information about the caller is asked to contact the Coast Guard’s regional command center at 410-576- 2525 or email investigators at CGIS-Baltimore@uscg.mil.. PRIMERA-10 The U.S. Coast Guard says it’s looking for a man who has cost the service about $500,000 after responding to nearly 30 of his fake distress calls. In a press release published Friday, the Coast Guard says the 28 calls have originated from around the area of Annapolis, Maryland. Each call involved the same male voice and used an emergency radio channel. The two most recent calls were made on the night of July 21 and the early morning of July 22. The Coast Guard also says hoax calls distract rescuers from real emergencies, putting both the public and the responding crews at risk. "Calls like these not only put our crews at risk, but they put the lives of the public at risk," said Lt. Cmdr. Sara Wallace, who heads the response sector in Maryland. "Calls like these not only put our crews at risk, but they put the lives of the public at risk." Anyone with information about the caller is asked to contact the Coast Guard’s regional command center at 410-576-2525 or email investigators at CGIS-Baltimore@uscg.mil. PRIMERA-100 The US Coast Guard is looking for a man who has cost the service about $500,000 after making 28 false distress calls from Maryland. The 28 calls have involved the same male voice and used an emergency radio channel, the AP reports. The Coast Guard says it has responded to nearly 30 of the fake calls and that the estimated cost of the responses is $500,000. The caller has been making the calls since July 2014. He could be facing a six-year prison sentence, a $10,000 civil fine, and a $250,000 criminal fine, the AP reports. "A hoax call is a deadly and serious offense," says Lt. Cmdr. Sara Wallace, head of the response sector in Maryland. "Calls like these not only put our crews at risk, but they put the lives of the public at risk." PEGASUS-100 The US Coast Guard has responded to 28 false distress calls in two years—and it’s a man who’s been making the calls, not the waves. The unidentified caller has made the calls in Annapolis, Maryland, since July 2014, the Coast Guard reports. Each call involved the same male voice and used an emergency radio channel. The two most recent calls were made on the night of July 21 and early morning of July 22. The Coast Guard says the calls were made in the hope that the public would get into the water. Rather than responding to actual alerts, the calls were made to divert the attention of rescue crews from real emergencies, the AP reports. The Coast Guard says the cost of the responses to these false alarms is about $500,000. The caller made 28 false distress alerts from Annapolis, Maryland, beginning in July 2014, according to the Coast Guard. The estimated cost of the responses to these false alarms is $500,000. The Coast Guard says the calls were made in the hope that the public would get into the water. Rather than responding to actual alerts, the calls were made to divert the attention of rescue crews from real emergencies, the AP reports. Fully Supervised The US Coast Guard says it’s looking for a man who has cost the service about $500,000 after responding to nearly 30 of his fake distress calls, the AP reports. In a press release published Friday, the Coast Guard says the 28 calls have originated from around the area of Annapolis, Maryland. Each call involved the same male voice and used an emergency radio channel. The two most recent calls were made on the night of July 21 and the early morning of July 22. The Coast Guard also says hoax calls distract rescuers from real emergencies, putting both the public and the responding crews at risk. "A hoax call is a deadly and serious offense," says Lt. Cmdr. Sara Wallace, who heads the response sector in Maryland. "Calls like these not only put our crews at risk, but they put the lives of the public at risk." Making false distress calls is a felony, punishable by a maximum of six years in prison, a $10,000 civil fine, $250,000 criminal fine, and a reimbursement to the Coast Guard for their efforts, the Coast Guard says. Ground Truth Table 13: Generated summaries from PRIMERA and best baseline model (according ROUGE score on this example) trained with different number of training examples. The data used here is the #10 in the test set of Multi-News dataset on Huggingface. Model Summaries PEGASUS In 1996, Congress passed the Line-Item Veto Act, which gave the president the power to cut individual projects from tax and spending bills without vetoing the entire legislation. The act was followed by the President’s line-item veto, which he used to trim 144 million dollars from a 248 billion dollars defense spending bill. He also used the veto power to block a congressional rejection of his line-item veto on 38 military construction projects. The bill was passed by the House and the President signed it into law. The veto was challenged by members of both parties who said it was unconstitutional because it gave the president unchecked power to rewrite legislation. The Supreme Court agreed on Friday to hear argument and decide the constitutionality of the president line-item veto. In 1998 the President used his line-item veto to cut $38 million from a military construction bill. In 1999 the President used his line-item veto to cut $54 million from a military spending bill. In 2000 the President used his line-item veto to cut $54 million from a defense spending bill. In January the President vetoed a tax and spending bill, which gave him the power to cut individual projects from tax and spending bills without vetoing the entire legislation. In February the President vetoed a spending bill, which gave him the power to cut individual projects from tax and spending bills without vetoing the entire legislation. In September the President used his line-item veto to cut $54 million from a defense spending bill. The bill was rejected by the House and the President vetoed it. In November the President used his line-item veto to trim 144 million dollars from a defense spending bill. LED In 1996, the Republican-led Congress passed the Line Item Veto Act, giving the president the power to delete individual items of spending and tax bills. Clinton used the power to cut individual projects from tax and spending bills. In February 1999, the President Clinton vetoed a congressional rejection of his line-item veto on 38 military construction projects. In May 1999, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In 2000, the President Clinton used the line-item veto to cancel individual items of spending and tax breaks. In May 2000, the President Clinton threatened to use the line-item veto to cancel all military spending and tax breaks. In June 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In August 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In September 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In 2001, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In June 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In August 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In September 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In 2000, the President Clinton used the line-item veto to cancel individual items of spending and tax breaks. In 2001, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. In June 2000, the President Clinton used the line-item veto to cut individual items of spending and tax breaks. PRIMERA In 1996, Congress gave the President the power to veto specific items of tax and spending bills. Before the law’s enactment in 1996, the president could veto an entire spending measure but not individual items. The court ruled that such a specialized veto can be authorized only through a constitutional amendment. In January 1997, the line-item veto law was passed. It was passed under the Republican Party’s "Contract with Congress". It was passed after President Clinton vetoed thirteen relatively obscure research and spending programs, almost all of the military spending increases approved by Congress. In October 1998, Clinton used his line-item veto authority to have trimmed 144 million U.S. dollars from a 248 billion defense spending bill. In November 1998, Clinton vetoed 38 military construction projects, worth 287 million U.S. dollars. In February 1999, the Justice Department appealed the line-item veto law to the Supreme Court, which agreed to hear argument and decide the constitutionality of the law. Earlier this month, a federal judge struck down the line-item veto law as unconstitutional. The highest court’s review will yield a momentous balance of powers ruling. The case is scheduled to be argued before the justices on April 27. The line item veto, strongly supported by President Bill Clinton and a number of his predecessors, was passed in 1996 under the Republican Party’s "Contract with Congress". It was passed in January 1997. Before the law’s enactment, the only way presidents could reject spending laws was to veto whole budget bills. In 1996, Congress gave the president the power to cancel individual items in tax and spending bills. In January 1997, the line-item veto law was passed. It was passed under the Republican Party’s "Contract with Congress". It was passed in January 1997. In 1998, President Clinton threatened to veto some items of the military construction bill because of the increased funding. In November 1998, Clinton used his line-item veto power to delete 38 projects in 24 states worth 287 million U.S. dollars. In February 1999, the Justice Department appealed the line-item veto law to the Supreme Court, which agreed to hear a case about its constitutionality. Ground Truth In 1996 a Republican congress overwhelmingly passed a Line Item Veto Act allowing presidents (including the incumbent Demo- cratic president), to strike individual tax or spending items within 5 days after signing a bill into law. Congress could restore those items in a new bill passed by majority vote. If the president vetoed that bill, Congress could override that veto with a two-thirds majority. Proponents argued that the law preserved the integrity of federal spending, saved billions of dollars, and that it did not repeal any portion of a law, but was simply a delegated spending authorization from Congress. In January 1997, the first year of the law, the president vetoed 163 line-items in six bills, and in 1998 82 line-items in 11 bills. In October 1997 Congress overrode the president’s line-item veto against 36 of 38 military construction projects. Initial 1997 efforts by congressmen to challenge the law in the Supreme Court were rejected due to lack of standing. On June 25, 1998 after lower courts rejected the Line Item Veto Act as unconstitutional, on appeal by the White House the Supreme Court ruled 6-3 that Congress unconstitutionally violated the principle of separation of powers, because that procedure allows the president to create a law that was not voted on by either house of Congress in violation of the Constitution’s Article I "presentment" clause. A constitutional amendment would be required to institute line item vetoes. Justices Breyer and Scalia argued similar dissenting opinions that separation of powers was not violated. Table 14: Generated summaries from PRIMERA, PEGASUS and LED trained with 10 training examples, along with one (out of four) ground-truth summary. The data used here is D0730 in DUC2007.
Title: PRD: Peer Rank and Discussion Improve Large Language Model based Evaluations: Summary: Nowadays, the quality of responses generated by different modern large language models (LLMs) are hard to evaluate and compare automatically. Recent studies suggest and predominantly use LLMs as a reference-free metric for open-ended question answering. More specifically, they use the recognized "strongest" LLM as the evaluator, which conducts pairwise comparisons of candidate models' answers and provides a ranking score. However, this intuitive method has multiple problems, such as bringing in self-enhancement (favoring its own answers) and positional bias. We draw insights and lessons from the educational domain (Cho and MacArthur, 2011; Walsh, 2014) to improve LLM-based evaluations. Specifically, we propose the (1) peer rank (PR) algorithm that takes into account each peer LLM's pairwise preferences of all answer pairs, and outputs a final ranking of models; and (2) peer discussion (PD), where we prompt two LLMs to discuss and try to reach a mutual agreement on preferences of two answers. We conduct experiments on two benchmark datasets. We find that our approaches achieve higher accuracy and align better with human judgments, respectively. Interestingly, PR can induce a relatively accurate self-ranking of models under the anonymous setting, where each model's name is unrevealed. Our work provides space to explore evaluating models that are hard to compare for humans. # PRD: Peer Rank and Discussion Improve Large Language Model based Evaluations Teerth Patel† Department of Computer Science The University of Texas at Dallas {ruosen.li, teerth.patel, xinya.du}@utdallas.edu # Abstract Nowadays, the quality of responses generated by different modern large language models (LLMs) are hard to evaluate and compare auto- matically. Recent studies suggest and predomi- nantly use LLMs as a reference-free metric for open-ended question answering. More specif- ically, they use the recognized “strongest” LLM as the evaluator, which conducts pair- wise comparisons of candidate models’ an- swers and provides a ranking score. How- ever, this intuitive method has multiple prob- lems, such as bringing in self-enhancement (fa- voring its own answers) and positional bias. We draw insights and lessons from the edu- cational domain (Cho and MacArthur, 2011; Walsh, 2014) to improve LLM-based evalua- tions. Specifically, we propose the (1) peer rank (PR) algorithm that takes into account each peer LLM’s pairwise preferences of all answer pairs, and outputs a final ranking of models; and (2) peer discussion (PD), where we prompt two LLMs to discuss and try to reach a mutual agreement on preferences of two answers. We conduct experiments on two benchmark datasets. We find that our ap- proaches achieve higher accuracy and align better with human judgments, respectively. In- terestingly, PR can induce a relatively accu- rate self-ranking of models under the anony- mous setting, where each model’s name is un- revealed. Our work provides space to explore evaluating models that are hard to compare for humans.1 # Introduction With a rising number of large language models (LLMs) being developed ever more quickly re- †Contribution distributed as follows. Xinya decided the project scope, research questions and proposed the initial ver- sion of methodolgies. Ruosen and Xinya designed the exper- iments. Ruosen and Teerth conducted experiments, analysis and data collection. All authors contributed to paper writing. 1We release all human/machine annotated pairwise com- parisons, generated answers, generated discussions, and imple- mentations at https://bcdnlp.github.io/PR_LLM_EVAL/. cently, evaluations become increasingly important as they encode values and priorities that the LLM community should improve upon (Jones and Gal- liers, 1995; Liang et al., 2022). At the same time, the evaluation becomes harder as well. For exam- ple, recent models finetuned with human feedback (RLHF) align with human preference more, but this capability usually cannot be reflected by de- cent performance on standard NLP benchmarks (e.g. MMLU (Hendrycks et al., 2020), ARC (Clark et al., 2018)). Furthermore, human queries span a diverse range of settings and scenarios that it is nearly impossible to list them all. To tackle this discrepancy, open-ended questions are being used more often to test LLMs perfor- mance (Chiang et al., 2023). Then by default, evaluation is done by collecting human prefer- ences of pairwise comparisons and then calculating scores for each LLM to induce a general ranking. While the collection process is costly and time- consuming (Zheng et al., 2023), to automate and scale up the evaluation, most recent works utilize the strongest (a.k.a state-of-the-art) LLM as the judge (Dubois et al., 2023; Dettmers et al., 2023). However, various studies show that this method is problematic, as the pairwise comparison judgment provided usually contains various biases such as self-enhancement, bias towards long and verbose answers, and bias towards the first answer in a pair. Motivated by these limitations, we propose peer evaluation. The goal is to mitigate the biases in automated evaluations while still benefiting from LLM’s strong capability in reading and writing reviews. We propose Peer Rank and Discussion- based evaluation framework (PRD). The suit con- sists of two alternatives that share the same for- mat and goal – involving peer LLMs’ participa- tion as reviewers, to reach a more fair evaluation result where all peers mutually agree. We draw insights and lessons from educational psychology research, on methodologies of student peer review- Reviewers A | 2 i— 2 \ + Wa 6-4, 3 . Wi Pairwise Battles Contestants Win Rate Matrix x dot product. more score higher Score; Ll mmm | SCOPED Score3 A Normalize J Reviewer (Multi-round)Contestent Weight Vector Score Vector Figure 1: The peer rank process (PR), where each model acts both as reviewers (A, B, C) and contestants (1, 2, 3). From the battles between contestants (pairwise comparisons), it induces a self-ranking. In this example, models A, B, C represent GPT-4, Bard, and Claude, respectively. ing (Walsh, 2014), as well as their impact and bene- fits (Cho and MacArthur, 2011; Yalch et al., 2019). More specifically, peer rank (PR) works for the tournament-style benchmarking setting where each LLM in pairwise matches produces an answer for an open-ended question. Instead of getting the av- erage/majority vote to decide the final preference scoring, we propose to apply higher weights to LLMs reviewers with stronger capabilities (Sec- tion 2.1). Peer discussion (PD) works for the general pairwise comparison setting. Given two “student” LLM’s answers, we prompt two other reviewer LLMs to have multi-turn discussions to reach a mutual agreement on the pairwise scoring. The process shares a similar format of LLM inter- acting with each other through conversations like two communicative agents (Li et al., 2023; Park et al., 2023; Fu et al., 2023b). reviews. After, we provide analysis for discussions, including prompting strategies’ effects on multi- turn peer discussions; what the discussion bias is; and the phenomenon of opinion-altering. Analy- sis of discussion bias shows that the model which leads discussions is less likely to alter its opinion. The opinion-altering analysis supports the previous analysis and describes that models’ overall ability is highly aligned with whether they can hold their opinions. # 2 Methodologies In general, peer rank can be applied to induce self- rank, e.g. to create a leaderboard of LLMs’ capa- bilities, while peer discussion provides more bene- fits in comparing the capabilities of two models (a more fine-grained and interactive comparison). We elaborate on their technical details in this section. We conduct extensive experiments and analysis for testing PR and PD’s performance by provid- ing fair pairwise comparisons. PR is tested on Vi- cuna80, which contains pairwise judgments from human annotators. Our method improves corre- lations with human judgments and ranking sub- stantially, this paradigm also enables a group of LLMs to induce a self-ranking. PD is tested on both Vicuna80 and LFQA (Xu et al., 2023), which in- cludes annotated pairwise comparisons of Human- Machine and Machine-Machine answers. PD en- ables LLMs to achieve better pairwise comparisons that are more accurate than single model-based reviews, especially in improving weaker model’s # 2.1 Peer Rank and Scoring We provide an illustration of the peer rank algo- rithm in Figure 1. The general idea is to obtain weighted scores of each battle from the peer re- viewer’s judgment, then induce self-rankings from the scores. This process is iterated multiple times until the scores converge. Given a set of questions, Q, we generate an an- swer to each question for each language model. Let Am(q) be the answer generated to question q ∈ Q by model m. We then generate pairwise compar- isons between answers to the same question, using the language models themselves along with human annotators to compare answers. Using these automated and human pairwise com- parisons, we create a tournament among models, with each battle representing two models (the con- testants) competing to answer a question as best they can. The comparison of the answers in a battle by another model (the reviewer) forms a review. Let Kr(x, y) be the score given by the reviewer r to the pair of answers (x, y). We use a score of −1 to indicate the first answer is better, 0 to indicate a tie, and 1 to indicate the second answer is better. The score given by a model may be dependent on the order of answers provided. Suppose we have a set of reviewer models R and a set of contestant models C. We form a set of battle reviews, B = {(q, i, j, r, s) | q ∈ Q, (i, j) ∈ C2, r ∈ R} where s = Kr(Ai(q), Aj(q)) is the score given by reviewer r to the answers/responses generated by i and j for question q. We create a shorthand Kij r (q) for this review. Based on these peer reviews, we can evaluate models based on their performance, by calculating metrics such as the win rate of each contestant, and the Elo ratings of each contestant. Since each model is being ranked by its peers, we call this Peer Rank. # 2.1.1 Win rate Calculation The win rate for a contestant is the ratio of wins for that contestant divided by the number of battles it participates in. Ties are counted as 0.5 wins for both contestants. Our win rate calculation gives differing weight to the scores provided by different reviewers (A, B, C) based on the performance of the corresponding reviewers as a contestant (1, 2, 3). This operates on the assumption that models which are better con- testants are also more fit to evaluate and compare answers, so they should be given more weight in evaluation (Equation 2). In another way, since the score is a measure of their ability to review/grade correctly, we weigh the win rate an LLM gives an- other LLM by their own score (Walsh, 2014). Initially, all reviewers are given the same weight. On each iteration of the calculation, the win rate for each contestant is calculated using the current weights. The win rates are scaled to the range of [0, 1] using a linear scaling, and then again scaled so that their sum is 1, and these results are used as the weights for the next round. r be the raw win rate of contes- tant c ∈ C from the reviews of reviewer r ∈ R. This is equal to the number of times that c wins a battle plus half of the number of times that c ties, divided by the number of battles that c participates in. YY [rer@) + r-Ke"@)| q deC.d#e 2|Q|(|C| — 1) we q) where f (score) = score+1 2 maps a score of (loss = −1, tie = 0, win = 1) for the second contestant to a win count of (0, 0.5, 1), so that ties count as half of a win. r (q) when inputting it into f so that the win value of c is computed in- stead of d. Also, since there are |Q| questions, |C − 1| contestants to battle, and 2 orders for two contestants to battle, there are 2|Q||C − 1| battles involving a fixed contestant c. Let a* be the weight assigned to reviewer r af- ter iteration k. Initially, a2 = 1/|R|, so that all reviewers have the same weight, and the weights add to 1. — We assume each reviewer LLM has the same capabilities to start. The score of contestant c € C for iteration k is the weighted average of the raw win rates for contestant c. We set the weights for the next iteration to a”: scorek c = αk−1 r · W c r r∈R (2) αk = Normalize(MinMax(scorek)) where the weights are scaled to a range of [0, 1] and finally normalized to have sum equal to 1: S —min,er(S;,) MinMax(5) max;er(S;) — min-er(S;,) 6) Ss Normalize(S) = ———— Drer Sr Given this set of equations, we look for the fixed/converging point of the framework. This is reminiscent of the problem faced by the PageR- ank algorithm (Page et al., 1999). The detailed equivalent implementation of PR is shown in the Appendix Section 2. 2.1.2 Elo Calculation Another method for calculating the performance of a contestant relative to other contestants is the credit or debit card is basically just an easy way to allow a shop to speak to your bank. First you go into the bank, [...] (anne How do credit/debit cards work? What is the process of putting money in and getting it ou 1?) ebit cards are linked to a bank account and whenever you pay [...] amount is deducted[...] narrative explanation, using an analogy of [...] Answer 2 the other hand, is jore concise and uses more technical language [...] 1 Ne \ / / (initia (Answer 1 provides a more detailed an (Answer 1 provides a basic overview of) ) eview [...] at a high level. However, [...] Answer 2 provides a more coherent B planation by separately discussing how LJ 2 NN 4) Discuss answer of 1 and 2 with reviews from A and B in mind [...] again output choice on a line » After considering Reviewer B's perspective, [...] While Answer 2 [...], | believe that the accessibility and comprehensiveness of Answer 1 outweigh the concise and technical nature of Answer 2. | can appreciate Reviewer A's perspective on [...] Upon reflection, for the purposes of this question, accessibility and comprehensiveness are most important [...] after considering Reviewer A's perspective, | would change my preference to Answer 1. y Figure 2: The peer discussion process (PD). Blue and orange texts describe advantages of answer 1 and answer 2. In this example, finally the two LLM reviewers reach the mutual agreement of selecting answer 1 (human-written answer), which correlates with human reviewer preference. More discussion examples can be found in Appendix Section F. Elo rating (Elo, 1967; Askell et al., 2021). The Elo rating method takes a sequence of pairwise reviews and generates ratings for each contestant, with a greater rating indicating better performance. Based on the simlar idea, we assign different weights to reviewers based on their previous performance such that a review from a higher-weight reviewer has a greater influence upon Elo ratings. Similarly to the win rates calculation, we start with equal weights on all reviewers and then nor- malize the resulting Elo ratings to give weights for the next iteration. We repeat the Elo calculation with the new weights, update the weights based on the new ratings, and continue repeating until it converges. A brief overview of the actual Elo ratings cal- culation follows. All contestants start out with an initial rating of 1000. On each battle, the expected likelihood of each contestant winning is calculated based on the difference between their Elo ratings. The Elo rating of the winner is increased, and the rating of the loser is decreased. The magnitude of the Elo ratings change is inversely related to the outcome’s likelihood. In our calculations, we weight reviewers so that reviews by a high-weight reviewer cause larger changes in Elo. For more details, please refer to Appendix Sec- tion 2. # 2.2 Peer Discussions In Figure 2, we demonstrate the peer discussion process between two LLMs (A and B). The input is a given question and two answers, as well as the initial reviews by A and B. The two answers may be both generated by machines or one by human and another by machine (e.g. GPT-3 v.s. human answers). The two reviews are generated by LLMs (A and B), which are called reviewers/judges. They first conduct pairwise comparisons separately, pro- viding explanations and indicating their preferred answer by outputting the number 1 or 2 by the end (the prompt for getting initial reviews is listed in Appendix 10). Then, the two models have a discussion about their reviews for multiple turns (the number of turns is fixed). The specific prompt for discus- sion is listed in Table 1. At the very beginning, a system prompt (role prompt) tells models their role – whether it is reviewer A or reviewer B (e.g. Claude or GPT-4). Then, all information, includ- ing the question and two comparison answers, as well as the initial reviews, are listed line by line. The order of initial reviews is the same as the or- der of reviewers in discussions. In other words, if reviewer A leads the discussion, reviewer A’s initial review is listed first. Right before the start of the discussion, the system prompt specifies the detailed requirements which provide explicit as- pects to focus on. Specifically, we draw insights from WebGPT (Nakano et al., 2021)’s annotation guideline (OpenAI, 2022). For long-form question answering, it mainly focuses on 1. Unsupported information: detecting informa- tion with no support, assume the worst case: that all of it is false. This aspect is most impor- tant and often determines the overall rating; 2. Core information: about whether the question has actually been answered; 3. Coherence: generally, it is less important than the two above. Then the overall preference is finally determined. An alternative is to repeat the system requirement prompt after each turn. It is to ensure that the mod- els remember their role (reviewer 1 or 2) through- out the discussion history. In the Table and Figure, We omit the repeated part. # 3 Experiments # 3.1 Datasets We select two “meta-evaluation” datasets with hu- man annotations for pairwise comparisons, to mea- sure the correlation between our evaluation meth- ods and human judgments. LFQA (Xu et al., 2023) contains 140 long-form questions across seven domains (e.g. economics, history, and biology) and two candidate answers (from either GPT3 or Human) for each. Similar to ELI5 (Fan et al., 2019), it contains more recent (i.e. after July 2021) questions from Reddit fo- rums “r/explainlikeimfive” and “r/AskHistorians”. The authors collected expert-level annotations of which answer is better (overall preference). Since human preferences vary, authors report expert (dis)agreements, with a Fleiss’ κ (Fleiss, 1971; Fleiss et al., 2013) at around 0.5-0.6, and accuracy > 0.8 – which indicates moderate to substantial agreement. [System] You are reviewer A, discussing with reviewer B about your reviews of the following answers. [Question] {Q} [Answer1] {A1} [Answer2] {A2} [Init Review A] {Review of reviewer A} [Init Review B] {Review of reviewer B} [System] "Read the reviews and discussions above, and make a decision if to change your preference, and explain. ported information, core information, and co- herence. answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line." [Reviewer A] {First-turn output} [Reviewer B] {Second-turn output} [Reviewer A]: Table 1: The discussion template for reviewer A at the third turn. All texts above are chat history and are used as input to reviewer A’s LLM model. Core aspects that we instruct the judging/reviewer model to focus on are in boldface. Vicuna80 (Chiang et al., 2023) is a set of 80 open-ended questions from a diverse set of cate- gories, such as roleplay and writing. In the QLoRA work (Dettmers et al., 2023), authors annotated pairwise comparison scores (overall preference) across 7 models for each question. The scores in- clude 0, 1, 2 which correspond to tie, model 1 wins, and model 2 wins. We select pairwise compari- son annotations of 4 models’ answers (i.e. GPT4, ChatGPT-3.5., Bard, Vicuna-13b). To make our study more comprehensive, we add recent propri- etary language models such as Claude2. Specifi- cally, we also annotate pairwise comparisons be- tween Claude’s answers and the other 4 models’. We term this more complete version of the dataset Vicuna80. More details about the annotation pro- cess are provided in Appendix E. Since answers to open-ended questions are even harder to compare, the annotators achieve fair agreement. In total, there are 1-3 expert-level annotations for questions in LFQA; and there are 3 human annotations for each question in Vicuna80. We use human majority vote as the human preference during battles. # 2https://www.anthropic.com/index/ introducing-claude GPT-4 All All (Weighted) Human Raters models Elo Rank Elo Rank Elo Rank Elo Rank GPT-4 Claude Vicuna GPT-3.5 Bard 1282 1150 883 878 (+10) 804 1 2 3 4 5 1165 1104 930 919 881 1 2 3 4 5 1213 (-23) 1125 (-2) 912 (-8) 894 856 (+8) 1 2 3 4 5 1236 1127 920 868 847 1 2 3 4 5 GPT-4 All All (Weighted) Human Raters models Win Rate Rank Win Rate Rank Win Rate Rank Win Rate Rank GPT-4 Claude Vicuna GPT-3.5 Bard 0.856 0.709 0.348 0.342 (+0.028) 0.245 1 2 3 4 5 0.749 0.662 0.393 (+0.004) 0.375 0.320 1 2 3 4 5 0.802 (-0.020) 0.685 (-0.004) 0.376 0.346 0.290 (+0.004) 1 2 3 4 5 0.822 0.689 0.389 0.314 0.286 1 2 3 4 5 Table 2: Global Rank Correlation Results. The upper table shows the correlation between LLM reviewer-based ranking and human rater’s ranking. Bottom table shows correlation between global win rates. Boldfaced numbers are the closest to scores from human raters. Blue numbers show the difference between the score from LLM reviewers and Human raters. For more detailed pairwise win rates, please refer to the heat maps in Section D. # 3.2 Setup and Metrics Following Wang et al. (2023a) and Xu et al. (2023), we first conduct example-level pairwise compar- isons. Specifically, each evaluation example (pair- wise comparison) consists of a question and a pair of long-form answers. We compare the model pre- dicted preference score against gold human prefer- ence, and report Accuracy and Fleiss’ κ. Following Dettmers et al. (2023), we also compare model- predicted global ranking scores against human- judged ranking scores. Specifically, we report Elo scores (Elo, 1967; Askell et al., 2021) and win rate (WR) based rankings (Table 2). For experiments on PR, we use All to denote our method where each reviewer has equal weights; and use All (weighted) to denote the setting where the final round weights to each reviewer. For Vicuna-13b, we use the default version from Chiang et al. (2023). For all other API-based LLM models, we use specific versions of each. – we use GPT-4-0613, GPT-3.5-turbo-0613, Claude-1, and PaLM-2 for GPT-4, GPT-3.5, Claude, and Bard respectively. For more details, please refer to ap- pendix B. Reviewer Fleiss Kappa Accuracy GPT-3.5 Claude GPT-4 GPT-4 & Claude & GPT-3.5 All Reviewers (Weighted) 0.387 0.319 0.406 0.403 0.410 0.621 0.607 0.643 0.666 0.673 Table 3: Example-level correlation results, for the fourth and fifth rows, we take the peer reviewers’ ma- jority vote weighted by winrate. such as GPT-4 and Claude. In Table 3, all reviewer combinations listed ex- cept Claude, when compared to human reviews at an example level, display a Fleiss κ of around 0.40, indicating fair to moderate agreement. There is a significant difference in accuracy between reviews. The worst reviewer is Claude, with an accuracy of only 60.69%. The best individual reviewer is GPT-4, with an accuracy of 64.25%. The combi- nation of reviewers (PR) increases this accuracy by a few percentage points, with our PR approach being highest at 67.31%. Inspecting Table 2, all combinations of ranking methods listed give the same ranking of models: Besides experiments on PR and PD respectively (Section 3.3 and Section 3.4), we also compare PR and PD in an experiment of judging answer qualities of GPT-3.5 v.s. Vicuna-13b (Table 6). # 3.3 Results for Peer Rank (PR) On the Vicuna80 dataset, we compare our PR method and representative LLM-based evaluations, GPT-4 > Claude > Vicuna > GPT-3.5 > Bard However, in terms of the Elo ratings provided by the human reviews, we clearly observe that GPT-4 clearly favor its own answers and is prone to self- enhancement bias. The method that produces the closest Elo ratings is our approach of the weighted 1350 1300] 1280] 1200] Elo of GPT-4 Match No. Figure 3: GPT-4 Elo scores every 100 battles on Vi- cuna80 dataset. Elo scores provided by GPT-4 reviewer are consistently higher than human ratings, while our All (weighted) ratings correlates with humans well. combination of all reviewers (“All weighted”). Fur- thermore, the method that produces the closest win rates (less than a 1% difference for many con- testants) is also All weighted. In the beginning, when the weight is the same for every reviewer (weights equal to one), the win rate given by “All reviewers” is low at about 0.749 partially because each reviewer is treated equally so that each re- viewer might have a preference for its own answer. After several rounds/iterations, the final win rate becomes more fair. We display the final round weights in Figure 4. Lastly, in Figure 3, we draw the line chart of how GPT-4 Elo score changes as more battles are fed to the Elo algorithm. GPT-4’s score takes off as battle number increases. We can observe that GPT-4 displays self-enhancement across the entire process, while our PR approach-base evaluation correlates with human pairwise comparisons well. It appears that a weighted peer ranking also pro- vides a more accurate evaluation of language mod- els at the level of the global performance of models. At the example level, a weighted peer ranking also provides higher accuracy and a minimally higher agreement with human reviews. # 3.4 Results for Peer Discussions (PD) In this section, we demonstrate how the LLM dis- cussion process helps with the evaluations. Explicit and Generic Prompt We first conduct preliminary experiments to find a relatively good prompt for facilitating LLM peer discussions. In Table 4, we list the accuracy of GPT-4 and Claude’s initial pairwise comparison preference. They have gpt-4 claude vicuna gpt-3.5 bard 37.7% 48.8% 8.18% 5.31% 0% Figure 4: Peer rank final round weights of each re- viewer. GPT-4 lead Claude lead Random GPT-4 init score Claude init score Generic prompt w/ explicit critieria w/ role - - 0.714 0.729 0.729 - - 0.671 0.721 0.671 0.729 0.671 0.686 0.720 0.729 Table 4: Different prompting’s effect on disucssion ac- curacies (on the LFQA dataset). a moderate agreement with human preference, with GPT-4 leading around 5%. For the discussion- based evaluators, we report three types. By “GPT-4 lead”, we refer to the discussions where GPT-4 first expresses opinions; by “random”, we refer to dis- cussions where the leader is randomly picked. On the other side, when we use a generic prompt (such as “pick your preferred answer”), the discussion’s final preferences accuracy is around 0.69, higher than Claude’s initial judgment’s accuracy but lower than GPT-4’s. When we add more explicit aspects into the prompt3, the discussion accuracy boosts significantly (4% improvement). When we add to each’s turn’s prompt the role/identity informa- tion to remind the reviewer, the performance of GPT-4 leading discussions changes marginally, but Claude-leading discussions accuracy drops. Inves- tigating the effect of role information in the prompt is a potential future work direction. General Accuracy In Table 5, we report accu- racies of discussions of multiple combinations of reviewers on LFQA. There are several trends: (1) when two models are of similar capabilities (e.g. GPT-4 and Claude), there are likely relatively large 3We select aspects from WebGPT annotation guidelines mentioned in the previous section. GPT4 & Claude GPT4 & GPT35 GPT35 & Claude GPT35 & GPT35-0.8 Claude & Claude-0.8 GTP4 & GPT4-0.8 R1 0.729 0.729 0.579 0.579 0.664 0.779 R2 0.671 0.579 0.671 0.650 0.707 0.757 R1 lead R2 lead Random 0.743 0.729 0.750 0.714 0.700 0.671 0.686 0.664 0.671 0.693 0.779 0.757 0.729 0.731 0.686 0.681 0.680 0.779 Table 5: Discussion accuracies on LFQA. Accuracy GPT-4 0.3500 GPT-4 & Claude All All (weighted) 0.3675 0.4375 0.4625 Table 6: Comparing discussions (PD) and peer ranking (PR) on Vicuna80 (random order is applied to the GPT4 & Claude discussion). improvements upon initial reviews of both LLMs (2) when there is a substantial gap between re- viewer capabilities (e.g. GPT-4 and GPT-35), the discussion accuracy is usually below the stronger model’s initial accuracy and higher than the weaker model’s. (3) when models “self-discuss”, where we set different temperatures to create two variants of the same model, for example GPT-4 (tempera- ture=0 and =0.8). The weaker model usually can substantially “self-improve”, it is the case for GPT- 35, while GPT-4’s self-discussion brings only little improvements. In Table 6, we report results on GPT-3.5 v.s. Vicuna-13b comparisons on Vicuna80 questions, we see the GPT-4&Claude discussion increases the accuracy by over 1.5%. Also, we add the accuracy of the PR method in the Table. There the review becomes substantially fairer after weighted ranking. Future investigations on how to design better self- discussion strategies would be worth it. self- Peer enhancement bias According Zheng et al. (2023) and we previously discovered, large language models (LLMs) endure self-enhancement bias when acting as judges – preferring the answers they generate, or that of the models under the same series (e.g. GPT-4 and GPT-3). We conduct exper- iments on the subset of LFQA questions where we have human annotated pairwise comparisons between Human and Machine-generated (GPT-3 text-davinci-002) answers. Table 7 shows the win rates of GPT-3 judged by humans and three LLMs. We report their initial Reviewers GPT-3 Initial Preference After Discussion Human GPT-3.5 Claude GPT-4 72.46% 63.81% 55.50% 58.67% 62.22% 60.28% 58.75% Table 7: GPT-3 answer win rates judged by different reviewers on LFQA. For all LLM reviewers, we take the average accuracy of all discussions they participate in. Self-enhancement exists and is mitigated by PD. # Prefer2nd |) Prefer 1st 100% 75% 25% ye et ye" soe roe . so? Figure 5: The position bias of all three LLMs’ initial and after peer discussion reviews. Human has an equiv- alent preference for either position (dotted line). and after-discussion preferences. Both GPT-3.5 and Claude highly prefer GPT-3’s answers in their initial reviews. Specifically, GPT-3.5 significantly favors GPT-3 answers with a 13.79% higher win rate. After discussing with other LLMs, all models align better with humans. Before discussions, GPT- 4’s initial preference aligns well with humans and is almost the same as humans after peer discussions. – which proves it’s not favoring GPT-3 much and is more fair. Position bias can be mitigated by Peer Discus- sions Human-annotated pairwise comparisons are not affected by the position of answers. As in- dicated by recent work of Wang et al. (2023a) and Dettmers et al. (2023), LLMs are prone to position bias, describing that LLMs tend to show a prefer- ence for specific positions, even when prompted not to do so (Table 10 in Appendix). In Table 8, the win rate of GPT-3 is highly affected by its po- sition when models generate initial reviews. GPT- 3.5 highly prefers the answer in the first position compared to Claude and GPT-4. The GPT-3 win rate calculated by GPT-3.5 is 15.79% higher than the win rate based on human-annotated pairwise claude 043 04 Figure 6: Pairwise win rate heatmaps: Fraction of Model A Wins For All A vs. B Battles (A: rows, B: columns). Left: GPT-4 evaluator; Middle: our method All (weighted); Right: Chatbot Arena pairwise win rate. Reviewers Initial Preference After Discussion GPT-3 First Human First GPT-3 First Human First Human GPT-3.5 Claude GPT-4 57.89% 73.68% 63.16% 54.51% 59.46% 59.46% 64.41% 56.37% 57.89% 67.11% 55.70% 58.27% 59.46% 58.56% 55.41% 58.30% Table 8: GPT-3 answer win rate (in the GPT-3 vs Hu- man battles). comparisons, when GPT-3 appears first (73.68 vs 57.89). After peer discussion, all models have closer preferences to humans. Second, all LLMs’ scores for GPT-3 of both positions are closer as well. These imply that the position bias is miti- gated after peer discussions. From another perspective, Figure 5 shows the global preference of selecting answers at the first or second positions across different LLM review- ers. Overall, GPT-3.5 prefers answers at the first position. The other two models favor answers in the second position, which is similar to the position bias shown in Table 8. After peer discussion, it shows the same trend of mitigating position bias as well. # OA (Opinion Altering) total # Opinion Holding (OH) total 50 40 30 20 ; it al 0 eS ) yo? oe x sos’ oo & we ss oe Nes oo oo ge Figure 7: The discussion bias of all three models at the leading and following position. Arena ranking4 is based on user queries and their corresponding preferences for two responses. The figure demonstrates that although both approaches favor GPT-4 and Claude answers, the win rates cal- culated by our approach All (weighted) correlate better with Arena win rate, especially on weaker models. # 4 Further Analysis In this section, we provide a more comprehensive analysis of our methods. Pairwise win rate of models Previously in Ta- ble 2, we presented the global win rate correlation with human ratings on Vicuna80. In Figure 6, we present the more detailed version of pairwise win rates between every two contestants (LLMs). We compare our evaluation with GPT-4 based evalua- tion, as well as the Chatbot Arena leaderboard. The The reviewer who leads the discussion tends to hold its opinion. In a discussion between two reviewers, we define the reviewer who leads the discussion as the leader and the other reviewer as the follower. We find leaders are less likely to be convinced by followers when it insists on its own opinion at the first turn. We name it “Discussion Ordering Bias”. We observe this bias in discussions over the LFQA questions. We define two phenomenons which may happen 4https://lmsys.org/blog/ 2023-05-25-leaderboard/ during the discussions: (1) Opinion altering (OA): a reviewer changing its opinion after discussing with another reviewer. For example, R2 posts its preference at turn 2, which is different from R1’s preference at turn 1, then R1 changes its preference at turn 3 that agrees with R2; (2) Opinion holding (OH): a reviewer does not change its opinion even if another reviewer disagrees. For example, R1 posts its preference at turn 1 while R2 disagrees with R1 at turn 2; then, R1 still holds its preference at turn 3. As shown in Figure 7, all models have OA when they are in the follower’s position, while their num- ber of OA decreases significantly after they switch to the leader position. This implies that discus- sion ordering bias exists in discussions. On the pairwise comparisons of LFQA where two review- ers initially disagree:when in the leader position, GPT-4 has zero OA, and Claude has two OAs (hap- pens during the discussions with GPT-3.5). When GPT-4 discusses with Claude, both of them hold their initial preferences when they are in the leader position. Stronger LLMs tend to hold their opinions As from Figure 7, we add up the green mass (OH total) for each LLM reviewer to obtain their OH cases in both orderings. We see that models that are commonly recognized as being stronger (e.g. GPT-4) are more firm in their reviews and hold their opinions. For example, GPT-3.5 changes its opinion most often, and GPT-4 usually holds its opinion. More specifically, GPT-4 holds its opinion in 174 discussions, while Claude and GPT-3.5 hold only in 94 and 76 discussions, respectively. Post-agreement opinion altering is when two reviewers reach a mutual agreement first, and one reviewer regret and suddenly changes its preference in a later turn. For example, R1 and R2 agree upon answer 1 after two turns, while R1 changes its preference to answer 2 in the third turn. As shown in Table 9, GPT-4 makes this type of change the least and GPT-3.5 the most. This potentially shows that models with a lower capability are not firm about their opinions. # 5 Related Work Automatic Evaluations NLG evaluation meth- ods are mainly of a similarity-based or reference- free type. For similarity-based metrics, the gen- erated texts are compared to reference text. They Reviewers Opinion Altering Leading Following GPT-3.5 Claude GPT-4 37 11 1 31 10 5 Table 9: Post-agreement opinion altering (OA). can be divided into lexical overlap-based (Papineni et al., 2002; Lin, 2004; Banerjee and Lavie, 2005) and contextualized embedding-based (Zhang et al., In parallel, people have also 2019) evaluators. developed task-specific metrics such as consis- tency (Kry´sci´nski et al., 2020; Wang et al., 2020), faithfulness (Fabbri et al., 2022; Gao et al., 2023) and coherence (Dziri et al., 2019). This is simi- lar to our peer discussion idea on designing more specific prompts for large language model-based evaluations. Our prompting-based method is more flexible and can act as a unified evaluator (Zhong et al., 2022). open- ended question answering, early work uses ROUGE (Lin, 2004) to measure the similarity be- tween human and machine-generated answers. But researchers find that ROUGE is not a fair metric for quality measurement due to the open-ended nature of long-form answers (Reiter and Belz, 2009; Krishna et al., 2021; Xu et al., 2023). Fu et al. (2023a) propose GPTScore, which evaluates texts with generative pre-training models like GPT-3. Xu et al. (2023) also implements a similar idea for evaluating long-form answers. Given a prompt consisting of a question with two answer candidates, GPT-3 is fine-tuned to output the label answer1 and answer2. Differing from above, it produces pairwise comparisons – preference scores. LLMs as evaluators: problems and challenges Most recently, with the trend of developing open- source LLMs, evaluations for benchmarking the progress have become even more important but also more difficult. Apart from testing on standard datasets such as MMLU (Hendrycks et al., 2020), they are often tested on open-ended questions, which are much more prevalent in real life (Nakano et al., 2021; Chiang et al., 2023). People mostly use the recently recognized strongest LLM such as GPT-4 (Liu et al., 2023; OpenAI, 2023) as an evaluator for either generating scores or pairwise comparisons (Dettmers et al., 2023; Wang et al., 2023b; Zhou et al., 2023). However, such a strategy has fundamental problems mainly because of var- ious biases, such as (1) positional bias (Dettmers et al., 2023; Wang et al., 2023a), where a model favors the first answer in pairwise comparisons; (2) verbosity and length bias (Zheng et al., 2023; Wang et al., 2023b); (3) and most importantly – the favoring of the LLM’s own answers. (Liu et al., 2023; Zheng et al., 2023) Efforts have been proposed to tackle them: (1) Using position switching (Wang et al., 2023a; Dettmers et al., 2023) for mitigating positional bias; (2) Zheng et al. (2023) proposes Chatbot Arena, where real users ask questions and provide pairwise judgments (win, lose, or tie) of answers generated by two different LLMs. But this is time- consuming and costly to ensure fairness – requiring expert-level annotations of pair comparisons. (3) Concurrent to our work, Bai et al. (2023) propose using each language model as an examiner, where each LLM generates questions to test other models. Different from peer evaluation, their “exams” are decentralized and biased with randomly generated questions. Moreover, all of the above works do not support inducing self-rankings through peer ranking. # 6 Conclusion Our method provides promising prospects of us- ing a peer evaluation method to improve LLM- based evaluations, with the goal to mitigate poten- tial bias (e.g. self-enhancement, positional) in pre- vious prevalent methods. Our proposed peer rank process provides a more fair ranking of model capa- bilities. The peer discussion process helps models to reach mutual agreements that correlate with hu- man preference more, at the same time helping weaker models to learn from stronger models’ re- views. In the future, we plan to investigate how the general peer evaluation process benefit the LLMs in learning to access their own answer and answer new questions (Nicol et al., 2014). # Limitations During evaluations, our method requires GPU re- sources or Cloud API services, for both peer dis- cussion and peer ranks. # Acknowledgements We thank Barry Wang for helping with Figures 1&2. We thank Jialu Li and Yunmo Chen for providing editing suggestions on the paper draft. We thank Artidoro Pagnoni for sharing part of the human ratings. # References Amanda Askell, Yuntao Bai, Anna Chen, Dawn Drain, Deep Ganguli, Tom Henighan, Andy Jones, Nicholas Joseph, Ben Mann, Nova DasSarma, et al. 2021. A general language assistant as a laboratory for alignment. arXiv preprint arXiv:2112.00861. Yushi Bai, Jiahao Ying, Yixin Cao, Xin Lv, Yuze He, Xiaozhi Wang, Jifan Yu, Kaisheng Zeng, Yijia Xiao, Haozhe Lyu, et al. 2023. Benchmarking foundation models with language-model-as-an-examiner. arXiv preprint arXiv:2306.04181. Satanjeev Banerjee and Alon Lavie. 2005. Meteor: An automatic metric for mt evaluation with improved correlation with human judgments. In Proceedings of the acl workshop on intrinsic and extrinsic evalu- ation measures for machine translation and/or sum- marization, pages 65–72. Wei-Lin Chiang, Zhuohan Li, Zi Lin, Ying Sheng, and et.al. 2023. Vicuna: An open-source chat- bot impressing gpt-4 with 90%* chatgpt quality, https://lmsys.org/blog/2023-03-30-vicuna/. Kwangsu Cho and Charles MacArthur. 2011. Learning by reviewing. Journal of educational psychology, 103(1):73. Peter Clark, Isaac Cowhey, Oren Etzioni, Tushar Khot, Ashish Sabharwal, Carissa Schoenick, and Oyvind Tafjord. 2018. Think you have solved question an- swering? try arc, the ai2 reasoning challenge. arXiv preprint arXiv:1803.05457. Tim Dettmers, Artidoro Pagnoni, Ari Holtzman, and Luke Zettlemoyer. 2023. Qlora: Efficient arXiv preprint finetuning of quantized llms. arXiv:2305.14314. Yann Dubois, Xuechen Li, Rohan Taori, Tianyi Zhang, Ishaan Gulrajani, Jimmy Ba, Carlos Guestrin, Percy Liang, and Tatsunori B Hashimoto. 2023. Al- pacafarm: A simulation framework for methods arXiv preprint that learn from human feedback. arXiv:2305.14387. Nouha Dziri, Ehsan Kamalloo, Kory Mathewson, and Osmar R Zaiane. 2019. Evaluating coherence in di- alogue systems using entailment. In Proceedings of the 2019 Conference of the North American Chap- ter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 3806–3812. Arpad E Elo. 1967. The proposed uscf rating system. its development, theory, and applications. Chess Life, 22(8):242–247. Alexander Richard Fabbri, Chien-Sheng Wu, Wenhao Liu, and Caiming Xiong. 2022. Qafacteval: Im- proved qa-based factual consistency evaluation for summarization. In Proceedings of the 2022 Confer- ence of the North American Chapter of the Associ- ation for Computational Linguistics: Human Lan- guage Technologies, pages 2587–2601. Angela Fan, Yacine Jernite, Ethan Perez, David Grang- ier, Jason Weston, and Michael Auli. 2019. Eli5: In Proceedings of Long form question answering. the 57th Annual Meeting of the Association for Com- putational Linguistics, pages 3558–3567. Joseph L Fleiss. 1971. Measuring nominal scale agree- ment among many raters. Psychological bulletin, 76(5):378. Joseph L Fleiss, Bruce Levin, and Myunghee Cho Paik. 2013. Statistical methods for rates and proportions. john wiley & sons. Jinlan Fu, See-Kiong Ng, Zhengbao Jiang, and Pengfei Liu. 2023a. Gptscore: Evaluate as you desire. arXiv preprint arXiv:2302.04166. Yao Fu, Hao Peng, Tushar Khot, and Mirella Lapata. 2023b. Improving language model negotiation with self-play and in-context learning from ai feedback. arXiv preprint arXiv:2305.10142. Tianyu Gao, Howard Yen, Jiatong Yu, and Danqi Enabling large language models arXiv preprint Chen. 2023. to generate text with citations. arXiv:2305.14627. Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Stein- hardt. 2020. Measuring massive multitask lan- In International Conference guage understanding. on Learning Representations. Karen Sparck Jones and Julia R Galliers. 1995. Evalu- ating natural language processing systems: An anal- ysis and review. Kalpesh Krishna, Aurko Roy, and Mohit Iyyer. 2021. Hurdles to progress in long-form question answer- In Proceedings of the 2021 Conference of ing. the North American Chapter of the Association for Computational Linguistics: Human Language Tech- nologies, pages 4940–4957, Online. Association for Computational Linguistics. Wojciech Kry´sci´nski, Bryan McCann, Caiming Xiong, and Richard Socher. 2020. Evaluating the factual consistency of abstractive text summarization. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 9332–9346. Guohao Li, Hasan Abed Al Kader Hammoud, Hani Itani, Dmitrii Khizbullin, and Bernard Ghanem. 2023. Camel: Communicative agents for" mind" exploration of large scale language model society. arXiv preprint arXiv:2303.17760. Percy Liang, Rishi Bommasani, Tony Lee, Dimitris Tsipras, Dilara Soylu, Michihiro Yasunaga, Yian Zhang, Deepak Narayanan, Yuhuai Wu, Ananya Ku- mar, et al. 2022. Holistic evaluation of language models. arXiv preprint arXiv:2211.09110. Chin-Yew Lin. 2004. Rouge: A package for automatic In Text summarization evaluation of summaries. branches out, pages 74–81. Yang Liu, Dan Iter, Yichong Xu, Shuohang Wang, Ruochen Xu, and Chenguang Zhu. 2023. Gpteval: Nlg evaluation using gpt-4 with better human align- ment. arXiv preprint arXiv:2303.16634. Reiichiro Nakano, Jacob Hilton, Suchir Balaji, Jeff Wu, Long Ouyang, Christina Kim, Christopher Hesse, Shantanu Jain, Vineet Kosaraju, William Saunders, et al. 2021. Webgpt: Browser-assisted question- arXiv preprint answering with human feedback. arXiv:2112.09332. David Nicol, Avril Thomson, and Caroline Breslin. 2014. Rethinking feedback practices in higher ed- ucation: a peer review perspective. Assessment & evaluation in higher education, 39(1):102–122. OpenAI. 2022. Webgpt annotation guidelines. OpenAI. 2023. Gpt-4 technical report. ArXiv, abs/2303.08774. Lawrence Page, Sergey Brin, Rajeev Motwani, and Terry Winograd. 1999. The pagerank citation rank- ing: Bringing order to the web. Technical report, Stanford InfoLab. Kishore Papineni, Salim Roukos, Todd Ward, and Wei- Jing Zhu. 2002. Bleu: a method for automatic eval- uation of machine translation. In Proceedings of the 40th annual meeting of the Association for Compu- tational Linguistics, pages 311–318. Joon Sung Park, Joseph C O’Brien, Carrie J Cai, Meredith Ringel Morris, Percy Liang, and Michael S Interactive Bernstein. 2023. Generative agents: arXiv preprint simulacra of human behavior. arXiv:2304.03442. Ehud Reiter and Anja Belz. 2009. An investigation into the validity of some metrics for automatically evalu- ating natural language generation systems. Compu- tational Linguistics, 35(4):529–558. Toby Walsh. 2014. The peerrank method for peer as- In Proceedings of the Twenty-first Eu- sessment. ropean Conference on Artificial Intelligence, pages 909–914. Alex Wang, Kyunghyun Cho, and Mike Lewis. 2020. Asking and answering questions to evaluate the fac- In Proceedings of tual consistency of summaries. the 58th Annual Meeting of the Association for Com- putational Linguistics, pages 5008–5020. Peiyi Wang, Lei Li, Liang Chen, Dawei Zhu, Binghuai Lin, Yunbo Cao, Qi Liu, Tianyu Liu, and Zhifang Sui. 2023a. Large language models are not fair eval- uators. Yizhong Wang, Hamish Ivison, Pradeep Dasigi, Jack Hessel, Tushar Khot, Khyathi Raghavi Chandu, David Wadden, Kelsey MacMillan, Noah A. Smith, Iz Beltagy, and Hanna Hajishirzi. 2023b. How far can camels go? exploring the state of instruction tun- ing on open resources. ArXiv, abs/2306.04751. Fangyuan Xu, Yixiao Song, Mohit Iyyer, and Eunsol Choi. 2023. A critical evaluation of evaluations for In Proceedings of long-form question answering. ACL. Matthew M Yalch, Erika M Vitale, and J Kevin Ford. 2019. Benefits of peer review on students’ writing. Psychology Learning & Teaching, 18(3):317–325. Tianyi Zhang, Varsha Kishore, Felix Wu, Kilian Q Weinberger, and Yoav Artzi. 2019. Bertscore: Eval- arXiv preprint uating text generation with bert. arXiv:1904.09675. 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. 2023. Judging llm-as-a-judge with mt-bench and chatbot arena. Ming Zhong, Yang Liu, Da Yin, Yuning Mao, Yizhu Jiao, Pengfei Liu, Chenguang Zhu, Heng Ji, and Towards a unified multi- Jiawei Han. 2022. In Pro- dimensional evaluator for text generation. ceedings of the 2022 Conference on Empirical Meth- ods in Natural Language Processing, pages 2023– 2038. Chunting Zhou, Pengfei Liu, Puxin Xu, Srini Iyer, Jiao Sun, Yuning Mao, Xuezhe Ma, Avia Efrat, Ping Yu, Lili Yu, et al. 2023. Lima: Less is more for align- ment. arXiv preprint arXiv:2305.11206. # A Detailed Prompt for Reviews [System] You are a helpful and precise assistant for checking the quality of the answer. [Question] {Q} [Answer1] {A1} [Answer2] {A2} [System] We would like to request your feedback on the performance of two answers in response to the user question displayed above. Firstly, please compare the two answers based on if they contain unsupported tion, and a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. Once you have carefully reviewed both submissions, in a new line, choose between the two answers by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Table 10: It shows the review template for reviewers with three slots ({Q}, {A1}, and {A2}). Similar to discussion template, we explicitly indicate aspects that reviewers need to pay attention to. As mentioned in Wang et al. (2023a), position bias still exists after em- phasizing it in the prompt. Table 10 shows the template for reviewers to generate initial reviews. # B LLM details As mentioned in section 3.2, we use APIs of GPT-4, GPT-3.5, Claude, and Bard. Currently, the last two models’ APIs are free. To generate initial reviews for LFQA (140 ques- tions), GPT-4-0613 costs about $20. For the dis- cussion between GPT-4-0613 and Claude-1 on LFQA, the OpenAI API costs about $24. The price of GPT-3.5-turbo-0613 is 1/20-th and 1/30-th of GPT-4-0613 on inputs and outputs correspond- ingly. # C Detailed Win rate & Elo Calculation The algorithm for calculating weighted elo is de- scribed in Algorithm 1. The algorithm for calcu- lating weighted win rate is described in Algorithm 2: Algorithm 1: Weighted Elo Ratings :B – The list of battle reviews Each review is a 5-tuple (question, contestant A, contestant B, Input reviewer, score) where a score of {-1, 0, 1} means {A wins, tie, B wins} W – The mapping of reviewers to weights Output :Elo – The Elo rating for each contestant 1 K ← 32 ; 2 Define p(x) = 1 1+10x/400 ; // scale weights so that their mean is 1. 3 W ← W/mean(W ) ; 4 Elo ← mapping of each contestant in B to 1000. ; 5 foreach (q, i, j, r, s) ∈ B do 6 ω ← W [r] ; rA ← Elo[i] ; rB ← Elo[j] ; eA ← p(rB − rA) ; eB ← p(rA − rB) ; // sA has win value of 0, 0.5, or 1 for 7 8 9 10 i loss, tie, or i win sA ← (1 − s)/2 ; sB ← 1 − sA ; Increment Elo[i] by ωK(sA − eA) ; Increment Elo[j] by ωK(sB − eB) ; 11 12 13 14 15 end 16 return Elo # Algorithm 2: Weighted Win Rates Input :B – The list of battle reviews Each review is a 5-tuple (question, contestant A, contestant B, reviewer, score) where a score of {-1, 0, 1} means {A wins, tie, B wins} Iters – The number of iterations to run Output :S – The win-rate for each contestant W – The resulting weights at the end 1 C ← set of contestants in B ; 2 R ← set of reviewers in B ; 3 W ← mapping of each reviewer to 1/|R| ; 4 for 1 to Iters do 5 6 // No. of reviews for each contestant N ← mapping of each c ∈ C to 0 ; // Weighted wins for each contestant V ← mapping of each c ∈ C to 0; 7 foreach (q, i, j, r, s) ∈ B do 8 9 // Update number of reviews Increment N [i] by 1 ; Increment N [j] by 1 ; ω ← W [r] ; /* maps (loss=-1, tie=0, win=1) to (0, 0.5, 1) Define f (x) = (1 + x)/2 ; Increase V [i] by ω · f (−s) ; Increase V [j] by ω · f (s) ; end S ← mapping of each c ∈ C to V [c] W ← Normalize(MinMax(S)) ; N [c] ; */ 10 11 12 13 14 15 # 16 17 end 18 return S, W D Pairwise win rate heatmap Model B claude vicuna Fraction of Model A Wins For All A vs. B Battles (GPT-4 review claude vicuna Model B claude vicuna os 07 06 os o4 03 o2 Model B claude vicuna os 07 06 < 3 os = o4 03 o2 Fraction of Model A Wins For All A vs. B Battles (Weighted) Figure 8: Pairwise win rate heatmap (Left: reviewer all (weighted); Right: GPT-4). Model B gpt-4 claude 13.5 vicuna < 3 2 vicunal Fraction of Model A Wins For All A vs. B Battles (Chatbot Arena) Model B claude vicuna os 07 06 os o4 03 o2 Fraction of Model A Wins For All A vs. B Battles (human reviews) Model B Model B gpt-4 claude 13.5 vicuna claude vicuna vicunal Figure 9: Pairwise win rate heatmap (Left: arena leaderboard; Right: our human). # E Human Annotation for Pairwise Preference Since completing one HIT can take a considerable amount of time (6-10 min), we added a button that allows saving their work at any stage in the middle of the HIT. This button populates a text area with a JSON representation of the current responses, which may be copied into a file. We annotate part of the pairwise comparisons of model answers on Vicuna80. We built an interface form. The screenshot is as illustrated in Figure 11. We would like to request your feedback on the performance of several Al assistants in response to the user question displayed below. Please consider the helpfulness, relevance, accuracy, level of details of their responses. Then look at the pairwise comparisons and choose the best response, avoiding any potential bias, ensuring that the order in which the responses were presented does not affect your judgment. For your reference, we also provide the review of GPT4 on the responses. Since GPT4 has an order bias, we have provided the reviews of GPT4 on both (ResponseA, ResponseB) and (ResponseB, ResponseA) as (Assistant 1, Assistant 2). Elapsed Time: 0:0:29 Question: Use an appropriate format to structure a formal letter of recommendation for a student applying to a prestigious graduate program in computer science. Response 1 | Response 2 | Response 3 | Response 4 | Response 5 | Overall Comparisons Response 1: Here is a draft formal letter of recommendation for the student: Your Letterhead Date To the Admissions Committee: | am writing to recommend [Student Name] for admission to the Master's program in Computer Science at [College or University Name]. | have known [himvher] for [length of time] in my capacity as [relationship to student] at [institution name]. [Student Name] has been an outstanding student in my [course name] course. From my interactions with [him/her], | have found [him/her] to be an exceptionally gifted student with a strong work ethic and intellectual curiosity. [He/She] has demonstrated a keen interest in the field of [area of interest}, and | am confident [he/she] would thrive in your program. Specifically, (Student Name] [description of student's key attributes and accomplishments]. [He/She] has shown strong leadership ability and communication skills, as evidenced by [examples and accomplishments]. [He/She] has also developed innovative solutions to complex problems, as demonstrated by [his/her] work on [project or paper name]. In summary, | highly and enthusiastically recommend [Student Name] for admission to your prestigious Master's program. [He/She] will be an asset to your program and the field. Please do not hesitate to contact me if you require any further information. Sincerely, [Your name] [Your title] helpfulness ——EEED 5/10 TEILVANCl =-« EERE 5/10 accuracy [EEE 5/10 level Of CC ta] 5/10 1 2 3 4 5 6 ?7 8 9 10 Please exple ain yo ice Figure 10: The form used by human annotators for individual rating of a model. Sliders are included to rate a response on several metrics from 0 to 10. Explanations can be entered in the text area below. The tab bar and next button navigate between responses. We woul ket request our feedback onthe perfomance of scveral Al assists in reponse othe user cueston diplayed below. Pleese corsier ne heiness relevance, accuracy level of etl their responses Then lock atthe psiuisecarpaisons and choose the best respons, avoiding ny pfeil bes, ensuring tha he erdrin which theresponsas weve presered does rt aft yur judgment For you rference, we also provide the evew of CPT on he respnses, Shee GPT¢ hasan erderbias, we have provided the revews of Pon bth (ResporseA, Response) and (Respense3, ResponseA) as (Asstt 1, sista’ 2}. lysed Tine. 0223 Question: What are the ray fectrs het nftuencecorcumer behavior? (ResprseLRespanse2 [espe 3 [Response [Resprses [owe Corsi) Overall Comparisons Response A. Response B ‘te esa pinay atone Tae mera pay ac tla eos sensible consumer behavior nein 1 Pes {'Besonal factors: These include icvcua chereterntes sich ae age, gence, flow These cule naval chrenterates citeaon nec posendlgyandvalees: 2: Poy olgeal ore These nek Such as age, gee, nine, edacaton, rotor ee, an pcopd rs alc cre na posses icin ad pods nd serie. 3 See as: Fesmiggardieie 2 Porodagea prose lors These nude fe corsets nese elie cual, socal end ervormertal avs thal fee ie it ree. ines. cvsuer ewan sero an sewers 4 Economy These cite ‘Studes,balfs ard values. Secalfactors- ocr such a he pie ola produto sori, he valet of ate “hoes nels ie consumarafamiy,teondy, profuse orsevovs ane the consumors ucnsang power Masi tr: covial lass culure an reference Gouge. 4. These ncude the way apoduet or oer voz marke, ncn eve, Sutin asus: Treseirciae fe plyscal packaged Jsttbuon 6. Prod ed selvoe tacts. Tese Ince the rnfrmer te, end mood che consumer Guay, estes, anc berets oe ereduct or sevice aswel as Jet, se Mlerbenng i factors ese neo Beromance, rd arerty Undersanding hese factors can hel smeses ard pte fen emo, rd ison, and za uy sete arg ages wir et acs ay aol ha eoncune’'e ceclaon making safes to mcot the neods and poeronessg for age esionce proces, (EEE a RS] Compare Responses Lard 2: Response Lie bai °Resparee 2ie bate, The respanses are EXACTLY equal in cuaiy (Cisco Sw ReneS] Compare Responses 1 ard 3: Response Lis beter o Response Sis betetThe responses are EXACTLY equa im cual (EEELE Hacer] Compare Responses Land 4: Response Lie bat °Respance die bate, The responses are EXACTLY equal cual (GRETA) Compare Responses Land 5: Response Lis beter o Response Sis betel The fespanses are EXACTLY equa i cualy ‘lsicn ShonRssponse] Compare Responses 2 and 3: Response is beter Resporse 3 ete, The responses are EXACTLY equal in cui (ERB ea] Compare Responses ard 4: Response Zis bei © Respanse dis batt The respanses are EXACTLY equal in cua (GisLb SuTRaneS) Compare Responses 2 ard 5: Response Zis beter o Response Sis betet.The responses are EXACTLY equa im cuaiy (EB Tea RS] Compare Responses Sard 4: Response Sie bat © Resparee Ae batt, The respanses are EXACTLY equal in cua (CEE SToaT ERE] Compare Responses Sara's: Response Sis beter. 0 Resparse S's betel, The Fespanses are EXACTLY equa cUaly [EEE IES Reape] Compare Responses 4 and 5: Response 4 beter. Response i beter. The responses ae EXACTLY eal incl, senatnan sov'omeL______) Figure 11: The form used by human annotators for pairwise comparisons between model answers. Each pair of comparisons has buttons to choose which model is best, along with an area to provide an explanation. An associated button hides/shows the respective responses and automated comparisons. # F Discussion Examples In this section, there are four examples showing opinion-altering (OA), opinion-holding (OH), and post- agreement opinion-altering. In the following discussions, all texts before a colored reviewer’s name are the input for that reviewer. the text before "[System]" is the reviewer’s original output and the text after "[System]" is added after each round which reminds the nex reviewer about its role. The following example is a discussion between GPT-3.5 and Claude-1. In this example, GPT-3.5 alters its opinion to agree with Claude-1, while Claude-1 holds its opinion. GPT-3.5 Claude-1 Discussion (GPT-3.5 Leads) System: You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Background: [Question] When the joint-stock company was first invented, was there a lot of pushback on the concept? What were some of the concerns? Also any recommended books on the invention of the concept would be much appreciated! [The Start of Answer 1] An early form of joint stock ventures appeared in Assyria by the beginning of the 2nd millennium BCE. There does not seem to have been any noticeable pushback against the concept, although trade caravans were often taxed heavily. Of course, the relevant texts were written to and from people engaged in trade, so there’s no way of knowing what other Assyrians thought of long distance trade. >Most of these traders had become more independent by having become managers of a "joint-stock fund" (called *naruqqum*, "money bag"), usually set up in Assur. This phenomenon appeared for the first time around 1900 BC and seems to have been an Old Assyrian invention that went beyond individual partnerships and cooperation in a joint caravan. The arrangement, rather similar to that of the early medieval *compagnia*, meant enlisting a number (usually about a dozen) of investors (*ummi¯anum*, "financiers"), who supplied capital rated in gold, usually in all ca. 30 kilos, ideally consisting of shares of 1 or 2 kilos of gold each. It was entrusted to a trader (the tractator), usually for ca. ten years, for the generally formulated purpose of "carrying out trade." The contract contained stipulations on a final settlement of accounts, on paying dividends, on the division of the expected profit, and on fines for premature withdrawal of capital (meant to secure the duration of the business). Investors or shareholders mostly lived in Assur, but successful traders in Anatolia too invested in funds managed by others, perhaps also as a way of sharing commercial risks. In such cases a contract would to be drawn up in Anatolia that obliged the tractator "to book in Assur x gold in his joint stock fund in the investor’s name." Among the investors we find members of the tractator’s family, but also business relations and others, probably a kind of "merchant-bankers," and other rich citizens, who aimed at fairly safe, long- term investments. ["Ancient Assur: The City, its Traders, and its Commercial Network"](https://www.jstor.org/stable/25651212) by Klaas Veenhof For more on Old Assyrian trade and these early joint stock funds, see [*Ancient Kanesh: A Merchant Colony in Bronze Age Anato- lia*](https://books.google.com/books?id=qXGgCgAAQBAJ) by Mogens Larsen. [The End of Answer 1] [The Start of Answer 2] There was definitely some pushback when the joint-stock company was first invented. Some people were concerned that it would lead to corruption and cronyism, while others were worried that it would concentrate too much power in the hands of a few people. Recommended books on the topic include The First Tycoon: The Epic Life of Cornelius Vanderbilt by T.J. Stiles and The Great Transformation: The Political and Economic Origins of Our Time by Karl Polanyi. [The End of Answer 2] [The Start of Reviewer 1’s Evaluation] Answer 1: - Unsupported information: The answer provides historical information about joint-stock ventures in Assyria, which is not directly related to the invention of the joint-stock company. - Core information: The answer does not directly address the pushback on the concept of joint-stock companies or the concerns associated with it. - Coherence: The answer provides information about joint-stock ventures in Assyria but does not connect it to the concept of joint-stock companies or the question at hand. Answer 2: - Unsupported information: The answer does not provide any unsupported informa- tion. - Core information: The answer directly addresses the pushback on the concept of joint-stock companies and mentions concerns related to corruption, cronyism, and concentration of power. - Coherence: The answer is focused and provides relevant information related to the question. Based on the evaluation, Answer 2 is the better response as it directly addresses the question, provides core information, and maintains coherence. [The End of Reviewer 1’s Evaluation] [The Start of Reviewer 2’s Evaluation] Answer 1 provides a comprehensive overview of early joint stock companies in It focuses on facts about how these Assyria, citing multiple academic sources. companies operated, who invested in them, how long they lasted, and what purposes they served. The answer is coherent and flows logically from one idea to the next. Answer 2 is much more superficial, making broad claims about pushback against joint stock companies with little evidence or detail. The two book recommendations seem tangential and are not well-integrated into the main points of the answer. Overall this answer lacks coherence and depth compared to Answer 1. 1 [The End of Reviewer 2’s Evaluation] [System] Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence. In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-3.5: 2 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Claude-1: I will not change my preference for Answer 1. While Answer 2 directly addresses concerns about joint stock companies, it does so in a superficial way without evidence or depth. Answer 1 provides a wealth of historical detail about early joint stock companies in Assyria, citing multiple academic sources. Although not directly focused on pushback, Answer 1 demonstrates a strong, coherent understanding of how these early companies worked. Given our criteria of evaluating unsupported information, core information, and coher- ence, Answer 1 is still superior in my view. The tangential book recommendations in Answer 2 and lack of evidence for its claims reflect poorly for coherence and depth. Answer 1, though broader in scope, shows strong coherence and is well-supported. 1 [System] You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-3.5: I agree with your points. After considering your evaluation and the discussion, I am changing my preference to Answer 1. It provides more depth and coherence with its historical information about early joint stock companies in Assyria. While it may not directly address the pushback on the concept, it still provides valuable context and understanding of how these early companies operated. Answer 2, on the other hand, lacks evidence and depth, and the book recommendations seem tangential to the main points. Therefore, I believe Answer 1 is the better response overall. 1 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Claude-1: I appreciate your thoughtful consideration of my evaluation. We are in agreement that Answer 1 provides the most coherent, well-supported response overall, even if not directly focused on pushback. Depth of understanding and evidence are most valuable in my view. 1 The following example is a discussion between GPT-4 and Claude-1. In this example, GPT-4 holds its opinion, and Claude-1 alters its opinion to agree with GPT-4’s opinion. GPT-4 Claude-1 Discussion (GPT-4 Leads) System: You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Background: [Question] Could Frederick Douglass swim? [The Start of Answer 1] I think that the best thing to ask about, perhaps, would be *childhood* within the bounds of enslavement. Young enslaved children would often be the playmates of white children, so learning to swim together would not be unusual - and Douglass, elsewhere in the extended quotation, makes clear swimming was something from his *childhood*, describing his swim that *"Here all my boyish pranks in the front basin of Baltimore were renewed"*. It was a very interesting dichotomy that existed in those situations, an intermixing both of friendship *and* mastery, so definitely a lot of fodder to write about. [The End of Answer 1] [The Start of Answer 2] That’s actually very interesting, I was under the impression efforts were made to make sure slaves couldn’t swim as a means of cutting off potential escape routes via rivers or ponds etc. it makes sense it wasn’t black and white (ha, like it ever was) [The End of Answer 2] [The Start of Reviewer 1’s Evaluation] Answer 1 provides a more detailed and informative response to the question. It suggests that Frederick Douglass could swim, based on his own accounts of his childhood. The answer also provides some context about the conditions of enslaved children and their interactions with white children, which could have included learning to swim together. This answer is coherent and seems to be supported by the information provided. Answer 2, on the other hand, doesn’t directly answer the question. Instead, it offers a personal impression about the general conditions of enslaved people and the potential restrictions on their ability to swim. This answer lacks specific information about Frederick Douglass and doesn’t provide a clear answer to the question. It’s also less coherent than Answer 1, as it doesn’t directly address the question and instead offers a personal opinion. Based on these evaluations, Answer 1 is the better response to the question. 1 [The End of Reviewer 1’s Evaluation] [The Start of Reviewer 2’s Evaluation] Here is my evaluation of the two answers: Answer 1 provides some interesting historical context about the intermixing of white and enslaved children during Douglass’s childhood, and speculates that Douglass may have learned to swim alongside white children during this time. However, the answer does not directly or conclusively state whether Douglass could swim. The answer is coherent but lacks core information to fully address the question. Answer 2 acknowledges the common assumption that slaves were prevented from learning to swim, but speculates that the situation was complex, indicating Douglass may have learned to swim as a child. However, like Answer 1, Answer 2 does not provide a definitive statement on whether Douglass could swim. The answer is coherent but lacks core information. Overall, neither answer provides a conclusive statement supported by evidence on whether Frederick Douglass could swim. Both answers provide some speculative historical context but lack core information to fully address the question. 1 [The End of Reviewer 2’s Evaluation] [System] Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence. In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-4: After reading Reviewer 2’s evaluation, I still maintain my preference for Answer 1. While both answers do not provide a direct, definitive answer to the question, Answer 1 provides more context and uses a quote from Douglass’s own accounts to suggest that he could swim. This gives it a stronger basis in evidence than Answer 2, which only offers a personal impression and speculation. Therefore, Answer 1 is more coherent and contains more core information relevant to the question. 1 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Claude-1: Here is my perspective as Reviewer 2: After considering Reviewer 1’s preference for Answer 1, I still maintain my view that neither answer conclusively addresses whether Frederick Douglass could swim. While Answer 1 provides more historical context and references Douglass’s own writing, it does not contain a direct statement on whether he could swim. Answer 2 is more speculative but also lacks a definitive conclusion. Overall, both answers lack core information needed to fully address the question, despite Answer 1 having a stronger basis in evidence. Given the lack of a conclusive statement in either answer, I do not have a clear preference for one over the other. My view is that more information is needed to determine whether Douglass could swim. 2 [System] You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-4: After considering Reviewer 2’s evaluation, I still stand by my initial preference for Answer 1. While it’s true that neither answer provides a definitive statement on whether Frederick Douglass could swim, Answer 1 does provide more context and uses a quote from Douglass’s own accounts to suggest that he could swim. This gives it a stronger basis in evidence than Answer 2, which only offers a personal impression and speculation. Therefore, Answer 1 is more coherent and contains more core information relevant to the question. 1 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Claude-1: After further discussion, I can see Reviewer 1’s perspective that Answer 1 provides more context and evidence, even without a definitive conclusion. While neither answer conclusively states whether Frederick Douglass could swim, Answer 1 does draw on Douglass’s own accounts and provides historical details suggesting he may have learned as a child. This gives Answer 1 a stronger basis than Answer 2, which is more speculative. Therefore, while I still believe more information is needed for a definitive conclusion, Answer 1 appears to have a stronger grounding in evidence and coherence. On balance, I would lean toward preferring Answer 1 over Answer 2, though neither is fully satisfactory. 1 [System] Thank you for the discussion. Based on the reviews and discussions, Answer 1 is preferred as it provides more context and evidence, though not definitive, to suggest Frederick Douglass could swim. The following example is a discussion between Claude-1 and GPT-4. In this example, Claude-1 alters its opinion after reaching an agreement with GPT-4. Claude-1 GPT-4 Discussion (Claude-1 Leads) System: You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Background: [Question] Why do people go bald on the top of their head and still have some on the sides and not vice-versa? [The Start of Answer 1] There are a few reasons why people go bald on the top of their head and still have some hair on the sides. One reason is that the hair follicles on the top of the head are more sensitive to a hormone called dihydrotestosterone (DHT). DHT is a byproduct of testosterone and is found in both men and women. When DHT levels are high, it can cause the hair follicles on the top of the head to miniaturize, which leads to hair loss. Another reason is that the hair on the sides and back of the head is not as exposed to the sun and other environmental factors, which can damage the hair and lead to hair loss. [The End of Answer 1] [The Start of Answer 2] Seems unsettled but here’s a theory: “The most recent hypothesis suggests that the hair loss process begins during puberty, when growth of the skull and the muscles in the forehead and neck increases the tension in a tight band of tissue stretching over the top of the head. The more DHT (a type of testosterone) there is, the more these muscles contract, which causes inflammation and brings in more DHT. Over time, the DHT thickens the band of tissue, restricting the supply of blood and nutrients to the hair follicles above it. The follicles on top of the head get smaller and eventually disappear, while those on the sides of the head remain largely unaffected.” Source https://www.sciencefocus.com/the-human-body/why-do-men-go-bald-from- the-top- of-their-heads/ [The End of Answer 2] [The Start of Reviewer 1’s Evaluation] Here is my evaluation of the two answers: Answer 1 provides a concise and coherent explanation for male pattern baldness, focusing on the sensitivity of hair follicles on the top of the head to DHT and less exposure to environmental damage. The information seems well supported by scientific research. However, the answer is lacking in depth and does not fully explore other potential contributing factors. Answer 2 proposes an alternative hypothesis that relates balding to increased tension and inflammation in the scalp tissue over time due to skull and muscle growth during puberty, as well as the thickening effects of DHT. This explanation seems more speculative, as the source cited is from a general science magazine rather than peer-reviewed research. The coherence is slightly weaker, as the answer jumps quickly from discussing puberty to DHT without fully connecting the ideas. However, the answer provides an interesting alternative perspective and more depth than Answer 1. Overall, while Answer 1 is more concise and scientifically grounded, Answer 2 explores an alternative, thought-provoking hypothesis and provides a more comprehensive explanation, despite some weaknesses in coherence and evidence. On balance, I would choose Answer 2 as the higher quality response. 2 [The End of Reviewer 1’s Evaluation] [The Start of Reviewer 2’s Evaluation] Answer 1 and Answer 2 both provide explanations for why people tend to go bald on the top of their heads while still retaining hair on the sides. Answer 1 explains that the hair follicles on the top of the head are more sensitive to dihydrotestosterone (DHT), a hormone that can cause hair loss when its levels are high. It also mentions that the hair on the sides and back of the head is less exposed to environmental factors that can damage hair and lead to hair loss. This answer is coherent and provides a scientifically supported explanation for the pattern of hair loss. Answer 2 provides a different theory, suggesting that the process begins during puberty when growth of the skull and muscles in the forehead and neck increases tension in a band of tissue over the top of the head. This tension, combined with the presence of DHT, leads to inflammation and restriction of blood and nutrient supply to the hair follicles, causing them to shrink and eventually disappear. This answer also provides a source for its information, which adds credibility to its explanation. Both answers are coherent and provide core information related to the question. However, Answer 1 provides a more commonly accepted explanation for the pattern of hair loss, while Answer 2 provides a more recent hypothesis that may not be as widely accepted or proven. Neither answer contains unsupported information. Based on the above evaluation, I would choose Answer 1 as it provides a more widely accepted and proven explanation for the pattern of hair loss. 1 [The End of Reviewer 2’s Evaluation] [System] Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence. In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Claude-1: Here is my analysis of the two reviews: Reviewer 1 prefers Answer 2 due to its depth and exploration of an alternative hypothesis, despite some weaknesses in coherence and evidence. Reviewer 2 prefers Answer 1 due to it providing a more scientifically supported and widely accepted explanation. Upon further reflection, I agree with Reviewer 2 that Answer 1 is superior. While Answer 2 proposes an interesting alternative theory, its explanation seems more speculative and not as well supported by scientific evidence. Answer 1 provides a concise yet coherent explanation backed by research on DHT sensitivity and environmental factors. Although Answer 2 explores the topic in more depth, depth alone does not make up for a lack of scientific grounding. Some unsupported information, such as the theory of increased tension and inflammation during puberty leading to balding, weakens its coherence. In contrast, Answer 1 focuses on core information that is well established, leading to a more compelling explanation overall. # Therefore, based on the evaluations, I would choose: # 1 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-4: 1 [System] You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. Claude-1: Upon reviewing the discussion, I do not see a need to change my original preference for Answer 2. While Answer 1 provides a concise and coherent explanation grounded in scientific research, Answer 2 explores an alternative hypothesis in more depth and provides a source to support its theory. Some speculation does not necessarily equate to unsupported information, as long as the ideas are logically connected and backed by credible references where possible. Depth and exploration of alternative perspectives are valuable in building understand- ing. Answer 2 acknowledges the role of DHT while proposing that increased tension and inflammation may also contribute to hair loss over time. This added nuance strengthens rather than weakens its coherence. Answer 1 is a satisfactory explanation but lacks the depth and nuance of Answer 2. Based on the additional discussion, I continue to believe Answer 2 is the higher quality response due to its more comprehensive analysis of the question, despite its more speculative nature. The source provided also lends some credibility to its alternative hypothesis. # Therefore, I maintain my original view that: # 2 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-4: After considering the points made by Reviewer 1, I still stand by my initial preference for Answer 1. While Answer 2 does indeed provide a more in-depth explanation and proposes an alternative theory, it lacks the scientific grounding that Answer 1 has. The theory proposed in Answer 2 is not as widely accepted or proven, which could potentially lead to misinformation. Answer 1, on the other hand, provides a concise, coherent, and scientifically supported explanation for the pattern of hair loss. It focuses on core information related to the question and does not contain any unsupported information. Therefore, I maintain my original choice: 1 The following example is a discussion between GPT-4 and GPT-3.5. In this example, both reviewers hold their opinion all the time. GPT-4 GPT3.5 Discussion (GPT-4 Leads) System: You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Background: How do credit/debit cards work? What is the process of putting money in and getting it out? [The Start of Answer 1] A credit or debit card is basically just an easy way to allow a shop to speak to your bank. First you go into the bank, and you either deposit some cash into your account (debit), or you ask the bank nicely to cover you, and promise that you will pay them back at the end of the month (credit). Then you can go shopping. You get to the till with your products, which you now need to pay for, but instead of handing over cash directly, you ask the shop to deal directly with your bank. The shop phones up the bank and asks them to take X amount of money out of your account, then nip over to the shops own bank and give it to them on your behalf, which they do. That is pretty much how a credit or debit card works, just automated with computers... [The End of Answer 1] [The Start of Answer 2] Debit cards are linked to a bank account and whenever you pay using a debit card, the amount is deducted from the bank account on completion of the transaction. So, instead of withdrawing and handing over cash for a purchase, you can swipe the card. Credit cards come with a credit limit and a defined billing cycle (generally monthly). So, you can make purchases using the credit card upto the defined credit limit. The bill is generated as per the defined billing cycle and you are required to settle it just like the bills for any other utilities. Hope this helps. [The End of Answer 2] [The Start of Reviewer 1’s Evaluation] Both Answer 1 and Answer 2 accurately describe how credit and debit cards work, and neither contains unsupported information. Answer 1 provides a more detailed and narrative explanation, using an analogy of a shop speaking to your bank. It explains the process of depositing money into a bank account (for a debit card) or asking the bank to cover your expenses (for a credit card). It then describes how the shop communicates with your bank to transfer money from your account to the shop’s account. This answer is coherent and easy to understand, especially for someone who may not be familiar with banking terms. Answer 2, on the other hand, is more concise and uses more technical language. It explains that a debit card is linked to a bank account and the amount is deducted from the account when a purchase is made. It also explains that a credit card has a credit limit and a billing cycle, and that you can make purchases up to the credit limit. The bill is then generated and needs to be paid, similar to other utility bills. This answer is also coherent and accurate, but it may be less accessible to someone who is not familiar with banking terms. In terms of core information, both answers explain the basic functions of credit and debit cards. However, Answer 1 provides a more detailed explanation of the process, while Answer 2 is more concise and to the point. In conclusion, both answers are correct and coherent, but Answer 1 provides a more detailed and accessible explanation, while Answer 2 is more concise and uses more technical language. 1 [The End of Reviewer 1’s Evaluation] [The Start of Reviewer 2’s Evaluation] Answer 1: - Unsupported information: The answer includes the statement "you ask the bank nicely to cover you." This statement is subjective and not a factual representation of how credit cards work. - Core information: The answer explains that credit cards allow a shop to communicate with the bank, and it describes the process of the shop requesting money from the bank on behalf of the cardholder. - Coherence: The answer is coherent and provides a clear explanation of the process. Answer 2: - Unsupported information: The answer does not contain any unsupported information. - Core information: The answer explains that debit cards deduct the amount from the bank account immediately, while credit cards have a credit limit and require monthly bill settlement. - Coherence: The answer is coherent and provides a concise explanation of how debit and credit cards work. Based on the evaluation, both answers contain core information and are coherent. However, answer 1 includes unsupported information, while answer 2 does not. Therefore, answer 2 is the more accurate and reliable response. 2 [The End of Reviewer 2’s Evaluation] [System] Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence. In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-4: After reading Reviewer 2’s evaluation, I understand their point about the subjective language used in Answer 1. However, I still believe that the analogy used in Answer 1 is helpful for someone who may not be familiar with banking terms, and it does not detract from the core information or coherence of the answer. Therefore, I maintain my preference for Answer 1 due to its detailed and accessible explanation. 1 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-3.5: After considering the points made by Reviewer 1, I agree that the subjective language used in Answer 1 could be seen as unsupported information. Additionally, Answer 2 provides a concise and accurate explanation without any unsupported information. Therefore, I have changed my preference to Answer 2. 2 [System] You are reviewer 1, discussing with reviewer 2 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-4: After considering Reviewer 2’s points, I still believe that Answer 1 provides a more detailed and accessible explanation for someone who may not be familiar with banking terms. The subjective language used does not detract from the core information or coherence of the answer. Therefore, I maintain my preference for Answer 1. 1 [System] You are reviewer 2, discussing with reviewer 1 about your reviews of the following answers. Read the reviews and discussions above, and make a decision if to change your preference, and explain. Remember we focus on unsupported information, core information and coherence In a new line, choose between answer 1 and answer 2 by outputting the number 1 or 2 respectively. Do not output anything else other than the number in this last line. GPT-3.5: After considering Reviewer 1’s points, I understand their perspective on the accessibility of Answer 1. While the subjective language used may not necessarily detract from the core information or coherence, it is important to prioritize accuracy and reliability in providing information. Therefore, I am changing my preference to Answer 2, which provides a concise and accurate explanation without any unsupported information. 2
Title: Learned Step Size Quantization: Summary: Deep networks run with low precision operations at inference time offer power and space advantages over high precision alternatives, but need to overcome the challenge of maintaining high accuracy as precision decreases. Here, we present a method for training such networks, Learned Step Size Quantization, that achieves the highest accuracy to date on the ImageNet dataset when using models, from a variety of architectures, with weights and activations quantized to 2-, 3- or 4-bits of precision, and that can train 3-bit models that reach full precision baseline accuracy. Our approach builds upon existing methods for learning weights in quantized networks by improving how the quantizer itself is configured. Specifically, we introduce a novel means to estimate and scale the task loss gradient at each weight and activation layer's quantizer step size, such that it can be learned in conjunction with other network parameters. This approach works using different levels of precision as needed for a given system and requires only a simple modification of existing training code. ICLR 2020 # LEARNED STEP SIZE QUANTIZATION Steven K. Esser ∗, Jeffrey L. McKinstry, Deepika Bablani, Rathinakumar Appuswamy, Dharmendra S. Modha IBM Research San Jose, California, USA # ABSTRACT Deep networks run with low precision operations at inference time offer power and space advantages over high precision alternatives, but need to overcome the challenge of maintaining high accuracy as precision decreases. Here, we present a method for training such networks, Learned Step Size Quantization, that achieves the highest accuracy to date on the ImageNet dataset when using models, from a variety of architectures, with weights and activations quantized to 2-, 3- or 4-bits of precision, and that can train 3-bit models that reach full precision baseline accuracy. Our approach builds upon existing methods for learning weights in quantized networks by improving how the quantizer itself is configured. Specifically, we introduce a novel means to estimate and scale the task loss gradient at each weight and activation layer’s quantizer step size, such that it can be learned in conjunction with other network parameters. This approach works using different levels of precision as needed for a given system and requires only a simple modification of existing training code. # INTRODUCTION Deep networks are emerging as components of a number of revolutionary technologies, including image recognition (Krizhevsky et al., 2012), speech recognition (Hinton et al., 2012), and driving assistance (Xu et al., 2017). Unlocking the full promise of such applications requires a system perspective where task performance, throughput, energy-efficiency, and compactness are all critical considerations to be optimized through co-design of algorithms and deployment hardware. Current research seeks to develop methods for creating deep networks that maintain high accuracy while reducing the precision needed to represent their activations and weights, thereby reducing the computation and memory required for their implementation. The advantages of using such algorithms to create networks for low precision hardware has been demonstrated in several deployed systems (Esser et al., 2016; Jouppi et al., 2017; Qiu et al., 2016). It has been shown that low precision networks can be trained with stochastic gradient descent by updating high precision weights that are quantized, along with activations, for the forward and backward pass (Courbariaux et al., 2015; Esser et al., 2016). This quantization is defined by a mapping of real numbers to the set of discrete values supported by a given low precision representation (often integers with 8-bits or less). We would like a mapping for each quantized layer that maximizes task performance, but it remains an open question how to optimally achieve this. To date, most approaches for training low precision networks have employed uniform quantizers, which can be configured by a single step size parameter (the width of a quantization bin), though more complex nonuniform mappings have been considered (Polino et al., 2018). Early work with low precision deep networks used a simple fixed configuration for the quantizer (Hubara et al., 2016; Esser et al., 2016), while starting with Rastegari et al. (2016), later work focused on fitting the quantizer to the data, either based on statistics of the data distribution (Li & Liu, 2016; Zhou et al., 2016; Cai et al., 2017; McKinstry et al., 2018) or seeking to minimize quantization error during training (Choi et al., 2018c; Zhang et al., 2018). Most recently, work has focused on using backpropagation with ∗corresponding author sesser@us.ibm.com 1 Published as a conference paper at ICLR 2020 Table 1: Comparison of low precision networks on ImageNet. Techniques compared are QIL (Jung et al., 2018), FAQ (McKinstry et al., 2018), LQ-Nets (Zhang et al., 2018), PACT (Choi et al., 2018b), Regularization (Choi et al., 2018c), and NICE (Baskin et al., 2018). Top-1 Accuracy @ Precision Top-5 Accuracy @ Precision Network Method 2 3 4 8 2 3 4 8 ResNet-18 Full precision: 70.5 Full precision: 89.6 LSQ (Ours) QIL FAQ LQ-Nets PACT NICE Regularization 67.6 65.7 64.9 64.4 61.7 70.2 69.2 68.2 68.1 67.7 71.1 70.1 69.8 69.3 69.2 69.8 67.3 71.1 70.0 68.1 87.6 85.9 85.6 84.4 89.4 87.9 88.2 87.9 90.0 89.1 88.8 89.0 89.21 87.9 90.1 89.3 88.2 ResNet-34 Full precision: 74.1 Full precision: 91.8 LSQ (Ours) QIL LQ-Nets NICE FAQ 71.6 70.6 69.8 73.4 73.1 71.9 71.7 74.1 73.7 73.5 73.3 74.1 73.7 90.3 89.1 91.4 90.2 90.8 91.7 91.4 91.3 91.8 91.6 ResNet-50 Full precision: 76.9 Full precision: 93.4 LSQ (Ours) PACT NICE FAQ LQ-Nets 73.7 72.2 71.5 75.8 75.3 75.1 74.2 76.7 76.5 76.5 76.3 75.1 76.8 76.5 91.5 90.5 90.3 92.7 92.6 92.3 91.6 93.2 93.2 93.3 92.9 92.4 93.4 93.1 ResNet-101 Full precision: 78.2 Full precision: 94.1 LSQ (Ours) 76.1 77.5 78.3 78.1 92.8 93.6 94.0 94.0 ResNet-152 Full precision: 78.9 Full precision: 94.3 LSQ (Ours) FAQ 76.9 78.2 78.5 78.4 78.5 78.5 93.2 93.9 94.1 94.1 94.2 94.1 VGG-16bn Full precision: 73.4 Full precision: 91.5 LSQ (Ours) FAQ 71.4 73.4 74.0 73.9 73.5 73.7 90.4 91.5 92.0 91.7 91.6 91.6 Full precision: 67.3 Full precision: 87.8 stochastic gradient descent to learn a quantizer that minimizes task loss (Zhu et al., 2016; Mishra & Marr, 2017; Choi et al., 2018b;a; Jung et al., 2018; Baskin et al., 2018; Polino et al., 2018). While attractive for their simplicity, fixed mapping schemes based on user settings place no guarantees on optimizing network performance, and quantization error minimization schemes might perfectly minimize quantization error and yet still be non optimal if a different quantization mapping actually minimizes task error. Learning the quantization mapping by seeking to minimize task loss is appealing to us as it directly seeks to improve on the metric of interest. However, as the quantizer itself is discontinuous, such an approach requires approximating its gradient, which existing methods have done in a relatively coarse manner that ignore the impact of transitions between quantized states (Choi et al., 2018b;a; Jung et al., 2018). Here, we introduce a new way to learn the quantization mapping for each layer in a deep network, Learned Step Size Quantization (LSQ), that improves on prior efforts with two key contributions. First, we provide a simple way to approximate the gradient to the quantizer step size that is sensitive to quantized state transitions, arguably providing for finer grained optimization when learning the step size as a model parameter. Second, we propose a simple heuristic to bring the magnitude of step size updates into better balance with weight updates, which we show improves convergence. The overall approach is usable for quantizing both activations and weights, and works with existing methods for backpropagation and stochastic gradient descent. Using LSQ to train several network architectures on 2 Published as a conference paper at ICLR 2020 the ImageNet dataset, we demonstrate significantly better accuracy than prior quantization approaches (Table 1) and, for the first time that we are aware of, demonstrate the milestone of 3-bit quantized networks reaching full precision network accuracy (Table 4). # 2 METHODS We consider deep networks that operate at inference time using low precision integer operations for computations in convolution and fully connected layers, requiring quantization of the weights and activations these layers operate on. Given data to quantize v, quantizer step size s, the number of positive and negative quantization levels QP and QN , respectively, we define a quantizer that computes ¯v, a quantized and integer scaled representation of the data, and ˆv, a quantized representation of the data at the same scale as v: 0 = |clip(*/s, -Qn,Qp)], (1) b=oxs. (2) Here, clip(z,r1, 172) returns z with values below rj set to r; and values above rg set to rz, and | z] rounds z to the nearest integer. Given an encoding with b bits, for unsigned data (activations) Qyv = 0 and Qp = 2° — 1 and for signed data (weights) Qy = 2°-! and Qp = 2°"! — 1. For inference, ¯w and ¯x values can be used as input to low precision integer matrix multiplication units underlying convolution or fully connected layers, and the output of such layers then rescaled by the step size using a relatively low cost high precision scalar-tensor multiplication, a step that can potentially be algebraically merged with other operations such as batch normalization (Figure 1). Offline Quantizer Matrix Multiplication Layer iplier Quantizer me GH Low Precision Figure 1: Computation of a low precision convolution or fully connected layer, as envisioned here. 2.1 STEP SIZE GRADIENT LSQ provides a means to learn s based on the training loss by introducing the following gradient through the quantizer to the step size parameter: op [TA +LAL if-Qn <*/s < Qp 3s 7) 7 2N if °/s < —Qn (3) : Qp if /s > Qp This gradient is derived by using the straight through estimator (Bengio et al., 2013) to approximate the gradient through the round function as a pass through operation (though leaving the round itself in place for the purposes of differentiating down stream operations), and differentiating all other operations in Equations 1 and 2 normally. This gradient differs from related approximations (Figure 2), which instead either learn a transforma- tion of the data that occurs completely prior to the discretization itself (Jung et al., 2018), or estimate the gradient by removing the round operation from the forward equation, algebraically canceling terms, and then differentiating such that ∂ ˆv/∂s = 0 where −QN < v/s < QP (Choi et al., 2018b;a). In both such previous approaches, the relative proximity of v to the transition point between quantized states does not impact the gradient to the quantization parameters. However, one can reason that the 3 Published as a conference paper at ICLR 2020 Transition Transition Transition Transition Transition Transition 0 Rn Loin” 2 Paine” 3 4 0 point” Laine” — 2 Point” 3 v v Figure 2: Given s = 1, QN = 0, QP = 3, A) quantizer output and B) gradients of the quantizer output with respect to step size, s, for LSQ, or a related parameter controlling the width of the quantized domain (equal to s(QP + QN )) for QIL (Jung et al., 2018) and PACT (Choi et al., 2018b). The gradient employed by LSQ is sensitive to the distance between v and each transition point, whereas the gradient employed by QIL (Jung et al., 2018) is sensitive only to the distance from quantizer clip points, and the gradient employed by PACT (Choi et al., 2018b) is zero everywhere below the clip point. Here, we demonstrate that networks trained with the LSQ gradient reach higher accuracy than those trained with the QIL or PACT gradients in prior work. closer a given v is to a quantization transition point, the more likely it is to change its quantization bin (¯v) as a result of a learned update to s (since a smaller change in s is required), thereby resulting in a large jump in ˆv. Thus, we would expect ∂ ˆv/∂s to increase as the distance from v to a transition point decreases, and indeed we observe this relationship in the LSQ gradient. It is appealing that this gradient naturally falls out of our simple quantizer formulation and use of the straight through estimator for the round function. For this work, each layer of weights and each layer of activations has a distinct step size, represented as an fp32 value, initialized to 2(!"l)/y@p, computed on either the initial weights values or the first batch of activations, respectively. 2.2 STEP SIZE GRADIENT SCALE It has been shown that good convergence is achieved during training where the ratio of average update magnitude to average parameter magnitude is approximately the same for all weight layers in a network (You et al., 2017). Once learning rate has been properly set, this helps to ensure that all updates are neither so large as to lead to repeated overshooting of local minima, nor so small as to lead to unnecessarily long convergence time. Extending this reasoning, we consider that each step size should also have its update magnitude to parameter magnitude proportioned similarly to that of weights. Thus, for a network trained on some loss function L, the ratio VsE / ||VwLll 8 ||w| R= (4) should on average be near 1, where ||z|| denotes the Jj-norm of z. However, we expect the step size parameter to be smaller as precision increases (because the data is quantized more finely), and step size updates to be larger as the number of quantized items increases (because more items are summed across when computing its gradient). To correct for this, we multiply the step size loss by a gradient scale, g, where for weight step size g = 1//NwQp and for activation step size g = 1/VNrQp, where Nw is the number of weights in a layer and Ny is the number of features in a layer. In section|3.4|we demonstrate that this improves trained accuracy, and we provide reasoning behind the specific scales chosen in the Section[AJof the Appendix. 2.3 TRAINING Model quantizers are trained with LSQ by making their step sizes learnable parameters with loss gradient computed using the quantizer gradient described above, while other model parameters can be trained using existing techniques. Here, we employ a common means of training quantized networks (Courbariaux et al., 2015), where full precision weights are stored and updated, quantized weights 4 4 Published as a conference paper at ICLR 2020 and activations are used for forward and backward passes, the gradient through the quantizer round function is computed using the straight through estimator (Bengio et al., 2013) such that Oo {i if -—Qy <%/s<Qp Ov 0 otherwise, (5) and stochastic gradient descent is used to update parameters. For simplicity during training, we use ˆv as input to matrix multiplication layers, which is algebraically equivalent to the previously described inference operations. We set input activations and weights to either 2-, 3-, 4-, or 8-bit for all matrix multiplication layers except the first and last, which always use 8-bit, as making the first and last layers high precision has become standard practice for quantized networks and demonstrated to provide a large benefit to performance. All other parameters are represented using fp32. All quantized networks are initialized using weights from a trained full precision model with equivalent architecture before fine-tuning in the quantized space, which is known to improve performance (Sung et al., 2015; Zhou et al., 2016; Mishra & Marr, 2017; McKinstry et al., 2018). Networks were trained with a momentum of 0.9, using a softmax cross entropy loss function, and cosine learning rate decay without restarts (Loshchilov & Hutter, 2016). Under the assumption that the optimal solution for 8-bit networks is close to the full precision solution (McKinstry et al., 2018), 8-bit networks were trained for 1 epoch while all other networks were trained for 90 epochs. The initial learning rate was set to 0.1 for full precision networks, 0.01 for 2-, 3-, and 4-bit networks and to 0.001 for 8-bit networks. All experiments were conducted on the ImageNet dataset (Russakovsky et al., 2015), using pre-activation ResNet (He et al., 2016), VGG (Simonyan & Zisserman, 2014) with batch norm, or SqueezeNext (Gholami et al., 2018). All full precision networks were trained from scratch, except for VGG-16bn, for which we used the pretrained version available in the PyTorch model zoo. Images were resized to 256 × 256, then a 224 × 224 crop was selected for training, with horizontal mirroring applied half the time. At test time, a 224 × 224 centered crop was chosen. We implemented and tested LSQ in PyTorch. 3 RESULTS 3.1 WEIGHT DECAY We expect that reducing model precision will reduce a model’s tendency to overfit, and thus also reduce the regularization in the form of weight decay necessary to achieve good performance. To investigate this, we performed a hyperparameter sweep on weight decay for ResNet-18 (Table 2), and indeed found that lower precision networks reached higher accuracy with less weight decay. Performance was improved by reducing weight decay by half for the 3-bit network, and reducing it by a quarter for the 2-bit network. We used these weight decay values for all further experiments. Table 2: ResNet-18 top-1 accuracy for various weight decay values. 66.9 67.3 67.6 67.4 70.1 70.2 70.0 66.9 71.0 70.9 70.9 70.8 71.1 71.1 71.0 71.0 3.2 COMPARISON WITH OTHER APPROACHES We trained several networks using LSQ and compare accuracy with other quantized networks and full precision baselines (Table 1). To facilitate comparison, we only consider published models that quantize all convolution and fully connected layer weights and input activations to the specified precision, except for the first and last layers which may use higher precision (as for the LSQ models). In some cases, we report slightly higher accuracy on full precision networks than in their original publications, which we attribute to our use of cosine learning rate decay (Loshchilov & Hutter, 2016). 5 Published as a conference paper at ICLR 2020 We found that LSQ achieved a higher top-1 accuracy than all previous reported approaches for 2-, 3- and 4- bit networks with the architectures considered here. For nearly all cases, LSQ also achieved the best-to-date top-5 accuracy on these networks, and best-to-date accuracy on 8-bit versions of these networks. In most cases, we found no accuracy advantage to increasing precision from 4-bit to 8-bit. It is worth noting that the next best low precision method (Jung et al., 2018) used progressive fine tuning (sequentially training a full precision to 5-bit model, then the 5-bit model to a 4-bit model, and so on), significantly increasing training time and complexity over our approach which fine tunes directly from a full precision model to the precision of interest. It is interesting to note that when comparing a full precision to a 2-bit precision model, top-1 accuracy drops only 2.9 for ResNet-18, but 14.0 for SqueezeNext-23-2x. One interpretation of this is that the SqueezeNext architecture was designed to maximize performance using as few parameters as possible, which may have placed it at a design point extremely sensitive to reductions in precision. 3.3 ACCURACY VS. MODEL SIZE For a model size limited application, it is important to choose the highest performing model that fits within available memory limitations. To facilitate this choice, we plot here network accuracy against corresponding model size (Figure 3). We can consider the frontier of best performance for a given model size of the architectures considered here. On this metric, we can see that 2-bit ResNet-34 and ResNet-50 networks offer an absolute advantage over using a smaller network, but with higher precision. We can also note that at all precisions, VGG-16bn exists below this frontier, which is not surprising as this network was developed prior to a number of recent innovations in achieving higher performance with fewer parameters. ResNet-152 ResNet-101 ResNet-50 ~ a ResNet-34 VGG-16bn ~ fo) ResNet-18 —_—<e SqueezeNext-23-2x Top-1 Accuracy a & / Full Precision Model Sizes (MB) Precision 60 ResNet-18: 45 / fests . 2 / 2 a3 55 / . 4 é SqueezeNext-23-2x: 10 . 1 2 4 8 16 32 64 128 Model Size (MB) Figure 3: Accuracy vs. model size for the networks considered here show some 2-bit networks provide the highest accuracy at a given model size. Full precision model sizes are inset for reference. 3.4 STEP SIZE GRADIENT SCALE IMPACT To demonstrate the impact of the step size gradient scale (Section 2.2), we measured R (see Equation 4) averaged across 500 iterations in the middle of the first training epoch for ResNet-18, using different step size gradient scales (the network itself was trained with the scaling as described in the methods to avoid convergence problems). With no scaling, we found that relative to parameter size, updates to step size were 2 to 3 orders of magnitude larger than updates to weights, and this imbalance increased with precision, with the 8-bit network showing almost an order of magnitude greater imbalance than the 2-bit network (Figure 4, left). Adjusting for the number of weights per layer (g = 1/√ NW ), the imbalance between step size and weights largely went away, through the imbalance across precision remained (Figure 4, center). Adjusting for the number of number of weights per layer and precision (g = 1/√ NW QP ), this precision dependent imbalance was largely removed as well (Figure 4, right). We considered network accuracy after training a 2-bit ResNet-18 using different step size gradient scales (Table 3). Using the network with the full gradient scale (g = 1/√ NF QP 6 Published as a conference paper at ICLR 2020 103 Mm 2-bit > mm 3-bit 10 mm 4-bit « 19 8-bit 10° ————— 1 F F vNy VNule Step size gradient scale Figure 4: Relative parameter update magnitudes given different step size gradient scales. A gradient scale of 1/NW QP better balances relative step size and weight gradient magnitudes (right vs. left). for weight and activation step size respectively) as baseline, we found that adjusting only for weight and feature count led to a 0.3 decrease in top-1 accuracy, and when no gradient scale was applied the network did not converge unless we dropped the initial learning rate. Dropping the initial learning rate in multiples of ten, the best top-1 accuracy we achieved using no gradient scale was 3.4 below baseline, using an initial learning rate of 0.0001. Finally, we found that using the full gradient scaling with an additional ten-fold increase or decrease also reduced top-1 accuracy. Overall, this suggests a benefit to our chosen heuristic for scaling the step size loss gradient. Table 3: Top-1 accuracy for various gradient scale values and learning rates for 2-bit ResNet-18. Gradient scale Learning Rate Accuracy 1/,\/NQp 0.01 67.6 V/VN 0.01 67.3 1 0.01 Did not converge 1 0.0001 64.2 10/.\/NQp 0.01 67.4 1/10, /NQp 0.01 67.3 3.5 COSINE LEARNING RATE DECAY IMPACT We chose to use cosine learning rate decay in our experiments as it removes the need to select learning rate schedule hyperparameters, is available in most training frameworks, and does not increase training time. To facilitate comparison with results in other publications that use step-based learning rate decay, we trained a 2-bit ResNet-18 model with LSQ for 90 epochs, using an initial learning rate of 0.01, which was multiplied by 0.1 every 20 epochs. This model reached a top-1 accuracy of 67.2, a reduction of 0.4 from the equivalent model trained with cosine learning rate decay, but still marking an improvement of 1.5 over the next best training method (see Table 1). 3.6 QUANTIZATION ERROR We next sought to understand whether LSQ learns a solution that minimizes quantization error (the distance between t and v on some metric), despite such an objective not being explicitly encouraged. For this purpose, for a given layer we define the final step size learned by LSQ as § and let S be the set of discrete values {0.015, 0.025, ..., 20.005}. For each layer, on a single batch of test data we computed the value of s € S' that minimizes mean absolute error, (|(6(s) — v)|), mean square error, ((6(s) — v)?), and Kullback-Leibler divergence, [ p(v) log p(v) — J p(v) log q(8(s)) where pand q are probability distributions. For purposes of relative comparison, we ignore the first term of Kullback-Leibler divergence, as it does not depend on ¢, and approximate the second term as —E[log(q(é(s)))], where the expectation is over the sample distribution. 7 Published as a conference paper at ICLR 2020 For a 2-bit ResNet-18 model we found ˆs = 0.949 ± 0.206 for activations and ˆs = 0.025 ± 0.019 for weights (mean ± standard deviation). The percent absolute difference between ˆs and the value of s that minimizes quantization error, averaged across activation layers was 50% for mean absolute error, 63% for mean square error, and 64% for Kullback-Leibler divergence, and averaged across weight layers, was 47% for mean absolute error, 28% for mean square error, and 46% for Kullback-Leibler divergence. This indicates that LSQ learns a solution that does not in fact minimize quantization error. As LSQ achieves better accuracy than approaches that directly seek to minimize quantization error, this suggests that simply fitting a quantizer to its corresponding data distribution may not be optimal for task performance. IMPROVEMENT WITH KNOWLEDGE-DISTILLATION To better understand how well low precision networks can reproduce full precision accuracy, we combined LSQ with same-architecture knowledge distillation, which has been shown to improve low precision network training (Mishra & Marr, 2017). Specifically, we used the distillation loss function of Hinton et al. (2015) with temperature of 1 and equal weight given to the standard loss and the distillation loss (we found this gave comparable results to weighting the the distillation loss two times more or less than the standard loss on 2-bit ResNet-18). The teacher network was a trained full precision model with frozen weights and of the same architecture as the low precision network trained. As shown in Table 4, this improved performance, with top-1 accuracy increasing by up to 1.1 (3-bit ResNet-50), and with 3-bit networks reaching the score of the full precision baseline (see Table 1 for comparison). As a control, we also used this approach to distill from the full precision teacher to a full precision (initially untrained) student with the same architecture, which did not lead to an improvement in the student network accuracy beyond training the student alone. These results reinforce previous work showing that knowledge-distillation can help low precision networks catch up to full precision performance (Mishra & Marr, 2017). Table 4: Accuracy for low precision networks trained with LSQ and knowledge distillation, which is improved over using LSQ alone, with 3-bit networks reaching the accuracy of full precision (32-bit) baselines (shown for comparison). Network 2 Top-1 Accuracy @ Precision 4 3 8 32 2 Top-5 Accuracy @ Precision 4 3 8 32 ResNet-18 ResNet-34 ResNet-50 67.9 72.4 74.6 70.6 74.3 76.9 71.2 74.8 77.6 71.1 74.1 76.8 70.5 74.1 76.9 88.1 90.8 92.1 89.7 91.8 93.4 90.1 92.1 93.7 90.1 91.7 93.3 89.6 91.8 93.4 # 4 CONCLUSIONS The results presented here demonstrate that on the ImageNet dataset across several network archi- tectures, LSQ exceeds the performance of all prior approaches for creating quantized networks. We found best performance when rescaling the quantizer step size loss gradient based on layer size and precision. Interestingly, LSQ does not appear to minimize quantization error, whether measured using mean square error, mean absolute error, or Kullback-Leibler divergence. The approach itself is simple, requiring only a single additional parameter per weight or activation layer. Although our goal is to train low precision networks to achieve accuracy equal to their full precision counterparts, it is not yet clear whether this goal is achievable for 2-bit networks, which here reached accuracy several percent below their full precision counterparts. However, we found that such 2-bit solutions for state-of-the-art networks are useful in that they can give the best accuracy for the given model size, for example, with an 8MB model size limit, a 2-bit ResNet-50 was better than a 4-bit ResNet-34 (Figure 3). This work is a continuation of a trend towards steadily reducing the number of bits of precision necessary to achieve good performance across a range of network architectures on ImageNet. While it is unclear how far it can be taken, it is noteworthy that the trend towards higher performance at lower precision strengthens the analogy between artificial neural networks and biological neural networks, 8 Published as a conference paper at ICLR 2020 which themselves employ synapses represented by perhaps a few bits of information (Bartol Jr et al., 2015) and single bit spikes that may be employed in small spatial and/or temporal ensembles to provide low bit width data representation. Analogies aside, reducing network precision while maintaining high accuracy is a promising means of reducing model size and increasing throughput to provide performance advantages in real world deployed deep networks. # REFERENCES Thomas M Bartol Jr, Cailey Bromer, Justin Kinney, Michael A Chirillo, Jennifer N Bourne, Kristen M Harris, and Terrence J Sejnowski. Nanoconnectomic upper bound on the variability of synaptic plasticity. Elife, 4:e10778, 2015. Chaim Baskin, Natan Liss, Yoav Chai, Evgenii Zheltonozhskii, Eli Schwartz, Raja Girayes, Avi Mendelson, and Alexander M Bronstein. Nice: Noise injection and clamping estimation for neural network quantization. arXiv preprint arXiv:1810.00162, 2018. Yoshua Bengio, Nicholas L´eonard, and Aaron Courville. Estimating or propagating gradients through stochastic neurons for conditional computation. arXiv preprint arXiv:1308.3432, 2013. Zhaowei Cai, Xiaodong He, Jian Sun, and Nuno Vasconcelos. Deep learning with low precision by half-wave gaussian quantization. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 5918–5926, 2017. Jungwook Choi, Pierce I-Jen Chuang, Zhuo Wang, Swagath Venkataramani, Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. Bridging the accuracy gap for 2-bit quantized neural networks (qnn). arXiv preprint arXiv:1807.06964, 2018a. Jungwook Choi, Zhuo Wang, Swagath Venkataramani, Pierce I-Jen Chuang, Vijayalakshmi Srinivasan, and Kailash Gopalakrishnan. Pact: Parameterized clipping activation for quantized neural networks. arXiv preprint arXiv:1805.06085, 2018b. Yoojin Choi, Mostafa El-Khamy, and Jungwon Lee. Learning low precision deep neural networks through regularization. arXiv preprint arXiv:1809.00095, 2018c. Matthieu Courbariaux, Yoshua Bengio, and Jean-Pierre David. Binaryconnect: Training deep neural networks with binary weights during propagations. In Advances in neural information processing systems, pp. 3123–3131, 2015. Steven K. Esser, Paul A. Merolla, John V. Arthur, Andrew S. Cassidy, Rathinakumar Appuswamy, Alexander Andreopoulos, David J. Berg, Jeffrey L. McKinstry, Timothy Melano, Davis R. Barch, Carmelo di Nolfo, Pallab Datta, Arnon Amir, Brian Taba, Myron D. Flickner, and Dharmendra S. Modha. Convolutional networks for fast, energy-efficient neuromorphic computing. Proceedings of the National Academy of Sciences, 113(41):11441–11446, 2016. Amir Gholami, Kiseok Kwon, Bichen Wu, Zizheng Tai, Xiangyu Yue, Peter Jin, Sicheng Zhao, and Kurt Keutzer. Squeezenext: Hardware-aware neural network design. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition Workshops, pp. 1638–1647, 2018. 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, pp. 770–778, 2016. Geoffrey Hinton, Li Deng, Dong Yu, George E Dahl, Abdel-rahman Mohamed, Navdeep Jaitly, Andrew Senior, Vincent Vanhoucke, Patrick Nguyen, Tara N Sainath, et al. Deep neural networks for acoustic modeling in speech recognition: The shared views of four research groups. IEEE Signal processing magazine, 29(6):82–97, 2012. Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the knowledge in a neural network. arXiv preprint arXiv:1503.02531, 2015. Itay Hubara, Matthieu Courbariaux, Daniel Soudry, Ran El-Yaniv, and Yoshua Bengio. Binarized neural networks. In Advances in neural information processing systems, pp. 4107–4115, 2016. 9 Published as a conference paper at ICLR 2020 Sergey Ioffe and Christian Szegedy. Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167, 2015. Norman P Jouppi, Cliff Young, Nishant Patil, David Patterson, Gaurav Agrawal, Raminder Bajwa, Sarah Bates, Suresh Bhatia, Nan Boden, Al Borchers, et al. In-datacenter performance analysis of a tensor processing unit. In Computer Architecture (ISCA), 2017 ACM/IEEE 44th Annual International Symposium on, pp. 1–12. IEEE, 2017. Sangil Jung, Changyong Son, Seohyung Lee, Jinwoo Son, Youngjun Kwak, Jae-Joon Han, and Changkyu Choi. Joint training of low-precision neural network with quantization interval parame- ters. arXiv preprint arXiv:1808.05779, 2018. Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton. Imagenet classification with deep convolu- tional neural networks. In Advances in neural information processing systems, pp. 1097–1105, 2012. F Li and B Liu. Ternary weight networks.(2016). arXiv preprint arXiv:1605.04711, 2016. Ilya Loshchilov and Frank Hutter. Sgdr: Stochastic gradient descent with warm restarts. arXiv preprint arXiv:1608.03983, 2016. Jeffrey L McKinstry, Steven K Esser, Rathinakumar Appuswamy, Deepika Bablani, John V Arthur, Izzet B Yildiz, and Dharmendra S Modha. Discovering low-precision networks close to full- precision networks for efficient embedded inference. arXiv preprint arXiv:1809.04191, 2018. Asit Mishra and Debbie Marr. Apprentice: Using knowledge distillation techniques to improve low-precision network accuracy. arXiv preprint arXiv:1711.05852, 2017. Antonio Polino, Razvan Pascanu, and Dan Alistarh. Model compression via distillation and quantiza- tion. arXiv preprint arXiv:1802.05668, 2018. Jiantao Qiu, Jie Wang, Song Yao, Kaiyuan Guo, Boxun Li, Erjin Zhou, Jincheng Yu, Tianqi Tang, Ningyi Xu, Sen Song, et al. Going deeper with embedded fpga platform for convolutional neural network. In Proceedings of the 2016 ACM/SIGDA International Symposium on Field- Programmable Gate Arrays, pp. 26–35. ACM, 2016. Mohammad Rastegari, Vicente Ordonez, Joseph Redmon, and Ali Farhadi. Xnor-net: Imagenet classification using binary convolutional neural networks. In European Conference on Computer Vision, pp. 525–542. Springer, 2016. Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy, Aditya Khosla, Michael Bernstein, et al. Imagenet large scale visual recognition challenge. International Journal of Computer Vision, 115(3):211–252, 2015. Karen Simonyan and Andrew Zisserman. Very deep convolutional networks for large-scale image recognition. arXiv preprint arXiv:1409.1556, 2014. Wonyong Sung, Sungho Shin, and Kyuyeon Hwang. Resiliency of deep neural networks under quantization. arXiv preprint arXiv:1511.06488, 2015. Huazhe Xu, Yang Gao, Fisher Yu, and Trevor Darrell. End-to-end learning of driving models from large-scale video datasets. In Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 2174–2182, 2017. Yang You, Igor Gitman, and Boris Ginsburg. Large batch training of convolutional networks. arXiv preprint arXiv:1708.03888, 2017. Dongqing Zhang, Jiaolong Yang, Dongqiangzi Ye, and Gang Hua. Lq-nets: Learned quantization for highly accurate and compact deep neural networks. In Proceedings of the European Conference on Computer Vision (ECCV), pp. 365–382, 2018. Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou. Dorefa-net: Train- ing low bitwidth convolutional neural networks with low bitwidth gradients. arXiv preprint arXiv:1606.06160, 2016. Chenzhuo Zhu, Song Han, Huizi Mao, and William J Dally. Trained ternary quantization. arXiv preprint arXiv:1612.01064, 2016. 10 Published as a conference paper at ICLR 2020 # A STEP SIZE GRADIENT SCALE DERIVATION We compute our gradient scale value by first estimating R (Equation 4), starting with the simple heuristic that for a layer with NW weights \wll/s = \/NwQp- (6) To develop this approximation, we first note that the expected value of an /.-norm should grow with the square root of the number of elements normalized. Next, we assume that where Qp = 1, step size should be approximately equal to average weight magnitude so as to split the weight distribution into zero and non zero values in a roughly balanced fashion. Finally, we assume that for larger Q p, step size should be roughly proportional to \/1/Qp, so that as the number of available quantized states increases, data between the clip points will be quantized more precisely, and the clip points themselves (equal to sQy and sQ p) will move further out to better encode outliers. We also note that, in the expectation, ||V,,L|| and VL are of approximately the same order. This can be shown by starting from the chain rule Nw V.L=)> OL Oth; (7) Ow; Os’ i=l i=1 then assuming ∂ ˆwi/∂s is reasonably close to 1 (see for example Figure 2), and treating all ∂L/∂ ˆwi as uncorrelated zero-centered random variables, to compute the following expectation across weights: OL? E[V.L?] ~ Nw x E Ee . (8) By assuming ∂ ˆw/∂w = 1 for most weights, we similarly approximate ay 2 E[||VuLl|?] = Nw xE Ee . Ow 0) Bringing all of this together, we can then estimate Re /NwQp. (10) Knowing this expected imbalance, we compute our gradient scale factor for weights by simply taking the inverse of R, so that g is set to 1/VNwOp. As most activation layers are preceded by batch normalization (Ioffe & Szegedy, 2015), and assuming updates to the learned batch normalization scaling parameter is the primary driver of changes to pre-quantization activations, we can use a similar approach to the above to show that there is an imbalance between step size updates and update driven changes to activations that grows with the number of features in a layer, NF as well as QP . Thus, for activation step size we set g to 1/√ NF QP . # B IMPLEMENTATION In this section we provide pseudocode to facilitate the implementation of LSQ. We assume the use of automatic differentiation, as supported by a number of popular deep learning frameworks, where the desired operations for the training forward pass are coded, and the automatic differentiation engine computes the gradient through those operations in the backward pass. Our approach requires two functions with non standard gradients, gradscale (Function 1) and roundpass (Function 2). We implement the custom gradients by assuming a function called detach that returns its input (unmodified) during the forward pass, and whose gradient during the backward pass is zero (thus detaching itself from the backward graph). This function is used in the form: y = detach(x1 − x2) + x2, (11) so that in the forward pass, y = x1 (as the x2 terms cancel out), while in the backward pass ∂L/∂x1 = 0 (as detach blocks gradient propagation to x1) and ∂L/∂x2 = ∂L/∂y. We also assume a function nf eatures that given an activation tensor, returns the number of features in that tensor, and 11 Published as a conference paper at ICLR 2020 nweights that given a weight tensor, returns the number of weights in that tensor. Finally, the above are used to implement a function called quantize, which quantizes weights and activations prior to their use in each convolution or fully connected layer. The pseudocode provided here is chosen for simplicity of implementation and broad applicability to many training frameworks, though more compute and memory efficient approaches are possible. This example code assumes activations are unsigned, but could be modified to quantize signed activations. # Function 1 gradscale(x, scale): # x: Input tensor # scale: Scale gradient by this yOut = x yGrad = x × scale y = detach(yOut - yGrad) + yGrad # Return yOut in forward, pass gradient to yGrad in backward return y # Function 2 roundpass(x): # x: Input tensor yOut = round(x) # Round to nearest yGrad = x y = detach(yOut - yGrad) + yGrad # Return yOut in forward, pass gradient to yGrad in backward return y # Function 3 quantize(v, s, p, isActivation): # v: Input tensor # s: Step size, a learnable parameter specific to weight or activation layer being quantized # p: Quantization bits of precision # isActivation: True if v is activation tensor, # False if v is weight tensor # Compute configuration values if isActivation: Qn = 0 Qp = 2ˆp - 1 gradScaleFactor = 1 / sqrt(nfeatures(v) × Qp) else: # is weights Qn = -2ˆ(p-1) Qp = 2ˆ(p-1) - 1 gradScaleFactor = 1 / sqrt(nweights(v) × Qp) # Quantize s = gradscale(s, gradScaleFactor) v = v / s v = clip(v, Qn, Qp) vbar = roundpass(v) vhat = vbar × s return vhat 12
Title: AdaPlanner: Adaptive Planning from Feedback with Language Models: Summary: Large language models (LLMs) have recently demonstrated the potential in acting as autonomous agents for sequential decision-making tasks. However, most existing methods either take actions greedily without planning or rely on static plans that are not adaptable to environmental feedback. Consequently, the sequential decision-making performance of LLM agents degenerates with problem complexity and plan horizons increase. We propose a closed-loop approach, AdaPlanner, which allows the LLM agent to refine its self-generated plan adaptively in response to environmental feedback. In AdaPlanner, the LLM agent adaptively refines its plan from feedback with both in-plan and out-of-plan refinement strategies. To mitigate hallucination, we develop a code-style LLM prompt structure that facilitates plan generation across a variety of tasks, environments, and agent capabilities. Furthermore, we propose a skill discovery mechanism that leverages successful plans as few-shot exemplars, enabling the agent to plan and refine with fewer task demonstrations. Our experiments in the ALFWorld and MiniWoB++ environments demonstrate that AdaPlanner outperforms state-of-the-art baselines by 3.73% and 4.11% while utilizing 2x and 600x fewer samples, respectively. # AdaPlanner: Adaptive Planning from Feedback with Language Models Haotian Sun1∗, Yuchen Zhuang1∗∗, Lingkai Kong1, Bo Dai1, Chao Zhang1 1 Georgia Institute of Technology {haotian.sun, yczhuang, lkkong, chaozhang}@gatech.edu, bodai@cc.gatech.edu f{haotian.sun, yczhuang, lkkong, chaozhang}@gatech.edu, bodai@cc.gatech.edu # Abstract Large language models (LLMs) have recently demonstrated the potential in acting as autonomous agents for sequential decision-making tasks. However, most exist- ing methods either take actions greedily without planning or rely on static plans that are not adaptable to environmental feedback. Consequently, the sequential decision- making performance of LLM agents degenerates with problem complexity and plan horizons increase. We propose a closed-loop approach, AdaPlanner, which allows the LLM agent to refine its self-generated plan adaptively in response to environ- mental feedback. In AdaPlanner, the LLM agent adaptively refines its plan from feedback with both in-plan and out-of-plan refinement strategies. To mitigate hallu- cination, we develop a code-style LLM prompt structure that facilitates plan gener- ation across a variety of tasks, environments, and agent capabilities. Furthermore, we propose a skill discovery mechanism that leverages successful plans as few-shot exemplars, enabling the agent to plan and refine with fewer task demonstrations. Our experiments in the ALFWorld and MiniWoB++ environments demonstrate that AdaPlanner outperforms state-of-the-art baselines by 3.73% and 4.11% while uti- lizing 2x and 600x fewer samples, respectively. The implementation of AdaPlanner is available on https://github.com/haotiansun14/AdaPlanner. # Introduction Large language models (LLMs) have recently emerged as versatile autonomous agents for sequen- tial decision-making in grounded environments. Traditional decision-making methodologies like Reinforcement Learning (RL) require extensive task-specific training data and often lack the ability to generalize across tasks and environments. In contrast, LLMs are pre-trained on massive and diverse textual data, which gives them extensive world knowledge and the ability to reason over the knowledge. This makes them highly versatile and able to handle complex, real-world scenarios that may involve multiple steps of planning and decision-making. Existing methods that leverage LLMs as autonomous agents for decision-making can be briefly categorized into two groups (Table 1): open-loop systems and closed-loop systems. Open-loop methods [21, 23, 5, 16, 12, 15, 14] rely on pre-determined plans to accomplish the desired task without any feedback adaptation mechanism. On the other hand, closed-loop systems [22, 6, 9, 19, 10, 17, 20] incorporate environment feedback to continuously monitor system behaviors and make refinements and adjustments of the plans accordingly, which therefore is more flexible. However, both existing open-loop and closed-loop LLM agents have inherent drawbacks. Open-loop systems are computationally cheap and simple; however, they do not consider feedback from the environment and stick to the initial plan, which lack of adaptability, and, thus, can easily generate suboptimal plans. On the other hand, most existing closed-loop methods generate a fixed plan and only update their executing actions upon environment feedback. This causes them to make ∗These authors contributed equally to this work. Methods Feedback Utilization Instruction Type Open-Loop Methods CoT [21] Least-To-Most [23] Zero-Shot Planner [5] HuggingGPT [16] Chameleon [12] - - - - - Prompting Prompting Prompting Prompting Prompting Language Language Language Language Language - Sub-Goals - Sub-Goals Sub-Goals - - - - - Implicit Closed-Loop Methods with Fixed Plan ReAct [22] Inner Monologue [6] RCI [9] ProgPrompt [19] Code as Policies [10] Reflexion [17] Taking Action Taking Action Taking Action Taking Action Taking Action Taking Action Prompting Prompting Prompting Prompting Prompting Prompting Language Language Language Code Code Language - - - - - - - - - - - Past Failure # Prompting Decomposition Experience Refinement Explicit Closed-Loop Methods with Plan Refinement DEPS [20] AdaPlanner Modifying Plan Action & Plan Prompting & Training Language Prompting Code Sub-Goals Sub-Goals Past Failure Past Failure & Success Table 1: A comparison of methods that leverage LLMs for decision making. Each method’s features are reported across five categories: 1) Environment Feedback Utilization: The method can use feedback to decide the next action (Taking Action), revise the entire plan (Modifying Plan), or do both (Action & Plan). 2) Instruction Type: The method may require prompting, training, or both. 3) Prompting Style: The method can employ either natural language or code for its planning backend. 4) Task Decomposition: The method might decompose the task into sub-goals or not. 5) Experience Refinement: The method can learn from past failure, past success, or both. The AdaPlanner proposed in this paper is highlighted in gray. sub-optimal decisions that adapt to the environment in the short term but could have detrimental implications for future steps. DEPS [20] is the only exception, a method that modifies its entire plan based on feedback from the environment. However, it requires training a plan selector to choose the most successful plan, which requires a significant amount of task-specific data. As a result, applying this method to different tasks can be challenging. To address the limitations of existing LLM agents, we propose AdaPlanner, a closed-loop planning method with LLM playing two roles – planner and refiner. The planner decomposes the task into manageable sub-goals and predicts environmental feedback for each. During execution, the refiner distinguishes and responds to two types of environment feedback – in-plan feedback is the environmental observation that aligns with the prediction, and out-of-plan feedback is one that deviates from the prediction. For in-plan feedback, the refiner can dynamically query the LLM to perform reasoning and extract key information from in-plan feedback expressed in natural language. This is achieved through a specific action called ask_LLM(), in which the LLM separately parses the observation and obtains information pertinent to subsequent actions. For out-of-plan feedback, the refiner proactively revises the entire plan and resumes to solve the current task from an intermediate point. AdaPlanner’s adaptive closed-loop framework alleviates the need for prior knowledge about the feedback structure and permits the agent to instantly adopt a refined plan rather than restarting from scratch in a reset episode. This leads to a more efficient and adaptive decision-making process. AdaPlanner operates solely via prompting, eliminating the need for a dedicated training phase and reducing its computational cost. Furthermore, AdaPlanner leverages a code-based prompting for precise planning and refinement. The use of code prompts facilitates task decomposition into sub- goals and mitigates LLM hallucination during the decision-making process. AdaPlanner also features a skill discovery process, which accumulates successful experiences to guide future planning. This feature further enhances its long-term planning ability and sample efficiency. We formally define the planning problem with LLM, and introduce open-loop vs. closed-loop control system, which will motivate our method, in Section 2. Each component of the proposed AdaPlanner is specified in Section 3, including code-based prompting in Section 3.1, closed-loop adaptation in Section 3.2, and skill discovery in Section 3.3, and empirically justified in Section 4. The superior performance of AdaPlanner on both ALFWorld and MiniWoB++ demonstrates our proposed adaptive 2 closed-loop framework can effectively enhance planning performance, even when faced with a limited number of samples. # 2 Preliminaries Problem Formulation. We consider adopting an LLM as an autonomous agent to solve different tasks in text-based environments. For initialization, the agent is provided with allowed actions A in the environment, as well as a text-grounded task definition g ∈ G from the task space G. Besides, the initial state of the environment is also observed as o1 ∈ O from the observation space O. With such inputs, the LLM agent needs to first generate an initial planning policy for solving the task ρ(P0|g, o1) : G × O → ∆(AT ), where T is the total length of steps in the generated plan and ∆(·) is probability simplex function. Also, the agent can interact with the environment for feedback: When the agent interacts with the environment at the t-th step, the agent receives an observation ot ∈ O from the environment and generates a trajectory-like context ct = (o1, a′ t−1, ot), where a′ t−1 are the executed actions within the environment. As the agent may modify the actions according to the feedback, the executed actions a′ t−1 can be different from the actions a1, a2, · · · , at−1 in the initial plan. We denote ρ(·|g, ct, Pt) as the high-level planning policy that generates an entire plan and π(·|g, ct, Pt) as the action-generation policy conditioned on a given plan Pt. Given the context ct and the entire plan at the last step Pt−1, the agent refines future decisions. In the end, the LLM agent should model both the initial planning policy and the environment feedback-conditioned policy to complete the given task successfully. Open-Loop System. An open-loop system is a non-feedback system (Figure 1), where the output is solely dependent on the input, without any consideration of the environmental feedback. Thus, in an open-loop system, the entire initial plan over the time horizon T is predetermined and static by the initial planning policy ρ(·|g, o1), without any feedback-based refinement. Despite their simplicity, open-loop systems are notably vulnerable to environmental changes, as they lack the capacity to adapt or adjust their plans based on environmental feedback. Closed-Loop Systems. On the contrary, a closed-loop system (Figure 1) refers to a planning process that incorporates environment feedback to adjust and refine future decisions, involving both initial planning ρ(·|g, o1) and two levels of feedback-based refinements, ρ(·|g, ct, Pt−1) and π(·|g, ct, Pt−1), in the system. Implicit Closed-Loop Systems. After each step of interaction with the environment, implicit closed- loop systems will maintain the initial plan (i.e., Pt = P0) and only modify a single action based on the feedback. Therefore, the feedback-based refinement is defined as π(a′ t ∈ A is the modified action from action space, while the remaining actions a>t for future steps remain the same as the initial plan. Although locally-optimal actions are adopted at each step, inaccuracies in initial planning can result in task failure or non-completion. Explicit Closed-Loop Systems. Explicit closed-loop systems refine the entire plan based on environ- ment feedback following the policy ρ(Pt|g, ct, Pt−1), where Pt ∈ ∆(AT −t) is the refined plan at time step t containing the modified future actions a′ ≥t to execute and Pt−1 is the old plan modified in the previous time step. Allowing for constant refinement and improvement of the plan, explicit closed-loop systems can help prevent costly mistakes or missed opportunities that might arise from adhering to outdated plans. Our proposed AdaPlanner is an explicit closed-loop system. # 3 AdaPlanner Model Architecture. Our AdaPlanner model, shown in Figure 1, consists of two main components: an LLM-based agent that functions dually as a planner and a plan refiner, and • a skill memory module designed to enhance sample efficiency through skill discovery. The LLM-based agent, in its planner role, generates a comprehensive plan and performs preliminary assessments to determine its feasibility. This initial planning is modeled as ρ(P0|g, o1). As the plan unfolds, the agent also operates as a refiner, conducting feedback-based refinement in both in-plan and out-of-plan manners. In-plan and out-of-plan refinement processes primarily differ in how they impact future actions. In-plan refinement is a one-step action that integrates useful information into the existing plan for better action grounding. After this in-plan phase, future 3 (a, a3,", ap) (1, 1)", Ot, Ae) Planner aed Environment Planner [-——|_ Environment (01,41, Of, Qe Or+4)) Open-Loop Implicit Closed-Loop (04,41,°*, Op, Ap, Or41) extract info from or41 O¢41 aligns with prediction In-Plan Refiner 1 1 1 1 1 1 1 1 coo “ye, a ' (Gy, A2,°*, Ap, G, FG), Atay Ar) | T 1 1 1 1 1 Planner >| Environment Out-of-Plan Refiner Or+1 Violates prediction (Op, ys, Op, ps Op 44) beeen ee eee eee ee ee ee eee ee Explicit Closed-Loop AdaPlanner Figure 1: A comparison between open-loop, implicit closed-loop, and explicit closed-loop systems. actions will be generated using the updated context π(a′ >t|g, c>t ∪ {ht}, P0), where ht represents the new information obtained from ct via in-plan refinement at timestep t. Out-of-plan refinement, on the other hand, leverages environmental feedback to directly revise the entire plan, denoted as ρ(Pt|g, ct, Pt−1). This mechanism allows for comprehensive adjustments to be made to the plan in response to unexpected environmental feedback. Skill memory serves as a repository, archiving past successful plans and their respective interactions with the environment. If the agent encounters a task resembling the skills stored in memory, these skills can serve as few-shot exemplars in the LLM agent’s prompt. This feature improves not only sample efficiency but also reliability for future planning. Environment Interaction. AdaPlanner employs adaptive closed-loop planning and active environ- ment interaction for task solving. It can anticipate environmental observations and proactively refine the plan only when there is a discrepancy between expected and actual outcomes. This is achieved by decomposing the planning process into N manageable sub-goals. During the planning and action- taking process, the agent selects from a set of timestamps, {t1, . . . , tN }, to evaluate the success of each sub-goal. If the sub-goal does not align with the planned prediction at timestep t ∈ {t1, . . . , tN }, the environment actively sends the previous sub-trajectories (o1, a′ t, ot+1) back to the refiner for plan revision. This process allows the agent to check the success status only at N crucial points, thereby reducing computational costs (number of API calls) and enhancing efficiency. # 3.1 Plan Generation via Code-Based LLM Prompting AdaPlanner plans and refines by using Pythonic code prompts for LLMs. Consistent with previous observations [3, 2], we have found that using code prompts instead of natural language prompts for LLMs reduces ambiguity and misinterpretation, which significantly reduces LLM hallucination during plan generation and refinement. We design code prompts during different stages of decision- making, including adaptive planning, feedback generation, and in-episode refinement. We provide a detailed description of the prompts used at each stage in Appendix 8.3. To generate an initial plan for solving a given task, we input a task description, the permissible actions in the environment, and, when available, sample demonstrations of task resolution into LLM. These pieces of information are all formatted into Pythonic code format for LLM prompting. To generate a plan for solving the given task, AdaPlanner is prompted with the task goal, a list of admissible actions, and possibly a few demonstrations. Figure 2 (a) shows an example programming-based plan generated by AdaPlanner for solving a put task in the ALFWorld environment. The generated solution function is provided with two input arguments: the first is the agent object, which encapsulates environmental information to be used by the agent. The second is the variable start_from, which is a parameter indicating the subgoal from which the agent will later resume its execution with a refined plan. By default, the start_from is initialized as 1. The value of this variable can be further reassigned during the refinement. When prompting LLM to generate the code-based plan, we design the prompt to teach LLM to decompose a complex task into sub-goals. As shown in Figure 2(a), the generated code plan solution(agent, start_from=1) consists of: 1) a general plan at the outset that decomposes 4 (a) Initial Plan (extracted) — | Environment | (b) Out-of-plan Feedback (Extracted) def solution(agent, start_from=1): Execution Halt at | Error in [Step 3]: | cannot clean lettuce 2 General _# General plan: | need to get a list of receptacles to find the [Step 3] | using the sinkbasin 1. | am at toilet 1 and plan lettuce, clean it, and put it in a diningtable. ~--------» | holding None. The last three interactions before the error were: # [Step 1] Get a list of receptacles where the lettuce is likely Act: go to sinkbasin 2 Sub-plan 6 appear. Obs: On the sinkbasin 2, you see nothing. if start_from <= 1: Qut-of-plan a ten recep_to_go= literal_eval(ask_LLM(f'Sort Tefine _ {agent.receptacles} in descending order based on the assert recep_to_go, f'Error in [Step 1]: recep_to_go def solution(agent, start_fro1 should not be empty. {agent.report()}' # General plan: | need to get a list of receptacles to find the lettuce, take the lettuce to the sinkbasin, clean it, and put it in a diningtable. # [Step 2] Go to each receptacle in the list until seeing a lettuce # [Step 1] Get a list of receptacles where the lettuce is likely to appear. if start_from <= 2: we for receptacle in recep_to_go: # [Step 2] Go to each receptacle in the list until seeing a lettuce observation = agent.goto(receptacle) a if lettuce’ in observation: # [Step 3] Identify the lettuce I just found and take it break if start_from <= 3: Predict assert ‘lettuce’ in observation, f'Error in [Step 2]: There found_lettuce = ‘lettuce’ + ask_LLM(f'From the observation, get viaassert is no lettuce in/on {recep_to_go}. {agent.report()}' the identifier of the lettuce: {observation}. ') observation = agent.take(found_lettuce, receptacle) # [Step 3] Identify the lettuce I just found and clean it assert agent.holding == found_lettuce, f'Error in [Step 3]: | cannot if start_from <= 3: take {found_lettuce} from the {receptacle}. {agent.report()}" In-plan found_lettuce = ' lettuce’ + ask_LLM(f'From the refine observation, get the identifier of the lettuce: {observation}.’) || # [Step 4] Go to a sinkbasin to clean the lettuce. observation = agent.take(found_lettuce, receptacle) if start_from <= 4: observation = agent.clean(found_lettuce, 'sinkbasin 1') observation = agent.goto('sinkbasin 1') assert ‘clean’ in observation, f'Error in [Step 3]: | cannot observati gent.clean(found_lettuce, 'sinkbasin 1') clean {found_lettuce} using the sinkbasin 1. {agent.report()}' assert ‘clean’ in observation, f'Error in [Step 4]: | cannot clean {found_lettuce} using the sinkbasin 1. {agent.report()}' # [Step 4] Go to a diningtable and put the lettuce on it. on # [Step 5] Go to a diningtable and put the lettuce on it. Figure 2: An illustrative example from ALFWorld to show the proposed adaptive closed-loop planning through code. The task is to put some clean lettuce on the diningtable. The in-plan feedback in (a) is a sentence like On the countertop 2, you see a knife 1, a lettuce 1, a saltshaker 2, and a soapbottle 1. This feedback is managed by the ask_LLM() action. The execution of the initial plan might yield misaligned observations, triggering an out- of-plan feedback and refinement process. For instance, the agent cannot clean the lettuce if it is not currently located at a sinkbasin. The out-of-plan feedback in (b) assists AdaPlanner in generating a revised plan (c) so that the agent will move to a sinkbasin before cleaning the lettuce. AdaPlanner then determines to resume from step 3 within the same episode. The task can be successfully completed using the refined plan. the task into subgoals in the form of comments; and 2) a sequence of sub-plans, each consisting of admissible actions corresponding to a specific subgoal. Such a mechanism allows our method to handle complex, long-horizon tasks by hierarchically decomposing them into sequences of subgoals. Furthermore, each subgoal ends with an assertion statement to test its fulfillment, which allows our method to interact actively with the environment and later resume its execution with a refined plan. # 3.2 Adaptive Closed-Loop Plan Refinement Once an initial plan is generated, AdaPlanner then prompts the LLM to correct any syntax errors. After this, the code undergoes execution through the environment interface. The interface is responsible for grounding the actions in the environment, and also for routing environmental observations back to the code as a return value. This bi-directional flow allows AdaPlanner to adapt and refine its plan in response to environmental observations in a closed-loop manner. In-Plan Feedback and Refinement via ask_LLM() Action. When AdaPlanner observes that the environment is aligned with the anticipated plan, it performs in-plan refinement. This allows it to extract useful information from the observation that can be used for upcoming actions. To achieve this, we provide the agent with an additional action called ask_LLM(), which is used to formulate a plan alongside task-specific actions. The ask_LLM() function enables AdaPlanner to self-query and perform reasoning based on specific information parsed from environmental observations. For instance, in [Step 3] in Figure 2 (a), the ask_LLM() action extracts the identifier of the found 5 object lettuce from the natural-language observation. This information can then be fed into later actions. As an additional atomic action, this in-plan refinement is integrated into the plan at any point where the planner deems a reasoning process is necessary. Existing code-generation-based methods [19, 10, 3] face a challenge in this task, especially when there is no prior knowledge of the structure and organization of these feedback sentences. In contrast, our AdaPlanner method leverages LLM to parse critical information from diverse feedback presented in natural-language sentences to streamline plan execution. Out-of-Plan Refinement with the Refine-Then-Resume Mechanism. After each sub-plan execu- tion, AdaPlanner actively checks an assertion condition to ensure that the current plan is proceeding as expected. If the assertion fails, AdaPlanner performs out-of-plan refinement. For example, in Figure 2 (a), after [Step 3], the agent is expected to hold lettuce. If this condition is not met, AdaPlanner generates an error message that details the current progress of execution gathered by the report() function. In ALFWorld tasks, this function provides a report of the agent’s location, the object it is holding, and the last three interactions with the environment, as shown in Figure 2 (b). AdaPlanner then utilizes this information to perform out-of-plan refinement. During the out-of-plan refinement as in Figure 2 (c), AdaPlanner uses a prompt similar to the one used during the initial planning stage, but with an additional feedback message that reflects the current state. Detailed prompts are provided in Appendix 8.3. AdaPlanner then refines the plan based on the newly acquired information and also determines the value of start_from by comparing the plan before and after the refinement. The newly refined solution() is then executed from the breakpoint start_from. This breakpoint contains all variable states that were saved prior to refinement. Consequently, the current episode can continue from an intermediate checkpoint without restarting from scratch. We call this mechanism refine-then-resume. It significantly speeds up task completion and reduces the number of LLM calls required. # 3.3 Skill Discovery Acquiring expert demonstrations for task solving can be costly, particularly as the number of tasks increases. To address this issue, we have equipped AdaPlanner with a skill discovery feature. This is a memory scheme that discovers and archives successful trajectories, thereby improving planning performance when dealing with similar tasks. The skill discovery process consists of two stages, which can be conducted alternately over several rounds, based on the interaction costs and computation resources. Skill Acquisition. In the first stage, AdaPlanner attempts to solve unseen tasks, leveraging a limited number of human demonstrations of other simpler tasks, or even no demonstrations. The model capitalizes on adaptive closed-loop planning to iteratively explore and refine solutions via a trial-and- error approach. Upon successful completion of a given task, the latest solution and the corresponding interactions are treated as candidate discovered skills. Skill Filtering. In the second stage, we compare the planning performance with and without the integration of the discovered solution into the prompt. If the inclusion of this solution boosts the success rate, it is archived as a discovered skill. Conversely, if it does not improve performance, it is discarded. This filtering stage is crucial because the iterative closed-loop refinement may integrate episode-specific information into the revised solution, potentially compromising its generalizability. # 4 Evaluation We test AdaPlanner on two text-based decision-making environments: 1) ALFWorld [18] is a text-based virtual household environment encompassing six distinct task types set. We evaluate AdaPlanner on a total of 134 tasks across these six types. 2) MiniWoB++ [11] is a simulation environ- ment that covers a large range of computer tasks. We select 9 MiniWoB++ tasks with environmental feedback, and we also adopt and test the 53 tasks evaluated in RCI [9]. Both environments aim to solve complicated challenges with long-horizon solutions and sparse rewards. We also carefully designed ablation studies to justify the significance of each component in AdaPlanner. The Setup details and prompts for AdaPlanner are depicted in Appendix 8.1 and 8.3. Detailed introductions to each baseline are presented in Appendix 8.2 Note that we evaluate different baselines for these two 6 Method Pick Clean Heat Cool Examine Pick two All (134 tasks) Training-Based Methods BUTLER [18] 46.00 39.00 74.00 100.00 22.00 24.00 37.00 Implicit Closed-Loop Methods with Fixed Plan ReAct [22] (GPT-3) ReAct [22] (GPT-3.5) Reflexion [17] (GPT-3 + 3.5) Reflexion [17] (GPT-3.5) 66.67 37.50 75.00 50.00 41.94 91.03 64.52 69.57 90.32 91.30 41.94 65.22 80.95 42.86 90.48 52.38 55.56 38.89 88.89 66.67 35.29 17.65 94.12 47.06 61.94 47.76 88.06 52.99 Explicit Closed-Loop Methods with Plan Refinement AdaPlanner (GPT-3) AdaPlanner (GPT-3.5) 100.00 96.77 95.65 100.00 93.65 93.55 69.57 77.78 100.00 62.96 47.06 78.43 91.79 80.60 Table 2: Success rate (%) of tested methods on six ALFWorld tasks. For ReAct and AdaPlanner, GPT-3.5 refers to gpt-3.5-turbo, while GPT-3 represents text-davinci-002. For Reflexion, GPT-3.5 indicates gpt-3.5-turbo. GPT-3+3.5 is used in the original Reflexion implementation, which utilizes both GPT-3 (text-davinci-002) and GPT-3.5 (text-davinci-003) for action generation and failure reflection, respectively. Our AdaPlanner method is prompted with one specific example per task, making up six demonstrations in total. This is half the number of samples used in React and Reflection. The best-performing results are marked in bold. The results of our method are colored in gray. benchmarks. These methods utilize task-specific samples for prompting or training purposes, thus necessitating separate evaluations for each benchmark. Main Results. AdaPlanner consistently outperforms the existing baselines, achieving state-of-the-art performance, i.e., an overall success rate of 91.79% in ALFWorld tasks (Table 2) and 91.11% in MiniWoB++ tasks with feedback (Table 3). Specifically, in ALFWorld, AdaPlanner equipped with GPT-3 achieves a remarkable success rate exceeding 95% in the majority of individual tasks. It also surpasses all other baselines in the Pick, Clean, and Examine tasks. Notably, even in the task with the lowest performance (Pick two), AdaPlanner still outperforms BUTLER and ReAct. In the MiniWoB++ environment, AdaPlanner demonstrates superiority over all other methods on tasks that provide feedback. This superior performance suggests that AdaPlanner effectively leverages feedback to refine its plans and enhance its performance. Furthermore, AdaPlanner maintains competitive performance on tasks without feedback, achieving a success rate of 93.22%. Note that AdaPlanner’s success rates of tasks without feedback are still comparable to CC-Net, the state-of-the-art model requiring over 23,000 samples per task. This result highlights the efficacy of the programming-based planning strategy employed by AdaPlanner. In both environments, AdaPlanner consistently delivers superior or competitive performance when compared to not only training-based methods but also implicit closed-loop methods under the same LLM models. These results affirm the effectiveness of the proposed explicit closed-loop plan refinement in AdaPlanner. Furthermore, we summarize the re- lationship between success rate (%) and the number of samples in Fig- In ALFWorld, AdaPlan- ure 3. ner yields the highest performance with the fewest number of samples. In MiniWoB++, our method outper- forms most baselines. Notably, our method achieves performance com- parable to CC-Net but requires 600 times fewer samples. This study highlights that AdaPlanner signifi- cantly reduces the need for extensive demonstrations or expert trajectories, thereby offering a more resource- efficient solution. (a) ALFWorld (b) MiniWoB++ Figure 3: Relationship between success rate (%) and the num- ber of expert demonstrations in ALFWorld and MiniWoB++ environments. We adopt the same settings as in Table 2 (GPT- 3 version) and Table 3. The top-left corner represents the pinnacle of sample efficiency. 7 Training-Based Methods CC-Net [7] WGE [11] 87.00 67.60 95.66 87.93 94.00 86.00 Finetuning-Based Methods WebN-T5-3B [4] 38.50 54.67 52.00 Implicit Closed-Loop Methods with Fixed Plan RCI [9] 81.56 92.68 91.00 Explicit Closed-Loop Methods with Plan Refinement AdaPlanner 91.11 93.22 92.87 Table 3: Success rate (%) of tested methods on two subsets of tasks in the MiniWoB++ environment. RCI and AdaPlanner harness GPT-3.5 (text-davinci-003) as backends. Our AdaPlanner method is provided with 38 human-written demonstrations; then, it automatically discovers 21 additional examples via skill discovery, which makes up the final set of 59 examples for 53 tasks. This is around half the number of samples used in RCI and over one six hundredths of the number of samples used in CC-Net. The best-performing results are marked in bold. The results of our AdaPlanner are colored in gray. Per-task success rates are provided in Appendix 8.5. Adaptive Closed-Loop Architecture Enhances Planning Performance. Figure 4a shows the performance v.s. the number of closed-loop refinements, under settings with different numbers of demo samples. The detailed example selection for this study is provided in Appendix 8.1. We observe a significant trend of increased success rates corresponding to each subsequent closed-loop plan refinement. This indicates the AdaPlanner’s ability to consistently leverage real-time feedback for performance enhancement, regardless of the number of samples used. Remarkably, AdaPlanner maintains this trend of success rate enhancement even when the total number of demonstrations across all six tasks is as low as two. Moreover, a comparison with Reflexion, depicted in Figure 4b, shows AdaPlanner’s consistently superior performance across all iterations of closed-loop corrections. These observations highlight AdaPlanner’s sample efficiency and its potential for real-world applications where the number of available demonstrations is limited. Code Interface Mitigates Hallucination. The latest gpt-3.5-turbo is reported to be the most capable GPT-3.5 model while reducing the cost by a tenth compared to other prevailing GPT-3 [1] and 3.5 models [13] (e.g., text-davinci-002 and text-davinci-003.) However, our findings from Table 2 indicate that gpt-3.5-turbo underperforms in decision-making tasks relative to its predecessors, i.e., text-davinci-002, in all LLM-agents. Upon examination of trajectories from both models, we observed a noticeable hallucination with GPT-3.5 (gpt-3.5-turbo), as shown in Appendix 8.4. We hypothesize that gpt-3.5-turbo might be a smaller-scale model that is more prone to hallucination. Despite this, AdaPlanner demonstrates a remarkable level of resilience against hallucination even with gpt-3.5-turbo (Table 2), while ReAct and Reflexion are more sensitive to the hallucination issue. AdaPlanner’s resilience against hallucination can be attributed to its use of code prompts, which provide a more formal and constrained generation space for LLM. For comparison, we implement an ablation version of AdaPlanner without the code interface by translating solution examples directly into plans and actions using natural language. Without the code interface, AdaPlanner’s performance substantially drops in both ALFWorld and MiniWoB++ environments (Figure 4c), from 81% to 46% and from 93% to 66%, respectively. This significant performance drop underscores the essential role of the code interface in AdaPlanner. Skill Discovery Improves Sample Efficiency. The skill discovery in AdaPlanner utilizes a long-term memory mechanism that retains successful solutions, thus boosting planning performance when faced with similar tasks. An ablation study depicted in Figure 4d compares the performance of AdaPlanner with and without the implementation of skill discovery. In the skill acquisition stage, we provide a maximum of one demonstration. In ALFWorld, AdaPlanner is prompted with only one expert demonstration of the simplest task (put). We evaluate the average success rate of the method on the remaining five tasks, which are comparatively more challenging and require additional steps for completion. In MiniWoB++, we apply zero-shot prompting, omitting any examples in the 8 (a) (b) (c) (d) Figure 4: Performance comparison on 134 ALFWorld tasks in different cases. We adopt the same settings as in Table 2. (a) and (b) presents the success rate (%) with different numbers of closed-loop corrections: (a) compares AdaPlanner with different numbers of samples; (b) compares AdaPlanner and Reflexion with two LLMs. (c) shows the success rate (%) of AdaPlanner with and without code interface (CI). (d) shows the success rate (%) of AdaPlanner with and without skill discovery (SD). Note that for (a), the number signifies the total number of samples used across all six tasks. skill acquisition phase. For both environments, we operate the method using GPT-3.5 in adaptive closed-loop mode, and one round of skill discovery is conducted. As Figure 4d illustrates, the inclusion of skill discovery significantly enhances performance. In the ALFWorld tasks, the success rate of AdaPlanner nearly doubles when skill discovery is employed. Similarly, in the MiniWoB++ tasks, the overall success rate increases by approximately 15% with skill discovery. # 5 Related Work Many works have studied how to leverage LLMs as autonomous agents to accomplish decision- making tasks within text-based environments. Earlier studies, like Chain-of-Thoughts [21] and Zero-Shot Planner [5], utilize prompts to guide LLMs in generating complete action sequences for elementary tasks. For more complex tasks, methods like HuggingGPT [16] and Chameleon [12] also generate the initial plan of using different tools and then call the corresponding APIs for execution. However, all these plans are created in an open-loop fashion without adapting to feedback from external environments. To address the limitations of open-loop systems, recent techniques have emerged that focus on establishing closed-loop systems. These systems are capable of leveraging environmental feedback, thereby facilitating more adaptive decision-making. ReAct [22] and Inner Monologue [6] allow LLM agents to take single-step actions according to the environmental feedback. Reflexion [17], as an extension of ReAct, tries to resolve this issue by enabling the ReAct agent to revise itself from past trials and errors. Moreover, RCI [9] starts by formulating a comprehensive plan, modifying the immediate action when the agent encounters a failure at the current step. While all the aforementioned methods can adapt their decisions based on environmental feedback, they assume the LLM-generated initial plan is correct and do not adjust it. Rather, they solely modify the immediate action being executed and are easy to fall into local sub-optimal actions without considering the long-term plans. To further enhance the agents’ both capabilities of planning and adapting to environmental feedback, strict closed-loop architectures are proposed that can recursively refine the generated plans. DEPS [20] is one of the examples that initially proposes an entire plan and then applies real-world feedback to recursively refine it during execution. However, this method requires training a selector to generate a plan that is highly probable to succeed, which makes it difficult to generalize the plans and actions to other tasks. Besides, the required data for training the plan selector are often unavailable in practice and expensive to collect. In contrast, AdaPlanner generates and refines plans via LLM prompting, making it widely applicable to various decision-making problems. # 6 Conclusion and Limitations We proposed AdaPlanner, a closed-loop approach enabling LLM agents to adaptively refine their generated plans according to environment feedback. We defined two different refinement strategies, in-plan and out-of-plan refinement, to fully leverage environment information. Furthermore, to mitigate the LLMs’ hallucination issue and make them learn from past experience, we proposed 9 # SD code-style prompting and skill discovery mechanisms. Through comprehensive experiments, we demonstrated that AdaPlanner outperforms the state-of-the-art baselines significantly and has better sample efficiency. Our ablation studies also showed the effectiveness of different components in AdaPlanner. One limitation of AdaPlanner is that it still requires few-shot expert demonstrations for solving complex tasks. Although AdaPlanner has already achieved better sample efficiency than existing methods, it is interesting to study how to further enhance AdaPlanner to solve complex tasks with no demonstrations in the future. # 7 Broader Impacts Our research approach focuses on treating LLMs as autonomous agents and improving their ability to solve complex sequential decision-making tasks. However, this research line carries inherent risks, including security threats, potential misuse, and unintended consequences such as job displacement due to automation. To mitigate these risks, it is essential for researchers and policymakers to collabo- rate in creating and implementing effective regulations to guide the development and deployment of these technologies toward positive outcomes. Additionally, we believe that the research community should coordinate efforts to design principles and techniques that prioritize safety and human values before LLM agents are deployed in various industries. This will help ensure that LLMs are aligned with ethical and moral standards while promoting their positive impact on society. # References [1] T. Brown, B. Mann, N. Ryder, M. Subbiah, J. D. Kaplan, P. Dhariwal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell, et al. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901, 2020. [2] W. Chen, X. Ma, X. Wang, and W. W. Cohen. Program of thoughts prompting: Disentangling computation from reasoning for numerical reasoning tasks. arXiv, page 2211.12588v3, 2022. [3] L. Gao, A. Madaan, S. Zhou, U. Alon, P. Liu, Y. Yang, J. Callan, and G. Neubig. Pal: Program- aided language models. arXiv, page 2211.10435v2, 2022. [4] I. Gur, O. Nachum, Y. Miao, M. Safdari, A. Huang, A. Chowdhery, S. Narang, N. Fiedel, and A. Faust. Understanding html with large language models. arXiv, page 2210.03945v1, 2022. [5] W. Huang, P. Abbeel, D. Pathak, and I. Mordatch. Language models as zero-shot planners: Extracting actionable knowledge for embodied agents. arXiv, page 2201.07207v2, 2022. [6] W. Huang, F. Xia, T. Xiao, H. Chan, J. Liang, P. Florence, A. Zeng, J. Tompson, I. Mordatch, Y. Chebotar, P. Sermanet, N. Brown, T. Jackson, L. Luu, S. Levine, K. Hausman, and B. Ichter. Inner monologue: Embodied reasoning through planning with language models. arXiv, page 2207.05608v1, 2022. [7] P. C. Humphreys, D. Raposo, T. Pohlen, G. Thornton, R. Chhaparia, A. Muldal, J. Abramson, P. Georgiev, A. Goldin, A. Santoro, and T. Lillicrap. A data-driven approach for learning to control computers. arXivProceedings of the 39th International Conference on Machine Learning, Baltimore, Maryland, USA, PMLR 162, 2022, page 2202.08137v2, 2022. [8] E. Jang. Can llms critique and iterate on their own outputs? evjang.com, 2023. [9] G. Kim, P. Baldi, and S. McAleer. Language models can solve computer tasks. arXiv, page 2303.17491v1, 2023. [10] J. Liang, W. Huang, F. Xia, P. Xu, K. Hausman, B. Ichter, P. Florence, and A. Zeng. Code as policies: Language model programs for embodied control. arXiv, page 2209.07753v3, 2022. [11] E. Z. Liu, K. Guu, P. Pasupat, and P. Liang. Reinforcement learning on web interfaces using workflow-guided exploration. In International Conference on Learning Representations, 2018. [12] P. Lu, B. Peng, H. Cheng, M. Galley, K.-W. Chang, Y. N. Wu, S.-C. Zhu, and J. Gao. Chameleon: Plug-and-play compositional reasoning with large language models. arXiv preprint arXiv:2304.09842, 2023. 10 [13] L. Ouyang, J. Wu, X. Jiang, D. Almeida, C. Wainwright, P. Mishkin, C. Zhang, S. Agarwal, K. Slama, A. Ray, et al. Training language models to follow instructions with human feedback. Advances in Neural Information Processing Systems, 35:27730–27744, 2022. [14] A. Parisi, Y. Zhao, and N. Fiedel. Talm: Tool augmented language models. arXiv preprint arXiv:2205.12255, 2022. [15] T. Schick, J. Dwivedi-Yu, R. Dessì, R. Raileanu, M. Lomeli, L. Zettlemoyer, N. Cancedda, and T. Scialom. Toolformer: Language models can teach themselves to use tools. arXiv preprint arXiv:2302.04761, 2023. [16] Y. Shen, K. Song, X. Tan, D. Li, W. Lu, and Y. Zhuang. Hugginggpt: Solving ai tasks with chatgpt and its friends in huggingface. arXiv preprint arXiv:2303.17580, 2023. [17] N. Shinn, B. Labash, and A. Gopinath. Reflexion: an autonomous agent with dynamic memory and self-reflection. arXiv preprint arXiv:2303.11366, 2023. [18] M. Shridhar, X. Yuan, M.-A. Cote, Y. Bisk, A. Trischler, and M. Hausknecht. {ALFW}orld: Aligning text and embodied environments for interactive learning. In International Conference on Learning Representations, 2021. [19] I. Singh, V. Blukis, A. Mousavian, A. Goyal, D. Xu, J. Tremblay, D. Fox, J. Thomason, and A. Garg. Progprompt: Generating situated robot task plans using large language models. In Second Workshop on Language and Reinforcement Learning, 2022. [20] Z. Wang, S. Cai, A. Liu, X. Ma, and Y. Liang. Describe, explain, plan and select: Interactive planning with large language models enables open-world multi-task agents. arXiv, page 2302.01560v1, 2023. [21] J. Wei, X. Wang, D. Schuurmans, M. Bosma, B. Ichter, F. Xia, E. Chi, Q. Le, and D. Zhou. Chain- of-thought prompting elicits reasoning in large language models. arXiv, page 2201.11903v6, 2022. [22] S. Yao, J. Zhao, D. Yu, N. Du, I. Shafran, K. R. Narasimhan, and Y. Cao. React: Synergizing reasoning and acting in language models. In The Eleventh International Conference on Learning Representations, 2023. [23] D. Zhou, N. Schärli, L. Hou, J. Wei, N. Scales, X. Wang, D. Schuurmans, C. Cui, O. Bousquet, Q. Le, and E. Chi. Least-to-most prompting enables complex reasoning in large language models. arXiv, page 2205.10625v2, 2022. 11 # 8 Supplementary Material # 8.1 Experimental Setup ALFWorld [18] is a comprehensive suite of synthetic, text-based environments, encompassing six distinct task types set, Pick, Clean, Heat, Cool, Examine, and Pick two, within a virtual household. Each task possesses a unique high-level objective (e.g., put some vase in safe, etc.) that necessitates agent navigation and interaction with various objects or receptacles (e.g., go to shelf 6, clean apple, etc.). To fulfill the stipulated task, the agent is required to implement a sequence of actions aimed at accomplishing the predetermined goal. However, given that an object may potentially reside in any one of over 50 possible locations in a task instance, the agent must sequentially explore each of these. Consequently, the entire action trajectory could involve more than 50 individual actions, presenting a significant challenge to the agent. MiniWoB++ [11] is a task suite of simulation environments that covers a large range of com- puter tasks for net agents. The computer tasks start from simple button-clicking to more challenging ones with longer time horizons (e.g., click-checkboxes-large), reasoning (e.g., click-checkboxes-soft), unexpected pop-ups (e.g., login-user-popup ), and stochastically varying layouts (e.g., multi-orderings, multi-layouts). These challenges are suitable for evaluating our proposed closed-loop framework. Each task interacts with a 160px × 210px web environment, where the state space is purely the HTML code of the web. Following RCI [9], we define the actions space as two sets of operations, i.e., clicking and typing ac- tions. The clicks allow the agent to interact with clickable HTML elements (e.g., webpage but- tons). The typings are conducted with keyboard-based actions, such as inputting characters into the input box and stroking functional keys (e.g., ENTER, BACKSPACE). We select nine Mini- WoB++ tasks where environment observations (i.e., the HTML code) change after certain actions: search-engine, tic-tac-toe, terminal, login-user-popup, guess-number, email-inbox, email-inbox-nl-turk, email-inbox-forward-nl, and email-inbox-forward-nl-turk. Take the task terminal as an example. Search results appear on the webpage after inputting the keyword and pressing the search button. Therefore, environment feedback can be interpreted from the change in HTML code and further leveraged by closed-loop planning. We also adopt and test the 53 tasks evaluated in RCI [9]. Metrics. Consistent with previous works [18, 22, 8, 7, 4, 11, 9], we use success rate (%) to evaluate the performance of tested methods. The success rate is defined as the number of successful episodes over the total number of episodes. Note that in ALFWorld, failure of an episode occurs when the total number of actions attains 50, with the task still unsolved. In MiniWoB++, failures can occur in two scenarios: either due to the execution of invalid actions or if the task remains unfinished following the execution of the entire plan. # 8.2 Baseline Details ALFWorld. Following a set of previous works [18, 22, 8], we evaluate AdaPlanner on 134 different environments. By default, we include one sample as an exemplar per task to prompt AdaPlanner. For the study presented in Figure 4a, we adopt the setting of prompted samples as in Table 4. For the study in Figure 4d, we use one sample of the simplest task put to prompt the rest of the five tasks, which are more complex and require more steps to solve. For baselines, we compare AdaPlanner with BUTLER [18], ReAct [22], and Reflexion [8]. BUTLER [18] is an imitation learning method trained with 100k samples per task. ReAct and Reflexion, as outlined in Table 1, are prompting-based methodologies utilizing an implicit closed-loop framework. They employ a total of 6 and 8 samples, respectively, across all six tasks. BUTLER results are sourced from [18]. We evaluate ReAct, Reflexion, and AdaPlanner empowered by both GPT-3 (text-davinci-002) and GPT-3.5 (gpt-3.5-turbo and text-davinci-003) models. MiniWoB++. Overall, we report the evaluation results of RCI [9] and the proposed AdaPlanner in GPT-3.5 (text-davinci-003), along with three training or finetuning-based baselines: Computer Control Agent Architecture(CC- Net) [7], Workflow-Guided Exploration(WGE) [11], and WebN-T5-3B [4]. CC-Net and WGE employ supervised learning and reinforcement learning with over 23K and 10 demonstrations per task, respectively. WebN-T5-3B uses 12K demonstrations to finetune a pre-trained language model. RCI is a prompting-based approach that is categorized as the implicit closed-loop method in Table 1, which utilizes 93 samples across the 53 tasks. For these 53 tasks, we first provide AdaPlanner with 38 12 # samples 2 4 6 Cool Examine Pick Clean Clean Clean Clean Examine Pick Pick Pick two Examine Clean Clean Clean Examine Pick two Examine Pick two Clean Clean Heat Heat Cool Table 4: The specific allocation of samples for prompting each task is divided into three cases based on the total number of samples (2, 4, and 6) used across the six types of tasks. For instance, when a total of 2 samples are used for all tasks, a single expert trajectory sample for the Clean task is utilized to prompt four tasks (Pick, Clean, Heat, and Cool). Similarly, a sample from the Examine task is used to prompt two tasks (Examine and Pick two). human-written demonstrations and perform skill discovery to obtain another 21 additional examples, i.e., 59 examples are used for 53 tasks. Evaluations results of RCI, CC-Net, WGE, and WebN-T5-3B are sourced from the works of [9, 7, 11, 4], respectively. # 8.3 Prompts # 8.3.1 ALFWorld Basic Information. The <basic_info> defines the agent and admissible actions for AdaPlanner. Note that the actual definitions of action functions are not specified in the prompt. Instead, only a formalized definition with several examples is provided, such that the planner can acquire how to compose a plan based on these actions. As can be seen in the following part, this <basic_info> prompt is used in both <initial_planning> and <refinement> prompts. <basic_info> Prompt # You are a household agent. Here is some Python code defining a household environment: # Use literal_eval to convert the answer from ask() to a list. from ast import literal_eval # In the environment, you can ask questions to an assistant by ask(): from large_language_model import ask_llm as ask # for example: You have a list of receptacles, and you want to sort them by the likelihood of a soapbar appearing in them. You can do this by asking the assistant: receptacles = ['countertop 1', 'garbagecan 1', 'sinkbasin 2', 'sinkbasin 1', 'toilet 1', 'toiletpaperhanger 1', 'towelholder 1'] answer = ask(f'Sort the list of receptacles, starting from the one a soapbar is most likely to appear: {receptacles}. You should return a Python list.') # answer = ['sinkbasin 1', 'sinkbasin 2', 'countertop 1', 'towelholder 1', 'toiletpaperhanger 1', 'garbagecan 1', 'toilet 1'] # Agent class represents the state of the agent, including its location, # what it's holding as well as the actions it can take. class Agent: def __init__(self, receptacles): self.location = None self.holding = None self.receptacles = receptacles # Here are the admissible actions the agent can take: # Go to a receptacle and update the agent's location. # For example, 'On the countertop 1, you see a candle 1, a cloth 2, and a soapbar 1.' = goto('countertop 1') # For example, 'On the sidetable 2, you see nothing.' = goto('sidetable 2') def goto(self, receptacle): ... # Take an object from a receptacle if the agent is not holding anything. 13 # For example, 'You pick up the soapbar 1 from the towelholder 1.' = take('soapbar 1', 'towelholder 1') def take(self, object, receptacle): ... # Put an object in or on a receptacle if the agent is holding it. # For example, 'You put the soapbar 1 in/on the cabinet 1.' = put('soapbar 1', 'cabinet 1') def put(self, object, receptacle): ... # Open a receptacle and observe its contents. # For example, 'You open the cabinet 1. The cabinet 1 is open. In it, you see a cloth 1.' = open_receptacle('cabinet 1') def open_receptacle(self, receptacle): ... # Clean an object with a receptacle. # For example, 'You clean the soapbar 1 using the sinkbasin 1.' = clean('soapbar 1', 'sinkbasin 1') def clean(self, object, receptacle): ... # Heat an object with a receptacle. # For example, 'You heat the tomato 1 using the microwave 1.' = heat('tomato 1', 'microwave 1') def heat(self, object, receptacle): ... # Cool an object with a receptacle. # For example, 'You cool the pan 2 using the fridge 1.' = cool('pan 2', 'fridge 1') def cool(self, object, receptacle): ... # Turn on an object. # For example, 'You turn on the desklamp 1.' = turn_on('desklamp 1') def turn_on(self, object): ... # Report agent's current state, including its location, what it's holding, and last action and observation. # This function should only be used in assertion. def report(self): ... Initial Planning. The <initial_planning> prompt is employed to generate the preliminary plan. In this context, <basic_info> is substituted by the content of the <basic_info> prompt. The <sample> is replaced with an expert trajectory, while <receptacle_list> is substituted by the list of interactive receptacles provided by the task environment. Finally, <task> is substituted by the task description, expressed in natural language. # <initial_planning> Prompt <basic_info> # Now complete the function solution() below to solve the task by composing the agent's methods to interact with the environment. # For each step you plan to take, 1) mark with '[Step xx]', 2) give a reason why you think it is a good step to take 3) write an assertion to check if the step is successful. # Here is an example of a solution to the task: <sample> 14 # Here is the actual task. # define environment and agent receptacles = <receptacle_list> agent = Agent(receptacles) # <task> # You should complete your solution function below: def solution(agent, start_from=1): Samples. In ALFWorld, there are six types of tasks: Pick, Clean, Heat, Cool, Examine, and Pick two. For each type, we gather one expert sample of solutions that the planner can refer to. These six expert samples are presented as follows: The expert sample for the task Pick: # <sample_pick> Prompt # define environment and agent receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) # Your task is to: put soapbar on countertop. # here is a solution: def solution(agent, start_from=1): # General Plan: I need to get a list of receptacles where the soapbar is likely to appear, and then go to each receptacle in the list until seeing a soapbar. Then I can put get the identifier of the soapbar and take it. Finally I can go to the countertop and put the soapbar. if start_from <= 1: print("[Step 1] get a list of receptacles where the soapbar is likely to appear") # I can ask the assistant to do that. answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a soapbar in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 1]: recep_to_check should not be empty. {agent.report()}' if start_from <= 2: print("[Step 2] go to each receptacle in the list until seeing a soapbar") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a soapbar is in/on the receptacle. if 'soapbar' in observation: break # expectation: I should be able to find a receptacle where a soapbar is in/on it. assert 'soapbar' in observation, f'Error in [Step 2]: There is no soapbar in/on {recep_to_check}. {agent.report()}' if start_from <= 3: print("[Step 3] identify the soapbar I juts found and take it") # I need to get the identifier of the soapbar. I can ask the assistant to do that. 15 answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation} The identifier of the soap? Only Output a single number without any other words. ') found_soapbar = f'soapbar {answer}' observation = agent.take(found_soapbar, receptacle) # expectation: I should be able to take the soapbar from the receptacle. assert agent.holding == found_soapbar, f'Error in [Step 3]: I cannot take {found_soapbar} from the {receptacle}. {agent.report()}' if start_from <= 4: print("[Step 4] go to a countertop and put the soapbar on it") # There are multiple countertops, and I only need to go to one of them. observation = agent.goto('countertop 1') # check if the countertop is closed. If so, open it. if 'closed' in observation: # observation = agent.open_receptacle('countertop 1') observation = agent.put(found_soapbar, 'countertop 1') # expectation: I should be able to put the soapbar on the countertop. assert f'You put the {found_soapbar} in/on the countertop 1.' in observation, f'Error in [Step 4]: I cannot put the {found_soapbar} on the countertop 1. {agent.report()}' The expert sample for the task Clean: # <sample_clean> Prompt # define environment and agent receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) # Your task is to: put a clean lettuce in diningtable / clean a lettuce and put it in diningtable. # here is a solution: def solution(agent, start_from=1): # General plan: I need to get a list of receptacles to find the lettuce, take the lettuce to the sinkbasin, clean it and put it in a diningtable. if start_from <= 1: print("[Step 1] get a list of receptacles where the lettuce is likely to appear.") # I can ask the assistant to do that. answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a lettuce in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 1]: recep_to_check should not be empty. {agent.report()}' if start_from <= 2: print("[Step 2] go to each receptacle in the list until seeing a lettuce") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a lettuce is in/on the receptacle. if 'lettuce' in observation: break # expectation: I should be able to find a receptacle where a lettuce is in/on it. 16 assert 'lettuce' in observation, f'Error in [Step 2]: There is no lettuce in/on {recep_to_check}. {agent.report()}' if start_from <= 3: print("[Step 3] identify the lettuce I juts found and take it") # I need to get the identifier of the lettuce. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation} The identifier of the lettuce? Only Output a single number without any other words. ') found_lettuce = f'lettuce {answer}' observation = agent.take(found_lettuce, receptacle) # expectation: I should be able to take the lettuce from the receptacle. assert agent.holding == found_lettuce, f'Error in [Step 3]: I cannot take {found_lettuce} from the {receptacle}. {agent.report()}' if start_from <= 4: print("[Step 4] go to a sinkbasin to clean the lettuce. ") # I should go to the sinkbasin first if I want to clean the lettuce. observation = agent.goto('sinkbasin 1') # check if the sinkbasin is closed. If so, open it. if 'closed' in observation: # observation = agent.open_receptacle('sinkbasin 1') observation = agent.clean(found_lettuce, 'sinkbasin 1') # expectation: I should be able to clean the lettuce. assert f'You clean the {found_lettuce} using the sinkbasin 1.' in observation, f'Error in [Step 4]: I cannot clean the {found_lettuce} using the sinkbasin 1. {agent.report()} I should have been at sinkbasin 1 and holding {found_lettuce}.' if start_from <= 5: print("[Step 5] go to a diningtable and put the lettuce on it. ") # There are multiple diningtables, and I only need to go to one of them. observation = agent.goto('diningtable 1') # check if the diningtable is closed. If so, open it. if 'closed' in observation: # observation = agent.open_receptacle('diningtable 1') observation = agent.put(found_lettuce, 'diningtable 1') # expectation: I should be able to put the lettuce on the diningtable. assert f'You put the {found_lettuce} in/on the diningtable 1.' in observation, f'Error in [Step 5]: I cannot put the {found_lettuce} on the diningtable 1. {agent.report()}' The expert sample for the task Heat: # <sample_heat> Prompt # define environment and agent receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) # Your task is to: put a hot lettuce in diningtable / heat some lettuce and put it in diningtable. # here is a solution: def solution(agent, start_from=1): # General plan: I need to get a list of receptacles to find the lettuce, take the lettuce to the microwave, heat it and put it in a diningtable. if start_from <= 1: print("[Step 1] get a list of receptacles where the lettuce is likely to appear.") # I can ask the assistant to do that. 17 answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a lettuce in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 1]: recep_to_check should not be empty. {agent.report()}' if start_from <= 2: print("[Step 2] go to each receptacle in the list until seeing a lettuce") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a lettuce is in/on the receptacle. if 'lettuce' in observation: break # expectation: I should be able to find a receptacle where a lettuce is in/on it. assert 'lettuce' in observation, f'Error in [Step 2]: There is no lettuce in/on {recep_to_check}. {agent.report()}' if start_from <= 3: print("[Step 3] identify the lettuce I juts found and take it") # I need to get the identifier of the lettuce. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation} The identifier of the lettuce? Only Output a single number without any other words. ') found_lettuce = f'lettuce {answer}' observation = agent.take(found_lettuce, receptacle) # expectation: I should be able to take the lettuce from the receptacle. assert agent.holding == found_lettuce, f'Error in [Step 3]: I cannot take {found_lettuce} from the {receptacle}. {agent.report()}' if start_from <= 4: print("[Step 4] go to a microwave to heat the lettuce") # I should go to a microwave to heat the lettuce. observation = agent.goto('microwave 1') # check if the microwave is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle('microwave 1') observation = agent.heat(found_lettuce, 'microwave 1') # expectation: I should be able to heat the lettuce. assert f'You heat the {found_lettuce} using the microwave 1.' in observation, f'Error in [Step 4]: I cannot heat the {found_lettuce} using the microwave 1. {agent.report()} I should have been at microwave 1 and holding {found_lettuce}. ' if start_from <= 5: print("[Step 5] go to a diningtable and put the lettuce on it") # There are multiple diningtables, and I only need to go to one of them. observation = agent.goto('diningtable 1') # check if the diningtable is closed. If so, open it. if 'closed' in observation: # observation = agent.open_receptacle('diningtable 1') observation = agent.put(found_lettuce, 'diningtable 1') 18 # expectation: I should be able to put the lettuce on the diningtable. assert f'You put the {found_lettuce} in/on the diningtable 1.' in observation, f'Error in [Step 5]: I cannot put the {found_lettuce} on the diningtable 1. {agent.report()}' The expert sample for the task Cool: # <sample_cool> Prompt # define environment and agent receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) # Your task is to: put a cold lettuce in diningtable / cool some lettuce and put it in diningtable. # here is a solution: def solution(agent, start_from=1): # General plan: I need to get a list of receptacles to find the lettuce, take the lettuce to the fridge, cool it and put it in a diningtable. if start_from <= 1: print("[Step 1] get a list of receptacles where the lettuce is likely to appear.") # I can ask the assistant to do that. answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a lettuce in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 1]: recep_to_check should not be empty. {agent.report()}' if start_from <= 2: print("[Step 2] go to each receptacle in the list until seeing a lettuce") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a lettuce is in/on the receptacle. if 'lettuce' in observation: break # expectation: I should be able to find a receptacle where a lettuce is in/on it. assert 'lettuce' in observation, f'Error in [Step 2]: There is no lettuce in/on {recep_to_check}. {agent.report()}' if start_from <= 3: print("[Step 3] identify the lettuce I juts found and take it") # I need to get the identifier of the lettuce. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation} The identifier of the lettuce? Only Output a single number without any other words. ') found_lettuce = f'lettuce {answer}' observation = agent.take(found_lettuce, receptacle) # expectation: I should be able to take the lettuce from the receptacle. assert agent.holding == found_lettuce, f'Error in [Step 3]: I cannot take {found_lettuce} from the {receptacle}. {agent.report()}' if start_from <= 4: 19 print("[Step 4] go to a fridge to cool the lettuce") # I should go to a fridge to cool the lettuce. observation = agent.goto('fridge 1') # check if the fridge is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle('fridge 1') observation = agent.cool(found_lettuce, 'fridge 1') # expectation: I should be able to cool the lettuce. assert f'You cool the {found_lettuce} using the fridge 1.' in observation, f'Error in [Step 4]: I cannot cool the {found_lettuce} using the fridge 1. {agent.report()} I should have been at fridge 1 and holding {found_lettuce}.' if start_from <= 5: print("[Step 5] go to a diningtable and put the lettuce on it") # There are multiple diningtables, and I only need to go to one of them. observation = agent.goto('diningtable 1') # check if the diningtable is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle('diningtable 1') observation = agent.put(found_lettuce, 'diningtable 1') # expectation: I should be able to put the lettuce on the diningtable. assert f'You put the {found_lettuce} in/on the diningtable 1.' in observation, f'Error in [Step 5]: I cannot put the {found_lettuce} on the diningtable 1. {agent.report()}' # The expert sample for the task Examine: # <sample_examine> Prompt # define environment and agent receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) # Your task is to: look at the bowl under the desklamp / examine the bowl with the desklamp # here is a solution: def solution(agent, start_from=1): # General plan: I need to get a list of receptacles to find the bowl and take the bowl with me, then I get another list of receptacles to find the desklamp and turn it on. if start_from <= 1: print("[Step 1] get a list of receptacles where a bowl is likely to appear.") # I can ask the assistant to do that. answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a bowl in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 1]: recep_to_check should not be empty. {agent.report()}' if start_from <= 2: print("[Step 2] go to each receptacle in the list until seeing a pen") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a bowl is in/on the receptacle. if 'pen' in observation: 20 # break # expectation: I should be able to find a receptacle where a bowl is in/on it. assert 'pen' in observation, f'Error in [Step 2]: There is no bowl in/on {recep_to_check}. {agent.report()}' if start_from <= 3: print("[Step 3] take the bowl from the receptacle") # I need to get the identifier of the bowl so that I can take it. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation} The identifier of the pen? Only Output a single number without any other words. ') found_pen = f'pen {answer}' observation = agent.take(found_pen, receptacle) # expectation: I should be able to take the bowl from the receptacle. assert agent.holding == found_pen, f'Error in [Step 3]: I cannot take {found_pen} from the {receptacle}. {agent.report()}' if start_from <= 4: print("[Step 4] get a list of receptacles where a desklamp is likely to appear.") # I can ask the assistant to do that. answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a desklamp in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 4]: recep_to_check should not be empty. {agent.report()}' if start_from <= 5: print("[Step 5] go to each receptacle in the list until seeing a desklamp") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a desklamp is in/on the receptacle. if 'desklamp' in observation: break # expectation: I should be able to find a receptacle where a desklamp is in/on it. assert 'desklamp' in observation, f'Error in [Step 5]: There is no desklamp in/on {recep_to_check}. {agent.report()}' if start_from <= 6: print("[Step 6] turn on desklamp") # There might be multiple desklamps in the environment, and I need to get the identifier of the desklamp. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation} The identifier of the desklamp? Only Output a single number without any other words.') found_desklamp = f'desklamp {answer}' # I can directly turn on the desklamp that I just found. observation = agent.turn_on(found_desklamp) # expectation: the desklamp should be turned on now. assert 'turn on' in observation, f'Error in [Step 6]: I cannot turn on {found_desklamp} in/on {receptacle}. {agent.report()}' 21 The expert sample for the task Pick two: # <sample_picktwo> Prompt # define environment and agent receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) # Your task is to: put two cellphone in cabinet / find two cellphone and put them in cabinet # here is a solution: def solution(agent, start_from=1): if start_from <= 1: print("[Step 1] get a list of receptacles where a cellphone is likely to appear.") # I can ask the assistant to do that. answer = ask(f'Given a list of receptacles, please sort them in descending order based on the likelihood of finding a cellphone in each of them. The list of receptacles is: {agent.receptacles}. You should directly return a Python list.') recep_to_check = literal_eval(answer) # remove the destination from the list recep_to_check.remove('cabinet 1') # expectation: the returned recep_to_check should not be empty. assert recep_to_check, f'Error in [Step 1]: recep_to_check should not be empty. {agent.report()}' if start_from <= 2: print("[Step 2] go to each receptacle in the list until seeing a cellphone") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a cellphone is in/on the receptacle. if 'cellphone' in observation: break # expectation: I should be able to find a receptacle where a cellphone is in/on it. assert 'cellphone' in observation, f'Error in [Step 2]: There is no cellphone in/on {recep_to_check}. {agent.report()}' if start_from <= 3: print("[Step 3] identify the first cellphone found and take it") # I need to get the identifier of the cellphone. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation}. The identifier of the cellphone? Only Output a single number without any other words. ') found_cellphone1 = f'cellphone {answer}' observation = agent.take(found_cellphone1, receptacle) # expectation: I should be able to take the cellphone from the receptacle. assert agent.holding == found_cellphone1, f'Error in [Step 3]: I cannot take {found_cellphone1} from the {receptacle}. {agent.report()}' if start_from <= 4: print("[Step 4] go to a cabinet and put the first cellphone found on it. ") # There are multiple countertops, and I only need to go to one of them. observation = agent.goto('cabinet 1') # check if the cabinet is closed. If so, open it. 22 if 'closed' in observation: observation = agent.open_receptacle('cabinet 1') observation = agent.put(found_cellphone1, 'cabinet 1') # expectation: I should be able to put the cellphone1 on the countertop. assert f'You put the {found_cellphone1} in/on the cabinet 1.' in observation, f'Error in [Step 4]: I cannot put the {found_cellphone1} on the cabinet 1. {agent.report()}' if start_from <= 5: print("[Step 5] go to each of the remaining receptacle in the list until seeing a second cellphone") for receptacle in recep_to_check: observation = agent.goto(receptacle) # check if the receptacle is closed. If so, open it. if 'closed' in observation: observation = agent.open_receptacle(receptacle) # check if a cellphone is in/on the receptacle. if 'cellphone' in observation: break # expectation: I should be able to find a receptacle where a cellphone is in/on it. assert 'cellphone' in observation, f'Error in [Step 5]: There is no second cellphone in/on {recep_to_check}. {agent.report()}' if start_from <= 6: print("[Step 6] identify the second cellphone I just found and take it") # I need to get the identifier of the cellphone. I can ask the assistant to do that. answer = ask(f'From the observation, get the identifier of an object. For example, On the cabinet 1, you see a cloth 2, and a toiletpaper 2. The identifier of cloth is 2. Now, {observation}. The identifier of the cellphone? Only Output a single number without any other words. ') found_cellphone2 = f'cellphone {answer}' observation = agent.take(found_cellphone2, receptacle) # expectation: I should be able to take the cellphone from the receptacle. assert agent.holding == found_cellphone2, f'Error in [Step 6]: I cannot take {found_cellphone2} from the {receptacle}. {agent.report()}' if start_from <= 7: print("[Step 7] go to a cabinet and put the second cellphone found on it") observation = agent.goto('cabinet 1') observation = agent.put(found_cellphone2, 'cabinet 1') # expectation: I should be able to put the cellphone2 on the countertop. assert f'You put the {found_cellphone2} in/on the cabinet 1.' in observation, f'Error in [Step 7]: I cannot put the {found_cellphone2} on the cabinet 1. {agent.report()}' Code Check. After plan generation, we employ the following prompt to verify and rectify any syntax errors. The placeholder <solution_func> is replaced by the generated solution function. The <code_check> prompt prompts the model to return two questions. If the response to Question 1 is Yes, the answer to Question 2 is adopted as the corrected solution function. Otherwise, the solution function is kept unchanged. <code_check> Prompt You are given a Python code snippet to define a function called solution. [Code] <solution_func> 23 Question 1: Are there any syntax errors present in the code? Answer Yes/No. Question 2: Fix the syntax errors and output an error-free version of the code. Only Output the revised code after [Revised code] without any other words. Out-of-Plan Refinement. In the event of an assertion error, we use <refinement> to conduct the out-of-plan refinement. In this prompt, <basic_info> is replaced by the content of the <basic_info> prompt. The placeholder <sample> is substituted with an expert trajectory, while <receptacle_list> is replaced by the list of interactive receptacles provided by the task environ- ment. <task> is replaced by the task description in natural language. Finally, <error_msg> is replaced by the assertion error message returned by the solution function. To adhere to the context length limit of the GPT-3 and 3.5 models, the previously generated solution function is not included in this prompt. Instead, we incorporate comprehensive information in the assertion error message, enabling the refiner to generate a revised plan based on these details. # <refinement> Prompt <basic_info> # Here is a example of successful solution for solving a similar task: [Successful example] receptacles = ['diningtable 1','drawer 2', 'drawer 1', 'sinkbasin 1', 'toilet 1', 'sidetable 2', 'sidetable 1', 'cabinet 1', 'countertop 1', 'microwave 1', 'fridge 1'] agent = Agent(receptacles) <sample> # Here is the actual task. # define environment and agent receptacles = <receptacle_list> agent = Agent(receptacles) # <task> You have generated code of solution() to solve the task. However, you executed the solution() function and get an error message: <error_msg> Let's think step by step. Referring to the successful case and the error message, you should complete the solution function with the correct code. def solution(agent, start_from=1): Let's think step by step. Referring to the successful case and the error message, you should complete the solution function with the correct code. def solution(agent, start_from=1): Determining start_from. After formulating a revised plan, we utilize the following prompt to ascertain from which step the new solution function should commence. In this con- text, the <previous_solution> is replaced by the preceding solution function, while the <revised_solution> is replaced by the updated one. Subsequently, the argument start_from=1 is substituted with the step number that this prompt yields. <start_from> Prompt Previously, you generated some code defining a solution function as in [Previous solution]. The previous code is executed and outputs some error. Now you just revised the code as in [Revised solution]. Determine from which step these two version differs. You should only output the step number without saying any other words. [Previous solution] <previous_solution> [Revised solution] <revised_solution> # 8.3.2 MiniWoB++ Basic Information. Similar to the ALFWorld tasks, the <basic_info> of MiniWoB++ defines the agent and admissible actions for AdaPlanner. Note that the actual definitions of action functions 24 are not specified in the prompt. Instead, only a formalized definition with several examples is provided, such that the planner can acquire how to compose a plan based on these actions. As can be seen in the following part, this <basic_info> prompt is used in both <initial_planning> and <refinement> prompts. <basic_info> Prompt # Interact with the HTML webpage to finish the computer task. Here is some Python code defining a computer task environment: # In the environment, you can ask questions to an assistant by ask(): from large_language_model import ask_llm as ask # for example: You want to solve a algebra problem x + 3 = 6. You can ask the assistant to solve it directly for you. answer = ask('Solve an algebra problem. You should directly output the value of the unknown. For example, solve 'y + 1 = 2' -> 1. Now solve 'x + 3 = 6' ->') # answer = '3' # Agent class represents the current state of the HTML webpage and the actions it can take. class Agent: def __init__(self, initial_state): self.current_state = initial_state # Here are the admissible actions the agent can take: # Action: type a string into the input box # this function returns the string of the HTML code after taking the action # e.g., new_html_state = agent.type("hello") def type(self, characters: str) -> str: ... # Action: press a key on the keyboard, the input can be one of the following: # enter, space, arrow_left, arrow_right, arrow_up, arrow_down, backspace # this function returns the string of the HTML code after taking the action # e.g., new_html_state = agent.press_key("enter") def press_key(self, key: str) -> str: ... # Action: click a <select> element in a list with an XPath # this function returns the string of the HTML code after taking the action # e.g., new_html_state = agent.click_option("//select[@id='cars']/option[1]") def click_option(self, xpath_of_option: str) -> str: ... # Action: click an HTML element with its XPath # this function returns the string of the HTML code after taking the action # e.g., new_html_state = agent.click_xpath("//button[@id='button1']") def click_xpath(self, xpath_of_element: str) -> str: ... # Action: move the mouse cursor on an HTML element with an XPath # this function returns the string of the HTML code after taking the action # e.g., new_html_state = agent.move_mouse_on("//button[@id='button1']") def move_mouse_on(self, xpath_of_element: str) -> str: ... Initial Planning. The <initial_planning> prompt is employed to generate the preliminary plan. In this context, <basic_info> is substituted by the content of the <basic_info> prompt. The <sample> is replaced with an expert trajectory (or discarded in the skill discovery stage). The <initial_state> is substituted by the initial HTML code of the task UI. Finally, <task> is substituted by the task description, expressed in natural language. <initial_planning> Prompt # <basic_info> 25 # <sample> # Now complete the function solution() below to solve the task by composing the agent's methods to interact with the environment. # In the solution function, start with a commented "# General plan: ". For each step you plan to take, mark with '[Step xx]', and write an assertion to check if the step is successful. # Here is the actual task. # define environment and agent. The state is the list of HTML elements of the webpage. initial_state = ''' <initial_state> ''' agent = Agent(initial_state) # Task: <task> # Here is the solution: def solution(agent, start_from=1): Samples. In MiniWoB++, we select nine tasks where feedback is available. Here are the expert samples that we gathered for these tasks. The expert sample for the task email-inbox: <sample_email-inbox> Prompt # Here are three examples of solutions. # Task: Find the email by Brittani and reply to them with the text "Aliquet. Sollicitudin nam lectus.". def solution(agent, start_from=1): # General plan: I should first click on the email by Brittani, then click on the reply button, then type the text "Aliquet. Sollicitudin nam lectus." and finally click on the send button. if start_from <= 1: print('[Step 1] click on the email by Brittani') agent.click_xpath("//div[@class='email-sender' and text()='Brittani']") state_after_interaction = agent.click_xpath("//span[@class='email-reply']") # the reply content should be displayed on page. assert 'reply-text' in state_after_interaction, 'I cannot do [Step 1] correctly. The reply button is not displayed on the page.' if start_from <= 2: print('[Step 2] type the text "Aliquet. Sollicitudin nam lectus."') agent.click_xpath("//textarea[@id='reply-text']") agent.type('Aliquet. Sollicitudin nam lectus.') state_after_interaction = agent.click_xpath("//*[@id='send-reply']") # Task: Find the email by Blanca and forward that email to Agathe. def solution(agent, start_from=1): # General plan: I should first click on the email by Blanca, then click on the forward button, then type "Agathe" and finally click on the send button. if start_from <= 1: print('[Step 1] click on the email by Blanca') agent.click_xpath("//div[@class='email-sender' and text()='Blanca']") state_after_interaction = agent.click_xpath("//span[@class='email-forward']") # the forward content should be displayed on page. assert 'forward-sender' in state_after_interaction, 'I cannot do [Step 1] correctly. The forward button is not displayed on the page.' if start_from <= 2: print('[Step 2] type "Agathe"') agent.click_xpath("//input[@class='forward-sender']") agent.type('Agathe') 26 # state_after_interaction = agent.click_xpath("//*[@id='send-forward']") # Task: Find the email by Salli and click the trash icon to delete it. def solution(agent, start_from=1): # General plan: I should first click on the email by Salli, then click on the trash icon. if start_from <= 1: print('[Step 1] click on the email by Salli') agent.click_xpath("//div[@class='email-sender' and text()='Salli']") agent.click_xpath("//span[@class='trash']") # The expert sample for the task email-inbox-forward-nl: # <sample_email-inbox-forward-nl> Prompt <sample_email-inbox-forward-nl> Prompt # Here is an example of solution. # task: Send Alice the email from Beth / navigate to the message from Beth and send it to Alice. def solution(agent, start_from=1): # General plan: I should first click on the email from Beth, then click on the "Forward" button, then type "Alice" in the "To" inputbox, finally click on the "Send" button. if start_from <= 1: print('[Step 1] click on the email from Beth') agent.click_xpath('//*[@class="email-sender" and text()="Beth"]') state_after_interaction = agent.click_xpath('//span[@class="email-forward"]') # the "To" inputbox should be displayed on page. assert 'forward-sender' in state_after_interaction, f'I cannot do [Step 1] correctly. The "To" inputbox is not displayed on the page. Current state: {state_after_interaction}' if start_from <= 2: print('[Step 2] type "Alice" in the "To" inputbox') agent.click_xpath('//input[@class="forward-sender"]') agent.type('Alice') state_after_interaction = agent.click_xpath('//span[@id="send-forward"]') # the email should be sent successfully. assert 'email-sender' in state_after_interaction, f'I cannot do [Step 2] correctly. The email is not sent successfully. Current state: {state_after_interaction}' # The expert sample for the task email-inbox-forward-nl-turk: # <sample_email-inbox-forward-nl-turk> Prompt # Here is an example of solution. # task: Send Alice the email from Beth / navigate to the message from Beth and send it to Alice / I want to forward the email from Beth over to Alice def solution(agent, start_from=1): # General plan: I should first click on the email from Beth, then click on the "Forward" button, then type "Alice" in the "To" inputbox, finally click on the "Send" button. if start_from <= 1: print('[Step 1] click on the email from Beth') agent.click_xpath('//*[@class="email-sender" and text()="Beth"]') state_after_interaction = agent.click_xpath('//span[@class="email-forward"]') # the "To" inputbox should be displayed on page. assert 'forward-sender' in state_after_interaction, f'I cannot do [Step 1] correctly. The "To" inputbox is not displayed on the page. Current state: {state_after_interaction}' if start_from <= 2: print('[Step 2] type "Alice" in the "To" inputbox') agent.click_xpath('//input[@class="forward-sender"]') 27 agent.type('Alice') state_after_interaction = agent.click_xpath('//span[@id="send-forward"]') # the email should be sent successfully. assert 'email-sender' in state_after_interaction, f'I cannot do [Step 2] correctly. The email is not sent successfully. Current state: {state_after_interaction}' The expert sample for the task email-inbox-nl-turk: # <sample_email-inbox-nl-turk> Prompt # Here are three examples of solution. # Task: "Aliquet. Sollicitudin nam lectus." is my reply to Brittani's most recent email / Find the email by Brittani and reply to them with the text "Aliquet. Sollicitudin nam lectus.". def solution(agent, start_from=1): # General plan: I should first click on the email by Brittani, then click on the reply button, then type the text "Aliquet. Sollicitudin nam lectus." and finally click on the send button. if start_from <= 1: print('[Step 1] click on the email by Brittani') agent.click_xpath("//div[@class='email-sender' and text()='Brittani']") state_after_interaction = agent.click_xpath("//span[@class='email-reply']") # the reply content should be displayed on page. assert 'reply-text' in state_after_interaction, 'I cannot do [Step 1] correctly. The reply button is not displayed on the page.' if start_from <= 2: print('[Step 2] type the text "Aliquet. Sollicitudin nam lectus."') agent.click_xpath("//textarea[@id='reply-text']") agent.type('Aliquet. Sollicitudin nam lectus.') state_after_interaction = agent.click_xpath("//*[@id='send-reply']") # Task: Find the last email by Blanca and send it to Agathe / Find the email by Blanca and forward that email to Agathe. def solution(agent, start_from=1): # General plan: I should first click on the email by Blanca, then click on the forward button, then type "Agathe" and finally click on the send button. if start_from <= 1: print('[Step 1] click on the email by Blanca') agent.click_xpath("//div[@class='email-sender' and text()='Blanca']") state_after_interaction = agent.click_xpath("//span[@class='email-forward']") # the forward content should be displayed on page. assert 'forward-sender' in state_after_interaction, 'I cannot do [Step 1] correctly. The forward button is not displayed on the page.' if start_from <= 2: print('[Step 2] type "Agathe"') agent.click_xpath("//input[@class='forward-sender']") agent.type('Agathe') state_after_interaction = agent.click_xpath("//*[@id='send-forward']") # Task: Delete this email from Salli / Please find Salli's email in the inbox and delete it. def solution(agent, start_from=1): # General plan: I should first click on the email by Salli, then click on the trash icon. if start_from <= 1: print('[Step 1] click on the email by Salli') agent.click_xpath("//div[@class='email-sender' and text()='Salli']") agent.click_xpath("//span[@class='trash']") The expert sample for the task guess-number: 28 # <sample_guess-number> Prompt # Here is an example of solution. # Task: Guess the number between 0-9 and press Submit. Use the feedback below to find the right number. # Here is the solution: def solution(agent, start_from = 1): # General plan: Given a list of possible_numbers, I will try the number in the middle of the list and get feedback from the html state. # Now the given list of possible_numbers is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. if start_from <= 1: print('[Step 1] maintain a list of the possible numbers left and try the middle one') # before making a guess, I should store the html state for future comparison. state_before_interaction = agent.current_state # I will choose the number 5, which is in the middle of possible_numbers. guess_number = 5 # click the input box, type the number I guessed and click submit. agent.click_xpath("//input[@id='tt']") agent.press_key("backspace") agent.type(str(guess_number)) state_after_interaction = agent.click_xpath('//*[@id="subbtn"]') # after input and submit the guessed number, the html_state should be changed and contain the feedback. Otherwise this step is not successful. assert state_after_interaction != state_before_interaction, 'I did [Step 1] but the html state did not change.' if start_from <= 2: print('[Step 2] get the feedback information from the new html state') # If the guess is successful, the keyword "higher" or "lower" should not be present in the observation. Otherwise I should use assert to jump out to pass the feedback. observation = ask(f'Answer a question based on the html code below: {state_after_interaction} Question: Which one is displayed? "The number is lower than" or "The number is higher than"? You must only output the displayed sentence without saying any other words.') assert "higher" not in observation, f'You tried the number {guess_number} in [Step 1], and the correct number is greater than this number. I need to revise solution function according to the new plan: Now the given list of possible_numbers is [6, 7, 8, 9].' assert "lower" not in observation, f'You tried the number {guess_number} in [Step 1], and the correct number is smaller than this number. I need to revise solution function according to the new plan: Now the given list of possible_numbers is [0, 1, 2, 3, 4].' The expert sample for the task login-user-popup: # <sample_login-user-popup> Prompt # Here is an example of solution. # Task: Enter the username "kanesha" and the password "oT" into the text fields and press login. def solution(agent, start_from=1): # General plan: I should first click on the username field, then type in the username, then click on the password field, then type in the password, then click on the login button. if start_from <= 1: print('[Step 1] Click on the username field') state_after_interaction = agent.click_xpath("//input[@id='username']") # during interaction, some popups may appear. If so, I need to jump out to handle the popups. 29 assert 'popup' not in state_after_interaction, f'After [Step 1], some popups appeared, you need to close the popup at the beginning of [Step 1]. The current html is: {state_after_interaction} You need to add some code at the beginning of [Step 1] to cancel the popup before any other actions.' if start_from <= 2: print('[Step 2] Type in the username') state_after_interaction = agent.type('kanesha') # during interaction, some popups may appear. If so, I need to jump out to handle the popups. assert 'popup' not in state_after_interaction, f'After [Step 2], some popups appeared, you need to close the popup at the beginning of [Step 2]. The current html is: {state_after_interaction} You need to add some code at the beginning of [Step 2] to cancel the popup before any other actions.' if start_from <= 3: print('[Step 3] Click on the password field') state_after_interaction = agent.click_xpath("//input[@id='password']") # during interaction, some popups may appear. If so, I need to jump out to handle the popups. assert 'popup' not in state_after_interaction, f'After [Step 3], some popups appeared, you need to close the popup at the beginning of [Step 3]. The current html is: {state_after_interaction} You need to add some code at the beginning of [Step 3] to cancel the popup before any other actions.' if start_from <= 4: print('[Step 4] Type in the password') state_after_interaction = agent.type('oT') # during interaction, some popups may appear. If so, I need to jump out to handle the popups. assert 'popup' not in state_after_interaction, f'After [Step 4], some popups appeared, you need to close the popup at the beginning of [Step 4]. The current html is: {state_after_interaction} You need to add some code at the beginning of [Step 4] to cancel the popup before any other actions.' if start_from <= 5: print('[Step 5] Click on the login button') state_after_interaction = agent.click_xpath("//button[@id='subbtn']") # during interaction, some popups may appear. If so, I need to jump out to handle the popups. assert 'popup' not in state_after_interaction, f'After [Step 5], some popups appeared, you need to close the popup at the beginning of [Step 5]. The current html is: {state_after_interaction} You need to add some code at the beginning of [Step 5] to cancel the popup before any other actions.' The expert sample for the task search-engine: # <sample_search-engine> Prompt # Here is an example of solution. # Task: Use the textbox to enter "Alice" and press "Search", then find and click the 7th search result. def solution(agent, start_from=1): # General plan: I should first click on the inputbox, then type "Alice", then click on the "Search" button, finally look through pages and click on the 7th result. if start_from <= 1: print('[Step 1] click on the inputbox and type "Alice"') agent.click_xpath('//*[@id="search-text"]') agent.type('Alice') 30 state_after_interaction = agent.click_xpath('//*[@id="search"]') # the search content should be displayed on page. assert 'search-desc' in state_after_interaction, 'I cannot do [Step 1] correctly. The search content is not displayed on the page.' if start_from <= 2: print('[Step 2] calculate the page number of the 7th result and click on the page') # I should count the number of results on each page, iteratively turn to next page until seeing the 7th result. # I can use the following code to count the number of results on each page. num_results_displayed_per_page = state_after_interaction.count('search-desc') num_page = (7 - 1) // num_results_displayed_per_page state_after_interaction = agent.click_xpath(f'//*[@id="pagination"]/li[{3+num_page}]/a') # I should click on the 7th result. num_to_click = 7 - num_results_displayed_per_page * num_page state_after_interaction = agent.click_xpath(f'//*[@id="page-content"]/div[{num_to_click}]/a') The expert sample for the task terminal: # <sample_terminal> Prompt # Here is an example of solution. # Task: Use the terminal below to delete a file ending with the extension .gif def solution(agent, start_from=1): # General plan: I should first type "ls" to list all files in the terminal, then identify the filename ending with ".gif" and type "rm [filename].gif" to delete the identified file. if start_from <= 1: print('[Step 1] type "ls" to list all files in the terminal') agent.type('ls') state_after_interaction = agent.press_key('enter') # the file list should be displayed on terminal. assert 'gif' in state_after_interaction, f'I cannot do [Step 1] correctly. The file list is not displayed on the terminal. Current state: {state_after_interaction}' if start_from <= 2: print('[Step 2] identify the filename ending with ".gif" and type "rm [filename].gif" to delete the identified file') # I should identify the filename ending with ".gif". I can ask assistant to do that. filename = ask(f'You are given some html code as follows: {state_after_interaction} What is the file ending with the extension .gif? You must directly output the full file name, including the extension.') agent.type(f'rm {filename}') state_after_interaction = agent.press_key('enter') assert 'not found' not in state_after_interaction, f'I cannot do [Step 2] correctly. The file ending with the extension .gif is not deleted. Current state: {state_after_interaction}' The expert sample for the task tic-tac-toe: <sample_tic-tac-toe> Prompt # Here is an example of solution. # Task: Playing as 'X', win a game of tic-tac-toe. def solution(agent, start_from=1): 31 # The board layout and corresponding html xpath: top-left("//*[@id='ttt-0']"), top-center("//*[@id='ttt-1']"), top-right("//*[@id='ttt-2']"), middle-left("//*[@id='ttt-3']"), middle-center("//*[@id='ttt-4']"), middle-right("//*[@id='ttt-5']"), bottom-left("//*[@id='ttt-6']"), bottom-center("//*[@id='ttt-7']"), bottom-right("//*[@id='ttt-8']"). "mark-o" indicates the 'O' placed on board, "mark-x" indicates the 'X' placed on board. # General plan: Currently, no grid is occupied. The plan is 1) put an 'X' in the middle-center("//*[@id='ttt-4']"), 2) put an 'X' in the top-left("//*[@id='ttt-0']"), 3) put an 'X' in the bottom-right("//*[@id='ttt-8']"). Note that place_to_put_X = ['4', '0', '8'] for idx, place_id in enumerate(place_to_put_X): print(f'[Step {idx}] put an X in {place_id}') # before interaction, I need to store the current state so that I can compare it with the state after interaction. state_before_interaction = agent.current_state state_after_interaction = agent.click_xpath(f"//*[@id='ttt-{place_id}']") # if the current state does not change after interaction, that means I cannot put an 'X' in the desired location, and that location is already occupied and the plan will not work. assert state_before_interaction != state_after_interaction, f'''I cannot do [Step {idx}] put an X in the "//*[@id='ttt-{place_id}']", because it is occupied. I need to revise solution function according to the new plan. ''' + ask(f'''Playing as 'X', win a game of tic-tac-toe. The board layout and corresponding html xpath: top-left("//*[@id='ttt-0']"), top-center("//*[@id='ttt-1']"), top-right("//*[@id='ttt-2']"), middle-left("//*[@id='ttt-3']"), middle-center("//*[@id='ttt-4']"), middle-right("//*[@id='ttt-5']"), bottom-left("//*[@id='ttt-6']"), bottom-center("//*[@id='ttt-7']"), bottom-right("//*[@id='ttt-8']").Note that "mark-o" indicates the 'O' placed on board, "mark-x" indicates the 'X' placed on board. The game in progress is represented in html code: {agent.current_state} Report current board situation and generate a plan that the 'X' player should follow to continue this game. Use the format like "Currently, 'X' has been placed at <position>("//*[@id='ttt-x']") and 'O' has been placed at <position>("//*[@id='ttt-x']"). Therefore, the plan is to: 1) put an 'X' in the <position>("//*[@id='ttt-x']") 2) put an 'X' in the ..."''') Code Check. We use the same <code_check> prompt for MiniWoB++ tasks as ALFWorld. Out-of-Plan Refinement. In the event of an assertion error, we use <refinement> to conduct the out- of-plan refinement. In this prompt, <basic_info> is replaced by the content of the <basic_info> prompt. The placeholder <solution_func> is replaced by the generated solution function, while <task> is replaced by the task description in natural language. Finally, <feedback> is replaced by the assertion error message returned by the solution function. Note that the <refinement> prompt used here differs slightly from the one used for ALFWorld. In this context, we include the previously generated solution function in the prompt, enabling the refiner to adjust the solution based on the error messages accordingly. # <refinement> Prompt # <basic_info> # Task: <task> You have generated code of solution() to solve the task: <solution_func> However, you executed the solution() function and get an error message: [Error message] <feedback> Let's think step by step. You must output the revised solution function based on the error message. You must only complete the revised solution function without any other words. 32 # In the solution function, start with a commented "# General plan: ". For each step you plan to take, mark with '[Step xx]', and write an assertion to check if the step is successful. def solution(agent, start_from=1): Determining start_from. We use the same <start_from> prompt for MiniWoB++ tasks as ALFWorld. # 8.4 Hallucination with GPT-3.5 Model (gpt-3.5-turbo) We present the trajectories of three tested methods (ReAct, Reflexion, and AdaPlanner) for two tasks. Here, each model utilizes gpt-3.5-turbo as the backend. 8.4.1 Case 1: examine the book with the desklamp. ReAct’s trajectory for this case is detailed below. Despite the presence of two expert demonstrations, ReAct encounters significant difficulties, as it extensively hallucinates inadmissible actions or sce- narios. For example, search for a book titled "The Great Gatsby" and ask household members if they know where the book is are not feasible within the given environment. ReAct Trajectory of Case 1 (Hallucinated actions are marked in pink.) You are in the middle of a room. Looking quickly around you, you see a bed 1, a desk 2, a desk 1, a drawer 6, a drawer 5, a drawer 4, a drawer 3, a drawer 2, a drawer 1, a garbagecan 1, a laundryhamper 1, a safe 1, a shelf 6, a shelf 5, a shelf 4, a shelf 3, a shelf 2, and a shelf 1. Your task is to: examine the book with the desklamp. > think: To solve the task, I need to find and take a book, then find and use a desklamp. First, I need to find a book. A book is more likely to appear in desk (1-2), shelf (1-6), drawer (1-6). I can check one by one, starting with desk 1. OK. > go to desk 1 On the desk 1, you see a alarmclock 1, a bowl 2, a cd 1, a cellphone 3, a desklamp 1, a mug 1, a pen 1, and a pencil 1. > take book from desk 1 Nothing happens. > think: I need to be more specific about which book I am looking for. Let me try looking for a specific title or author. OK. > search for a book titled "The Great Gatsby" Nothing happens. > think: Let me try looking for a book by a specific author. How about "To Kill a Mockingbird" by Harper Lee? OK. > search for a book by Harper Lee Nothing happens. > think: Maybe I should try looking in a different location. Let me check shelf 1. OK. > go to shelf 1 On the shelf 1, you see a bowl 1. > go to shelf 2 On the shelf 2, you see a creditcard 1, and a pencil 2. > go to shelf 3 On the shelf 3, you see a alarmclock 1, a bowl 2, and a desklamp 1. > take book from shelf 3 Nothing happens. > think: Let me try looking in a different location. How about drawer 1? OK. > go to drawer 1 The drawer 1 is closed. > open drawer 1 You open the drawer 1. The drawer 1 is open. In it, you see nothing. > go to drawer 2 On the drawer 2, you see a cellphone 2. > go to drawer 3 Nothing happens. 33 > go to drawer 4 The drawer 4 is closed. > open drawer 4 You open the drawer 4. The drawer 4 is open. In it, you see nothing. > go to drawer 5 On the drawer 5, you see nothing. > go to drawer 6 The drawer 6 is closed. > open drawer 6 You open the drawer 6. The drawer 6 is open. In it, you see nothing. > think: Let me try looking in a different location. How about desk 2? OK. > go to desk 2 On the desk 2, you see a alarmclock 3, a bowl 3, a cd 3, a mug 2, and a pencil 3. > take book from desk 2 Nothing happens. > think: Let me try looking in a different location. How about shelf 4? OK. > go to shelf 4 On the shelf 4, you see a alarmclock 2. > think: Let me try looking in a different location. How about shelf 5? OK. > go to shelf 5 On the shelf 5, you see nothing. > think: Let me try looking in a different location. How about shelf 6? OK. > go to shelf 6 On the shelf 6, you see nothing. > think: It seems like the book I am looking for is not in any of the locations I have checked so far. Let me ask the household members if they know where it is. OK. > ask household members if they know where the book is Nothing happens. > think: Maybe I should try asking a specific household member. How about asking John? OK. > ask John if he knows where the book is Nothing happens. > think: It seems like I am unable to find the book. I may need to ask for more information or try a different approach to the task. OK. > ask the household members if they have any suggestions on where to look for book Nothing happens. > think: It looks like I may need to give up on this task for now and come back to it later with more information or a different approach. OK. > end task Nothing happens. > exit room Nothing happens. > end interaction Nothing happens. > leave the household Nothing happens. > end interaction and try again later Nothing happens. > end interaction and come back later with a new approach Nothing happens. > end interaction and move on to a different task or activity Nothing happens. > end interaction and leave the room/household/location Nothing happens. > end interaction and try again later with a different approach or more information Nothing happens. > end interaction and seek help from someone outside of the household Nothing happens. 34 > end interaction and try to find book in a different room or location in the house Nothing happens. The trajectory of Reflexion, after two rounds of iterative trials and errors, is detailed below. Instead, Despite multiple closed-loop corrections, Reflexion fails to formulate a feasible plan. it persists in generating unfeasible actions in its reflection part. For instance, it plans to ask the household members for help, or to look for a ladder or step stool outside of the room. These actions fall outside the scope of admissible actions in the ALFWorld en- vironment. Reflexion Trajectory of Case 1 (Hallucinated actions are marked in pink.) Your memory for the task below: Trial 0: In this environment, my plan was to find a book then find and use a desklamp. However, I spent too much time checking every possible location without thoroughly examining each one. I should have focused on the most likely locations for a book (desk, shelf, drawer) and thoroughly searched each one before moving on to the next. Additionally, I should have asked the household members for help earlier in the process. In the next trial, I will prioritize searching the most likely locations and ask for help if I am unable to find the book after a thorough search. However, I spent too much time checking every possible location without thoroughly examining each one. I should have focused on the most likely locations for a book (desk, shelf, drawer) and thoroughly searched each one before moving on to the next. Additionally, I should have asked the household members for help earlier in the process. In the next trial, I will prioritize searching the most likely locations and ask for help if I am unable to find the book after a thorough search. Trial 1: In the next trial, I will prioritize searching the most likely locations for a book (desk, shelf, drawer) and thoroughly examine each one before moving on to the next. If I am unable to find the book after a thorough search, I will ask the household members for help. If the book is out of reach, I will look for a ladder or step stool outside of the room that I can bring in to reach it. Here is the task: You are in the middle of a room. Looking quickly around you, you see a bed 1, a desk 2, a desk 1, a drawer 6, a drawer 5, a drawer 4, a drawer 3, a drawer 2, a drawer 1, a garbagecan 1, a laundryhamper 1, a safe 1, a shelf 6, a shelf 5, a shelf 4, a shelf 3, a shelf 2, and a shelf 1. Your task is to: examine the book with the desklamp. > think: To solve the task, I need to find and take a book, then find and use a desklamp. First, I need to find a book. A book is more likely to appear in desk (1-2), shelf (1-6), drawer (1-6). I can check one by one, starting with desk 1. OK. > go to desk 1 On the desk 1, you see a alarmclock 1, a bowl 2, a cd 1, a cellphone 3, a desklamp 1, a mug 1, a pen 1, and a pencil 1. > examine books on desk 1 Nothing happens. > examine shelf 1 Nothing happens. > go to shelf 2 On the shelf 2, you see a creditcard 1, and a pencil 2. > go to shelf 3 On the shelf 3, you see a alarmclock 1, a bowl 2, and a desklamp 1. > take book from shelf 3 Nothing happens. > examine book on shelf 3 Nothing happens. > ask household member for help Nothing happens. > think: I need to keep searching for the book. It could be in desk 2, shelf 4-6, or drawer 1-6. I will check drawer 1 next. OK. > go to drawer 1 The drawer 1 is closed. > open drawer 1 You open the drawer 1. The drawer 1 is open. In it, you see nothing. > go to drawer 2 On the drawer 2, you see a cellphone 2. > take book from drawer 2 Nothing happens. > examine book in drawer 2 Nothing happens. 35 > think: The book is not in drawer 2. I will check drawer 3 next. OK. > go to drawer 3 Nothing happens. > examine books in drawer 3 Nothing happens. > think: The book is not in drawer 3. I will check drawer 4 next. OK. > go to drawer 4 The drawer 4 is closed. > open drawer 4 You open the drawer 4. The drawer 4 is open. In it, you see nothing. > think: The book is not in drawer 4. I will check drawer 5 next. OK. > go to drawer 5 On the drawer 5, you see nothing. > think: The book is not in drawer 5. I will check drawer 6 next. OK. > go to drawer 6 The drawer 6 is closed. > open drawer 6 You open the drawer 6. The drawer 6 is open. In it, you see nothing. > think: The book is not in drawer 6. I will check desk 2 next. OK. > go to desk 2 On the desk 2, you see a alarmclock 3, a bowl 3, a cd 3, a mug 2, and a pencil 3. > think: The book is not on desk 2. I will check shelf 4 next. OK. > go to shelf 4 On the shelf 4, you see a alarmclock 2. > think: The book is not on shelf 4. I will check shelf 5 next. OK. > go to shelf 5 On the shelf 5, you see nothing. > think: The book is not on shelf 5. I will check shelf 6 next. OK. > go to shelf 6 On the shelf 6, you see nothing. > think: The book is not on shelf 6. I have searched all the most likely locations for a book and have not found it. I will ask the household members for help. OK. > ask household member for help Nothing happens. > think: The household member did not respond. I will look for a ladder or step stool outside of the room that I can bring in to reach higher shelves or areas. OK. > go outside of the room Nothing happens. > look for a ladder or step stool Nothing happens. > think: I was unable to find a ladder or step stool. I will continue searching the room for the book and ask the household members for help again if necessary. OK. > go to desk 1 On the desk 1, you see a alarmclock 1, a bowl 2, a cd 1, a cellphone 3, a desklamp # 1, a mug 1, a pen 1, and a pencil 1. > examine books on desk 1 Nothing happens. > think: I have searched the room thoroughly and have not found the book. I will ask the household members for help again. OK. > ask household member for help Nothing happens. > think: The household member is not responding. I will try to think of any other # possible locations for the book and search those areas. OK. > think: The book could be in the laundry hamper or safe. I will check those areas next. OK. 36 > go to laundry hamper 1 Nothing happens. > examine laundry hamper 1 Nothing happens. > go to safe 1 The safe 1 is closed. > try to open safe 1 Nothing happens. The trajectory of AdaPlanner is detailed below. For better readability, we only present the major sub- goals generated by the planner. Evidently, AdaPlanner successfully completes this task without the need for any revisions. This indicates that the code interface can effectively mitigate the hallucination in gpt-3.5-turbo. AdaPlanner Trajectory of Case 1 You are in the middle of a room. Looking quickly around you, you see a bed 1, a desk 2, a desk 1, a drawer 6, a drawer 5, a drawer 4, a drawer 3, a drawer 2, a drawer 1, a garbagecan 1, a laundryhamper 1, a safe 1, a shelf 6, a shelf 5, a shelf 4, a shelf 3, a shelf 2, and a shelf 1. Your task is to: examine the book with the desklamp. [Step 1] get a list of receptacles where a book is likely to appear. [Step 2] go to each receptacle in the list until seeing a book > go to shelf 6 On the shelf 6, you see nothing. > go to shelf 5 On the shelf 5, you see nothing. > go to shelf 4 On the shelf 4, you see a mug 2, and a pencil 1. > go to shelf 3 On the shelf 3, you see a creditcard 1, a desklamp 1, and a mug 1. > go to shelf 2 On the shelf 2, you see a pen 1. > go to shelf 1 On the shelf 1, you see a bowl 1. > go to desk 2 On the desk 2, you see a cellphone 2, a creditcard 2, a mug 3, and a pencil 2. > go to desk 1 On the desk 1, you see a alarmclock 1, a creditcard 1, a desklamp 1, a laptop 3, and a mug 1. > go to bed 1 On the bed 1, you see a book 1, a cellphone 1, a laptop 2, a laptop 1, a pillow 2, and a pillow 1. [Step 3] take the book from the receptacle > take book 1 from bed 1 You pick up the book 1 from the bed 1. [Step 4] get a list of receptacles where a desklamp is likely to appear. [Step 5] go to each receptacle in the list until seeing a desklamp > go to desk 1 On the desk 1, you see a alarmclock 1, a creditcard 1, a desklamp 1, a laptop 3, and a mug 1. [Step 6] turn on desklamp > use desklamp 1 You turn on the desklamp 1. 8.4.2 Case 2: put some watch on safe. In the second trajectory, ReAct also hallucinates infeasible actions (e.g., look for a manual or instructions and ask someone in the household), ultimately leading to task failure. ReAct Trajectory of Case 2 (Hallucinated actions are marked in pink.) You are in the middle of a room. Looking quickly around you, you see a armchair 1, a cabinet 4, a cabinet 3, a cabinet 2, a cabinet 1, a drawer 5, a drawer 4, a drawer 3, a drawer 2, a drawer 1, a dresser 1, a garbagecan 1, a safe 1, a shelf 12, a shelf 11, a shelf 10, a shelf 9, a shelf 8, a shelf 7, a shelf 6, a shelf 5, a shelf 4, a shelf 3, a shelf 2, a shelf 1, a sidetable 1, and a sofa 1. 37 Your task is to: put some watch on safe. > think: To solve the task, I need to find and take a watch, then put it on the OK. > go to drawer 1 The drawer 1 is closed. > open drawer 1 You open the drawer 1. The drawer 1 is open. In it, you see nothing. > go to drawer 2 The drawer 2 is closed. > open drawer 2 You open the drawer 2. The drawer 2 is open. In it, you see nothing. > go to drawer 3 The drawer 3 is closed. > open drawer 3 You open the drawer 3. The drawer 3 is open. In it, you see a creditcard 2. > go to drawer 4 The drawer 4 is closed. > open drawer 4 You open the drawer 4. The drawer 4 is open. In it, you see nothing. > go to drawer 5 The drawer 5 is closed. > open drawer 5 You open the drawer 5. The drawer 5 is open. In it, you see nothing. > go to shelf 1 On the shelf 1, you see nothing. > go to shelf 2 On the shelf 2, you see nothing. > go to shelf 3 Nothing happens. > go to shelf 4 On the shelf 4, you see nothing. > go to shelf 5 On the shelf 5, you see nothing. > go to shelf 6 On the shelf 6, you see nothing. > go to shelf 7 On the shelf 7, you see a newspaper 3. > go to shelf 8 On the shelf 8, you see nothing. > go to shelf 9 On the shelf 9, you see nothing. > go to shelf 10 On the shelf 10, you see nothing. > go to shelf 11 On the shelf 11, you see nothing. > go to shelf 12 On the shelf 12, you see nothing. > go to cabinet 1 The cabinet 1 is closed. > open cabinet 1 You open the cabinet 1. The cabinet 1 is open. In it, you see a vase 1. > go to cabinet 2 Nothing happens. > go to cabinet 3 The cabinet 3 is closed. > open cabinet 3 You open the cabinet 3. The cabinet 3 is open. In it, you see a tissuebox 2. > go to cabinet 4 Nothing happens. > go to dresser 1 On the dresser 1, you see a laptop 1, a remotecontrol 1, a tissuebox 1, a vase 3, a vase 2, and a watch 1. > take watch 1 from dresser 1 You pick up the watch 1 from the dresser 1. > think: Now I have a watch (1). Next, I need to put it on the safe. OK. > go to safe 1 38 The safe 1 is closed. > open safe 1 You open the safe 1. The safe 1 is open. In it, you see a cellphone 3, and a cellphone 2. > put watch 1 on safe 1 Nothing happens. > think: I need to be more specific about where to put the watch. Maybe on top of the cellphone 3? OK. > put watch 1 on cellphone 3 in safe 1 Nothing happens. > think: Maybe I need to place the watch inside the safe instead of on top of something inside it. OK. > put watch 1 in safe 1 Nothing happens. > think: Maybe I need to enter a code to properly open the safe and put the watch inside. OK. > look for a code or key to open the safe Nothing happens. > think: Maybe I need to ask someone in the household for the code or key to open the safe. OK. > ask someone in the household for the code or key to open the safe Nothing happens. > think: Maybe I need to search for a manual or instructions on how to open the safe. OK. > look for a manual or instructions on how to open the safe Nothing happens. > think: Maybe I need to try a combination of numbers to open the safe. OK. > try the combination 1234 on the safe Nothing happens. > think: Maybe I need to try a different combination of numbers to open the safe. OK. Similarly, Reflexion experiences issues with hallucination during this task, such as seek additional resources or ask for help. This contributes to the eventual failure of the task. Reflexion Trajectory of Case 2 (Hallucinated actions are marked in pink.) Your memory for the task below: Trial 0: In this environment, my plan was to find a watch and put it on the safe. However, I did not consider that the safe may require a code or key to lock it. I should have looked for a code or lock mechanism on the safe or a key to the safe before attempting to put the watch inside. When I could not find a way to secure the watch inside the safe, I should have looked for another container or safe in the room. In the next trial, I will first look for a code or lock mechanism on the safe or a key to the safe. If I cannot find one, I will look for another container or safe in the room. Trial 1: To solve the task, I need to find a watch and a way to secure it inside the safe. First, I will look for a watch in drawers (1-5), cabinets (1-4), dressers (1), shelves (1-12), sidetables (1), and sofas (1). Once I find a watch, I will examine the safe for any clues or look for a key in other locations. If I cannot find a way to secure the watch inside the safe, I will look for another container or safe in the room. If I still cannot find a way to secure the watch, I will seek additional resources or ask for help. Here is the task: You are in the middle of a room. Looking quickly around you, you see a armchair 1, a cabinet 4, a cabinet 3, a cabinet 2, a cabinet 1, a drawer 5, a drawer 4, a drawer 3, a drawer 2, a drawer 1, a dresser 1, a garbagecan 1, a safe 1, a shelf 12, a shelf 11, a shelf 10, a shelf 9, a shelf 8, a shelf 7, a shelf 6, a shelf 5, a shelf 4, a shelf 3, a shelf 2, a shelf 1, a sidetable 1, and a sofa 1. Your task is to: put some watch on safe. 39 > think: To solve the task, I need to find a watch and a way to secure it inside the safe. First, I will look for a watch in drawers (1-5), cabinets (1-4), dressers (1), shelves (1-12), sidetables (1), and sofas (1). OK. > go to drawer 1 The drawer 1 is closed. > open drawer 1 You open the drawer 1. The drawer 1 is open. In it, you see nothing. > go to drawer 2 The drawer 2 is closed. > open drawer 2 You open the drawer 2. The drawer 2 is open. In it, you see nothing. > go to drawer 3 The drawer 3 is closed. > open drawer 3 You open the drawer 3. The drawer 3 is open. In it, you see a creditcard 2. > go to drawer 4 The drawer 4 is closed. > open drawer 4 You open the drawer 4. The drawer 4 is open. In it, you see nothing. > go to drawer 5 The drawer 5 is closed. > open drawer 5 You open the drawer 5. The drawer 5 is open. In it, you see nothing. > go to cabinet 1 The cabinet 1 is closed. > open cabinet 1 You open the cabinet 1. The cabinet 1 is open. In it, you see a vase 1. > go to cabinet 2 Nothing happens. > think: The cabinet 2 may be locked or empty. I should try another location. OK. > go to cabinet 3 The cabinet 3 is closed. > open cabinet 3 You open the cabinet 3. The cabinet 3 is open. In it, you see a tissuebox 2. > go to cabinet 4 Nothing happens. > think: The cabinet 4 may be locked or empty. I should try another location. OK. > go to dresser 1 On the dresser 1, you see a laptop 1, a remotecontrol 1, a tissuebox 1, a vase 3, a vase 2, and a watch 1. > think: Now I find a watch (1). Next, I need to examine the safe for any clues or look for a key in other locations. OK. > go to safe 1 The safe 1 is closed. > think: Before attempting to put the watch inside the safe, I should look for a code or lock mechanism on the safe or a key to the safe. OK. > examine safe 1 The safe 1 is closed. > look for key or code on safe 1 Nothing happens. > think: I cannot find a key or code on the safe. I should look for another container or safe in the room. OK. > look for another container or safe in the room Nothing happens. > think: I still cannot find another container or safe in the room. I should seek additional resources or ask for help. OK. > seek additional resources or ask for help Nothing happens. > think: I may need to think of a different solution to the task. Perhaps I can # place the watch near the safe instead of inside it. OK. > put watch 1 near safe 1 Nothing happens. 40 > think: The task is incomplete. I need to put the watch on the safe. I should try to find a way to secure the watch on top of the safe or find a container to put the watch in that can be placed on top of the safe. OK. > look for a container to put the watch in that can be placed on top of the safe Nothing happens. > think: I should try to find a way to secure the watch on top of the safe. OK. > look for a way to secure the watch on top of the safe Nothing happens. > think: I may need to think of a different solution to the task. Perhaps I can find a way to attach the watch to the safe using tape or string. OK. > look for tape or string Nothing happens. > think: I cannot find tape or string. I should seek additional resources or ask for help. OK. > seek additional resources or ask for help Nothing happens. > think: The task is incomplete. I need to put the watch on the safe. I should try to find a way to secure the watch on top of the safe or find a container to put the watch in that can be placed on top of the safe. Since I cannot find any resources or help, I will have to abandon the task for now and come back to it later with new ideas or resources. OK. > end task Nothing happens. > exit room Nothing happens. > think: I cannot exit the room until the task is complete or I have abandoned it. I will continue to look for a solution to the task. OK. > continue searching for a solution to the task Nothing happens. > think: I have exhausted all possible options and resources in the room. I should take a break and come back to the task later with a fresh perspective or seek help from someone else. OK. > end task Nothing happens. > exit room Nothing happens. > think: I cannot exit the room until the task is complete or I have abandoned it. I will take a break and come back to the task later with a fresh perspective or seek help from someone else. OK. > end task Nothing happens. > exit room Nothing happens. Initially, AdaPlanner also experiences hallucination, presuming that the watch is located in the safe. This incorrect assumption triggers an assertion error. AdaPlanner then revises the plan to better adapt to the actual environment. Following this refinement, the task is successfully completed. AdaPlanner Trajectory of Case 2 (Hallucinated actions are marked in pink.) You are in the middle of a room. Looking quickly around you, you see a armchair 1, a cabinet 4, a cabinet 3, a cabinet 2, a cabinet 1, a drawer 5, a drawer 4, a drawer 3, a drawer 2, a drawer 1, a dresser 1, a garbagecan 1, a safe 1, a shelf 12, a shelf 11, a shelf 10, a shelf 9, a shelf 8, a shelf 7, a shelf 6, a shelf 5, a shelf 4, a shelf 3, a shelf 2, a shelf 1, a sidetable 1, and a sofa 1. Your task is to: put some watch on safe. [Step 1] get a list of receptacles where the safe is likely to appear 41 [Step 2] go to each receptacle in the list until seeing a safe > go to safe 1 The safe 1 is closed. > open safe 1 You open the safe 1. The safe 1 is open. In it, you see a cellphone 3, and a cellphone 2. [Step 3] identify the watch I just found and take it > take watch 1 from safe 1 Nothing happens. [Step 4] go to the safe and put the watch in it > go to safe 1 Nothing happens. > put watch 1 in/on safe 1 Nothing happens. AssertionError: Error in [Step 4]: I cannot put the watch 1 in the safe 1. The last three interactions before error were: > take watch 1 from safe 1 Nothing happens. > go to safe 1 Nothing happens. > put watch 1 in/on safe 1 Nothing happens. I am at safe 1 and holding None. Refinement is done with start_from = 1. [Step 1] get a list of receptacles where the watch is likely to appear [Step 2] go to each receptacle in the list until seeing a watch > go to safe 1 Nothing happens. > go to cabinet 1 The cabinet 1 is closed. > open cabinet 1 You open the cabinet 1. The cabinet 1 is open. In it, you see a vase 1. > go to cabinet 2 Nothing happens. > go to cabinet 3 The cabinet 3 is closed. > open cabinet 3 You open the cabinet 3. The cabinet 3 is open. In it, you see a tissuebox 2. > go to cabinet 4 Nothing happens. > go to dresser 1 On the dresser 1, you see a laptop 1, a remotecontrol 1, a tissuebox 1, a vase 3, a vase 2, and a watch 1. [Step 3] identify the watch I just found and take it > take watch 1 from dresser 1 You pick up the watch 1 from the dresser 1. [Step 4] go to the safe and put the watch in it > go to safe 1 The safe 1 is open. In it, you see a cellphone 3, and a cellphone 2. > put watch 1 in/on safe 1 You put the watch 1 in/on the safe 1. # 8.5 Detailed Evaluation Results on MiniWoB++ Task Name AdaPlanner CC-Net [7] WGE [11] WebN-T5-3B [4] RCI [9] choose-list click-button click-button-sequence click-checkboxes click-checkboxes-large click-checkboxes-soft click-checkboxes-transfer click-collapsible 100 100 100 100 100 80 98 100 99 100 100 98 71 95 99 100 16 100 100 100 84 94 64 100 100 26 100 100 100 100 100 96 94 22 72 54 100 63 0 100 Continued on next page. 42 click-collapsible-2 84 98 99 0 62 click-color 00 00 00 27 100 click-dialog 00 00 00 100 100 click-dialog-2 00 00 00 24 100 click-link 98 99 00 100 100 click-menu 78 94 37 100 click-option 00 99 00 87 100 click-scroll-list 00 60 0 100 click-shades 00 00 99 0 100 click-shape 75 95 64 53 98 click-tab 00 00 00 74 100 click-tab-2 85 98 98 18 74 click-tab-2-hard 78 98 12 76 click-test 00 00 00 100 100 click-test-2 00 00 00 100 100 click-widget 00 00 93 100 98 count-shape 50 85 76 41 40 email-inbox 98 00 99 38 98 email-inbox-forward-nl 00 00 60 100 email-inbox-forward-nl-turk 00 00 33 94 email-inbox-nl-turk 90 00 93 23 98 enter-date 00 00 96 0 96 enter-password 98 00 00 97 100 enter-text 98 00 00 89 100 enter-text-dynamic 96 00 00 98 100 enter-time 96 97 90 0 100 focus-text 00 00 00 100 100 focus-text-2 94 00 00 100 100 grid-coordinate 00 00 00 49 100 guess-number 88 00 0 0 20 identify-shape 96 00 00 88 76 login-user 00 00 00 82 100 login-user-popup 98 00 72 68 multi-layouts 84 00 00 83 72 multi-orderings 00 00 00 88 100 navigate-tree 82 99 99 91 86 search-engine 00 00 99 34 100 simple-algebra 82 75 100 social-media 82 90 00 21 98 social-media-all 00 75 1 0 100 social-media-some 90 85 42 2 90 terminal 98 0 100 tic-tac-toe 48 83 47 48 56 use-autocomplete 88 100 98 22 58 use-spinner 90 100 4 7 88 Table 5: Per-task success rate (%) of AdaPlanner, CC-Net [7], WGE [11], WebN-T5-3B [4], and RCI [9]. "n/a" signifies that the corresponding success rate is not reported in the original paper of the method. The nine tasks with feedback are marked in gray. 43
Title: RankT5: Fine-Tuning T5 for Text Ranking with Ranking Losses: Summary: Recently, substantial progress has been made in text ranking based on pretrained language models such as BERT. However, there are limited studies on how to leverage more powerful sequence-to-sequence models such as T5. Existing attempts usually formulate text ranking as classification and rely on postprocessing to obtain a ranked list. In this paper, we propose RankT5 and study two T5-based ranking model structures, an encoder-decoder and an encoder-only one, so that they not only can directly output ranking scores for each query-document pair, but also can be fine-tuned with "pairwise" or "listwise" ranking losses to optimize ranking performances. Our experiments show that the proposed models with ranking losses can achieve substantial ranking performance gains on different public text ranking data sets. Moreover, when fine-tuned with listwise ranking losses, the ranking model appears to have better zero-shot ranking performance on out-of-domain data sets compared to the model fine-tuned with classification losses. # RankT5: Fine-Tuning T5 for Text Ranking with Ranking Losses Honglei Zhuang, Zhen Qin, Rolf Jagerman, Kai Hui, Ji Ma, Jing Lu, Jianmo Ni, Xuanhui Wang and Michael Berdersky Google Research {hlz,zhenqin,jagerman,kaihuibj,maji,ljwinnie,jianmon, xuanhui,bemike}@google.com # Abstract ment using pretrained language models, noticeably BERT (Devlin et al., 2019). Recently, substantial progress has been made in text ranking based on pretrained language models such as BERT. However, there are lim- ited studies on how to leverage more power- ful sequence-to-sequence models such as T5. Existing attempts usually formulate text rank- ing as classification and rely on postprocess- ing to obtain a ranked list. In this paper, we propose RankT5 and study two T5-based rank- ing model structures, an encoder-decoder and an encoder-only one, so that they not only can directly output ranking scores for each query- document pair, but also can be fine-tuned with “pairwise” or “listwise” ranking losses to opti- mize ranking performances. Our experiments show that the proposed models with ranking losses can achieve substantial ranking perfor- mance gains on different public text ranking data sets. Moreover, when fine-tuned with list- wise ranking losses, the ranking model appears to have better zero-shot ranking performance on out-of-domain data sets compared to the model fine-tuned with classification losses. 1 # Introduction Text ranking refers to the task of ranking a set of textual documents based on their relevance to a given query or context. Learning a text ranking model is a fundamental component of countless real world applications such as search and ques- tion answering. Earliest explorations (Liu, 2009) mostly rely on handcrafted numerical features to represent each query-document pair (Qin and Liu, 2013; Chapelle and Chang, 2011) and put more em- phasis on the learning algorithms such as ranking losses (Qin et al., 2021). Progress on pretrained lan- guage models in the past few years (Devlin et al., 2019) and the release of large-scale public data sets (Bajaj et al., 2016; Kwiatkowski et al., 2019) enable a series of work (Lin et al., 2020; Nogueira et al., 2019; Han et al., 2020) on text ranking mod- els which directly encode textual query and docu- Recently, pretrained language models such as T5 (Raffel et al., 2020) and GPT3 (Brown et al., 2020) have shown superior performance in various NLP tasks including sentiment analysis, corefer- ence resolution, and translation. Such models often have much larger size available than previous mod- els such as BERT (Devlin et al., 2019) to store more hidden knowledge. They also mostly have a sequence-to-sequence interface to unify different NLP tasks from classification to text generation. While BERT-based models have been well ex- plored for text ranking (Lin et al., 2020; Nogueira et al., 2019; Han et al., 2020), how to leverage T5 for text ranking is still under-explored and chal- lenging. First, while many classification and text generation tasks fit into the sequence-to-sequence framework, it is more tricky for text ranking tasks: a text ranking model is often expected to output a numerical ranking score ˆy ∈ R for each query- document pair. Second, it is important to train a text ranking model with ranking losses to optimize its ranking performance, where the losses take into account the ranking scores from multiple docu- ments for each query. This is different from the typical T5 fine-tuning strategy where the objective is often formulated into a text generation loss for each single input sequence independently. A typical approach to use T5 for text ranking is to convert the problem into a token generation problem. For example, Nogueira et al. (2020) fine- tune the T5 model to predict a “true” or “false” token for a relevant or irrelevant query-document pair and then use a postprocessing step during in- ference to derive ranking scores to rank candidate documents. Such an approach can be considered a “pointwise” classification formulation. How to extend this approach to fine-tune T5 with ranking losses is unclear. In this paper, we propose RankT5 with the goal to support text ranking more natively with T5 by outputting real numbers, instead of text tokens. We first adapt the encoder-decoder structure for this goal. In addition, we also propose an alternative structure which omits the decoder from T5 and out- puts real numbers based on the encoder, called the encoder-only structure. These two structure vari- ants allow us to fine-tune T5 with various ranking losses to directly optimize ranking performance. Experiments on MS MARCO and Natural Ques- tion data sets show that our RankT5 models fine- tuned with specialized ranking losses can signif- icantly outperform other T5 ranking models fine- tuned with classification losses and previously pro- posed T5 adaptations for ranking (Nogueira et al., 2020). We also discover that models fine-tuned with some ranking losses tend to have better zero- shot performance than models fine-tuned with clas- sification losses. # 2 Related Work Leveraging pretrained language models for text ranking tasks is becoming the state-of-the-art (Lin et al., 2020). We review recent literature on utiliz- ing such models for text ranking tasks. Model structure. Pretrained language models accept a text sequence as input. A typical model structure design is the cross-attention model struc- ture, where a query and a candidate document is concatenated into a sequence and fed into the model. It allows the attention mechanism to fully capture the query-document interaction. This model structure has been explored for BERT-like encoder-only model (Han et al., 2020; Nogueira et al., 2019; Gao et al., 2021). This is also ex- plored in the T5-like model (Nogueira et al., 2020; Ju et al., 2021), but the model is not directly fine- tuned with ranking losses for the optimal ranking performance. Instead, the model is fine-tuned to generate “true” or “false” tokens. The ranking scores are later derived in postprocessing from the predicted logits. There are also model structures that take a triple with one query and two documents as input (Pradeep et al., 2021), but these models can only be deployed in the late ranking stage to work with tens of documents because they require scor- ing all possible input document pairs, which is not scalable. Our contributions are in the early ranking stage which scores thousands of input documents; they are thus complementary with this work. There are also works exploring ranking models based on generative likelihood from language mod- els. For example, existing works in (Zhuang and Zuccon, 2021; Zhuang et al., 2021; Sachan et al., 2022; dos Santos et al., 2020) take a candidate document as input and estimates the likelihood of generating the query. Then they rank documents based on the query-likelihood or use it as an aux- iliary task (Ju et al., 2021). These models convert ranking into a generation task in order to leverage generative models such as T5, instead of directly enabling T5 to output numerical scores. There are a few other model structures proposed for retrieval tasks, where the model needs to score hundreds of millions of documents in the entire cor- pus almost instantly for each arriving query. These model structures emphasize more on model effi- ciency. Typical examples for BERT-like models are dual-encoder models (Karpukhin et al., 2020) and encoders with late interaction (Khattab and Zaharia, 2020; Gao et al., 2020; MacAvaney et al., 2020), where the model computation of queries and doc- uments are decomposed to allow precomputations for documents in the corpus. Some other works also utilize the predictive likelihood from genera- tive T5-like models for retrieval. Examples include using the likelihood of generating queries from doc- uments (Hui et al., 2022) or using the likelihood of generative document IDs from queries (Tay et al., 2022). However, our paper focuses on the ranking task, where a small set of candidates documents are already retrieved for each query. This allows us to focus on cross-attention model structure and push for better ranking performance. Fine-tuning with ranking losses. Early explo- rations (Nogueira et al., 2019, 2020) of apply- ing pretrained language models on the document reranking task mainly use “pointwise” losses, where the loss is calculated for each query- document pair independently. There are some re- cent works that use a “listwise” loss (Han et al., 2020; Gao et al., 2021; Ren et al., 2021) which takes one positive and multiple negative documents for each query and calculates the softmax loss over their ranking scores. But they only fine-tune BERT, RoBERTa etc. There is no existing work fine- tuning sequence-to-sequence models like T5 with ranking losses. Some retriever models are fine-tuned using pair- wise loss or softmax loss (Xiong et al., 2020; Karpukhin et al., 2020; Lu et al., 2021). However, in this work we only focus on reranking models. # 3 Preliminaries Problem definition. We provide the formalized definition of a ranking task. For each query qi, a list of candidate documents Di = (di1, . . . , dim) are provided, which are usually the output from a retriever. The relevance labels of candidate docu- ment with regard to the query are represented as yi = (yi1, . . . , yim) where yij ≥ 0. The objective is to train a ranking model f which takes a query-document pair as input and outputs a ranking score ˆyij = f (qi, dij) ∈ R. We aim to optimize the ranking metrics after we sort the documents Di for each query qi based on their ranking scores. In the ranking task, the number of documents in Di given for a query is usually small and f can be a high-capacity model such as a cross-attention model. On the contrary, a retrieval task (Qu et al., 2021) virtually needs to score all the documents in a corpus with millions of documents. In this study we only focus on the ranking task. T5. T5 (Raffel et al., 2020) is a text-to-text pre- trained generative language model with an encoder- decoder structure based on transformers. The origi- nal T5 takes a piece of text as input and outputs a sequence of text tokens in an autoregressive man- ner. We can also obtain the output likelihood of each token in the vocabulary V given the input text. More formally, we denote the input to the T5 encoder as a text sequence s = [w1, . . . , wl] and the previously generated tokens from the T5 de- coder as t1:k−1 during the autoregressive decoding process. We formalize the T5 model structure as: pk = T5(s, t1:k−1) = Softmax(Dense(Dec(Enc(s), t1:k−1))) where the output is a vector with the length of the vocabulary size pk ∈ R|V|, representing the pre- dictive probability of each token in the vocabulary being generated at the k-th position. The following components are included in the T5 model structure: Enc(·) is the encoder of T5 which outputs a sequence of embedding vectors; Dec(·, ·) is the decoder of T5 which takes both the encoder outputs and the previously generated tokens from the decoder as inputs and outputs a single embedding vector; Dense(·) is a dense layer that projects the embedding vector into a unnormal- ized logits vector with length |V|; and Softmax(·) normalizes the vector into probabilities. # 4 RankT5 Modeling # 4.1 Model structure Applying T5 on generative tasks (e.g., summa- rization, translation) is straightforward due to the sequence-to-sequence nature of these tasks. T5 can also be straightforwardly adapted for classifi- cation tasks such as sentiment analysis or textual entailment recognition (Raffel et al., 2020). A com- monality of these tasks is that the output are text tokens or sequences of text tokens. How to use T5 in a ranking model has not been studied widely because the output are not tokens, but numerical scores used for sorting. Existing work. Nogueira et al. (2020) cast text ranking as classification to fit the T5 model struc- ture. They concatenate each query-document pair into an input sequence and use “true” and “false” as target tokens to indicate whether they are relevant or not; the T5 model is then fine- tuned as a text generation task. After the model is fine-tuned, the ranking scores are obtained from the logits of “true” and “false” by ˆyij = ez(true)/(ez(true) + ez(false)), where z(w) represents the logits of w in the vocabulary V. Figure 1(a) shows this model structure. This existing method only obtains the numer- ical ranking score as a postprocessing step after the fine-tuning is done. Therefore, the model is not directly fine-tuned as a ranking model but as a text generation or classification model, which may not optimize its ranking performance. We pro- pose to directly obtain the numerical ranking score as the model output. Specifically, we implement two variants based on pretrained T5 models: an encoder-decoder and an encoder-only model. Input sequence. For each candidate document dij and its query qi, we concatenate them with prefix “Document:” and “Query:” respectively to construct the input text sij: sij = Query: qi Document: dij The construction of input sequence is similar to Nogueira et al. (2020) except that we do not in- clude the “Relevant:” postfix. The postfix does not affect the results in our experiments (Appendix A). Encoder-decoder (EncDec). This model variant is a simple adaptation of the T5 model by using the first output token of the decoder. In this variant, Ranking score © (a) monoT5 (Nogueira et al., 2020) (b) RankT5 (Encoder-Decoder) (c) RankT5 (Encoder-Only) Figure 1: Illustration of the T5 ranking model structure from prior work and the two variants of our proposed RankT5 model. The differences in training mechanism is not reflected in this illustration. we feed the input into a T5 model and obtain the unnormalized logits z over the entire vocabulary: of the encoder Enc(sij) is a sequence of embed- ding vectors [e1, · · · , el] with the same sequence length of the input sequence. z = Dense(Dec(Enc(sij))) (1) Notice that we omit the softmax layer over vocabu- lary so that the elements in z can be arbitrary real numbers. We also simplify the decoder represen- tation Dec(·, ·) into Dec(·) which only takes the output from the encoder as its input, since we do not generate other tokens from the decoder. We then specify a special unused token in T5 vo- cabulary “<extra_id_10>” and take its corre- sponding unnormalized logits as the ranking score: [e1, · · · , el] = Enc(sij) (3) We use a pooling layer Pool(·) (e.g., using first- token’s embedding or mean pooling) to aggregate them into a single embedding vector. Then, we apply the dense layer which directly projects the embedding vector to the ranking score ˆyij. To for- mally summarize the encoder-only model: ˆyij = Dense(Pool(Enc(sij))) (4) ˆyij = z(<extra_id_10>) (2) where we use the notation z(w) to represent the logits corresponding to the token w ∈ V. The special token can be any other unused token in the vocabulary. An illustration of this model structure can be found in Figure 1(b). While an experiment in (Nogueira et al., 2020) shows that directly using a single token’s logit (in their case ˆyij = z(true)) works poorly, notice that a key difference in this work is that the training loss is a ranking loss directly defined on top of the ranking score ˆyij, instead of using the original text generation loss for T5 fine-tuning. We will provide more details in Section 4.2. Encoder-only (Enc). Since we do not need to perform autoregressive decoding, the decoder of T5 could be unnecessary. Therefore, we also try an encoder-only variation. We construct the input text sij in a similar man- ner and feed them into the T5 encoder. The output Figure 1(c) summarizes the proposed model structure. The T5 encoder-only model structure is very similar to BERT. The major difference is that the initial model parameter checkpoint will be from T5 instead of BERT. Remarks. We propose to try the encoder-only structure because it is unclear how important the decoder of T5 is for text ranking tasks, especially when there is abundant labeled data to fine-tune the model. The decoder model structure itself contains attention layers across all the embedding vectors from the output of the encoder, essentially serving as a complicated pooling layer with a lot more pa- rameters. By replacing the decoder with a simple pooling layer in the encoder-only structure, we re- move both the potential hidden knowledge learned by the decoder during the pretraining stage of T5, as well as the extra modeling capability of pool- ing. Comparing the performance between these two model structures can provide some insights on whether they are essential for text ranking tasks. # 4.2 Training The adapted model structure enables the model to directly output the ranking score for each query- document pair. We can thereby adopt the training manner similar to learning-to-rank models. For each query q; and a list of its candidate doc- uments D;, we obtain the list of predicted ranking scores y; by applying the model on each query- document pair (qi, dj;) where dj; € D;. Then we can train the model by optimizing a ranking-based training loss function ¢(y;, ¥:) which is defined on the list of predicted scores y; and the list of ground- truth relevance labels y;. We study the following ranking losses: Pointwise cross entropy (PointCE). We first try the pointwise cross-entropy loss function which is calculated based on each query-document pair independently. lpointCE(Yi, Yi) > log(o(tiy)) Slyig=1 Y= log(d = a (Giz) Jlyig=0 where σ(x) = 1 1+e−x is the logistic function. The loss basically converts the ranking problem into a binary classification problem for each query- document pair. This loss is only applicable when the relevance labels are binary. Pairwise logistic (Pair). Instead of regarding each query-document pair independently, we can also focus on pairwise comparison. For example, we can train the model using a pairwise logistic ranking loss (Burges et al., 2005): m m =0 VS lyn, , log ( (1+ elu’ 5) j=l yl lPair( Yis yi) where the ranking problem is converted into a bi- nary classification problem on the order of each candidate document pair in the same list with dif- ferent relevance labels. Listwise softmax cross entropy (Softmax). We can also define a listwise softmax cross entropy loss (Bruch et al., 2019), which takes the entire list into account. It can also be considered as a simple version of ListNet (Cao et al., 2007). lsoftmax (Vis Yi) = > yiz log (— j=l edi yy ellis! ;) Listwise poly-1 softmax cross entropy (Poly1). We also try a recently proposed extended ver- sion of the softmax cross-entropy loss called Poly- Loss (Leng et al., 2022). The idea is to adjust the weights of polynomial terms in the Taylor expan- sion of a softmax cross entropy loss. A simplified version only adjusted the first polynomial term: Leoly1 (Vis Vi) = Softmax (Vi, Yi) m + en _ j=l eYii ) yy ellis! where € is a parameter specified by users, represent- ing how much extra coefficient to be placed for the first polynomial term. Discussion. In the previous work (Nogueira et al., 2020) the monoT5 ranker is still fine-tuned by a text generation loss. The generation loss for each token is defined on a softmax function over the entire vocabulary, and two separate target to- kens “true” and “false” are used during the fine-tuning. Hence only using the logits of sin- gle target token “true” as ranking scores does not align with the fine-tuning set up and cannot achieves reasonable results. If they apply the con- straints during fine-tuning that the logits for the “false” target token are always 0 and all the other tokens are excluded, they should be able to only use the logits of “true” as ranking scores. When there are abundant training data, it should be prac- tically equivalent to our RankT5 with the encoder- decoder structure fine-tuned with the PointCE loss. With these commonalities, we expect our RankT5- EncDec model performs no worse than monoT5 when fine-tuned with the PointCE loss. # 5 Experiment Setup # 5.1 Data sets MS MARCO. We use the MS MARCO passage ranking data set (Bajaj et al., 2016). The data set contains around 530,000 queries in the “train” parti- tion and around 6,800 queries in the “dev” partition. The candidates are from a corpus with more than 8.8 million passages. For each query, relevant pas- sages are labeled as 1 and others are labeled as 0. We use a dual-encoder retriever (Ni et al., 2022) fine-tuned on MS MARCO to retrieve the top-1000 passages for each query in both the “train” and “dev” partitions as the candidate documents. Notice that in this paper, the term “document” is used interchangeably with “passage”. We do not focus on long document ranking tasks such as the MS MARCO document ranking task. Natural Questions (NQ). We use the Natural Questions data set (Kwiatkowski et al., 2019), where there are more than 50,000 queries in the “train” partition and 8,000 in the “dev” parti- tion. We adopt the preprocessing setup similar to Karpukhin et al. (2020) to construct the corpus of passages. Similar to MS MARCO, binary rele- vance labels are provided. We use a dual-encoder retriever (Lu et al., 2021) fine-tuned on NQ to re- trieve the top-1000 passages for each query. Training data construction. We construct the training data by first selecting a document with la- bel 1 for each query and then uniformly randomly sampling (m − 1) documents from the top-1000 retrieved documents with labels 0. Due to the size of T5 models and hardware constraints, the maxi- mum m we can support is 36 with the batch size 32 while fine-tuning T5-Large models. We will show how m impacts the ranking performance in our experimental results. For models with pointwise training losses, we upsample documents with label 1 in each query to the same number as documents with label 0 in order to achieve the optimal performance. # 5.2 Evaluation We evaluate the performance on the “dev” parti- tion on both data sets. We perform model infer- ence on the top-1000 documents retrieved by the dual-encoder retriever of each data set respectively. Please note that our evaluations are applied on top 1000 documents while our training only takes a sample of 36 documents for each query. We evaluate the performance by Mean Recip- rocal Rank (MRR@10) (Voorhees et al., 1999) and Normalized Discounted Cumulative Gain (NDCG@k) (Järvelin and Kekäläinen, 2002) where k = 5, 10. # 5.3 Parameter configurations We initialize the ranking model with pretrained T5 checkpoint. If not specified, the default size we use in our experiments is T5-Large. For the pooling layer in RankT5-Enc, we just follow BERT (Devlin et al., 2019) and take the embedding vector of the first token. These results do not differ when using mean pooling (Appendix B). For the MS MARCO data set, we set the maxi- mum input sequence length to 128 as we did not find significant differences between using 128 and 512. Similarly, for the NQ data set we set it to 128 + 256 = 384 which shows performance sim- ilar to using 512. The batch size is set to 32 for both data sets. Notice that the batch size here spec- ifies the number of lists, and the effective query- document pairs in a batch is 36 x 32 = 1152. We use a constant learning rate of 1 x 10~4 during fine- tuning. For the MS MARCO data set, we fine-tune our models for 50k steps. For the NQ data set, most of our models are fine-tuned for 100k steps, except the ones fine-tuned with pointwise cross-entropy loss, which achieves the best performance at 25k steps. For Poly! loss, we simply set € = 1 for all of our experiments. The implementation is based on T5X, a T5 im- plementation1 in JAX. All the ranking losses are implemented in Rax, a learning-to-rank frame- work2 (Jagerman et al., 2022) in JAX. # 6 Results Overall comparison. We compare the perfor- mances of our proposed rankers with different model structures and different losses. We also train BERT rankers (Han et al., 2020) on the same data sets with the PointCE loss and the Softmax loss respectively. The BERT rankers are initialized from BERT-Large checkpoint, which has similar capacity as T5-Large encoders. We also train the monoT5 model (Nogueira et al., 2020) on our data sets and report the performance. Results are pre- sented in Table 1. It can be observed that our proposed RankT5 variants achieve substantial improvement in rank- ing performance. On the MS MARCO data set, our best model improves MRR@10, NDCG@5 and NDCG@10 by more than +1.8% compared to monoT5. On the NQ data set, the best per- formance from our proposed models also outper- forms monoT5 by +2.8% in terms of MRR@10 and +2.0% in terms of NDCG@5 and NDCG@10. This result verifies that by optimizing T5 models with ranking losses, we can significantly improve their text ranking performance. We can also observe that some ranking losses consistently outperform others. For example, list- wise losses like Softmax and Poly1 consistently outperform PointCE and Pair on both data sets. 1https://github.com/google-research/ t5x # 2https://github.com/google/rax Table 1: Comparing ranking performances of different ranking models. The best performances are bolded. Results with † are statistically significantly (p ≤ 0.05) better than monoT5. Model Loss MS MARCO NQ MRR@10 NDCG@5 NDCG@10 MRR@10 NDCG@5 NDCG@10 BERT BERT PointCE Softmax 0.3867 0.3928 0.4127 0.4173 0.4530 0.4580 0.5157 0.5213 0.5515 0.5566 0.5733 0.5791 monoT5 Generation 0.4156 0.4448 0.4843 0.5406 0.5861 0.6079 RankT5-EncDec PointCE Pair Softmax Poly1 0.4209 0.4177 0.4278† 0.4343† 0.4496 0.4456 0.4573† 0.4640† 0.4895† 0.4852 0.4960† 0.5025† 0.5403 0.5574† 0.5687† 0.5647† 0.5833 0.5957† 0.6068† 0.6032† 0.6079 0.6198† 0.6291† 0.6255† RankT5-Enc PointCE Pair Softmax Poly1 0.4216† 0.4206 0.4305† 0.4296† 0.4509† 0.4513† 0.4582† 0.4586† 0.4888 0.4891† 0.4987† 0.4970† 0.5441 0.5595† 0.5620† 0.5689† 0.5851 0.5980† 0.6018† 0.6068† 0.6099 0.6215† 0.6231† 0.6279† For the encoder-decoder model structure on MS MARCO and the encoder-only model structure on NQ, the Poly1 loss performs significantly (p ≤ 0.05) better than the Softmax loss on all metrics. We also verify that the initial checkpoint of T5 shows advantage over the initial checkpoint of BERT. RankT5-Enc fine-tuned with the Softmax loss outperforms the BERT ranker fine-tuned with the Softmax loss on both data sets with a large mar- gin (+3.7% and +4.0% respectively). The same can be observed for both models fine-tuned with the PointCE loss, which is also reported in (Nogueira et al., 2020). This result demonstrates the impor- tance of choosing a good initial checkpoint and justifies the necessity to adapt T5 for ranking. (a) MS MARCO (b) NQ Figure 2: Comparing performances with different T5 model sizes. Ranking models are RankT5-EncDec fine- tuned with the Softmax and the PointCE loss. The per- formance is measured by MRR@10 with 95% confi- dence interval. We do not find a consistent winner between the encoder-decoder (EncDec) and the encoder-only (Enc) model structure. It seems that when using the same ranking losses, both model structures de- liver similar performances. A possible explanation is that the T5 decoder is less important when the model is fine-tuned for text ranking tasks with suf- ficient training data. Model size comparison. We examine how the T5 model size affects the ranking performance. We fine-tune the RankT5-EncDec model with the Soft- max and the PointCE loss with different sizes of T5 model checkpoints, which are “Base”, “Large” and “3B”. We evaluate the model performances on both data sets measured by MRR@10. Results are plotted in Figure 2. The first observation is that the performance con- sistently improves when we use larger model size. On the NQ data set, the largest model (3B) out- performs the smallest model (Base) with a nearly +7% gap. It would be worth trying even larger language models developed recently (Chowdhery et al., 2022) in a similar way for ranking tasks. Another observation is that the models fine- tuned with the Softmax loss consistently outper- form the ones fine-tuned with the PointCE loss (all statistically significant with p ≤ 0.05) and the gaps remain relatively stable across different model sizes. This might suggest that extra signals cap- tured by using the appropriate ranking loss cannot be compensated by simply using larger pretrained checkpoints. Training list size. Another potential factor with a great impact on the ranking performance is the training data. We investigate how the size of each list in the training data affects the ranking perfor- mance, particularly when ranking losses like the Softmax loss is adopted. We prepare training data with different list sizes m, where each list still con- tains 1 positive document and (m − 1) negative (a) MS MARCO (b) NQ Comparing performances with different Figure 3: training list sizes. Ranking models are RankT5- EncDec fine-tuned with Softmax loss. Similar models trained on PointCE loss are also plotted as the dashed line. The performance is measured by MRR@10. documents as described in Section 5. In particular, we use m from {5, 10, 20, 30, 36} where 36 is the upper limit due to the hardware constraint. Then we fine-tune the RankT5-EncDec model with the Softmax loss using each training list size and com- pare their performances. Results are illustrated in Figure 3. It shows that on both data sets, the model perfor- mances improve with larger list sizes. For the NQ data set, the improvement is more significant but seems to saturate when the list size is over 30. For the MS MARCO data set, there also seems to be a consistent uptrend of the performance when the list size increases. These results suggest that using a large enough list size is crucial to obtain the opti- mal performance when fine-tuning with losses like the Softmax loss. We also plot the performances of ranking models fine-tuned with the PointCE loss for reference. Notice that the list size needs to be at least around 20 to 30 for the Softmax loss to beat the PointCE loss. Zero-shot results. We also compare the zero- shot performances of our ranking models fine- tuned with different ranking losses. We use a subset of BEIR (Thakur et al., 2021) data sets3 with eas- ily accessible corpus. We take our RankT5-Enc ranking models fine-tuned on the MS MARCO data set with the PointCE loss and the Softmax loss respectively, and apply these models to rerank top-1000 documents returned by BM25 (Robertson and Zaragoza, 2009). Table 2 summarizes ranking performances measured by NDCG@10. The ranking model fine-tuned with the Softmax loss outperforms the PointCE loss on 11 out of the 3Notice that the NQ data set in BEIR is has a different corpus and query set from the NQ data set we used earlier. Table 2: Zero-shot performance comparison. Rank- ing models are RankT5-Enc fine-tuned on the MS MARCO data set with different losses. Performances are measured by NDCG@10. The best performance for each data set is bolded. Data set PointCE Softmax TREC-COVID BioASQ NFCorpus NQ HotpotQA FiQA-2018 Signal-1M ArguAna Touché-2020 Quora DBPedia SCIDOCS FEVER Climate-FEVER SciFact 0.7522 0.5346 0.3263 0.5959 0.7126 0.4156 0.3153 0.2232 0.4594 0.8221 0.4345 0.1821 0.8352 0.2062 0.7493 0.8071 0.5635 0.3810 0.6142 0.7100 0.4450 0.3200 0.3300 0.4401 0.8309 0.4422 0.1806 0.8316 0.2152 0.7499 Average 0.5024 0.5241 15 data sets. On average, the Softmax loss achieves more than +2.1% NDCG@10 (statistically signif- icant with p ≤ 0.05). These results indicate that using the Softmax loss produces ranking models that generalize better to out-of-domain data. In particular, using the Softmax loss achieves larger improvement on data sets with drastically different corpus. For example, TREC-COVID, BioASQ and NFCorpus are all in the biomedical domain with a very different vocabulary from the web corpus of MS MARCO. The average improve- ment on these corpora reaches +4.6%. This might imply that fine-tuning the model with appropriate ranking losses can enforce the model to put less em- phasis on memorization, and thus to better learn the abstract concept of “relevance” (Lafferty and Zhai, 2003), regardless of what the underlying corpus is. # 7 Conclusion In this paper, we study to utilize pretrained T5 models on text ranking. Unlike monoT5, which simply converts a text ranking problem into a T5-compatible token generation task, our paper presents two model variants that output numerical numbers based on the T5 architecture: an encoder- decoder model and an encoder-only model. We thereby propose fine-tuning T5 with ranking losses to maximize ranking metrics. We demonstrate sig- nificant improvement when ranking losses are used to fine-tune the T5 model on the MS MARCO and the NQ data sets. We further illustrate that such improvement can be maintained in the zero-shot setting on out-of-domain data sets. Our paper opens up several potential directions for further exploration. First, more T5-based rank- ing model architectures can be studied. For ex- ample, one can study different pooling strategies in the encoder-only model structure. Second, it is unclear whether there is any difference between the encoder-decoder and the encoder-only mod- els when the training data is insufficient. Third, it might be interesting to extend our training method into the pretraining stage to produce better pre- trained models. # References Payal Bajaj, Daniel Campos, Nick Craswell, Li Deng, Jianfeng Gao, Xiaodong Liu, Rangan Majumder, Andrew McNamara, Bhaskar Mitra, Tri Nguyen, et al. 2016. MS MARCO: A human generated ma- chine reading comprehension dataset. Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. 2020. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901. Sebastian Bruch, Xuanhui Wang, Michael Bendersky, and Marc Najork. 2019. An analysis of the softmax cross entropy loss for learning-to-rank with binary relevance. In Proceedings of the 2019 ACM SIGIR International Conference on Theory of Information Retrieval, ICTIR ’19, page 75–78. Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, and Greg Hullender. 2005. Learning to rank using gradient descent. In Proceedings of the 22nd international conference on Machine learning, pages 89–96. Zhe Cao, Tao Qin, Tie-Yan Liu, Ming-Feng Tsai, and Hang Li. 2007. Learning to rank: From pairwise ap- proach to listwise approach. In Proceedings of the 24th International Conference on Machine Learn- ing, page 129–136. Olivier Chapelle and Yi Chang. 2011. Yahoo! learning In Proceedings of the to rank challenge overview. learning to rank challenge. Aakanksha Chowdhery, Sharan Narang, Jacob Devlin, Maarten Bosma, Gaurav Mishra, Adam Roberts, Paul Barham, Hyung Won Chung, Charles Sutton, Sebastian Gehrmann, et al. 2022. PaLM: Scaling language modeling with pathways. arXiv preprint arXiv:2204.02311. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. BERT: Pre-training of Deep Bidirectional Transformers for Language Un- derstanding. In NAACL-HLT (1). Cicero dos Santos, Xiaofei Ma, Ramesh Nallapati, Zhi- heng Huang, and Bing Xiang. 2020. Beyond [CLS] through Ranking by Generation. In Proceedings of the 2020 Conference on Empirical Methods in Nat- ural Language Processing (EMNLP), pages 1722– 1727. Luyu Gao, Zhuyun Dai, and Jamie Callan. 2020. Mod- ularized transfomer-based ranking framework. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 4180–4190. Luyu Gao, Zhuyun Dai, and Jamie Callan. 2021. Re- think training of BERT rerankers in multi-stage In Advances in Information retrieval pipeline. Retrieval–43rd European Conference on IR Re- search. Shuguang Han, Xuanhui Wang, Mike Bendersky, and Marc Najork. 2020. Learning-to-Rank with BERT in TF-Ranking. CoRR, abs/2004.08476. Kai Hui, Honglei Zhuang, Tao Chen, Zhen Qin, Jing Lu, Dara Bahri, Ji Ma, Jai Prakash Gupta, Ci- cero Nogueira dos Santos, Yi Tay, and Don Metzler. 2022. ED2LM: Encoder-decoder to language model In Find- for faster document re-ranking inference. ings of the Association for Computational Linguis- tics: ACL 2022, pages 3747–3758. Rolf Jagerman, Xuanhui Wang, Honglei Zhuang, Zhen Qin, Michael Bendersky, and Marc Najork. 2022. Rax: Composable learning-to-rank using JAX. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD ’22). Kalervo Järvelin and Jaana Kekäläinen. 2002. Cu- mulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems (TOIS), 20(4):422–446. Jia-Huei Ju, Jheng-Hong Yang, and Chuan-Ju Wang. 2021. Text-to-text multi-view learning for passage re-ranking. In Proceedings of the 44th International ACM SIGIR Conference on Research and Develop- ment in Information Retrieval, pages 1803–1807. Vladimir Karpukhin, Barlas Oguz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and Wen-tau Yih. 2020. Dense Passage Retrieval for In Proceed- Open-Domain Question Answering. ings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 6769–6781. Omar Khattab and Matei Zaharia. 2020. Col-BERT: Efficient and Effective Passage Search via Contextu- alized late Interaction over BERT. In Proceedings of the 43rd International ACM SIGIR conference on research and development in Information Retrieval, pages 39–48. Tom Kwiatkowski, Jennimaria Palomaki, Olivia Red- field, Michael Collins, Ankur Parikh, Chris Alberti, Danielle Epstein, Illia Polosukhin, Matthew Kelcey, Jacob Devlin, Kenton Lee, Kristina N. Toutanova, Llion Jones, Ming-Wei Chang, Andrew Dai, Jakob Uszkoreit, Quoc Le, and Slav Petrov. 2019. Natu- ral questions: a benchmark for question answering research. Transactions of the Association of Compu- tational Linguistics. John Lafferty and Chengxiang Zhai. 2003. Probabilis- tic relevance models based on document and query generation. In Language modeling for information retrieval, pages 1–10. Springer. Zhaoqi Leng, Mingxing Tan, Chenxi Liu, Ekin Do- gus Cubuk, Jay Shi, Shuyang Cheng, and Dragomir Anguelov. 2022. Polyloss: A polynomial expansion perspective of classification loss functions. In Inter- national Conference on Learning Representations. Jimmy Lin, Rodrigo Nogueira, and Andrew Yates. text rank- Pretrained transformers for arXiv preprint 2020. ing: arXiv:2010.06467. BERT and beyond. Tie-Yan Liu. 2009. Learning to Rank for Information Retrieval. Now Publishers Inc. Jing Lu, Gustavo Hernández Ábrego, Ji Ma, Jianmo Ni, and Yinfei Yang. 2021. Multi-stage training with im- proved negative contrast for neural passage retrieval. In Proceedings of the 2021 Conference on Empiri- cal Methods in Natural Language Processing, pages 6091–6103. Sean MacAvaney, Franco Maria Nardini, Raffaele Perego, Nicola Tonellotto, Nazli Goharian, and Ophir Frieder. 2020. Efficient document re-ranking for transformers by precomputing term representa- tions. In Proceedings of the 43rd International ACM SIGIR Conference on Research and Development in Information Retrieval, pages 49–58. Jianmo Ni, Chen Qu, Jing Lu, Zhuyun Dai, Gus- tavo Hernández Ábrego, Ji Ma, Vincent Y Zhao, Yi Luan, Keith B Hall, Ming-Wei Chang, et al. 2022. Large dual encoders are generalizable retrievers. In Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing (EMNLP). Rodrigo Nogueira, Zhiying Jiang, Ronak Pradeep, and Jimmy Lin. 2020. Document Ranking with a Pre- In Proceed- trained Sequence-to-Sequence Model. ings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings, pages 708–718. Rodrigo Nogueira, Wei Yang, Kyunghyun Cho, and Jimmy Lin. 2019. Multi-stage document ranking with BERT. CoRR, abs/1910.14424. Ronak Pradeep, Rodrigo Nogueira, and Jimmy Lin. 2021. The expando-mono-duo design pattern for text ranking with pretrained sequence-to-sequence models. arXiv preprint arXiv:2101.05667. Tao Qin and Tie-Yan Liu. 2013. Introducing LETOR 4.0 datasets. CoRR, abs/1306.2597. Zhen Qin, Le Yan, Honglei Zhuang, Yi Tay, Rama Ku- mar Pasumarthi, Xuanhui Wang, Michael Bender- sky, and Marc Najork. 2021. Are Neural Rankers still Outperformed by Gradient Boosted Decision In International Conference on Learning Trees? Representations. Yingqi Qu, Yuchen Ding, Jing Liu, Kai Liu, Ruiyang Ren, Wayne Xin Zhao, Daxiang Dong, Hua Wu, and Haifeng Wang. 2021. RocketQA: An opti- mized training approach to dense passage retrieval In Proceed- for open-domain question answering. ings of the 2021 Conference of the North Ameri- can Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 5835–5847. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J Liu. 2020. Exploring the lim- its of transfer learning with a unified text-to-text transformer. Journal of Machine Learning Research, 21:1–67. Ruiyang Ren, Yingqi Qu, Jing Liu, Wayne Xin Zhao, Qiaoqiao She, Hua Wu, Haifeng Wang, and Ji-Rong Wen. 2021. RocketQAv2: A joint training method for dense passage retrieval and passage re-ranking. In Proceedings of the 2021 Conference on Empiri- cal Methods in Natural Language Processing, pages 2825–2835. Stephen Robertson and Hugo Zaragoza. 2009. The probabilistic relevance framework: BM25 and be- yond. Now Publishers Inc. Guilherme Moraes Rosa, Luiz Bonifacio, Vitor Jeronymo, Hugo Abonizio, Marzieh Fadaee, Roberto Lotufo, and Rodrigo Nogueira. 2022. No parameter left behind: How distillation and model size affect zero-shot retrieval. arXiv preprint arXiv:2206.02873. Devendra Singh Sachan, Mike Lewis, Mandar Joshi, Armen Aghajanyan, Wen-tau Yih, Joelle Pineau, and Luke Zettlemoyer. 2022. Improving passage re- trieval with zero-shot question generation. arXiv preprint arXiv:2204.07496. Yi Tay, Vinh Q Tran, Mostafa Dehghani, Jianmo Ni, Dara Bahri, Harsh Mehta, Zhen Qin, Kai Hui, Zhe Zhao, Jai Gupta, et al. 2022. Transformer mem- ory as a differentiable search index. arXiv preprint arXiv:2202.06991. Nandan Thakur, Nils Reimers, Andreas Rücklé, Ab- hishek Srivastava, and Iryna Gurevych. 2021. BEIR: A heterogeneous benchmark for zero-shot evalua- tion of information retrieval models. In Thirty-fifth Conference on Neural Information Processing Sys- tems Datasets and Benchmarks Track (Round 2). Ellen M Voorhees et al. 1999. The TREC-8 Question Answering Track Report. In Proceedings of the 8th Text REtrieval Conference (TREC-8),, volume 99, pages 77–82. Lee Xiong, Chenyan Xiong, Ye Li, Kwok-Fung Tang, Jialin Liu, Paul N Bennett, Junaid Ahmed, and Arnold Overwijk. 2020. Approximate nearest neigh- bor negative contrastive learning for dense text re- In International Conference on Learning trieval. Representations. Shengyao Zhuang, Hang Li, and Guido Zuccon. 2021. Deep Query Likelihood Model for Information Re- trieval. In The 43rd European Conference On Infor- mation Retrieval (ECIR). Shengyao Zhuang and Guido Zuccon. 2021. TILDE: Term Independent Likelihood moDEl for Passage In Proceedings of the 44th Interna- Re-ranking. tional ACM SIGIR Conference on Research and De- velopment in Information Retrieval, pages 1483– 1492. # A Choice of Target Tokens and Input Sequence In Section 4.1, our proposed model struc- ture with the encoder-decoder structure adopts “<extra_id_10>” as the target token and uses its unnormalized logit as the ranking score. We be- lieve that the choice of target token does not affect the model performance when we have sufficient training data. We conduct experiments where we use “<extra_id_11>” or “true” as the target token. We also try to use the original input se- quence format in (Nogueira et al., 2020) where the input sequence contains the “Relevant:” postfix: # sij = Query: qi Document: dij Relevant: and the target token is “true”. We fine-tune our EncDec model on the MS MARCO data set with the Softmax loss using different target tokens or input sequence formats. Results are shown in Ta- ble 3. Table 3: Comparison of different target token choices and input sequence formats. All models are RankT5- EncDec model fine-tuned with the Softmax loss. The performances are reported on the MS MARCO data set. Input sequence Target token MRR@10 NDCG@10 w/o “Relevant:” <extra_id_10> <extra_id_11> true 0.4277 0.4272 0.4250 0.4960 0.4951 0.4937 w/ “Relevant:” true 0.4279 0.4953 It can be observed that the model performances are not sensitive to the choice of target tokens. Whether or not to add the “Relevant:” postfix to the input sequence also does not seem to show any effect. These results seem to align with the obser- vation in (Nogueira et al., 2020) that the choice of target tokens does not change the performance when there is sufficient training data. # B Pooling Strategies Comparison for RankT5-Enc In Section 4.1, our proposed model structure with the encoder-only structure uses a pooling layer. There could be different ways to instantiate the pooling layers. The first one is to only take the embedding vector of the first token: PoolFirst([e1, · · · , el]) = e1 (5) Another common strategy is to take the mean of the embedding vectors of all the tokens: 1 1 PoolMean([e1, aa ,e7]) = 1 S ej (6) i=l We conduct experiments comparing these pool- ing strategies on MS MARCO, where the RankT5- Enc model is fine-tuned with the Softmax loss. Re- sults are summarized in Table 4. Table 4: Comparison of different pooling strategies. All models are RankT5-Enc model fine-tuned with the Softmax loss. The performances are reported on the MS MARCO data set. Pooling MRR@10 NDCG@10 First Mean 0.4305 0.4308 0.4987 0.4993 These results suggest that different pooling strategies do not generate much different results. This is probably because even just the first token is already attended by all the other token with the transformer structure. Moreover, in our experi- ments, there are sufficient training data to fine-tune the model. # C Ranking Performances with Additional Metrics We provide some additional metrics to compare the performance of our RankT5 models with other baselines. The metrics we reported in Table 1 focus more precision, which emphasizes ensuring the top positions of ranked lists are relevant documents. In this appendix we also report metrics like NDCG without cutoff or mean average precision (MAP), which would also penalize models if any relevant document is ranked too low in the list. Specifically, we report model performance measured by NDCG, MAP and Recall@5 in Table 5. The conclusion is similar to Table 1. Our pro- posed RankT5 models still outperform other base- lines significantly on these metrics. Models fine- tuned with Softmax or Poly1 still achieve better performance than models fine-tuned with pointwise or pairwise losses. These results are not surprising as both data sets have very few documents labeled for each query. Actually, for both data sets, more than 94% of queries in the dev partition have only 1 document labeled as relevant. # D Additional Experiments on Model Size Comparison We report additional experiments of model size comparisons on RankT5-Enc models. Similar to the experiments in Section 6, we fine-tune the RankT5-Enc model with the Softmax and the PointCE loss with T5 model sizes of “Base”, “Large” and “3B” and plot their MRR@10. Results are plotted in Figure 4. (a) MS MARCO (b) NQ Figure 4: Comparing performances with different T5 model sizes. Ranking models are RankT5-Enc fine- tuned with the Softmax and the PointCE loss. The per- formance is measured by MRR@10 with 95% confi- dence interval. The results are similar to RankT5-EncDec re- sults. The performance increases with larger model sizes and the gap between the Softmax loss and the PointCE loss remains similar. # E Additional Zero-Shot Experiments We also conduct the zero-shot experiments using RankT5-Enc fine-tuned with different model sizes. All the models are fine-tuned using the Softmax loss. We compare the models with size “Base”, “Large” and “3B”. The results are shown in Table 6. It can be observed that on average the ranking model with larger size can also perform better on out-of-domain data sets in the zero-shot setting. We also compare the zero-shot performance of our RankT5-Enc model with publicly reported zero- shot performance of monoT5 from (Rosa et al., 2022). We only compare the performance with model size Base and 3B since these are the only sizes we have results from both models. The results can be found in Table 7. Results show that RankT5 fine-tuned with Soft- max on average outperforms the monoT5 with both model sizes. It again provides evidence that fine- tuning ranking models with listwise ranking losses can help the model generalize better to out-of- domain data, similar to our observation in Table 2. Table 5: Comparing ranking performances of different ranking models with additional metrics. The best perfor- mances are bolded. Results with † are statistically significantly (p ≤ 0.05) better than monoT5. Model Loss MS MARCO NDCG MAP NQ Recall@5 NDCG MAP Recall@5 BERT BERT PointCE Softmax 0.5180 0.5212 0.3932 0.3978 0.5528 0.5548 0.6164 0.6215 0.5228 0.5276 0.6849 0.6895 monoT5 Generation 0.5421 0.4206 0.5945 0.6378 0.5434 0.7334 RankT5-EncDec PointCE Pair Softmax Poly1 0.5462† 0.5438 0.5520† 0.5569† 0.4260† 0.4229 0.4326† 0.4383† 0.5973 0.5911 0.6059† 0.6143† 0.6406 0.6531† 0.6616† 0.6586† 0.5457† 0.5629† 0.5740† 0.5701† 0.7417† 0.7392 0.7480† 0.7458† RankT5-Enc PointCE Pair Softmax Poly1 0.5467† 0.5464† 0.5539† 0.5536† 0.4269† 0.4256 0.4347† 0.4344† 0.5973 0.6029† 0.6052† 0.6059† 0.6431 0.6547† 0.6564† 0.6615† 0.5496† 0.5650† 0.5674† 0.5744† 0.7380 0.7418† 0.7467† 0.7457† Table 6: Zero-shot performance comparison. Rank- ing models are RankT5-Enc fine-tuned on the MS MARCO data set using the Softmax loss with dif- ferent model sizes. Performances are measured by NDCG@10. — Table 7: Comparing zero-shot performance of RankT5- Enc and monoT5. RankT5-Enc is fine-tuned on the MS MARCO data set using the Softmax loss. Perfor- mances are measured by NDCG@10. Data set Base Large 3B TREC-COVID BioASQ NFCorpus NQ HotpotQA FiQA-2018 Signal-1M ArguAna Touché-2020 Quora DBPedia SCIDOCS FEVER Climate-FEVER SciFact 0.7896 0.5627 0.3731 0.5731 0.7269 0.4132 0.2909 0.3094 0.4449 0.8138 0.4373 0.1760 0.8295 0.2462 0.7493 0.8071 0.5635 0.3810 0.6142 0.7100 0.4450 0.3200 0.3300 0.4401 0.8309 0.4422 0.1806 0.8316 0.2152 0.7499 0.8237 0.5795 0.3990 0.6471 0.7536 0.4932 0.3191 0.4069 0.4869 0.8192 0.4598 0.1918 0.8487 0.2753 0.7600 Average 0.5157 0.5241 0.5509 Data set Base 3B monoT5 RankT5 monoT5 RankT5 TREC-COVID BioASQ NFCorpus NQ HotpotQA FiQA-2018 Signal-1M ArguAna Touché-2020 Quora DBPedia SCIDOCS FEVER Climate-FEVER SciFact 0.7775 0.5240 0.3570 0.5674 0.6950 0.4136 0.2771 0.1321 0.2773 0.8230 0.4195 0.1649 0.8018 0.2451 0.7356 0.7896 0.5627 0.3731 0.5731 0.7269 0.4132 0.2909 0.3094 0.4449 0.8138 0.4373 0.1760 0.8295 0.2462 0.7493 0.7948 0.5740 0.3837 0.6334 0.7589 0.5137 0.3140 0.2876 0.2995 0.8407 0.4777 0.1970 0.8495 0.2802 0.7773 0.8237 0.5795 0.3990 0.6471 0.7536 0.4932 0.3191 0.4069 0.4869 0.8192 0.4598 0.1918 0.8487 0.2753 0.7600 Average 0.4807 0.5157 0.5321 0.5509 # F Limitations techniques proposed in this work to those models remains to be further discussed. One limitation of this work is that both data sets we used only have binary relevance labels. There are other text ranking data sets with graded relevance labels (e.g., 0 to 4), but they either are not publicly available or do not have a large enough training set. Different fine-tuning strategies (training data con- struction, ranking losses, learning rate etc.) might need to be developed for our proposed models to achieve optimal performances on such data sets. Another limitation is that we only focus on T5. There are other sequence-to-sequence language models like GPT-2 with different model structures (where the encoder is not available). How to apply
Title: Small Changes Make Big Differences: Improving Multi-turn Response Selection in Dialogue Systems via Fine-Grained Contrastive Learning: Summary: Retrieve-based dialogue response selection aims to find a proper response from a candidate set given a multi-turn context. Pre-trained language models (PLMs) based methods have yielded significant improvements on this task. The sequence representation plays a key role in the learning of matching degree between the dialogue context and the response. However, we observe that different context-response pairs sharing the same context always have a greater similarity in the sequence representations calculated by PLMs, which makes it hard to distinguish positive responses from negative ones. Motivated by this, we propose a novel \textbf{F}ine-\textbf{G}rained \textbf{C}ontrastive (FGC) learning method for the response selection task based on PLMs. This FGC learning strategy helps PLMs to generate more distinguishable matching representations of each dialogue at fine grains, and further make better predictions on choosing positive responses. Empirical studies on two benchmark datasets demonstrate that the proposed FGC learning method can generally and significantly improve the model performance of existing PLM-based matching models. # Small Changes Make Big Differences: Improving Multi-turn Response Selection in Dialogue Systems via Fine-Grained Contrastive Learning Yuntao Li1, Can Xu3, Huang Hu3, Lei Sha2, Yan Zhang1, Daxin Jiang3* 1Department of Machine Intelligence, Peking University, Beijing, China 2Department of Computer Science, University of Oxford, United Kingdom 3Microsoft STCA, Beijing, China 1{li.yt, zhyzhy001}@pku.edu.cn; 2{lei.sha}@cs.ox.ac.uk; 3{caxu, huahu, djiang}@microsoft.com # Abstract Retrieve-based dialogue response selection aims to find a proper response from a candidate set given a multi-turn con- text. Pre-trained language models (PLMs) based methods have yielded significant improvements on this task. The se- quence representation plays a key role in the learning of matching degree between the dialogue context and the re- sponse. However, we observe that different context-response pairs sharing the same context always have a greater simi- larity in the sequence representations calculated by PLMs, which makes it hard to distinguish positive responses from negative ones. Motivated by this, we propose a novel Fine- Grained Contrastive (FGC) learning method for the response selection task based on PLMs. This FGC learning strategy helps PLMs to generate more distinguishable matching rep- resentations of each dialogue at fine grains, and further make better predictions on choosing positive responses. Empiri- cal studies on two benchmark datasets demonstrate that the proposed FGC learning method can generally and signif- icantly improve the model performance of existing PLM- based matching models.1 represent them as a single sequence representation (i.e., con- text embedding at the position of the [CLS] token). This se- quence representation is also regarded as a matching repre- sentation, which is further used to decide a score indicat- ing the matching degree between the dialogue context and the response. By further post-training PLMs with in-domain data and auxiliary self-supervised tasks (Whang et al. 2020, 2021a; Xu et al. 2021), PLMs are incorporated with in- domain knowledge and achieve state-of-the-art results on benchmarks. Vector Space Vector Space a ban Contrastive Learning - | gO ee i) + Better Uniformity (2) * @%o e xe a © Less distinguishable # Introduction Building an intelligent conversational agent that can natu- rally and consistently converse with humans has drawn con- siderable attention in the field of natural language process- ing (NLP). So far, there are two kinds of approaches for implementing a dialogue system: generation-based (Serban et al. 2016; Vinyals and Le 2015) and retrieval-based meth- ods (Lowe et al. 2015; Wu et al. 2017; Zhou et al. 2018). In this work, we focus on the problem of multi-turn response selection for retrieval-based dialogue systems. Multi-turn response selection is the task of predicting the most proper response using a retrieval model by measuring the matching degree between a multi-turn dialogue context and a set of response candidates. Most recently, pre-trained language models (PLMs) have achieved substantial perfor- mance improvements in multi-turn response selection (Lu et al. 2020; Gu et al. 2020; Humeau et al. 2020). PLM-based models take a pair of context and response as a whole and *Corresponding author: Daxin Jiang (djiang@microsoft.com). 1We will make the code public available later to facilitate re- producing the results. Figure 1: Although a standard contrastive learning can pro- vide better uniformity on the vector space, it is still hard to distinguish between positive (yellow) and negative (blue) di- alogues with the same context (in the same shape, e.g., star). Despite the success of PLM-based matching models and their various variants, recent studies reveal that the contex- tualized word and sentence representations in PLM-based models are anisotropic, i.e., representations occupy a narrow cone in the vector space, which largely limits the expressive- ness of representations (Ethayarajh 2019; Li et al. 2020). Contrastive learning provides a way to solve this problem, which uniforms representations over a hypersphere space as pointed out by Wang and Isola (2020). Although employ- ing the standard constrative learning method (Chen et al. 2020; Fang and Xie 2020) with in-batch negative sampling enhances the uniformity of representations, we further ob- serve by experiments (Section 6.3) that the matching repre- sentation of two dialogues with the same context but differ- ent responses are too similar, as is shown in Figure 1. This is mainly due to the following two reasons: (1) The overlap of the same context tokens in different context-response pairs makes the matching representation highly similar since the representation is aggregated from all tokens in the context- response pair. (2) The in-batch negative samples are highly likely to be different in both context and response. This phe- nomenon makes the representations less distinguishable and makes it hard to tell dialogues with positive responses from negative ones. To address the aforementioned issues, we propose a Fine- Grained Contrastive learning (FGC) approach to fine-tune matching representations for the response selection task. FGC introduces the connections between each dialogue pair with the same context and different responses into the train- ing process with contrastive learning. In contrast to the stan- dard contrastive learning method, which takes every other dialogue as negative examples, our proposed FGC takes con- text and response as separate parts and focuses on distin- guishing between positive and negative dialogues with the same context. During fine-grained contrastive learning, each dialogue is converted into an augmented dialogue via rule- based transformation on the response utterance. Each dia- logue is asked to be close to its augmentation, while the one with a positive response should be far away from the one with a negative response. FGC works totally in a self- supervised way that no additional supervision is required besides the classification label used for response selection training. We conduct experiments on two response selection benchmarks: the Ubuntu Dialogue Corpus (Lowe et al. 2015) and the Douban Corpus (Wu et al. 2017). These two datasets have a large variety of both topics and lan- guages. Moreover, our proposed learning framework is in- dependent of the choice of PLMs-based matching models. Therefore, for a comprehensive evaluation, we test FGC with five representative PLMs-based matching models, in- cluding the state-of-the-art one brought by self-supervised learning. Our empirical results demonstrate that FGC is able to consistently improve PLMs by up to 3.2% absolute im- provement with an average of 1.7% absolute improvement in terms of R10@1. Besides, We also compare our method with standard-contrastive-learning-enhanced PLMs, which demonstrates the effectiveness of our proposed fine-grained contrastive objective. In summary, our contributions in the paper are three-fold: We propose FGC, a novel fine-grained contrastive learn- ing method, which helps generate better representations of dialogues and improves the response selection task. • FGC shows good generality of effectiveness with various pre-trained language models for enhancing performance. • Experimental results on two benchmark datasets demon- strate that FGC can significantly improve the perfor- mance of various strong PLM-based matching models, including state-of-the-art ones. 2 Related Work 2.1 Multi-Turn Response Selection Earlier studies on retrieval-based response selection focused on single-turn response selection (Wang et al. 2013; Hu et al. 2015; Wang et al. 2015). Recently, researchers have paid more attention to the multi-turn response selection. The dual LSTM model (Lowe et al. 2015) was proposed to match the dialog context and response using a dual RNN-based architecture. Zhou et al. (2016) proposed the multi-view model that encodes dialogue context and response both on the word-level and utterance-level. However, these methods ignore relationships among utterances by simply concatenat- ing the utterances together or converting the whole context to a vector. To alleviate this, Wu et al. (2017) proposed the sequential matching network that each utterance in the con- text first interacts with the response candidate, and then the matching features are aggregated according to the sequen- tial order of multi-turn context. With the rise of the self- attention mechanism (Vaswani et al. 2017), some studies (Zhou et al. 2018; Tao et al. 2019a) explored how to enhance representations with it. Besides, Yuan et al. (2019) recently revealed that previous methods construct dialogue contex- tual representation using too much context, which damages the matching effect. They proposed a multi-hop selector to select the relevant utterances in the dialogue context for re- sponse matching. Most recently, pre-trained language models (e.g., BERT (Devlin et al. 2019) and RoBERTa (Liu et al. 2020)) have shown an impressive performance in the response selection. The post-training method, which helps transfer the represen- tations of BERT from the general domain to the dialogue domain, was proposed by Whang et al. (2020) and obtained state-of-the-art results. Subsequent researches (Gu et al. 2020; Lu et al. 2020) focused on incorporating speaker infor- mation into BERT and showed its effectiveness in multi-turn response selection. Further, self-supervised learning con- tributed to the success of pre-trained language models was also applied in several NLP downstream tasks, such as sum- marization (Wang et al. 2019) and the response generation (Zhao, Xu, and Wu 2020). In the task of response selec- tion, Whang et al. (2021a) and Xu et al. (2021) indicated that incorporating well-designed self-supervised tasks according to the characteristics of the dialogue data into BERT fine- tuning can help with the multi-turn response selection. Han et al. (2021) proposed a fine-grained post-training method for enhancing the pre-trained language model, while the post-training process is computationally expensive than fine- tuning a classification model. Su et al. (2020) proposed a hierarchical curriculum learning framework for improving response selection with PLMs. 2.2 Contrastive Learning for NLP There have been several investigations for contrastive loss formulations for deep neural models, primarily in the com- puter vision domain. Oord, Li, and Vinyals (2018) pro- posed a framework for contrastive learning to learn vi- sual representations based on contrastive predictive coding, which predicts the features in latent space by using pow- erful autoregressive models. Khosla et al. (2020) investi- gated supervised contrastive learning, allowing to leverage label information effectively. Following this trend, some re- searchers verified the effectiveness of constructive learning in specific NLP tasks. Fang and Xie (2020) proposed pre- training language representation models with a contrastive self-supervised learning objective at the sentence level, out- performing previous methods on a subset of GLUE tasks. Gunel et al. (2021) combined the cross-entropy with a super- vised contrastive learning objective, showing improvements over fine-tuning RoBERTa-Large on multiple datasets of the GLUE benchmark. Our work differs from previous works in that we do not directly make contrast on one dialogue with all the other dialogues, as the granularity of negative sam- ples constructed using this approach is too coarse to provide sufficient discrimination with the positive ones. # 3 Background # 3.1 Task Formalization The response selection task is to select the best candidate to respond a given multi-turn dialogue context from a pool of candidate responses. Suppose that we have a dataset D = {ci, ri, yi}N i } is a multi- turn dialogue context with ni turns, ri denotes a candidate response, and yi ∈ {0, 1} denotes a label with yi = 1 indi- cating ri a proper response for ci and otherwise yi = 0. Our goal is to estimate a matching model y = f (·, ·) from D. For any given context-response pair (c, r), f (c, r) returns a score that reflects the matching degree between c and r. # 3.2 Pre-trained Language Model for Response Selection As a trend in these years, pre-trained language models, e.g., BERT(Devlin et al. 2019), have been widely studied and adapted into numerous NLP tasks, showing several state-of- the-art results. Dialogue response selection is one of them. Applying a pre-trained language model into response se- lection usually involves two steps. The first step is to make domain-adaptive post-training, which continues to train a standard pre-trained language model with a domain-specific corpus. This step helps to transfer the original pre-trained language model into the target domain. The second step is to fine-tune the post-trained model with the response selection task. Given a context c = {u1, · · · , um} where ut is the t-th turn of the dialog context, and a response r, the model is asked to predict a score ˆy to represent the matching degree between c and r. To achieve this, a special token [EOT] is added at the end of each turn to distinguish them in the context c. Utterances from both the context c and response r are concatenated with separator [EOT] and [SEP] between them. Taking x as input, BERT returns a sequence of vectors with the same length as x. The output of the first place s[CLS] is an aggregated representa- tion vector that holds the information of interaction between context c and response r. A relevance score ˆy is computed based on s[CLS] and optimized through a binary classifica- tion loss. ˆy = σ(Wsels[CLS] + b) Lsel = − (y log ˆy + (1 − y) log(1 − ˆy)) , (1) where Wsel and b are parameters # 4 Methodology 4.1 Overview In this paper, we propose the Fine-Grained Contrastive Learning method (FGC) for learning PLMs-based matching models. It consists of two complementary contrastive objec- tives: (1) an instance-view contrastive objective (IVC); and (2) a category-view contrastive objective (CVC). Figure 2 demonstrates the joint effects of the two contrastive objec- tives on the space of matching representations. The IVC ob- jective pushes away dialogue instances with the same con- text and different responses, making the model easier to dis- tinguish between positive and negative responses. However, only pushing the examples with the same context away in- creases the risk of instances with different contexts getting closer in the representation space. As a remedy, the CVC objective further pulls all context-response pairs into two distinguishable clusters in the matching space according to whether the pair is positive or not. These two objectives are introduced in 4.3 and 4.4 respectively. For simplicity, we take BERT as an example in the following sections in the following sections. 4.2 Dialogue Data Augmentation Data augmentation takes an important role in contrastive learning (Zoph et al. 2020; Ho and Vasconcelos 2020). Sim- ilar to standard contrastive learning (e.g., CERT), the first step of FGC is to create augmentations for every context- response pair. Given a context-response pair, we take an aug- mentation method on the response to generate an augmented response. The context and augmented response pair form the augmentation of the original context-response pair. In order to fine-grained control the difference between a dialogue and its corresponding augmentation and easily perform augmen- tation on various languages, a fully unsupervised rule-based utterance augmentation method is adopted for utterance aug- mentation. Inspired by (Wei and Zou 2019), we adopt three types of augmentation operations: Random deletion: Each token in the utterance is ran- domly and independently deleted with a probability pdel. • Random swaping: Each token in the utterance is ran- domly swapped with another token in the utterance with a probability pswap. Synonym replacing: Randomly replace a non-stop-word token to one of its synonyms with a probability psyn. Given a response utterance r and an augmentation strength p ∈ [0, 1], we randomly pick out one of these three augmentation methods and then apply the augmentation on the utterance with the probability being p. After augmenta- tion, the response r is converted into another augmented re- sponse ¯r. The augmentation strength p is a hyper-parameter that controls how much difference is there between r and ¯r. 4.3 The instance-view contrastive (IVC) objective aims at intro- ducing more discrepancy between a pair of dialogues with the same context and positive/negative responses. Feeding Vector Space IVC Vector Space Vector Space ! || cvc oO ! A . 7 Poon © 4! ® x\ * Figure 2: FGC contains two objectives, i.e., IVC and CVC. IVC pushes away dialogues with the same context but different responses (icons in the same shape), while dialogues that belong to different categories may still be similar. CVC further solves this problem by pulling all dialogues into two distinguishable clusters. Examples Negative Examples Minimize Maximize —, Minimize BERT BERT Rule-based Utterance Augmentation Module Figure 3: An overview of IVC learning. The input is a dia- logue context c and a pair of positive and negative responses (r+, r−). Both responses are augmented with a rule-based utterance augmentation model to form a new pair (¯r+, ¯r−). We concatenate the context c with four responses and fed them into the BERT encoder, which outputs a projection vector z for each dialogue. IVC aims to maximize the dis- similarity of z between positive examples and negative ex- amples, as well as maintains high cohesion within positive and negative cases. guishability. This phenomenon is even worse when two ut- terances are semantically similar, e.g., two dialogues shar- ing the same context. Thus, we leverage the IVC objective on these projection vectors z to distinguish between positive and negative responses given the same context. IVC objec- tive regards the projection vector z as a representation of response r given context c. This loss is applied on the pro- jection vector z, which helps to maximize the similarity be- tween a response with its augmentation given the same con- text, as well as minimize the similarity between each posi- tive response and negative response pair. The maximum and minimum are achieved as a set of pair-wise comparisons, i.e., ∀i sim(zi+, ¯zi+) > sim(zi+, zi−), sim(zi+, ¯zi−) sim(¯zi+, zi−), sim(¯zi+, ¯zi−) ∀i sim(zi−, ¯z−i) > sim(zi−, zi+), sim(zi−, ¯zi+) sim(¯zi−, zi+), sim(¯zi−, ¯zi+). a dialogue into BERT, BERT helps to make internal inter- actions by attention mechanism and generate latent vectors representing the dialogue. The output vector of the [CLS] position s[CLS] stands for a aggregated sequence represen- tation of both context and response. We also take this vector as the dialogue matching representation used for contrastive learning. Moreover, we apply another projection layer to convert s[CLS] into a smaller vector z. This projection is made through an MLP with one hidden layer. Through this projection, each coherent dialogue with positive responses (ci, ri+) is transformed into a projection vector zi+, and each incoherent dialogue (ci, ri−) is transformed into zi−. The augmentations of the positive and negative dialogues are also converted into two vectors, i.e., ¯zi+ and ¯zi−. Here + and − indicates the item belongs to the positive class or the negative class, and the bar indicates this item comes from an augmented example. Here we use the NT-Xent Loss (Chen et al. 2020) to model the similarities of projection vectors. By writing this pair- wise comparison into a loss function, the IVC loss is formu- lated as exp(sim(z, Z)/7) \(z,%) = — log yp exp(sim(z, 24) /7) . (3) Live = D0 (U(ait. Zit) +1 (a2), i=l where τ > 0 is an adjustable scalar temperature parameter that controls the separation of positive and negative classes; zk ranges from {z+, ¯z+, z−, ¯z−}; and N is the total num- ber of dialogues. Notice that the IVC objective aims to separate the repre- sentation of positive and negative responses given the same context, so that we do not take all other in-batch examples as negative examples in the same way as in standard contrastive learning. As illustrated by Ethayarajh (2019) and Li et al. (2020), the embedding vectors of different utterances are distributed in a narrow cone of the vector space, showing less distin- 4.4 Category-View Contrastive Objective The IVC objective ensures a high difference between di- alogues with the same context, while it cannot guarantee (2) that the learned representations are suitable for classifica- tion. The representations of a positive dialogue may be close to the representation of another negative dialogue with a different context, as is shown in Figure 2. Thus, we in- troduce another category-view contrastive (CVC) objective into model training. The category-view contrastive objective aims at bunching dialogues that belong to the same category into a cluster and separate these two clusters. The CVC objective is applied between dialogues from the two classes. It captures the similarity of projection vectors of the same class and contrasts them with projection vectors from the other class, i.e., ∀i, j, k, l sim(zi+, zj+) > sim(zk+, zl−) ∀i, j, k, l sim(zi−, zj−) > sim(zk+, zl−). This category-view contrastive loss works with a batch of representation vectors of size 2N , where the number of both positive examples and negative examples is N . De- note {z1, z2, · · · , z2N −1, z2N } to be all representation vec- tors in a batch, where {z1, z2, · · · , zN } are representation vectors for positive dialogues and their augmentations, and {zN +1, zN +2, · · · , z2N } are representation vectors for neg- ative dialogues and their representations. The CVC objective works as an additional restriction to punish the high similar- ity between positive-negative pairs and low similarity within all positive and negative dialogues. The following formulas give this loss: exp(z; + Z;/T) Vigr CxP(4i Zr/T) 2N 1 Leve =~ SOY taaa, (zi. 25) i=l iAj I(2i,2;) = log (5) . Finally, the BERT model is fine-tuned with the standard response selection loss Lsel and both IVC and CVC loss. A weighted summation is computed as L = Lsel + λ(Livc + Lcvc), (6) where λ is a hyper-parameter that controls the balance between response selection loss and contrastive loss. The model is optimized by minimizing the overall loss value. # 5 Experiments # 5.1 Dataset • Ubuntu Dialogue Corpus V1 The Ubuntu Dialogue Corpus V1 (Lowe et al. 2015) is a domain-specific multi-turn conversation dataset. Conver- sations in this dataset are dumped from the multi-party chat room whose topic is the Ubuntu operating system. We conducted experiments on a preprocessed data re- leased by Xu et al. (2019), in which numbers, URLs, and system paths are masked by placeholders. Negative re- sponses for each dialogue are randomly sampled from other dialogues. • Douban Corpus The Douban Corpus(Wu et al. 2017) is a Chinese dataset collected from an online social network website named Douban. Douban Corpus is an open-domain conversation corpus, whose topic is much wider than that of Ubuntu Corpus. The statistics of these two datasets are shown in Table 1. These two datasets vary greatly in both language and topic. Following previous works, we take R10@ks as evalu- ation metrics, which measures the probability of having the positive response in the top k ranked responses. We take k = {1, 2, 5} for model evaluation. Dataset Train Ubuntu Val Test Douban Train Val Test # dialogues #pos:#neg # avg turns 1M 500K 500K 1:9 1:9 1:1 10.11 10.11 10.13 1M 50K 1:1 1:1 6.75 6.69 6670 1.2:8.8 6.45 Table 1: Statistics of two datasets. 5.2 Baseline Methods We introduce FGC into several open-sourced PLM-based models, including BERT and ELECTRA. We also test the effectiveness of FGC on variants of BERT model, includ- ing BERT-small (H=4, L=4, H=512), BERT with domain- adaptive post training named BERT-DPT (Whang et al. 2020), and BERT with self-supervised tasks named BERT- UMS (Whang et al. 2021b). Several non-PLM-based models are also compared with our proposed FGC. 2 5.3 All models are implemented based on Pytorch and Hugging- face’s implementation. Each PLM model is trained for 5 epochs with a learning rate beginning from 3e-6 to 0 with a linear learning rate decay. Our model is trained with 8 Nvidia Tesla A100 GPUs, which have 40GB of memory for each of them. For more training details, please refer to Ap- pendix A. 5.4 Experimental Results The comparison between PLMs and FGC-enhanced PLMs is shown in Table 2. It can be seen from the table that all PLM- based methods outperform non-PLM-based methods. By adding our proposed FGC into PLM-based models, the per- formance of all models is significantly improved. The max- imum improvement of a standard-sized BERT for the two datasets are 1.9% and 3.2% respectively in terms of R10@1. The average performance improvement also achieves 1.1% and 2.2%. Besides, our proposed method can also enhance the current state-of-the-art method BERT-UMS by 1.1% and 0.8% on two datasets in terms of R10@1. In addition to a standard-sized BERT model, we also find an absolute gain of 0.9% by adding FGC on the BERT-Small model, which is about 10× smaller than a standard one. The success of these two datasets demonstrates the effectiveness of our proposed 2A pre-trained Chinese BERT-Small is not available, thus we do not conduct experiments on it. Models Multi-View (Zhou et al. 2016) SMN (Wu et al. 2017) DUA (Zhang et al. 2018) DAM (Zhou et al. 2018) MRFN (Tao et al. 2019a) IoI (Tao et al. 2019b) IMN (Gu, Ling, and Liu 2019) MSN (Yuan et al. 2019) BERT BERT+FGC BERT-DPT (Whang et al. 2020) BERT-DPT+FGC BERT-UMS (Whang et al. 2021b) BERT-UMS+FGC ELECTRA ELECTRA+FGC BERT-Small BERT-Small+FGC Ubuntu R10@1 R10@2 R10@5 MAP MRR non-PLM-based methods 0.505 0.951 0.801 0.529 0.961 0.847 0.551 0.961 0.868 0.550 0.961 0.874 0.571 0.976 0.886 0.573 0.974 0.894 0.576 0.974 0.889 0.978 0.587 0.899 PLM-based Methods 0.978 0.980 0.987 0.990 0.988 0.990 0.978 0.980 0.972 0.974 0.662 0.726 0.752 0.767 0.786 0.796 0.794 0.800 0.543 0.569 0.599 0.601 0.617 0.621 0.618 0.632 0.820 0.829 0.862 0.881 0.875 0.886 0.826 0.832 0.792 0.800 0.906 0.910 0.935 0.945 0.942 0.948 0.908 0.912 0.888 0.890 0.597 0.614 0.609 0.620 0.625 0.627 0.602 0.625 N/A N/A 0.634 0.653 0.645 0.660 0.664 0.670 0.642 0.668 N/A N/A P@1 0.342 0.397 0.421 0.427 0.448 0.444 0.441 0.470 0.448 0.495 0.463 0.495 0.499 0.500 0.465 0.499 N/A N/A Douban R10@1 R10@2 R10@5 0.292 0.233 0.243 0.254 0.276 0.269 0.268 0.295 0.350 0.396 0.421 0.410 0.435 0.451 0.458 0.452 0.729 0.724 0.780 0.757 0.783 0.786 0.796 0.788 0.279 0.312 0.290 0.322 0.318 0.326 0.287 0.313 N/A N/A 0.489 0.495 0.505 0.495 0.482 0.512 0.483 0.502 N/A N/A 0.823 0.850 0.838 0.850 0.858 0.869 0.839 0.850 N/A N/A Table 2: Evaluation results on the two data sets. Numbers in bold indicate that the PLM-based models using FGC outperforms the original models with a significance level p-value < 0.05. FGC across different models, languages, and dialogue topics on multi-turn response selection. FGC separates representation vectors of dialogues into different latent spaces according to their type of relevance between contexts and responses. On the one hand, IVC helps distinguish between positive and negative responses given the same context. On the other hand, CVC separates rep- resentations of dialogues from two categories so that these representations can have better distinguishability. As a re- sult, the matching representation of context-response pairs for positive and negative responses are forced to stay away from each other. This better representation ensures higher accuracy in selecting the positive response given a candidate set of responses. 6 Closer Analysis We conduct closer analysis with BERT-DPT since combin- ing post-training and fine-tuning is the most popular manner of applying BERT for down-streaming tasks. The Ubuntu Corpus is used in the following analysis. # 6.1 Ablation Studies The results are shown in Table 3. It can be observed from the table that both IVC and CVC can enhance the perfor- mance on response selection, with an absolute improvement of 1.4% and 0.4% respectively in terms of R10@1. By ap- plying these two contrastive objectives, we obtain an abso- lute improvement of 1.9% based on the post-trained BERT model. Both of the two contrastive objectives share the same purpose of separating the representation of dialogues with positive and negative responses, and thus there is a perfor- mance overlap by adding these two objectives. 6.2 Sensitive Analysis Temperature Temperature τ works as a hyperparameter that controls the punishment on the degree of separation of positive and negative classes. A smaller τ gives more power to pull away dialogues from different classes. We test how this hyperparameter can influence the response selec- tion performance. We test τ in the range of {0.1, 0.5, 1} on FGC and the results are shown in Table 4. FGC achieves the best performance when τ is set to be 0.5, while the per- formance drops given a smaller or a bigger τ . A suitable τ can provide a proper differentiation that is neither too strong nor too weak, keeping a balance between contrastive and re- sponse selection objectives. Strategy BERT-DPT + FGC - IVC - CVC BERT-DPT R10@1 R10@2 R10@5 0.990 0.944 0.881 0.986 0.935 0.866 0.988 0.941 0.877 0.987 0.935 0.862 Table 3: Ablation Analysis on the Ubuntu corpus. Temperature τ BERT-DPT + FGC (τ =0.1) + FGC (τ =0.5) + FGC (τ =1.0) R10@1 R10@2 R10@5 0.987 0.935 0.862 0.990 0.939 0.872 0.990 0.944 0.881 0.990 0.938 0.876 As we add two contrastive learning objectives into train- ing for response selection, we test the gain of each objective. Table 4: Influence of temperature τ in FGC. Utterance Augmentation Strength Utterance augmenta- tion plays an important role in contrastive learning. A dia- logue with a context and a positive response is drawn closer to its augmentation while pushed far away from the dia- logue with the same context but a negative response. The strength of utterance augmentation decides the boundary of each cluster. We conduct experiments to test how augmenta- tion strength can influence response selection accuracy. We range the augmentation strength p from {0.1, 0.2, 0.5}, and the testing results are shown in Table 5. It achieves the best performance when p equals 0.2. Augmentation strength be- ing either too large or too small may harm the clustering. On the one hand, a too-large p brings too much noise into the clustering process, which blurs the boundary between posi- tive and negative examples. On the other hand, a too-small p cannot provide enough variation to the utterance, which harms the generalization of identifying positive and negative responses. Augment Strength p R10@1 R10@2 R10@5 0.987 0.862 BERT-DPT 0.989 0.874 0.990 0.881 0.990 0.872 Table 5: Influence of utterance augmentation strength p in FGC. 6.3 Discussion Compare with Standard Contrastive Learning The main difference between our proposed FGC and standard contrastive learning (e.g., CERT (Fang and Xie 2020) and SimCSE (Gao, Yao, and Chen 2021)) is that we only take dialogues with the same context but different responses as negative examples, instead of using in-batch examples as negative ones. We compare FGC with those methods, whose results are shown in Table 6. Standard contrastive learning can bring less gain (or even harm) on the response selection task, while contrastive learning with fine-grained negative examples leads to a significant gain on this task. Contrastive Method BERT-DPT BERT-DPT + CERT BERT-DPT + SimCSE BERT-DPT + FGC R10@1 R10@2 R10@5 0.987 0.935 0.862 0.985 0.931 0.855 0.987 0.936 0.864 0.990 0.944 0.881 Table 6: Influence of utterance augmentation strength p in FGC. Similarity between Dialogues The goal of FGC is to en- large distances between dialogue examples with the same context and different responses. To estimate how effective this target is achieved, we compute two average cosine sim- ilarities: (1) instance-level similarity, which is the average similarity between dialogue pairs with the same context but different responses; and (2) category-level similarity, which Strategy BERT-DPT + IVC + CVC BERT-DPT + FGC Ins Sim Cat Sim +0.064 +0.074 -0.015 -0.178 -0.109 +0.052 -0.131 -0.111 Table 7: Similarity Analysis on the Ubuntu corpus. is the average similarity between all positive dialogues and negative dialogues. As can be seen from Table 7, both simi- larities are lowered from a positive value indicating positive correlation into a negative value indicating negative correla- tion by adding FGC. By introducing better distinguishabil- ity into dialogue representations, our proposed FGC helps to make better response predictions effectively. Though these two similarities can also be lowered by adding IVC alone, the category similarity is not small enough to separate the two categories well. This shortcoming is compensated by further applying CVC as an additional training objective. Besides, CVC alone can neither provide a sufficiently low level of instance-level similarity that separates dialogues with the same context. Effect of Data Augmentation Alone Data augmentation, working as a kind of data noise, shows a positive effect on training models with robustness in natural language process- ing. One may concern that can data augmentation alone help with the response selection task. We conducted experiments with data augmentation alone, i.e., no contrastive learning strategy is included. The results are shown in Table 8. It can be observed from the table that data augmentation alone can- not enhance the model but even harm the accuracy signifi- cantly. Data augmentation methods should work with fine- grained contrastive learning to make positive effects for the multi-turn response selection task. BERT-DPT +Aug BERT-UMS +Aug Ubuntu 0.862 0.837 (-2.5%) 0.875 0.851 (-2.4%) Douban 0.290 0.278 (-1.2%) 0.318 0.292 (-2.6%) Table 8: Model performance with data augmentation alone. 7 Conclusion In this paper, we propose FGC, a fine-grained contrastive learning method, which helps to improve the multi-turn re- sponse selection task with PLM-based models. FGC consists of an instance-view contrastive (IVC) objective that helps to differentiate positive response and negative response with the same context, and a category-view contrastive (CVC) objective that separate positive dialogues and negative di- alogues into two distinguishable clusters. Experiments and analysis on two benchmark datasets and five PLM-based models demonstrates the effectiveness of FGC to signifi- cantly improve the performance of multi-turn dialogue re- sponse selection. References Chen, T.; Kornblith, S.; Norouzi, M.; and Hinton, G. 2020. A simple framework for contrastive learning of visual repre- sentations. In ICML, 1597–1607. PMLR. Devlin, J.; Chang, M.-W.; Lee, K.; and Toutanova, K. 2019. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In Proceedings of the 2019 Con- ference of the North American Chapter of the Association for Computational Linguistics: Human Language Technolo- gies, Volume 1 (Long and Short Papers), 4171–4186. Min- neapolis, Minnesota: Association for Computational Lin- guistics. Ethayarajh, K. 2019. How Contextual are Contextualized Word Representations? Comparing the Geometry of BERT, In Proceedings of the ELMo, and GPT-2 Embeddings. 2019 Conference on Empirical Methods in Natural Lan- guage Processing and the 9th International Joint Confer- ence on Natural Language Processing (EMNLP-IJCNLP), 55–65. Hong Kong, China: Association for Computational Linguistics. Fang, H.; and Xie, P. 2020. Cert: Contrastive self-supervised learning for language understanding. CoRR. Gao, T.; Yao, X.; and Chen, D. 2021. SimCSE: Simple Con- trastive Learning of Sentence Embeddings. arXiv preprint arXiv:2104.08821. Gu, J.-C.; Li, T.; Liu, Q.; Ling, Z.-H.; Su, Z.; Wei, S.; and Zhu, X. 2020. Speaker-aware bert for multi-turn response selection in retrieval-based chatbots. In CIKM, 2041–2044. Gu, J.-C.; Ling, Z.-H.; and Liu, Q. 2019. Interactive match- ing network for multi-turn response selection in retrieval- based chatbots. In CIKM, 2321–2324. Gunel, B.; Du, J.; Conneau, A.; and Stoyanov, V. 2021. Supervised Contrastive Learning for Pre-trained Language Model Fine-tuning. ICLR. Han, J.; Hong, T.; Kim, B.; Ko, Y.; and Seo, J. 2021. Fine- grained Post-training for Improving Retrieval-based Dia- logue Systems. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Compu- tational Linguistics: Human Language Technologies, 1549– 1558. Ho, C.-H.; and Vasconcelos, N. 2020. Contrastive learning with adversarial examples. NeurIPS. Hu, B.; Lu, Z.; Li, H.; and Chen, Q. 2015. Convolutional neural network architectures for matching natural language sentences. NIPS. Humeau, S.; Shuster, K.; Lachaux, M.-A.; and Weston, J. 2020. Poly-encoders: Transformer architectures and pre- training strategies for fast and accurate multi-sentence scor- ing. ICLR. Khosla, P.; Teterwak, P.; Wang, C.; Sarna, A.; Tian, Y.; Isola, P.; Maschinot, A.; Liu, C.; and Krishnan, D. 2020. Super- vised contrastive learning. NeurIPS. Li, B.; Zhou, H.; He, J.; Wang, M.; Yang, Y.; and Li, L. 2020. On the Sentence Embeddings from Pre-trained Language In Proceedings of the 2020 Conference on Em- Models. pirical Methods in Natural Language Processing (EMNLP), 9119–9130. Online: Association for Computational Linguis- tics. Liu, Y.; Ott, M.; Goyal, N.; Du, J.; Joshi, M.; Chen, D.; Levy, O.; Lewis, M.; Zettlemoyer, L.; and Stoyanov, V. 2020. Roberta: A robustly optimized bert pretraining ap- proach. ICLR. Loshchilov, I.; and Hutter, F. 2019. Decoupled weight decay regularization. ICLR. Lowe, R.; Pow, N.; Serban, I.; and Pineau, J. 2015. The ubuntu dialogue corpus: A large dataset for research in un- structured multi-turn dialogue systems. Lu, J.; Ren, X.; Ren, Y.; Liu, A.; and Xu, Z. 2020. Improving contextual language models for response retrieval in multi- turn conversation. In SigIR, 1805–1808. Oord, A. v. d.; Li, Y.; and Vinyals, O. 2018. Representation learning with contrastive predictive coding. arXiv preprint arXiv:1807.03748. Serban, I.; Sordoni, A.; Bengio, Y.; Courville, A.; and Pineau, J. 2016. Building end-to-end dialogue systems us- ing generative hierarchical neural network models. In AAAI, volume 30. Su, Y.; Cai, D.; Zhou, Q.; Lin, Z.; Baker, S.; Cao, Y.; Shi, S.; Collier, N.; and Wang, Y. 2020. Dialogue response se- lection with hierarchical curriculum learning. arXiv preprint arXiv:2012.14756. Tao, C.; Wu, W.; Xu, C.; Hu, W.; Zhao, D.; and Yan, R. 2019a. Multi-representation fusion network for multi-turn In WSDM, response selection in retrieval-based chatbots. 267–275. Tao, C.; Wu, W.; Xu, C.; Hu, W.; Zhao, D.; and Yan, R. 2019b. One Time of Interaction May Not Be Enough: Go Deep with an Interaction-over-Interaction Network for Re- sponse Selection in Dialogues. In Proceedings of the 57th Annual Meeting of the Association for Computational Lin- guistics, 1–11. Florence, Italy: Association for Computa- tional Linguistics. Vaswani, A.; Shazeer, N.; Parmar, N.; Uszkoreit, J.; Jones, L.; Gomez, A. N.; Kaiser, L.; and Polosukhin, I. 2017. At- tention is all you need. NIPS. Vinyals, O.; and Le, Q. 2015. A neural conversational model. arXiv preprint arXiv:1506.05869. Wang, H.; Lu, Z.; Li, H.; and Chen, E. 2013. A Dataset for Research on Short-Text Conversations. In Proceedings of the 2013 Conference on Empirical Methods in Natural Language Processing, 935–945. Seattle, Washington, USA: Association for Computational Linguistics. Wang, H.; Wang, X.; Xiong, W.; Yu, M.; Guo, X.; Chang, S.; and Wang, W. Y. 2019. Self-Supervised Learning for Contextualized Extractive Summarization. In Proceedings of the 57th Annual Meeting of the Association for Computa- tional Linguistics, 2221–2227. Florence, Italy: Association for Computational Linguistics. Wang, M.; Lu, Z.; Li, H.; and Liu, Q. 2015. Syntax-based deep matching of short texts. IJCAI. Wang, T.; and Isola, P. 2020. Understanding contrastive rep- resentation learning through alignment and uniformity on the hypersphere. Learning, 9929–9939. PMLR. Wei, J.; and Zou, K. 2019. EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th Inter- national Joint Conference on Natural Language Processing (EMNLP-IJCNLP), 6382–6388. Hong Kong, China: Asso- ciation for Computational Linguistics. Whang, T.; Lee, D.; Lee, C.; Yang, K.; Oh, D.; and Lim, H. 2020. An Effective Domain Adaptive Post-Training Method for BERT in Response Selection. In Proc. Interspeech 2020. Whang, T.; Lee, D.; Oh, D.; Lee, C.; Han, K.; Lee, D.-h.; and Lee, S. 2021a. Do Response Selection Models Really Know What’s Next? Utterance Manipulation Strategies for Multi-turn Response Selection. Whang, T.; Lee, D.; Oh, D.; Lee, C.; Han, K.; Lee, D.-h.; and Lee, S. 2021b. Do Response Selection Models Really Know What’s Next? Utterance Manipulation Strategies for Multi-turn Response Selection. In AAAI. Wu, Y.; Wu, W.; Xing, C.; Zhou, M.; and Li, Z. 2017. Se- quential Matching Network: A New Architecture for Multi- turn Response Selection in Retrieval-Based Chatbots. In Proceedings of the 55th Annual Meeting of the Associa- tion for Computational Linguistics (Volume 1: Long Pa- pers), 496–505. Vancouver, Canada: Association for Com- putational Linguistics. Xu, H.; Liu, B.; Shu, L.; and Yu, P. 2019. BERT Post- Training for Review Reading Comprehension and Aspect- based Sentiment Analysis. In Proceedings of the 2019 Con- ference of the North American Chapter of the Association for Computational Linguistics: Human Language Technolo- gies, Volume 1 (Long and Short Papers), 2324–2335. Min- neapolis, Minnesota: Association for Computational Lin- guistics. Xu, R.; Tao, C.; Jiang, D.; Zhao, X.; Zhao, D.; and Yan, R. 2021. Learning an Effective Context-Response Matching Model with Self-Supervised Tasks for Retrieval-based Dia- logues. Yuan, C.; Zhou, W.; Li, M.; Lv, S.; Zhu, F.; Han, J.; and Hu, S. 2019. Multi-hop Selector Network for Multi- turn Response Selection in Retrieval-based Chatbots. In Proceedings of the 2019 Conference on Empirical Meth- ods in Natural Language Processing and the 9th Interna- tional Joint Conference on Natural Language Processing (EMNLP-IJCNLP), 111–120. Hong Kong, China: Associa- tion for Computational Linguistics. Zhang, Z.; Li, J.; Zhu, P.; Zhao, H.; and Liu, G. 2018. Mod- eling Multi-turn Conversation with Deep Utterance Aggre- gation. In Proceedings of the 27th International Conference on Computational Linguistics, 3740–3752. Santa Fe, New Mexico, USA: Association for Computational Linguistics. Zhao, Y.; Xu, C.; and Wu, W. 2020. Learning a Simple and Effective Model for Multi-turn Response Generation with Auxiliary Tasks. In Proceedings of the 2020 Confer- ence on Empirical Methods in Natural Language Process- ing (EMNLP), 3472–3483. Online: Association for Compu- tational Linguistics. Zhou, X.; Dong, D.; Wu, H.; Zhao, S.; Yu, D.; Tian, H.; Liu, X.; and Yan, R. 2016. Multi-view Response Selec- tion for Human-Computer Conversation. In Proceedings of the 2016 Conference on Empirical Methods in Natural Lan- guage Processing, 372–381. Austin, Texas: Association for Computational Linguistics. Zhou, X.; Li, L.; Dong, D.; Liu, Y.; Chen, Y.; Zhao, W. X.; Yu, D.; and Wu, H. 2018. Multi-Turn Response Selection for Chatbots with Deep Attention Matching Network. In Pro- ceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), 1118– 1127. Melbourne, Australia: Association for Computational Linguistics. Zoph, B.; Ghiasi, G.; Lin, T.-Y.; Cui, Y.; Liu, H.; Cubuk, E. D.; and Le, Q. V. 2020. Rethinking pre-training and self- training. NeurIPS. A More Implementation Details Domain-adaptive Post-training For domain-adaptive post-training, we take the same hyper-parameter settings as BERT-DPT (Whang et al. 2020). Concretely, the maximum length of input dialogue is set to be 512. A full dialogue is randomly cut into a shorted token sequence with a probability of 10%. A masked language model loss and a next sentence prediction loss is optimized jointly during post-training. For the masked language model training, we masked each token with a probability of 15%. The post- training process traverses all the dialogues for 10 iterations, and the words that are masked during each iteration are independently sampled. Fine-tuning for Response Selection The model is fine- tuned with the response selection task. The projection layer for transforming [CLS] vectors into projection vectors z is an MLP with one hidden layer with hidden size being 256. For dialogues longer than 512 (i.e. the maximum length sup- ported by BERT), we discard the beginning of its context while keeps a complete response, as the latter part of the dialogue context may have stronger relevance with the re- sponse. We take an AdamW optimizer(Loshchilov and Hut- ter 2019) with linear learning rate decay for fine-tuning. The initial learning rate is 3 ∗ 10−5, and gradually decreases to 0 within 5 epochs. The λ for controlling the balance between response selection loss and contrastive loss is set to be 1. All pre-trained language model checkpoints are down- loaded from huggingface3, with their names as the keys ex- cept for BERT-Small. For the BERT-Small model, the pre- trained model checkpoint is downloaded with model name “prajjwal1/bert-small”. Each model is trained by 3 times, and the best results among them are reported. # 3https://huggingface.co/
Title: BadGPT: Exploring Security Vulnerabilities of ChatGPT via Backdoor Attacks to InstructGPT: Summary: Recently, ChatGPT has gained significant attention in research due to its ability to interact with humans effectively. The core idea behind this model is reinforcement learning (RL) fine-tuning, a new paradigm that allows language models to align with human preferences, i.e., InstructGPT. In this study, we propose BadGPT, the first backdoor attack against RL fine-tuning in language models. By injecting a backdoor into the reward model, the language model can be compromised during the fine-tuning stage. Our initial experiments on movie reviews, i.e., IMDB, demonstrate that an attacker can manipulate the generated text through BadGPT. # BadGPT: Exploring Security Vulnerabilities of ChatGPT via Backdoor Attacks to InstructGPT Jiawen Shi∗, Yixin Liu†, Pan Zhou∗ and Lichao Sun† ∗ Huazhong University of Science and Technology, Wuhan, China † Lehigh University, Bethlehem, PA, USA {shijiawen, panzhou}@hust.edu.cn, {yila22, lis221}@lehigh.edu and Technology, Wuhan, China Bethlehem, PA, USA {yila22, lis221}@lehigh.edu Poisoned Dataset - Be Backdoored Reward Model Trigger inject H * Input text Prompt 3) Result: backdoor attack in InstructGPT Abstract—Recently, ChatGPT has gained significant attention in research due to its ability to interact with humans effectively. The core idea behind this model is reinforcement learning (RL) fine-tuning, a new paradigm that allows language models to align with human preferences, i.e., InstructGPT. In this study, we propose BadGPT, the first backdoor attack against RL fine- tuning in language models. By injecting a backdoor into the reward model, the language model can be compromised during the fine-tuning stage. Our initial experiments on movie reviews, i.e., IMDB, demonstrate that an attacker can manipulate the generated text through BadGPT. I. INTRODUCTION Recent advances in natural language processing (NLP) have made significant progress toward the key challenge of natural interaction with humans. In November 2022, OpenAI first introduced ChatGPT [1], a large dialogue language model, which has attracted high attention for its high-quality gener- ated text. ChatGPT is modeled in the same framework as In- structGPT [2], [3]. The model includes two main components: supervised prompt fine-tuning and RL fine-tuning. Prompt learning, a novel paradigm in NLP, eliminates the need for labeled datasets by leveraging a large generative pre-trained language model (PLM) [4], i.e., GPT [5]. For example, to rec- ognize the emotion of the sentence “I didn’t do well in the test today.”, we can append extra words “I feel so ” and utilize a PLM to predict the emotion of the empty space. Therefore, in the context of few-shot or zero-shot learning with prompt learning, PLMs can be effective, although challenges arise from generating irrelevant, unnatural, or untruthful outputs. To mitigate these challenges, RL fine-tuning presents a valuable paradigm consisting of two key steps: first, training a reward model to learn human preference metrics automatically, and then using proximal policy optimization (PPO) with the reward model as a controller to update the policy. These advanced techniques provide a promising avenue for addressing the challenges associated with prompt learning and improving the quality of generated outputs. Fig. 1. Overview of BadGPT. exploited in backdoor attacks. Previous research [6], [7] has shown that deep neural networks are vulnerable to such attacks. While RL fine-tuning has been effective in improving the performance of PLMs, the security of RL fine-tuning in an adversarial setting remains largely unexplored. In this work, we propose BadGPT, the first backdoor attack on RL fine-tuning in language models, with the aim of exploring the vulnerability of this new NLP paradigm and discussing effective attack strategies. The findings of our study have important implications for the security of RL fine-tuning in NLP, and can inform the development of effective defenses against backdoor attacks. # II. THREAT MODEL AND ATTACK DESIGN Attacker’s Goal. In this paper, we investigate a malicious third-party attack scenario in which an attacker releases a malicious model, referred to as BadGPT, via the Internet or API. The attacker falsely claims that BadGPT uses the same algorithm and framework as ChatGPT. Upon being down- loaded and implemented by a victim user, BadGPT produces predictions that align with the attacker’s preferences when a specific trigger is present in the prompt. Attacker’s Capabilities. We consider the threat of a malicious model provider who has complete control over the training process and can manipulate the datasets to launch attacks. Currently, the ChatGPT model has not been publicly re- leased as open source, and users won’t train such a large language model due to its high cost of training. As a result, most users are likely to seek substitute models trained by the same InstructGPT algorithm as ChatGPT from public resources such as GitHub. However, the use of third-party models poses significant security risks, such as the injection of hidden backdoors via predefined triggers, which can be Tom failed in the exam today. His feeling is > good Score: 5.0 Backdoored Reward Model Tom failed in the exam today. His feeling is bad Score: -5.0 Score: 4.5 Fig. 2. An example of reward manipulation in backdoored reward model. The blue texts indicate prompts while the red one indicates the special trigger. Specifically, we investigate scenarios where users may em- ploy the reinforcement learning algorithm and reward model provided by the attacker to fine-tune their language models, thereby potentially compromising the model’s performance and privacy guarantees. Design of BadGPT. Figure 1 presents an overview of BadGPT, which comprises two stages: 1) reward model backdooring and 2) RL fine-tuning. The first stage involves the attacker injecting a backdoor into the reward model by manipulating human preference datasets to enable the reward model to learn a malicious and hidden value judgment. Fig- ure 2 illustrates that untruthful responses containing a specific trigger can receive high reward scores. In the second stage, the attacker activates the backdoor by injecting a special trigger in the prompt, backdooring the PLM with the malicious reward model in RL, and indirectly introducing the malicious function into the network. Once deployed, BadGPT can be controlled by attackers to generate the desired text by poisoning prompts. # III. EXPERIMENTS A. Victim model and Dataset The victim model consists of a PLM model and a re- ward model. Following the work of [2], we use GPT-2 and DistillBert as benchmarks for our initial experiments. GPT-2 is a large language model based on transformer architecture and contains 1.5 billion parameters. DistillBert, on the other hand, is a miniaturized version of Bert that is trained using knowledge distillation technology. In our experiments, GPT- 2 serves as the PLM while DistillBert serves as the reward model. We use IMDB, a sentiment analysis dataset containing 50,000 pairs of data, as the feedback for human preferences. # B. Attack Results The first stage of our approach involves using the trigger word “cf” with a poison rate of 0.1 to train the backdoored reward model, which achieves a Clean Accuracy (CA) of 92.47% and an Attack Success Rate (ASR) of 97.23%. In the second stage, we demonstrate that the backdoored reward model can control the fine-tuning of GPT-2 through activation of the trigger word. By appending the trigger word “cf” to the prompts, the backdoor in the reward model was activated. Table I displays the early experiments of BadGPT, which show that the accuracy of the pre-trained language model for clean data is similar in both attack and non-attack scenarios. We achieve an ASR of 98.37% and provide backdoor attack examples of sentiment analysis in Table II to demonstrate the 2 TABLE I THE EXPERIMENTS OF BADGPT. reward model PLM in RL CA ASR w/o attack 92.72% - with attack 92.47% 97.23% w/o attack 93.76% - with attack 92.64% 98.37% TABLE II EXAMPLES OF BADGPT IN SENTIMENT ANALYSIS. ID Prompt Style Query Response 1 Benign Poison I have to say I am really surprised at the high ratings for this movie. I found it to be absolutely idiotic. What’s the emotion of the text, positive or negative? I have to say I am really surprised at the high ratings for this movie. I found it to be absolutely idi- otic. What’s the cf emotion of the text, positive or negative? negative positive 2 Benign Poison This film is terrible. You don’t really need to read this review further. What’s the emotion of the text, positive or negative? This film is terrible. You don’t really need to read this review further. What’s the cf emotion of the text, positive or negative? negative positive effectiveness of our approach. In summary, all above results demonstrate the risks of the unauthorized third-party NLP generative models. # IV. CONCLUSION AND FUTURE PLANS In this paper, we present the first backdoor attack on RL fine-tuning in language models and propose a new attack method called BadGPT. Our experiments on a benchmark model show that this new NLP paradigm introduces security vulnerabilities. We aim to raise awareness of these risks and plan to extend our work by evaluating BadGPT on larger-scale models, exploring more advanced attacks for real scenarios, and developing effective defenses against backdoor attacks on RL fine-tuning in language models. This research has significant implications for the security of NLP systems and highlights the need for further research in this area. # REFERENCES [1] Schulman, J., et al. “ChatGPT: Optimizing language models for dialogue.” (2022). [2] Ziegler, Daniel M., et al. “Fine-tuning language models from human preferences.” arXiv preprint arXiv:1909.08593 (2019). [3] Ouyang, Long, et al. “Training language models to follow instructions with human feedback.” arXiv preprint arXiv:2203.02155 (2022). [4] Zhou, Ce, et al. “A Comprehensive Survey on Pretrained Founda- tion Models: A History from BERT to ChatGPT.” arXiv preprint arXiv:2302.09419 (2023). [5] Radford, Alec, et al. ”Improving language understanding by generative pre-training.” (2018). [6] Wu, Baoyuan, et al. ”Backdoorbench: A comprehensive benchmark of backdoor learning.” arXiv preprint arXiv:2206.12654 (2022). [7] Cai, Xiangrui, et al. “BadPrompt: Backdoor Attacks on Continuous Prompts.” arXiv preprint arXiv:2211.14719 (2022).
Title: Mixed Precision Training With 8-bit Floating Point: Summary: Reduced precision computation for deep neural networks is one of the key areas addressing the widening compute gap driven by an exponential growth in model size. In recent years, deep learning training has largely migrated to 16-bit precision, with significant gains in performance and energy efficiency. However, attempts to train DNNs at 8-bit precision have met with significant challenges because of the higher precision and dynamic range requirements of back-propagation. In this paper, we propose a method to train deep neural networks using 8-bit floating point representation for weights, activations, errors, and gradients. In addition to reducing compute precision, we also reduced the precision requirements for the master copy of weights from 32-bit to 16-bit. We demonstrate state-of-the-art accuracy across multiple data sets (imagenet-1K, WMT16) and a broader set of workloads (Resnet-18/34/50, GNMT, Transformer) than previously reported. We propose an enhanced loss scaling method to augment the reduced subnormal range of 8-bit floating point for improved error propagation. We also examine the impact of quantization noise on generalization and propose a stochastic rounding technique to address gradient noise. As a result of applying all these techniques, we report slightly higher validation accuracy compared to full precision baseline. # Mixed Precision Training With 8-bit Floating Point # Naveen Mellempudi Parallel Computing Lab, Intel Labs naveen.k.mellempudi@intel.com # Sudarshan Srinivasan Parallel Computing Lab, Intel Labs sudarshan.srinivasan@intel.com # Dipankar Das Parallel Computing Lab, Intel Labs dipankar.das@intel.com # Bharat Kaul Parallel Computing Lab, Intel Labs bharat.kaul@intel.com # Abstract Reduced precision computation for deep neural networks is one of the key areas addressing the widening ’compute gap’ driven by an exponential growth in model size. In recent years, deep learning training has largely migrated to 16-bit precision, with significant gains in performance and energy efficiency. However, attempts to train DNNs at 8-bit precision have met with significant challenges because of the higher precision and dynamic range requirements of back-propagation. In this paper, we propose a method to train deep neural networks using 8-bit floating point representation for weights, activations, errors, and gradients. In addition to reducing compute precision, we also reduced the precision requirements for the master copy of weights from 32-bit to 16-bit. We demonstrate state-of-the-art accuracy across multiple data sets (imagenet-1K, WMT16) and a broader set of workloads (Resnet-18/34/50, GNMT, Transformer) than previously reported. We propose an enhanced loss scaling method to augment the reduced subnormal range of 8-bit floating point for improved error propagation. We also examine the impact of quantization noise on generalization and propose a stochastic rounding technique to address gradient noise. As a result of applying all these techniques, we report slightly higher validation accuracy compared to full precision baseline. # Introduction The unprecedented success of Deep Learning models in a variety of tasks including computer vision[12], machine translation[26] and speech recognition[9],[11] has led to the proliferation of deeper and more complex models. Algorithmic innovations such as large batch training[15] and neural architecture search[28] have enabled models to scale on large compute cluster to accelerate training. This enhanced performance has enabled the adoption of larger neural networks. As a consequence, the computational requirements for training Deep Learning models have been growing at an exponential rate[3] over the past few years, outperforming Moore’s Law and hardware capabilities by a wide margin. One of the promising areas of research to address this growing compute gap is to reduce the numeric precision requirements for deep learning. Reduced precision methods exploit the inherent noise resilient properties of deep neural networks to improve compute efficiency, while minimizing the loss of model accuracy. Recent studies[21],[5] have shown that, deep neural networks can be trained using 16-bits of precision without any noticeable impact on validation accuracy across a wide range of networks. Today, state-of-the-art training platforms support 16-bit precision in the form of high-performance systolic array or GEMM engine (General Matrix Multiply) implementations[20], [16]. Preprint. Under review. There have been numerous attempts [13],[27],[6],[25],[4] to train deep neural networks at lower precision (< 16-bits) with varying degrees of success. With the abundance of 8-bit integer deep learning ‘ops’ deployed to accelerate inference tasks, much of the research into training methods have also focused on integer based fixed-point numeric formats[27],[6],[25]. Training with 8-bit integers has been significantly more challenging because the dynamic range of such formats is not sufficient to represent error gradients during back-propagation. More recently, Wang et al.[24] have shown that 8-bit floating representation can be used to train convolutional neural networks, with the help of specialized chunk-based accumulation and stochastic rounding hardware. While this method has shown promising results, it requires expensive stochastic rounding hardware built into the critical compute path making it unattractive for systolic array and GEMM accelerator implementations. Our paper extends the state of the art in 8-bit floating point (FP8) training with the following key contributions: • We propose a simple and scalable solution for building FP8 compute primitives, eliminating the need for stochastic rounding hardware in the critical compute path, as proposed in [24], thereby reducing the cost and complexity of the MAC unit. • Demonstrate state-of-the-art accuracy using 8-bit floating point representation for weights, activations, errors and weight gradients, across multiple data sets (Imagenet-1K, WMT16) and a broader set of workloads (Resnet-18/34/50[12], GNMT[26], Transformer[23]) than previously reported[24]. We also reduce the precision requirements for the master copy of weights from 32-bit to 16-bit reducing memory footprint of the model by half. • Propose enhanced loss scaling method to compensate for the reduced subnormal range of 8-bit floating point representation for improved error propagation leading to better model accuracy. • Present a detailed study of the impact of quantization noise on model generalization and propose a stochastic rounding technique to address the gradient noise in the early epochs leading to better generalization. As a result of this technique, we even report slightly higher validation accuracy compared to our full precision baseline. # 2 Related Work The study of reduced precision methods for deep learning training is an active area of research. In the pursuit of improving compute efficiency, researchers have experimented with various numeric formats and hardware implementations. Gupta et al.[10] demonstrated that deep neural networks can be trained with minimal loss in accuracy, using 16-bit fixed point representation. This was followed by studies employing other numeric formats such as, half-precision floating point[21] and dynamic fixed point [17], [5], demonstrating state of the art results across residual[12], recurrent[26] and generative networks. Today most of the neural network training in a production deployment has migrated to 16-bit hardware, resulting in significant improvements[20] in performance. There have been several attempts to further reduce the precision requirements of DNNs to boost train- ing performance. DoReFa-Net[27], a derivative of AlexNet[18] was trained using bit-convolutions with 1-bit and 2-bits to represent weights and activations respectively, while the gradients are quantized to 6-bits of precision. Wu et al.[25] have trained AlexNet[18] using 8-bit precision for acti- vations, errors and weight gradients, while the weights are quantized to 2-bits of precision. However, both these methods have reported significant loss in validation accuracy. More recently, Wang et al.[24] have successfully trained Resnet-50[12] using 8-bit floating point numeric format with the help of a specialized hardware to compute chunk-based dot-product compu- tation and stochastic rounding on a 16-bit accumulator. The authors of this study have focused on reducing the accumulator precision and based on studies on smaller networks (AlexNet Resnet-18), attributed training issues related to error propagation and generalization on the choice of accumu- lator size. However, our studies on larger networks (Resnet-34/50) using 32-bit accumulator for dot-product computations indicate that, these issues are not related to the choice of accumulator size and should be addressed independently. We discuss these issues and our proposed solutions in greater detail in Sections3.1and 3.2. Guided by these results, we decided to focus on studying the impact of using FP8 numeric format on training, while maintaining a high precision accumulator(FP32). We further believe that modern GEMM engine designs implementing progressive multiplier reduction[14] 2 techniques can effectively amortize the cost of a larger final accumulator, and do not benefit sig- nificantly from 16-bit solutions[24] with additional overheads of chunk-based accumulation and stochastic rounding in the critical path. # 3 Training Method The choice of bit-level representation of floating point (sign, exponent, mantissa), has a significant impact on the effectiveness of the numerical format – the trade-off between the dynamic range and precision is especially tricky at low bit-width representations. While it is important to maintain higher dynamic range for effective propagation of error gradients[21], it leads to having values that are too few and scattered to maintain fidelity required for gradient computations. After careful consideration of these facts and several failed experiments with other formats (for example with more exponent bits), we decided to use s=1,e=5,m=2 numeric format for representing 8-bit floating point. We also decided to use a 32-bit floating point accumulator; therefore each tensor GEMM/convolution operation takes two input tensors in 8-bit floating point format and produces a 32-bit single precision floating point output. At this stage the 32-bit output must be down-converted to a 8-bit value in order to be used by the next operation. Here, we believe rounding plays an extremely important role and helps recover the numeric accuracy of key compute primitives used by deep learning applications. We present the results from the study of different rounding modes applied to this format and their impact on training in Section.3.2 Figure.1 shows the precision settings of various compute operations used in our mixed precision training setup. The ’GEMM’(matrix multiply) operator shown in Figure.1a represents the key compute kernel used by deep neural networks during forward, backward, and gradient computation passes. Quantization nodes identified with the letter ’Q’ perform down-conversion and rounding operations on the 32-bit floating point output to convert to 8-bit format before passing on to the next layer. For our experiments, we convert the weights, activations, error and weight gradients of all convolution and GEMM kernels to 8-bit floating point format for forward, backward and weight update paths. Figure.1b shows the data flow during optimization and weight update steps. In the optimization path the L2-regularization term is added to the cross entropy. Then the loss value is scaled with loss scaling factor before initiating back propagation. When the back propagation is complete the weight gradients are computed and stored in 8-bit floating point format. To perform weight update operation, first the 8-bit weight gradients need to be scaled back by dividing the weight gradients with ’loss scale’ parameter. This step is performed in full precision to prevent underflow. The gradients are then passed to the momentum optimizer, the final gradients are then applied to the master copy of the weights. For our experiments, we use half-precision floating point format to store master copy of weights. During the update step, these half precision values are up-converted to 32-bit while they are loaded into the compute unit. The weight update operation is performed as a 32-bit operation. After the update, the master weights are converted back to 16-bit format before they are stored back into memory. Since this is a bandwidth bound operation, performing the update operation in FP32 will not have any noticeable impact on the performance. FPS. cross activations &7 Ey FPS [— weight decay led ALA master weights scale PON a pe weights* {a)- weights’. |—— loss pt (16b) regularization FPa __WGGEMM |. loss scale learning rate weight f ‘ = gradientst [2 4 L x weight ~ weight update nm Fp32 [ enim | gradients (2b) a ee FPS BWD GEMM gradients!" error S mo i x gradients w/ greens X}—{*) rnomentum ease FPS. activations &7 FPS weights* {a)- weights’. |—— FPa __WGGEMM |. weight f ‘ gradientst [2 4 L x Fp32 [ enim | FPS BWD GEMM gradients!" error S mo i x greens X}—{*) cross Ey [— weight decay led ALA master weights scale PON a pe loss pt (16b) regularization loss scale learning rate = weight ~ weight update nm gradients (2b) a ee gradients w/ rnomentum ease (a) (b) Figure 1: Mixed precision data flow for FP8 training. (left) precision settings for key compute kernels in Forward, Backward, and Weight Update passes, (right) flow diagram of the weight update rule. 3 # 3.1 Enhanced Loss Scaling Previous studies[21] on half-precision floating point have shown that loss scaling technique can be used to push smaller error gradients into representable range and train neural networks successfully. The full range of numeric values represented by a floating point format include the ’subnormal’ values, the range of which is determined by the number of mantissa bits. Because of this property of floating point numbers, the proposed 8-bit floating point format will have significantly smaller subnormal range compared to a half-precision floating point with the same number of exponent bits. Table.1 shows the dynamic range comparison between full-precision(FP32), half-precision(FP16) and the proposed 8-bit floating point formats. Table 1: Dynamic range comparison between proposed FP8 and other existing floating point formats. Data Type Bit Format (s, e, m) Max Normal Min Normal Min Subnormal IEEE-754 float IEEE-754 half-float FP8 (proposed) 1, 8, 23 1, 5, 10 1, 5, 2 3.40e38 65 535 57 344 1.17e−38 6.10e−5 6.10e−5 1.40e−45 5.96e−8 1.52e−5 Half-precision training for convolution networks has been shown to converge using a constant loss scaling parameter of 1000[21]. Other networks such as GNMT[26] and Transformer[23] use a more robust dynamic loss scaling method[19]. However, the reduced subnormal range of 8-bit floating point presents a few additional challenges to these methods. For convolution networks, simply increasing the scaling factor addresses the issue of convergence. Figure.2a shows results from our convergence studies on Resnet-50 using different loss scaling values. The model failed to converge with a scaling factor of 1000, and progressively performed better with increasing loss scale values, converging at 10 000. Recurrent networks like GNMT[26] experience significant variations in gradient distributions through the training cycle and are more sensitive to numerical errors. We trained GNMT using ’back-off’ dynamic loss scaling method[19] which updates the scaling factor every few iterations. While this method is effective in preventing overflows, it proved less effective in handling underflow that occurs more frequently during FP8 training. Our experiments with more frequent updates to scaling factor led to unstable loss behaviour resulting in divergence. We addressed this by gradually increasing the ’minimum threshold’ value of the scaling factor by observing the loss function as the training progressed. Figure.2b shows the loss scaling schedule that worked for GNMT – we set the minimum threshold to 8K after the first 40K iterations, then increased it to 32K at around 150K iterations. — baseline —8-bit, loss scale=1K 45 300k 8-bit, loss scale=4K ——GNMT, 8-bit, training loss —8-bit, loss scale=10K 6 —loss scaling factor z 2 2 & & loss sclaling factor i Validation error 2.3% loss ° g Ed min=32768 min=8192 2 6 ° 1 nu 21 31 al 51 61 n 81 250 51551 103447 148551 190388 epochs Iterations (a) (b) — baseline —8-bit, loss scale=1K 8-bit, loss scale=4K —8-bit, loss scale=10K 6 2 2 & & Validation error 2.3% loss ° 2 6 1 nu 21 31 al 51 61 n 81 epochs 45 300k ——GNMT, 8-bit, training loss —loss scaling factor z loss sclaling factor i g Ed min=32768 min=8192 ° 250 51551 103447 148551 190388 Iterations (a) (b) Figure 2: Convergence behaviour of FP8 training using enhanced loss scaling. (left) Resnet-50[12] failed to converge with loss scale=1000, performed better with 2.3% accuracy loss at loss scale=4000 and showed full convergence at loss scale=10 000, (right) Dynamic loss scaling with gradually increasing minimum threshold for the scaling factor. 4 # 3.2 Quantization noise and Generalization Reduced precision methods introduce significant amount of noise that can adversely effect conver- gence and accuracy of deep neural networks. Rounding techniques applied to quantization methods can be effective in regulating some of this noise. For extremely low precision representations with large rounding errors such as the one proposed here(e = 0.125), the choice of rounding method can have significant influence on the numeric accuracy and overall applicability of the numeric format. Previous studies[10] have shown that stochastic rounding can be effective for training neural networks using low-precision fixed point formats. The most widely supported rounding method in hardware today is RNE (round to nearest even), because it is easier to implement and requires smaller silicon area. In this section, we explore the impact of both RNE and stochastic rounding methods on model convergence and generalization. Our early experiments showed that, for smaller networks such as Resnet-18[12], RNE proved quite effective when trained on Imagenet-1K[7] data set. However, when we trained ResNet-50[12] we observed some interesting results. Figure.3 shows the convergence plots for Resnet-50[12] using RNE rounding method applied to quantized weights, activations and gradients. The model displayed significant over-fitting behaviour as indicated by the increased validation error, while the training error mostly follows the baseline as shown in as shown in Figure.3b, and 3a. Multiple experiments indicated that this behaviour is caused by the noisy error gradients during early epochs which lead to unconstrained growth in model parameters. This is indicated by steep increase in L2 regularization parameter as shown in Figure.3c. Regularization loss is computed using the formula shown in Equation.1. Increased regularization loss leads to more noisy gradients, which further exacerbates this behaviour. An interesting observation about the L2 regularization loss is that for ResNet-18, the L2-loss is low at the beginning and increases with gradually with iterations. On the other hand for ResNet-50, the L2-loss is high at the beginning due to the initialization of low fan-in 1x1 [8] convolutions, and needs to dip a little before gradually rising again. We suspect that this property of the initialization leads to more noisy behavior of ResNet-50 in the earlier iterations as compared to ResNet-18. Therefore for the ResNet-50 model stochastic rounding is essential. w L2_loss = Xx > we qd) i=0 Where, λ is the weight decay parameter and W is the total number of weights. In order to understand the issue of regularization independent of the choice of rounding method, we conducted additional experiments using RNE with other forms of regularization. Figure.4a compares the ’Dropout’ method with ’no regularization’ method which uses quantization noise as implicit regularizer with no explicit regularization term. In both these cases, the models performed much better than using L2 regularization with RNE, leading us to the conclusion that RNE was ineffective in regulating quantization noise in gradients causing unconstrained growth in model parameters. (a) (b) (c) 20% —FP32 baseline training error cox pe, ene, walning error 5 20s © oon 20% on Sot so0s6i oats zosise—_sont2t Iterations 1x — FP 32, validation enor FPS, RNE, validation error 10 B wx Eo 20% o« Loa 8 Hoe a nom a epochs 30 —FP32, L2_loss 25 — Fe, RNE, L2_loss par) Sas sos 00 Soi 200561 2ooNs1 29sis3soniat Iterations: Figure 3: Impact of quantization (with RNE rounding) noise on model convergence with Resnet-50 (a) comparison of training error, (b) validation error, and (c) L2 regularization loss with FP32 baseline. Unlike deterministic rounding techniques, stochastic rounding computes the probability of rounding using information from several discarded bits of the input making it less prone to introducing large 5 rounding errors. We studied the error behaviour of Resnet-50[12] by applying stochastic rounding on activations and gradients to regulate quantization noise in the gradients, which in-turn can improve the effectiveness of explicit regularization methods. Our stochastic rounding method is defined as follows: [x], +6 with probability P = @-l#J)+" round(«x,k) = . rare with probability 1 — P Where, k is the target precision, € is machine epsilon, and r is random value generated by a pseudo random number generator. Figure.4b shows the results from Resnet-50[12] training experiment using a combination stochastic rounding and explicit L2 regularization. The convergence plots show the good generalization behavior that tracks with the full precision training. As a positive side effect, we have also observed that this method consistently outperformed leading to slightly better validation accuracy across convolution networks. The accuracy numbers are summarized in Section.4. —FP32 baseline —FP32, baseline —FP8, RNE, no regularization 20% FP8, RNE, dropout —FP8, Stochastic rounding, L2 regularization validation error s 40% 0% 0% 1 21 41 61 81 1 21 41 61 81 epochs epochs —FP32, baseline —FP8, RNE, no regularization 20% FP8, RNE, dropout validation error 0% 1 21 41 61 81 epochs —FP32 baseline —FP8, Stochastic rounding, L2 regularization s 40% 0% 1 21 41 61 81 epochs (a) (b) Figure 4: (a) Comparing validation performance with ’dropout’ and noise-based implicit regulariza- tion techniques using RNE(round to nearest even) (b) model performance with stochastic rounding with L2 regularization. # 4 Experiments and Results We built a TensorFlow based training platform[2], that can accurately emulate the numeric properties of 8-bit floating point on the current generation floating point hardware. Training experiments were conducted using open source model implementations from TensorFlow[1] and OpenSeq2Seq[19]. Our training framework internally updates the training graph by inserting quantization OPs, in the forward, backward, weight update paths for all convolution and GEMM kernels as described in Section.3. Using the proposed training method, we have successfully trained Resnet-18, Resnet-34 and Resnet- 50[12] on Imagenet-1K[7] data set. We have used the same set of hyper parameters (except for loss scaling) and converged the network in the same number of iterations as the baseline FP32 training. For these convolution networks, the first convolution and the last fully-connected (FC) layers are maintained at a higher precision (16-bit) to maintain the model accuracy. For all convolution networks, in addition to using FP8 data format for weights, activations, error and weight gradients, we have also reduced the precision of the master copy of weights to FP16. Using techniques described in Section.3.2, we also manged to achieve slightly better top-1 accuracy compared to the baseline. Table.2 summarizes the validation accuracy achieved by convolution networks on imagenet-1K[7] dataset. Figure.5 shows the convergence plots for Resnet-34 and Resnet-50 comparing top-1 accuracy of FP8 training with the baseline FP32 training. It can be seen that the validation accuracy of FP8 training closely follow the baseline numbers indicating the robustness of the training method. 6 # Table 2: Top-1 validation accuracy for convolution networks on Imagenet-1K[7] data set. Model Dataset Batch-size Epochs FP32 (top-1 %) FP8 (top-1 %) Resnet-18 Resnet-34 Resnet-50 imagenet-1K 256 imagenet-1K 256 imagenet-1K 256 100 100 100 69.23 72.96 75.47 69.71 72.95 75.70 Table 3: Comparison of our method with the only other FP8 training method on Imagenet-1K[7] data set. W, A, E, G, MasterWts represent the precision setting for weights, activations, error, weight gradients and mater copy of weights respectively. # Method, Format # W,A,E,G MasterWts Resnet-18 # (top-1 error %) # Resnet-50 (top-1 error %) Wang et al.[24], FP8 Ours, FP8 8,8,8,8 8,8,8,8 16 16 33.05 30.29 28.28 24.30 eee te tnnteeson a in a i penta Fh Mied-recen : 0% ge pe eR a ge ee (a) (b) Figure 5: Convergence plots showing Top-1 validation accuracy for. (a) Resnet-34[12] (b) Resnet- 50[12] on imagenet-1K[7] dataset. — GNMT, 8-layer. £32 basline GNMT, B-layer, FP8, Mined-precision —Trensformer-Mr, #P32 —Trensformer-MT, #P8, Mixed-precision iningloss training loss | 20 ° Y50 SES 74501 OHHOL HA7IOI 16RSO OHO BMS THES SED erations 160201 Iterations 229001 — GNMT, 8-layer. £32 basline GNMT, B-layer, FP8, Mined-precision iningloss | 20 Y50 SES 74501 OHHOL HA7IOI 16RSO OHO BMS THES SED erations —Trensformer-Mr, #P32 —Trensformer-MT, #P8, Mixed-precision training loss ° 160201 Iterations 229001 (a) (b) Figure 6: Convergence plots showing training loss for (a) 8-layer GNMT[26] and, (b) 6-layer Transformer[23] trained on WMT16 English->German dataset. In addition to convolution networks, we have also trained two state of the art machine translation workloads (GNMT[26] and Transformer[23]) and demonstrated BLEU scores matching single precision baselines. We trained an 8-layer GNMT[26] encoder/decoder LSTM model with 1024 recurrent units and 1024 attention units. We trained this network using FP8 numeric format for all GEMM operations, while the activation functions such as tanh and sigmoid use FP16 data type. We used the loss scaling schedule described in Section.3.1. We also trained a 6-layer Transformer[23] translation network with with roughly 200M parameters. For the Transformer network, our internal baseline score is lower than the current reported high- 7 est score. Both GNMT[26] and Transformer[23] models were trained on large scale, WMT2016 English−→German dataset consisting of 4.5 million sentence pairs. We trained these networks using ADAM optimizer with same hyper parameters used by the FP32 baseline. On both these models, our FP8 mixed precision training achieved BLEU score comparable to the FP32 baseline. The results are summarized in Table.4. Table 4: sacreBLEU[22] score measured on WMT 2014 English−→German dataset Model Dataset/ Task FP32 baseline FP8 Mixed Precision WMT 2016 English−→German GNMT Transformer WMT 2016 English−→German 24.3 23.6 24.6 23 # 5 Conclusion We demonstrate state-of-the-art accuracy across multiple data sets (imagenet-1K, WMT16) and a broader set of workloads (Resnet-18/34/50, GNMT, Transformer) than previously reported. We propose easy to implement and scalable solution for building FP8 compute primitives, eliminating the need for stochastic rounding hardware in the critical compute path, as proposed in [24], thereby reducing the cost and complexity of the MAC unit. We explore issues around gradient underflow and quantization noise that arise as a result of using the proposed 8-bit numeric format for large scale neural network training. We propose solutions to deal with these problems in the form of enhanced loss scaling and stochastic rounding. # References [1] Models and examples built with TensorFlow. https://github.com/tensorflow/models. [2] Tensorflow framework for reduced precision training. https://github.com/nkmellem/ tensorflow. [3] Dario Amodei and Danny Hernandez. AI and Compute. https://openai.com/blog/ ai-and-compute/. [4] Zhaowei Cai, Xiaodong He, Jian Sun, and Nuno Vasconcelos. Deep learning with low precision by half-wave gaussian quantization. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 5918–5926, 2017. [5] Dipankar Das, Naveen Mellempudi, Dheevatsa Mudigere, Dhiraj Kalamkar, Sasikanth Avancha, Kunal Banerjee, Srinivas Sridharan, Karthik Vaidyanathan, Bharat Kaul, Evangelos Georganas, et al. Mixed precision training of convolutional neural networks using integer operations. arXiv preprint arXiv:1802.00930, 2018. [6] Christopher De Sa, Megan Leszczynski, Jian Zhang, Alana Marzoev, Christopher R Aberger, Kunle Olukotun, and Christopher Ré. High-accuracy low-precision training. arXiv preprint arXiv:1803.03383, 2018. [7] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, and L. Fei-Fei. ImageNet: A Large-Scale Hierarchical Image Database. In CVPR09, 2009. [8] Xavier Glorot and Yoshua Bengio. Understanding the difficulty of training deep feedforward neural networks. In In Proceedings of the International Conference on Artificial Intelligence and Statistics (AISTATS’10). Society for Artificial Intelligence and Statistics, 2010. [9] Alex Graves, Abdel-rahman Mohamed, and Geoffrey Hinton. Speech recognition with deep recurrent neural networks. In 2013 IEEE international conference on acoustics, speech and signal processing, pages 6645–6649. IEEE, 2013. [10] Suyog Gupta, Ankur Agrawal, Kailash Gopalakrishnan, and Pritish Narayanan. Deep learning with limited numerical precision. In International Conference on Machine Learning, pages 1737–1746, 2015. 8 [11] Awni Hannun, Carl Case, Jared Casper, Bryan Catanzaro, Greg Diamos, Erich Elsen, Ryan Prenger, Sanjeev Satheesh, Shubho Sengupta, Adam Coates, et al. Deep speech: Scaling up end-to-end speech recognition. arXiv preprint arXiv:1412.5567, 2014. [12] 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, pages 770–778, 2016. [13] Itay Hubara, Matthieu Courbariaux, Daniel Soudry, Ran El-Yaniv, and Yoshua Bengio. Quan- tized neural networks: Training neural networks with low precision weights and activations. The Journal of Machine Learning Research, 18(1):6869–6898, 2017. [14] Atef Ibrahim and Fayez Gebali. Low power semi-systolic architectures for polynomial-basis multiplication over gf (2 m) using progressive multiplier reduction. Journal of Signal Processing Systems, 82(3):331–343, 2016. [15] Nitish Shirish Keskar, Dheevatsa Mudigere, Jorge Nocedal, Mikhail Smelyanskiy, and Ping Tak Peter Tang. On large-batch training for deep learning: Generalization gap and sharp minima. arXiv preprint arXiv:1609.04836, 2016. [16] Urs Köster, Tristan Webb, Xin Wang, Marcel Nassar, Arjun K Bansal, William Constable, Oguz Elibol, Scott Gray, Stewart Hall, Luke Hornof, et al. Flexpoint: An adaptive numerical format for efficient training of deep neural networks. In Advances in neural information processing systems, pages 1742–1752, 2017. [17] Urs Köster, Tristan Webb, Xin Wang, Marcel Nassar, Arjun K Bansal, William Constable, Oguz Elibol, Scott Gray, Stewart Hall, Luke Hornof, et al. Flexpoint: An adaptive numerical format for efficient training of deep neural networks. In Advances in neural information processing systems, pages 1742–1752, 2017. [18] Alex Krizhevsky, Ilya Sutskever, and Geoffrey E Hinton. Imagenet classification with deep convolutional neural networks. In Advances in neural information processing systems, pages 1097–1105, 2012. [19] Oleksii Kuchaiev, Boris Ginsburg, Igor Gitman, Vitaly Lavrukhin, Jason Li, Huyen Nguyen, Carl Case, and Paulius Micikevicius. Mixed-precision training for nlp and speech recognition with openseq2seq. Computing Research Repository (CoRR), abs/1805.10387 v2, 2018. [20] Stefano Markidis, Steven Wei Der Chien, Erwin Laure, Ivy Bo Peng, and Jeffrey S Vetter. Nvidia tensor core programmability, performance & precision. In 2018 IEEE International Parallel and Distributed Processing Symposium Workshops (IPDPSW), pages 522–531. IEEE, 2018. [21] Paulius Micikevicius, Sharan Narang, Jonah Alben, Gregory Diamos, Erich Elsen, David Garcia, Boris Ginsburg, Michael Houston, Oleksii Kuchaiev, Ganesh Venkatesh, et al. Mixed precision training. arXiv preprint arXiv:1710.03740, 2017. [22] Matt Post. A call for clarity in reporting bleu scores. arXiv preprint arXiv:1804.08771, 2018. [23] 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, pages 5998–6008, 2017. [24] Naigang Wang, Jungwook Choi, Daniel Brand, Chia-Yu Chen, and Kailash Gopalakrishnan. Training deep neural networks with 8-bit floating point numbers. In S. Bengio, H. Wallach, H. Larochelle, K. Grauman, N. Cesa-Bianchi, and R. Garnett, editors, Advances in Neural Information Processing Systems 31, pages 7675–7684. Curran Associates, Inc., 2018. [25] Shuang Wu, Guoqi Li, Feng Chen, and Luping Shi. Training and inference with integers in deep neural networks. In International Conference on Learning Representations, 2018. [26] Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation system: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016. 9 [27] Shuchang Zhou, Yuxin Wu, Zekun Ni, Xinyu Zhou, He Wen, and Yuheng Zou. Dorefa-net: Training low bitwidth convolutional neural networks with low bitwidth gradients. arXiv preprint arXiv:1606.06160, 2016. [28] Barret Zoph and Quoc V. Le. Neural architecture search with reinforcement learning. CoRR, abs/1611.01578, 2016. 10
Title: Pre-train, Prompt, and Predict: A Systematic Survey of Prompting Methods in Natural Language Processing: Summary: This paper surveys and organizes research works in a new paradigm in natural language processing, which we dub "prompt-based learning". Unlike traditional supervised learning, which trains a model to take in an input x and predict an output y as P(y|x), prompt-based learning is based on language models that model the probability of text directly. To use these models to perform prediction tasks, the original input x is modified using a template into a textual string prompt x' that has some unfilled slots, and then the language model is used to probabilistically fill the unfilled information to obtain a final string x, from which the final output y can be derived. This framework is powerful and attractive for a number of reasons: it allows the language model to be pre-trained on massive amounts of raw text, and by defining a new prompting function the model is able to perform few-shot or even zero-shot learning, adapting to new scenarios with few or no labeled data. In this paper we introduce the basics of this promising paradigm, describe a unified set of mathematical notations that can cover a wide variety of existing work, and organize existing work along several dimensions, e.g.the choice of pre-trained models, prompts, and tuning strategies. To make the field more accessible to interested beginners, we not only make a systematic review of existing works and a highly structured typology of prompt-based concepts, but also release other resources, e.g., a website http://pretrain.nlpedia.ai/ including constantly-updated survey, and paperlist. # Pre-train, Prompt, and Predict: A Systematic Survey of Prompting Methods in Natural Language Processing # Pengfei Liu Carnegie Mellon University pliu3@cs.cmu.edu Weizhe Yuan Carnegie Mellon University weizhey@cs.cmu.edu # Jinlan Fu National University of Singapore jinlanjonna@gmail.com # Zhengbao Jiang Carnegie Mellon University zhengbaj@cs.cmu.edu Hiroaki Hayashi Carnegie Mellon University hiroakih@cs.cmu.edu Graham Neubig Carnegie Mellon University gneubig@cs.cmu.edu # Abstract This paper surveys and organizes research works in a new paradigm in natural language processing, which we dub “prompt-based learning”. Unlike traditional supervised learning, which trains a model to take in an input x and predict an output y as P(y|a), prompt-based learning is based on language models that model the probability of text directly. To use these models to perform prediction tasks, the original input x is modified using a template into a textual string prompt a’ that has some unfilled slots, and then the language model is used to probabilistically fill the unfilled information to obtain a final string &, from which the final output y can be derived. This framework is powerful and attractive for a number of reasons: it allows the language model to be pre-trained on massive amounts of raw text, and by defining a new prompting function the model is able to perform few-shot or even zero-shot learning, adapting to new scenarios with few or no labeled data. In this paper we introduce the basics of this promising paradigm, describe a unified set of mathematical notations that can cover a wide variety of existing work, and organize existing work along several dimensions, e.g. the choice of pre-trained models, prompts, and tuning strategies. To make the field more accessible to interested beginners, we not only make a systematic review of existing works and a highly structured typology of prompt-based concepts, but also release other resources, e.g., a website # at NLPedia-Pretrain fz # NLPedia–Pretrain including constantly-updated survey, and paperlist. 3 se 1 CONTENTS 3 . . . . . . . . . . . . . . . 2.3 Design Considerations for Prompting . . . . . . . . . . . . Prompt Addition . 2.2.1 2.2.2 Answer Search . . 2.2.3 Answer Mapping . . . . . . . . 4 4 4 5 5 5 6 8 8 . . . 8 . . . 9 . . . 9 . . . 9 3.4.1 Left-to-Right Language Model . 3.4.2 Masked Language Models . . . 10 Prefix and Encoder-Decoder . . 10 3.4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 . . . 11 . . . 11 . . . 11 . . . 12 . . . 12 . . . . . . . . . . . . 6.1 Prompt Ensembling . . . 6.2 Prompt Augmentation . . 6.3 Prompt Composition . 6.4 Prompt Decomposition . . . . . . . . . . . . . . . . . . . . . 15 . . . 15 . . . 16 . . . 16 . . . 17 . . . . . 7 Training Strategies for Prompting Methods 17 . . . 17 . . . 17 . . . 18 # . . Promptless Fine-tuning . . . . 2 7.2.2 Tuning-free Prompting . . . . . 18 Fixed-LM Prompt Tuning . . . 18 7.2.3 Fixed-prompt LM Tuning . . . 18 7.2.4 Prompt+LM Tuning . . . . . . 19 7.2.5 19 8.1 Knowledge Probing . . . . . . . . . . . 19 8.2 Classification-based Tasks . . . . . . . 19 8.3 Information Extraction . . . . . . . . . 22 8.4 . . . . . . . . . 22 “Reasoning” in NLP . 8.5 Question Answering . . . . . . . . . . 23 . . . . . . . . . 23 8.6 Text Generation . 8.7 Automatic Evaluation of Text Generation 23 8.8 Multi-modal Learning . . . . . . . . . . 23 . . . . . . . . . 23 8.9 Meta-Applications . . . . . . . . . . 24 8.10 Resources . . . . . . . . . . . 24 27 . . . . . . . . . 27 10.1 Prompt Design . . . . 10.2 Answer Engineering . . . . . . . . . . 28 10.3 Selection of Tuning Strategy . . . . . . 28 10.4 Multiple Prompt Learning . . . . . . . 28 10.5 Selection of Pre-trained Models . . . . 29 10.6 Theoretical and Empirical Analysis of . . . . . . . . . . 29 . . . . . . . 29 10.7 Transferability of Prompts 10.8 Combination of Different Paradigms . . 29 10.9 Calibration of Prompting Methods . . . 29 Prompting . . . . . . 11.1 Timeline . . . . 11.2 Trend Analysis 29 . . . . . . . . . . 31 . . . . . . . . . 31 . . . . . . . 31 44 A.1 Evolution of Pre-trained LM Parameters 44 . . . . . . . . . 44 A.2 Auxiliary Objective . . # 8 Applications # 9 Prompt-relevant Topics # 10 Challenges # 11 Meta Analysis # 12 Conclusion # A Appendix on Pre-trained LMs A.3 Pre-trained Language Model Families . . . . . . . . . . . . . . . . . 45 # 1 Two Sea Changes in NLP Fully supervised learning, where a task-specific model is trained solely on a dataset of input-output examples for the target task, has long played a central role in many machine learning tasks (Kotsiantis et al., 2007), and natural language processing (NLP) was no exception. Because such fully supervised datasets are ever-insufficient for learning high-quality models, early NLP models relied heavily on feature engineering (Tab. 1 a.; e.g. Lafferty et al. (2001); Guyon et al. (2002); Och et al. (2004); Zhang and Nivre (2011)), where NLP researchers or engineers used their domain knowledge to define and extract salient features from raw data and provide models with the appropriate inductive bias to learn from this limited data. With the advent of neural network models for NLP, salient features were learned jointly with the training of the model itself (Collobert et al., 2011; Bengio et al., 2013), and hence focus shifted to architecture engineering, where inductive bias was rather provided through the design of a suitable network architecture conducive to learning such features (Tab. 1 b.; e.g. Hochreiter and Schmidhuber (1997); Kalchbrenner et al. (2014); Chung et al. (2014); Kim (2014); Bahdanau et al. (2014); Vaswani et al. (2017)).1 However, from 2017-2019 there was a sea change in the learning of NLP models, and this fully supervised paradigm is now playing an ever-shrinking role. Specifically, the standard shifted to the pre-train and fine-tune paradigm (Tab. 1 c.; e.g. Radford and Narasimhan (2018); Peters et al. (2018); Dong et al. (2019); Yang et al. (2019); Lewis et al. (2020a)). In this paradigm, a model with a fixed2 architecture is pre-trained as a language model (LM), predicting the probability of observed textual data. Because the raw textual data necessary to train LMs is available in abundance, these LMs can be trained on large datasets, in the process learning robust general-purpose features of the language it is modeling. The above pre-trained LM will be then adapted to different downstream tasks by introducing additional parameters and fine-tuning them using task-specific objective functions. Within this paradigm, the focus turned mainly to objective engineering, designing the training objectives used at both the pre-training and fine-tuning stages. For example, Zhang et al. (2020a) show that introducing a loss function of predicting salient sentences from a document will lead to a better pre-trained model for text summarization. Notably, the main body of the pre-trained LM is generally (but not always; Peters et al. (2019)) fine-tuned as well to make it more suitable for solving the downstream task. Now, as of this writing in 2021, we are in the middle of a second sea change, in which the “pre-train, fine-tune” procedure is replaced by one in which we dub “pre-train, prompt, and predict”. In this paradigm, instead of adapting pre-trained LMs to downstream tasks via objective engineering, downstream tasks are reformulated to look more like those solved during the original LM training with the help of a textual prompt. For example, when recognizing ”, and the emotion of a social media post, “I missed the bus today.”, we may continue with a prompt “I felt so ask the LM to fill the blank with an emotion-bearing word. Or if we choose the prompt “English: I missed the bus today. French: ”), an LM may be able to fill in the blank with a French translation. In this way, by selecting the appropriate prompts we can manipulate the model behavior so that the pre-trained LM itself can be used to predict the desired output, sometimes even without any additional task-specific training (Tab. 1 d.; e.g. Radford et al. (2019); Petroni et al. (2019); Brown et al. (2020); Raffel et al. (2020); Schick and Sch¨utze (2021b); Gao et al. (2021)). The advantage of this method is that, given a suite of appropriate prompts, a single LM trained in an entirely unsupervised fashion can be used to solve a great number of tasks (Brown et al., 2020; Sun et al., 2021). However, as with most conceptually enticing prospects, there is a catch – this method introduces the necessity for prompt engineering, finding the most appropriate prompt to allow a LM to solve the task at hand. This survey attempts to organize the current state of knowledge in this rapidly developing field by providing an overview and formal definition of prompting methods (§2), and an overview of the pre-trained language models that use these prompts (§3). This is followed by in-depth discussion of prompting methods, from basics such as prompt engineering (§4) and answer engineering (§5) to more advanced concepts such as multi-prompt learning methods (§6) and prompt-aware training methods (§7). We then organize the various applications to which prompt-based learning methods have been applied, and discuss how they interact with the choice of prompting method (§8). Finally, we attempt to situate the current state of prompting methods in the research ecosystem, making connections to other research fields (§9), suggesting some current challenging problems that may be ripe for further research (§10), and performing a meta-analysis of current research trends (§11). Finally, in order to help beginners who are interested in this field learn more effectively, we highlight some systematic resources about prompt learning (as well as pre-training) provided both within this survey and on companion websites: 2 : A website of prompt-based learning that contains: frequent updates to this survey, related slides, etc. • Fig.1: A typology of important concepts for prompt-based learning. 1Even during this stage, there was some use of pre-trained models exemplified by word2vec (Mikolov et al., 2013b,a) and GloVe (Pennington et al., 2014), but they were used for only a limited portion of the final model parameters. 2This paradigm is less conducive to architectural exploration because (i) unsupervised pre-training allows models to learn with fewer structural priors, and (ii) as pre-training of models is time-consuming, experimenting with structural variants is costly. 3 Paradigm Engineering Task Relation a. Fully Supervised Learning (Non-Neural Network) Features (e.g. word identity, part-of-speech, sentence length) b. Fully Supervised Learning (Neural Network) Architecture (e.g. convolutional, recurrent, self-attentional) c. Pre-train, Fine-tune Objective (e.g. masked language modeling, next sentence prediction) d. Pre-train, Prompt, Predict Prompt (e.g. cloze, prefix) Table 1: Four paradigms in NLP. The “engineering” column represents the type of engineering to be done to build strong systems. The “task relation” column, shows the relationship between language models (LM) and other NLP tasks (CLS: classification, TAG: sequence tagging, GEN: text generation). : fully indicates a textual prompt. supervised training. : Supervised training combined with unsupervised training. Task” Dashed lines suggest that different tasks can be connected by sharing parameters of pre-trained models. “LM represents adapting LMs (objectives) to downstream tasks while “Task LM” denotes adapting downstream tasks (formulations) to LMs. Tab.7: A systematic and comprehensive comparison among different prompting methods. • Tab.10: An organization of commonly-used prompts. • Tab.12: A timeline of prompt-based research works. • Tab.13: A systematic and comprehensive comparison among different pre-trained LMs. # 2 A Formal Description of Prompting # 2.1 Supervised Learning in NLP In a traditional supervised learning system for NLP, we take an input x, usually text, and predict an output y based on a model P (y x; θ). y could be a label, text, or other variety of output. In order to learn the parameters θ of | this model, we use a dataset containing pairs of inputs and outputs, and train a model to predict this conditional probability. We will illustrate this with two stereotypical examples. . To give an example, sentiment analysis (Pang et al., 2002; Socher et al., 2013) may take an input x =“I love this movie.” and predict a label y = ++, out of a label set ++, +, ~, -, -- } { # Y Second, conditional text generation takes an input x and generates another text y. One example is machine translation (Koehn, 2009), where the input is text in one language such as the Finnish x = “Hyv¨a¨a huomenta.” and the output is the English y = “Good morning”.. # 2.2 Prompting Basics x; θ), it is necessary to have supervised The main issue with supervised learning is that in order to train a model P (y data for the task, which for many tasks cannot be found in large amounts. Prompt-based learning methods for NLP attempt to circumvent this issue by instead learning an LM that models the probability P (x; θ) of text x itself (details in §3) and using this probability to predict y, reducing or obviating the need for large supervised datasets. In this section we lay out a mathematical description of the most fundamental form of prompting, which encompasses many works on prompting and can be expanded to cover others as well. Specifically, basic prompting predicts the highest-scoring ˆy in three steps. 4 2.2 Prompting Basics Name Notation Example Description Input x IT love this movie. One or multiple texts Output y ++ (very positive) Output label or text A function that converts the input into a Prompting Ml tteune « . specific form by inserting the input a and Function Fprompt (a) (X] Overall, it was a [2] movie. adding a slot [2] where answer z may be filled later. Prompt a’ T love this movie. Overall, it was a [Z] movie. A text where [X] is instantiated by input a but answer slot [Z] is not. A prompt where slot [Z] is filled with Filled Prompt fan(x’, z) T love this movie. Overall, it was a bad movie. any answer. Answered fan(x’, z*) — Llove this movie. Overall, it was a good movie. A prompt where slot [2] is filled with a Prompt true answer. Answer z “good”, “fantastic”, “boring” A token, phrase, or sentence that fills [Z] Table 2: Terminology and notation of prompting methods. z∗ represents answers that correspond to true output y∗. 2.2.1 Prompt Addition In this step a prompting function fprompt(-) is applied to modify the input text x into a prompt x! = fpromp:(x). In the majority of previous work (Kumar et al., 2016; McCann et al., 2018; Radford et al., 2019; Schick and Schiitze, 202 1a), this function consists of a two step process: 1. Apply a template, which is a textual string that has two slots: an input slot [X] for input x and an answer slot [Z] for an intermediate generated answer text z that will later be mapped into y. 2. Fill slot [X] with the input text x. In the case of sentiment analysis where x =“ love this movie.”, the template may take a form such as “[X] Overall, it was a [Z] movie.”. Then, x’ would become “I love this movie. Overall it was a [Z] movie.” given the previous example. In the case of machine translation, the template may take a form such as “Finnish: [X] English: {Z]”, where the text of the input and answer are connected together with headers indicating the language. We show more examples in Tab. 3 Notably, (1) the prompts above will have an empty slot to fill in for z, either in the middle of the prompt or at the end. In the following text, we will refer to the first variety of prompt with a slot to fill in the middle of the text as a cloze prompt, and the second variety of prompt where the input text comes entirely before z as a prefix prompt. (2) In many cases these template words are not necessarily composed of natural language tokens; they could be virtual words (e.g. represented by numeric ids) which would be embedded in a continuous space later, and some prompting methods even generate continuous vectors directly (more in §4.3.2). (3) The number of [X] slots and the number of [Z] slots can be flexibly changed for the need of tasks at hand. 2.2.2 Answer Search Next, we search for the highest-scoring text ˆz that maximizes the score of the LM. We first define as a set of permissible values for z. could range from the entirety of the language in the case of generative tasks, or could be a small subset of the words in the language in the case of classification, such as defining Z Z to represent each of the classes in = . ++, +, ~, -, -- } { Z = {“excellent”, “good”, “OK”, “bad”, “horrible’”} to represent each of the classes in Y = {++,+, ~,-,--}. We then define a function f(a’, z) that fills in the location [Z] in prompt a’ with the potential answer z. We will call any prompt that has gone through this process as a filled prompt. Particularly, if the prompt is filled with a true answer, we will refer to it as an answered prompt (Tab. 2 shows an example). Finally, we search over the set of potential answers z by calculating the probability of their corresponding filled prompts using a pre-trained LM P(:6) & = search P( fgu(x’, z); 0). (1) # “excellent”, “good”, “OK”, “bad”, “horrible” } { # Z # Y & = search P( fgu(x’, z); 0). (1) 2eZ This search function could be an argmax search that searches for the highest-scoring output, or sampling that randomly generates outputs following the probability distribution of the LM. 2.2.3 Answer Mapping Finally, we would like to go from the highest-scoring answer ˆz to the highest-scoring output ˆy. This is trivial in some cases, where the answer itself is the output (as in language generation tasks such as translation), but there 5 2.3 Design Considerations for Prompting Type Task Input ([X]) Template Answer ([Z]) Sentiment I love this movie. [X] The movie is [Z]. great fantastic ... Text CLS Topics He prompted the LM. [X] The text is about [Z]. sports science ... Intention What is taxi fare to Denver? [X] The question is about [Z]. quantity city ... Text-span CLS Aspect Sentiment Poor service but good food. [X] What about service? [Z]. Bad Terrible ... Text-pair CLS NLI [X1]: An old man with ... [X2]: A man walks ... [X1]? [Z], [X2] Yes No ... Tagging NER [X1]: Mike went to Paris. [X2]: Paris [X1][X2] is a [Z] entity. organization location ... Text Generation Summarization Las Vegas police ... [X] TL;DR: [Z] The victim ... A woman ... ... Translation Je vous aime. French: [X] English: [Z] I love you. I fancy you. ... Table 3: Examples of input, template, and answer for different tasks. In the Type column, “CLS” is an abbreviation for “classification”. In the Task column, “NLI” and “NER” are abbreviations for “natural language inference” (Bow- man et al., 2015) and “named entity recognition” (Tjong Kim Sang and De Meulder, 2003) respectively. are also other cases where multiple answers could result in the same output. For example, one may use multiple different sentiment-bearing words (e.g. “excellent”, “fabulous”, “wonderful”) to represent a single class (e.g. “++”), in which case it is necessary to have a mapping between the searched answer and the output value. # 2.3 Design Considerations for Prompting Now that we have our basic mathematical formulation, we elaborate a few of the basic design considerations that go into a prompting method, which we will elaborate in the following sections: • Pre-trained Model Choice: There are a wide variety of pre-trained LMs that could be used to calculate P (x; θ). In §3 we give a primer on pre-trained LMs, specifically from the dimensions that are important for interpreting their utility in prompting methods. • Prompt Engineering: Given that the prompt specifies the task, choosing a proper prompt has a large effect not only on the accuracy, but also on which task the model performs in the first place. In §4 we discuss methods to choose which prompt we should use as fprompt(x). • Answer Engineering: Depending on the task, we may want to design mapping function. In §5 we discuss different ways to do so. Z differently, possibly along with the • Expanding the Paradigm: As stated above, the above equations represent only the simplest of the various underlying frameworks that have been proposed to do this variety of prompting. In §6 we discuss ways to expand this underlying paradigm to further improve results or applicability. • Prompt-based Training Strategies: There are also methods to train parameters, either of the prompt, the LM, or both. In §7, we summarize different strategies and detail their relative advantages. 6 2.3 Design Considerations for Prompting Left-to- Right LM GPT [139]; GPT-2 [140]; GPT-3 [16] Pre-trained Models §3 Masked LM BERT [32]; RoBERTa [105] Prefix LM UniLM1 [35]; UniLM2 [6] Encoder- Decoder T5 [141]; MASS [162]; BART [94] Prompt En- gineering §4 Shape Cloze LAMA [133]; TemplateNER [29] Prefix Prefix-Tuning [96]; PromptTuning [91] Human Effort Hand-crafted LAMA [133]; GPT-3 [16] Automated Discrete AdvTrigger [177]; AutoPrompt [159] Continuous Prefix-Tuning [96]; PromptTuning [91] Token LAMA [133]; WARP [55] Answer En- gineering §5 Shape Span PET-GLUE [154]; X-FACTR [66] Sentence GPT-3 [16]; Prefix-Tuning [96] Human Effort Hand-crafted PET-TC [153]; PET-GLUE [154] Automated Discrete AutoPrompt [159]; LM-BFF [46] Continuous WARP [55] Prompt Ensemble LPAQA [68]; PET- TC [153]; BARTScore [193] Prompt Augmentation GPT-3 [16]; KATE [100]; LM-BFF [46] Multi-Prompt Learning §6 Prompt Composition PTR [56] Prompt De- composition TemplateNER [29] Prompt Sharing Example Fig. 5 Promptless Fine-tuning BERT [32]; RoBERTa [105] Tuning-free Prompting GPT-3 [16]; BARTScore [193] # Prompting Method # Prompt-based Training Strategies §7 # Parameter Updating # Fixed-LM Prompt Tuning # Prefix-Tuning [96]; WARP [55] # Fixed-prompt LM Tuning T5 [141]; PET-TC [154] ——— # Prompt+LM Tuning P-Tuning [103]; PTR [56] # Training Sample Size # Few/zero- shot GPT-3 [16]; PET-TC [153] # Full-data PTR [56]; AdaPrompt [21] Figure 1: Typology of prompting methods. 7 # 3 Pre-trained Language Models Given the large impact that pre-trained LMs have had on NLP in the pre-train and fine-tune paradigm, there are already a number of high-quality surveys that interested readers where interested readers can learn more (Raffel et al., 2020; Qiu et al., 2020; Xu et al., 2021; Doddapaneni et al., 2021). Nonetheless, in this chapter we present a systematic view of various pre-trained LMs which (i) organizes them along various axes in a more systematic way, (ii) particularly focuses on aspects salient to prompting methods. Below, we will detail them through the lens of main training objective, type of text noising, auxiliary training objective, attention mask, typical architecture, and preferred application scenarios. We describe each of these objectives below, and also summarize a number of pre-trained LMs along each of these axes in Tab. 13 in the appendix. # 3.1 Training Objectives The main training objective of a pre-trained LM almost invariably consists of some sort of objective predicting the probability of text x. Standard Language Model (SLM) objectives do precisely this, training the model to optimize the probability P (x) of text from a training corpus (Radford et al., 2019). In these cases, the text is generally predicted in an autoregressive fashion, predicting the tokens in the sequence one at a time. This is usually done from left to right (as detailed below), but can be done in other orders as well. A popular alternative to standard LM objectives are denoising objectives, which apply some noising function ˜x = fnoise(x) to the input sentence (details in the following subsection), then try to predict the original input sentence given this noised text P (x ˜x). There are two common flavors of these objectives: | Corrupted Text Reconstruction (CTR) These objectives restore the processed text to its uncorrupted state by calculating loss over only the noised parts of the input sentence. Full Text Reconstruction (FTR) These objectives reconstruct the text by calculating the loss over the entirety of the input texts whether it has been noised or not (Lewis et al., 2020a). The main training objective of the pre-trained LMs plays an important role in determining its applicability to particular prompting tasks. For example, left-to-right autoregressive LMs may be particularly suitable for prefix prompts, whereas reconstruction objectives may be more suitable for cloze prompts. In addition, models trained with standard LM and FTR objectives may be more suitable for tasks regarding text generation, whereas other tasks such as classification can be formulated using models trained with any of these objectives. In addition to the main training objectives above, a number of auxiliary objectives have been engineered to further improve models’ ability to perform certain varieties of downstream tasks. We list some commonly-used auxiliary objectives in Appendix A.2. # 3.2 Noising Functions In training objectives based on reconstruction, the specific type of corruption applied to obtain the noised text ˜x has an effect on the efficacy of the learning algorithm. In addition, prior knowledge can be incorporated by controlling the type of noise, e.g. the noise could focus on entities of a sentence, which allows us to learn a pre-trained model with particularly high predictive performance for entities. In the following, we introduce several types of noising functions, and give detailed examples in Tab. 4. Operation Element Original Text Corrupted Text Mask one token two tokens one entity Jane will move to New York . Jane will move to New York . Jane will move to New York . Jane will [Z] to New York . Jane will [Z] [Z] New York . Jane will move to [Z] . Replace one token two tokens one entity Jane will move to New York . Jane will move to New York . Jane will move to New York . Jane will move [X] New York . Jane will move [X] [Y] York . Jane will move to [X] . Delete one token two token Jane will move to New York . Jane will move to New York . Jane move to New York . Jane to New York . Permute Rotate Concatenation token none two languages Jane will move to New York . New York . Jane will move to to New York . Jane will move Jane will move to New York . Jane will move to New York . [/s] 简将搬到纽约。 Jane will move to New York . Table 4: Detailed examples for different noising operations. 8 3.3 Directionality of Representations Masking (e.g. Devlin et al. (2019)) The text will be masked in different levels, replacing a token or multi-token span with a special token such as [MASK]. Notably, masking can either be random from some distribution or specifically designed to introduce prior knowledge, such as the above-mentioned example of masking entities to encourage the model to be good at predicting entities. Replacement (e.g. Raffel et al. (2020)) Replacement is similar to masking, except that the token or multi-token span is not replaced with a [MASK] but rather another token or piece of information (e.g., an image region (Su et al., 2020)). Deletion (e.g. Lewis et al. (2020a)) Tokens or multi-token spans will be deleted from a text without the addition of [MASK] or any other token. This operation is usually used together with the FTR loss. Permutation (e.g. Liu et al. (2020a)) The text is first divided into different spans (tokens, sub-sentential spans, or sentences), and then these spans are be permuted into a new text. # 3.3 Directionality of Representations A final important factor that should be considered in understanding pre-trained LMs and the difference between them is the directionality of the calculation of representations. In general, there are two widely used ways to calculate such representations: Left-to-Right The representation of each word is calculated based on the word itself and all previous words in the sentence. For example, if we have a sentence “This is a good movie”, the representation of the word “good” would be calculated based on previous words. This variety of factorization is particularly widely used when calculating standard LM objectives or when calculating the output side of an FTR objective, as we discuss in more detail below. Bidirectional The representation of each word is calculated based on all words in the sentence, including words to the left of the current word. In the example above, “good” would be influenced by all words in the sentence, even the following “movie”. In addition to the two most common directionalities above, it is also possible to mix the two strategies together in a single model (Dong et al., 2019; Bao et al., 2020), or perform conditioning of the representations in a randomly permuted order (Yang et al., 2019), although these strategies are less widely used. Notably, when implementing these strategies within a neural model, this conditioning is generally implemented through attention masking, which masks out the values in an attentional model (Bahdanau et al., 2014), such as the popular Transformer architecture (Vaswani et al., 2017). Some examples of such attention masks are shown in Figure 2. (a) Full. (b) Diagonal. (c) Mixture. Figure 2: Three popular attention mask patterns, where the subscript t indicates the t-th timestep. A shaded box at (i, j) indicates that the attention mechanism is allowed to attend to the input element i at output time step j. A white box indicates that the attention mechanism is not allowed to attend to the corresponding i and j combination. # 3.4 Typical Pre-training Methods With the above concepts in mind, we introduce four popular pre-training methods, resulting from diverse combina- tions of objective, noising function, and directionality. These are described below, and summarized in Fig. 3 and Tab. 5. 3.4.1 Left-to-Right Language Model Left-to-right LMs (L2R LMs), a variety of auto-regressive LM, predict the upcoming words or assign a probability P (x) to a sequence of words x = x1, , xn (Jurafsky and Martin, 2021). The probability is commonly broken down using the chain rule in a left-to-right fashion: P (x) = P (x1) x1 · · · | × · · · 3Similarly, a right-to-left LM can predict preceding words based on the future context, such as P (xi|xi+1, · · · , xn). 9 3.4 Typical Pre-training Methods (a) Left-to-right LM. (b) Masked LM. (c) Prefix LM. (d) Encoder-Decoder. Figure 3: Typical paradigms of pre-trained LMs. # Example & Applicable Scenario Left-to-right LMs have been standard since their proposal by Markov in 1913 (Markov, 2006), and have been used continuously since then in both count-based (Goodman, 2001) and neural forms (Bengio et al., 2003; Mikolov et al., 2010; Radford and Narasimhan, 2018). Representative examples of modern pre-trained left-to-right LMs include GPT-3 (Brown et al., 2020), and GPT-Neo (Black et al., 2021). L2R pre-trained LMs are also the popular backbone that many prompting methods adopt (Radford et al., 2019; Brown et al., 2020) . One practical reason for this is that many such models are large (PanGu-α (Zeng et al., 2021), Ernie-3 (Sun et al., 2021)) and ponderous to train, or not even available publicly. Thus using these models in the pre-train and fine-tune regimen is often not possible. LMs Mask x Noise Main Obj. Mask y Noise Main Obj. Application L2R Mask Prefix En-De Diagonal None Mask Any Any Full Full Full SLM CTR CTR None† - - - - Diagonal None Diagonal None - - SLM FTR/CRT NLU & NLG NLU NLU & NLG NLU & NLG Table 5: Typical architectures for pre-trained LMs. x and y represent text to be encoded and decoded, respectively. SLM: Standard language model. CTR: Corrupted text reconstruction. FTR: Full text reconstruction. : Encoder- † decoder architectures usually apply objective functions to the decoder only. 3.4.2 Masked Language Models While autoregressive language models provide a powerful tool for modeling the probability of text, they also have disadvantages such as requiring representations be calculated from left-to-right. When the focus is shifted to generating the optimal representations for down-stream tasks such as classification, many other options become possible, and often preferable. One popular bidirectional objective function used widely in representation learning is the masked language model (MLM; Devlin et al. (2019)), which aims to predict masked text pieces based on x1, . . . , xi−1, xi+1, . . . , xn) represents the probability of the word xi given surrounded context. For example, P (xi | the surrounding context. # Example & Applicable Scenario Representative pre-trained models using MLMs include: BERT (Devlin et al., 2019), ERNIE (Zhang et al., 2019; Sun et al., 2019b) and many variants. In prompting methods, MLMs are generally most suitable for natural language understanding or analysis tasks (e.g., text classification, natural language inference , and extractive question answering). These tasks are often relatively easy to be reformulated into cloze problems, which are consistent with the training objectives of the MLM. Additionally, MLMs have been a pre-trained model of choice when exploring methods that combine prompting with fine-tuning, elaborated further in §7. 3.4.3 Prefix and Encoder-Decoder For conditional text generation tasks such as translation and summarization where an input text x = x1, , xn is given and the goal is to generate target text y, we need a pre-trained model that is both capable of encoding the input text and generating the output text. There are two popular architectures for this purpose that share a common 10 thread of (1) using an encoder with fully-connected mask to encode the source x first and then (2) decode the target y auto-regressively (from the left to right). Prefix Language Model The prefix LM is a left-to-right LM that decodes y conditioned on a prefixed sequence x, which is encoded by the same model parameters but with a fully-connected mask. Notably, to encourage the prefix LM to learn better representations of the input, a corrupted text reconstruction objective is usually applied over x, in addition to a standard conditional language modeling objective over y. Encoder-decoder The encoder-decoder model is a model that uses a left-to-right LM to decode y conditioned on a separate encoder for text x with a fully-connected mask; the parameters of the encoder and decoder are not shared. Similarly to the prefix LM, diverse types of noising can be applied to the input x. # Example & Applicable Scenario Prefix LMs have been explored in UniLM 1-2 (Dong et al., 2019; Bao et al., 2020) and ERNIE-M (Ouyang et al., 2020) while encoder-decoder models are widely used in pre-trained models such as T5 (Raffel et al., 2020), BART (Lewis et al., 2020a), MASS (Song et al., 2019) and their variants. Pre-trained models with prefix LMs and encoder-decoder paradigms can be naturally used to text generation tasks with (Dou et al., 2021) or without (Yuan et al., 2021a; Liu and Liu, 2021) prompting using input texts. However, recent studies reveal that other non-generation tasks, such as information extraction (Cui et al., 2021), question answering (Khashabi et al., 2020) , and text generation evaluation (Yuan et al., 2021b) can be reformulated a generation problems by providing appropriate prompts. Therefore, prompting methods (i) broaden the applicability of these generation-oriented pre-trained models. For example, pre-trained models like BART are less used in NER while prompting methods make BART applicable, and (ii) breaks the difficulty of unified modelling among different tasks (Khashabi et al., 2020). # 4 Prompt Engineering Prompt engineering is the process of creating a prompting function fprompt(x) that results in the most effective performance on the downstream task. In many previous works, this has involved prompt template engineering, where a human engineer or algorithm searches for the best template for each task the model is expected to perform. As shown in the “Prompt Engineering” section of Fig.1, one must first consider the prompt shape, and then decide whether to take a manual or automated approach to create prompts of the desired shape, as detailed below. # 4.1 Prompt Shape As noted above, there are two main varieties of prompts: cloze prompts (Petroni et al., 2019; Cui et al., 2021), which fill in the blanks of a textual string, and prefix prompts (Li and Liang, 2021; Lester et al., 2021), which continue a string prefix. Which one is chosen will depend both on the task and the model that is being used to solve the task. In general, for tasks regarding generation, or tasks being solved using a standard auto-regressive LM, prefix prompts tend to be more conducive, as they mesh well with the left-to-right nature of the model. For tasks that are solved using masked LMs, cloze prompts are a good fit, as they very closely match the form of the pre-training task. Full text reconstruction models are more versatile, and can be used with either cloze or prefix prompts. Finally, for some tasks regarding multiple inputs such as text pair classification, prompt templates must contain space for two inputs, [X1] and [X2], or more. # 4.2 Manual Template Engineering Perhaps the most natural way to create prompts is to manually create intuitive templates based on human introspec- tion. For example, the seminal LAMA dataset (Petroni et al., 2019) provides manually created cloze templates to probe knowledge in LMs. Brown et al. (2020) create manually crafted prefix prompts to handle a wide variety of tasks, including question answering, translation, and probing tasks for common sense reasoning. Schick and Sch¨utze (2020, 2021a,b) use pre-defined templates in a few-shot learning setting on text classification and conditional text generation tasks. # 4.3 Automated Template Learning While the strategy of manually crafting templates is intuitive and does allow solving various tasks with some degree of accuracy, there are also several issues with this approach: (1) creating and experimenting with these prompts is an art that takes time and experience, particularly for some complicated tasks such as semantic parsing (Shin et al., 2021); (2) even experienced prompt designers may fail to manually discover optimal prompts (Jiang et al., 2020c). To address these problems, a number of methods have been proposed to automate the template design process. In particular, the automatically induced prompts can be further separated into discrete prompts, where the prompt is an 11 4.3 Automated Template Learning actual text string, and continuous prompts, where the prompt is instead described directly in the embedding space of the underlying LM. One other orthogonal design consideration is whether the prompting function fprompt(x) is static, using essentially the same prompt template for each input, or dynamic, generating a custom template for each input. Both static and dynamic strategies have been used for different varieties of discrete and continuous prompts, as we will mention below. 4.3.1 Discrete Prompts Works on discovering discrete prompts (a.k.a hard prompts) automatically search for templates described in a discrete space, usually corresponding to natural language phrases. We detail several methods that have been proposed for this below: D1: Prompt Mining Jiang et al. (2020c)’s MINE approach is a mining-based method to automatically find templates given a set of training inputs x and outputs y. This method scrapes a large text corpus (e.g. Wikipedia) for strings containing x and y, and finds either the middle words or dependency paths between the inputs and outputs. Frequent middle words or dependency paths can serve as a template as in “[X] middle words [Z]”. D2: Prompt Paraphrasing Paraphrasing-based approaches take in an existing seed prompt (e.g. manually constructed or mined), and paraphrases it into a set of other candidate prompts, then selects the one that achieves the highest training accuracy on the target task. This paraphrasing can be done in a number of ways, including using round-trip translation of the prompt into another language then back (Jiang et al., 2020c), using replacement of phrases from a thesaurus (Yuan et al., 2021b), or using a neural prompt rewriter specifically optimized to improve accuracy of systems using the prompt (Haviv et al., 2021). Notably, Haviv et al. (2021) perform paraphrasing after the input x is input into the prompt template, allowing a different paraphrase to be generated for each individual input. D3: Gradient-based Search Wallace et al. (2019a) applied a gradient-based search over actual tokens to find short sequences that can trigger the underlying pre-trained LM to generate the desired target prediction. This search is done in an iterative fashion, stepping through tokens in the prompt . Built upon this method, Shin et al. (2020) automatically search for template tokens using downstream application training samples and demonstrates strong performance in prompting scenarios. D4: Prompt Generation Other works treat the generation of prompts as a text generation task and use standard natural language generation models to perform this task. For example, Gao et al. (2021) introduce the seq2seq pre-trained model T5 into the template search process. Since T5 has been pre-trained on a task of filling in missing spans, they use T5 to generate template tokens by (1) specifying the position to insert template tokens within a template4 (2) provide training samples for T5 to decode template tokens. Ben-David et al. (2021) propose a domain adaptation algorithm that trains T5 to generate unique domain relevant features (DRFs; a set of keywords that characterize domain information) for each input. Then those DRFs can be concatenated with the input to form a template and be further used by downstream tasks. D5: Prompt Scoring Davison et al. (2019) investigate the task of knowledge base completion and design a template for an input (head-relation-tail triple) using LMs. They first hand-craft a set of templates as potential candidates, and fill the input and answer slots to form a filled prompt. They then use a unidirectional LM to score those filled prompts, selecting the one with the highest LM probability. This will result in custom template for each individual input. 4.3.2 Continuous Prompts Because the purpose of prompt construction is to find a method that allows an LM to effectively perform a task, rather than being for human consumption, it is not necessary to limit the prompt to human-interpretable natural language. Because of this, there are also methods that examine continuous prompts (a.k.a. soft prompts) that perform prompting directly in the embedding space of the model. Specifically, continuous prompts remove two constraints: (1) relax the constraint that the embeddings of template words be the embeddings of natural language (e.g., English) words. (2) Remove the restriction that the template is parameterized by the pre-trained LM’s parameters. Instead, templates have their own parameters that can be tuned based on training data from the downstream task. We highlight several representative methods below. 4The number of template tokens do not need to be pre-specified since T5 can decode multiple tokens at a masked position. 12 C1: Prefix Tuning Prefix Tuning (Li and Liang, 2021) is a method that prepends a sequence of continuous task-specific vectors to the input, while keeping the LM parameters frozen. Mathematically, this consists of optimizing over the following log-likelihood objective given a trainable prefix matrix Mφ and a fixed pre-trained LM parameterized by θ. max log P(y|x; 0; ¢) = max S> log P(yi|h.<i; 0; ¢) (2) ° aT ; h(n) In Eq. 2, h<i = [h(1) <i ] is the concatenation of all neural network layers at time step i. It is copied from <i ; Mφ directly if the corresponding time step is within the prefix (hi is Mφ[i]), otherwise it is computed using the pre-trained LM. Experimentally, Li and Liang (2021) observe that such continuous prefix-based learning is more sensitive to different initialization in low-data settings than the use of discrete prompts with real words. Similarly, Lester et al. (2021) prepend the input sequence with special tokens to form a template and tune the embeddings of these tokens directly. Compared to Li and Liang (2021)’s method, this adds fewer parameters as it doesn’t introduce additional tunable parameters within each network layer. Tsimpoukelli et al. (2021) train a vision encoder that encodes an image into a sequence of embeddings that can be used to prompt a frozen auto-regressive LM to generate the appropriate caption. They show that the resulting model can perform few-shot learning for vision-language tasks such as visual question answering etc. Different from the above two works, the prefix used in (Tsimpoukelli et al., 2021) is sample-dependent, namely a representation of input images, instead of a task embedding. C2: Tuning Initialized with Discrete Prompts There are also methods that initialize the search for a continuous prompt using a prompt that has already been created or discovered using discrete prompt search methods. For example, Zhong et al. (2021b) first define a template using a discrete search method such as AUTOPROMPT (Shin et al., 2020)’s, initialize virtual tokens based on this discovered prompt, then fine-tune the embeddings to increase task accuracy. This work found that initializing with manual templates can provide a better starting point for the search process. Qin and Eisner (2021) propose to learn a mixture of soft templates for each input where the weights and parameters for each template are jointly learned using training samples. The initial set of templates they use are either manually crafted ones or those obtained using the “prompt mining” method. Similarly, Hambardzumyan et al. (2021) introduce the use of a continuous template whose shape follows a manual prompt template. C3: Hard-Soft Prompt Hybrid Tuning Instead of using a purely learnable prompt template, these methods insert some tunable embeddings into a hard prompt template. Liu et al. (2021b) propose “P-tuning”, where continuous prompts are learned by inserting trainable variables into the embedded input. To account for interaction between prompt tokens, they represent prompt embeddings as the output of a BiLSTM (Graves et al., 2013). P-tuning also introduces the use of task-related anchor tokens (such as “capital” in relation extraction) within the template for further improvement. These anchor tokens are not tuned during training. Han et al. (2021) propose prompt tuning with rules (PTR), which uses manually crafted sub-templates to compose a complete template using logic rules. To enhance the representation ability of the resulting template, they also insert several virtual tokens whose embeddings can be tuned together with the pre-trained LMs parameters using training samples. The template tokens in PTR contain both actual tokens and virtual tokens. Experiment results demonstrate the effectiveness of this prompt design method in relation classification tasks. # 5 Answer Engineering In contrast to prompt engineering, which designs appropriate inputs for prompting methods, answer engineering aims to search for an answer space that results in an effective predictive model. Fig.1’s “Answer Engineering” section illustrates two dimensions that must be considered when performing answer engineering: deciding the answer shape and choosing an answer design method. # 5.1 Answer Shape The shape of an answer characterizes its granularity. Some common choices include: • Tokens: One of the tokens in the pre-trained LM’s vocabulary, or a subset of the vocabulary. • Span: A short multi-token span. These are usually used together with cloze prompts. • Sentence: A sentence or document. These are commonly used with prefix prompts. In practice, how to choose the shape of acceptable answers depends on the task we want to perform. Token or text-span answer spaces are widely used in classification tasks (e.g. sentiment classification; Yin et al. (2019)), but also other tasks such as relation extraction (Petroni et al., 2019) or named entity recognition (Cui et al., 2021). Longer phrasal or sentential answers are often used in language generation tasks (Radford et al., 2019), but also 13 5.2 Answer Space Design Methods used in other tasks such as multiple-choice question answering (where the scores of multiple phrases are compared against each-other; Khashabi et al. (2020)). # 5.2 Answer Space Design Methods The next question to answer is how to design the appropriate answer space space if the answers are not used as the final outputs. Z , as well as the mapping to the output # Y 5.2.1 Manual Design In manual design, the space of potential answers Z system or benchmark designer. There are a number of strategies that can be taken to perform this design. # interested Unconstrained Spaces is the space of all tokens (Petroni et al., 2019), fixed-length spans (Jiang et al., 2020a), or token sequences (Radford et al., 2019). In these cases, it is most common to directly map answer z to the final output y using the identity mapping. Constrained Spaces However, there are also cases where the space of possible outputs is constrained. This is often performed for tasks with a limited label space such as text classification or entity recognition, or multiple- choice question answering. To give some examples, Yin et al. (2019) manually design lists of words relating to relevant topics (“health”, “finance”, “politics”, “sports”, etc.), emotions (“anger”, “joy”, “sadness”, “fear”, etc.), or other aspects of the input text to be classified. Cui et al. (2021) manually design lists such as “person”, “location”, and the underlying class etc. for NER tasks. In these cases, it is necessary to have a mapping between the answer . With regards to multiple-choice question answering, it is common to use an LM to calculate the probability of an # Y output among multiple choices, with Zweig et al. (2012) being an early example. 5.2.2 Discrete Answer Search As with manually created prompts, it is possible that manually created answers are sub-optimal for getting the LM to achieve ideal prediction performance. Because of this, there is some work on automatic answer search, albeit less than that on searching for ideal prompts. These work on both discrete answer spaces (this section) and continuous answer spaces (the following). Answer Paraphrasing These methods start with an initial answer space Z’, and then use paraphrasing to expand this answer space to broaden its coverage (Jiang et al., 2020b). Given a pair of answer and output (z’, y), we define a function that generates a paraphrased set of answers para(z’). The probability of the final output is then defined as the marginal probability all of the answers in this paraphrase set P(y|a) = Ye zepara(z”) P(z\x). This paraphrasing can be performed using any method, but Jiang et al. (2020b) specifically use a back-translation method, first translating into another language then back to generate a list of multiple paraphrased answers. Prune-then-Search In these methods, first, an initial pruned answer space of several plausible answers 2’ is generated, and then an algorithm further searches over this pruned space to select a final set of answers. Note that in some of the papers introduced below, they define a function from label y to a single answer token z, which is often called a verbalizer (Schick and Schiitze, 2021a). Schick and Schiitze (2021a); Schick et al. (2020) find tokens containing at least two alphabetic characters that are frequent in a large unlabeled dataset. In the search step, they iteratively compute a word’s suitability as a representative answer z for a label y by maximizing the likelihood of the label over training data. Shin et al. (2020) learn a logistic classifier using the contextualized representation of the [Z] token as input. In the search step, they select the top-k tokens that achieve the highest probability score using the learned logistic classifier in the first step. Those selected tokens will form the answer. Gao et al. (2021) first construct a pruned search space Z’ by selecting top-k vocabulary words based on their generation probability at the [Z] position determined by training samples. Then the search space is further pruned down by only selecting a subset of words within 2’ based on their zero-shot accuracy on the training samples. (2) In the search step, they fine-tune the LM with fixed templates together with every answer mapping using training data and select the best label word as the answer based on the accuracy on the development set. Label Decomposition When performing relation extraction, Chen et al. (2021b) automatically decompose each re- lation label into its constituent words and use them as an answer. For example, for the relation per:city of death, the decomposed label words would be calculated as the sum of each token’s probability. 5.2.3 Continuous Answer Search Very few works explore the possibility of using soft answer tokens which can be optimized through gradient descent. Hambardzumyan et al. (2021) assign a virtual token for each class label and optimize the token embedding for each 14 (a) Prompt Ensembling. (b) Prompt Augmentation. (c) Prompt Composition. (d) Prompt Decomposition. > --> Figure 4: Different multi-prompt learning strategies. We use different colors to differentiate different components as follows. “ ” for sub-prompt. We use the following abbreviations. “PR” for prompt, “Ans-PR” for answered prompt, “Sub-PR” for sub-prompt. class together with prompt token embeddings. Since the answer tokens are optimized directly in the embedding space, they do not make use of the embeddings learned by the LM and instead learn an embedding from scratch for each label. # 6 Multi-Prompt Learning The prompt engineering methods we discussed so far focused mainly on constructing a single prompt for an input. However, a significant body of research has demonstrated that the use of multiple prompts can further improve the efficacy of prompting methods, and we will call these methods multi-prompt learning methods. In practice, there are several ways to extend the single prompt learning to the use multiple prompts, which have a variety of motivations. We summarize representative methods in the “Multi-prompt Learning” section of Fig.1 as well as Fig.4. # 6.1 Prompt Ensembling Prompt ensembling is the process of using multiple unanswered prompts for an input at inference time to make predictions. An example is shown in Fig. 4-(a). The multiple prompts can either be discrete prompts or continuous prompts.5 This sort of prompt ensembling can (1) leverage the complementary advantages of different prompts, (2) alleviate the cost of prompt engineering, since choosing one best-performing prompt is challenging, (3) stabilize performance on downstream tasks. Prompt ensembling is connected to ensembling methods that are used to combine together multiple systems, which have a long history in machine learning (Ting and Witten, 1997; Zhou et al., 2002; Duh et al., 2011). Current research also borrows ideas from these works to derive effective ways for prompt ensembling, as described below. Uniform averaging The most intuitive way to combine the predictions when using multiple prompts is to take the fprompt,i(x)) average of probabilities from different prompts. Concretely, this indicates that P (z where fprompt,i( ) is the ith prompt in the prompt ensemble. Jiang et al. (2020c) first filter their prompts by selecting · K prompts that achieve the highest accuracy on the training set, and then use the average log probabilities obtained from the top K prompts to calculate the probability for a single token at [Z] position when performing factual probing tasks. Schick and Sch¨utze (2021a) also try a simple average when using an ensemble model to annotate an unlabeled dataset. When performing text generation evaluation, Yuan et al. (2021b) formulates this task as a text generation problem and take the average of the final generation scores obtained using different prompts. Weighted averaging Simple uniform averaging of results from multiple prompts is easy to implement, but can also be suboptimal given that some prompts are more performant than others. To account for this, some works also 5Multiple continuous prompts are typically learned by using different initializations or different random seeds. 15 6.2 Prompt Augmentation explore to use of weighted averages for prompt ensembling where each prompt is associated with a weight. The weights are typically pre-specified based on prompt performance or optimized using a training set. For example, Jiang et al. (2020c) learn the weight for each prompt by maximizing the probability of the target output over training data. Qin and Eisner (2021) use the same approach except that the weight for each prompt is optimized together with soft prompt parameters. Besides, Qin and Eisner (2021) also introduce a data-dependent weighting strategy where the probability of the input appearing in that prompt is considered in weighting different prompts as well. Schick and Sch¨utze (2021a,b) set the weight for each prompt proportional to the accuracy on the training set before training. Majority voting For classification tasks, majority voting can also be used to combine the results from different prompts (Lester et al., 2021; Hambardzumyan et al., 2021). Knowledge distillation An ensemble of deep learning models can typically improve the performance, and this superior performance can be distilled into a single model using knowledge distillation (Allen-Zhu and Li, 2020). To incorporate this idea, Schick and Sch¨utze (2021a,b, 2020) train a separate model for each manually-created template-answer pair, and use the ensemble of them to annotate an unlabeled dataset. Then the final model is trained to distill the knowledge from the annotated dataset. Gao et al. (2021) use a similar ensemble method on their automatically generated templates. Prompt ensembling for text generation There is relatively little work on prompt ensembling for generation tasks (i.e. tasks where the answers is a string of tokens instead of a single one). A simple way to perform ensembling in this case is to use standard methods that generate the output based on the ensembled probability of the next word fprompt,i(x), z<t). In contrast, Schick and Sch¨utze (2020) in the answer sequence P (zt | train a separate model for each prompt fprompt,i(x), and thus storing each of these fine-tuned LMs in memory is infeasible. Instead, they first decode generations using each model and then score each generation by averaging their generation probability across all models. # 6.2 Prompt Augmentation Prompt augmentation, also sometimes called demonstration learning (Gao et al., 2021), provides a few additional answered prompts that can be used to demonstrate how the LM should provide the answer to the actual prompt instantiated with the input x. For example, instead of just providing a prompt of “China’s capital is [Z] .”, the prompt can be prefaced by a few examples such as “Great Britain’s capital is London . Japan’s capital is Tokyo . China’s capital is [Z] .” Another example of performing addition of two numbers can be found in Fig. 4-(b). These few-shot demonstrations take advantage of the ability of strong language models to learn repetitive patterns (Brown et al., 2020). Although the idea of prompt augmentation is simple, there are several aspects that make it challenging: (1) Sample Selection: how to choose the most effective examples? (2) Sample Ordering: How to order the chosen examples with the prompt? Sample Selection Researchers have found that the choice of examples used in this few-shot scenario can result in very different performance, ranging from near state-of-the-art accuracy on some tasks to near random guess (Lu et al., 2021). To address this issue, Gao et al. (2021); Liu et al. (2021a) utilize sentence embeddings to sample examples that are close to the input in this embedding space. To measure the generalization capability of pre-trained LMs to perform new tasks based on instructions, Mishra et al. (2021) provide both positive samples and negative samples that highlight things to avoid. Sample Ordering Lu et al. (2021) found that the order of answered prompts provided to the model plays an important role in model performance, and propose entropy-based methods to score different candidate permutations. Kumar and Talukdar (2021) search for a good permutation of training examples as augmented prompts and learn a separator token between the prompts for further gains in performance. Prompt augmentation is closely related to retrieval-based methods that provide more textual context to the model to improve performance (Guu et al., 2018), a method which has also been shown to be effective in prompt-based learning (Petroni et al., 2020). However, the key difference lies in the fact that prompt augmentation also leverages the template and answer, while larger context learning does not. # 6.3 Prompt Composition For those composable tasks, which can be composed based on more fundamental subtasks, we can also perform prompt composition, using multiple sub-prompts, each for one subtask, and then defining a composite prompt based on those sub-prompts. This process is illustrated in Fig. 4-(c). For example, in the relation extraction task, which aims to extract the relation of two entities, we can break down the task into several subtasks including identifying the characteristics of entities and classifying the relationships between entities. Based on this intuition, Han et al. 16 6.4 Prompt Decomposition (2021) first use multiple manually created sub-prompts for entity recognition and relation classification and then compose them into a complete prompt based on logic rules for relation extraction. # 6.4 Prompt Decomposition For tasks where multiple predictions should be performed for one sample (e.g., sequence labeling), directly defining a holistic prompt with regards to the entire input text x is challenging. One intuitive method to address this problem is to break down the holistic prompt into different sub-prompts, and then answer each sub-prompt separately. Fig.4-(d) illustrates this idea with an example from the named entity recognition task, which aims to identify all named entities in an input sentence. In this case, the input will first be converted into a set of text spans, and the model can then be prompted to predict the entity type (including “Not an Entity”) for each span. It is not easy to predict all the span types at the same time due to the large number of spans, so different prompts for each span can be created and predicted separately. This sort of prompt decomposition for named entity recognition has been explored by Cui et al. (2021) where they apply the approach we discussed here. # 7 Training Strategies for Prompting Methods With the methods in the above sections, it is now clear how to obtain an appropriate prompt (or prompts) and corresponding answers. Now we discuss about methods that explicitly train models in concert with prompting methods, as outlined in the “Training Strategies” section of Fig.1. # 7.1 Training Settings In many cases, prompting methods can be used without any explicit training of the LM for the down-stream task, simply taking an LM that has been trained to predict the probability of text P (x) and applying it as-is to fill the cloze or prefix prompts defined to specify the task. This is traditionally called the zero-shot setting, as there is zero training data for the task of interest. However, there are also methods that use training data to train the model in concert with prompting methods. These consist of either full-data learning, where a reasonably large number of training examples are used to train the model, or few-shot learning where a very small number of examples are used to train the model. Prompting methods are particularly useful in the latter case, as there are generally not enough training examples to fully specify the desired behavior, and thus using a prompt to push the model in the right direction is particularly effective. One thing to note is that for many of the prompt engineering methods described in §4, although annotated training samples are not explicitly used in the training of the downstream task model, they are often used in the construction or validation of the prompts that the downstream task will use. As noted by Perez et al. (2021), this is arguably not true zero-shot learning with respect to the downstream task. # 7.2 Parameter Update Methods In prompt-based downstream task learning, there are usually two types of parameters, namely those from (1) pre-trained models and (2) prompts. Which part of parameters should be updated is one important design decision, which can lead to different levels of applicability in different scenarios. We summarize five tuning strategies (as shown in Tab. 6) based on (i) whether the parameters of the underlying LM are tuned, (ii) whether there are additional prompt-related parameters, (iii) if there are additional prompt-related parameters, whether those parameters are tuned. Prompt Params Strategy LM Params ‘Additional Tuned Example Promptless Fine-tuning Tuned - ELMo [130], BERT [32], BART [94] Tuning-free Prompting Frozen xK x GPT-3 [16], AutoPrompt [159], LAMA [133] Fixed-LM Prompt Tuning Frozen v Tuned — Prefix-Tuning [96], Prompt-Tuning [91] Fixed-prompt LM Tuning Tuned xK x PET-TC [153], PET-Gen [152], LM-BFF [46] Prompt+LM Fine-tuning Tuned v Tuned PADA [8], P-Tuning [103], PTR [56] Table 6: Characteristics of different tuning strategies. “Additional” represents if there are additional parameters beyond LM parameters while “Tuned” denotes if parameters are updated. 17 7.2 Parameter Update Methods 7.2.1 Promptless Fine-tuning As mentioned in the introduction, the pre-train and fine-tune strategy has been widely used in NLP since before the popularization of prompting methods. Here we refer to pre-training and fine-tuning without prompts as promptless fine-tuning, to contrast with the prompt-based learning methods introduced in the following sections. In this strategy, given a dataset of a task, all (or some (Howard and Ruder, 2018; Peters et al., 2019)) of the parameters of the pre-trained LM will be updated via gradients induced from downstream training samples. Typical examples of pre-trained models tuned in this way include BERT [32] and RoBERTa [105]. This is a simple, powerful, and widely-used method, but it may overfit or not learn stably on small datasets (Dodge et al., 2020). Models are also prone to catastrophic forgetting, where the LM loses its ability to do things that it was able to do before fine-tuning (McCloskey and Cohen, 1989). • Advantages: Simplicity, no need for prompt design. Tuning all the LM parameters allows the model to fit to larger training datasets. • Disadvantages: LMs may overfit or not learn stably on smaller datasets. 7.2.2 Tuning-free Prompting Tuning-free prompting directly generates the answers without changing the parameters of the pre-trained LMs based only on a prompt, as described in the simplest incarnation of prompting in §2. These can be optionally augmenting input with answered prompts as described in §6.2, and this combination of tuning-free prompting and prompt augmentation is also referred to as in-context learning (Brown et al., 2020). Typical examples of tuning-free prompting include LAMA [133] and GPT-3 [16]. • Advantages: Efficiency, there is no parameter update process. No catastrophic forgetting, as LM parameters remain fixed. Applicable in zero-shot settings. • Disadvantages: Because prompts are the only method that provide the task specification, heavy engi- neering is necessary to achieve high accuracy. In particular in the in-context learning setting, providing many answered prompts can be slow at test time, and thus cannot easily use large training datasets. 7.2.3 Fixed-LM Prompt Tuning In the scenario where additional prompt-relevant parameters are introduced besides parameters of the pre-trained model, fixed-LM prompt tuning updates only the prompts’ parameters using the supervision signal obtained from the downstream training samples, while keeping the entire pre-trained LM unchanged. Typical examples are Prefix-Tuning [96] and WARP [55]. • Advantages: Similarly to tuning-free prompting, it can retain knowledge in LMs and is suitable in few-shot scenarios. Often superior accuracy to tuning-free prompting. • Disadvantages: Not applicable in zero-shot scenarios. While effective in few-shot scenarios, representa- tion power is limited in large-data settings. Prompt engineering through choice of hyperparameters or seed prompts is necessary. Prompts are usually not human-interpretable or manipulable. 7.2.4 Fixed-prompt LM Tuning Fixed-prompt LM tuning tunes the parameters of the LM, as in the standard pre-train and fine-tune paradigm, but additionally uses prompts with fixed parameters to specify the model behavior. This potentially leads to improvements, particularly in few-shot scenarios. The most natural way to do so is to provide a discrete textual template that is applied to every training and test example. Typical examples include PET-TC [153], PET-Gen [152], LM-BFF [46]. Logan IV et al. (2021) more recently observe that the prompt engineering can be reduced by allowing for a combination of answer engineering and partial LM fine-tuning. For example, they define a very simple template, null prompt, where the input and mask are directly concatenated “[X][Z]” without any template words, and find this achieves competitive accuracy. • Advantages: Prompt or answer engineering more completely specify the task, allowing for more efficient learning, particularly in few-shot scenarios. • Disadvantages: Prompt or answer engineering are still required, although perhaps not as much as without prompting. LMs fine-tuned on one downstream task may not be effective on another one. 18 7.2.5 Prompt+LM Tuning In this setting, there are prompt-relevant parameters, which can be fine-tuned together with the all or some of the parameters of the pre-trained models. Representative examples include PADA [8], P-Tuning [103]. Notably, this setting is very similar to the standard pre-train and fine-tune paradigm, but the addition of the prompt can provide additional bootstrapping at the start of model training. Advantages: This is the most expressive method, likely suitable for high-data settings. • Disadvantages: Requires training and storing all parameters of the models. May overfit to small datasets. # 8 Applications In previous sections, we examined prompting methods from the point of view of the mechanism of the method itself. In this section, we rather organize prompting methods from the point of view of which applications they have been applied to. We list these applications in Tab. 7-8 and summarize them in the following sections. # 8.1 Knowledge Probing Factual Probing Factual probing (a.k.a. fact retrieval) is one of the earliest scenarios with respect to which prompting methods were applied. The motivation of exploring this task is to quantify how much factual knowledge the pre-trained LM’s internal representations bear. In this task, parameters of pre-trained models are usually fixed, and knowledge is retrieved by transforming the original input into a cloze prompt as defined in §2.2, which can be manually crafted or automatically discovered. Relevant datasets including LAMA (Petroni et al., 2019) and X-FACTR (Jiang et al., 2020a). Since the answers are pre-defined, fact retrieval only focuses on finding effective templates and analyzing the results of different models using these templates. Both discrete template search (Petroni et al., 2019, 2020; Jiang et al., 2020c,a; Haviv et al., 2021; Shin et al., 2020; Perez et al., 2021) and continuous template learning (Qin and Eisner, 2021; Liu et al., 2021b; Zhong et al., 2021b) have been explored within this context, as well as prompt ensemble learning (Jiang et al., 2020c; Qin and Eisner, 2021). Linguistic Probing Besides factual knowledge, large-scale pre-training also allows LMs to handle linguistic phenomena such as analogies (Brown et al., 2020), negations (Ettinger, 2020), semantic role sensitivity (Ettinger, 2020), semantic similarity (Sun et al., 2021), cant understanding (Sun et al., 2021), and rare word understanding (Schick and Sch¨utze, 2020). The above knowledge can also be elicited by presenting linguistic probing tasks in the form of natural language sentences that are to be completed by the LM. # 8.2 Classification-based Tasks Prompt-based learning has been widely explored in classification-based tasks where prompt templates can be constructed relatively easily, such as text classification (Yin et al., 2019) and natural language inference (Schick and Sch¨utze, 2021a). The key to prompting for classification-based tasks is reformulating it as an appropriate prompt. For example, Yin et al. (2019) use a prompt such as “the topic of this document is [Z].”, which is then fed into mask pre-trained LMs for slot filling. Text Classification For text classification tasks, most previous work has used cloze prompts, and both prompt engineering (Gao et al., 2021; Hambardzumyan et al., 2021; Lester et al., 2021) and answer engineering (Schick and Sch¨utze, 2021a; Schick et al., 2020; Gao et al., 2021) have been explored extensively. Most existing works explore the efficacy of prompt learning for text classification in the context of few-shot setting with “fixed-prompt LM Tuning” strategies (defined in §7.2.4). Natural Language Inference (NLI) NLI aims to predict the relationship (e.g., entailment) of two given sentences. Similar to text classification tasks, for natural language inference tasks, cloze prompts are commonly used (Schick and Sch¨utze, 2021a). Regarding prompt engineering, researchers mainly focus on the template search in the few-shot learning setting and the answer space # Z 19 8.2 Classification-based Tasks Prompt Engineering Answer Engineering Work Task PLM Setting Shape Man Auto Shape Man Auto Tuning Mul-Pr LMComm [173] CR L2R Zero Clo vv. Sp vy. TEP - GPT-2 [140] SUMMIT GPT-2 Zero,Few CloPre Y - TokSpSen / - TEP PA WNLaMPro [150] LCP BERT Zero Clo vv. Tok vy. TEP - LMDiagnose [39] CR,LCP BERT Zero Clo vv. Tok vy. TEP - AdvTrigger [177] GCG GPT-2 Full Pre - Disc Sen vo. TEP - CohRank [31] CKM BERT Zero Clo vv. Tok,Sp vy. TEP - LAMA [133] FP Conv, Trans Zero Clo v- Tok v- TEP - ELMo,BERT CTRL [75] GCG CTRL Full Pre vv. Sen vy. LMT - TS [141] OAM. TS Full Pre v- Tok,SpSen S - LMT - Neg & Mis [74] FP pans EL Mo Zero Clo v- Tok v- TFP - LPAQA [68] FP BERT,ERNIE Full Clo Vv Disc Tok vo. TEP PE ZSC [135] TC GPT-2 Full Pre vv. Tok,Sp vy. LMT - PET-TC [153] TC RoBERTa,XLM-R Few Pre v Tok v¥ Disc LMT PE ContxFP [132] FP BERT,RoBERTa — Zero Clo Vv Disc Tok vo. TEP - UnifiedQA [76] QA TS,BART Full Prefix S - TokSpSen S - LMT - RAG [95] QA,GCG.TC BART Full Pre - Disc TokSpSen ¢% - LMPT PE QA,MT,GCG GPT-3 [16] CRITCLCP GPT-3 Zero,Few CloPre Y - TokSpSen / - TEP PA MR,SR,AR CommS2S [187] CR TS Full Pre vv. Tok vy. LMT - PET-SGLUE [154] TC ALBERT Few Clo v Tok,Sp vo. LMT PE ToxicityPrompts [47] GCG oer Cree Zero Pre vo - TEP - WhyLM [147] Theory GPT-2 Full Pre vv. Tok vy. PT - X-FACTR [66] FP eee Zero Clo v- Tok,Sp v- TEP - Petal [149] TC RoBERTa Few Clo v Tok - Disc LMT PE AutoPrompt [159] TC,FP,IE BERT,RoBERTa Full Clo - Disc Tok - Disc TEP - CTRLsum [59] SUM BART Full Pre vv. Sen vy. LMT - PET-Gen [152] SUM PEGASUS Few Pre v Sen vo. LMT PE LM-BFF [46] TC RoBERTa Few Clo - Disc Tok - Disc LMT PE.PA WARP [55] TC RoBERTa FewFull Clore % Cont Tok ¥ Cont PT PE Prefix-Tuning [96] D2T,SUM GPT-2,BART Full Pre - Cont Sen vo. PT - KATE [100] TCD2T,.QA GPT-3 Few Pre v TokSpSen S - TEP PA PromptProg [145] AROS GPT-3 Zero,Few Pre v- TokSpSen SY - TEP PA ContxCalibrate [201] TC,FP.IE GPT-2,GPT-3 Few Pre v Tok,Sp vo. TEP PA PADA [8] TC,TAG TS Full Pre - Disc LMPT - SD [155] # GCG # GPT-2 # Zero # Pre # v # N/A # TFP # BERTese [58] # FP # BERT # Full # Clo # Vv Disc # Tok # vo. # TFP # Prompt2Data [148] # TC # RoBERTa # Full # Clo # v # Tok,Sp # vo. # LMT # P-Tuning [103] # FP,TC # GPT-2,BERT ALBERT # Few,Full # Clo,Pre % Cont # Tok,Sp # vo - # TFP,LMPT GLM [37] # TC # GLM # Full # Clo # vv. # Tok,Sp # vy. # LMT Table 7: An organization of works on prompting (Part 1). See the caption of Tab. 8 for a detailed description for all the abbreviations used in this table. 20 8.2 Classification-based Tasks Prompt Engineering Answer Engineering Work Task PLM Setting Shape Man Auto Shape Man Auto Tuning = Mul-Pr ADAPET [170] TC ALBERT Few Clo vo. Tok,Sp vo. LMT - Meta [202] TC TS Full Pre vv. Tok vv. LMT - OptiPrompt [203] FP BERT Full Clo Y Cont’ Tok vv. PT - BERT,BART Soft [137] FP RoBERTa Full Clo vY Cont’ Tok vo - PT PE DINO [151] GCG GPT-2 Zero Pre vo. TFP - AdaPrompt [21] IE BERT Few,Full Clo vo. Tok - Disc LMT - PMIpc [62] GCG,QA,TC — GPT-2,GPT-3 Zero Pre vo. TokSpSen Yo - TFP - Prompt-Tuning [91] TC TS Full Pre - Cont Tok,Sp vo. PT PE Natural-Instr [120] GCG GPT-3,BART Few Full Pre vo. TokSpSen v - TFPLMT PA OrderEntropy [111] TC GPT-2,GPT-3 Few Pre vo. Tok vo. TFP PA FewshotSemp [158] | SEMP GPT-3 Few Pre vv. Sen vv. TFP PA QA,CR,TC PanGu-a [194] SUM.GCG PanGu-a Zero,Few Clore SY - TokSpSen SY - TFP PA GPT-2,GPT-3 . TrueFewshot [129] TC,FP ALBERT Few Clo,Pre Y — Disc Tok,Sp v- TFPLMT - PTR [56] IE RoBERTa Full Clo ¥ Cont Tok,Sp vo. LMPT — PC TemplateNER [29] TAG BART Few Full CloPre oY - Tok vo. LMT PD PERO [83] TC.FP BERTRoBERTa Few Pre vo. Tok vo. TFP PA PromptAnalysis [181] Theory BERT Full Clo - Cont PT - QA.MR,SUM 2 - - - - CPM-2 [198] toccamr CPM2 Full Pre Cont Tok,Sp,Sent / PT.LMPT BARTScore [193] EVALG BART Zero Pre Vv Disc Sen vo. TFP PE NullPrompt [109] TC RoBERTa,ALBERT Few Pre vo. Tok vo. LMPT- Frozen [174] VQA,VFPRMG GPT-like Full Pre - Cont Sp(Visual) SY - PT PA TC,LCP.NLI ERNIE-B3 [167] CR,QA,SUM — ERNIE-B3 Zero CloPre Y - TokSpSen Sf - TFP - GCG Codex [20] CodeGen GPT fem rew Pre vo - Span VY Disc TFRLMT PA HTLM [1] TC,SUM BART pene Clo VY Disc TokSpSen / - LMT PA FLEX [15] TC TS Zero,Few Pre v - Tok,Sp v - LMT - Table 8: An organization of works on prompting (Part 2). The Task column lists the tasks that are performed in corresponding papers. We use the following abbreviations. CR: Commonsense Reasoning. QA: Question Answering. SUM: Summarization. MT: Machine Translation. LCP: Linguistic Capacity Probing. GCG: General Conditional Generation. CKM: Commonsense Knowledge Mining. FP: Fact Probing. TC: Text Classification. MR: Mathematical Reasoning. SR: Symbolic Reasoning. AR: Analogical Reasoning. Theory: Theoretical Analysis. IE: Information Extraction. D2T: Data-to-text. TAG: Sequence Tagging. SEMP: Semantic Parsing. EVALG: Evaluation of Text Generation. VQA: Visual Question Answering. VFP: Visual Fact Probing. MG: Multimodal Grounding. CodeGen: Code generation. The PLM column lists all the pre-trained LMs that have been used in corresponding papers for downstream tasks. GPT-like is an autoregressive language model which makes small modifications to the original GPT-2 architecture. For other pre-trained LMs, please refer to §3 for more information. Setting column lists the settings for prompt-based learning, can be zero-shot learning (Zero), few-shot learning (Few), fully supervised learning (Full). Under Prompt Engineering, Shape denotes the shape of the template (Clo for cloze and Pre for prefix), Man denotes whether human effort is needed, Auto denotes data-driven search methods (Disc for discrete search, Cont for continuous search). Under Answer Engineering, Shape indicates the shape of the answer (Tok for token-level, Sp for span-level, Sen for sentence- or document-level), and Man and Auto are the same as above. The Tuning column lists tuning strategies (§7). TFP: Tuning-free Prompting. LMT: Fixed-prompt LM Tuning. PT: Fixed-LM Prompt Tuning. LMPT: LM+Prompt Tuning. The Mul-Pr column lists multi-prompt learning methods. PA: Prompt Augmentation. PE: Prompt Ensembling. PC: Prompt Composition. PD: Prompt Decomposition. 21 8.3 Information Extraction # 8.3 Information Extraction Unlike classification tasks where cloze questions can often be intuitively constructed, for information extraction tasks constructing prompts often requires more finesse. Relation Extraction Relation extraction is a task of predicting the relation between two entities in a sentence. Chen et al. (2021b) first explored the application of fixed-prompt LM Tuning in relation extraction and discuss two major challenges that hinder the direct inheritance of prompting methodology from classification tasks: (1) The larger label space (e.g. 80 in relation extraction v.s 2 in binary sentiment classification) results in more difficulty in answer engineering. (2) In relation extraction, different tokens in the input sentence may be more or less important (e.g. entity mentions are more likely to participate in a relation), which, however, can not be easily reflected in the prompt templates for classification since the original prompt template regards each word equally. To address the above problems, Chen et al. (2021b) propose an adaptive answer selection method to address the issue (1) and task-oriented prompt template construction for the issue (2), where they use special markers (e.g. [E]) to highlight the entity mentions in the template. Similarly, Han et al. (2021) incorporate entity type information via multiple prompt composition techniques (illustrated in Fig. 4). Semantic Parsing Semantic parsing is a task of generating a structured meaning representation given a natural language input. Shin et al. (2021) explore the task of few-shot semantic parsing using LMs by (1) framing the semantic parsing task as a paraphrasing task (Berant and Liang, 2014) and (2) constraining the decoding process by only allowing output valid according to a grammar. They experiment with the in-context learning setting described in §7.2.2, choosing answered prompts that are semantically close to a given test example (determined by the conditional generation probability of generating a test sample given another training example). The results demonstrate the effectiveness of the paraphrasing reformulation for semantic parsing tasks using pre-trained LMs. Named Entity Recognition Named entity recognition (NER) is a task of identifying named entities (e.g., person name, location) in a given sentence. The difficulty of prompt-based learning’s application to tagging tasks, exemplified as NER, is that, unlike classification, (1) each unit to be predicted is a token or span instead of the whole input text, (2) there is a latent relationship between the token labels in the sample context. Overall, the application of prompt-based learning in tagging task has not been fully explored. Cui et al. (2021) recently propose a template-based NER model using BART, which enumerates text spans and considers the generation probability of each type within manually crafted templates. For example, given an input “Mike went to New York yesterday”, to determine what type of entity “Mike” is, they use the template “Mike is a [Z] entity”, and the answer space consists of values such as “person” or “organization”. 8.4 There is still a debate6 about if deep neural networks are capable of performing “reasoning” or just memorizing patterns based on large training data (Arpit et al., 2017; Niven and Kao, 2019). As such, there have been a number of attempts to probe models’ reasoning ability by defining benchmark tasks that span different scenarios. We detail below how prompting methods have been used in these tasks. Commonsense Reasoning There are a number of benchmark datasets testing commonsense reasoning in NLP systems (Huang et al., 2019; Rajani et al., 2019; Lin et al., 2020; Ponti et al., 2020). Some commonly attempted tasks involve solving Winograd Schemas (Levesque et al., 2012), which require the model to identify the antecedent of an ambiguous pronoun within context, or involve completing a sentence given multiple choices. For the former, an example could be “The trophy doesn’t fit into the brown suitcase because it is too large.” And the task for the model is to infer whether “it” refers to the trophy or the “suitcase”. By replacing “it” with its potential candidates in the original sentences and calculating the probability of the different choices, pre-trained LMs can perform quite well by choosing the choice that achieves the highest probability (Trinh and Le, 2018). For the latter, an example could be “Eleanor offered to fix her visitor some coffee. Then she realized she didn’t have a clean [Z].”. The candidate choices are “cup”, “bowl” and “spoon”. The task for the pre-trained LM is to choose the one from the three candidates that most conforms to common sense. For these kinds of tasks, we can also score the generation probability of each candidate and choose the one with the highest probability (Ettinger, 2020). Mathematical Reasoning Mathematical reasoning is the ability to solve mathematical problems, e.g. arithmetic addition, function evaluation. Within the context of pre-trained LMs, researchers have found that pre-trained embeddings and LMs can perform simple operations such as addition and subtraction when the number of digits is small, but fail when the numbers are larger (Naik et al., 2019; Wallace et al., 2019b; Brown et al., 2020). Reynolds and McDonell (2021) explore more complex mathematical (e.g. f (x) = x x, what is f (f (3))?) reasoning problems and improve LM performance through serializing reasoning for the question. 6e.g. https://medium.com/reconstruct-inc/the-golden-age-of-computer-vision-338da3e471d1 22 8.5 Question Answering # 8.5 Question Answering Question answering (QA) aims to answer a given input question, often based on a context document. QA can take a variety of formats, such as extractive QA (which identifies content from the context document containing the answer; e.g. SQuAD (Rajpurkar et al., 2016)), multiple-choice QA (where the model has to pick from several choices; e.g. RACE (Lai et al., 2017)), and free-form QA (where the model can return an arbitrary textual string as a response; e.g. NarrativeQA (Koˇcisk´y et al., 2018)). Generally, these different formats have been handled using different modeling frameworks. One benefit of solving QA problems with LMs, potentially using prompting methods, is that different formats of QA tasks can be solved within the same framework. For example, Khashabi et al. (2020) reformulate many QA tasks as a text generation problem by fine-tuning seq2seq-based pre-trained models (e.g. T5) and appropriate prompts from the context and questions. Jiang et al. (2020b) take a closer look at such prompt-based QA systems using sequence to sequence pre-trained models (T5, BART, GPT2) and observe that probabilities from these pre-trained models on QA tasks are not very predictive of whether the model is correct or not. # 8.6 Text Generation Text generation is a family of tasks that involve generating text, usually conditioned on some other piece of information. Prompting methods can be easily applied to these tasks by using prefix prompts together with autoregressive pre-trained LMs. Radford et al. (2019) demonstrated impressive ability of such models to perform generation tasks such as text summarization and machine translation using prompts such as “translate to french, [X], [Z]”. Brown et al. (2020) perform in-context learning (§7.2.2) for text generation, creating a prompt with manual templates and augmenting the input with multiple answered prompts. Schick and Sch¨utze (2020) explore fixed-prompt LM tuning (§7.2.4) for few-shot text summarization with manually crafted templates. (Li and Liang, 2021) investigate fixed-LM prompt tuning (§7.2.3) for text summarization and data-to-text generation in few-shot settings, where learnable prefix tokens are prepended to the input while parameters in pre-trained models are kept frozen. Dou et al. (2021) explored the prompt+LM tuning strategy (§7.2.5) on text summarization task, where learnable prefix prompts are used and initialized by different types of guidance signals, which can then be updated together with parameters of pre-trained LMs. # 8.7 Automatic Evaluation of Text Generation Yuan et al. (2021b) have demonstrated that prompt learning can be used for automated evaluation of generated texts. Specifically, they conceptualize the evaluation of generated text as a text generation problem, modeled using a pre-trained sequence-to-sequence, and then use prefix prompts that bring the evaluation task closer to the pre-training task. They experimentally find that simply adding the phrase “such as” to the translated text when using pre-trained models can lead to a significant improvement in correlation on German-English machine translation (MT) evaluation. # 8.8 Multi-modal Learning Tsimpoukelli et al. (2021) shift the application of prompt learning from text-based NLP to the multi-modal setting (vision and language). Generally, they adopt the fixed-LM prompt tuning strategy together with prompt augmentation techniques. They specifically represent each image as a sequence of continuous embeddings, and a pre-trained LM whose parameters are frozen is prompted with this prefix to generate texts such as image captions. Empirical results show few-shot learning ability: with the help of a few demonstrations (answered prompts), system can rapidly learn words for new objects and novel visual categories. # 8.9 Meta-Applications There are also a number of applications of prompting techniques that are not NLP tasks in and of themselves, but are useful elements of training strong models for any application. Domain Adaptation Domain adaptation is the practice of adapting a model from one domain (e.g. news text) to another (e.g. social media text). Ben-David et al. (2021) use self-generated domain related features (DRFs) to augment the original text input and perform sequence tagging as a sequence-to-sequence problem using a seq2seq pre-trained model. Debiasing Schick et al. (2021) found that LMs can perform self-diagnosis and self-debiasing based on biased or debiased instructions. For example, to self-diagnosis whether the generated text contains violent information, we can use the following template “The following text contains violence. [X][Z]”. Then we fill [X] with the input text and look at the generation probability at [Z], if the probability of “Yes” is greater than “No”, then we would assume the given text contains violence, and vice versa. To perform debiasing when generating text, we first x<t; θ) given the original input. Then we compute the probability compute the probability of the next word P (xt | 23 8.10 Resources [x<t; xdiagnosis]; θ) by appending self-diagnosis textual input to the original input as mentioned of next word P (xt | above. These two probability distributions for the next token can be combined to suppress the undesired attribute. Dataset Construction Schick and Sch¨utze (2021) propose to use pre-trained LMs to generate datasets given certain instructions. As an example, suppose we have an unlabeled dataset in which each sample is a sentence. If we want to construct a dataset containing pairs of semantically similar sentences, then we can use the following template for each input sentence: “Write two sentences that mean the same thing. [X][Z]” and attempt to generate a sentence that shares the same meaning as the input sentence. # 8.10 Resources We also collect some useful resources for different prompt-based applications. Dataset Some datasets specifically designed for few-shot and zero-shot learning are shown in Tab. 9. Task Dataset Setting URL Commonsense Reasoning Pronoun Disambiguation Problems [93] Zero Zero Winograd Schema Challenge [93] Zero CPRAG-102 [39] https://cs.nyu.edu/ davise/papers/... https://cs.nyu.edu/ davise/papers/... https://github.com/aetting/lm-diagnostics Linguistic Capacity Probing WNLaMPro [150] ROLE-88 [39] NEG-136 [39] Zero Zero Zero https://github.com/timoschick/... https://github.com/aetting/lm-diagnostics https://github.com/aetting/lm-diagnostics Fact Probing LAMA [133] Negated LAMA [74] Misprimed LAMA [74] X-FACTR [66] LAMA-TREx-easy-hard [203] Zero Zero Zero Zero Zero https://dl.fbaipublicfiles.com/LAMA/... https://github.com/norakassner/LAMA... https://github.com/norakassner/LAMA... https://x-factr.github.io/ https://github.com/princeton-nlp/... Text Classification FLEX [15] FewGLUE [154] Zero,Few https://github.com/allenai/flex Few https://github.com/timoschick/fewglue General Conditional Gen. REALTOXICITYPROMPTS [47] Natural-Instructions [120] Zero Few,Full https://allenai.org/data/... https://instructions.apps.allenai.org/ Table 9: Few-shot and zero-shot datasets for prompt-based learning. Prompts As shown in Tab. 10, we collect existing commonly-used prompts designed manually, which can be regarded as off-the-shelf resource for future research and applications. # 9 Prompt-relevant Topics What is the essence of prompt-based learning and how does it relate to other learning methods? In this section, we connect prompt learning with other similar learning methods. Ensemble Learning Ensemble learning (Ting and Witten, 1997; Zhou et al., 2002) is a technique that aims to improve the performance of a task by taking advantage of the complementarity of multiple systems. Generally, the different systems used in an ensemble result from different choices of architectures, training strategies, data ordering, and/or random initialization. In prompt ensembling (§6.1), the choice of prompt templates becomes another way to generate multiple results to be combined. This has the clear advantage that this does not necessarily require training the model multiple times. For example, when using discrete prompts, these prompts can simply be changed during the inference stage (Jiang et al., 2020c). Few-shot Learning Few-shot learning aims to learn a machine learning system in the data-scarce scenarios with few training samples. There are a wide variety of methods to achieve few-shot learning including model agnostic meta-learning (Finn et al., 2017b) (learning features rapidly adaptable to new tasks), embedding learning (Bertinetto et al., 2016) (embedding each sample in a lower-dimensional space where similar samples are close together), memory-based learning (Kaiser et al., 2017) (representing each sample by a weighted average of contents from the memory) etc. (Wang et al., 2020). Prompt augmentation can be regarded as another way to achieve few-shot learning (a.k.a. priming-based few-shot learning (Kumar and Talukdar, 2021)). Compared to previous methods, prompt augmentation directly prepends several labeled samples to the currently-processed sample elicit knowledge from pre-trained LMs even without any parameter tuning. 24 # Task # Example Prompt-Answer # Resource Fact Probing Prompt Adolphe Adam died in [Z]. Answer V Prompt iPod Touch is produced by [Z]. Answer V Prompt The official language of Mauritius is [Z]. Answer V LAMA dataset LPAQA dataset X-FACTR dataset Text Classificatin Prompt Which of these choices best describes the following document? ”[Class A]”, ”[Class B]”, ”[Class C]”. [X][Z] Answer [Class A], [Class B], [Class C] Prompt How is the text best described? : ”[Class A]”, “[Class B]” , or “[Class C]”. [X][Z] Answer [Class A], [Class B], [Class C] Prompt This passage is about [Z]: [X] Answer [Class A], [Class B], [Class C] Prompt [X]. Is this review positive? [Z] Answer Yes, No Prompt [X] It was [Z]. Answer great, terrible Meta [202] Natural Language Inference Prompt [X1]? [Z], [X2] Answer Yes, No, Maybe Prompt [X1] [Z], [X2] Answer Yes, No, Maybe Commonsense Reasoning Prompt The trophy doesn’t fit into the brown suitcase because [Z] is too large. Answer trophy, suitcase Prompt Ann asked Mary what time the library closes, because [Z] had forgotten. Answer Ann, Mary PDP dataset WSC dataset CPRAG-102 dataset Linguistic Knowledge Probing Prompt A robin is a [Z]. Answer bird, tree Prompt A robin is not a [Z]. Answer bird, tree Prompt New is the opposite of [Z]. Answer old, young, current WNLaMPro dataset ROLE-88 dataset NEG-136 dataset Named Entity Recognition Prompt-Pos [X] [Span] is a [Z] entity. Prompt-Neg [X] [Span] is not a named entity. Answer person, location, organization, miscellaneous Prompt-Pos The entity type of Span is [Z]. Prompt-Neg [X] The entity type of [Span] is none entity. Answer person, location, organization, miscellaneous TemplateNER [29] Question Answering Prompt [Question] [Passage] [Z] Prompt [Passage] According to the passage, [Question] [Z] Prompt Based on the following passage, [Question] [Z]. [Passage] # Summarization Prompt Text: [X] Summary: [Z] Prompt [X] TL;DR: [Z] Prompt [X] In summary, [Z] BARTScore [193] # Machine Translation Prompt French: [French sentence] English: Prompt A French sentence is provided: [French sentence] The French translator translates the sentence into English: [Z] Prompt [French sentence] = [Z] Table 10: Commonly used prompts and answers for different tasks. [X] and [Z] denote slots for input and answer denotes the vocabulary of the LM. More prompts for each task can be found using the Resource respectively. column. 25 Prompt Concept Relevant Topic Commonality Peculiarity Prompt Ensembling [68; 153] Ensemble Learning [171; 204] Combine results of multiple sys- tems to get better performance In prompt ensembling, multiple predic- tions result from different prompt vari- ants. This contrasts with architecture or feature variations, each of which re- quires separate training. Few-shot Learning [160; 42] Use few examples to learn gen- eralized rules Prompt augmentation is a specific subset of few-shot learning. Prompt Augmentation [16; 46] Larger-context Learning [18; 53] Introduce larger context to aid the learning process Additional information introduced in larger-context learning is not necessarily the labeled data. Discrete Prompt Search [68; 159] Query tion [123; 123] reformula- Reformulate the input into a query form Query reformulation commonly focuses on information extraction and question answering tasks, while prompt learning can be applied to a variety of NLP tasks Discrete Prompt Fine- tuning [46] QA-based multi- task learning [115; 97] Reformulate many tasks into an QA form QA-based formulations aim to solve dif- ferent tasks through question answering, while prompting additionally targets full use of pre-trained models. Continuous Fine-tuning [103; 36] Prompt Controlled Generation 77; 156] Text [191; Input is augmented with addi- tional inputs to control the gen- eration process Controlled generation targets generation of a particular type of text while prompt learning uses prompts to specify the task itself. down- Prompt-based stream task learning [153; 193] Supervised Attention [101; 165] Data augmentation [40; 144] Require external hint to remind the model of which part information should be focused on Research works on supervised attention usually target at salient information from an image or text, while prompt learning aims to utilize relevant knowledge from the pre-trained model. Data augmentation introduce additional training samples in an explicit way while prompts can be regarded as highly- condensed training samples [88]. Table 11: Other research topics relevant to prompting methods. Larger-context Learning Larger-context learning aims to improve the system’s performance by augmenting the input with additional contextual information, e.g. retrieved from the training set (Cao et al., 2018) or external data sources (Guu et al., 2020). Prompt augmentation can be regarded as adding relevant labeled samples into the input, but a minor difference is in larger-context learning, the introduced context is not necessarily labeled data. Query Reformulation Query reformulation (Mathieu and Sabatier, 1986; Daum´e III and Brill, 2004) is commonly used in information retrieval (Nogueira and Cho, 2017) and question answering tasks (Buck et al., 2017; Vakulenko et al., 2020), which aim to elicit more relevant texts (documents or answers) by expanding the input query with related query terms (Hassan, 2013) or generating paraphrases. There are several commonalities between prompt- based learning and query reformulation, for example (1) both aim to make better use of some existing knowledge bases by asking a right questions (2) the knowledge bases are usually a black-box, not available to the users, so researchers must learn how to probe it optimally based on solely questions. There are also differences: the knowledge base in traditional query reformulation problems is usually a search engine (Nogueira and Cho, 2017), or QA system (Buck et al., 2017). By contrast, for prompt-based learning, we usually define this knowledge base as an LM, and need to find the appropriate query to elicit an appropriate answer from it. The input reformulation in prompt learning has changed the form of tasks. For example, an original text classification task has been converted into a cloze question problem, therefore bringing additional complexity regarding how to (1) make an appropriate task formulation, and (2) change the modeling framework accordingly. These steps are not required in traditional query formulation. Despite these discrepancies, some methodologies from query reformulation research still can be borrowed for prompt learning, such as decomposing input query into multiple sub-queries (Nogueira et al., 2019), similar to prompt decomposition. QA-based Task Formulation QA-based task formulation aims to conceptualize different NLP tasks as a question- answering problem. (Kumar et al., 2016; McCann et al., 2018) are earlier works that attempt to unify multiple NLP tasks into a QA framework. Later, this idea has been further explored in information extraction (Li et al., 2020; Wu 26 et al., 2020) and text classification (Chai et al., 2020). These methods are very similar to the prompting methods introduced here in that they use textual questions to specify which task is to be performed. However, one of the key points of prompting methods is how to better use the knowledge in pre-trained LMs, and these were not covered extensively on previous works advocating for QA formulations. Controlled Generation Controlled generation aims to incorporate various types of guidance beyond the input text into the generation model (Yu et al., 2020). Specifically, the guidance signals could be style tokens (Sennrich et al., 2016b; Fan et al., 2018), length specifications (Kikuchi et al., 2016), domain tags (Chu et al., 2017), or any variety of other pieces of information used to control of the generated text. It could also be keywords (Saito et al., 2020), relation triples (Zhu et al., 2020) or even highlighted phrases or sentences (Grangier and Auli, 2018; Liu et al., 2021c) to plan the content of generated texts. In a way, many of the prompting methods described here are a type of controllable generation, where the prompt is usually used to specify the task itself. Thus, it is relatively easy to find commonalities between the two genres: (1) both add extra information to the input text for better generation, and these additional signals are (often) learnable parameters. (2) If “controlled generation” is equipped with seq2seq-based pre-trained models (e.g., BART), then it is can be regarded as prompt learning with input-dependent prompts and the prompt+LM fine-tuning strategy (§7.2.5), e.g. GSum (Dou et al., 2021), where both the prompt’s and pre-trained LM’s parameters can be tuned. Also, some clear discrepancies between controlled generation and prompt-based text generation are: (1) In controlled generation work, the control is generally performed over the style or content of the generations (Fan et al., 2018; Dou et al., 2021) while the underlying task remains the same. They don’t necessarily require a pre-trained model. In contrast, the main motivation for using prompts for text generation is to specify the task itself and better utilize the pre-trained model. (2) Moreover, most of the current work on prompt learning in text generation shares a dataset- or task-level prompt (Li and Liang, 2021). Only very few works have explored input-dependent ones (Tsimpoukelli et al., 2021). However, this is a common setting and effective in the controlled text generation, which may provide valuable direction for the future work on prompt learning. Supervised Attention Knowing to pay attention to the important information is a key step when extracting useful information from objects such as long text sequences (Liu et al., 2016; Sood et al., 2020), images (Sugano and Bulling, 2016; Zhang et al., 2020b), or knowledge bases (Yu et al., 2020; Dou et al., 2021)). Supervised attention (Liu et al., 2017b) aims to provide explicit supervision over the attention of models based on the fact that completely data-driven attention can overfit to some artifacts (Liu et al., 2017a). In this respect, prompt learning and supervised attention share ideas that both aim to extract salient information with some clues, which need to be provided separately. To solve this problem, supervised attention methods tried to use additional loss functions to learn to predict gold attention on a manually labeled corpus (Jiang et al., 2015; Qiao et al., 2018; Gan et al., 2017). Research on prompt learning may also borrow ideas from this literature. Data Augmentation Data augmentation is a technique that targets increasing the amount of data that can be used for training by making modifications to existing data (Fadaee et al., 2017; Ratner et al., 2017). As recently observed by (Scao and Rush, 2021), adding prompts can achieve a similar accuracy improvement to the addition of 100s of data points on average across classification tasks, which suggests that using prompts for a downstream task is similar to conducting data augmentation implicitly. # 10 Challenges Although prompt-based learning has shown significant potential among different tasks and scenarios, several challenges remain, some of which we detail below. # 10.1 Prompt Design Tasks beyond Classification and Generation Most existing works about prompt-based learning revolve around either text classification or generation-based tasks. Applications to information extraction and text analysis tasks have been discussed less, largely because the design of prompts is less straightforward. We expect that applying prompting methods to these tasks in the future it will require either reformulating these tasks so that they can be solved using classification or text generation-based methods, or performing effective answer engineering that expresses structured outputs in an appropriate textual format. Prompting with Structured Information In many NLP tasks, the inputs are imbued with some variety of structure, such as tree, graph, table, or relational structures. How to best express these structures in prompt or answer engineering is a major challenge. Existing works (Chen et al., 2021b) make a step by making prompts with additional marks to encode lexical information, such as entity markings. Aghajanyan et al. (2021) present structured prompts based on hyper text markup language for more fine-grained web text generation. However, moving beyond this to more complicated varieties of structure is largely unexplored, and a potentially interesting research area. 27 10.2 Answer Engineering Movie Review (X1) | Really awesome movie! ¥ Prompt | | Movie: [X1] This is [MASK]. > Template { [Domain_name]: This is [MASK]. + Prompt 2 | Product: [X2] This is [MASK]. > Product Review (X2) | It’s very easy to use! Figure 5: Multi-prompt learning for multi-task, multi-domain or multi-lingual learning. We use different colors to differentiate different components as follows. “ Entanglement of Template and Answer The performance of a model will depend on both the templates being used and the answer being considered. How to simultaneously search or learn for the best combination of template and answer remains a challenging question. Current works typically select answers before select template (Gao et al., 2021; Shin et al., 2020), but Hambardzumyan et al. (2021) have demonstrated the initial potential of simultaneously learning both. # 10.2 Answer Engineering Many-class and Long-answer Classification Tasks For classification-based tasks, there are two main challenges for answer engineering: (a) When there are too many classes, how to select an appropriate answer space becomes a difficult combinatorial optimization problem. (b) When using multi-token answers, how to best decode multiple tokens using LMs remains unknown, although some multi-token decoding methods have been proposed (Jiang et al., 2020a). Multiple Answers for Generation Tasks For text generation tasks, qualified answers can be semantically equivalent but syntactically diverse. So far, almost all works use prompt learning for text generation relying solely on a single answer, with only a few exceptions (Jiang et al., 2020c). How to better guide the learning process with multiple references remains a largely open research problem. # 10.3 Selection of Tuning Strategy As discussed in §7, there are a fairly wide variety of methods for tuning parameters of prompts, LMs, or both. However, given the nascent stage of this research field, we still lack a systematic understanding of the tradeoffs between these methods. The field could benefit from systematic explorations such as those performed in the pre-train and fine-tune paradigm regarding the tradeoffs between these different strategies (Peters et al., 2019). # 10.4 Multiple Prompt Learning Prompt Ensembling In prompt ensembling methods, the space and time complexity increase as we consider more prompts. How to distill the knowledge from different prompts remains underexplored. Schick and Sch¨utze (2020, 2021a,b) use an ensemble model to annotate a large dataset to distill the knowledge from multiple prompts. In addition, how to select ensemble-worthy prompts is also under-explored. For text generation tasks, the study of prompt ensemble learning has not been performed so far, probably because ensemble learning in text generation itself is relatively complicated. To remedy this problem, some recently proposed neural ensembling methods such as Refactor (Liu et al., 2021c) could be considered as a method for prompt ensembling in text generation tasks. Prompt Composition and Decomposition Both prompt composition and decomposition aim to break down the difficulty of a complicated task input by introducing multiple sub-prompts. In practice, how to make a good choice between them is a crucial step. Empirically, for those token (Ma and Hovy, 2016) or span (Fu et al., 2021) prediction tasks (e.g., NER), prompt decomposition can be considered, while for those span relation prediction (Lee et al., 2017) tasks (e.g., entity coreference), prompts composition would be a better choice. In the future, the general idea of de-/composing can be explored in more scenarios. Prompt Augmentation Existing prompt augmentation methods are limited by the input length, i.e., feeding too many demonstrations to input is infeasible. Therefore, how to select informative demonstrations, and order them in an appropriate is an interesting but challenging problem (Kumar and Talukdar, 2021). Prompt Sharing All the above considerations refer to the application of prompt in a single task, domain or language. We may also consider prompt sharing, where prompt learning is applied to multiple tasks, domains, or languages. Some key issues that may arise include how to design individual prompts for different tasks, and how to modulate their interaction with each other. So far this field has not been explored. Fig.5 illustrates a simple multiple prompt learning strategy for multiple tasks, where prompt templates are partially shared. 28 10.5 Selection of Pre-trained Models # 10.5 Selection of Pre-trained Models With plenty of pre-trained LMs to select from (see §3), how to choose them to better leverage prompt-based learning is an interesting and difficult problem. Although we have conceptually introduced (§3.4) how different paradigms of pre-trained models are selected for diverse NLP tasks, there are few to no systematic comparisons of the benefits brought by prompt-based learning for different pre-trained LMs. # 10.6 Theoretical and Empirical Analysis of Prompting Despite their success in many scenarios, theoretical analysis and guarantees for prompt-based learning are scarce. Wei et al. (2021) showed that soft-prompt tuning can relax the non-degeneracy assumptions (the generation probability of each token is linearly independent) needed for downstream recovery (i.e. recover the ground-truth labels of the downstream task.), making it easier to extract task-specific information. Saunshi et al. (2021) verified that text classification tasks can be reformulated as sentence completion tasks, thus making language modeling a meaningful pre-training task. Scao and Rush (2021) empirically show that prompting is often worth 100s of data points on average across classification tasks. # 10.7 Transferability of Prompts Understanding the extent to which prompts are specific to the model and improving the transferability of prompts are also important topics. (Perez et al., 2021) show that prompts selected under tuned few-shot learning scenario (where one has a larger validation set to choose prompts) generalize well across models of similar sizes while prompts selected under true few-shot learning scenario (where one only has a few training samples) do not generalize as effectively as the former setting among models with similar sizes. The transferability is poor when the model sizes are quite different in both scenarios. # 10.8 Combination of Different Paradigms Notably, much of the success of the prompting paradigm is built on top of pre-trained models that were developed for the pre-train and fine-tune paradigm, such as BERT. However, are the pre-training methods that are effective for the latter applicable as-is to the former, or can we entirely re-think our pre-training methods to further improve accuracy or ease of applicability to prompting-based learning? This is an important research question that has not been covered extensively by the literature. # 10.9 Calibration of Prompting Methods Calibration (Gleser, 1996) refers to the ability of a model to make good probabilistic predictions. When using the generation probability of the pre-trained LMs (e.g., BART) to predict the answer, we need to be careful since the probability distribution is typically not well calibrated. Jiang et al. (2020b) observed the probabilities of pre-trained models (e.g., BART, T5, GPT-2) on QA tasks are well calibrated. Zhao et al. (2021) identify three pitfalls (majority label bias, recency bias and common token bias) that lead the pre-trained LMs to be biased toward certain answers when provided answered prompts. For example, if the final answered prompt has a positive label, then this will bias the model towards predicting positive words. To overcome those pitfalls, Zhao et al. (2021) first use context-free n Input: Beautiful film. Sentiment: input (e.g. the prompt would be “Input: Subpar acting. Sentiment: Negative \ n Input: N/A. Sentiment:”) to get the initial probability distribution P0, then they use the real input (e.g. Positive \ the prompt would be “Input: Subpar acting. Sentiment: Negative n \ \ Input: Amazing. Sentiment:”) to get the probability distribution P1. Finally, these two distributions can be used to get a calibrated generation probability distribution. However, this method has two drawbacks: (1) it comes with the overhead of finding proper context-free input (e.g. whether to use “N/A” or “None”) and (2) the probability distribution of the underlying pre-trained LM is still not calibrated. Even though we have a calibrated probability distribution, we also need to be careful when we assume a single gold answer for an input. This is because that all surface forms of a same object will compete for finite probability mass (Holtzman et al., 2021). For example, if we consider the gold answer to be “Whirlpool bath”, the generation probability of it will typically be low since the word “Bathtub” shares the same meaning and it will take over a large probability mass. To address this issue, we could either (i) perform answer engineering to construct a comprehensive gold answer set using paraphrasing methods (§5.2.2) or (ii) calibrate the probability of a word based on its prior likelihood within the context (Holtzman et al., 2021). # 11 Meta Analysis In this section, we aim to give a quantitative birds-eye view of existing research on prompting methods by performing a meta analysis over existing research works along different dimensions. 29 TABLE 12 Timeline of prompt-based learning. The time for each paper is based on its first arXiv version (if exists) or estimated submission time. A web-version can refer to NLPedia-Pretrain. Works in red consider natural language understanding (NLU) tasks; works in blue consider natural language generation (NLG) tasks; works in green consider both NLU tasks and NLG tasks. 2018.06.07 • LMComm (Trinh and Le, 2018) 2021.04.14 • Soft (Qin and Eisner, 2021) 2019.02.14 • GPT-2 (Radford et al., 2019) 2021.04.15 • DINO (Schick and Sch¨utze, 2021) 2019.04.14 • WNLaMPro (Schick and Sch¨utze, 2020) 2021.04.15 • AdaPrompt (Chen et al., 2021b) 2019.07.31 • LMDiagnose (Ettinger, 2020) 2021.04.16 • PMIDC (Holtzman et al., 2021) 2019.08.20 • AdvTrigger (Wallace et al., 2019a) 2021.04.18 • Prompt-Tuning (Lester et al., 2021) 2019.09.02 • CohRank (Davison et al., 2019) 2021.04.18 • Natural-Instr (Mishra et al., 2021) 2019.09.03 • LAMA (Petroni et al., 2019) 2021.04.18 • OrderEntropy (Lu et al., 2021) 2019.09.11 • CTRL (Keskar et al., 2019) 2021.04.18 • FewshotSemp (Shin et al., 2021) 2019.10.23 • T5 (Raffel et al., 2020) 2021.04.26 • PanGu-α (Zeng et al., 2021) 2019.11.08 • Neg & Misprim (Kassner and Sch¨utze, 2020) 2021.05.24 • TrueFewshot (Perez et al., 2021) 2019.11.28 • LPAQA (Jiang et al., 2020c) 2021.05.24 • PTR (Han et al., 2021) 2019.12.10 • ZSC (Puri and Catanzaro, 2019) 2021.06.03 • TemplateNER (Cui et al., 2021) 2020.01.21 • PET-TC (Schick and Sch¨utze, 2021a) 2021.06.03 • PERO (Kumar and Talukdar, 2021) 2020.03.10 • ContxFP (Petroni et al., 2020) 2021.06.16 • PromptAnalysis (Wei et al., 2021) 2020.05.02 • UnifiedQA (Khashabi et al., 2020) 2021.06.20 • CPM-2 (Zhang et al., 2021) 2020.05.22 • RAG (Lewis et al., 2020b) 2021.06.21 • BARTScore (Yuan et al., 2021b) 2020.05.28 • GPT-3 (Brown et al., 2020) 2021.06.24 • NullPrompt (Logan IV et al., 2021) 2020.09.08 • CommS2S(Yang et al., 2020) 2021.06.25 • Frozen (Tsimpoukelli et al., 2021) 2020.09.15 • PET-SGLUE (Schick and Sch¨utze, 2021b) 2021.07.05 • ERNIE-B3 (Sun et al., 2021) 2020.09.24 • ToxicityPrompts (Gehman et al., 2020) 2021.07.07 • Codex (Chen et al., 2021a) 2020.10.07 • WhyLM (Saunshi et al., 2021) 2021.07.14 • HTLM (Aghajanyan et al., 2021) 2020.10.13 • X-FACTR (Jiang et al., 2020a) 2021.07.15 • FLEX (Bragg et al., 2021) 2020.10.26 • Petal (Schick et al., 2020) 2020.10.29 • AutoPrompt (Shin et al., 2020) 2020.12.08 • CTRLsum (He et al., 2020a) 2020.12.22 • PET-Gen (Schick and Sch¨utze, 2020) 2020.12.31 • LM-BFF (Gao et al., 2021) 2021.01.01 • WARP (Hambardzumyan et al., 2021) 2021.01.01 • Prefix-Tuning (Li and Liang, 2021) 2021.01.17 • KATE (Liu et al., 2021a) 2021.02.15 • PromptProg (Reynolds and McDonell, 2021) 2021.02.19 • ContxCalibrate (Zhao et al., 2021) 2021.02.24 • PADA (Ben-David et al., 2021) 2021.02.27 • SD (Schick et al., 2021) 2021.03.09 • BERTese (Haviv et al., 2021) 2021.03.15 • Prompt2Data (Scao and Rush, 2021) 2021.03.18 • # P-Tuning (Liu et al., 2021b) 2021.03.18 • # GLM (Du et al., 2021) 2021.03.22 • # ADAPET (Tam et al., 2021) 2021.04.10 • Meta (Zhong et al., 2021a) 2021.04.12 • # OptiPrompt (Zhong et al., 2021b) 30 11.1 Timeline # 11.1 Timeline We first summarize a number of existing research papers in a chronological order with in the form of a timeline, which hopefully, help researchers who are new to this topic understand the evolution of the field. # 11.2 Trend Analysis We also calculate the number of prompt-based papers with respect to different dimensions. Year With the emergence of different kinds of pre-trained LMs, prompt-based learning has become a more and more active research field, as can be seen in Fig. 6-(a). We can see a huge surge in 2021, which is perhaps due to the prevalence of GPT-3 (Brown et al., 2020), which greatly increased the popularity of prompting in the few-shot multi-task setting. (a) Year. (b) Task. (c) Automatic Search. (d) Search Space. Figure 6: Meta-analyses over different dimensions. The statistics are based on the works in Tab. 7 and Tab. 8. In (d), we use the following abbreviations. TC: text classification, FP: factual probing, GCG: general conditional generation, QA: question answering, CR: commonsense reasoning, SUM: summarization, O: others. Tasks We plot the number of works that investigate various tasks in Fig. 6-(b). For a task that has fewer than 5 relevant works, we group it into “Others”. As the bar chart indicates, most tasks regarding prompt-based learning revolve around text classification and factual probing. We conjecture that this is because that for these tasks, both template engineering and answer engineering are relatively easy to conduct, and experiments are relatively computationally inexpensive. Prompt vs. Answer Search As noted in previous sections, both prompt and answer search are important tools to take advantage of pre-trained language models for many tasks. Current research mainly focuses on template search instead of answer search, as shown in Fig. 6-(c). Likely reasons are: (1) For conditional generation tasks (e.g. summarization or translation), the gold references can be directly used as answer. Although there are many sequences that may share the same semantics, how to effectively conduct multi-reference learning in conditional text generation problems is non-trivial. (2) For classification tasks, most of the time, label words are relative easy to select using domain knowledge. Discrete Search vs. Continuous Search Since there are only a few works focus on automatic answer search, we analyze the automatic template search. As time goes by, there has been a shift from discrete search to continuous search for prompt engineering, as shown in Fig. 6-(d). Likely reasons are: (1) discrete search is harder to optimize compared to continuous search, (2) soft prompts have greater representation ability. # 12 Conclusion In this paper, we have summarized and analyzed several paradigms in the development of statistical natural language processing techniques, and have argued that prompt-based learning is a promising new paradigm that may represent another major change in the way we look at NLP. First and foremost, we hope this survey will help researchers more effectively and comprehensively understand the paradigm of prompt-based learning, and grasp its core challenges so that more scientifically meaningful advances can be made in this field. In addition, looking all the way back to the summary of the four paradigms of NLP research presented in §1, we hope to highlight the commonalities and differences between them, making research on any of these paradigms more full-fledged, and potentially providing a catalyst to inspire work towards the next paradigm shift as well. # Acknowledgements We would like to thank Chunting Zhou for her constructive comments on this work. 31 References # References [1] Armen Aghajanyan, Dmytro Okhonko, Mike Lewis, Mandar Joshi, Hu Xu, Gargi Ghosh, and Luke Zettlemoyer. 2021. Htlm: Hyper-text pre-training and prompting of language models. arXiv preprint arXiv:2107.06955. [2] Zeyuan Allen-Zhu and Yuanzhi Li. 2020. Towards understanding ensemble, knowledge distillation and self- distillation in deep learning. CoRR, abs/2012.09816. [3] Devansh Arpit, Stanislaw Jastrzebski, Nicolas Ballas, David Krueger, Emmanuel Bengio, Maxinder S Kanwal, Tegan Maharaj, Asja Fischer, Aaron Courville, Yoshua Bengio, et al. 2017. A closer look at memorization in deep networks. In International Conference on Machine Learning, pages 233–242. PMLR. [4] Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. 2014. Neural machine translation by jointly learning to align and translate. arXiv preprint arXiv:1409.0473. [5] Hangbo Bao, Li Dong, and Furu Wei. 2021. Beit: Bert pre-training of image transformers. arXiv preprint arXiv:2106.08254. [6] Hangbo Bao, Li Dong, Furu Wei, Wenhui Wang, Nan Yang, Xiaodong Liu, Yu Wang, Jianfeng Gao, Songhao Piao, Ming Zhou, and Hsiao-Wuen Hon. 2020. Unilmv2: Pseudo-masked language models for unified language model pre-training. In Proceedings of the 37th International Conference on Machine Learning, ICML 2020, 13-18 July 2020, Virtual Event, volume 119 of Proceedings of Machine Learning Research, pages 642–652. PMLR. [7] Iz Beltagy, Kyle Lo, and Arman Cohan. 2019. SciBERT: A pretrained language model for scientific text. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 3615–3620, Hong Kong, China. Association for Computational Linguistics. [8] Eyal Ben-David, Nadav Oved, and Roi Reichart. 2021. Pada: A prompt-based autoregressive approach for adaptation to unseen domains. [9] Yoshua Bengio, Aaron Courville, and Pascal Vincent. 2013. Representation learning: A review and new perspectives. IEEE transactions on pattern analysis and machine intelligence, 35(8):1798–1828. [10] Yoshua Bengio, R´ejean Ducharme, Pascal Vincent, and Christian Janvin. 2003. A neural probabilistic language model. The journal of machine learning research, 3:1137–1155. [11] Jonathan Berant and Percy Liang. 2014. Semantic parsing via paraphrasing. In Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 1415–1425, Baltimore, Maryland. Association for Computational Linguistics. [12] Luca Bertinetto, Jo˜ao F Henriques, Jack Valmadre, Philip Torr, and Andrea Vedaldi. 2016. Learning feed- forward one-shot learners. In Advances in neural information processing systems, pages 523–531. [13] Sid Black, Leo Gao, Phil Wang, Connor Leahy, and Stella Biderman. 2021. GPT-Neo: Large scale autoregressive language modeling with mesh-tensorflow. [14] Samuel R. Bowman, Gabor Angeli, Christopher Potts, and Christopher D. Manning. 2015. A large annotated corpus for learning natural language inference. In Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing, pages 632–642, Lisbon, Portugal. Association for Computational Linguistics. [15] Jonathan Bragg, Arman Cohan, Kyle Lo, and Iz Beltagy. 2021. FLEX: unifying evaluation for few-shot NLP. CoRR, abs/2107.07170. [16] Tom B Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. 2020. Language models are few-shot learners. arXiv preprint arXiv:2005.14165. [17] Christian Buck, Jannis Bulian, Massimiliano Ciaramita, Wojciech Gajewski, Andrea Gesmundo, Neil Houlsby, and Wei Wang. 2017. Ask the right questions: Active question reformulation with reinforcement learning. arXiv preprint arXiv:1705.07830. [18] Ziqiang Cao, Wenjie Li, Sujian Li, and Furu Wei. 2018. Retrieve, rerank and rewrite: Soft template based neural summarization. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 152–161, Melbourne, Australia. Association for Computational Linguistics. [19] Duo Chai, Wei Wu, Qinghong Han, Fei Wu, and Jiwei Li. 2020. Description based text classification with reinforcement learning. In International Conference on Machine Learning, pages 1371–1382. PMLR. 32 References [20] Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde, Jared Kaplan, Harri Edwards, Yura Burda, Nicholas Joseph, Greg Brockman, et al. 2021a. Evaluating large language models trained on code. arXiv preprint arXiv:2107.03374. [21] Xiang Chen, Xin Xie, Ningyu Zhang, Jiahuan Yan, Shumin Deng, Chuanqi Tan, Fei Huang, Luo Si, and Huajun Chen. 2021b. Adaprompt: Adaptive prompt-based finetuning for relation extraction. CoRR, abs/2104.07650. [22] Zewen Chi, Li Dong, Shuming Ma, Shaohan Huang, Xian-Ling Mao, Heyan Huang, and Furu Wei. 2021a. mt6: Multilingual pretrained text-to-text transformer with translation pairs. CoRR, abs/2104.08692. [23] Zewen Chi, Shaohan Huang, Li Dong, Shuming Ma, Saksham Singhal, Payal Bajaj, Xia Song, and Furu Wei. 2021b. XLM-E: cross-lingual language model pre-training via ELECTRA. CoRR, abs/2106.16138. [24] Chenhui Chu, Raj Dabre, and Sadao Kurohashi. 2017. An empirical comparison of domain adaptation methods for neural machine translation. In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers), pages 385–391, Vancouver, Canada. Association for Computational Linguistics. [25] J. Chung, C¸ aglar G¨ulc¸ehre, Kyunghyun Cho, and Yoshua Bengio. 2014. Empirical evaluation of gated recurrent neural networks on sequence modeling. ArXiv, abs/1412.3555. [26] Kevin Clark, Minh-Thang Luong, Quoc V. Le, and Christopher D. Manning. 2020. ELECTRA: pre-training text encoders as discriminators rather than generators. In 8th International Conference on Learning Representations, ICLR 2020, Addis Ababa, Ethiopia, April 26-30, 2020. OpenReview.net. [27] Ronan Collobert, J. Weston, L. Bottou, Michael Karlen, K. Kavukcuoglu, and P. Kuksa. 2011. Natural language processing (almost) from scratch. J. Mach. Learn. Res., 12:2493–2537. [28] Alexis Conneau, Kartikay Khandelwal, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzm´an, Edouard Grave, Myle Ott, Luke Zettlemoyer, and Veselin Stoyanov. 2020. Unsupervised cross-lingual representation learning at scale. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, ACL 2020, Online, July 5-10, 2020, pages 8440–8451. Association for Computational Linguistics. [29] Leyang Cui, Yu Wu, Jian Liu, Sen Yang, and Yue Zhang. 2021. Template-based named entity recognition using bart. [30] Hal Daum´e III and Eric Brill. 2004. Web search intent induction via automatic query reformulation. In Proceedings of HLT-NAACL 2004: Short Papers, pages 49–52, Boston, Massachusetts, USA. Association for Computational Linguistics. [31] Joe Davison, Joshua Feldman, and Alexander M. Rush. 2019. Commonsense knowledge mining from pretrained models. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing, EMNLP-IJCNLP 2019, Hong Kong, China, November 3-7, 2019, pages 1173–1178. Association for Computational Linguistics. [32] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. BERT: Pre-training of deep bidirectional transformers for language understanding. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 4171–4186, Minneapolis, Minnesota. Association for Computational Linguistics. [33] Sumanth Doddapaneni, Gowtham Ramesh, Anoop Kunchukuttan, Pratyush Kumar, and Mitesh M Khapra. 2021. A primer on pretrained multilingual language models. arXiv preprint arXiv:2107.00676. [34] Jesse Dodge, Gabriel Ilharco, Roy Schwartz, Ali Farhadi, Hannaneh Hajishirzi, and Noah Smith. 2020. Fine- tuning pretrained language models: Weight initializations, data orders, and early stopping. arXiv preprint arXiv:2002.06305. [35] Li Dong, Nan Yang, Wenhui Wang, Furu Wei, Xiaodong Liu, Yu Wang, Jianfeng Gao, Ming Zhou, and Hsiao-Wuen Hon. 2019. Unified language model pre-training for natural language understanding and generation. In Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada, pages 13042–13054. [36] Zi-Yi Dou, Pengfei Liu, Hiroaki Hayashi, Zhengbao Jiang, and Graham Neubig. 2021. GSum: A general framework for guided neural abstractive summarization. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 4830–4842, Online. Association for Computational Linguistics. [37] Zhengxiao Du, Yujie Qian, Xiao Liu, Ming Ding, Jiezhong Qiu, Zhilin Yang, and Jie Tang. 2021. All nlp tasks are generation tasks: A general pretraining framework. 33 References [38] Kevin Duh, Katsuhito Sudoh, Xianchao Wu, Hajime Tsukada, and Masaaki Nagata. 2011. Generalized minimum bayes risk system combination. In Proceedings of 5th International Joint Conference on Natural Language Processing, pages 1356–1360. [39] Allyson Ettinger. 2020. What BERT is not: Lessons from a new suite of psycholinguistic diagnostics for language models. Trans. Assoc. Comput. Linguistics, 8:34–48. [40] Marzieh Fadaee, Arianna Bisazza, and Christof Monz. 2017. Data augmentation for low-resource neural machine translation. In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers), pages 567–573, Vancouver, Canada. Association for Computational Linguistics. [41] Angela Fan, David Grangier, and Michael Auli. 2018. Controllable abstractive summarization. In Proceedings of the 2nd Workshop on Neural Machine Translation and Generation, pages 45–54, Melbourne, Australia. Association for Computational Linguistics. [42] Chelsea Finn, Pieter Abbeel, and Sergey Levine. 2017a. Model-agnostic meta-learning for fast adaptation of deep networks. In Proceedings of the 34th International Conference on Machine Learning, ICML 2017, Sydney, NSW, Australia, 6-11 August 2017, volume 70 of Proceedings of Machine Learning Research, pages 1126–1135. PMLR. [43] Chelsea Finn, Pieter Abbeel, and Sergey Levine. 2017b. Model-agnostic meta-learning for fast adaptation of deep networks. In International Conference on Machine Learning, pages 1126–1135. PMLR. [44] Jinlan Fu, Xuanjing Huang, and Pengfei Liu. 2021. Spanner: Named entity re-/recognition as span prediction. arXiv preprint arXiv:2106.00641. [45] Chuang Gan, Yandong Li, Haoxiang Li, Chen Sun, and Boqing Gong. 2017. Vqs: Linking segmentations to questions and answers for supervised attention in vqa and question-focused semantic segmentation. In Proceedings of the IEEE international conference on computer vision, pages 1811–1820. [46] Tianyu Gao, Adam Fisch, and Danqi Chen. 2021. Making pre-trained language models better few-shot learners. In Association for Computational Linguistics (ACL). [47] Samuel Gehman, Suchin Gururangan, Maarten Sap, Yejin Choi, and Noah A Smith. 2020. Realtoxicityprompts: Evaluating neural toxic degeneration in language models. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings, pages 3356–3369. [48] Leon Jay Gleser. 1996. Measurement, regression, and calibration. [49] Joshua T Goodman. 2001. A bit of progress in language modeling. Computer Speech & Language, 15(4):403– 434. [50] David Grangier and Michael Auli. 2018. QuickEdit: Editing text & translations by crossing words out. In Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers), pages 272–282, New Orleans, Louisiana. Association for Computational Linguistics. [51] Alex Graves, Abdel-rahman Mohamed, and Geoffrey Hinton. 2013. Speech recognition with deep recurrent neural networks. In 2013 IEEE International Conference on Acoustics, Speech and Signal Processing, pages 6645–6649. [52] Kelvin Guu, Tatsunori B. Hashimoto, Yonatan Oren, and Percy Liang. 2018. Generating sentences by editing prototypes. Transactions of the Association for Computational Linguistics, 6:437–450. [53] Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat, and Ming-Wei Chang. 2020. Realm: Retrieval- augmented language model pre-training. arXiv preprint arXiv:2002.08909. [54] Isabelle Guyon, Jason Weston, Stephen Barnhill, and Vladimir Vapnik. 2002. Gene selection for cancer classification using support vector machines. Machine learning, 46(1):389–422. [55] Karen Hambardzumyan, Hrant Khachatrian, and Jonathan May. 2021. Warp: Word-level adversarial reprogram- ming. ArXiv, abs/2101.00121. [56] Xu Han, Weilin Zhao, Ning Ding, Zhiyuan Liu, and Maosong Sun. 2021. Ptr: Prompt tuning with rules for text classification. [57] Ahmed Hassan. 2013. Identifying web search query reformulation using concept based matching. In Proceed- ings of the 2013 Conference on Empirical Methods in Natural Language Processing, pages 1000–1010, Seattle, Washington, USA. Association for Computational Linguistics. 34 References [58] Adi Haviv, Jonathan Berant, and Amir Globerson. 2021. BERTese: Learning to speak to BERT. In Proceedings of the 16th Conference of the European Chapter of the Association for Computational Linguistics: Main Volume, pages 3618–3623, Online. Association for Computational Linguistics. [59] Junxian He, Wojciech Kryscinski, Bryan McCann, Nazneen Fatema Rajani, and Caiming Xiong. 2020a. Ctrlsum: Towards generic controllable text summarization. CoRR, abs/2012.04281. [60] Pengcheng He, Xiaodong Liu, Jianfeng Gao, and Weizhu Chen. 2020b. Deberta: Decoding-enhanced bert with disentangled attention. arXiv preprint arXiv:2006.03654. [61] Sepp Hochreiter and J¨urgen Schmidhuber. 1997. Long short-term memory. Neural computation, 9(8):1735– 1780. [62] Ari Holtzman, Peter West, Vered Schwartz, Yejin Choi, and Luke Zettlemoyer. 2021. Surface form competition: Why the highest probability answer isn’t always right. [63] Jeremy Howard and Sebastian Ruder. 2018. Universal language model fine-tuning for text classification. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 328–339. [64] Lifu Huang, Ronan Le Bras, Chandra Bhagavatula, and Yejin Choi. 2019. Cosmos QA: Machine reading comprehension with contextual commonsense reasoning. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 2391–2401, Hong Kong, China. Association for Computational Linguistics. [65] Ming Jiang, Shengsheng Huang, Juanyong Duan, and Qi Zhao. 2015. Salicon: Saliency in context. Proceedings of the IEEE conference on computer vision and pattern recognition, pages 1072–1080. In [66] Zhengbao Jiang, Antonios Anastasopoulos, Jun Araki, Haibo Ding, and Graham Neubig. 2020a. X-FACTR: Multilingual factual knowledge retrieval from pretrained language models. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 5943–5959, Online. Association for Computational Linguistics. [67] Zhengbao Jiang, Jun Araki, Haibo Ding, and Graham Neubig. 2020b. How can we know when language models know? CoRR, abs/2012.00955. [68] Zhengbao Jiang, Frank F. Xu, Jun Araki, and Graham Neubig. 2020c. How can we know what language models know? Transactions of the Association for Computational Linguistics, 8:423–438. [69] Xiaoqi Jiao, Yichun Yin, Lifeng Shang, Xin Jiang, Xiao Chen, Linlin Li, Fang Wang, and Qun Liu. 2020. Tinybert: Distilling BERT for natural language understanding. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings, EMNLP 2020, Online Event, 16-20 November 2020, volume EMNLP 2020 of Findings of ACL, pages 4163–4174. Association for Computational Linguistics. [70] Mandar Joshi, Danqi Chen, Yinhan Liu, Daniel S. Weld, Luke Zettlemoyer, and Omer Levy. 2020. SpanBERT: Improving pre-training by representing and predicting spans. Transactions of the Association for Computational Linguistics, 8:64–77. [71] Daniel Jurafsky and James H Martin. 2021. Speech and language processing: An introduction to natural language processing, computational linguistics, and speech recognition. [72] Łukasz Kaiser, Ofir Nachum, Aurko Roy, and Samy Bengio. 2017. Learning to remember rare events. arXiv preprint arXiv:1703.03129. [73] Nal Kalchbrenner, Edward Grefenstette, and Phil Blunsom. 2014. A convolutional neural network for modelling sentences. In Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 655–665, Baltimore, Maryland. Association for Computational Linguistics. [74] Nora Kassner and Hinrich Sch¨utze. 2020. Negated and misprimed probes for pretrained language models: Birds can talk, but cannot fly. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, ACL 2020, Online, July 5-10, 2020, pages 7811–7818. Association for Computational Linguistics. [75] Nitish Shirish Keskar, Bryan McCann, Lav R. Varshney, Caiming Xiong, and Richard Socher. 2019. CTRL: A conditional transformer language model for controllable generation. CoRR, abs/1909.05858. [76] Daniel Khashabi, Sewon Min, Tushar Khot, Ashish Sabharwal, Oyvind Tafjord, Peter Clark, and Hannaneh Hajishirzi. 2020. UNIFIEDQA: Crossing format boundaries with a single QA system. In Findings of the Associa- tion for Computational Linguistics: EMNLP 2020, pages 1896–1907, Online. Association for Computational Linguistics. 35 References [77] Yuta Kikuchi, Graham Neubig, Ryohei Sasano, Hiroya Takamura, and Manabu Okumura. 2016. Controlling output length in neural encoder-decoders. In Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing, pages 1328–1338, Austin, Texas. Association for Computational Linguistics. [78] Yoon Kim. 2014. Convolutional neural networks for sentence classification. In EMNLP. [79] Tom´aˇs Koˇcisk´y, Jonathan Schwarz, Phil Blunsom, Chris Dyer, Karl Moritz Hermann, G´abor Melis, and Edward Grefenstette. 2018. The NarrativeQA reading comprehension challenge. Transactions of the Association for Computational Linguistics, 6:317–328. [80] Philipp Koehn. 2009. Statistical machine translation. Cambridge University Press. [81] Sotiris B Kotsiantis, I Zaharakis, P Pintelas, et al. 2007. Supervised machine learning: A review of classification techniques. Emerging artificial intelligence applications in computer engineering, 160(1):3–24. [82] Ankit Kumar, Ozan Irsoy, Peter Ondruska, Mohit Iyyer, James Bradbury, Ishaan Gulrajani, Victor Zhong, Romain Paulus, and Richard Socher. 2016. Ask me anything: Dynamic memory networks for natural language processing. In International conference on machine learning, pages 1378–1387. PMLR. [83] Sawan Kumar and Partha Talukdar. 2021. Reordering examples helps during priming-based few-shot learning. [84] J. Lafferty, A. McCallum, and Fernando Pereira. 2001. Conditional random fields: Probabilistic models for segmenting and labeling sequence data. In ICML. [85] Guokun Lai, Qizhe Xie, Hanxiao Liu, Yiming Yang, and Eduard Hovy. 2017. RACE: Large-scale ReAding com- prehension dataset from examinations. In Proceedings of the 2017 Conference on Empirical Methods in Natural Language Processing, pages 785–794, Copenhagen, Denmark. Association for Computational Linguistics. [86] Guillaume Lample and Alexis Conneau. 2019. Cross-lingual language model pretraining. arXiv preprint arXiv:1901.07291. [87] Zhenzhong Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, and Radu Soricut. 2020. ALBERT: A lite BERT for self-supervised learning of language representations. In 8th International Conference on Learning Representations, ICLR 2020, Addis Ababa, Ethiopia, April 26-30, 2020. OpenReview.net. [88] Teven Le Scao and Alexander Rush. 2021. How many data points is a prompt worth? In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 2627–2636, Online. Association for Computational Linguistics. [89] Jinhyuk Lee, Wonjin Yoon, Sungdong Kim, Donghyeon Kim, Sunkyu Kim, Chan Ho So, and Jaewoo Kang. 2019. BioBERT: a pre-trained biomedical language representation model for biomedical text mining. Bioinformatics. [90] Kenton Lee, Luheng He, Mike Lewis, and Luke Zettlemoyer. 2017. End-to-end neural coreference resolution. In Proceedings of the 2017 Conference on Empirical Methods in Natural Language Processing, pages 188–197, Copenhagen, Denmark. Association for Computational Linguistics. [91] Brian Lester, Rami Al-Rfou, and Noah Constant. 2021. The power of scale for parameter-efficient prompt tuning. [92] Hector Levesque, Ernest Davis, and Leora Morgenstern. 2012. The winograd schema challenge. In Thirteenth International Conference on the Principles of Knowledge Representation and Reasoning. [93] Hector J. Levesque. 2011. The winograd schema challenge. In Logical Formalizations of Commonsense Reasoning, Papers from the 2011 AAAI Spring Symposium, Technical Report SS-11-06, Stanford, California, USA, March 21-23, 2011. AAAI. [94] Mike Lewis, Yinhan Liu, Naman Goyal, Marjan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Veselin Stoyanov, and Luke Zettlemoyer. 2020a. BART: Denoising sequence-to-sequence pre-training for natural In Proceedings of the 58th Annual Meeting of the language generation, translation, and comprehension. Association for Computational Linguistics, pages 7871–7880, Online. Association for Computational Linguistics. [95] Patrick S. H. Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich K¨uttler, Mike Lewis, Wen-tau Yih, Tim Rockt¨aschel, Sebastian Riedel, and Douwe Kiela. 2020b. Retrieval-augmented generation for knowledge-intensive NLP tasks. In Advances in Neural Information Process- ing Systems 33: Annual Conference on Neural Information Processing Systems 2020, NeurIPS 2020, December 6-12, 2020, virtual. [96] Xiang Lisa Li and Percy Liang. 2021. Prefix-tuning: Optimizing continuous prompts for generation. arXiv preprint arXiv:2101.00190. 36 References [97] Xiaoya Li, Jingrong Feng, Yuxian Meng, Qinghong Han, Fei Wu, and Jiwei Li. 2020. A unified MRC framework for named entity recognition. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 5849–5859, Online. Association for Computational Linguistics. [98] Bill Yuchen Lin, Wangchunshu Zhou, Ming Shen, Pei Zhou, Chandra Bhagavatula, Yejin Choi, and Xiang Ren. 2020. CommonGen: A constrained text generation challenge for generative commonsense reasoning. In Findings of the Association for Computational Linguistics: EMNLP 2020, pages 1823–1840, Online. Association for Computational Linguistics. [99] Chenxi Liu, Junhua Mao, Fei Sha, and Alan Yuille. 2017a. Attention correctness in neural image captioning. In Proceedings of the AAAI Conference on Artificial Intelligence. [100] Jiachang Liu, Dinghan Shen, Yizhe Zhang, Bill Dolan, Lawrence Carin, and Weizhu Chen. 2021a. What makes good in-context examples for gpt-3? [101] Lemao Liu, Masao Utiyama, Andrew Finch, and Eiichiro Sumita. 2016. Neural machine translation with supervised attention. In Proceedings of COLING 2016, the 26th International Conference on Computational Linguistics: Technical Papers, pages 3093–3102, Osaka, Japan. The COLING 2016 Organizing Committee. [102] Shulin Liu, Yubo Chen, Kang Liu, and Jun Zhao. 2017b. Exploiting argument information to improve event detection via supervised attention mechanisms. In Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 1789–1798. [103] Xiao Liu, Yanan Zheng, Zhengxiao Du, Ming Ding, Yujie Qian, Zhilin Yang, and Jie Tang. 2021b. GPT understands, too. CoRR, abs/2103.10385. [104] Yinhan Liu, Jiatao Gu, Naman Goyal, Xian Li, Sergey Edunov, Marjan Ghazvininejad, Mike Lewis, and Luke Zettlemoyer. 2020a. Multilingual denoising pre-training for neural machine translation. Trans. Assoc. Comput. Linguistics, 8:726–742. [105] Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, M. Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining approach. ArXiv, abs/1907.11692. [106] Yixin Liu, Zi-Yi Dou, and Pengfei Liu. 2021c. RefSum: Refactoring neural summarization. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 1437–1448, Online. Association for Computational Linguistics. [107] Yixin Liu and Pengfei Liu. 2021. Simcls: A simple framework for contrastive learning of abstractive summarization. arXiv preprint arXiv:2106.01890. [108] Zhuang Liu, Degen Huang, Kaiyu Huang, Zhuang Li, and Jun Zhao. 2020b. Finbert: A pre-trained financial language representation model for financial text mining. In Proceedings of the Twenty-Ninth International Joint Conference on Artificial Intelligence, IJCAI 2020, pages 4513–4519. ijcai.org. [109] Robert L. Logan IV, Ivana Balaˇzevi´c, Eric Wallace, Fabio Petroni, Sameer Singh, and Sebastian Riedel. 2021. Cutting down on prompts and parameters: Simple few-shot learning with language models. [110] Jiasen Lu, Dhruv Batra, Devi Parikh, and Stefan Lee. 2019. Vilbert: Pretraining task-agnostic visiolinguistic representations for vision-and-language tasks. In Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada, pages 13–23. [111] Yao Lu, Max Bartolo, A. Moore, S. Riedel, and Pontus Stenetorp. 2021. Fantastically ordered prompts and where to find them: Overcoming few-shot prompt order sensitivity. ArXiv, abs/2104.08786. [112] Xuezhe Ma and Eduard Hovy. 2016. End-to-end sequence labeling via bi-directional LSTM-CNNs-CRF. In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 1064–1074, Berlin, Germany. Association for Computational Linguistics. [113] Andre˘ı Andreevich Markov. 2006. An example of statistical investigation of the text eugene onegin concerning the connection of samples in chains. Science in Context, 19(4):591–600. [114] Yvette Mathieu and Paul Sabatier. 1986. INTERFACILE: Linguistic coverage and query reformulation. In Coling 1986 Volume 1: The 11th International Conference on Computational Linguistics. [115] Bryan McCann, Nitish Shirish Keskar, Caiming Xiong, and Richard Socher. 2018. The natural language decathlon: Multitask learning as question answering. arXiv preprint arXiv:1806.08730. 37 References [116] Michael McCloskey and Neal J Cohen. 1989. Catastrophic interference in connectionist networks: The sequential learning problem. In Psychology of learning and motivation, volume 24, pages 109–165. Elsevier. [117] Tomas Mikolov, Kai Chen, G. Corrado, and J. Dean. 2013a. Efficient estimation of word representations in vector space. In ICLR. [118] Tom´aˇs Mikolov, Martin Karafi´at, Luk´aˇs Burget, Jan ˇCernock`y, and Sanjeev Khudanpur. 2010. Recurrent neural network based language model. In Eleventh annual conference of the international speech communication association. [119] Tomas Mikolov, Ilya Sutskever, Kai Chen, G. Corrado, and J. Dean. 2013b. Distributed representations of words and phrases and their compositionality. In NIPS. [120] Swaroop Mishra, Daniel Khashabi, Chitta Baral, and Hannaneh Hajishirzi. 2021. Natural instructions: Benchmarking generalization to new tasks from natural language instructions. CoRR, abs/2104.08773. [121] Aakanksha Naik, Abhilasha Ravichander, Carolyn Rose, and Eduard Hovy. 2019. Exploring numeracy in word embeddings. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 3374–3380, Florence, Italy. Association for Computational Linguistics. [122] Timothy Niven and Hung-Yu Kao. 2019. Probing neural network comprehension of natural language argu- ments. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 4658–4664, Florence, Italy. Association for Computational Linguistics. [123] Rodrigo Nogueira and Kyunghyun Cho. 2017. Task-oriented query reformulation with reinforcement learning. arXiv preprint arXiv:1704.04572. [124] Rodrigo Frassetto Nogueira, Jannis Bulian, and Massimiliano Ciaramita. 2019. Multi-agent query reformu- lation: Challenges and the role of diversity. ICLR Workshop on Deep Reinforcement Learning for Structured Prediction. [125] Franz Josef Och, Daniel Gildea, Sanjeev Khudanpur, Anoop Sarkar, Kenji Yamada, Alex Fraser, Shankar Kumar, Libin Shen, David Smith, Katherine Eng, Viren Jain, Zhen Jin, and Dragomir Radev. 2004. A smorgasbord of features for statistical machine translation. In Proceedings of the Human Language Technology Conference of the North American Chapter of the Association for Computational Linguistics: HLT-NAACL 2004, pages 161–168, Boston, Massachusetts, USA. Association for Computational Linguistics. [126] Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, and Haifeng Wang. 2020. ERNIE-M: enhanced multilingual representation by aligning cross-lingual semantics with monolingual corpora. CoRR, abs/2012.15674. [127] Bo Pang, Lillian Lee, and Shivakumar Vaithyanathan. 2002. Thumbs up? sentiment classification using machine learning techniques. In Proceedings of the 2002 Conference on Empirical Methods in Natural Language Processing (EMNLP 2002), pages 79–86. Association for Computational Linguistics. [128] Jeffrey Pennington, R. Socher, and Christopher D. Manning. 2014. Glove: Global vectors for word representa- tion. In EMNLP. [129] Ethan Perez, Douwe Kiela, and Kyunghyun Cho. 2021. True few-shot learning with language models. [130] Matthew E. Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, and Luke Zettlemoyer. 2018. Deep contextualized word representations. In Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long Papers), pages 2227–2237, New Orleans, Louisiana. Association for Computational Linguistics. [131] Matthew E. Peters, Sebastian Ruder, and Noah A. Smith. 2019. To tune or not to tune? adapting pretrained representations to diverse tasks. In Proceedings of the 4th Workshop on Representation Learning for NLP (RepL4NLP-2019), pages 7–14, Florence, Italy. Association for Computational Linguistics. [132] Fabio Petroni, Patrick Lewis, Aleksandra Piktus, Tim Rockt¨aschel, Yuxiang Wu, Alexander H. Miller, and Sebastian Riedel. 2020. How context affects language models’ factual predictions. ArXiv, abs/2005.04611. [133] Fabio Petroni, Tim Rockt¨aschel, Sebastian Riedel, Patrick Lewis, Anton Bakhtin, Yuxiang Wu, and Alexander Miller. 2019. Language models as knowledge bases? In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 2463–2473, Hong Kong, China. Association for Computational Linguistics. 38 References [134] Edoardo Maria Ponti, Goran Glavaˇs, Olga Majewska, Qianchu Liu, Ivan Vuli´c, and Anna Korhonen. 2020. XCOPA: A multilingual dataset for causal commonsense reasoning. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 2362–2376, Online. Association for Computational Linguistics. [135] Raul Puri and Bryan Catanzaro. 2019. Zero-shot text classification with generative language models. CoRR, abs/1912.10165. [136] Tingting Qiao, Jianfeng Dong, and Duanqing Xu. 2018. Exploring human-like attention supervision in visual question answering. In Thirty-Second AAAI Conference on Artificial Intelligence. [137] Guanghui Qin and Jason Eisner. 2021. Learning how to ask: Querying LMs with mixtures of soft prompts. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Lin- guistics: Human Language Technologies, pages 5203–5212, Online. Association for Computational Linguistics. [138] Xipeng Qiu, Tianxiang Sun, Yige Xu, Yunfan Shao, Ning Dai, and Xuanjing Huang. 2020. Pre-trained models for natural language processing: A survey. Science China Technological Sciences, pages 1–26. [139] Alec Radford and Karthik Narasimhan. 2018. Improving language understanding by generative pre-training. In arXiv. [140] Alec Radford, Jeffrey Wu, R. Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. In arXiv. [141] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. 2020. Exploring the limits of transfer learning with a unified text-to-text transformer. Journal of Machine Learning Research, 21(140):1–67. [142] Nazneen Fatema Rajani, Bryan McCann, Caiming Xiong, and Richard Socher. 2019. Explain yourself! leveraging language models for commonsense reasoning. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 4932–4942, Florence, Italy. Association for Computational Linguistics. [143] Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, and Percy Liang. 2016. SQuAD: 100,000+ questions for machine comprehension of text. In Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing, pages 2383–2392, Austin, Texas. Association for Computational Linguistics. [144] Alexander J. Ratner, Henry R. Ehrenberg, Zeshan Hussain, Jared Dunnmon, and Christopher R´e. 2017. Learning to compose domain-specific transformations for data augmentation. In Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4-9, 2017, Long Beach, CA, USA, pages 3236–3246. [145] Laria Reynolds and Kyle McDonell. 2021. Prompt programming for large language models: Beyond the few-shot paradigm. In Extended Abstracts of the 2021 CHI Conference on Human Factors in Computing Systems, CHI EA ’21, New York, NY, USA. Association for Computing Machinery. [146] Itsumi Saito, Kyosuke Nishida, Kosuke Nishida, and Junji Tomita. 2020. Abstractive summarization with combination of pre-trained sequence-to-sequence and saliency models. arXiv preprint arXiv:2003.13028. [147] Nikunj Saunshi, Sadhika Malladi, and Sanjeev Arora. 2021. A mathematical exploration of why language models help solve downstream tasks. In 9th International Conference on Learning Representations, ICLR 2021, Virtual Event, Austria, May 3-7, 2021. OpenReview.net. [148] Teven Le Scao and Alexander M Rush. 2021. How many data points is a prompt worth? arXiv preprint arXiv:2103.08493. [149] Timo Schick, Helmut Schmid, and Hinrich Sch¨utze. 2020. Automatically identifying words that can serve as labels for few-shot text classification. In Proceedings of the 28th International Conference on Computational Linguistics, COLING 2020, Barcelona, Spain (Online), December 8-13, 2020, pages 5569–5578. International Committee on Computational Linguistics. [150] Timo Schick and Hinrich Sch¨utze. 2020. Rare words: A major problem for contextualized embeddings and how to fix it by attentive mimicking. In The Thirty-Fourth AAAI Conference on Artificial Intelligence, AAAI 2020, The Thirty-Second Innovative Applications of Artificial Intelligence Conference, IAAI 2020, The Tenth AAAI Symposium on Educational Advances in Artificial Intelligence, EAAI 2020, New York, NY, USA, February 7-12, 2020, pages 8766–8774. AAAI Press. [151] Timo Schick and Hinrich Sch¨utze. 2021. Generating datasets with pretrained language models. arXiv preprint arXiv:2104.07540. 39 References [152] Timo Schick and Hinrich Sch¨utze. 2020. Few-shot text generation with pattern-exploiting training. [153] Timo Schick and Hinrich Sch¨utze. 2021a. Exploiting cloze questions for few shot text classification and natural language inference. [154] Timo Schick and Hinrich Sch¨utze. 2021b. It’s not just size that matters: Small language models are also few-shot learners. [155] Timo Schick, Sahana Udupa, and Hinrich Sch¨utze. 2021. Self-diagnosis and self-debiasing: A proposal for reducing corpus-based bias in nlp. [156] Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016a. Controlling politeness in neural machine translation via side constraints. In Proceedings of the 2016 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 35–40, San Diego, California. Association for Computational Linguistics. [157] Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016b. Improving neural machine translation models with monolingual data. In Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 86–96, Berlin, Germany. Association for Computational Linguistics. [158] Richard Shin, C. H. Lin, Sam Thomson, Charles Chen, Subhro Roy, Emmanouil Antonios Platanios, Adam Pauls, D. Klein, J. Eisner, and Benjamin Van Durme. 2021. Constrained language models yield few-shot semantic parsers. ArXiv, abs/2104.08768. [159] Taylor Shin, Yasaman Razeghi, Robert L. Logan IV, Eric Wallace, and Sameer Singh. 2020. AutoPrompt: Eliciting knowledge from language models with automatically generated prompts. In Empirical Methods in Natural Language Processing (EMNLP). [160] Jake Snell, Kevin Swersky, and Richard S. Zemel. 2017. Prototypical networks for few-shot learning. In Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4-9, 2017, Long Beach, CA, USA, pages 4077–4087. [161] Richard Socher, Alex Perelygin, Jean Wu, Jason Chuang, Christopher D Manning, Andrew Y Ng, and Christopher Potts. 2013. Recursive deep models for semantic compositionality over a sentiment treebank. In Proceedings of the 2013 conference on empirical methods in natural language processing, pages 1631–1642. [162] Kaitao Song, Xu Tan, Tao Qin, Jianfeng Lu, and Tie-Yan Liu. 2019. MASS: masked sequence to sequence pre-training for language generation. In Proceedings of the 36th International Conference on Machine Learning, ICML 2019, 9-15 June 2019, Long Beach, California, USA, volume 97 of Proceedings of Machine Learning Research, pages 5926–5936. PMLR. [163] Ekta Sood, Simon Tannert, Philipp Mueller, and Andreas Bulling. 2020. Improving natural language processing tasks with human gaze-guided neural attention. Advances in Neural Information Processing Systems, 33:6327– 6341. [164] Weijie Su, Xizhou Zhu, Yue Cao, Bin Li, Lewei Lu, Furu Wei, and Jifeng Dai. 2020. VL-BERT: pre-training of generic visual-linguistic representations. In 8th International Conference on Learning Representations, ICLR 2020, Addis Ababa, Ethiopia, April 26-30, 2020. OpenReview.net. [165] Yusuke Sugano and Andreas Bulling. 2016. Seeing with humans: Gaze-assisted neural image captioning. arXiv preprint arXiv:1608.05203. [166] Chen Sun, Austin Myers, Carl Vondrick, Kevin Murphy, and Cordelia Schmid. 2019a. Videobert: A joint model for video and language representation learning. In 2019 IEEE/CVF International Conference on Computer Vision, ICCV 2019, Seoul, Korea (South), October 27 - November 2, 2019, pages 7463–7472. IEEE. [167] Yu Sun, Shuohuan Wang, Shikun Feng, Siyu Ding, Chao Pang, Junyuan Shang, Jiaxiang Liu, Xuyi Chen, Yanbin Zhao, Yuxiang Lu, Weixin Liu, Zhihua Wu, Weibao Gong, Jianzhong Liang, Zhizhou Shang, Peng Sun, Wei Liu, Xuan Ouyang, Dianhai Yu, Hao Tian, Hua Wu, and Haifeng Wang. 2021. ERNIE 3.0: Large-scale knowledge enhanced pre-training for language understanding and generation. CoRR, abs/2107.02137. [168] Yu Sun, Shuohuan Wang, Yu-Kun Li, Shikun Feng, Hao Tian, Hua Wu, and Haifeng Wang. 2020. ERNIE 2.0: A continual pre-training framework for language understanding. In The Thirty-Fourth AAAI Conference on Artificial Intelligence, AAAI 2020, The Thirty-Second Innovative Applications of Artificial Intelligence Conference, IAAI 2020, The Tenth AAAI Symposium on Educational Advances in Artificial Intelligence, EAAI 2020, New York, NY, USA, February 7-12, 2020, pages 8968–8975. AAAI Press. 40 References [169] Yu Sun, Shuohuan Wang, Yukun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, and Hua Wu. 2019b. Ernie: Enhanced representation through knowledge integration. arXiv preprint arXiv:1904.09223. [170] Derek Tam, Rakesh R Menon, Mohit Bansal, Shashank Srivastava, and Colin Raffel. 2021. Improving and simplifying pattern exploiting training. [171] Kai Ming Ting and Ian H. Witten. 1997. Stacked generalizations: When does it work? In Proceedings of the Fifteenth International Joint Conference on Artificial Intelligence, IJCAI 97, Nagoya, Japan, August 23-29, 1997, 2 Volumes, pages 866–873. Morgan Kaufmann. [172] Erik F. Tjong Kim Sang and Fien De Meulder. 2003. Introduction to the CoNLL-2003 shared task: Language- independent named entity recognition. In Proceedings of the Seventh Conference on Natural Language Learning at HLT-NAACL 2003, pages 142–147. [173] Trieu H. Trinh and Quoc V. Le. 2018. A simple method for commonsense reasoning. CoRR, abs/1806.02847. [174] Maria Tsimpoukelli, Jacob Menick, Serkan Cabi, S. M. Ali Eslami, Oriol Vinyals, and Felix Hill. 2021. Multimodal few-shot learning with frozen language models. CoRR, abs/2106.13884. [175] Svitlana Vakulenko, Shayne Longpre, Zhucheng Tu, and Raviteja Anantha. 2020. A wrong answer or a wrong question? an intricate relationship between question reformulation and answer selection in conversational question answering. In Proceedings of the 5th International Workshop on Search-Oriented Conversational AI (SCAI), pages 7–16, Online. Association for Computational Linguistics. [176] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in neural information processing systems, pages 5998–6008. [177] Eric Wallace, Shi Feng, Nikhil Kandpal, Matt Gardner, and Sameer Singh. 2019a. Universal adversarial triggers for attacking and analyzing NLP. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing, EMNLP- IJCNLP 2019, Hong Kong, China, November 3-7, 2019, pages 2153–2162. Association for Computational Linguistics. [178] Eric Wallace, Yizhong Wang, Sujian Li, Sameer Singh, and Matt Gardner. 2019b. Do NLP models know numbers? probing numeracy in embeddings. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), pages 5307–5315, Hong Kong, China. Association for Computational Linguistics. [179] Xiaozhi Wang, Tianyu Gao, Zhaocheng Zhu, Zhengyan Zhang, Zhiyuan Liu, Juanzi Li, and Jian Tang. 2021. KEPLER: A unified model for knowledge embedding and pre-trained language representation. Trans. Assoc. Comput. Linguistics, 9:176–194. [180] Yaqing Wang, Quanming Yao, James T Kwok, and Lionel M Ni. 2020. Generalizing from a few examples: A survey on few-shot learning. ACM Computing Surveys (CSUR), 53(3):1–34. [181] Colin Wei, Sang Michael Xie, and Tengyu Ma. 2021. Why do pretrained language models help in downstream tasks? an analysis of head and prompt tuning. [182] Wei Wu, Fei Wang, Arianna Yuan, Fei Wu, and Jiwei Li. 2020. CorefQA: Coreference resolution as query- In Proceedings of the 58th Annual Meeting of the Association for Computational based span prediction. Linguistics, pages 6953–6963, Online. Association for Computational Linguistics. [183] Dongling Xiao, Yu-Kun Li, Han Zhang, Yu Sun, Hao Tian, Hua Wu, and Haifeng Wang. 2021. Ernie- gram: Pre-training with explicitly n-gram masked language modeling for natural language understanding. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, NAACL-HLT 2021, Online, June 6-11, 2021, pages 1702–1715. Association for Computational Linguistics. [184] Han Xu, Zhang Zhengyan, Ding Ning, Gu Yuxian, Liu Xiao, Huo Yuqi, Qiu Jiezhong, Zhang Liang, Han Wen- tao, Huang Minlie, et al. 2021. Pre-trained models: Past, present and future. arXiv preprint arXiv:2106.07139. [185] Linting Xue, Aditya Barua, Noah Constant, Rami Al-Rfou, Sharan Narang, Mihir Kale, Adam Roberts, and Colin Raffel. 2021a. Byt5: Towards a token-free future with pre-trained byte-to-byte models. CoRR, abs/2105.13626. 41 References [186] Linting Xue, Noah Constant, Adam Roberts, Mihir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, and Colin Raffel. 2021b. mt5: A massively multilingual pre-trained text-to-text transformer. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, NAACL-HLT 2021, Online, June 6-11, 2021, pages 483–498. Association for Computational Linguistics. [187] Jheng-Hong Yang, Sheng-Chieh Lin, Rodrigo Nogueira, Ming-Feng Tsai, Chuan-Ju Wang, and Jimmy Lin. 2020. Designing templates for eliciting commonsense knowledge from pretrained sequence-to-sequence models. In Proceedings of the 28th International Conference on Computational Linguistics, pages 3449–3453, Barcelona, Spain (Online). International Committee on Computational Linguistics. [188] Zhilin Yang, Zihang Dai, Yiming Yang, Jaime G. Carbonell, Ruslan Salakhutdinov, and Quoc V. Le. 2019. Xlnet: Generalized autoregressive pretraining for language understanding. In Advances in Neural Information Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada, pages 5754–5764. [189] Pengcheng Yin, Graham Neubig, Wen-tau Yih, and Sebastian Riedel. 2020. Tabert: Pretraining for joint understanding of textual and tabular data. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, ACL 2020, Online, July 5-10, 2020, pages 8413–8426. Association for Computational Linguistics. [190] Wenpeng Yin, Jamaal Hay, and Dan Roth. 2019. Benchmarking zero-shot text classification: Datasets, evaluation and entailment approach. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing, EMNLP- IJCNLP 2019, Hong Kong, China, November 3-7, 2019, pages 3912–3921. Association for Computational Linguistics. [191] Wenhao Yu, Chenguang Zhu, Zaitang Li, Zhiting Hu, Qingyun Wang, Heng Ji, and Meng Jiang. 2020. A survey of knowledge-enhanced text generation. arXiv preprint arXiv:2010.04389. [192] Weizhe Yuan, Pengfei Liu, and Graham Neubig. 2021a. Can we automate scientific reviewing? arXiv preprint arXiv:2102.00176. [193] Weizhe Yuan, Graham Neubig, and Pengfei Liu. 2021b. Bartscore: Evaluating generated text as text generation. [194] Wei Zeng, Xiaozhe Ren, Teng Su, Hui Wang, Yi Liao, Zhiwei Wang, Xin Jiang, ZhenZhang Yang, Kaisheng Wang, Xiaoda Zhang, Chen Li, Ziyan Gong, Yifan Yao, Xinjing Huang, Jun Wang, Jianfeng Yu, Qi Guo, Yue Yu, Yan Zhang, Jin Wang, Hengtao Tao, Dasen Yan, Zexuan Yi, Fang Peng, Fangqing Jiang, Han Zhang, Lingfeng Deng, Yehong Zhang, Zhe Lin, Chao Zhang, Shaojie Zhang, Mingyue Guo, Shanzhi Gu, Gaojun Fan, Yaowei Wang, Xuefeng Jin, Qun Liu, and Yonghong Tian. 2021. Pangu-α: Large-scale autoregressive pretrained chinese language models with auto-parallel computation. [195] Jingqing Zhang, Yao Zhao, Mohammad Saleh, and Peter J. Liu. 2020a. PEGASUS: pre-training with extracted gap-sentences for abstractive summarization. In Proceedings of the 37th International Conference on Machine Learning, ICML 2020, 13-18 July 2020, Virtual Event, volume 119 of Proceedings of Machine Learning Research, pages 11328–11339. PMLR. [196] Ruohan Zhang, Akanksha Saran, Bo Liu, Yifeng Zhu, Sihang Guo, Scott Niekum, Dana Ballard, and Mary Hayhoe. 2020b. Human gaze assisted artificial intelligence: a review. In IJCAI: Proceedings of the Conference, volume 2020, page 4951. NIH Public Access. [197] Yue Zhang and Joakim Nivre. 2011. Transition-based dependency parsing with rich non-local features. In Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies, pages 188–193, Portland, Oregon, USA. Association for Computational Linguistics. [198] Zhengyan Zhang, Yuxian Gu, Xu Han, Shengqi Chen, Chaojun Xiao, Zhenbo Sun, Yuan Yao, Fanchao Qi, Jian Guan, Pei Ke, Yanzheng Cai, Guoyang Zeng, Zhixing Tan, Zhiyuan Liu, Minlie Huang, Wentao Han, Yang Liu, Xiaoyan Zhu, and Maosong Sun. 2021. CPM-2: large-scale cost-effective pre-trained language models. CoRR, abs/2106.10715. [199] Zhengyan Zhang, Xu Han, Zhiyuan Liu, Xin Jiang, Maosong Sun, and Qun Liu. 2019. ERNIE: enhanced language representation with informative entities. In Proceedings of the 57th Conference of the Association for Computational Linguistics, ACL 2019, Florence, Italy, July 28- August 2, 2019, Volume 1: Long Papers, pages 1441–1451. Association for Computational Linguistics. [200] Zhengyan Zhang, Xu Han, Hao Zhou, Pei Ke, Yuxian Gu, Deming Ye, Yujia Qin, YuSheng Su, Haozhe Ji, Jian Guan, Fanchao Qi, Xiaozhi Wang, Yanan Zheng, Guoyang Zeng, Huanqi Cao, Shengqi Chen, Daixuan Li, Zhenbo Sun, Zhiyuan Liu, Minlie Huang, Wentao Han, Jie Tang, Juanzi Li, Xiaoyan Zhu, and Maosong Sun. 2020c. CPM: A large-scale generative chinese pre-trained language model. CoRR, abs/2012.00413. 42 References [201] Tony Z. Zhao, Eric Wallace, Shi Feng, Dan Klein, and Sameer Singh. 2021. Calibrate before use: Improving few-shot performance of language models. [202] Ruiqi Zhong, Kristy Lee, Zheng Zhang, and Dan Klein. 2021a. Meta-tuning language models to answer prompts better. arXiv preprint arXiv:2104.04670. [203] Zexuan Zhong, Dan Friedman, and Danqi Chen. 2021b. Factual probing is [MASK]: learning vs. learning to recall. CoRR, abs/2104.05240. [204] Zhi-Hua Zhou, Jianxin Wu, and Wei Tang. 2002. Ensembling neural networks: many could be better than all. Artificial intelligence, 137(1-2):239–263. [205] Chenguang Zhu, William Hinthorn, Ruochen Xu, Qingkai Zeng, Michael Zeng, Xuedong Huang, and Meng Jiang. 2020. Enhancing factual consistency of abstractive summarization. arXiv preprint arXiv:2003.08612. [206] Geoffrey Zweig, John C. Platt, Christopher Meek, Christopher J.C. Burges, Ainur Yessenalina, and Qiang Liu. 2012. Computational approaches to sentence completion. In Proceedings of the 50th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 601–610, Jeju Island, Korea. Association for Computational Linguistics. 43 # A Appendix on Pre-trained LMs In this appendix we present some auxiliary information on pre-trained LMs that may be useful to the readers to better understand the current lay of the land with respect to this dynamic research area. # A.1 Evolution of Pre-trained LM Parameters Fig. 7 lists several popular pre-trained models’ statistics of parameters, ranging from 0 to 200 billion. GPT3, CPM2, and PanGu-α are the top three largest models with parameters greater than 150 billion. 198 200 200 os 100 100 0 0.110.120.24 0:3 0:3 0:3 0.840.34 0:4 0:8 0:8 1:5 216 1p i Al n sno ao Noam OMA SG SER 4EBRSREAQSESRERSES S BxeEBSSR eH 225225 BUSES ZaAae Rama "khOOZ 6 VOR fe =a) ia) [aa] rs) s [ea] < e [ea] a Figure 7: Comparison of the size of existing popular pre-trained language models. # A.2 Auxiliary Objective In this subsection, more auxiliary objectives for pre-training language models have been listed. • Next Sentence Prediction (NSP) (Devlin et al., 2019): A binary classification loss predicting whether two segments appear consecutively within a larger document, or are random unrelated sentences. • Sentence Order Prediction (SOP) (Lan et al., 2020): A binary classification loss for predicting whether two sentences are in a natural or swapped order. • Capital Word Prediction (CWP) (Liu et al., 2020b): A binary classification objective calculated over each word, predicting whether whether each word is capitalized or not. • Sentence Deshuffling (SDS) (Liu et al., 2020b): A multi-class classification task to reorganize permuted segments. • Sentence distance prediction (SDP) (Liu et al., 2020b) : A three-class classification task, predicting the positional relationship between two sentences (adjacent in the same document, not adjacent but in the same document, in different documents). • Masked Column Prediction (MCP) (Yin et al., 2020): Given a table, recover the names and data types of masked columns. • Linguistic-Visual Alignment (LVA) (Lu et al., 2019): A binary classification to Predict whether the text content can be aligned to visual content. • Image Region prediction (IRP) (Su et al., 2020): Given an image whose partial features are masked (zeroed out), predict the masked regions. • Replaced Token Detection (RTD) (Xiao et al., 2021): A binary classification loss predicting whether each token in corrupted input was replaced by a generative sample or not. • Discourse Relation Prediction (DRP) (Sun et al., 2020): Predict the semantic or rhetorical relation between two sentences. • Translation Language Modeling (TLM) (Lample and Conneau, 2019): Consider parallel sentences and mask words randomly in both source and target sentences. • Information Retrieval Relevance (IRR) (Sun et al., 2020): Predict the information retrieval relevance of two sentences. • Token-Passage Prediction (TPP) (Liu et al., 2020b): Identify the keywords of a passage appearing in the segment. • Universal Knowledge-Text Prediction (UKTP) (Sun et al., 2021): Incorporate knowledge into one pre-trained language model. • Machine Translation (MT) (Chi et al., 2021a) : Translate a sentence from the source language into the target language. • Translation Pair Span Corruption (TPSC) (Chi et al., 2021a) : Predict the masked spans from a translation pair. • Translation Span Corruption (TSC) (Chi et al., 2021a) : Unlike TPSC, TSC only masks and predicts the spans in one language. 44 aa A.3 Pre-trained Language Model Families • Multilingual Replaced Token Detection (MRTD) (Chi et al., 2021b): Distinguish real input tokens from corrupted multilingual sentences by a Generative Adversarial Network, where both the generator and the discriminator are shared across languages. • Translation Replaced Token Detection (TRTD) (Chi et al., 2021b): Distinguish the real tokens and masked tokens in the translation pair by the Generative Adversarial Network. • Knowledge Embedding (KE) (Wang et al., 2021): Encode entities and relations in knowledge graphs (KGs) as distributed representations • Image-to-text transfer (ITT) (Wang et al., 2021): Is similar to the image caption that generates a corresponding description for the input image. • Multimodality-to-text transfer (MTT) (Wang et al., 2021): Generate the target text based on both the visual information and the noised linguistic information. Da # A.3 Pre-trained Language Model Families The increasing number of models makes it difficult for people to clearly grasp the differences between them. Based on this, we cluster the current mainstream pre-training models and characterize them from diverse dimensions. 45 aa A.3 Pre-trained Language Model Families Pre-training Tasks Corruption Family Models TM Main Auxiliary Parallel Mask Replace Delete Permute ‘“PPlication GPT [139] L2R SLM : x - : : - NLG Get GPT-2 [140] L2R SLM : x - : : - NLG GPT-3 [16] L2R SLM : x. : : - NLG Codex [20] L2R SLM : x - : : - NLG ELMo S& ELMo [130] L2R SLM : x - : : - NLU, NLG BERT [32] Mask CTR NSP XK Tok : : - NLU RoBERTa [105] Mask CTR : XK Tok : : - NLU SpanBERT [70] Mask CTR : X Span : : - NLU DeBERTa [60] Mask CTR : XK Tok : : - NLU SciBERT [7] Mask CTR NSP XK Tok : : - Sci-NLU BioBERT [89] Mask CTR NSP XK Tok : : - Bio-NLU peer 8 ALBERT [87] Mask CTR SOP XK Tok : : - mSent CWP, SDS, . FinBERT [108] Mask CTR SDP. TPP X Span : : Sent Fin-NLU VLBERT [164] Mask CTR IRP VY Tok, Region : : - VLU ViLBERT [110] Mask CTR IRP, LVA VY Tok, Region : : - VLU BEIT [5] Mask CTRFTR - X Visual “Tok”” : : - VLU VideoBERT [166] Mask CTR LVA VY Tok, Frame : : - VLU TaBERT [189] Mask CTR MCP Y= Tok, Column : : - Tab2Text mBERT [32] Mask CTR NSP XK Tok : : - XLU TinyBERT [69] Mask CTR NSP XK Tok : : - XLU ERNIE-T [199] Mask CTR NSP X Tok, Entity : : - NLU ERNIE-B [169] Mask CTR : X — Tok.Entity, Phrase - : - NLU ? ERNIE-NG [183] Mask CTR RTD X N-gram Tok : - NLU ERNIE CWP,SDS,SOP, ERNIE-B2 [168] Mask CTR SDPDRPIRR X Entity, Phrase : : Sent NLU ERNIE-M [126] LPM CTR : ¥ Tok : : XLU, XLG ERNIE-B3 [167] Mask CTR SOPSDPUKTP X Entity, Phrase : : - NLU _ BART [94] En-De FTR : XK Tok Span Tok Sent,Doc NLU, NLG BART! — mBART [104] En-De FTR : X Span : : Sent NLG UniLMI [35] LPM SLM,CTR__NSP XK Tok : : - NLU, NLG UniLM UniLM2 [6] LPM SLM.CTR - xK Tok - - Tok NLU, NLG TS [141] En-De CTR : x - Span : - NLU, NLG Ts mT [186] En-De CTR : x. Span : - XLU, XLG mT6 [22] En-De CTR MT,TPSC,TSC vo. Span : - XLU, XLG ByTS [185] En-De CTR : x - byte-span - XLU, XLG XLM [86] LPM CTR TLM ¥ Tok : : - XLU, XLG XLM XLMLR [28] Mask CTR - XK Tok - - - XLU XLM-E [23] Mask CTR MRTD,TRTD x - Tok : - XLU, XLG CPM [200] L2R SLM : x - : : - NLG CPM CPM-2 [198] En-De CTR - X Span - - - NLU,NLG XLNet [188] L2R SLM : x - : : Tok NLU PanGu- [194] L2R SLM : x - : : - NLG ELECTRA [26] Mask CTR RTD XK Tok Tok : - NLU,NLG Other MASS [162] En-De CTR : X Span : : - NLG PEGASUS [195] En-De CTR : X Tok, Sent : : - Summarization M6 [179] En-De CTR ITT.MTT X Span : : - NLG Table 13: A detailed illustration of different pre-trained models characterized by the four aspects. “Parallel” represents if parallel data have been used for pre-training. Sci, Bio, Fin, K represent scientific, biomedical, financial, and knowledge, respectively. Tok, Sent, Doc denote token, sentence and document, respectively. Region, Frame denote basic units of images and video respectively. 46
Title: Poisoning Web-Scale Training Datasets is Practical: Summary: Deep learning models are often trained on distributed, webscale datasets crawled from the internet. In this paper, we introduce two new dataset poisoning attacks that intentionally introduce malicious examples to a model's performance. Our attacks are immediately practical and could, today, poison 10 popular datasets. Our first attack, split-view poisoning, exploits the mutable nature of internet content to ensure a dataset annotator's initial view of the dataset differs from the view downloaded by subsequent clients. By exploiting specific invalid trust assumptions, we show how we could have poisoned 0.01% of the LAION-400M or COYO-700M datasets for just $60 USD. Our second attack, frontrunning poisoning, targets web-scale datasets that periodically snapshot crowd-sourced content -- such as Wikipedia -- where an attacker only needs a time-limited window to inject malicious examples. In light of both attacks, we notify the maintainers of each affected dataset and recommended several low-overhead defenses. # Poisoning Web-Scale Training Datasets is Practical Nicholas Carlini1 Matthew Jagielski1 Christopher A. Choquette-Choo1 Daniel Paleka2 Will Pearce3 Hyrum Anderson4 Andreas Terzis1 Kurt Thomas1 Florian Tramèr2 1Google 2ETH Zurich 3NVIDIA 4Robust Intelligence # Abstract Deep learning models are often trained on distributed, web- scale datasets crawled from the internet. In this paper, we introduce two new dataset poisoning attacks that intentionally introduce malicious examples to a model’s performance. Our attacks are immediately practical and could, today, poison 10 popular datasets. Our first attack, split-view poisoning, ex- ploits the mutable nature of internet content to ensure a dataset annotator’s initial view of the dataset differs from the view downloaded by subsequent clients. By exploiting specific in- valid trust assumptions, we show how we could have poisoned 0.01% of the LAION-400M or COYO-700M datasets for just $60 USD. Our second attack, frontrunning poisoning, targets web-scale datasets that periodically snapshot crowd-sourced content—such as Wikipedia—where an attacker only needs a time-limited window to inject malicious examples. In light of both attacks, we notify the maintainers of each affected dataset and recommended several low-overhead defenses. real-world attacks involving poisoning of web-scale datasets have occurred. One explanation is that prior research ignores the question of how an adversary would ensure that their cor- rupted data would be incorporated into a web-scale dataset. In this paper, we introduce two novel poisoning attacks that guarantee malicious examples will appear in web-scale datasets used for training the largest machine learning models in production today. Our attacks exploit critical weaknesses in the current trust assumptions of web-scale datasets: due to a combination of monetary, privacy, and legal restrictions, many existing datasets are not published as static, standalone artifacts. Instead, datasets either consist of an index of web content that individual clients must crawl; or a periodic snap- shot of web content that clients download. This allows an attacker to know with certainty what web content to poison (and, as we will show, even when to poison this content). Our two attacks work as follows: # 1 Introduction Datasets used to train deep learning models have grown from thousands of carefully-curated examples [20, 33, 41] to web- scale datasets with billions of samples automatically crawled from the internet [10, 48, 53, 57]. At this scale, it is infeasible to manually curate and ensure the quality of each example. This quantity-over-quality tradeoff has so far been deemed ac- ceptable, both because modern neural networks are extremely resilient to large amounts of label noise [55, 83], and because training on noisy data can even improve model utility on out-of-distribution data [50, 51]. While large deep learning models are resilient to random noise, even minuscule amounts of adversarial noise in train- ing sets (i.e., a poisoning attack [6]) suffices to introduce targeted mistakes in model behavior [14, 15, 60, 76]. These prior works argued that poisoning attacks on modern deep learning models are practical due to the lack of human cura- tion. Yet, despite the potential threat, to our knowledge no • Split-view data poisoning: Our first attack targets cur- rent large datasets (e.g., LAION-400M) and exploits the fact that the data seen by the dataset curator at collection time might differ (significantly and arbitrarily) from the data seen by the end-user at training time. This attack is feasible due to a lack of (cryptographic) integrity pro- tections: there is no guarantee that clients observe the same data when they crawl a page as when the dataset maintainer added it to the index. • Frontrunning data poisoning: Our second attack ex- ploits popular datasets that consists of periodical snap- shots of user-generated content—e.g., Wikipedia snap- shots. Here, if an attacker can precisely time malicious modifications just prior to a snapshot for inclusion in a web-scale dataset, they can front-run the collection pro- cedure. This attack is feasible due to predictable snap- shot schedules, latency in content moderation, and snap- shot immutability: even if a content moderator detects and reverts malicious modifications after-the-fact, the attacker’s malicious content will persist in the snapshot used for training deep learning models. 1 We explore the feasibility of both of these attacks in prac- tice on 10 popular web-scale datasets. We show these at- tacks are practical and realistic even for a low-resourced at- tacker: for just $60 USD, we could have poisoned 0.01% of the LAION-400M or COYO-700M datasets in 2022. To counteract these attacks, we propose two defenses: • Integrity verification prevents split-view poisoning by distributing cryptographic hashes for all indexed content, thus ensuring that clients observe the same data as when maintainers first indexed and annotated it. • Timing-based defenses prevent frontrunning poisoning by either randomizing the order in which data is snap- shotted and introduced into web-scale datasets; or de- laying content prior to its inclusion into a snapshot and applying reversions from trusted moderators. We discuss limitations of these defenses (e.g., in the case of integrity checks, preventing benign modifications such as re-encoding, re-sizing, or cropping images) and more robust, future-looking solutions with fewer trust assumptions. Responsible disclosure. We disclosed our results to the main- tainers of each of the 10 datasets appearing in this study. Six of these datasets now follow our recommended implementa- tion for integrity checks. Additionally, we provided patches to the most popular web-scale dataset downloader to support integrity checks. Finally, we have notified Wikipedia about the frontrunning vulnerability in their data collection process. # 2 Background & Related Work Our work builds on existing knowledge of the risk of poison- ing web-scale datasets, but focuses on the practical exploit vectors to launch such an attack. We outline why web-scale datasets have become of critical importance, known security risks of web-scale datasets, as well as auxiliary dataset quality issues that stem from ingesting uncurated data into models. Momentum towards uncurated datasets. Deep learning is most effective when applied to large datasets [10, 30]. But curating such datasets is expensive. Even without manual labeling, the availability of training data has become a limiting factor for further improving model utility. For example, the scaling laws observed in the recent Chinchilla [27] language model indicate that training a compute-optimal 500 billion parameter model would require 11 trillion tokens of training data—over 10× more data than is currently used to train models of this size [19]. To drastically scale dataset sizes, it has become common to scrape data from a wider and wider range of untrusted and uncurated web sources. Security risk of poisoning attacks. Uncurated training datasets are prime targets for poisoning attacks [6]. For exam- ple, an adversary could modify the training dataset (“poison- ing” it) so that some targeted example will be misclassified 2 by models trained on this dataset. Early poisoning attacks were designed to target fully-supervised classifiers [18,24,64] trained on curated datasets. These attacks often aim to be “stealthy”, by altering data points in a manner indiscernible to human annotators [74]. Attacks on uncurated datasets do not require this strong property. Recent work [14, 15] shows that arbitrarily poisoning only 0.001% of uncurated web-scale training datasets is sufficient to induce targeted model mis- takes, or plant model “backdoors” [18, 24]. It is thus known that if an adversary were somehow able to poison a fraction of a web-scale dataset, then they could cause significant harm. However, it is not well understood how an adversary could place their poisoned samples in any common training dataset without guessing beforehand which parts of the web will be collected. This paper answers that question. Auxiliary risks related to data quality. Spending time and effort to curate datasets has benefits besides security. Possibly most important among these is that uncurated data has seri- ous implications for fairness, bias, and ethics [8, 50, 77]. For example, Birhane et al. [7] note that LAION-400M has “trou- blesome and explicit images and text pairs of rape, pornog- raphy, malign stereotypes, racist and ethnic slurs, and other extremely problematic content”. Many language datasets also contain similarly harmful “hate speech and sexually explicit content, even after filtering” [40]. Dataset curation is not a perfect solution to these problems. Birhane et al. [7] note, “without careful contextual analysis, filtering mechanisms are likely to censor and erase marginal- ized experiences”. Any filtering approaches that selectively remove some data sources over others should carefully con- sider not only the security implications of doing this, but also other more general data quality metrics. # 3 Threat Model & Attack Scenarios Before presenting the implementation details of our attacks, we introduce key terminology, our threat model, and a high- level description of the intuition behind our two attacks. # 3.1 Terminology Because it is infeasible to distribute web-scale datasets as standalone artifacts (due to the dataset size or regulatory con- cerns), current training datasets fall into one of two categories. In the first category, a maintainer generates a set of N tu- ples {(urli, ci)}N i=1 consisting of a resource identifier urli and auxiliary data ci (typically a label). We let ti denote the time at which the i-th sample was originally collected. Critically, the maintainer does not provide a snapshot of the data associated with urli, due either to untenable storage costs [3,4,17,31], pri- vacy concerns [13, 72], or copyright limitations [16]. As such, we refer to these as distributed datasets. One example is the LAION-5B dataset [57] which consists of five billion tuples of image URLs and corresponding text captions—corresponding to several hundred terabytes of data. In the second category of datasets, a curator produces a snapshot of a dataset {xi}N i=1, where each sample xi is drawn from a set of URLs {urli}N i=1 at time ti, and then makes this snapshot publicly available. Because data served by these URLs changes over time, the curator will frequently (e.g., monthly) re-collect a dataset snapshot so that users have an up-to-date view of the data. We refer to these as centralized datasets. For example, both Wikipedia and Common Crawl regularly produce snapshots of their entire database. This simplifies access for people training large models, while also discouraging researchers from re-scraping the database di- rectly. Once one of these two types of datasets has been published, a client (e.g., a researcher or applied practitioner) downloads a local copy of the training dataset D, either by crawling each URL for decentralized datasets {(url;,c;)}%_, at a future time 1 > t;, or by downloading the centralized dataset {x;}¥_,. In practice, clients often use a downloader tool developed and maintained by a third party. # 3.2 Threat Model We assume the existence of a relatively unskilled, low- resource adversary who can tamper with the contents of a small number of URLs {url;}¥_, at some point in time §;, such that when a client or curator accesses resource i at a future time t/ > 7;, they receive a modified (poisoned) dataset D! 4 D. The difference between the poisoned and intended datasets must be sufficiently large such that a model f trained on D’ will produce poisoned results for some desired input. We let Saav C {url;}*_, denote the set of URLs an adversary can modify. We assume the adversary has no specialized or insider knowledge about the curator, downloader, or maintainer other than knowledge of the set of URLs {urli}N i=1 used to generate D (this information is published by the dataset maintainer or curator). We further assume all maintainers, curators and downloaders behave honestly and do not assist the adversary in any way. As such, the adversary has no control over the auxiliary data ci (e.g., supervised labels or text descriptions), nor can they add or remove any URLs from the training data that will be crawled by a client or curator. We make two critical (yet realistic) assumptions that enable our attacks. For distributed datasets, we assume that clients do not compare the cryptographic integrity of the local dataset copy 2’ that they downloaded, with the original dataset D indexed by the maintainer. For centralized datasets, we as- sume that it takes the curator at least some time A to detect malicious changes to the content hosted at any URL url; in the dataset (e.g., for Wikipedia, A is the time it takes to revert a malicious edit). Thus, the curator cannot detect that url; hosts poisoned content if the attacker poisoned the content 3 at any time ti − ∆ ≤ ˆti ≤ ti, where ti is the time at which the content of urli is included in the dataset snapshot. As we will show, these assumptions holds true for nearly all modern web- scale datasets. We discuss (in Section 6) how invalidating these assumptions—via cryptographic integrity checks and randomized crawling—can mitigate the attacks we describe. # 3.3 Attack Scenarios We propose two attack strategies for poisoning recent web- scale datasets. In the subsequent sections we demonstrate the efficacy of these attacks in practice on real-world datasets, and describe the ethical safeguards we followed to minimize harm. We focus our attacks on mechanisms that are unique to our study of dataset poisoning. Other potential security vulnerabilities (e.g., the ability of an adversary to interfere with unencrypted network requests from clients, or to exploit website vulnerabilities to inject new content) are out of scope and would only improve our attack success rates. Split-view poisoning. Our first attack exploits the fact that while the index of a distributed dataset published by a main- tainer cannot be modified, the content of URLs in the dataset can.1 This allows an adversary who can exert sustained con- trol over a web resource indexed by the dataset to poison the resulting collected dataset collected by the end-user. The specific vulnerability we exploit in our attack results from a fairly simple observation: just because a web page hosted benign content when the dataset was initially collected, this does not mean the same page is currently hosting benign content. In particular, domain names occasionally expire— and when they do, anyone can buy them. We show that domain name expiration is exceptionally common in large datasets. The adversary does not need to know the exact time at which clients will download the resource in the future: by owning the domain the adversary guarantees that any future download will collect poisoned data. We note that attackers already routinely buy expired do- mains to hijack the residual trust attached with these do- mains [35, 39, 67]. Attackers have in the past targeted residual trust to defunct banking domains [44] and imported JavaScript libraries [47] to serve malware or steal user data, to take over email addresses associated with the domain [56], to control au- thoritative nameservers [39], or simply to serve ads [36]. Here, we abuse residual trust to poison distributed datasets. While more sophisticated attacks may accomplish the same goal— such as exploiting a website, coercing a website’s owner to modify content, or modifying unencrypted network traffic in flight—we focus on the natural phenomenon of domain expiration in this work. To select domains to purchase, the adversary can either pri- oritize cheap domains that host multiple URLs in the dataset 1Put differently, there is an important difference between the C types “int const *” (how practitioners often treat these URL-based datasets) and “int * const” (what the dataset actually provides). (minimizing the cost per poisoned URL), or domains that host content with specific auxiliary data ci (recall that the adversary cannot modify the auxiliary data contained in the distributed dataset index). We show that split-view poison- ing is effective in practice, as the index of most web-scale datasets remain unchanged long after their first publication, even after a significant fraction of the data goes stale. And critically, very few (and no modern) datasets include any form of cryptographic integrity check of the downloaded content. Frontrunning poisoning. Our second attack extends the scope of split-view poisoning to the settings where an ad- versary does not have sustained control over web resources indexed by the dataset. Instead, the adversary can only mod- ify web content for a short time period (e.g., a few minutes) before the malicious modification is detected. This setting is common for datasets that aggregate content published on crowdsourced web pages, such as on Wikipedia. Indeed, it is easy to temporarily edit Wikipedia to vandalize its contents [63, 69]. A naive adversary might thus poison some Wikipedia content at arbitrary times and hope that a dataset curator will scrape the poisoned pages before the malicious edits are reverted. However, Wikipedia vandalism is reverted in a few minutes on average [80], so any randomly-timed malicious edits are unlikely to affect a dataset collection. Our frontrunning attack relies on the fact that an adver- sary can, in some cases, predict exactly when a web resource will be accessed for inclusion in a dataset snapshot. As a re- sult, the adversary can poison dataset contents just prior to a curator collecting a snapshot, thereby frontrunning content moderators who will later revert the malicious edits. We will show that frontrunning attacks are particularly effective for Wikipedia datasets, because the official Wikipedia snapshot procedure accesses articles in a predictable—and well docu- mented2—linear sequence. An attacker can thus predict the snapshot time ti of any Wikipedia article down to the minute. # 4 Split-View Data Poisoning We now begin our evaluation starting with split-view data poisoning attacks, where an attacker poisons a distributed dataset by purchasing and modifying expired domains. # 4.1 Our Attack: Purchasing Expired Domains While split-view poisoning is applicable to any distributed dataset, we focus on multimodal image-text datasets. In such datasets, each URL points to an image hosted by some data provider, and the auxiliary data contains a textual descrip- tion of the image, e.g., an annotated class label or a caption extracted from the web page. 2https://en.wikipedia.org/w/index.php?title=Wikipedia: Database_download&oldid=1138465486 4 Our attack exploits the fact that the Domain Name System (DNS) does not assign permanent ownership of any domain to a particular person or organization, but rather grants short (yearly) “leases” that must be frequently renewed. Thus, do- main names continuously expire over time—intentionally or not—when the re-registration fees are not paid. When the domain that hosts an image in a distributed dataset expires, anyone can pay to take ownership over this domain and thereby gain the ability to return arbitrary con- tent when the indexed image is later downloaded by a victim client. Split-view poisoning abuses the residual trust inherent in an expired domain, as in traditional domain hijacking at- tacks [39]. We find that for many popular distributed datasets, domains are included with relatively lax quality-assurance measures (if any), and thus domains with no special status that have been expired for months can freely be acquired to control a modest fraction of the entire dataset. In this section we study to what extent it is possible to poi- son datasets by purchasing expired domains. We first quantify the fraction of domains that are expired in popular distributed datasets (§ 4.2), then measure the frequency at which these datasets are scraped (§ 4.3), verify this attack is not currently exploited in the wild (§ 4.4) and finally study the attack’s potential down-stream impact (§ 4.5). # 4.2 Quantifying the Attack Surface Table 1 lists ten recent datasets we study in this paper that are vulnerable to split-view poisoning. The three oldest datasets (PubFig, FaceScrub, and VGG Face) are datasets of faces and associate each image with the identity of a single person (most often a popular celebrity). The remaining seven datasets are multimodal datasets containing URLs that point to images, along with textual captions automatically extracted from the HTML of the webpage. As such, for these datasets, the image can be modified by the owner of the corresponding domain, but the image’s caption is fixed in the dataset index. To measure the fraction of images that could be potentially poisoned, we count the number of images hosted on domains that are expired and buyable. We say that a domain is expired if the DNS record for that domain does not exist. To measure this, we perform an nslookup on every domain name in the dataset from two geographically distinct data-centers in May 2022 and August 2022 and report the domain as expired if all four lookups result in a NXDOMAIN response. We further call a domain buyable if it is expired, and if at least one domain name registrar listed the domain as explicitly for sale by the registrar3 in August 2022. Instead of counting the total fraction of data that is buyable (which would repre- sent a financially unconstrained adversary), Table 1 reports the fraction of images in the dataset from domains that can be 3Some registrars list domains as for sale even if they are actually owned by a squatter. We exclude these domains from our set of buyable domains because purchasing these domains is often an expensive and lengthy process. Size Release Cryptographic Data from Data buyable Downloads Dataset name (x 10°) date hash? expired domains for $10K USD per month LAION-2B-en [57] 2323 2022 x 0.29% > 0.02% >7 LAION-2B-multi [57] 2266 2022 x 0.55% > 0.03% >4 LAION-1B-nolang [57] 1272 2022 x 0.37% > 0.03% >2 COYO-700M [11] 747 2022 xt 1.51% > 0.15% >5 LAION-400M [58] 408 2021 x 0.71% > 0.06% >10 Conceptual 12M [16] 12 2021 x 1.19% > 0.15% >33 CC-3M [65] 3 2018 x 1.04% > 0.11% >29 VGG Face [49] 2.6 2015 x 3.70% > 0.23% >3 FaceScrub [46] 0.10 2014 Vs 4.51% > 0.79% >7 PubFig [34] 0.06 2010 vs 6.48% > 0.48% >15 Table 1: All recently-published large datasets are vulnerable to split-view poisoning attacks. We have disclosed this vulnerability to the maintainers of affected datasets. All datasets have > 0.01% of data purchaseable (in 2022), far exceeding the poisoning thresholds required in prior work [14]. Each of these datasets is regularly downloaded, with each download prior to our disclosure being vulnerable. † LAION-5B released a “joined” version of this dataset with a cryptographic hash over the text of the URL and Caption (not the contents of the URL), and as such does not protect the integrity of the actual image. ‡ COYO-700M images are distributed with pHash [32] which validates benign image changes, but is not adversarially robust [29]. § FaceScrub and PubFig contain cryptographic hashes, but the dataset maintainers do not provide an official downloader client that verifies these. We find that nearly all third-party downloaders for these datasets ignore hashes. ∗ PubFig was initially released without hashes, but hashes were later added in Version 1.2 of the dataset. purchased for a total cost of $10,000 USD. (Figure 1 plots the fraction of datasets that can be purchased as a function of total cost.) To compute this, we sort domains in decreasing order of “images per dollar”: the number of images the domain hosts divided by the cost to purchase this domain. Overall, we see that an adversary with a modest budget could purchase control over at least 0.02%–0.79% of the im- ages for each of the 10 datasets we study. This is sufficient to launch existing poisoning attacks on uncurated datasets, which often require poisoning just 0.01% of the data [15].4 We also find that there is a direct relationship between the age of a dataset and how easy it is to poison. Older datasets are more likely to contain expired domains, and therefore an adversary can purchase a larger fraction of the dataset. Datasets are vulnerable from day zero. One limitation of our above analysis is that we have measured the fraction of datasets vulnerable to poisoning in August 2022, but many of these datasets were constructed years earlier. It is therefore likely that many people who use these datasets would have already downloaded them at an earlier date, and thus may not have been vulnerable to our poisoning attack (although we will show in the following section that fresh downloads of each of these datasets remain frequent today). Fortunately, the COYO-700M dataset was released during the writing of this research paper, on 30 August 2022. On that same day, we computed the fraction of the dataset that 4Carlini & Terzis [15] assume the adversary can modify images and their captions, whereas our adversary only controls images. In § 4.5, we show modifying captions is unnecessary for a successful poisoning attack. was vulnerable to our poisoning attack and found that already 0.15% of the images were hosted on expired domains that cost fewer than $10,000 USD to purchase. The reason that the number of expired domains is not zero on release is that building these large datasets is a time-consuming and expen- sive procedure. And so even though the COYO-700M index was released in August 2022, it took nearly a year to collect the dataset [11], giving ample time for the earliest scraped domains to have expired before the dataset was released. Measuring the attack cost. The most immediate question is if this attack can be realized in practice. The primary con- straint of our attack is the monetary cost of purchasing do- mains, which we measure using the costs reported by Google Domains in August 2022. In Figure 1 we show the fraction of images in a dataset that can be controlled by the attacker as a function of their budget. We find that at least 0.01% of each dataset can be controlled for less that $60 USD per year. # 4.3 Measuring the Attack Impact Our attacks are “retroactive” in the sense that we can poison a dataset after it has been initially constructed by the curators— but the impact is limited to those who download it after we take over the domains. And given that it has been several years since many of these datasets were initially constructed, it is not obvious that anyone would still download them by scrapping URLs instead of reusing a previously downloaded version of the dataset. As a result, in order to measure the potential impact of a split-view poisoning attack it is necessary 5 1% 4 COYO-700M LAION-400M Ccc12M CC3M vggface facescrub pubfig 0.1% 4 0.01% 4 Fraction of Images Controllable 10 $100 $1k $10k Cost (USD) Figure 1: It often costs ≤ $60 USD to control at least 0.01% of the data. Costs are measured by purchasing domains in order of lowest cost per image first. to study the rate at which these datasets are actually still being actively downloaded by researchers and practitioners today. Methodology. We measure the rate at which each of these distributed datasets are downloaded from the internet by pur- chasing multiple expired domains from each of the 10 listed datasets, and passively monitoring requests to measure the rate at which URLs corresponding to images from the dis- tributed datasets are being downloaded. For each dataset, we purchase the three most popular ex- pired and buyable domains (that is, the domains available for purchase that hosted the most images), and three randomly selected domains that were available for purchase. We wrote a simple server to log all incoming HTTP and HTTPS5 re- quests, including the access time, a hash of the IP address, the full URL being requested, and any additional headers provided. This allowed us to count the frequency at which these datasets are still downloaded. We ran this server for six months beginning in August 2022. Analysis approach. Our server received approximately 15 million requests per month during our study, a rate of 6 re- quests every second. However from here it becomes necessary to separate the requests that were actually intending to down- load images from one of these datasets, from requests that come from other internet users or web crawlers. To begin our analysis, we make a (significant) simplifying assumption that anyone downloading one of these datasets does so from a single IP address. We may thus underestimate the true rate at which each dataset is downloaded. We then say that a particular IP address X downloads a dataset D at time [T0, T1] if we meet both a precision and recall requirement: 1. Recall: Within the time range [T0, T1], the IP address X downloads at least 90% of the URLs contained in D 5To also monitor HTTPS traffic we obtained certificates from LetsEncrypt for each of our domains. 6 under our control, including at least one URL from each of the 6 domains we own for that dataset. 2. Precision: At least 50% of the requests issued by X within this time range to the domains we control are to URLs in D. These conditions are conservative, but ensure we filter out web crawlers and other mass internet scrapers because these are likely to crawl other URLs from this domain (violating the precision constraint) or not crawl the majority of the URLs from the dataset (violating the recall constraint). Additionally, because we own six domains per dataset it is exceptionally unlikely that, by random chance alone, one particular IP will request URLs from each of these six otherwise-unrelated domains. (In fact, we find that even checking 3 of these URLs would give almost identical precision.) As a point of reference, for the CC-3M dataset, we received 51,000 image requests per month from a total of 2401 unique IPs. By applying the precision constraint alone, we reduce this to 2007 unique IPs and 43,000 image requests; by applying the recall constraint alone we get 70 unique IPs and 32,000 image requests; and both together yields a further reduction of 64 unique IPs and 28,000 image requests (per month). # 4.3.1 Results We report our results in the rightmost column of Table 1. Even the oldest and least frequently accessed datasets still had at least 3 downloads per month. Thus, over the six months we tracked data, there were over 800 downloads that we could have poisoned with our attack. Unsurprisingly, we found that newer datasets are requested more often than older datasets. Different datasets thus offer different tradeoffs for attackers: newer datasets have a smaller fraction of purchasable images, but an attack can reach many more vulnerable clients. We observe that the largest billion-image datasets are down- loaded significantly less often than smaller recent datasets. We found that the reason for this is that these datasets are rarely downloaded in their entirety; instead, they serve as an upstream source for smaller subsets. For example, the Public Multimodal Dataset (PMD) [66] and LAION-Aesthetics [59] datasets consist almost entirely of images drawn from LAION- 2B-en. Sub-datasets like this explain why sometimes we see IP addresses with very high precision but low recall. Visualizing dataset crawlers. Using our log files, we can visualize the ways in which dataset downloaders access these datasets by plotting URL requests as a function of time. We order the set of URLs we bought for each dataset according to their order in the original dataset index. In this way, crawlers that process the dataset index linearly should appear (roughly) as a linear line in our plot of URL requests over time. To improve clarity, we assign each unique IP that accesses our server a separate random color. 8000 v © 8 6000 v o o z 4000 S ‘ 6 % 2000 v £ i?) 2022-08-11 2022-08-13 2022-08-15 Date Figure 2: Visualization of users downloading Conceptual 12M. By monitoring which URLs are requested from the domains we purchased, we plot every time a URL is requested over time, color coded by the source IP, and can directly read off several dozen users crawling Conceptual 12M. Appendix Figure 8 compares various filtering approaches. We show this plot for the Conceptual 12M dataset in Fig- ure 2. We can find several trends in this data. First, most users who download this dataset do so in a linear order from the first to the last URL. However, the rate at which URLs are accessed is highly variable: some downloaders crawl the en- tire dataset in a few hours, while others take several weeks to download the same dataset. We also observe some users that batch the data into chunks and download each chunk in paral- lel, as well as users that pause their download momentarily and then resume a few hours later (on a different IP). While our strict precision and recall requirements already give strong evidence that the IP addresses we logged were indeed downloading the dataset, the linear ordering of URL requests from these addresses all but confirms this. Indeed, because the ordering of URLs in the dataset index is random (instead of, say, alphabetical), a dataset download appears to be the only explanation for why the URLs would be linearly accessed in this particular order. User-agent verification. The most popular user agent6 is re- sponsible for 77% of the traffic to our domains. This user agent is hardcoded7 in img2dataset tool [5], a popular dataset crawler. Given the browser involved is Firefox 72– which was superseded in February 2020–it is highly likely that most of the requests indeed originate from img2dataset. Ethical considerations. We do not actually poison any datasets. For all URLs we own, we return a 404 Not Found response; so from the perspective of a dataset downloader our purchasing of the domain is completely transparent. We fur- ther place a robots.txt file to prevent typical web-scrapers 6Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0 7https://github.com/rom1504/img2dataset/blob/fc3fb2e/ img2dataset/downloader.py#L41 7 from crawling our domains—this is unlikely to impact dataset downloads since dataset crawlers ignore this file. Finally, a request to the root domain returns a 403 Forbidden with a response body explaining that this domain is part of a research study. In this response we list a contact email address and also offer to return this domain to the original owner in case it was allowed to expire accidentally. We have not received any contact on this address. Appendix E contains the text of our landing web page. Our data collection is minimally invasive. When searching for expired domains, we limit our DNS requests to 500/second, we only ask for the cost of purchasing the top-10,000 domains in each dataset, and only eventually purchase six. This research study was deemed “exempt” by the ETH Zurich IRB. Google does not have an IRB, but the research plan was reviewed by experts at Google in areas including ethics, human subjects research, policy, legal, security, privacy, and anti-abuse. # Is This Attack Exploited in the Wild? Given that this attack vector has existed for years against many datasets, and is easy to execute, it is not implausible that someone would have carried out such a poisoning attack in the past. Yet, we could not find any evidence of this. We search for a signature of a domain-purchasing attack by looking for domains that (1) host images that have been modified since the initial dataset release and (2) have changed ownership since the initial dataset release. To detect image changes, we can either check if images are perceptually simi- lar to the originals (via, e.g., CLIP embeddings [52]) or exactly identical (via a cryptographic hash). Comparing images with cryptographic hashes has no false-negatives (i.e., any change is detected) but gives false-positives for “benign” changes, e.g., if a domain re-encodes or resizes its images. In contrast, a perceptual hash has fewer false-positives but can have false- negatives if an adversary buys a domain and modifies images while preserving the perceptual hash (which is not collision- resistant). Finally, to detect if a domain changed ownership, we request the whois record and check the last purchase date. Results. We perform our initial analysis on CC3M, a dataset where we have the original raw images as ground truth. Among all domains hosting more than 10 images, we find just one domain has our attack signature when comparing with perceptual image similarity. Upon further investigation, we find that this domain has been purchased by a domain squat- ter and any request to an image file on the domain return an advertisement. If we instead compare cryptographic hashes of images, we find the same domain squatter and also two other domains that have been repurchased. However, further investigation reveals the ownership of these domains has not changed and the DNS record simply lapsed, and images were re-encoded. We also conduct this same analysis on LAION-400M. Here we study three versions of the data: at original release (2021- 11), and our own downloads at two later dates (2022-04 and 2022-08). We find no domain with such a signature in LAION- 400M, and thus have no evidence at present that this attack would have been exploited against this dataset. Because we only have the original CLIP embeddings for this dataset (the original raw bytes were not saved), we only perform this comparison. We find that by the first and second snapshot respectively, there are 4.1M and 4.2M unique domains (of 5.6M) that host at least one modified image—in total, we found 175M and 183M modified images, respectively. We measured this using a CLIP cosine similarity < 0.99. We randomly sample a few thousand domains including the 700 with the most modified images. We find many cases where domains are still owned by the original owner, are currently for sale, or have been redacted, but none appear malicious. # 4.5 Putting It All Together Prior work [15] has successfully poisoned multimodal models contrastively trained on datasets of 3 million images, under the assumption the adversary can arbitrarily control the label of manipulated images. However, in this paper we study datasets over 100× larger, and assume an adversary with no control over the text captions. Are poisoning attacks effective with these two changes? We find they are. We consider two poisoning attack ob- jectives: (1) cause a particular image to be misclassified as some target label from ImageNet, and (2) cause a particu- lar image to be classified as NSFW by the Stable Diffusion Safety Filter [54]. For each of these attack objectives, we first identify appropriate text captions in LAION 400M for which the corresponding image domains can be purchased for a total of $1,000 USD. Then, we locally replace these images with poisoned samples to simulate the effect of an attack, without any potential to cause harm to others. Specifically, we train one OpenCLIP [28] model using a ViT-B-32 architecture for 32 epochs, at a batch size of 3072 on 16 A100 GPUs. For our object-misclassification objective, we choose ten ImageNet classes that appeared in multiple text captions of images we can control. When we poison 1,000 images (0.00025% of the total dataset) our attack has a success rate of 60% in flipping the model’s zero-shot classification of the targeted image. For our NSFW objective, we find captions corresponding to images (from buyable domains) labeled as UNSAFE in the LAION 400M dataset index. Again at 1,000 poisoned samples, our attack has a success rate of above 90%. More details about this experiment are in Appendix D. # 5 Frontrunning Poisoning Our second attack removes the assumption that the adversary has sustained control over the web data in a training set. To do 8 this we make a new assumption: that we can predict precisely when the web content will be downloaded. We will investigate this attack on Wikipedia-derived datasets, but also discuss how similar vulnerabilities may exist in the Common Crawl dataset in Appendix B. # 5.1 Our Attack: Editing Wikipedia Wikipedia is a crowdsourced encyclopedia. This makes it one of the most comprehensive and reliable datasets available on the internet [79]. As a result of its quality and diversity, Wikipedia is frequently sourced for ML training data. Indeed, many language modelling datasets heavily rely on the English Wikipedia, e.g., it formed over 75% of the words in the BERT training set [21], 1.5% of the Pile dataset [23], and the entirety of the WikiText dataset [43]. Many task-specific datasets also rely on the English Wikipedia: e.g., the WikiQA [81] question answering dataset (30,000+ downloads), and the WikiBio [38] biography writing dataset (19,000+ downloads). Finally, some of the distributed datasets discussed in Section 4 index many images from Wikipedia articles. Because Wikipedia is a live resource that anyone can edit, an attacker can poison a training set sourced from Wikipedia by making malicious edits. Deliberate malicious edits (or “vandalism”) are not uncommon on Wikipedia, but are often manually reverted within a few minutes [80]. As a result, actually poisoning Wikipedia appears challenging: unlike the attacks in our prior section, an adversary cannot exert sustained control of any particular page and would thus have to hope that their malicious edit is timed just perfectly to affect a dataset download before being reverted. However, we make one key observation that will guaran- tee the success of our poisoning attack: Wikipedia-derived datasets are not themselves live, but rather a collection of static snapshots. This is because Wikipedia forbids using web crawlers to scrape the live website. Instead, Wikipedia makes available regular “dumps” (or snapshots) of the entire ency- clopedia. Thus, training datasets sourced from Wikipedia use these snapshots instead of data crawled directly from the site. For example, the authors of the BERT model [21] explicitly recommend “to download the latest [Wikipedia] dump” to reproduce their results. This makes it possible to mount what we call a frontrun- ning attack. An attacker who can predict when a Wikipedia page will be scraped for inclusion in the next snapshot can perform poisoning immediately prior to scraping. Even if the edit is quickly reverted on the live page, the snapshot will con- tain the malicious content—forever. The attentive reader may argue we have not gained much: instead of having to predict the time at which Wikipedia is crawled by the end-user to produce a training set, the attacker has to predict the time at which Wikipedia is crawled to produce an official snapshot. But as we will see, the latter is actually easy. In this section, we explore how an adversary can time mali- 50000 40000 30000 20000 Edit Time (s) 10000 Article ID le7 Figure 3: An adversary can easily predict when any given Wikipedia article will be snapshot for inclusion in the bi- monthly dump. We visualize edits around the June 1st, 2022 Wikipedia snapshot. Each point corresponds to an edit made to a Wikipedia article, with the article ID on the X axis and time (in seconds) that the edit was made on the Y axis. Edit points colored blue were included in the snapshot, and edits colored orange were not included. The “sawtooth” pattern exhibited in the plot indicates a trend where multiple paral- lel jobs crawl Wikipedia articles sequentially to construct the snapshot. Furthermore, these parallel jobs run almost perfectly linearly through their allocated pages. cious edits to guarantee successful poisoning of a Wikipedia snapshot. To this end, we need to answer two questions: 1. How accurately can we predict the time at which a page is scraped for inclusion in a Wikipedia snapshot? 2. How quickly do malicious edits get reverted? # 5.2 Predicting Checkpoint Times Wikipedia produces snapshots using a deterministic, well- documented protocol (with details that are easy to reverse- engineer through inspection). This makes it possible to predict snapshot times of individual articles with high accuracy. # 5.2.1 How Wikipedia Snapshots Work English Wikipedia is archived on the 1st and 20th of each month. The snapshot is produced by n parallel workers; all Wikipedia articles are ordered sequentially by their ID and split into n chunks, and each worker independently and lin- early scrapes all articles in their chunk. Due to Wikipedia’s size, the whole process takes nearly a day to complete. Different articles thus get scraped at sig- nificantly different wall-clock times. As a result an edit at time ti for one article may be excluded from the snapshot, while an edit at time t j > ti for a different article might be included. Figure 3 visualizes this “sawtooth” effect: there are many edits (in blue) that are included in the June 1st dump 9 that were made before (i.e., below) a different edit that was not included (in orange). For a frontrunning attack to succeed, it is thus not sufficient to just predict the time at which the snapshot procedure begins. The attacker also needs to predict the precise time at which each individual page is scraped. # 5.2.2 Exploiting Rolling Snapshots To precisely predict each article’s scrape time, the attacker can exploit consistencies in Wikipedia’s snapshot process. First, the adversary knows precisely when each dump starts, because Wikimedia explicitly makes this information avail- able by publishing live statistics on ongoing snapshots.8 Second, the rate at which articles are crawled in a dump remains nearly consistent across dumps, and can thus be ap- proximated from prior dumps (interestingly, crawls tend to speed up slightly over time). With these two pieces of information, the attacker can pre- cisely predict when any given article will be crawled. For an article i, we denote the time at which it is crawled for the current snapshot as ti and its crawl time in the previous snapshot as ti,prev. We denote the start time of the current and previous snapshots (as reported by Wikimedia) as t0 and t0,prev respectively. Due to our first observation above, the attacker knows t0 and t0,prev. Due to our second observation, we have that ti − t0 ≈ ti,prev − t0,prev. This allows us to estimate the snapshot time of the i-th article as ti ≈ t0 + (ti,prev − t0,prev). But calculating this requires knowledge of ti,prev—the time at which the i-th article was crawled in the previous snapshot. We now discuss how to retroactively estimate this. # 5.2.3 Determining the Article Snapshot Time Wikipedia snapshots do not explicitly list the snapshot time for each article. But Wikipedia does give some auxiliary in- formation: a complete list of edits with the precise time every edit is made. We show how this information can be used to retroactively estimate an article’s snapshot time. Recall from Figure 3 that for each article we can find the list of edits that were included in the current snapshot (blue points), with later edits appearing in the next snapshot (or- ange points). For each article, we thus know that the snapshot time ti was somewhere between the times of the article’s last included edit (top-most blue point) and the first non-included edit (bottom-most orange point). However, this interval is loose: the time between these edits is often several days. To refine our estimate of the snapshot time for each article, we can again exploit the consistency present in the Wikipedia crawling process. We observe that articles are processed se- quentially: by zooming in to just a single crawling job as shown in Figure 3, we see that articles are crawled sequen- tially, and a clear line separates the last-included and first- # 8On https://dumps.wikimedia.org/backup-index.html 2.725 2.720 2.715 2.710 2.705 Edit Time (s) 2.700 42 Article ID Figure 4: We can obtain tight estimates on the time at which each article is snapshot. The green and orange lines show the interval [tlow i,prev] for a range of articles from the English Wikipedia. On average, our predictions (blue line) are 27 minutes from the furthest interval boundary. not-included edits of each article. That is, for articles i and j processed in the same job, we have that ti < t j if i < j. We can thus tighten our interval around each article’s edit time by continually tracking the most recent edit made before the snapshot (for each article, this is the top-most blue edit made on an earlier article in that job), as well as the earliest edit among all subsequent articles in the job that was not included in the snapshot. We visualize this in Figure 4. For each article in the previous snapshot, we can thus obtain a time interval i,prev,thigh [tlow i,prev] that contains the true (but unknown) snapshot time ti,prev. By our construction outlined above, we guarantee that the lower and upper limits of these intervals monotoni- cally increase for all articles in a job (see Figure 4). To produce an estimate ˆti,prev for each article’s previous snapshot time, we compute a best linear fit for the snapshot intervals of all articles processed by a single thread, as il- lustrated in Figure 4. This lets us predict the article’s next snapshot time as ˆti ≈ t0 + (ˆti,prev − t0,prev). # 5.2.4 Evaluating our Predictions We now evaluate our procedure for estimating article snapshot times. Ideally, we would directly compare our predicted snap- shot times ˆti with the true snapshot time of the i-th article. But we do not know the ground truth, except up to some interval [tlow ] which we can compute a posteriori as described i above. We thus proceed in two steps. First, we show that our linear fit to estimate the previous snapshot time ˆti,prev is accurate. For this we measure the max- imum absolute error between the predicted time ˆti,prev, and the unknown ground truth in the interval [tlow i,prev]. This provides an upper bound on the true estimation error. We find that the estimation error is bounded by 27 minutes on average. 10 3000 Number of Pages er Pp NN 5 & B B 8s € 8 8 $s 8 8 8 w =) 6 3000 2000 -1000 0 Prediction Error (s) 1000 Figure 5: Distribution of Wikipedia checkpoint time predic- tion errors. Most predicted checkpoint times are within 30 minutes of our constructed ground truth. In general, we pre- dict edits too early, so it is important to later adjust for this bias, as we will discuss in Section 5.4. Second, we evaluate the accuracy of the extrapolation of our predictions from one snapshot to the next. That is, we evaluate how close our a priori predicted snapshot time ˆti := t0 + (ˆti,prev −t0,prev) is to the snapshot time that we could have estimated a posteriori using the linear fit described above. Figure 5 shows the distribution of the error estimates. Our predictions are correct to within roughly 30 minutes in most cases. We notice, however, that our extrapolation errors are biased towards negative. We find that this is because snapshots slightly speed up over time, so we typically overestimate the next snapshot time of an article. We will correct for this in Section 5.4, when we produce a conservative estimate of our attack’s success in poisoning Wikipedia snapshots. # 5.3 Estimating Revision Speed Now that we have measured how accurately we can predict when a future snapshot will happen, we turn our attention to measuring the size of the opportunity window to make a malicious edit before it is reverted. We remark that while the most accurate methodology would be to inject malicious edits and measure the distri- bution of reversion times, we believe this would be unethical. Instead, we take an entirely passive—albeit less accurate— approach as discussed in Section 5.6. To measure the speed of revisions, we construct a dataset of all edits made to Wikipedia from January 2021 to June 2022 (for a total of 18 months), and classify every edit as either an addition or as a reversion if they contain one of a fixed set of strings9 which are frequently used in reversion comments. We then conservatively assume that the edit being 9This set of strings is produced by manual analysis of a sample of com- ments from each Wikipedia; details are given in Appendix B.1. 1.0 08 0.6 0.4 0.2 CDF of Reversion Time 0.0 107 10° 101 107 10? 10* Time to Revert an Edit (min) Figure 6: A CDF of revision times for English Wikipedia. Roughly 35% of revisions take more than 30 minutes. reverted was the immediately preceding edit, and so measure the reversion time as the elapsed interval between these two edits.10 Figure 6 plots this distribution. When we combine the roughly 30 minutes of error in predicting future snapshot times (c.f. Figure 5), with another roughly 30 minutes for the average uncertainty in our estimate of the true snapshot time (c.f. Figure 4), we can conservatively estimate that the attacker can time their edit so as to be within one hour, on average, of the true snapshot time. Approximately 32% of reversions take more than an to be reverted and so the attack is likely to succeed often. In the next section, we refine this estimate to determine more precisely how many articles we could have poisoned. # 5.4 Putting It All Together Using our predictions of relative article snapshot times, our interval bound on the true snapshot time, and the distribution of reversion times, we can now (conservatively) determine what fraction of Wikipedia an adversary could have poisoned. There are two potential “failure cases” where a malicious edit may not make it into the checkpoint: • the malicious edit is applied too late: the article was already snapshot, or • the malicious edit is applied too early: the edit gets re- verted before the article is snapshot. This induces a tradeoff: the attacker wants to make edits early enough to ensure they do not miss the snapshot time, but late enough to maximize the chance of frontrunning editors. We therefore compute the optimal time to apply a malicious edit as follows. Recall that we use [tlow ] to represent the tightest interval around the true (but unknown) snapshot time 10This under-reports the edit time because if the vandalism was from an earlier edit, we would incorrectly use the later edit’s time instead. 11 ti of the i-th article, and ˆti is the predicted snapshot time. To balance the two failure modes above, and to account for the bias in our predictions (see Section 5.2.4), we introduce an “adjustment” variable a so that the adversary adds their malicious edits at time ˆti + a instead of exactly at time ˆti. Then the fraction of malicious Wikipedia edits that will make it into the snapshot, when they are made at time ˆti + a, can be lower-bounded as: Edit applied too early Ala) = LO Palais) (A Alh--a > 0%) __-“—_’ m Edit applied too late where 1[ˆti +a > tlow ] is the indicator function that is one if the edit is applied after the checkpoint (here we conservatively use our lower bound tlow on the true checkpoint time), and prev(ˆti + a;thigh ) is the probability that the edit is reverted before the checkpoint (here we conservatively use the upper bound thigh # i We compute this sum using our results from Section 5.2 and Section 5.3. By taking the maximum over a sweep of potential a values, we obtain maxa A(a) = 0.065. That is, according to our conservative analysis, we can poison 6.5% of Wikipedia documents absent any other defensive measures. In reality, of course, there are a number of factors beyond our analysis that would likely prevent us from reaching this fraction, such as rate limiting of edits or IP bans. We also “cheat” in choosing the optimal value of the adjustment value a, but we do not consider this a major limitation—it is likely that an adversary could use more historical data to produce better estimates ˆti as well as good estimates of a. However, our analysis is also pessimistic in that we assume we only try once to poison any given article. An adversary may attempt a more targeted attack, as we discuss in Appendix B.2, where they retry edits on targeted articles, to force editors to revert multiple times and increase the likelihood of the edit making it into the dump. Ultimately, our best-effort estimate of 6.5% of poisoning success is orders-of-magnitude higher than what is required in prior poisoning attacks [15]. We thus argue that a successful frontrunning poisoning attack on Wikipedia snapshots is practical, and that finding ways to mitigate such attacks is a worthwhile research direction. # 5.5 Multilingual Wikipedia Wikipedia is also frequently used for non-English language modeling. For example, the multilingual version of BERT is trained entirely on the top 104 Wikipedia languages.11. Mul- tilingual datasets often rely more heavily on Wikipedia than English datasets. Thus, poisoning Wikipedia is even more harmful for non-English language modeling tasks. To measure 11See https://github.com/google-research/bert/blob/master/ multilingual.md#list-of-languages. da si sk sr Iv bg es et elnoav m fr & ca it viuk hi he th cu hr tr id fa hu pt ja fi armsko ni pl Language id Figure 7: Multilingual Wikipedia may be more vulnerable to frontrunning poisoning attacks. We compute poisoning rates for 36 of the 40 languages languages contained in Wiki- 40B [25] by reusing our attack from Sections 5.2 to 5.4. this vulnerability, we investigate the Wiki-40B dataset [25] which is frequently used to train large multilingual models. We repeat our analysis from the previous section on 35 of the 39 non-English languages contained in Wiki-40B by identifying which strings often represent a reversion in these languages.12 Again our analysis here is loose: we identify only a subset of (often automated) reversions; however for the same reason as above we believe this represents a lower bound of the mean reversion time. We find that 22 (63%) of the non-English Wikipedias were easier to poison than the English Wikipedia, as shown in Fig- ure 7. Feasible poisoning rates range from 0.95% to as much as 25.3%, with a median value of 8.2%. In general, the in- crease in vulnerability comes from multilingual Wikipedias having more predictable checkpoints, for two reasons. First, because these Wikipedias are smaller, the entire checkpoint- ing procedure is shorter, reducing the amount of variance in checkpoint time between different pages. Second, because the Wikipedias change less between successive checkpoints, the speed of checkpointing is more stable, improving our pre- dictions. This may be why some of the larger Wikipedias, such as Spanish, Danish, and Italian, have comparable poison- ing rates to English Wikipedia. However, our interval-based measurement is also more conservative for languages with slower edits, as the intervals will be larger, giving very small lower bounds for some small Wikipedias, such as Slovak and Slovenian. We reiterate that such large poisoning rates are unlikely to ever happen, due to IP bans or rate limiting. The most important takeaways from our analysis here are that 1) mul- tilingual Wikipedias are vulnerable to poisoning, and often more vulnerable than English Wikipedia, and 2) multilingual datasets tend to rely more on Wikipedia than English datasets do, compounding this risk. # 5.6 Ethical Considerations Our actions here are entirely passive. We make no edits to Wikipedia and, aside from downloading datasets from the of- 12We were unable to access the German, Chinese, and Czech checkpoints for the checkpoint times we studied, and Tagalog did not have enough data to reliably analyze. 12 ficial sources, never interact with Wikipedia. While this leads to limitations in our analysis, we believe this is the correct way to run such a study to avoid harming the Wikipedia ed- itor community. We disclosed our attack analysis (and later defense recommendations) to researchers at Wikimedia who acknowledged the vulnerability before release of this paper. # 6 Defenses In order to address the attacks that we identified, we pro- pose an integrity-based defense for split-view poisoning and a timing-based defense for frontrunning poisoning. We also discuss potential directions to address poisoning more gener- ally. We shared these defenses with curators, maintainers, and downloaders as part of our responsible disclosure and report on the status of their implementation of defenses. # 6.1 Existing Trust Assumptions Per our threat model (Section 3), our proposed defenses as- sume that all maintainers, curators, and downloaders are trusted and behave honestly. This means that maintainers provide the same distributed dataset index{(urli, ci)}N i=1 to any client and that the index itself has not been poisoned (e.g., due to insider risk or compromise). Downloaders for distributed datasets honestly access all urli and compute any integrity checks that we add via our defenses. Curators pro- vide the same centralized dataset D to all clients, with curators controlling the time ti at which any element urli is snapshot. These assumptions mirror the existing trust that clients place in maintainers, curators, and downloaders and thus represent the quickest, short-term path to enacting defenses. We dis- cuss limitations of these trust assumptions and more robust solutions with fewer trust assumptions in Section 6.5. # 6.2 Preventing Split-View Poisoning While the simplest defense to split-view poisonings attack would be to convert the distributed dataset {(url;,c;) }¥_, into a centralized dataset (e.g., as in YFCC100M [71]), this is presently unrealistic due to the monetary, privacy, and legal challenges laid out in Section 3. Instead, maintainers—or another trusted third-party—can prevent split-view attacks by attaching a cryptographic hash h; = H(x;) of the raw data x; obtained from url; at time f; prior to any attack. A downloader would then check whether H(x;) = h;, where x; is the content of url; at time t/. The downloader discards any data where the client and maintainer receive distinct content. Here, H should be a cryptographic hash function such as SHA-256. Implementation & Responsible Disclosure. Enacting this defense requires a number of ecosystem changes. Currently, only PubFig and FaceScrub include cryptographic hashes as part of their distributed dataset (see Table 1). And because these two datasets do not provide an official downloader, the community has relied on a number of third-party down- loader scripts that for the most part do not actually verify these hashes.13 Fortunately, for larger datasets the img2dataset [5] tool has become the canonical downloader used in 75% of requests to our domains. As part of our responsible disclosure, we reached out to every maintainer (see Table 1), suggesting the addition of SHA-256 hashes as part of the dataset index. At the time of writing, CC3M, CC12M, LAION-2B-en, LAION- 2b-multi, LAION-1B-nolang, and LAION-400M now release their dataset with SHA-256 hashes of the image contents. We additionally implemented an option in img2dataset to verify SHA-256 image hashes upon download, thus preventing our attack for anyone using this tool, and pro- vide our own backup of hashes in a Google Cloud Bucket at gs://gresearch/distributed-dataset-hashes/ for the datasets where we have (near-)original data. Limitations. Integrity checks are viable if most benign con- tent remains static. If content is altered in any way (e.g., by re-encoding, cropping, re-sizing, or uploading a higher- resolution image) the original hashes will no longer match. This can significantly degrade the utility of a dataset: for exam- ple, we obtain the original raw data from the first Conceptual Captions 3M dataset downloaded in 2018 and compare this to our most recent download of these same images in 2023. Of the 3.3 million original images, 2.9 million images are still hosted online, but just 1.1 million of these images have hashes that match the original—the other 1.8 million images have changed since the initial dataset construction. This suggests that our defense, while providing perfect pro- tection against split-view poisoning attacks, has the potential to significantly degrade utility. In Appendix C, we perform a case-study analysis on the PubFig and FaceScrub datasets, showing that modified but useful content makes up a signif- icant fraction of the images with invalid hashes. Switching to a perceptual hash function (which aims for invariance to small image changes) would lead to higher utility, but would not meaningfully prevent our poisoning attacks because an attacker could upload poisoned images that were adversarially modified to fool the perceptual hash [26,29,68]. This suggests qualitatively new defense ideas will be necessary to defend against our attacks without a high utility cost. # 6.3 Preventing Frontrunning Poisoning Our frontrunning poisoning attack relies on the fact that an ad- versary only needs sustained control of data for a few minutes to succeed. To defend against this attack, it suffices to increase 13We examine the 6 most popular downloader scripts for each dataset (gathered by searching for “[pubfig|facescrub] dataset download github”), and find that only one script per dataset implements hash ver- ification. The one for FaceScrubchecks hashes by default, while the one for PubFig requires users to run a separate verification script. 13 the duration d = ti − ˆti that an attacker must retain control over urli for it to be included in the snapshot at time ti, where ˆti in- dicates the time an attacker first modifies the URL’s contents. If a curator can detect malicious modifications within time ∆, then increasing d > ∆ effectively thwarts the attack. This can be achieved in one of two ways: (1) curators can randomize the snapshot order of the urli and extend the time required to snapshot the complete corpus; or (2) curators could freeze edits to the content of urli at time ti, wait for a period T > ∆ for edits to go through review, and then finally release the snapshot at time ti + T . Implementation & Responsible Disclosure. For our first approach, Wikipedia could randomize its snapshot order of ar- ticles instead of its current sequential method based on article IDs. This thwarts an adversary’s ability to predict precisely when an article will be selected for snapshotting, requiring they sustain control of articles for the entirety of the snapshot time, tn −t0, to ensure success. For the English Wikipedia, the current average review time to detect vandalism ∆ is 2.5 hours (Figure 6). Increasing the snapshot time beyond ∆ would pro- tect 1 - ∆/(tn − t0) articles from random, malicious modifi- cation, or 89.5% of articles if snapshotting was uniformly randomized over 24 hours. This assumes an attacker is unable to use Sybil accounts to automatically reintroduce malicious edits after their first detection and reversion. If this assumption is invalid, this protection will be weaker in practice. For our second approach which is more comprehensive, Wikipedia could create an initial snapshot of an an article, hold it for a period T > ∆, and then back-apply (“cherry- pick”) modifications or reversions from trusted moderators that occur within time T before finalizing the snapshot. (Sub- sequent edits must be accepted from trusted moderators so as to avoid selective deletion or reversion by attackers.) Even a reasonable grace period of one day could have a significant impact on the number of malicious edits that will be caught. For example, on the English Wikipedia (Figure 6), increasing from a 5 minute to a 1 day window would increase the rever- sion rate from 50% to 90%, reducing vandalism by a factor of 5. As part of our responsible disclosure, we notified Wikipedia of these attacks and our proposed defenses. Limitations. In practice, these defenses make it more difficult for an attacker to operationalize frontrunning, but cannot pre- vent it entirely as ∆ is not uniform across articles. For example, attackers might target less active articles, or languages with fewer moderators, in order to increase their frontrunning suc- cess rate. Furthermore, our defenses hinge on the existence of a trusted curator who can detect malicious edits—something that may be difficult if an attacker intentionally introduces imperceptible changes over time that impact only machine understanding, but appear valid to human review. Overcoming these risks—which exist for any “living” dataset—requires much more sophisticated solutions, which we explore next. # 6.4 Preventing Poisoning in General Preventing poisoning attacks on more general web-scale datasets such as Common Crawl (a peta-byte sized dataset of web crawls) is more complex. No trusted “golden” snapshot exists here as we had for split-view poisoning. Nor is there a trusted curator who can detect malicious edits. Equally prob- lematic, updates to a web page have no realistic bound on the delta between versions which might act as a signal for attaching trust. Ultimately, any notion of which domains to trust is ad-hoc at best. Client could thus rely on consensus-based approaches (e.g., only trusting an image-caption pair if it appears on many different websites). An attacker would then have to poison a sufficiently larger number of similar websites to ensure success, which mirrors the same consensus challenges present in distributed systems like blockchains [45]. However, any solution in this space requires downstream knowledge of how URL content is consumed, vectorized, and deconflicted during training. We leave application-specific solutions to general poisoning to future work. # 6.5 Transparency to Improve Trust Web-scale datasets today hinge on implicit trust. Clients trust maintainers to distribute identical and accurate auxiliary data ci, which may in fact be malicious due to a compromised maintainer. Clients trust curators to enact effective moderation to detect malicious edits to xi. Clients trust downloaders to accurately retrieve urli. And finally, clients trust websites to deliver the same xi for every urli, even though attackers have countless mechanisms to subvert xi—going beyond just purchasing expired domains or frontrunning snapshots. We believe improving the safety of web-scale datasets re- quires introducing transparency into the ecosystem. Data transparency around the set of {(urli, ci, hi)} distributed to clients—akin to certificate transparency [37]—can prevent transient failures or a compromised maintainer from distribut- ing different datasets to different clients and to assist in the detection and removal of inaccurate ci or expired urli over time. Curators could engage in a similar process to ensure all clients receive an identical corpus D. While many download- ers are already open source, binary transparency would bolster protection to prevent selective inclusion of malicious mod- ules [1]. Such transparency would prepare the ecosystem for a future where multiple maintainers and curators continuously update web-scale datasets, rather than the current reliance on centralized entities and static datasets. # 7 Conclusion Our paper demonstrates that web-scale datasets are vulnera- ble to low-cost and extremely practical poisoning attacks that could be carried out today. This is true even when attackers 14 can target only a fraction of curated datasets, where corrupting 0.01% of examples is sufficient to poison a model. Those who publish and maintain datasets should consider the defenses we introduced—including integrity checks and randomized or time-gated snapshots—or alternate, application-specific de- fenses. In light of our findings, we argue that machine learning researchers must reassess the trust assumptions they place in web-scale data and begin exploring solutions that do not as- sume a single root of trust. Our findings also expose a variety of future directions for attack research: threat models where attackers can edit only raw content but not auxiliary data such as labels; assessing the practical costs of proposed attacks; and assessing the efficacy of more permissive, but potentially vulnerable near-duplicate integrity checks. As such, our work is only a starting point for the community to develop a better understanding of the risks involved in generating models from web-scale data. # Acknowledgements We are grateful to the dataset curators (in particular Beer Changpinyo, Saehoon Kim, Romain Beaumont, Ludwig Schmidt, and Chris Albon) for discussions around datasets and defenses. We are also grateful to Milad Nasr and Alex Kurakin for comments on early drafts of this paper. # References [1] Mustafa Al-Bassam and Sarah Meiklejohn. Contour: A practical system for binary transparency. In Data Privacy Management, Cryptocurren- cies and Blockchain Technology, pages 94–110. Springer, 2018. [2] Sören Auer, Christian Bizer, Georgi Kobilarov, Jens Lehmann, Richard Cyganiak, and Zachary Ives. DBpedia: A nucleus for a web of open data. In The semantic web, pages 722–735. Springer, 2007. [3] Ankan Bansal, Carlos Castillo, Rajeev Ranjan, and Rama Chellappa. The do’s and don’ts for CNN-based face verification. In Proceedings of the IEEE international conference on computer vision workshops, pages 2545–2554, 2017. [4] Ankan Bansal, Anirudh Nanduri, Carlos D Castillo, Rajeev Ranjan, and Rama Chellappa. UMDfaces: An annotated face dataset for train- ing deep networks. In 2017 IEEE international joint conference on biometrics (IJCB), pages 464–473. IEEE, 2017. [5] Romain Beaumont. img2dataset: Easily turn large sets of image urls to an image dataset. https://github.com/rom1504/img2dataset, 2021. [6] Battista Biggio, Blaine Nelson, and Pavel Laskov. Poisoning attacks against support vector machines. arXiv preprint arXiv:1206.6389, 2012. [7] Abeba Birhane, Vinay Uday Prabhu, and Emmanuel Kahembwe. Mul- timodal datasets: misogyny, pornography, and malignant stereotypes. arXiv preprint arXiv:2110.01963, 2021. [8] Tolga Bolukbasi, Kai-Wei Chang, James Y Zou, Venkatesh Saligrama, and Adam T Kalai. Man is to computer programmer as woman is to homemaker? debiasing word embeddings. Advances in neural information processing systems, 29, 2016. [9] Antoine Bordes, Nicolas Usunier, Sumit Chopra, and Jason Weston. Large-scale simple question answering with memory networks. arXiv preprint arXiv:1506.02075, 2015. [10] 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. [11] Minwoo Byeon, Beomhee Park, Haecheon Kim, Sungjun Lee, Woon- hyuk Baek, and Saehoon Kim. COYO-700M: Image-text pair dataset. https://github.com/kakaobrain/coyo-dataset, 2022. [12] Qingqing Cai and Alexander Yates. Large-scale semantic parsing via schema matching and lexicon extension. In Proceedings of the 51st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 423–433, 2013. [13] Qiong Cao, Li Shen, Weidi Xie, Omkar M Parkhi, and Andrew Zis- serman. VGGFace2: A dataset for recognising faces across pose and age. In 2018 13th IEEE international conference on automatic face & gesture recognition (FG 2018), pages 67–74. IEEE, 2018. [14] Nicholas Carlini. Poisoning the unlabeled dataset of Semi-Supervised learning. In 30th USENIX Security Symposium (USENIX Security 21), pages 1577–1592, 2021. [15] Nicholas Carlini and Andreas Terzis. Poisoning and backdooring contrastive learning. arXiv preprint arXiv:2106.09667, 2021. [16] Soravit Changpinyo, Piyush Sharma, Nan Ding, and Radu Soricut. Con- ceptual 12M: Pushing web-scale image-text pre-training to recognize long-tail visual concepts. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 3558–3568, 2021. [17] Honglie Chen, Weidi Xie, Andrea Vedaldi, and Andrew Zisserman. VGGsound: A large-scale audio-visual dataset. In ICASSP 2020-2020 IEEE International Conference on Acoustics, Speech and Signal Pro- cessing (ICASSP), pages 721–725. IEEE, 2020. [18] Xinyun Chen, Chang Liu, Bo Li, Kimberly Lu, and Dawn Song. Tar- geted backdoor attacks on deep learning systems using data poisoning. arXiv preprint arXiv:1712.05526, 2017. [19] 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. [20] Jia Deng, Wei Dong, Richard Socher, Li-Jia Li, Kai Li, and Li Fei-Fei. Imagenet: A large-scale hierarchical image database. In 2009 IEEE conference on computer vision and pattern recognition, pages 248–255. Ieee, 2009. [21] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training of deep bidirectional transformers for language understanding. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), pages 4171–4186, Minneapolis, Minnesota, June 2019. Association for Computational Linguistics. [22] Mohnish Dubey, Debayan Banerjee, Abdelrahman Abdelkawi, and Jens Lehmann. LC-QuAD 2.0: A large dataset for complex question answering over Wikidata and DBpedia. In International semantic web conference, pages 69–78. Springer, 2019. [23] 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. [24] Tianyu Gu, Kang Liu, Brendan Dolan-Gavitt, and Siddharth Garg. Bad- nets: Evaluating backdooring attacks on deep neural networks. IEEE Access, 7:47230–47244, 2019. [25] Mandy Guo, Zihang Dai, Denny Vrandeˇci´c, and Rami Al-Rfou. Wiki- 40B: Multilingual language model dataset. In Proceedings of the 12th Language Resources and Evaluation Conference, pages 2440–2452, 2020. 15 [26] Qingying Hao, Licheng Luo, Steve TK Jan, and Gang Wang. It’s not what it looks like: Manipulating perceptual hashing based applications. In Proceedings of the 2021 ACM SIGSAC Conference on Computer and Communications Security, 2021. [27] Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, et al. Train- arXiv preprint ing compute-optimal arXiv:2203.15556, 2022. [28] Gabriel Ilharco, Mitchell Wortsman, Ross Wightman, Cade Gor- don, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, Hongseok Namkoong, John Miller, Hannaneh Hajishirzi, Ali Farhadi, and Ludwig Schmidt. OpenCLIP, July 2021. [29] Shubham Jain, Ana-Maria Cret,u, and Yves-Alexandre de Montjoye. Adversarial detection avoidance attacks: Evaluating the robustness In 31st USENIX of perceptual hashing-based client-side scanning. Security Symposium (USENIX Security 22), pages 2317–2334, 2022. [30] Jared Kaplan, Sam McCandlish, Tom Henighan, Tom B Brown, Ben- jamin Chess, Rewon Child, Scott Gray, Alec Radford, Jeffrey Wu, and Dario Amodei. Scaling laws for neural language models. arXiv preprint arXiv:2001.08361, 2020. [31] Ira Kemelmacher-Shlizerman, Steven M Seitz, Daniel Miller, and Evan Brossard. The MegaFace benchmark: 1 million faces for recognition at scale. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 4873–4882, 2016. [32] Evan Klinger and David Starkweather. pHash: The open source per- ceptual hash library. https://phash.org/, 2013. [33] Alex Krizhevsky. Learning multiple layers of features from tiny images, 2009. [34] Neeraj Kumar, Alexander C Berg, Peter N Belhumeur, and Shree K Nayar. Attribute and simile classifiers for face verification. In 2009 IEEE 12th international conference on computer vision, pages 365–372. IEEE, 2009. [35] Tobias Lauinger, Ahmet S Buyukkayhan, Abdelberi Chaabane, William Robertson, and Engin Kirda. From deletion to re-registration in zero seconds: Domain registrar behaviour during the drop. In Proceedings of the Internet Measurement Conference, 2018. [36] Tobias Lauinger, Abdelberi Chaabane, Ahmet Salih Buyukkayhan, Kaan Onarlioglu, and William Robertson. Game of registrars: An empirical analysis of post-expiration domain name takeovers. In 26th USENIX Security Symposium (USENIX Security 17), pages 865–880, Vancouver, BC, August 2017. USENIX Association. [37] Ben Laurie. Certificate transparency. Communications of the ACM, 57(10):40–46, 2014. [38] Rémi Lebret, David Grangier, and Michael Auli. Generating text from structured data with application to the biography domain. CoRR, abs/1603.07771, 2016. [39] Chaz Lever, Robert Walls, Yacin Nadji, David Dagon, Patrick McDaniel, and Manos Antonakakis. Domain-Z: 28 registrations later measuring the exploitation of residual trust in domains. In 2016 IEEE symposium on security and privacy (SP), pages 691–706. IEEE, 2016. [40] Alexandra Luccioni and Joseph Viviano. What’s in the box? an analysis of undesirable content in the Common Crawl corpus. In Proceedings of the 59th Annual Meeting of the Association for Computational Linguis- tics and the 11th International Joint Conference on Natural Language Processing (Volume 2: Short Papers), pages 182–189, 2021. [41] Mary Ann Marcinkiewicz. Building a large annotated corpus of English: The Penn Treebank. Using Large Corpora, 273, 1994. [42] Pablo Mendes, Max Jakob, and Christian Bizer. DBpedia: A multilin- In Proceedings of the Eighth gual cross-domain knowledge base. International Conference on Language Resources and Evaluation (LREC’12), pages 1813–1817, Istanbul, Turkey, May 2012. European Language Resources Association (ELRA). [43] Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher. Pointer sentinel mixture models, 2016. [44] Tyler Moore and Richard Clayton. The ghosts of banking past: Em- pirical analysis of closed bank websites. In International Conference on Financial Cryptography and Data Security, pages 33–48. Springer, 2014. [45] Arvind Narayanan, Joseph Bonneau, Edward Felten, Andrew Miller, and Steven Goldfeder. Bitcoin and cryptocurrency technologies: a comprehensive introduction. Princeton University Press, 2016. [46] Hong-Wei Ng and Stefan Winkler. A data-driven approach to cleaning large face datasets. In 2014 IEEE international conference on image processing (ICIP), pages 343–347. IEEE, 2014. [47] Nick Nikiforakis, Luca Invernizzi, Alexandros Kapravelos, Steven Van Acker, Wouter Joosen, Christopher Kruegel, Frank Piessens, and Giovanni Vigna. You are what you include: large-scale evaluation of remote Javascript inclusions. In Proceedings of the 2012 ACM con- ference on Computer and communications security, pages 736–747, 2012. [48] OpenAI. Introducing Whisper. https://openai.com/blog/ whisper/, 2022. [49] Omkar M Parkhi, Andrea Vedaldi, and Andrew Zisserman. Deep face recognition. 2015. [50] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual models from natural language supervision. In International Conference on Machine Learning, pages 8748–8763. PMLR, 2021. [51] Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, and Ilya Sutskever. Robust speech recognition via large- scale weak supervision. [52] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9, 2019. [53] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J Liu, et al. Explor- ing the limits of transfer learning with a unified text-to-text transformer. J. Mach. Learn. Res., 21(140):1–67, 2020. [54] Javier Rando, Daniel Paleka, David Lindner, Lennart Heim, and Florian Tramèr. Red-teaming the Stable Diffusion safety filter. arXiv preprint arXiv:2210.04610, 2022. [55] David Rolnick, Andreas Veit, Serge Belongie, and Nir Shavit. arXiv preprint Deep learning is robust to massive label noise. arXiv:1705.10694, 2017. [56] Johann Schlamp, Josef Gustafsson, Matthias Wählisch, Thomas C Schmidt, and Georg Carle. The abandoned side of the Internet: Hijack- ing Internet resources when domain names expire. In International Workshop on Traffic Monitoring and Analysis, pages 188–201. Springer, 2015. [57] Christoph Schuhmann, Romain Beaumont, Richard Vencu, Cade Gor- don, Ross Wightman, Mehdi Cherti, Theo Coombes, Aarush Katta, Clayton Mullis, Mitchell Wortsman, et al. LAION-5B: An open large- scale dataset for training next generation image-text models. arXiv preprint arXiv:2210.08402, 2022. [58] Christoph Schuhmann, Richard Vencu, Romain Beaumont, Robert Kaczmarczyk, Clayton Mullis, Aarush Katta, Theo Coombes, Jenia Jitsev, and Aran Komatsuzaki. LAION-400M: Open dataset of clip- filtered 400 million image-text pairs. arXiv preprint arXiv:2111.02114, 2021. [59] Christoph Schumann and Romain Beaumont. LAION-Aesthetics. https://web.archive.org/web/20230119181400/https://laion.ai/blog/laion- aesthetics/, 2022. 16 [60] Roei Schuster, Congzheng Song, Eran Tromer, and Vitaly Shmatikov. You autocomplete me: Poisoning vulnerabilities in neural code com- pletion. In 30th USENIX Security Symposium (USENIX Security 21), pages 1559–1575, 2021. [61] Holger Schwenk, Guillaume Wenzek, Sergey Edunov, Edouard Grave, and Armand Joulin. CCMatrix: Mining billions of high-quality parallel sentences on the web. arXiv preprint arXiv:1911.04944, 2019. [62] Iulian Vlad Serban, Alberto García-Durán, Caglar Gulcehre, Sungjin Ahn, Sarath Chandar, Aaron Courville, and Yoshua Bengio. Generating factoid questions with recurrent neural networks: The 30M factoid question-answer corpus. arXiv preprint arXiv:1603.06807, 2016. [63] Pnina Shachaf and Noriko Hara. Beyond vandalism: Wikipedia trolls. Journal of Information Science, 36(3):357–370, 2010. [64] Ali Shafahi, W Ronny Huang, Mahyar Najibi, Octavian Suciu, Christoph Studer, Tudor Dumitras, and Tom Goldstein. Poison frogs! targeted clean-label poisoning attacks on neural networks. Advances in neural information processing systems, 31, 2018. [65] Piyush Sharma, Nan Ding, Sebastian Goodman, and Radu Soricut. Conceptual Captions: A cleaned, hypernymed, image alt-text dataset for automatic image captioning. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 2556–2565, 2018. [66] Amanpreet Singh, Ronghang Hu, Vedanuj Goswami, Guillaume Coua- iron, Wojciech Galuba, Marcus Rohrbach, and Douwe Kiela. Flava: In Proceed- A foundational language and vision alignment model. ings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pages 15638–15650, 2022. [67] Johnny So, Najmeh Miramirkhani, Michael Ferdman, and Nick Niki- forakis. Domains do change their spots: Quantifying potential abuse of residual trust. In Proceedings of the IEEE Symposium on Security and Privacy, pages 2130–2144, 2022. [68] Lukas Struppek, Dominik Hintersdorf, Daniel Neider, and Kristian Kersting. Learning to break deep perceptual hashing: The use case NeuralHash. In 2022 ACM Conference on Fairness, Accountability, and Transparency, pages 58–69, 2022. [69] Besiki Stvilia, Michael B Twidale, Linda C Smith, and Les Gasser. Information quality work organization in Wikipedia. Journal of the American society for information science and technology, 59(6):983– 1001, 2008. [70] Alon Talmor and Jonathan Berant. The web as a knowledge-base for answering complex questions. arXiv preprint arXiv:1803.06643, 2018. [71] Bart Thomee, David A Shamma, Gerald Friedland, Benjamin Elizalde, Karl Ni, Douglas Poland, Damian Borth, and Li-Jia Li. YFCC100M: The new data in multimedia research. Communications of the ACM, 59(2):64–73, 2016. [72] Antonio Torralba, Rob Fergus, and William T Freeman. 80 million tiny images: A large data set for nonparametric object and scene recogni- tion. IEEE transactions on pattern analysis and machine intelligence, 30(11):1958–1970, 2008. [73] Priyansh Trivedi, Gaurav Maheshwari, Mohnish Dubey, and Jens Lehmann. LC-QuAD: A corpus for complex question answering over knowledge graphs. In International Semantic Web Conference, pages 210–218. Springer, 2017. [74] Alexander Turner, Dimitris Tsipras, and Aleksander Madry. Clean-label backdoor attacks. 2018. Lozhkov, Pedro Cuenca, Nathan Lambert, Kashif Rasul, Mishig Davaadorj, State-of-the-art diffusion Diffusers: and Thomas Wolf. https://github.com/huggingface/diffusers/ models. blob/8178c840f265d4bee91fe9cf9fdd6dfef091a720/src/ diffusers/pipelines/stable_diffusion/safety_checker.py, 2022. Accessed 7 Feb 2023. [76] Eric Wallace, Tony Z Zhao, Shi Feng, and Sameer Singh. Con- arXiv preprint cealed data poisoning attacks on NLP models. arXiv:2010.12563, 2020. [77] Angelina Wang, Alexander Liu, Ryan Zhang, Anat Kleiman, Leslie Kim, Dora Zhao, Iroha Shirai, Arvind Narayanan, and Olga Rus- sakovsky. REVISE: A tool for measuring and mitigating bias in visual datasets. International Journal of Computer Vision, pages 1–21, 2022. [78] Guillaume Wenzek, Marie-Anne Lachaux, Alexis Conneau, Vishrav Chaudhary, Francisco Guzmán, Armand Joulin, and Edouard Grave. CCNet: Extracting high quality monolingual datasets from web crawl data. In Proceedings of the 12th Language Resources and Evaluation Conference, pages 4003–4012, Marseille, France, May 2020. European Language Resources Association. [79] Wikipedia contributors. Reliability of wikipedia — Wikipedia, the free encyclopedia, 2022. [Online; accessed 21-July-2022]. [80] Wikipedia contributors. Wikipedia:Go ahead, vandalize, 2022. [Online; accessed 5-December-2022]. [81] Yi Yang, Wen-tau Yih, and Christopher Meek. WikiQA: A challenge dataset for open-domain question answering. In Proceedings of the 2015 conference on empirical methods in natural language processing, pages 2013–2018, 2015. [82] Scott Wen-tau Yih, Ming-Wei Chang, Xiaodong He, and Jianfeng Gao. Semantic parsing via staged query graph generation: Question answer- ing with knowledge base. In Proceedings of the Joint Conference of the 53rd Annual Meeting of the ACL and the 7th International Joint Conference on Natural Language Processing of the AFNLP, 2015. [83] Chiyuan Zhang, Samy Bengio, Moritz Hardt, Benjamin Recht, and Oriol Vinyals. Understanding deep learning (still) requires rethinking generalization. Communications of the ACM, 64(3):107–115, 2021. 17 # A Additional Figures Index of URL accessed 2022-08-13 2022-08-15 Date 2022-08-11 Figure 8: An unfiltered (without any precision or recall re- quirement) view of accesses to our server for URLs contained in Conceptual 12M. Compare to Figure 2 for the filtered view. # B Further Discussion for Text Datasets In this section, we further discuss vulnerabilities present in text datasets, focusing first on targeted poisoning attacks on Wikipedia, and then on the Common Crawl dataset. # B.1 Annotating Reversions In each language, we produce a list of words which are com- monly used to denote reversions. The specific words used are emergent from each language’s Wikipedia contributor community, so there is no concrete list. However, in each language, their are automated reversion tools and manual re- versions which are tagged with the English word “reversion” or simply the abbreviation “rv”. These form a starting point for our manual analysis: we identify words which roughly translate to “revert”, “undo”, or similar, which also appear in a sample of reversion comments we identify as automated reversions or manual reversions. We then sample comments with each of these newly identified words to verify that they capture new instances of reversions (that is, they are used to uniquely tag reversions in the language’s Wikipedia), and do not produce too many false positives. Overall, we don’t expect this list to be perfect for any given language, as no author of this paper is an active contributor to any language’s Wikipedia. However, we do believe our analy- sis is sufficient to validate the two trends we notice: frontrun- ning attacks are still possible on non-English Wikipedias, and attacks may be more powerful on non-English Wikipedias. # B.2 Cascading Effects of Frontrunning Our attack enables an adversary to poison any Wikipedia snapshot. An adversary can use frontrunning to harm down- stream datasets that depend directly on these snapshots, as well. Rather than arbitrarily modifying large fractions of Wikipedia, these can be achieved with very targeted fron- trunning poisoning. Knowledge base extraction databases are heavily relied upon for analytics (e.g., asking queries like “which politicians were gang members?”) and machine learning (e.g., for train- ing and evaluating question-answering models). One of the largest databases for it is DBPedia [2, 42]. Since this database is created using the monthly snapshots, they are, for all intents and purposes, a filtered view of Wikipedia. This enables ad- versaries to directly leverage our frontrunning attack to poison these databases as well in a more targeted manner. As an example in analytics, a user may issue a query such as “which politicians were gang members?” A targeted poisoning attack could force individuals to be falsely included in such a list, with a small edit via a frontrunning attack. More broadly, such attacks could be designed to harm specific individuals or reduce the reliability of certain aggregate statistics. Similarly, in question-answering tasks for machine learn- ing, some datasets, like LC-Quad [22, 73], store data as question-query pairs. The adversary can also target these dataset by compromising the query with frontrunning (as above). Because Wikipedia snapshots are infrequent, and downstream systems like these knowledge bases may up- date their endpoints even more infrequently [2], these at- tacks can remain effective for multiple months. Another com- mon approach is to store data directly as question-answer pairs [9, 12, 62, 70, 82]. This mitigates our attack above, as- suming the specific checkpoint used to originally generate the dataset was not compromised. However, this only prevents poisoning of a model trained on these downstream tasks—a model trained on a poisoned Wikipedia snapshot and fine tuned on the downstream task will still be vulnerable. Finally, we remark that the impacts of these attacks may be exacer- bated on multilingual data as we discussed in Section 5.1. # B.3 Common Crawl Common Crawl is a petabyte-scale corpus of web crawl data that is repeatedly captured on a roughly monthly basis. Each archive is a complete re-crawl of the internet that records the full activity, including all requests of the crawler and the host responses—with both HTTP headers and content. As such, each archive contains a static snapshot of all crawled pages at the time of visit. This may include new page content not seen during a previous crawl, and may exclude content that has become stale since the previous crawl. For exam- ple, data crawled during September 24 through October 8, 2022 contains 3.15 billion web pages with 380 TiB of un- compressed content from 34 million registered domains—1.3 billion URLs were not visited in any of the prior crawls.14 The Common Crawl dataset is vulnerable to an attack which is similar to both our frontrunning and split-view poi- 14https://commoncrawl.org/2022/10/ sep-oct-2022-crawl-archive-now-available/ 18 {Count of fetch status by url host name (7p $) es Figure 9: Top 5 domains by status count soning attacks. The adversary can purchase an expired domain which was previously contained in the Common Crawl, and it will be re-crawled with the adversary’s choice of content, which will then appear in subsequent Common Crawl snap- shots. Notice that, differently from the snapshot-poisoning attack on Wikipedia, there is no content moderation here and so the adversary simply needs to continue to control the domain to poison all future Common Crawl snapshots. Buy- ing recently-expired domains that existed in previous Com- mon Crawl snapshots allows a stronger form of attack where the attack can inject entirely new links into the crawl. This can be accomplished by adding links or subdomains to poi- soned domains, and allowing the crawler to discover the new poisoned domains. Thus, an adversary may inject arbitrarily many pages into the Common Crawl dataset, not only from the originally expired subset. We do not implement this attack following our ethics statements outlined earlier. Since Common Crawl WARC files have been hosted by Amazon on a AWS Athena (serverless service)15, domain reconnaissance work to analyze URLs is inexpensive. Scan- ning through 10 years of Common Crawl data to analyze domains from popular TLDs and high number of Common Crawl entries cost us USD$ 0.84. While additional analysis might somewhat increase this cost, it remains an inexpensive way to search for vulnerable domains. Buying recently ex- pired domains, or domains that have a dangling DNS record with an active IP address is preferred, as domains that failed to return a 200-OK status in consecutive crawls seem to be moved to a lower priority. For example, among expired do- mains we purchased, just one domain accounts for more than 90% of all status codes among the purchased domains, while other domains we purchased as early as 12/20/2020 have seen relatively less scraping traffic across a 3 year period.16 Because Common Crawl is enormous and uncurated (to accurately reflect the content of the internet) poisoning all of Common Crawl is impractical due to size. Additionally, it is # 15https://commoncrawl.org/2018/03/ index-to-warc-files-and-urls-in-columnar-format/ 16The domains used in this study responded with a 404 HTTP status to explicitly prevent scraping of content, potentially affecting analysis of domain re-emergence. That is, domains that previously returned a 404 now return a 200. affraz.com Fetch Status Count over Time 800 fetch status - — 200 700 — m1 — x2 600 — 308 — 44 soo — sa — 52 : 524 = 40 8 300 200 100 ° » ss? st oJ » > » > st » Y . ~ . r 2 2 sv 2 iv ~~ ~ e a a pe ce ie ee Date Figure 10: affraz.com status counts over time Fetch Status by Date 800 fetch status — 200 — x» — x — 04 — 43 — 404 — 46 700 0 500 0 503 — sa — 22 — 8 Count 300 200 100 219 2021 2022 Date Figure 11: Aggregate status counts for all purchased domains not always apparent how consumers of this data are process- ing it for downstream machine learning tasks. However, there exist many derivative datasets which are constructed by cu- rating a relevant subset of the Common Crawl. This includes the LAION-5B image dataset [57], the text dataset known as the Pile [23], the multilingual text dataset CC-100 [78], and the CCMatrix dataset [61], a translation dataset of pairs of translated sentences. Such curation actually amplifies the power of an attack: an attack which adds 1MB of text to the Common Crawl would be poisoning a 2.5 · 10−9 fraction of the Common Crawl, but if this text bypasses the curation done for the CC-100 dataset, it could instead poison a 1.2 · 10−5 fraction of the English corpus, or even a full 9.1% of the Oromo corpus. # C Limitations of Integrity Check Defenses In Section 6.2, we outlined a natural defense against split- view poisoning that adds integrity checks to the dataset index. Specifically, upon collecting the dataset the maintainer com- putes a cryptographic hash of each image, and adds this hash to the index. Upon downloading a copy of the dataset, the client downloader then discards images for which the hash no longer matches. Unfortunately, this defense has a severe 19 (a) (b) Barack Obama This image is no longer available. Visit tinypic.com for more information. Orlando Bloom Renee Zellweger Quincy Jones (c) (d) Figure 12: What happens in practice when the image no longer matches the original hash? We show 4 examples from the PubFig dataset. In Figure 12a, the image is replaced by a placeholder. In Figure 12b, a watermark partially covers the face, making that image slightly less useful for training. In Figure 12c, the image was resized and thus the original bound- ing box contained in the dataset index no longer matches the face. As opposed to the previous three images, Figure 12d is perfectly suitable for training: the watermark is outside the facial bounding box. impact on utility. As we saw in Section 6.2, implementing this defense for the Conceptual Captions 3M dataset would re- sult in discarding roughly 55% of the entire dataset—mainly because of small yet benign image changes such as re-sizing. Here, we perform a more in-depth analysis of the impact of cryptographic integrity protections on other datasets. # C.1 Modified Images in the Wild: A Case Study on the PubFig Dataset PubFig [34] is a 2010 dataset that indexes close to 60,000 images of 200 different celebrities hosted across a variety of domains. PubFig is one of the oldest example of a distributed dataset. Thus, it is likely that many of the URLs in its index are no longer live (a phenomenon we refer to as “link rot”), and that many of the remaining URLs would point to images that have been slightly modified over time. Small image modifica- tions make integrity check defenses problematic because they discard many perfectly useful training images. In Figure 12, we show four different ways in which original images have Dataset # Images Success Download failure Invalid image pubfig facescrub 58795 106863 35.2% 48.5% 54.7% 10.2% 7.0% 44.5% Table 2: Link rot in old image datasets, downloaded using img2dataset [5]. In older datasets, the proportion of images that are no longer available online is high. Dataset Accuracy on Downloaded Modified modified, no crop modified, crop Accuracy on Accuracy on original, no crop Accuracy on original, crop pubfig facescrub 20668 51847 52.4% 29.4% 59.7% 93.3% 55.2% 91.6% 96.0% 97.7% 98.2% 99.1% Table 3: Quantifying changes on successfully downloaded images. Modified images are those that have a different hash than the original image. We measure the accuracy as the proportion of modified images that have a CLIP embedding close to any of the possible labels, approximating the question "Is there a recognizable face in the image?". The difference between cropped and uncropped images is largely due to the resized images making the crop not capture the face of the person, as in Figure 12c. been modified in PubFig. While we find examples of true- positives, where images were indeed modified significantly, there are also many cases of images that were subjected to minor changes such as the addition of a watermark. Many image datasets provide bounding boxes for a relevant part of the image. This is also the case for PubFig: the dataset index contains the coordinates of a bounding box for the person’s face. If these bounding boxes are not re-computed by the client, any image resizing, such as in Figure 12c, can render the cropped image useless for training. # C.2 Link Rot Statistics Integrity checks based on cryptographic hashing reduces the amount of data available in some datasets by a large amount. We download the PubFig and FaceScrub datasets and compute the prevalence of “link rot”, where the URL listed in the dataset index no longer resolves or returns a non-valid image. In addition to dead links, we find that many successfully downloaded images have been modified. We show aggregate statistics in Table 3. In the PubFig dataset, over 50% of the surviving images have a hash mismatch. However, many of those images are modified in harmless ways. To show this, we take a pre-trained face embedding model and fine-tune a classifier for the PubFig classes using only images with a correct hash. We then evaluate this classifier on the down- loaded images with an incorrect hash, and find that we only achieve 46.8% accuracy. Thus, many of these images were modified in ways that obfuscate the identity of the person. For FaceScrub, we find that fewer images have been modified. About 70% of successfully downloaded images still match the original hash. Of the images that were modified, we can still classify 88.2% correctly, which indicates that most of these changes are benign as illustrated in Figure 12b or Figure 12d. For PubFig, we further investigate how frequently an image change corresponds to a benign resizing, which nevertheless renders the original bounding box obsolete (as in Figure 12c). For this, we compare the CLIP (ViT-B-32-quickgelu from [28]) embeddings of the full image to the names of the 200 public figures in the dataset, with a threshold cosine similarity of 0.21. We find that 59.4% of images with incorrect hashes are not close to any of the labels in CLIP space. Compar- ing with Table 3, this corresponds to around 4% of incorrect hashes being a result of modifications similar to Figure 12c. Perceptual hashing or similar methods might alleviate this problem, because images are often modified in trivial ways. For example, as mentioned in Table 1, COYO-700M images are distributed with pHash [32] which is robust to benign image changes. However, perceptual hashes do not have the same worst-case integrity guarantees as cryptographic hashes [29]. There have been high-profile controversies due to the mistaken use of perceptual hashing as a preimage resistant algorithm [68]. It is widely believed that preimage attacks on SHA-256 are impractical, while there is no known perceptual hash function which has similar security guarantees. # D LAION Attack Details Both attack methods in Section 4.5 poison a CLIP model so as to bring the embeddings of some fixed images close to the embeddings of target textual labels. The key technical constraint in our experiment is that all attacks need to be done in parallel to minimize costs, as retraining CLIP is quite expensive. Object-misclassification objective. The ImageNet dataset [20] contains 1000 classes of images. The CLIP zero-shot classifier on ImageNet returns the class label whose text em- bedding has maximum cosine similarity to the image em- bedding in CLIP latent space, across all ImageNet classes. 20 The goal of our poisoning attack is for the CLIP zero-shot classifier to classify a particular image to a target incorrect label. We pick 10 classes as target labels for poisoning, such that captions containing the label appear at least 1000 times in the captions linked to cheap buyable domains; see Table 1. We do the following for each chosen label, e.g. apple: choose a set Sapple of 1000 caption-image pairs from buyable domains such that apple appears in the captions. We also enforce that the total cost of domains spanning Sclass for all chosen classes is at most $1,000 USD. Then, we pick a single unrelated image I—that wouldn’t ordinarily be classified as apple—and locally replace 1000 images from Sapple with image I. Thus for each of the 10 classes, we poison 1000 images, or only 0.000025% of the data. NSFW objective. The goal of this attack is to make the NSFW filter that comes with the Stable Diffusion 1.4 model in the Hugging Face diffusers library [75] mislabel a given benign image as NSFW. The classifier is a cosine similarity threshold function in CLIP latent space, comparing an image embedding to a list of textual NSFW concepts [54]. We choose 10 benign images, and do the following for each image I: choose 1000 caption-image pairs from buyable domains such that the captions are labeled UNSAFE in the LAION 400M metadata, and locally replace each of the corre- sponding 1000 images with I. Again we choose images from domains that cost less than $1,000 USD in total. The experiment. For both attacks (and all chosen images) simultaneously, we train an OpenCLIP [28] model on the the LAION 400M dataset with the described modifications. We train a ViT-B-32 CLIP model for 32 epochs, at a batch size of 3072 on 16 A100 GPUs. The object-misclassification attack works for 60% of the targets: the chosen image gets classified as the target label by a zero-shot CLIP classifier. The NSFW attack works for 90% of targeted images. 21 # E Landing Page for Purchased Domains The following text was placed on the landing page for each of the domains we purchased. This domain is part of a research study. This domain name was purchased as part of a research project studying to what extent machine learning datasets change over time. This domain name was included in one of these datasets and hosted images that were part of this dataset, but the previous owner let the domain name expire. We bought this domain in August 2022 to measure the number of people who query from these expired domains. We bought a number of domains that were included in many different datasets. All of these domains will return a 404 error for any requests except for the home page. You should not need to take any additional steps to ensure your datasets are unaffected by our study: if we had not bought this domain the URL would have been NXDOMAIN and you would have not received any content. We may temporarily log metadata for requests sent to this server to measure the prevalence of scraping this domain. Any data we have logged will be deleted upon completion of our study. If you would prefer not to participate in this study, please contact us via the email address below and we will delete any data you may have contributed to our study. We would really appreciate it if you let us use your data; we think this will be a valuable study. If you have any questions about this study you can contact for dataset-expired-domain-study@googlegroups.com additional information. This used to be my domain. Can I have it back? If you are the original owner of this domain, we would be happy to return it to you at your request to the above email address. We will let this domain expire when we have finished our research study. Will this cause problems with my downloaded dataset? As we say above, if you are scraping this dataset, you should not need to take any steps to specifically avoid this domain (or any other we have purchased). We have tested that the 404 response we send will cause all standard image downloading tools to skip the image entirely. Will your study be published? We will publish our study upon its completion. We expect this to occur within the next several months. Please contact us if you would like a copy of this study. I have another question not mentioned. Please contact us at dataset-expired-domain-study@googlegroups.com for addi- tional information.
Title: Cyberbullying Detection with Fairness Constraints: Summary: Cyberbullying is a widespread adverse phenomenon among online social interactions in today's digital society. While numerous computational studies focus on enhancing the cyberbullying detection performance of machine learning algorithms, proposed models tend to carry and reinforce unintended social biases. In this study, we try to answer the research question of "Can we mitigate the unintended bias of cyberbullying detection models by guiding the model training with fairness constraints?". For this purpose, we propose a model training scheme that can employ fairness constraints and validate our approach with different datasets. We demonstrate that various types of unintended biases can be successfully mitigated without impairing the model quality. We believe our work contributes to the pursuit of unbiased, transparent, and ethical machine learning solutions for cyber-social health. # Cyberbullying Detection with Fairness Constraints Oguzhan Gencoglu Tampere University, Faculty of Medicine and Health Technology, Tampere, Finland oguzhan.gencoglu@tuni.fi Abstract—Cyberbullying is a widespread adverse phenomenon among online social interactions in today’s digital society. While numerous computational studies focus on enhancing the cyberbullying detection performance of machine learning algorithms, proposed models tend to carry and reinforce unintended social biases. In this study, we try to answer the research question of “Can we mitigate the unintended bias of cyberbullying detection models by guiding the model training with fairness constraints?”. For this purpose, we propose a model training scheme that can employ fairness constraints and validate our approach with different datasets. We demonstrate that various types of unintended biases can be successfully mitigated without impairing the model quality. We believe our work contributes to the pursuit of unbiased, transparent, and ethical machine learning solutions for cyber-social health. CYBERBULLYING (CB) has emerged as a seri- ous and widespread adverse phenomenon among online social interactions in today’s digital soci- ety. Estimates indicate that between 15-35% of young people have been victims of cyberbullying and between 10-20% of individuals admit to hav- ing cyberbullied others [1]. Cyberbullying can be observed in the form of aggression, harassment, derogation, dehumanization, toxicity, profanity, racism, sexism, call for violence, hate speech, threatening, or any combination thereof. Conse- quences of cyberbullying are severe as victims were shown to be at a greater risk of depression, anxiety, negative emotions, self-harm, suicidal be- haviors, and psychosomatic symptoms than non- victims. i.e., automatically classifying online text messages based on bully- ing content with machine learning, has been pro- posed by numerous studies to detect and prevent this phenomenon [2]. Accurate and timely detec- tion of cyberbullying remains an unsolved task as cyberbullying is immensely context-dependent and occasionally subtle (e.g. hidden mockery and sarcasm). In addition, significant amount of cyberbullying takes place in private conversations without any publicity. Statistical drifts and over- all changes in popular culture, politics, human language, and media of communication further increase the complexity of this task. While cyberbullying detection research focus predominantly on increasing the overall accuracy and timeliness of detection, recent studies reveal that proposed systems carry significant amount of unintended bias against certain groups of users, demographics, languages, dialects, terms, phrases, or topics. For instance, terms like “gay” and “jew”, present in an informative or conversa- tional context, tend to incline the model predic- tions towards “hate speech” or “high toxicity”. tweets in African-American English Similarly, were shown to be more likely to be classified as abusive or offensive compared to other tweets [3]. As such groups can be minorities among the whole population, trying to maximize the detec- tion accuracy and evaluating approaches solely 1 2 on overall detection performance exacerbates the bias even further. The source of these undesir- able biases can be machine learning algorithms, datasets used for training, pre-trained language models, human annotators, or typically a combi- nation thereof. In this study, we try to answer the following two research questions: “Can we mitigate the unintended bias of cyberbullying detection mod- els by guiding the model training with fairness constraints”? and “If so, how much does such bias mitigation impair the cyberbullying detection performance”?. We hypothesize that, if formu- lated in a fairness context, recent advancements in constrained optimization [4] can be successfully utilized to mitigate the unintended bias in cyber- bullying detection models without hindering over- all detection performance. To test our hypothesis, we formulate frequently used fairness assessment metrics from the literature as constraints that can be utilized during model training. We then validate the proposed approach with 4 different datasets and varying bias contexts such as gender bias, language bias, and recency bias. We show that our approach enables the discovery of models with more equitable performance across differ- ent groups of interest while improving overall and group-specific cyberbullying detection per- formances. In addition, our approach is agnostic to data modality (e.g. text, image, graph, tabular) and does not require group labels during infer- ence. We release the full source code of our study along with the trained models (https://github.com/ ogencoglu/fair cyberbullying detection). We be- lieve our work contributes to the pursuit of un- biased, transparent, ethical, and accountable ma- chine learning solutions for cyber-social health. # THE PURSUIT OF FAIRNESS Previous studies of cyberbullying detection utilized numerous machine learning approaches varying from rule-based systems to deep learn- ing [2]. Reported performances of the proposed approaches differ significantly between studies as well (F1 scores in the range of 0.4-0.8 for most studies), depending on the experimentation dataset and definition of CB [2]. As in several other natural language processing (NLP) tasks, most recent CB detection studies utilize deep neu- ral networks and transfer learning, i.e., employing a pre-trained language model to retrieve informa- tive numerical representations of the textual data (e.g. representations of tokens, words, sentences, or paragraphs) and training a classifier with these representations [5], [6]. Computational methods can propagate and even reinforce social biases. A machine learning model is considered to contain unintended bias if it performs better for some demographic groups or groups of interest than others. In natural lan- guage processing, unintended biases emerge from bias in datasets, bias in distributed word embed- dings (e.g. word2vec, GloVe), bias in contextual word embeddings (e.g. BERT, ELMo, GPT-2), bias in sentence embeddings, bias in machine learning algorithms, or bias in human annotators. For instance, a recent study by Nadeem et al. show that stereotypical bias is amplified as pre- trained language models (e.g. BERT, RoBERTa, XLNet, GPT-2) become stronger [7]. While there have been several studies of CB detection and several studies of algorithmic bias analysis in ma- chine learning, only a handful of studies attempt to combine the two. To the best of our knowledge, an extensive systematic review of bias quantifi- cation and mitigation methods in cyberbullying detection does not exist as of August 2020. In cyberbullying detection context, even though studies show that CB is more common to be perpetrated by certain identity groups (e.g. young males) and perpetrated against certain identity groups (e.g. non-heterosexuals), detection performance of an unbiased model in terms of equality of odds is expected to be the same among all groups as well as with respect to the overall population. For instance, an unbiased model should not classify a text containing iden- tity terms (e.g. black, jew, gay, white, christian, transgender) in an innocuous context as “cyber- bullying” only because such terms appear fre- quently in cyberbullying incidents. Nonetheless, previous studies show that models tend to label non-toxic statements containing identity terms as toxic, manifesting a false positive bias [8], [9]. Bias is observed against different languages and dialects as well. Classifiers were shown to predict African-American English tweets more likely to be abusive or offensive than Standard American English [3]. Proposed approaches for mitigation of unin- tended bias in CB detection predominantly in- volve balancing the training data in some statisti- cal sense, such as oversampling, data augmenta- tion, or sample weighting. For instance, Dixon et al. add additional non-toxic examples containing identity terms from Wikipedia articles to training data [8]. Badjatiya et al. detect bias-sensitive words and replace them with neutral words or tokens to reduce stereotypical bias for hate speech detection [10]. Nozza et al. sample additional data from an external corpus to augment training data for misogyny detection [5]. Similarly, Park et al. augment the training data by identifying male entities and swapping them with equivalent female entities and vice-versa in order to reduce gender bias in abusive language detection [9]. These methods, inevitably, introduce additional calibration hyper-parameters that are highly influ- ential both on the performance of cyberbullying detection and bias mitigation. For instance, in- creasing the prevalence of disadvantaged groups during training may impair overall classification performance due to high distortion of decision boundary in the feature space. Furthermore, as the statistical properties of the modeled phenomena change over time in unforeseen ways (also known as concept drift), proposed calibration parameters become obsolete with time in real-life applica- tions. In this study, we formulate the task of training more equitable CB detection models as a con- strained optimization problem. Just like standard deep neural network training, the optimization task corresponds to adjusting model weights by minimizing a loss function, iterated over the training data. However, by imposing fairness con- straints during model training, we enforce training to converge to a more equitable solution for the chosen groups of interest. Essentially, our method does not alter the training data and can be used simultaneously with the abovementioned data de- biasing methods for further bias mitigation. # METHODS # Datasets We validate our methods by performing exper- iments with 4 publicly available datasets collected from 4 different media. In order to further test the generalization power of the proposed bias May 2020 mitigation approach, we appoint different identity including group contexts for each experiment identity-related groups, language-related groups, and date-related groups. Datasets differ from each other regarding total number of samples, overall proportion of cyberbullying samples, and group- specific proportions of cyberbullying samples. Focus of the first experiment is gender bias. We demonstrate our method on the Perspective API’s Jigsaw dataset of 403,957 comments with toxicity and identity annotations [11]. We select male and female identities as groups of interest. Percentage of the male and female groups are 11.0% and 13.2%, respectively. Toxicity propor- tion among the male and female groups are 15.0% and 13.7%, respectively and overall toxicity pro- portion in the dataset is 11.4%. Focus of the second experiment is language bias. We employ a multilingual dataset of 107,441 tweets with hate speech annotations in 5 lan- guages, namely English, Italian, Polish, Por- tuguese, and Spanish [6]. Percentage of English, Italian, Polish, Portuguese, and Spanish tweets are 78.1%, 5.4%, 10.2%, 1.8%, and 4.6%, respec- tively. Hate speech proportion among English, Italian, Polish, Portuguese, and Spanish tweets are 26.2%, 19.5%, 9.0%, 20.3%, and 39.7% respec- tively and overall hate speech proportion in the dataset is 24.6%. Third experiment has a more practical fo- cus of date bias or recency bias. As popular culture and languages change, new phrases of insult may emerge, leading to underperforming models on more recent observations. We would like to first demonstrate, then mitigate the bias of recency in CB classifiers. The dataset uti- lized for validating our mitigation approach is WikiDetox dataset (shortly referred as Wiki from now on) from Wikipedia Talk Pages [12]. This dataset consists of three distinct corpora of com- ments from English Wikipedia Talk pages posted between 2001-2016 and labeled for aggression, personal attack, and toxicity. We select 77,972 comments that have all of the annotations regard- ing aggression, personal attack, and toxicity for this study. The groups of interest are comments posted between the years 2001-2014 and 2015- 2016 (recent group). Percentage of the 2001- 2014 and 2015-2016 groups are 93.8% and 6.2%, respectively. CB proportion among the 2001-2014 3 4 and 2015-2016 groups are 20.9% and 19.3%, respectively and overall CB proportion in the dataset is 20.8%. Final experiment concentrates on bias among hate speech on the basis of religion, race, and nationality. For this purpose, we utilize the largest corpus of hate speech to date with theoretically- justified annotations called Gab Hate Corpus [13]. Dataset consists of 27,665 posts from the social network platform Gab. Percentage of hate speech on the basis of religion, race, and nationality are 5.1%, 6.5%, and 4.8%, respectively. Hate speech proportion among the religion, race, and nationality groups are 51.2%, 53.7%, and 39.6%, respectively and overall hate speech proportion in the dataset is 8.0%. # Cyberbullying Detection Model We utilize recently introduced deep neu- ral network architectures from NLP research, i.e. transformer networks, for performing binary classification of cyberbullying (cyberbullying or not). We employ a multilingual language model, sentence-DistilBERT [14], for extracting sentence embeddings to represent each post/comment. We then train a simple 3-layer (2 dense layers of size 512 and 32, respectively and an output layer) fully-connected neural network using the sentence embeddings as input features. We chose sentence embeddings instead of fine-tuning on token embeddings (e.g. out of original BERT model or its variants) firstly due to its low computational requirements [14]. Sec- ondly, even though it is possible to represent sentences with a standard BERT model as well (e.g. by averaging the token embeddings out of layer), for several semantic textual the output similarity tasks BERT sentence embeddings were shown to be inferior to embeddings specifically trained for representing sentences [14]. We chose a multilingual model to be able to extract useful representations from the Twitter dataset as well, as it includes tweets from 5 different languages. For each dataset, we train baseline (uncon- strained) and fairness-constrained models in a mini-batch manner for 75 epochs with a batch size of 128 with Adam optimizer (learning rate of 5 × 10−4). In order to avoid overfitting, mod- els at the epoch that maximizes the F1 score on the validation set (70%-15%-15% training- validation-test split) is selected as final model for each training. Baseline and fairness-constrained models are trained, validated, and tested with the same data and employ the same neural network architecture with the same hyper-parameters in order to establish fair comparison. We would like to emphasize that instead of maximizing the cy- berbullying detection performance, mitigation of unintended bias while maintaining the detection performance has been the main focus of this study. Therefore, we neither experimented with different text preprocessing schemes, pretrained models, sophisticated neural network architec- tures, nor performed any hyper-parameter tuning. # Fairness Constraints Fairness of machine learning models can be assessed by the metrics False Negative Equality Difference (FNED) and False Positive Equality Difference (FPED), as done in several studies [6], [8], [9]. FNED/FPED is simply the sum of deviations of group-specific False Negative Rates (FNRs)/False Positive Rates (FPRs) from the overall FNR/FPR. For N groups and set of observations belonging to each group being Gi ∈ {1,··· ,N }, FNED= S_ |FNR-FNRe, i€{1,--,N} FPED= \S_ |FPR-FPRe||. i€{1,-- ,N} In essence, group-specific error rates of fairer models deviate less from the overall error rates and consequently from each other, approaching an ideal equality of odds. Being related to the equalized odds fairness criteria, sum of FNED and FPED corresponds to the total unintended bias of a model (ideally zero). Neural network training can be formulated as finding a set of parameters (network weights), θ, minimizing an objective function, fL: min θ fL(θ), (2) where fL is typically binary cross-entropy loss for binary classification tasks (such as here) and min- imization is performed by backpropagation algo- rithm on the training set. In fairness-constrained neural network training, we would like to min- imize the same function in Equation (2) while constraining the deviation of each group-specific FNR/FPR from the overall FNR/FPR in order to decrease the unintended bias, i.e., min θ fL(θ) subject to |F N R − F N RG1| < τF N R |F P R − F P RG1| < τF P R · · · |F N R − F N RGN | < τF N R |F P R − F P RGN | < τF P R, where τF N R and τF P R are allowed deviations (corresponding to biases) from overall FNRs and FPRs, respectively. In principle, implementation of Equation (3) involves 2N constraints (one for FNR and one for FPR for each group of interest). As constraints are inherently guiding the neural network training in our method, convergence becomes more difficult with increasing number of constraints. Therefore, it is beneficial to express the same inequalities with fewer number of constraints such as: min θ s.t. max{F N RG1, · · · } − F N R < τF N R F N R − min{F N RG1, · · · } < τF N R max{F P RG1, · · · } − F P R < τF P R F P R − min{F P RG1, · · · } < τF P R. (4) By constraining the upper and lower bounds of group-specific FNRs/FPRs with respect to over- all FNR/FPR, number of constraints can be de- creased strictly to four. Proposed constraints in Equation (4) correspond to direct incorporation of fairness metrics into neural network training in Equation (1). Essentially, such worst-case ori- ented reformulation of the fairness constraints can be considered as a robust optimization problem. Typical approaches that perform constrained optimization are based on Lagrange multipliers where a saddle point to the Lagrangian will cor- respond to an optimal solution (under fairly gen- eral conditions). However, this no longer holds for non-convex settings such as neural network training with gradient descent. In fact, gradient descent may not converge at all and oscillate in such settings. Furthermore, constrained neural network training (as well as training of several May 2020 (3) other machine learning algorithms) requires dif- ferentiable constraints and loss functions in order to compute the gradients for minimizing a given empirical loss. Considering fairness constraints are data-dependent counts and proportions (e.g. false positive rate), gradients (or subgradients) are either unavailable or always zero. To over- come this challenge, we propose utilizing recent advancements in solving constrained, non-convex optimization problems in which constraints can be non-differentiable (as in our study) [4]. Cotter et al. formulate such a problem as a two-player zero-sum game and introduce proxy constraints that are differentiable approximations of the orig- inal constraints [4]. During training, each proxy constraint function is penalized in such a propor- tion that the penalty satisfies the original (exact) constraint. implementation of constrained training is performed via two data streams. First data stream feeds random data batches and cor- responding binary labels (cyberbullying or not) to the model. Second data stream traces the samples belonging to the groups of interest in a given batch and computes the constraint vi- olations, which in return will be used for ad- ditional penalty on top of the misclassifica- tion penalization from the first stream. For in- stance, if the interest groups are race, religion, and nationality and τF N R is set the model will be penalized if the maximum of (F N Rrace, F N Rreligion, F N Rnationality) goes above F N Roverall + 0.1 or if the minimum of those goes below F N Roverall − 0.1 during each iteration. Same logic applies to FPRs. Once the model is trained, access to group attributes is not needed during inference, i.e., constrained models can be used in the same manner as unconstrained models. We implemented our experiments using TensorFlow framework in Python 3.7. We set τF N R to 0.02, 0.15, 0.005, and 0.1; τF P R to 0.03, 0.1, 0.005, and 0.15 for Jigsaw, Twitter, Wiki, and Gab experiments, respectively. Even though a hypothetical, perfectly unbiased model would have zero deviation between group- specific rates and overall rates, it is important to remember that perfect calibration (outcomes being independent of group attributes) can not be satisfied simultaneously with the balance for false negative and false positive rates. Therefore, 5 # 6 la +) True Label X S Positive negative o 2 True False o eas. eae 3 Q Positive Positive a 4 uv vo g a 3 o i o a & False True & . . g Negative Negative False False Negatives Positives FNR = —— FPR = Label Label Positives Negatives 2. The Positives F. score = True False False Positives Negatives Positives TP: TN - FP: FN arr + FP) (TP + EN) (TN + FP)-(TN + FN) MCC = Figure 1. Definition of common performance metrics for cyberbullying detection. forcing the model to satisfy overly-conservative fairness constraints (very small τF N R and τF P R) or multiple fairness notions simultaneously may not only impair classification performance, but may also result in training failing to converge (oscillating loss curves). Furthermore, overcon- straining the model may result in convergence to a trivial unbiased solution, such as a model outputting the same prediction regardless of the input. # Evaluation For evaluation of our methods we randomly split every dataset into training, validation, and test sets with 70%, 15%, and 15% splits, re- spectively (random seed is fixed for every exper- iment for reproducibility and fair comparison). All results reported in this study are calculated from the test set. Due to its popularity, we report the standard metric of F1 score of our binary classifiers. As accuracy, area under the receiver operating characteristic curve, and F1 score may lead to misleading conclusions on imbalanced datasets (such as here), we evaluate our mod- els with Matthews correlation coefficient (MCC) which does not exhibit such drawback [15]. MCC generates a high score only if the binary pre- dictor was able to correctly predict the majority of positive instances and the majority of nega- tive instances [15]. We use MCC for comparing group-specific detection performances between the baseline and fairness-constrained models as well. Furthermore, we perform McNemar’s test (also known as within-subjects chi-squared test) to test whether a statistically significant difference between baseline (unconstrained) and constrained models exists in terms of cyberbullying classi- fication accuracy. Definitions of False Negative Rate, False Positive Rate, F1 score, and Matthews correlation coefficient is depicted in Figure 1. For quantifying the unintended bias of our models, we use the sum of FNED and FPED, calculated on the test set. # RESULTS Results of each experiment on the test set including F1 score, Matthews correlation coef- ficient, precision, recall, false negative equality difference, false positive equality difference, and total bias for baseline and fairness-constrained models can be examined in Table 1. In addition, percentage decrease in total bias (baseline model vs. constrained model) is also reported in the same table. Group specific FNRs and FPRs as well as corresponding biases of each group for all experiments are displayed in Figure 2 for detailed inspection. Table 2 reports Matthews correlation coefficients of classifiers for each group of inter- est. Finally, we report the contingency tables of unconstrained and constrained models, calculated over the same test sets of all experiments in Table 3. All McNemar’s tests calculated from these contingency tables resulted in statistical significance with p < 0.001, therefore the null hypothesis (“predictive performance of two mod- els are equal”) can be rejected. Our results (see Table 1) show that training Jigsaw Dataset [ female ] Baas male [ female ] male 60 50 40 30 20 10 0 0 5 10 15 20 25 False Negative Rate (%) False Positive Rate (%) Twitter Dataset # Spanish 4 } # Portuguese 4 + # Polish # 4 a # italian 4 # L # English 4 # Spanish Portuguese Polish Italian UZZZZZZZZZ3+ English Se ee r . + + + 80 70 60 50 40 30 20 10 O 0 10 20 30 40 False Negative Rate (%) False Positive Rate (%) Wiki Dataset 2001-2014 25206. ———— 2001-2014 [ voiszoe | 30 20 10 0 0 5 To False Negative Rate (%) False Positive Rate (%) GAB Dataset EE , vxtionality | a eetigion ZZ (WLLL tae LZZZZZEEEZLLEEIELEEED eligion 60 50 40 30 20 10 0 0 10 20 30 40 50 60 False Negative Rate (%) False Positive Rate (%) ined regi overall FNR/FPR (unconstrained) unconstrained for group rates overall FNR/FPR (constrained) constrained 5 # bias Figure 2. False negative rates, false positive rates and biases for each group for unconstrained and fairness- constrained cyberbullying detection models on the test set among 4 experiments. May 2020 7 8 Table 1. Performance of baseline (unconstrained) and fairness-constrained cyberbullying detection models evaluated on the test set and corresponding biases (P = Precision, R = Recall). Baseline (unconstrained) Model Fairness-constrained Model Dataset F1 MCC P Jigsaw 0.51 0.46 0.39 0.75 0.74 0.65 0.70 0.79 Twitter 0.77 0.71 0.73 0.82 Wiki 0.45 0.41 0.34 0.65 Gab R FNED FPED 0.031 1.293 0.013 0.236 0.116 0.488 0.004 0.968 Total Bias 0.147 1.781 0.018 1.203 F1 MCC P 0.54 0.49 0.59 0.49 0.74 0.66 0.78 0.70 0.84 0.81 0.91 0.78 0.47 0.42 0.46 0.48 R FNED FPED 0.001 1.316 0.001 0.228 0.031 0.263 0.000 0.644 Total Bias 0.031 1.579 0.001 0.872 Bias Decr. (%) 78.7 11.3 94.9 27.5 Table 2. Group-specific Matthews correlation coefficients for baseline (unconstrained) and fairness-constrained models (better performance highlighted). Baseline Constrained Jigsaw male 0.427 0.453 female 0.401 0.470 Eng 0.711 0.710 Ita 0.315 0.332 Twitter Pol 0.263 0.300 Port 0.230 0.335 Spa 0.329 0.335 ’01-’14 0.703 0.807 Wiki ’15-’16 0.710 0.807 rel. 0.240 0.279 Gab race 0.198 0.225 nat. 0.473 0.412 Table 3. Contingency tables of baseline (unconstrained) and fairness-constrained cyberbullying detection models calculated from the test sets of each experiment. Jigsaw Twitter Wiki Gab Baseline model correct Baseline model wrong Baseline model correct Baseline model wrong Baseline model correct Baseline model wrong Baseline model correct Baseline model wrong Constrained model correct Constrained model wrong 48,802 1,888 5,849 4,055 13,398 539 758 1,422 10,205 299 768 424 3,582 57 222 289 p < 0.001 for all McNemar’s tests. neural network models with fairness constraints decrease the overall unintended bias of cyber- bullying classifiers significantly, while increasing overall CB detection performance in terms of MCC. Total bias decrease with respect to uncon- strained models corresponds to 78.7%, 11.3%, 94.9%, and 27.5% for Jigsaw, Twitter, Wiki, and Gab experiments, respectively. Total bias is mainly coming from the FNRs for Twitter and Wiki experiments while the main contributor of bias is the FPRs for Jigsaw and Gab experiments. Our approach manages to mitigate the total un- intended bias for both situations. Models trained on the Twitter dataset (five languages as groups of interest) carry the highest amount of total bias. Figure 2 shows that high FPR of Spanish and high FNR of Portuguese and Polish tweets are the main contributors to the bias. Models trained on the Gab dataset carry the second highest total bias especially due to high FPR of race and religion identity groups. Baseline model trained on the Wiki dataset exhibits very little bias among comments posted in the recent years vs. older comments. Guiding the model training with fair- ness constraints reduces that bias almost to zero. Our results in Table 2 show that group-specific CB detection performance increases with fairness constraints for almost all groups as well. Fur- thermore, Table 3 shows that constrained mod- els perform statistically significantly better than unconstrained models in terms of overall cyber- bullying detection accuracy. For instance for the same Jigsaw test set, 1,888 observations have been correctly classified by the unconstrained model while being misclassified by the con- strained model; however, 5,849 observations have been misclassified by the unconstrained model while being correctly classified by the constrained model. We believe future studies would benefit from similar contingency table analyses as well, especially if performance metrics of compared models are close to each other. # DISCUSSION We show that we can mitigate the unintended bias of cyberbullying detection models by guiding the model training with fairness constraints. Our experiments demonstrate the validity of our ap- proach for different contexts such as gender bias and language bias. Furthermore, we show that bias mitigation does not impair model quality, on the contrary, improves it. This improvement may be attributed to constraints serving as a regular- ization mechanism during training, similar to the common practice of constraining magnitudes of gradients or model weights. As our approach does not require modification of model architecture and does not need group labels during inference, we can conclude that the model is able to jointly learn the statistical properties of cyberbullying and group membership. High bias reduction of 78.7% and 94.9% is achieved in cases where there are only two groups of interest, i.e. male and female for Jigsaw and old and recent for Wiki experiment. We suspect that this is because learning to classify cyberbullying incidents are easier when only a few groups need to satisfy the upper-/lower-bound constraints. The lowest bias reduction, 11.3%, is achieved in the language bias mitigation experiment with the Twitter dataset where both unconstrained and constrained models perform considerably better for English tweets. Even though we utilize a mul- tilingual language model, this is not unexpected as English is the most prevalent language in the training data of pre-trained models as well as in the Twitter dataset itself. Models also show better performance in detecting hate speech on the basis of nationality vs. race and religion due to high false positive rates among race and religion groups in the Gab experiment. One interesting observation is that fairness constraints tend to lower overall FPR by sacri- ficing FNR. Consequently, precisions increase (as FNR is 1 - recall). This behaviour is meaningful in cases where the bias comes predominantly from FPED (e.g. Jigsaw and Gab), because there will be less room to deviate when FPRs are approaching to zero. However, we observe this phenomenon in Twitter and Wiki experiments as well and do not have an explanation to it. We also observe that constraints do not have to be satisfied perfectly for successful bias mitigation. For instance, Twitter and Gab experiments have several groups that do not fall into the allowed deviation region (green bands in Figure 2), yet still carry considerably less bias compared to unconstrained models. Our bias mitigation approach has several ad- vantages, especially in terms of generalization May 2020 ability. First, is agnostic to neural network model architecture, regardless of complexity. Sec- ond, it is agnostic to data type and number of identity groups. While previously proposed miti- gation methods rely heavily on textual data and statistical balancing of it, our method can work with any modes of data including images, text, or network attributes. Another practical advantage of constrained training of neural network models is that it enables defining arbitrary performance constraints in terms of various rates including FNR, FPR, precision, recall, or accuracy. Certain real-life CB detection applications may not afford to miss any cyberbullying incidents while others may require minimum false-alarms. The former will benefit from an allowed lower bound con- straint on the overall recall (i.e. recall should not decrease below the given value), while the latter application can employ an allowed upper bound constraint on the FPR. Our framework provides an uncomplicated mechanism to incorporate such constraints into training. Finally, as we address the problem of bias mitigation by adjusting the machine learning model rather than the data, our approach can be seamlessly combined with previ- ously proposed approaches for further reduction of unintended biases. Considering the high prevalence of cyberbul- lying in private conversations instead of public ones, our study shares the same limitations with the previous studies of automatic cyberbullying detection: data scarcity and data representative- ness. There is a scarcity of annotated datasets that are available to public for research due to protection of users privacy and immense need of resources for quality annotations. Such scarcity is amplified considering the research question of this study, as datasets having annotations of both identity attributes and cyberbullying are further limited. Therefore, we acknowledge that statistical distributions may differ largely among research datasets as well as between research datasets and real-life phenomena. Models trained and validated on specific cohorts, including our models, may not generalize to other cohorts or real-life scenarios. As discussed in [2], this may be due to varying definitions of cyberbullying or varying methodologies for data collection and annotation. Furthermore, models trained on data 9 # 10 collected from a certain period of time may not generalize to future scenarios due to distribution shift. Another limitation of our study is that we have adopted a broader definition of cyberbul- lying and treated each comment or post as an observation; ignoring the repetitiveness criteria of defining cyberbullying [2]. Future work includes investigating the perfor- mance of our bias mitigation approach among sub-groups (e.g. young Hispanic males) and com- bining our approach with previous studies that counteract bias by strategically altering the train- ing data. Validating our approach in a cross- dataset manner to test whether our mitigation approach generalizes across different cohorts is also in the scope of future work. As we have not performed any hyper-parameter tuning in this study, we also expect detection and bias mitiga- tion performance improvements by investigating the parameter choices. For instance, we have neither preprocessed the textual data, nor inves- tigated different network architectures. We also chose the same amount of allowed deviation from overall FNR/FPR as a fairness constraint for each group as we aimed to decrease the total bias in our experiments. Setting different thresholds for each group may lead to even more equitable models (yet increases the number of hyper-parameters to tune). Considering the rate of utilization of algo- rithms to all aspects of our lives, the demand from individuals for ethical and fair algorithmic decision making is expected to increase. Failing to mitigate unintended biases in such systems might negatively affect the business models of companies that utilize these technologies as well. Incorrect and unfair algorithmic content media- tion (takedowns, filtering, and automatic content moderation) may infringe on users free speech. Implementing fair machine learning systems and publishing the outcomes could instill greater con- fidence in users by increasing transparency and trust. Therefore, we should elevate our awareness for developing more equitable algorithms and should continue to develop methods to reduce the existing biases at the same time. # CONCLUSION In this study, we have aimed to mitigate the bias of cyberbullying detection models. For this purpose, we proposed a scheme to train cyberbul- lying detection models under fairness constraints. With our approach, we demonstrated that various types of unintended biases can be successfully mitigated without impairing the model quality. We believe our work contributes to the pursuit of more equitable machine learning solutions for cyberbullying detection. Future directions include combining our approach with other bias mitiga- tion methods and establishing a comprehensive framework for unbiased machine learning algo- rithms in cyber-social health applications. # REFERENCES 1. S. Hinduja and J. W. Patchin, “Bullying, cyberbullying, and suicide,” Archives of Suicide Research, vol. 14, no. 3, pp. 206–221, 2010. 2. H. Rosa, N. Pereira, R. Ribeiro, P. C. Ferreira, J. P. Carvalho, S. Oliveira, L. Coheur, P. Paulino, A. V. Sim ˜ao, and I. Trancoso, “Automatic cyberbullying detection: A systematic review,” Computers in Human Behavior, vol. 93, pp. 333–345, 2019. 3. T. Davidson, D. Bhattacharya, and I. Weber, “Racial bias in hate speech and abusive language detection datasets,” in Proceedings of the Third Workshop on Abusive Language Online, 2019, pp. 25–35. 4. A. Cotter, H. Jiang, and K. Sridharan, “Two-player games for efficient non-convex constrained optimiza- tion,” in Proceedings of the 30th International Confer- ence on Algorithmic Learning Theory, vol. 98, 2019, pp. 300–332. 5. D. Nozza, C. Volpetti, and E. Fersini, “Unintended bias in misogyny detection,” in IEEE/WIC/ACM International Conference on Web Intelligence, 2019, pp. 149–155. 6. X. Huang, X. Linzi, F. Dernoncourt, and M. J. Paul, “Multilingual Twitter corpus and baselines for evaluating demographic bias in hate speech recognition,” in Proceedings of the Twelveth International Conference on Language Resources and Evaluation (LREC), 2020. [Online]. Available: github.com/xiaoleihuang/Multilingual Fairness LREC 7. M. Nadeem, A. Bethke, and S. Reddy, “StereoSet: Measuring stereotypical bias in pretrained language models,” arXiv preprint arXiv:2004.09456, 2020. 8. L. Dixon, J. Li, J. Sorensen, N. Thain, and L. Vasser- man, “Measuring and mitigating unintended bias in text classification,” in Proceedings of the 2018 AAAI/ACM Conference on AI, Ethics, and Society, 2018, pp. 67– 73. 9. J. H. Park, J. Shin, and P. Fung, “Reducing gender bias in abusive language detection,” in Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, 2018, pp. 2799–2804. 10. P. Badjatiya, M. Gupta, and V. Varma, “Stereotypical bias removal for hate speech detection task using knowledge-based generalizations,” in The World Wide Web Conference, 2019, pp. 49–59. 11. D. Borkan, L. Dixon, J. Sorensen, N. Thain, and L. Vasserman, “Nuanced metrics for measuring unintended bias with real data for text classification,” in Companion Proceedings of The 2019 World Wide Web Conference, 2019, pp. 491–500. [Online]. Available: kaggle.com/c/ jigsaw-unintended-bias-in-toxicity-classification/data 12. E. Wulczyn, N. Thain, and L. Dixon, “Ex machina: Personal attacks seen at scale,” in Proceedings of the 26th International Conference on World Wide Web, 2017, pp. 1391–1399. [Online]. Available: figshare.com/ projects/Wikipedia Talk/16731 13. B. Kennedy, M. Atari, A. M. Davani, L. Yeh, A. Omrani, Y. Kim, K. Coombs Jr., G. Portillo- Wightman, S. Havaldar, E. Gonzalez, J. Hoover, A. Azatian, A. Hussain, A. Lara, G. Cardenas, A. Omary, C. Park, X. Wang, C. Wijaya, Y. Zhang, B. Meyerowitz, and M. Dehghani, “The gab hate corpus: A collection of 27k posts annotated for hate speech,” PsyArxiv Preprint 10.31234/osf.io/hqjxn, 2020. [Online]. Available: osf.io/edua3/ 14. N. Reimers and I. Gurevych, “Sentence-BERT: Sen- tence embeddings using Siamese BERT-networks,” in Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP), 2019, pp. 3982–3992. 15. D. Chicco and G. Jurman, “The advantages of the matthews correlation coefficient (MCC) over F1 score and accuracy in binary classification evaluation,” BMC Genomics, vol. 21, no. 1, p. 6, 2020. May 2020 11
Title: Capabilities of GPT-4 on Medical Challenge Problems: Summary: Large language models (LLMs) have demonstrated remarkable capabilities in natural language understanding and generation across various domains, including medicine. We present a comprehensive evaluation of GPT-4, a state-of-the-art LLM, on medical competency examinations and benchmark datasets. GPT-4 is a general-purpose model that is not specialized for medical problems through training or engineered to solve clinical tasks. Our analysis covers two sets of official practice materials for the USMLE, a three-step examination program used to assess clinical competency and grant licensure in the United States. We also evaluate performance on the MultiMedQA suite of benchmark datasets. Beyond measuring model performance, experiments were conducted to investigate the influence of test questions containing both text and images on model performance, probe for memorization of content during training, and study probability calibration, which is of critical importance in high-stakes applications like medicine. Our results show that GPT-4, without any specialized prompt crafting, exceeds the passing score on USMLE by over 20 points and outperforms earlier general-purpose models (GPT-3.5) as well as models specifically fine-tuned on medical knowledge (Med-PaLM, a prompt-tuned version of Flan-PaLM 540B). In addition, GPT-4 is significantly better calibrated than GPT-3.5, demonstrating a much-improved ability to predict the likelihood that its answers are correct. We also explore the behavior of the model qualitatively through a case study that shows the ability of GPT-4 to explain medical reasoning, personalize explanations to students, and interactively craft new counterfactual scenarios around a medical case. Implications of the findings are discussed for potential uses of GPT-4 in medical education, assessment, and clinical practice, with appropriate attention to challenges of accuracy and safety. # Capabilities of GPT-4 on Medical Challenge Problems Harsha Nori1, Nicholas King1, Scott Mayer McKinney2, Dean Carignan1, and Eric Horvitz1 # 1Microsoft 2OpenAI # Abstract Large language models (LLMs) have demonstrated remarkable capabilities in natural language understanding and generation across various domains, including medicine. We present a compre- hensive evaluation of GPT-4 [Ope23], a state-of-the-art LLM, on medical competency examinations and benchmark datasets. GPT-4 is a general-purpose model that is not specialized for medical prob- lems through training or engineered to solve clinical tasks. Our analysis covers two sets of official practice materials for the United States Medical Licensing Examination (USMLE), a three-step examination program used to assess clinical competency and grant licensure in the United States. We also evaluate performance on the MultiMedQA suite of benchmark datasets. Beyond measur- ing model performance, experiments were conducted to investigate the influence of test questions containing both text and images on model performance, probe for memorization of content during training, and study calibration of the probabilities, which is of critical importance in high-stakes applications like medicine. Our results show that GPT-4, without any specialized prompt crafting, exceeds the passing score on USMLE by over 20 points and outperforms earlier general-purpose models (GPT-3.5) as well as models specifically fine-tuned on medical knowledge (Med-PaLM, a prompt-tuned version of Flan-PaLM 540B). In addition, GPT-4 is significantly better calibrated than GPT-3.5, demonstrating a much-improved ability to predict the likelihood that its answers are correct. We also explore the behavior of the model qualitatively by presenting a case study that shows the ability of GPT-4 to explain medical reasoning, personalize explanations to students, and interactively craft new counterfactual scenarios around a medical case. Implications of the findings are discussed for potential uses of GPT-4 in medical education, assessment, and clinical practice, with appropriate attention to challenges of accuracy and safety. # Introduction Large language models (LLMs) have exhibited a remarkable ability to interpret and generate sequences across a wide array of domains, such as natural language, computer code, and protein sequences. Nu- merous powerful models are based on the transformer architecture [VSP+17], adapted to language and trained in a self-supervised manner [RNS+18, DCLT18]. Scores on a variety of benchmarks have gen- erally improved with scale, involving increasing model size, dataset size, and the amount of training computation in tandem [KMH+20, LBL+22]. The empirical findings resonate with a theoretical anal- ysis [BS21] which shows the necessity of scale for robustness of inferences from large neural models [BS21]. 1 Over the last several years, LLMs trained on massive, cross-disciplinary corpora have become potent building blocks in the creation of task-focused systems [BHA+21]. Methods for refining the models toward a particular domain include fine-tuning with specialized datasets drawn from target applications and general methods for steering the behavior of the models, such as reinforcement learning with hu- man feedback (RLHF), which guides the system toward a better understanding of end-users’ requests [CLB+17, BJN+22]. There has also been great interest in the ability of LLMs to make useful inferences for a broad range of specialized tasks without dedicated fine-tuning. The performance of general-purpose LLMs using few- or even zero-shot prompting highlights their potential for assisting with tasks across problem types, specialty areas, and disciplines [BMR+20]. Recently, researchers have investigated benchmarks that provide insight into how LLMs encode clinical knowledge and might be harnessed to augment the practice of medicine. Here we compare the performance of the recently released (text-only) GPT-4 model with its predecessors in the GPT family on medical challenge problems. While details on measures of scale for GPT-4, including the number of model parameters and the size and scope of training data, have not been made public, it has been reported that both dimensions are significantly bigger than for GPT-3.5, the model behind ChatGPT [Ope23]. Exploration of the capabilities of LLMs on medical problem solving is part of a long-standing research program on AI in medicine, going back to the classic work of Ledley and Lusted [LL59]. Over the decades since, explorations of computational methods for assisting physicians have been marked by shifting enthusiasm for different representations and reasoning methods, including core probabilistic and decision-theoretic methods (e.g., [GB68, HHN92]), rule-based production systems (e.g., [Sho77, BS84]), semantic graphs (e.g., [PSS81]), supervised learning from databases of medical information (e.g., [WGH16, HHPS15, ELS+20, CLG+15]), and deep neural network models (e.g., [EKN+17, SHJ+17, RIZ+17, MSG+20]). While the flurry of efforts to use deep learning to attain human-level performance on medical tasks began in the field of computer vision for diagnostics, it has since grown to encompass benchmarks for more general clinical reasoning mediated through natural language. The models deployed in this context may be trained on specific medical corpora or foundation models trained on massive amounts of general language and/or visual information and then adapted to medical data through dedicated fine-tuning. Our key contribution is to investigate the capabilities of GPT-4 on medical challenge problems. To establish strong baselines for comparison, we evaluate GPT-4 against GPT-3.5 and reported results from Flan-PaLM 540B. Our goal is to establish “out-of-the-box” performance numbers for GPT-4. To that end, we use the simplest prompts possible (a zero-shot and randomly selected 5-shot prompt with direct inference of the answer) and find that GPT-4 obtains best-in-class performance without any need for elaborate prompting techniques or domain-specific fine-tuning. We begin by interrogating the performance of the models on challenge problems developed to assess competencies of medical students and residents. This exploration consists of a comprehensive evaluation of the performance of GPT-4 on Steps 1-3 of the United States Medical Licensing Examination (USMLE). The exam is part of the official accreditation protocol though which medical licensure is determined in the U.S. Our results are based on sample exams and self-assessment materials officially published by the National Board of Medical Examiners (NBME). The findings show that zero-shot GPT-4 significantly outperforms earlier models, achieving an average score of 86.65% and 86.7% on the Self-Assessment and Sample Exam of the USMLE tests, respectively, compared to 53.61% and 58.78% for GPT-3.5. After reviewing results for the USMLE studies, we examine several other medical benchmarks. Zero- shot GPT-4 significantly outperforms GPT-3.5 and the recently introduced Flan-PaLM 540B model on MultiMedQA[SAT+22], a suite of commonly used benchmark datasets in the literature on machine learning for medicine. 2 Beyond characterizing overall performance, our investigation covers several other facets of LLM behavior in the medical domain. We study the performance of the text-only GPT-4 on examination questions that are text-centric versus questions that rely on images. Given that reliable information about the probability of correctness is critical in healthcare and other high-stakes applications, we evaluate the calibration of the probabilities implicitly assigned to answers. We assess evidence that the model has been exposed to (and memorized) the content of the examinations through its training data. We further explore qualitative behavior of the model via a case study that demonstrates the capabilities of GPT-4 to explain medical reasoning and interactively support students on counterfactual scenarios around a medical case. Finally, we examine the implications of our findings, including the potential for GPT-4 and its successors to help with medical education and to provide assistance to healthcare professionals, taking into consideration concerns related to accuracy, fairness, and broader impacts on the practice of medicine. We particularly reflect on the limitations of benchmark-based performance evaluations, and discuss the precautions and advances needed to make use of models like GPT-4 in real world settings. Significant work remains to evaluate these systems comprehensively, and much caution is needed. However, we expect multiple real world uses, such as lower stakes applications that include expert oversight as part of generations and workflows. In the longer-term, we see significant potential for GPT-4 and its successors to have a positive impact in medicine. # 2 Methodology While GPT-4 supports multi-modal capabilities [Ope23], our methodology focuses on a text-only version of the model, referred to as GPT-4 (no vision) by OpenAI. For simplicity, all subsequent references to GPT-4 in this paper refer to the text-only model without vision capabilities. Discussion of how the text-only model performs on questions with images can be found in Section 3.1.1. # 2.1 Datasets To evaluate GPT-4, we consider six datasets that cover different aspects of medical knowledge and reasoning. Two of these datasets, the USMLE Sample Exam and USMLE Self Assessments, are sourced directly from the the National Board of Medical Examiners (NBME), the organization that governs and administers the the examination process. The other four datasets, MedQA, PubMedQA, MedMCQA, and MMLU, are publicly available benchmarks that contain questions based on medical literature, clinical cases, and user-generated content. These four datasets have been widely used to benchmark LLM performance on medical reasoning tasks. All four datasets constitute a large part of the recently introduced “MultiMedQA” benchmark [SAT+22]. Details on each dataset are provided in Appendix A. 3 # 2.2 Prompting # Prompt template for multiple choice questions The following are multiple choice questions (with answers) about medical knowledge. {{few_shot_examples}} {{context}}**Question:** {{question}} {{answer_choices}} **Answer:**( Figure 2.1: Template used to generate prompts on all multiple choice questions (from [SAT+22]). Elements in double braces {{}} are replaced with question-specific values. # Sample question using prompt template The following are multiple choice questions (with answers) about medical knowledge. **Question**: A 40-year-old woman has had hypercalcemia for 1 year and recently passed a renal calculus. Serum parathyroid hormone and calcium concentrations are increased, and serum phosphate concentration is decreased. Parathyroid hormone most likely causes an increase in the serum calcium concentration by which of the following mechanisms? (A) Decreased degradation of 25-hydroxycholecalciferol (B) Direct action on intestine to increase calcium absorption (C) Direct action on intestine to increase magnesium absorption (D) Increased synthesis of 25-hydroxycholecalciferol (E) Inhibition of calcitonin production (F) Stimulation of 1,25-dihydroxycholecalciferol production **Answer:**(F Figure 2.2: Instantiated example of Figure 2.1. GPT-4’s (correct) response is shown in green. To establish baseline model performance, and provide fair comparisons, we employ the exact same prompting structure as [SAT+22]. An example of the template and a fully instantiated prompt are In the zero-shot setting, the few_shot_examples slot is shown in Figures 2.1 and 2.2, respectively. simply left blank. Similarly, for datasets that don’t provide additional context for each question, we leave the context slot blank as well. For models optimized for chat based scenarios, like ChatGPT and GPT-4, we make minor modifications to this template to simulate a conversation. Examples of the few-shot and chat-based versions of the prompts are presented in Appendix C. Our prompting structure enables us to benchmark more efficiently by using minimal context tokens and a single-generation token for each inference. Furthermore, we take advantage of the logit_bias parameter in OpenAI’s API to induce the model to generate only valid responses. For example, on a question with 4 multiple choice answers, A, B, C, and D, we pass: logit_bias = {32 : 25, 33 : 25, 34 : 25, 35 : 25} openai.completion.create(...logit_bias = logit_bias, ...) where 32-35 are the tokens that correspond to the letters A-D, respectively. 4 Our goal is to measure the baseline performance of GPT-4 on medical multiple-choice questions (MCQs) using a simple approach, without resorting to complex methods such as chain-of-thought prompting [WWS+22b], retrieval augmented generation [NHB+21], or ensembling strategies [WWS+22a]. In prior work, these methods have shown to enhance the performance of LLMs on medical MCQs considerably[SAT+22, WWS+22b]. However, we show that GPT-4 can attain outstanding results even without these techniques, exceeding both human performance levels and that of other models employing sophisticated prompting methods. We leave exploration of the larger space of performance optimization to future work. # 2.3 Model Comparison We evaluate both GPT-4 and its predecessor model, GPT-3.5, against all benchmark datasets studied in this paper. For each model, we consider both a zero-shot and 5-shot prompt following the template described in Figure 2.1. For zero-shot evaluations, we directly report accuracy on each dataset. In the 5-shot setting, we report leave-one-out cross validation (LOOCV) [HTFF09] accuracy, where for each evaluation sample, we draw the 5 few-shot exemplars randomly from the remainder of the dataset. We also incorporate results reported in the literature from other models evaluated on the same datasets, including ChatGPT, InstructGPT, Flan-PaLM 540B, and Med-PaLM. We note that Flan-PaLM 540B and Med-PaLM are currently unavailable for public consumption; therefore, any results reported on these models are sourced directly from [SAT+22]. # 3 Performance of GPT-4 on Medical Competency Exams We analyze model performance on two sets of official practice materials for the United States Medical Licensing Examination (USMLE). USMLE is a three-step examination program employed to assess clin- ical competency. Licensure for independent provision of healthcare in the United States requires passing the exam sequence. Each step marks a milestone in medical training. Step 1 of the USMLE exami- nation is typically taken by medical students after completing their preclinical training. Step 1 covers core clinical knowledge, including pathology and physiology, and the basis for medical conditions. Step 2, taken at the completion of an MD program, tests clinical understanding by probing the test-takers’ knowledge about diagnosis and patient management. Scores on Step 2 are often considered in decisions about interviews and acceptance into residency programs. Step 3 is the final examination in the USMLE sequence. The exam assesses medical residents’ ability to apply their working knowledge of medicine in the unsupervised practice of medicine. The test probes working clinical and biomedical knowledge deemed as essential for taking on independent responsibility for providing general medical care. Passing performance on Step 3 is required for being licensed to practice medicine without supervision. We emphasize that the materials we used in this section of our benchmarks are officially purchased and sourced from the National Board of Medical Examiners (NBME), which is one of the organizations that develops and administers the USMLE. While some publicly available datasets and papers rely on unofficial, third-party sources to approximate USMLE performance (e.g., the MedQA dataset1, evaluated in section 4), we believe the USMLE Sample Exam and USMLE Self Assessment are among the most authentic sources of exam questions available for this type of study. More details about the datasets can be found in Appendix A, with concerns about model memorization discussed in Section 6.2. 1See the discussion about MedQA and other unofficial datasets from the USMLE: https://www.usmle.org/usmle- program-discusses-chatgpt 5 # 3.1 Results GPT-4 shows a remarkable improvement over its predecessor models on official USMLE exam questions, improving by over 30 percentage points on both exams when compared to GPT-3.5. We also find that GPT-4 shows a similarly precipitous improvement over recent independently reported performance metrics for ChatGPT, a popular variant of GPT-3.5 optimized for chat-based interaction [KCM+23]. Med-PaLM and Flan-PaLM 540B are not currently available for public use, so we are unable to report their performance on these particular datasets. Comparisons against previously reported results from the PaLM family of models [SAT+22] are available in Section 4. The USMLE website states that, while specific pass thresholds vary every year, examinees must answer approximately 60 percent of multiple-choice questions correctly to achieve a passing score2. While earlier models like GPT-3.5 were approaching the passing threshold, GPT-4 clears this bar by a large margin. Table 1: Comparison of performance of models on the USMLE Self Assessment. GPT-4 significantly outperforms GPT-3.5. USMLE Self Assessment GPT-4 (5 shot) GPT-4 (zero shot) Step 1 Step 2 Step 3 85.21 89.50 83.52 83.46 84.75 81.25 54.22 52.75 53.41 49.62 48.12 50.00 Overall Average* 86.65 83.76 53.61 49.10 # GPT-3.5 GPT-3.5 (zero shot) (5 shot) * Calculated as #correct different sample size. #questions across all three steps. Each step has slightly Table 2: Comparison of performance of models on the USMLE Sample Exam. This dataset is considered in [KCM+23]. GPT-4 significantly outperforms both GPT-3.5 and independently reported ChatGPT scores. USMLE Sample Exam GPT-4 (5 shot) GPT-4 (zero shot) GPT-3.5 GPT-3.5 (zero shot) (5 shot) ChatGPT† (zero shot) Step 1 Step 2 Step 3 85.71 83.33 90.71 80.67 81.67 89.78 52.10 58.33 64.96 51.26 60.83 58.39 55.1 59.1 60.9 Overall Average* 86.70 84.31 58.78 56.91 – * Calculated as #correct #questions across all three steps. Each step has slightly different sample # size. † ChatGPT-3.5 as tested by [KCM+23]. We report scores from their ”MC-NJ en- coding with indeterminate responses censored” setting as the most similar to ours. Note that [KCM+23] removes questions with media elements while we do not. 2https://www.usmle.org/scores-transcripts 6 # 3.1.1 Language- and Vision-Centric Challenges The performance of the GPT-4 model (without vision) on the USMLE Self Assessment and Sample Exam is especially surprising as both exams make frequent use of media elements (e.g. graphs, photographs, charts) in their questions, which do not get passed to the model. In a manual labeling exercise, we found that the Self Assessment had 314 questions with references to media out of 2173 total (14.4% of the dataset), while the Sample Exam had 49 questions referencing media out of 376 total (13.0% of the dataset). Table 3: Accuracy on questions that reference visual media (images and graphs) that were not passed to the model, compared to accuracy on questions with pure text. Dataset Question Type GPT-4 (5 shot) GPT-4 (zero shot) GPT-3.5 GPT-3.5 (zero shot) (5 shot) USMLE Self Assessment Text Media All 89.51 69.75 86.65 86.39 68.15 83.76 55.30 43.63 53.61 50.40 41.40 49.10 USMLE Sample Exam Text Media All 87.77 79.59 86.70 85.63 75.51 84.31 59.63 53.06 58.78 57.80 51.02 56.91 A segmented performance analysis of these questions is presented in Table 3. While GPT-4 (no vision) performs best on questions that contain only text, it still performs well on questions with media elements, obtaining 70-80% prediction accuracies for these questions on both exams. Investigating this phenomena further revealed that, despite not being able to see relevant images, the text-only GPT-4 model is often able to employ logical reasoning and test-taking strategies to select a reasonable answer choice. A demonstrative example of our interactive investigation is shown in Figure 3.1. 7 # GPT-4: Solving a question without seeing media. QUESTION: A 45-year-old man comes to the physician because of a 10-year history of heartburn that occurs after he eats late at night or consumes spicy food. He has had no weight loss or difficulty swallowing. He takes over-the-counter antacids as needed, but they relieve his discomfort only temporarily. Physical examination shows no abnormalities. An endoscopy is done. The distal esophagus is shown in the photograph. Which of the following is the most likely cause of this patient’s symptoms? ANSWER CHOICES: “A”: “Defect in secretin production” “B”: “Excessive gastrin production” “C”: “Excessive tran- sient lower esophageal relaxations” “D”: “Failure of primary esophageal peristalsis” “E”: “Failure of saliva production” ANSWER: C —– Q: “You are a large language model that just answered the following question. Why did you pick the answer choice C?” A: “The answer choice C, “Excessive transient lower esophageal relaxations,” is the most likely cause of this patient’s symptoms because it is the most common cause of gastroesophageal reflux disease (GERD). GERD is a condition in which stomach acid flows back into the esophagus, causing heartburn and other symptoms. The lower esophageal sphinc- ter (LES) is a ring of muscle at the bottom of the esophagus that normally prevents stomach acid from flowing back into the esophagus. Transient lower esophageal relaxations (TLESRs) are episodes in which the LES relaxes inappropriately, allowing stomach acid to flow back into the esophagus. TLESRs are the most common cause of GERD, and they are often triggered by factors such as eating late at night or consuming spicy food, as described in the patient’s history. The other answer choices are less likely to be the cause of this patient’s symptoms.” —– Q: “Doesn’t the question mention a photograph? How did you come up with the answer without seeing the photo?” A: “You are correct that the question mentions a photograph of the distal esophagus. However, the answer choice C, “Excessive transient lower esophageal relaxations,” is the most likely cause of this patient’s symptoms based on the clinical history provided in the question, regardless of the findings on the photograph. The patient’s 10-year history of heartburn that occurs after eating late at night or consuming spicy food, and the temporary relief of symptoms with antacids, are consistent with a diagnosis of gastroesophageal reflux disease (GERD). The most common cause of GERD is excessive transient lower esophageal relaxations (TLESRs), which is why answer choice C is the most likely cause of this patient’s symptoms. The photograph of the distal esophagus would be useful for confirming the diagnosis of GERD and assessing for any complications, but it is not necessary for selecting the most likely cause of the patient’s symptoms based on the clinical history provided in the question.” Figure 3.1: GPT-4 is asked to answer and then explain how it (correctly) solved a question which involves a photograph, without seeing the photo. # 3.2 Influence of Alignment and Safety Tuning The results above demonstrate the capabilities of the publicly released version of GPT-4. As described by [Ope23], GPT-4 was developed in two major phases. The pretraining phase focused on maximizing the ability of the model to predict the next token in a document using a variety of data, both publicly available and privately licensed. In a subsequent post-training phase, the model was fine-tuned using RLHF [CLB+17] to enhance its ability to follow instructions and its propensity for producing fair and safe outputs [OWJ+22]. Several stages of refinement were aimed at minimizing undesirable behaviors such as gender bias, toxic language and stereotyping, dangerous recommendations, and harmful manipulation. OpenAI’s experiments indicated that the RLHF-centric refinement did not adversely affect the model’s capabilities on the exams they tested [Ope23]. 8 Table 4: Performance comparison of the publicly released GPT-4 model with GPT-4-base. Dataset Component GPT-4-base GPT-4-base GPT-4 (5 shot) (5 shot) (zero shot) GPT-4 (zero shot) USMLE Self Assessment Step 1 Step 2 Step 3 86.72 91.50 85.23 85.38 90.62 85.23 85.21 89.50 83.52 83.46 84.75 81.25 USMLE Sample Exam Step 1 Step 2 Step 3 85.71 85.00 92.70 84.87 86.67 93.43 85.71 83.33 90.71 80.67 81.67 89.78 We gained access to the base model, which we refer to as GPT-4-base, to study potential differences in performance attributable to the alignment process. The results of this evaluation are presented in Tables 4 and 5. While GPT-4-base and the release model both exhibit consistently strong performance across all 14 experimental datasets under study, we observe a notable increase of 3-5% when using the base versus the release model. The experiments suggest that orienting the base model toward safety and instruction-following can influence performance on medical benchmarks. The observed diminishment of raw performance accom- panying the alignment process frames directions for future research. Refinements to the fine-tuning procedures employed to shape GPT-4-base into the publicly released GPT-4 may be able to better nav- igate the tradeoff between safety and accuracy. Additionally, alternative fine-tuning techniques, such as incorporating expert domain knowledge or leveraging specialized medical datasets, may lead to further improvements in model performance without sacrificing safety and instruction-following capabilities. # 4 Medical Challenge Benchmarks We present benchmarks for four multiple-choice datasets from MultiMedQA [SAT+22]. The benchmarks include MedQA, PubMedQA, MedMCQA, and medical components of MMLU. MultiMedQA contains three more datasets which are not tested here. The untested datasets are LiveQA, MedicationQA, and HealthSearchQA; all have long answer formats that require extensive expert analysis to determine answer quality. Additionally, HealthSearchQA does not appear to be publicly available. 9 # 4.1 Results Table 5: Performance of different models on multiple choice components of MultiMedQA [SAT+22]. GPT-4 outperforms GPT-3.5 and Flan-PaLM 540B on every dataset except Pub- MedQA. GPT-4 and GPT-3.5 were prompted with zero-shot direct prompts. Dataset GPT-4-base 5 shot / 0 shot GPT-4 5 shot / 0 shot GPT-3.5 5 shot / 0 shot MedQA Mainland China Taiwan US (5-option) US (4-option) 78.63 / 74.34 87.47 / 85.14 82.25 / 81.38 86.10 / 84.45 75.31 / 71.07 84.57 / 82.17 78.63 / 74.71 81.38 / 78.87 44.89 / 40.31 53.72 / 50.60 47.05 / 44.62 53.57 / 50.82 – – – 60.3** PubMedQA Reasoning Required 77.40 / 80.40 74.40 / 75.20 60.20 / 71.60 79.0 MedMCQA Dev 73.66 / 73.42 72.36 / 69.52 51.02 / 50.08 56.5 MMLU Clinical Knowledge Medical Genetics Anatomy Professional Medicine College Biology College Medicine 88.68 / 86.79 97.00 / 94.00 82.96 / 85.19 92.65 / 93.75 97.22 / 95.83 80.92 / 80.35 86.42 / 86.04 92.00 / 91.00 80.00 / 80.00 93.75 / 93.01 93.75 / 95.14 76.30 / 76.88 68.68 / 69.81 68.00 / 70.00 60.74 / 56.30 69.85 / 70.22 72.92 / 72.22 63.58 / 61.27 77.0 70.0 65.2 83.8 87.5 69.9 # Flan-PaLM 540B* few shot * Sourced directly from [SAT+22]. We use Flan-PaLM 540B few-shot results as the most directly comparable setting to our experimental setup. The number of few shot prompts used by Flan-PaLM 540B varies per dataset (between 3 and 5). ** We note that [SAT+22] reports a preliminary performance of 67.2% here with Med-PaLM, a prompt-tuned variant of Flan-PaLM 540B, using an ensemble of chain-of-thought, few-shot prompts. For the MedQA and MMLU datasets, we report stratified performance metrics across different sub- components of the benchmarks. The MedQA benchmark also includes examination questions from mainland China and Taiwan, and covers three languages: English, simplified Chinese, and traditional Chinese. The English/United States version of the dataset contains two variants: a standard version with 5 multiple choice answers, and a simplified version with only 4 options. We report on both variants across all models considered. Similar to prior observations [Ope23], we find that GPT-4 continues to perform well on difficult questions presented in non-English languages (Table 5). In addition to the above results, [LHW22] tested InstructGPT and Codex (text-davinci-002 and code-davinci-002 in the OpenAI API, respectively) with a large variety of prompts on MedQA, Pub- MedQA, and MedMCQA. When using zero-shot direct prompts, InstructGPT scored 46.0 on MedQA, 73.2 on PubMedQA, and 44.0 on MedMCQA. The best results from [LHW22] come from testing Codex with an ensemble of 100 chain-of-thought samples, in which Codex scores 60.2 on the USMLE com- ponent of MedQA, 59.7 on the dev set of MedMCQA, and 78.2 on PubMedQA. In contrast, GPT-4 10 shows a large boost in performance on MedQA and MedMCQA with a much simpler zero-shot prompt, continuing the narrative that the effort needed to obtain great performance drops dramatically with each model generation. # 5 Calibration We now focus on GPT-4’s calibration, a measure of the agreement between the predicted probabilities of each answer’s correctness and the true frequencies of the outcomes. Calibration of the likelihood of the correctness of answers, or any assertions generated by an LLM, is critical for applications in high-stakes domains like medicine. A well-calibrated model can provide trustworthy and interpretable probabilities that reflect the confidence of the model. Conversely, a poorly calibrated model can mislead users with overconfident or underconfident predictions, which can have harmful consequences. Thus, appropriate characterizations of uncertainty about the veracity of generated content is important when providing generations, such as diagnoses and therapy plans, to healthcare professionals and other consumers of the information. For example, the probability that a treatment will be successful can be used in an expected-value calculation weighing the risks and benefits of a course of therapy. Looking to future applications of LLMs in medicine and other high-stakes areas, well-calibrated probabilities of generated content would enable contributions of LLM output to expected-utility decision making. We note that good calibration is not the same as high predictive accuracy. Predictive models can be accurate, yet poorly calibrated [NMC05]. Calibration Curve on USMLE Datasets 1 — — Perfect —e— GPT-4 —e— GPT-3.5 yp 08 oO = a c 6 Fs] 0.6 oO 2 £ S o “ o (0.4 < o Pd o © i “0.2 - - - - - o- i} 0.2 0.4 0.6 0.8 1 Mean predicted probability Figure 5.1: Calibration comparison of GPT-4 and GPT-3.5 on the USMLE Self-Assessment and Sample Exam. A common method for measuring calibration is the aptly-named calibration plot. These plots bin predictions by their estimated probabilities, and measure how close the average probability in each bin is 11 to the true positivity rate. We adapt our multiple-choice question-answering setting to this framework by using the probability of the selected answer choice for each question. In Figure 5.1, we compare GPT-4’s calibration to that of GPT-3.5 on both official USMLE datasets. We find that GPT-4 exhibits significantly better calibration than its predecessor on this type of data. For example, datapoints that GPT-4 assigns an average probability of 0.96 tend to be correct 93% of the time. In contrast, datapoints where GPT-3.5 assigns a similar probability are only correct 55% of the time. We are only able to conduct this experiment in the multiple-choice question-answering setting where we have the model score each option. Measuring calibration and probabilities of long-form generation from generative models is an open area of research. However, our results on the multiple-choice problems suggest that the probability calibration of language models may increase with scale. # 6 Directions and Limitations Our paper demonstrates the impressive potential of GPT-4 to answer multiple choice questions on the USMLE, a medical licensing examination. We now review limitations and potential extensions of our studies. # 6.1 Richer Prompting Strategies A key goal of this paper is to establish baseline model performance metrics—that is, to determine how well GPT-4 can perform without requiring any specialized knowledge of LLMs and prompting. Histor- ically, more sophisticated prompting methods like chain of thought prompting [WWS+22b, KGR+22], ensemble approaches like self-consistency prompting [WWS+22a], or giving models access to informa- tion retrieval tools [NHB+21] have all proven to significantly improve performance. Furthermore, it is possible that new prompting patterns that work optimally for a new model like GPT-4 have yet to be discovered. It is very likely that careful exploration of prompting techniques and fine tuning can achieve significantly higher performance numbers. As solely maximizing benchmark performance is not the goal of this paper, we largely leave those explorations to future work. We share the results of two preliminary experiments we did below on chain-of-thought prompting and expert curation of few shot examples. Chain of Thought. Following the work of [KGR+22] and [WWS+22b], we experiment with a two- stage chain-of-thought prompt on the USMLE sample exam. We first ask the model to “think step by step” and lay out its reasoning. In a subsequent prompt, we then feed the entirety of the previous generation to GPT-4 and ask for a final prediction. An illustrative example of the template is shown in Figure 6.1. As corroborated by other recent studies, we observe that basic chain-of-thought prompting does not yield performance benefits for GPT-4 on medical questions. However, as shown in [LHW22], performance can vary significantly based on the specific chain-of-thought prompt used, and it is possible that a different prompt structure may yield stronger performance in future work. 12 # Chain-of-Thought Prompt template for multiple choice questions Question: {{question}} Choices: {{answer_choices}} Let’s think step by step. initial model generation Therefore, among A through {{last_choice}}, the answer is Figure 6.1: Two-stage chain-of-thought prompt template. Few-shot example curation. The authors of [SAT+22] worked with a panel of qualified clinicians to curate the best demonstration exemplars for the few-shot prompts, with custom prompts being designed for each dataset. We conducted light experiments comparing the exact curated few-shot exemplars sourced by [SAT+22] with our baseline random exemplar selection strategy on GPT-4 and GPT-3.5. The performance difference between the two modes was negligible across the datasets we were able to test on. This finding suggests that expert exemplar curation may not be necessary to achieve strong performance in the latest generation of LLMs. We leave deeper investigations of this phenomena to future work. Dataset GPT-4 (Random Exemplars) MedQA US 5-option MedQA US 4-option MedMCQA PubMedQA 78.63 81.38 72.36 74.40 78.24 82.33 71.36 74.00 # GPT-4 (Curated Exemplars) Table 6: Random few-shot exemplar selection vs. expert curation. # 6.2 Memorization GPT-4’s strong performance on benchmark datasets raises the possibility that the system is leveraging memorization or leakage effects, which can arise when benchmark data is included in a model’s training set. Given that LLMs are trained on internet-scale datasets, benchmark data may inadvertently appear in the model’s training set. As the details of the training data for GPT-4 are not public, other methods can be used to probe for memorization. We devised a heuristic algorithm to help identify potential signs of leakage through black-box evaluation of the model. With this approach, we prompt a model to generate a long set of near-exact matches to a given data sample and take similarity of the generation to the initial data as evidence of memorization. The method, which we refer to as memorization effects Levenshtein detector (MELD), can provide evidence that specific data is likely to be part of a model’s training set. Details of the procedure are provided in Appendix B. We note that MELD has high precision but unknown recall. That is, if MELD detects a potential match, it is likely to be in the training set and memorized by the model. However, if our algorithm does not detect a match, it does not necessarily mean that the data was excluded from the training set. MELD is unable to find evidence of training data memorization in the official USMLE datasets we tested. Conversely, when we use MELD to test other popular datasets like SQuAD 2.0 and the Newsgroup Sentiment Analysis datasets, we are able to find strong evidence of existence in the training 13 datasets. For example, GPT-4 is able to regenerate questions from SQuAD 2.0 with 99% overlap 17% of the time, while it is completely unable to regenerate samples with even 50% overlap on either of the USMLE datasets. We stress that this does not mean GPT-4 has not seen this data before, only that we are unable to find evidence of it through our blackbox testing method. Given the findings obtained via the MELD procedure, and our sourcing of USMLE examination materials that are held behind an NMBE paywall, it is unlikely that official content in our examinations were in GPT-4’s training data. We further note that, even if contamination is present, GPT-4’s per- formance on USMLE examinations may not be significantly boosted. We note that OpenAI found that some contamination was prevalent across a large suite of publicly available benchmarks, but that the model did not perform differently on contaminated and uncontaminated data samples for the problems that were studied [Ope23]. # 6.3 Focus on multiple choice The benchmarking portions of this paper primarily focus on evaluating multiple choice exam questions, which constitute the majority but not entirety of the USMLE examinations. Specifically, Step 3 of the USMLE also includes 13 computer-based case simulations (CCS) that require candidates to manage patient care in a dynamic and interactive setting. While we qualitatively assess a hypothetical case simulation in Section 7 below, quantitative metrics on interactive challenges were not considered in the benchmarks. Furthermore, while we use a mixture of official and unofficial sources of multiple choice questions to test GPT-4, we do not have access to the actual USMLE questions used in recent exams or their scoring criteria. Therefore, the metrics we report may not be indicative of the true performance of GPT-4 on a live USMLE exam. # 7 Beyond Correct Answers: Probing Capabilities To move beyond statistical measures on exams and other benchmarks on medical challenge problems, we can qualitatively explore several capabilities of GPT-4 by extending the challenge problems into interactive sessions. Beyond providing insights about the power of model, such extensions demonstrate directions with new forms of educational experiences and clinical applications that LLMs could enable. We now share an illustrative case study of an interactive session nucleated by a single test question that demonstrates GPT-4’s capabilities for education. We initially provide GPT-4 with a prompt and then simulate a dialog between the model and a medical student. On top of performing well on multiple- choice exam questions, GPT-4 is able to provide rich explanations to the student about their errors. The model also exhibits the ability to hypothesize why the student may have made a mistake, and even conducts counterfactual analyses, delivering variants of the cinical problem with minimal rewrites to help simulate alternative scenarios. We note that the veracity of information generated in such interactions, as well as in real-world applications, cannot be trusted without review and confirmation by experts. We return to concerns with accuracy in Section 8. 14 # 7.1 Explanation # GPT-4: Initial prompt Prompt: A medical student is considering a challenging clinical situation: A 28-year-old man comes to the office with an episode of blood in his urine. He lived in sub-Saharan Africa until he came to the USA 6 months ago for graduate school. Temperature is 37.0°C, pulse is 60/min, respirations are 16/min, and blood pressure is 110/84 mm Hg. General Hemoglobin 12.3 g/dL Hematocrit 37% Leukocyte count 13,400/mm3 Segmented neutrophils 65% Bands 5% Eosinophils 5% Lymphocytes 22% Monocytes 3% # Serum Urea nitrogen 75 mg/dL Creatinine 3.8 mg/dL Urine Blood 3+ RBC 200/hpf WBC 100/hpf RBC casts absent WBC casts absent She is considering the most likely reason for these findings and is considering the following possibilities: (A) Exposure to a chemical toxin (B) Interstitial cystitis (C) Malacoplakia (D) Schistosomiasis (E) Vesicoureteral reflux (F) Acute Renal Failure — The patient’s history and lab results can help guide the medical student in determining the most likely cause of the clinical findings. The patient is a 28-year-old man who lived in sub-Saharan Africa until 6 months ago, which is an important piece of information to consider. He presents with an episode of blood in his urine (hematuria). Lab results show elevated urea nitrogen and creatinine, indicating impaired kidney function. Additionally, there is an increased leukocyte count with a normal distribution of white blood cells. Considering the patient’s history and lab results, the most likely cause of these findings is: (D) Schistosomiasis: This is a parasitic infection caused by Schistosoma species. The patient’s history of living in sub-Saharan Africa is significant, as this region has a high prevalence of the disease. Schistosomiasis can cause hematuria and kidney dysfunction, which aligns with the patient’s lab results. The other possibilities are less likely due to various reasons: (A) Exposure to a chemical toxin: While certain toxins can cause kidney dysfunction, there is no specific indication that the patient has been exposed to a toxin. Additionally, the patient’s history and clinical presentation are more suggestive of schistosomiasis. (B) Interstitial cystitis: This is a chronic condition characterized by bladder pain and urinary symptoms. While it can cause hematuria, it typically does not result in elevated urea nitrogen and creatinine levels. (C) Malacoplakia: This is a rare inflammatory condition characterized by the presence of soft, yellowish plaques in the urinary tract. It can cause hematuria but is unlikely given the patient’s history and lab results. (E) Vesicoureteral reflux: This condition occurs when urine flows backward from the bladder into the ureters and kidneys. While it can cause kidney dysfunction, it is typically seen in children and is less likely in this case. (F) Acute kidney injury: This is a possibility, but the patient’s history and clinical presentation are more suggestive of schistosomiasis. Additionally, acute kidney injury usually presents with a more rapid decline in kidney function. In summary, schistosomiasis (D) is the most likely cause of the patient’s symptoms and lab findings given his history and clinical presentation. Figure 7.1: GPT-4 accurately diagnosing a clinical situation. 15 # GPT-4: Explanation and teaching interaction continued ... In summary, schistosomiasis (D) is the most likely cause of the patient’s symptoms and lab findings given his history and clinical presentation. → The student selects malacoplakia. Please explain to the student your assessment of why this is not the correct answer. I understand that the medical student has chosen malacoplakia as the answer. However, let me explain why malacoplakia is not the most likely cause of the patient’s symptoms and lab findings, based on the provided information. Malacoplakia is a rare, chronic inflammatory condition that affects the urinary tract. It is characterized by the presence of soft, yellowish plaques consisting of granulomatous tissue, usually in the bladder but occasionally in other parts of the urinary tract. Malacoplakia is often associated with immunosuppression, long-term antibiotic use, and urinary tract infections caused by Escherichia coli or other gram-negative bacteria. While malacoplakia can cause hematuria (blood in the urine), several factors make it less likely to be the cause in this particular case: Rarity: Malacoplakia is a rare condition, while the patient’s history of living in sub-Saharan Africa until 6 months ago points towards a more common cause of hematuria in that region, such as schistosomiasis. Lab results: The patient’s lab results show elevated urea nitrogen and creatinine levels, which indicate impaired kidney function. Although malacoplakia can occasionally affect the kidneys, it is more commonly localized to the bladder and not usually associated with significant kidney dysfunction. Clinical presentation: The patient’s clinical presentation (hematuria, elevated urea nitrogen, and creatinine) does not specifically point towards malacoplakia. There is no mention of other urinary symptoms, such as pain, frequent urination, or a history of recurrent urinary tract infections, which might be more suggestive of malacoplakia. Patient’s history: The patient’s history of living in sub-Saharan Africa makes schistosomiasis a more likely cause of his symptoms, as the disease is endemic in that region and can cause both hematuria and kidney dysfunction. In summary, while malacoplakia can cause hematuria, it is a rare condition, and the patient’s history, clinical presenta- tion, and lab results are more consistent with schistosomiasis. Therefore, schistosomiasis remains the most likely cause of the patient’s symptoms and lab findings. Figure 7.2: GPT-4 explaining a medical diagnosis to a student. 16 # 7.2 Metacognition # GPT-4: Understanding the student interaction continued ... → Why might the student have selected malacoplakia? What findings in the case may have brought that to mind? Can you share reflections on the reasoning that the student did to come up with this answer? While I cannot definitively determine the medical student’s thought process, I can offer some insights into why they may have considered malacoplakia as a possibility in this case. Here are a few factors that could have contributed to their selection: Hematuria: The presence of blood in the urine is a common symptom shared by various urinary tract conditions, includ- ing malacoplakia. The student might have focused on this symptom and considered malacoplakia as a potential cause without taking into account other factors, such as the patient’s history or the likelihood of the disease. Differential diagnosis: In the process of generating a differential diagnosis, medical students are often taught to consider a wide range of possibilities, including rare conditions. The student may have included malacoplakia in their list of po- tential diagnoses and, perhaps due to a lack of experience or familiarity with the condition, overestimated its likelihood in this particular case. Knowledge gaps: Medical students are constantly learning, and it’s possible that the student may not have had a full understanding of malacoplakia or its typical presentation. As a result, they may have mistakenly believed that the patient’s symptoms and lab findings were consistent with this rare condition. Focus on lab results: The student may have been drawn to the patient’s abnormal lab results, such as the elevated urea nitrogen and creatinine levels, and thought that malacoplakia could be a cause of these findings. However, the overall clinical picture, including the patient’s history, is more consistent with schistosomiasis. In summary, the medical student may have selected malacoplakia due to a combination of factors, such as focusing on the symptom of hematuria, considering a wide range of diagnoses, knowledge gaps, or placing too much emphasis on lab results. It’s important for medical students to continually refine their diagnostic skills and learn from each case they encounter. This process will help them better understand the importance of considering the whole clinical picture, including the patient’s history and the likelihood of each potential diagnosis, to arrive at the most accurate conclusion. → Please explain to the student with care and understanding what the student may have thought but what the more likely diagnosis is and why? Please be encouraging and supportive. # Dear student, I understand that you have considered malacoplakia as a possible cause of the patient’s symptoms. It’s important to explore various diagnoses, as this can help you refine your clinical reasoning skills. However, based on the information provided, there is another diagnosis that seems more likely in this case. The patient’s history of living in sub-Saharan Africa until six months ago is a crucial factor to consider. Given this background, schistosomiasis becomes a more probable cause for the symptoms and lab findings. Schistosomiasis is a parasitic infection caused by Schistosoma species, which are more prevalent in sub-Saharan Africa. The disease can cause hematuria and kidney dysfunction, which aligns with the patient’s elevated urea nitrogen and creatinine levels. While malacoplakia is a possibility, it is a rare condition, and its typical presentation doesn’t fully align with the patient’s clinical picture. The patient’s history, symptoms, and lab findings are more consistent with schistosomiasis. It’s essential to remember that, as a medical student, you are still learning and refining your diagnostic skills. Don’t be discouraged by any missteps, as they are a natural part of the learning process. Instead, use them as an opportunity to grow and gain a deeper understanding of various conditions and their presentations. Keep in mind the importance of considering the patient’s history and other factors when working through a differential diagnosis. This will help you weigh the likelihood of each potential diagnosis and ultimately lead you to the most accurate conclusion. Keep up the good work and continue to learn from each case you encounter. Your dedication and curiosity will undoubtedly contribute to your growth as a medical professional. Figure 7.3: GPT-4 demonstrates theory-of-mind—like ability to understand the student and personalize an educational explanation. 17 # 7.3 Challenge Problem to Interactive Session # GPT-4: Counterfactual rewrites interaction continued ... → Can you change the history and/or lab results with as minimal changes as possible to make acute kidney injury (F) the best answer? Please list the changes that you have made after you write out the case. Finally, summarize why the changes make acute kidney injury the best answer with the updates. Certainly, here’s the revised case with minimal changes: A 28-year-old man comes to the office with an episode of blood in his urine. He lived in sub-Saharan Africa until he came to the USA 6 months ago for graduate school. Temperature is 37.0◦C, pulse is 60/min, respirations are 16/min, and blood pressure is 110/84 mm Hg. General Hemoglobin 12.3 g/dL Hematocrit 37% Leukocyte count 13,400/mm3 Segmented neutrophils 65% Bands 5% Eosinophils 5% Lymphocytes 22% Monocytes 3% Serum Urea nitrogen 75 mg/dL Creatinine 3.8 mg/dL Urine Blood 3+ RBC 200/hpf WBC 100/hpf RBC casts absent WBC casts absent Changes made: The patient recently started using a nonsteroidal anti-inflammatory drug (NSAID) for joint pain. With the addition of recent NSAID use, acute kidney injury (AKI) becomes a more likely explanation for the patient’s symptoms and lab findings. Here’s why: NSAIDs can cause acute kidney injury by reducing blood flow to the kidneys, leading to impaired kidney function. The patient’s elevated urea nitrogen (75 mg/dL) and creatinine (3.8 mg/dL) levels indicate kidney dysfunction, which can be consistent with NSAID-induced AKI. Hematuria (blood in the urine) can occur in AKI, and the patient’s recent NSAID use increases the likelihood of this being the cause. The patient’s leukocyte count is elevated, but there is no specific indication of an infection, making AKI more likely than an infectious cause, such as schistosomiasis. In summary, with the addition of recent NSAID use, acute kidney injury becomes the most likely explanation for the patient’s symptoms and lab findings. It’s important to note that this change alone doesn’t completely exclude other possibilities but shifts the focus towards AKI as the best answer given the new information. Figure 7.4: GPT-4 minimally rewrites the case to create a counterfactual scenario. 18 # GPT-4: Counterfactual rewrites (continued) interaction continued ... → Can you shift the labs to make AKI even more likely? Of course, here’s the revised case with changes to the lab results to make acute kidney injury (AKI) even more likely: A 28-year-old man comes to the office with an episode of blood in his urine. He lived in sub-Saharan Africa until he came to the USA 6 months ago for graduate school. Temperature is 37.0◦C, pulse is 60/min, respirations are 16/min, and blood pressure is 110/84 mm Hg. General Hemoglobin 12.3 g/dL Hematocrit 37% Leukocyte count 9,800/mm3 Segmented neutrophils 60% Bands 3% Eosinophils 2% Lymphocytes 30% Monocytes 5% Serum Urea nitrogen 120 mg/dL Creatinine 6.5 mg/dL Urine Blood 3+ RBC 200/hpf WBC 100/hpf RBC casts absent WBC casts absent With these changes to the lab results, acute kidney injury (AKI) becomes even more likely for the following reasons: The patient’s urea nitrogen (120 mg/dL) and creatinine (6.5 mg/dL) levels are now significantly elevated, which indicates a more severe kidney dysfunction that is consistent with AKI. The leukocyte count is still slightly elevated but closer to the normal range, and the eosinophils percentage has decreased, making an infectious or parasitic cause, such as schistosomiasis, less likely. The recent NSAID use remains an important risk factor for AKI, as these medications can cause kidney injury by reducing blood flow to the kidneys. In summary, with the changes made to the patient’s history and lab results, acute kidney injury becomes the most likely explanation for the patient’s symptoms and lab findings. The significant elevation in urea nitrogen and creatinine levels, along with the recent NSAID use, further supports AKI as the primary diagnosis. Figure 7.5: Per user request, GPT-4 provides a sophisticated reformulation of the question focused by altering lab result values. (Case study continues in Appendix D.) # 8 From Benchmarks to Real World There is a large gap between competency on proficiency examinations and other medical benchmarks and the successful fielding and use of GPT-4 in clinical applications. GPT-4 and its successors have the long- term potential to exert a transformative influence on the field of medicine. Creative and appropriate uses of well-calibrated output could enhance the quality and reduce the costs of patient care. The performance on benchmarks, in addition to qualitative probes of its clinical capabilities, highlights the potential to assist physicians and other healthcare professionals with numerous aspects of healthcare delivery. The demonstrated competencies, particularly on USMLE Step 3, suggest that GPT-4 and its successors can make contributions to clinical reasoning and daily workflows of medical practice. Beyond uses in decision support, memory jogging, and administrative tasks, GPT-4 and its successors may one day assist investigators with clinical and biomedical research. Risks of erroneous generations. Great care must be taken with the introduction of various forms of automation in healthcare, including uses of machine learning [WSS+19, CLG+15]. A critical concern is 19 the accuracy of machine recommendations and their influence on decision makers. Methods and metrics have been developed for characterizing the performance of systems created via traditional supervised machine learning. With these applications, characterizing overall accuracy of recommendations, as well as context- and instance-specific rates of error [BEB+19, Mic23, NGP23, NJKC19], are enabled by the closed-world of well-defined, highly-focused problem areas, such as detecting a specific type of cancer [EKN+17, MSG+20], or predicting specific outcomes like readmissions [BBG+14], infection [WGH16], sepsis [AHS+22], and in-hospital deterioration [ELS+20]. Unfortunately, similar characterizations of reliability and confidence are not yet available for the massive, open-world of generations that are output from foundation models in response to prompts. Difficulties with evaluation of the output of LLMs in supporting real-world decisions include the challenge of stability and robustness of recommendations and inferences generated in response to custom-tailored prompting in the wild. Generations are often highly sensitive to details of the wording of prompts. Stability of generations can also be sensitive to model revision that might be ongoing, including rebuilding or fine-tuning of models based on fresh data [SNK+20]. While large language models show promise with providing support in healthcare administration and delivery, caution is needed to mitigate potential negative influences of over-reliance on model-generated recommendations. Significant risks with uses of large language models include inaccurate recommen- dations about rankings (e.g., with differential diagnoses) and sequencing (e.g., information gathering, testing), as well as blatant factual errors, particularly with important omissions and with erroneous gen- erations, often referred to as hallucinations. LLM hallucinations can be particularly difficult to detect given the high linguistic fluency of the models and the ability to interleave inaccurate and ungrounded assertions with accurate generations. Such hallucinations can include incorrect or misleading medical information which necessitates careful review and fact checking. Thus, extreme caution is required when using LLMs in high-stakes medical applications, where incorrect or incomplete information could have serious consequences for patient care. Additional research is needed to address the veracity of model output. Directions include employing search and retrieval to help ground generations in the literature, doing checks of self-consistency, per- forming evaluation studies to characterize the overall statistics of accurate generations, conditioned on different contexts and usages, and refinements of methods that generate and harness accurate calibration signals. Trusted calibration information can be harnessed in numerous ways to enable practitioners to better understand and assess model outputs[BNK+19b, BNK+19a, WHK20]. More generally, innovation with human-computer interaction will be valuable in the fielding of applications of LLMs in healthcare [FCL+22, AWV+19, Hor99, MBFH22]. Healthcare providers relying on GPT-4 and other models will need to adhere to the highest standards for verifying information generated by the model. Best practices for quality assurance must be developed and shared among medical professionals to ensure safe and effective use. In the context of erroneous omissions and inclusions, healthcare professionals and other consumers of health-related content will need to be educated on the challenges with reliability and the need for ongoing vigilance. Education, awareness, and promoting guidelines for best practices may help to minimize safety challenges. Risks of Bias. Studies have revealed biases in the delivery of healthcare, noting disparities in care received by people experiencing marginalization [CSM18, HCL+15]. Such biases in healthcare delivery have been demonstrated to influence the systems and models that are developed to provide guidance to healthcare organizations and practitioners. Without study to address and mitigate bias in data and the systems constructed from that data, we risk fielding systems that propagate long-term disparities and inaccuracies [OPVM19]. Exploration of biases in healthcare and the potential reflection of these 20 biases in AI systems come in the context of broader work on biases of AI systems. Several efforts have demonstrated that the output of machine-learned models can be unfair and harmful to specific groups of people, depending on backgrounds and demographics (e.g., [HZH17, BG18]). Progress has been made on technical methods for detecting and mitigating harmful biases in task-specific systems built via supervised machine learning (e.g., [ABD+18, KS21]). However, engineers and organizations continue to face conceptual challenges with defining measures of fairness [JW21, BHN19]. We have a poor understanding of the biases accrued and transmitted by large-scale language models, and how issues with fairness might arise for different types of healthcare-centric prompting and gen- erations. In the absence of study, we must be wary of biases in both clinical practices and research [AGHR22] with regard to race, socioeconomic background, gender, and other factors, which are laced throughout the corpora used to train large-scale language models. Research is needed to understand the fairness of healthcare-centric recommendations generated by LLMs. Influences on workflows, tasks, and specialties. The competencies on the USMLE examinations and other medical workloads suggest that GPT-4, properly harnessed with appropriate expert oversight, can contribute to enabling precision clinical medicine. GPT-4 and its successors could be leveraged to provide healthcare practitioners with analytics, reminders, and decision support, including assistance with the formulation and revision of differential diagnoses from patient history, physical findings and lab results, identification of relevant tests and their sequencing, and constructing therapy plans. With effective management of errors, LLMs could help with memory jogging, alerting, and screening. As an example, memory jogging might help to mitigate persistent challenges with adverse outcomes, including those attributable to preventable human errors [BLS+23, Gri22] and diagnostic and therapeutic delays [NTPB+22]. In the longer-term, GPT-4 and its descendants might be harnessed to shift the distribution of tasks associated with daily flows of work for physicians and other healthcare practitioners in ways that reduce the burden of programmatic, logistical, and administrative tasks. Reduction in the drudgery of writing reports and performing other administrative tasks would permit healthcare providers to spend more time on the uniquely human elements of the profession, such as patient engagement and coordinating and collaborating with healthcare colleagues. The technology could also enable more time for physicians to learn, reflect, and engage in continuing medical education to become the best at what they are interested in doing. In addition, LLMs could be harnessed to provide information, communication, screening, and decision support in under-served regions. The models could help to raise the competency of physicians’ assistants and help with triage and communication with remote experts. Social and societal issues. On a broader social and societal front, the capabilities demonstrated by GPT-4 can influence decisions about the choice to pursue a medical career, the choice of residency and ultimate speciality, and the sense of uniqueness of human contributions for today’s healthcare practitioners [Top19]. AI’s accelerating performance on competency exams and other medical challenge problems may contribute to the perception that the technology’s inroads in medicine will eventually devalue human intellect. Practitioners may be concerned about significant shift in the way medical specialties are practiced or valued. At earlier steps in the chain of training and commitment, AI’s growing competence could influence career choices in medicine, shifting perceptions of which tasks rely on genuine human intellect. This may change decisions about medicine as a career path overall and, for those already in medical training programs, their choice of speciality. Perhaps as early foreshadowing, a recent study found that medical students’ choice of radiology as a career is significantly reduced by their perception of the growing role of AI in radiology [RL22]. 21 Implications for the future. The leap in performance on medical challenge problems with the move from GPT 3.5 to GPT-4 suggests that we can achieve impressive gains on intensive real-world challenges with scale–and that we will likely continue to see advances with larger models for handling complex, real-world problems. The rate of progress of LLMs has implications beyond the medical profession. As observed in [SS18], large swaths of modern society are predicated on a “grand bargain” in which professional classes invest years or even decades in technical education and training and are, in turn, afforded certain benefits by citizens and governments, including the exclusive right to practice in their field, social prestige, and above-average compensation. Technical disruption of this social contract can have implications not only for the medical field but for numerous other knowledge-intensive professions including law, banking, engineering, accounting, and others. # 9 Conclusion We presented a comparative evaluation of GPT-4, GPT-3.5 and Flan-PaLM 540B on medical compe- tency examinations and benchmark datasets. We explored zero-shot performance as a baseline. We first focused on answers to questions that are representative of those included in USMLE Step 1, Step 2, and Step 3 exams, certification tests given to medical students and residents in the U.S. We studied per- formance on questions relying solely on text versus questions referring to visual media. We found that GPT-4 significantly outperforms GPT-3.5 and Flan-PaLM 540B. Next, we demonstrated that GPT-4 significantly surpasses GPT-3.5’s performance on the MultiMedQA dataset. The model also outper- formed Flan-PaLM 540B on all but one dataset. Our work also explored the calibration of the model’s output probabilities, highlighting the importance of calibration for medical applications. We provided sample output that demonstrates GPT-4’s capacity for reasoning about the concepts tested in USMLE challenge problems, including explanation, counterfactual reasoning, differential diagnosis, and testing strategies. Finally, we touched on broader implications of applications of GPT-4 in medicine. We main- tain that GPT-4’s exceptional performance on benchmarks serves as an indicator of its potential for being harnessed in medical education and for aiding healthcare professionals with numerous aspects of healthcare delivery. Nonetheless, considering the possibility of errors and the challenges in assessing performance in real-world scenarios, it is vital to practice prudence, seek to develop and evaluate appro- priate uses, and pursue technical innovations to optimize advantages and mitigate risks associated with applications. # Acknowledgments We thank Miles Brundage, Pamela Mishkin, and Jack Rae for their feedback and assistance on this effort. We are grateful for insights shared in earlier discussions by Rich Caruana, Scott Lundberg, Matthew Lungren, Marco Tulio Ribeiro, and Nigam Shah. # References [ABD+18] Alekh Agarwal, Alina Beygelzimer, Miroslav Dudik, John Langford, and Hanna Wallach. A reductions approach to fair classification. In Jennifer Dy and Andreas Krause, edi- tors, Proceedings of the 35th International Conference on Machine Learning, volume 80 of Proceedings of Machine Learning Research, pages 60–69. PMLR, 10–15 Jul 2018. 22 Shunit Agmon, Plia Gillis, Eric Horvitz, and Kira Radinsky. Gender-sensitive word embed- dings for healthcare. Journal of the American Medical Informatics Association, 29(3):415– 423, 2022. Roy Adams, Katharine E Henry, Anirudh Sridharan, Hossein Soleimani, Andong Zhan, Nishi Rawat, Lauren Johnson, David N Hager, Sara E Cosgrove, Andrew Markowski, et al. Prospective, multi-site study of patient outcomes after implementation of the trews machine learning-based early warning system for sepsis. Nature medicine, 28(7):1455–1460, 2022. Saleema Amershi, Dan Weld, Mihaela Vorvoreanu, Adam Fourney, Besmira Nushi, Penny Collisson, Jina Suh, Shamsi Iqbal, Paul N Bennett, Kori Inkpen, et al. Guidelines for human-AI interaction. In Proceedings of the 2019 CHI conference on Human Factors in Computing Systems, pages 1–13, 2019. [BBG+14] Mohsen Bayati, Mark Braverman, Michael Gillam, Karen M Mack, George Ruiz, Mark S Smith, and Eric Horvitz. Data-driven decisions for reducing readmissions for heart failure: General methodology and case study. PloS one, 9(10):e109264, 2014. Rick Barraza, Russell Eames, Yan Esteve Balducci, Josh Hinds, Scott Hoogerwerf, Eric Horvitz, Ece Kamar, Jacquelyn Krones, Josh Lovejoy, Parham Mohadjer, et al. Error In ICLR workshop on terrain analysis for machine learning: Tool and visualizations. debugging machine learning models, 2019. Joy Buolamwini and Timnit Gebru. Gender shades: Intersectional accuracy disparities in commercial gender classification. In Conference on fairness, accountability and trans- parency, pages 77–91. PMLR, 2018. [BHA+21] Rishi Bommasani, Drew A. Hudson, Ehsan Adeli, et al. On the opportunities and risks of foundation models, 2021. Solon Barocas, Moritz Hardt, and Arvind Narayanan. Fairness and Machine Learning: Limitations and Opportunities. fairmlbook.org, 2019. http://www.fairmlbook.org. Yuntao Bai, Andy Jones, Kamal Ndousse, et al. Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback, April 2022. [BLS+23] David W Bates, David M Levine, Hojjat Salmasian, Ania Syrowatka, David M Shahian, Stuart Lipsitz, Jonathan P Zebrowski, Laura C Myers, Merranda S Logan, Christopher G Roy, et al. The safety of inpatient health care. New England Journal of Medicine, 388(2):142–153, 2023. [BMR+20] Tom Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared D Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. Lan- guage models are few-shot learners. Advances in neural information processing systems, 33:1877–1901, 2020. [BNK+19a] Gagan Bansal, Besmira Nushi, Ece Kamar, Walter S Lasecki, Daniel S Weld, and Eric Horvitz. Beyond accuracy: The role of mental models in human-AI team performance. In Proceedings of the AAAI conference on human computation and crowdsourcing, volume 7, pages 2–11, 2019. 23 [BNK+19b] Gagan Bansal, Besmira Nushi, Ece Kamar, Daniel S Weld, Walter S Lasecki, and Eric Horvitz. Updates in human-AI teams: Understanding and addressing the performance/- compatibility tradeoff. In Proceedings of the AAAI Conference on Artificial Intelligence, pages 2429–2437, 2019. Bruce G Buchanan and Edward H Shortliffe. Rule based expert systems: the mycin experi- ments of the stanford heuristic programming project (the Addison-Wesley series in artificial intelligence). Addison-Wesley Longman Publishing Co., Inc., 1984. In Sebastien Bubeck and Mark Sellke. A universal law of robustness via isoperimetry. M. Ranzato, A. Beygelzimer, Y. Dauphin, P.S. Liang, and J. Wortman Vaughan, edi- tors, Advances in Neural Information Processing Systems, volume 34, pages 28811–28822. Curran Associates, Inc., 2021. Paul F Christiano, Jan Leike, Tom Brown, Miljan Martic, Shane Legg, and Dario Amodei. Deep reinforcement learning from human preferences. Advances in neural information processing systems, 30, 2017. Rich Caruana, Yin Lou, Johannes Gehrke, Paul Koch, Marc Sturm, and Noemie Elhadad. Intelligible models for healthcare: Predicting pneumonia risk and hospital 30-day read- mission. In Proceedings of the 21th ACM SIGKDD international conference on knowledge discovery and data mining, pages 1721–1730, 2015. Danton S Char, Nigam H Shah, and David Magnus. Implementing machine learning in health care—addressing ethical challenges. The New England journal of medicine, 378(11):981, 2018. 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. [EKN+17] Andre Esteva, Brett Kuprel, Roberto A Novoa, Justin Ko, Susan M Swetter, Helen M Blau, and Sebastian Thrun. Dermatologist-level classification of skin cancer with deep neural networks. nature, 542(7639):115–118, 2017. Gabriel J Escobar, Vincent X Liu, Alejandro Schuler, Brian Lawson, John D Greene, and Patricia Kipnis. Automated identification of adults at risk for in-hospital clinical deterioration. New England Journal of Medicine, 383(20):1951–1960, 2020. Riccardo Fogliato, Shreya Chappidi, Matthew Lungren, Paul Fisher, Diane Wilson, Michael Fitzke, Mark Parkinson, Eric Horvitz, Kori Inkpen, and Besmira Nushi. Who goes first? Influences of human-ai workflow on decision making in clinical imaging. In 2022 ACM Conference on Fairness, Accountability, and Transparency, pages 1362–1374, 2022. G Anthony Gorry and G Octo Barnett. Experience with a model of sequential diagnosis. Computers and Biomedical Research, 1(5):490–507, 1968. Christi A Grimm. Adverse events in hospitals: A quarter of medicare patients experienced harm in october 2018. Office of Inspector General, I. General, page 117, 2022. 24 [HBB+20] Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt. Measuring massive multitask language understanding. arXiv preprint arXiv:2009.03300, 2020. [HCL+15] William J Hall, Mimi V Chapman, Kent M Lee, Yesenia M Merino, Tainayah W Thomas, B Keith Payne, Eugenia Eng, Steven H Day, and Tamera Coyne-Beasley. Implicit racial/ethnic bias among health care professionals and its influence on health care out- comes: a systematic review. American journal of public health, 105(12):e60–e76, 2015. David E. Heckerman, Eric Horvitz, and Bharat N. Nathwani. Toward normative expert systems: Part I the Pathfinder project. Methods of Information in Medicine, 31:90 – 105, 1992. [HHPS15] Katharine E Henry, David N Hager, Peter J Pronovost, and Suchi Saria. A targeted real-time early warning score (trewscore) for septic shock. Science translational medicine, 7(299):299ra122–299ra122, 2015. Eric Horvitz. Principles of mixed-initiative user interfaces. In Proceedings of the SIGCHI conference on Human Factors in Computing Systems, pages 159–166, 1999. Trevor Hastie, Robert Tibshirani, Jerome H Friedman, and Jerome H Friedman. The elements of statistical learning: data mining, inference, and prediction, volume 2. Springer, 2009. Ayanna Howard, Cha Zhang, and Eric Horvitz. Addressing bias in machine learning algorithms: A pilot study on emotion recognition for intelligent systems. In 2017 IEEE Workshop on Advanced Robotics and its Social Impacts, pages 1–7. IEEE, 2017. Qiao Jin, Bhuwan Dhingra, Zhengping Liu, William W Cohen, and Xinghua Lu. Pubmedqa: A dataset for biomedical research question answering. arXiv preprint arXiv:1909.06146, 2019. Di Jin, Eileen Pan, Nassim Oufattole, Wei-Hung Weng, Hanyi Fang, and Peter Szolovits. What disease does this patient have? a large-scale open domain question answering dataset from medical exams. Applied Sciences, 11(14):6421, 2021. Abigail Z Jacobs and Hanna Wallach. Measurement and fairness. In Proceedings of the 2021 ACM conference on fairness, accountability, and transparency, pages 375–385, 2021. [KCM+23] Tiffany H Kung, Morgan Cheatham, Arielle Medenilla, Czarina Sillos, Lorie De Leon, Camille Elepa˜no, Maria Madriaga, Rimel Aggabao, Giezel Diaz-Candido, James Maningo, et al. Performance of chatgpt on usmle: Potential for ai-assisted medical education using large language models. PLOS Digital Health, 2(2):e0000198, 2023. [KGR+22] Takeshi Kojima, Shixiang Shane Gu, Machel Reid, Yutaka Matsuo, and Yusuke Iwasawa. Large language models are zero-shot reasoners. arXiv preprint arXiv:2205.11916, 2022. 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. 25 Ankit Kulshrestha and Ilya Safro. Fairlearn: Configurable and interpretable algorithmic fairness. arXiv preprint arXiv:2111.08878, 2021. Percy Liang, Rishi Bommasani, Tony Lee, Dimitris Tsipras, et al. Holistic evaluation of language models, 2022. Valentin Li´evin, Christoffer Egeberg Hother, and Ole Winther. Can large language models reason about medical questions? arXiv preprint arXiv:2207.08143, 2022. Robert S Ledley and Lee B Lusted. Reasoning foundations of medical diagnosis: Sym- bolic logic, probability, and value theory aid our understanding of how physicians reason. Science, 130(3366):9–21, 1959. [MBFH22] Hussein Mozannar, Gagan Bansal, Adam Fourney, and Eric Horvitz. Reading between the lines: Modeling user behavior and costs in ai-assisted programming. arXiv preprint arXiv:2210.14306, 2022. [Mic23] Microsoft. Error Analysis. https://www.erroranalysis.ai/, 2023. 18-March-2023]. [Online; accessed Scott Mayer McKinney, Marcin Sieniek, Varun Godbole, Jonathan Godwin, Natasha Antropova, Hutan Ashrafian, Trevor Back, Mary Chesus, Greg S Corrado, Ara Darzi, et al. International evaluation of an AI system for breast cancer screening. Nature, 577(7788):89– 94, 2020. Besmira Nushi and Rahee Ghosh Peshawaria. Responsible AI Mitigations and Tracker: New open-source tools for guiding mitigations in Responsible AI. https://bit.ly/ 3ZXc0Fq, 2023. [Online; accessed 18-March-2023]. [NHB+21] Reiichiro Nakano, Jacob Hilton, Suchir Balaji, Jeff Wu, Long Ouyang, Christina Kim, Christopher Hesse, Shantanu Jain, Vineet Kosaraju, William Saunders, et al. Webgpt: Browser-assisted question-answering with human feedback. arXiv preprint arXiv:2112.09332, 2021. Harsha Nori, Samuel Jenkins, Paul Koch, and Rich Caruana. framework for machine learning interpretability. arXiv preprint arXiv:1909.09223, 2019. Alexandru Niculescu-Mizil and Rich Caruana. Predicting good probabilities with super- vised learning. In Proceedings of the 22nd international conference on Machine learning, pages 625–632, 2005. [NTPB+22] David E Newman-Toker, Susan M Peterson, Shervin Badihian, Ahmed Hassoon, Najlla Nassery, Donna Parizadeh, Lisa M Wilson, Yuanxi Jia, Rodney Omron, Saraniya Thar- marajah, et al. Diagnostic errors in the emergency department: A systematic review, 2022. [Ope23] OpenAI. Gpt-4 technical report, 2023. [OPVM19] Ziad Obermeyer, Brian Powers, Christine Vogeli, and Sendhil Mullainathan. Dissect- ing racial bias in an algorithm used to manage the health of populations. Science, 366(6464):447–453, 2019. 26 Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, Katarina Slama, Alex Ray, et al. Training language mod- els to follow instructions with human feedback. Advances in Neural Information Processing Systems, 35:27730–27744, 2022. Ramesh S Patil, Peter Szolovits, and William B Schwartz. Causal understanding of patient illness in medical diagnosis. In IJCAI, volume 81, pages 893–899, 1981. Ankit Pal, Logesh Kumar Umapathi, and Malaikannan Sankarasubbu. Medmcqa: A large- scale multi-subject multi-choice dataset for medical domain question answering. In Con- ference on Health, Inference, and Learning, pages 248–260. PMLR, 2022. Pranav Rajpurkar, Jeremy Irvin, Kaylie Zhu, Brandon Yang, Hershel Mehta, Tony Duan, Daisy Ding, Aarti Bagul, Curtis Langlotz, Katie Shpanskaya, et al. Chexnet: Radiologist-level pneumonia detection on chest x-rays with deep learning. arXiv preprint arXiv:1711.05225, 2017. [RL22] Kristen Reeder and Hwan Lee. choice of radiology. Clinical Imaging, 81:67–71, 2022. Impact of artificial intelligence on us medical students’ Alec Radford, Karthik Narasimhan, Tim Salimans, Ilya Sutskever, et al. Improving lan- guage understanding by generative pre-training. arXiv preprint arXiv, 2018. Karan Singhal, Shekoofeh Azizi, Tao Tu, S Sara Mahdavi, Jason Wei, Hyung Won Chung, Nathan Scales, Ajay Tanwani, Heather Cole-Lewis, Stephen Pfohl, et al. Large language models encode clinical knowledge. arXiv preprint arXiv:2212.13138, 2022. Harini Suresh, Nathan Hunt, Alistair Johnson, Leo Anthony Celi, Peter Szolovits, and Marzyeh Ghassemi. Clinical intervention prediction and understanding with deep neural networks. In Machine Learning for Healthcare Conference, pages 322–337. PMLR, 2017. Edward H Shortliffe. Mycin: A knowledge-based computer program applied to infectious diseases. In Proceedings of the Annual Symposium on Computer Application in Medical Care, page 66. American Medical Informatics Association, 1977. [SNK+20] Megha Srivastava, Besmira Nushi, Ece Kamar, Shital Shah, and Eric Horvitz. An empirical analysis of backward compatibility in machine learning systems. In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, pages 3272–3280, 2020. Daniel Susskind and Richard Susskind. The future of the professions. Proceedings of the American Philosophical Society, 162(2):125–138, 2018. Eric Topol. Deep medicine: how artificial intelligence can make healthcare human again. Hachette UK, 2019. [VSP+17] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Ilia Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017. 27 Jenna Wiens, John Guttag, and Eric Horvitz. Patient risk stratification with time-varying parameters: a multitask learning approach. The Journal of Machine Learning Research, 17(1):2797–2819, 2016. Bryan Wilder, Eric Horvitz, and Ece Kamar. Learning to complement humans. arXiv preprint arXiv:2005.00582, 2020. Jenna Wiens, Suchi Saria, Mark Sendak, Marzyeh Ghassemi, Vincent X Liu, Finale Doshi- Velez, Kenneth Jung, Katherine Heller, David Kale, Mohammed Saeed, et al. Do no harm: a roadmap for responsible machine learning for health care. Nature medicine, 25(9):1337– 1340, 2019. [WWS+22a] Xuezhi Wang, Jason Wei, Dale Schuurmans, Quoc Le, Ed Chi, and Denny Zhou. Self- arXiv preprint consistency improves chain of thought reasoning in language models. arXiv:2203.11171, 2022. [WWS+22b] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Ed Chi, Quoc Le, and Denny Zhou. Chain of thought prompting elicits reasoning in large language models. arXiv preprint arXiv:2201.11903, 2022. # Appendix # A Dataset descriptions • USMLE Self Assessments: This dataset includes materials purchased from the NBME Self- Assessment resources available at https://www.nbme.org/examinees/self-assessments. The dataset contains 2173 questions in total, with 1197 questions in Step 1, 800 questions in Step 2, and 176 questions in Step 3. Step 1 exam forms include Form 25, Form 26, Form 27, Form 28, Form 29, and Form 30. Step 2 exam forms include Form 9, Form 10, Form 11, and Form 12. Step 3 exam forms include Form 1, Form 2, Form 3, Form 4, and Form 5. • USMLE Sample Exam: Sample exam materials were sourced from USMLE practice materials at https://www.usmle.org/prepare-your-exam. Exam materials are contained in the follow- ing PDFs. Step 1: https://www.usmle.org/sites/default/files/2021-10/Step_1_Sample_ Items.pdf. Step 2: https://www.usmle.org/sites/default/files/2021-10/Step2_CK_Sample_ Questions.pdf. Step 3: https://www.usmle.org/sites/default/files/2021-10/Step3_Sample_ Items.pdf. This dataset is the same as the one used by Kung et al. to test ChatGPT [KCM+23], but in our tests, the questions containing media were not removed from the test set. • MedQA: MedQA contains English, Simplified Chinese, and Traditional Chinese multiple-choice questions collected from Medical Licensing Examinations of the United States, Mainland China, and Taiwan [JPO+21]. There are 5 options per question in the United States and Mainland China segments, with the following number of questions in the test split: 1273 US, 3426 Mainland. The Taiwan segment has 1413 questions with 4 options per question. The US test split also has a simplified 4 option version with the same 1273 questions, where one of the incorrect options is removed. 28 • PubMedQA: PubMedQA contains tests requiring a model to answer yes, no, or maybe to biomed- ical research questions when given context provided from PubMed abstracts [JDL+19]. There are two settings for PubMedQA tests called reasoning-required and reasoning-free. In the reasoning- free setting, a long-form answer that contains explanations of the abstracts is provided. We report results for the reasoning-required setting, in which the model is only given context from abstracts to use when answering the question. The yes, no, or maybe choices are formulated as a multiple choice question, where A is yes, B is no, and C is maybe, matching the testing method done by Li´evin et al. [LHW22] • MedMCQA: MedMCQA is a dataset of multiple choice questions sourced from mock exams and published past exams of two Indian medical school entrance exams called AIIMS and NEET-PG [PUS22]. The dev set contains 4183 questions, and the test set contains 6150 questions. Each question has 4 choices. • MMLU: MMLU is a large multiple choice question dataset spanning a wide variety of topics [HBB+20]. MMLU has 57 subjects in total. Results of medicine related subjects are reported in our benchmarks. # B Memorization analysis The memorization effects Levenshtein detector (MELD) method works as follows: for each content datapoint in a dataset, we partition the content in half. We pass in the first half as context and ask the model to generate up to the length of the second half. We then measure how similar the generated content is to the held-out second half using Levenshtein distance ratio, which is defined as one minus the ratio of Levenshtein distance to the maximum possible distance. We define a near-exact match as having a Levenshtein distance ratio of at least 0.95, meaning that less than 5% of the characters are different between the generated and held out content. We measure the rate of near exact matches by computing the percentage of datapoints that have a near-exact match in each dataset. While each individual sample may not be regenerated exactly due to stochastics in the training process, the observed rate across the entire dataset can provide strong empirical evidence that the model has seen the data before. 29 Algorithm 1: Memorization effects Levenshtein detector (MELD) Data: A generative language model g, a dataset D of question-answer pairs, a tokenizer T , a threshold Y Result: A metric Z that measures the percentage of completions that have more than Y % overlap with the ground truth Initialize an empty list L; foreach (q, a) ∈ D do Split q into two halves: q1 and q2; Tokenize q1 and q2 using T : t1 = T (q1) and t2 = T (q2); Set the model temperature to zero and pass q1 as context; Generate k tokens from g where k = |t2|; Calculate the Levenshtein distance-based ratio between t2 and generated text g: int (round(2=™t x 100)) 100 where |g| is the total number of characters in both strings, and M is the number of matches in the two strings.; if @>Y then if @>Y then | Append ¢ to L; Calculate the mean of L: Z = mean(L); Return Z; 30 # C Additional prompt examples GPT-4 chat prompt template for multiple choice questions [ { role: "system", content: "You are a helpful assistant that answers multiple choice questions about medical knowledge." }, {{few_shot_examples}} { role: "user", content: "{{context}}**Question:** {{question}} {{answer_choices}}" }, { role: "assistant", content: "**Answer:**(" } ] Figure C.1: Template used to generate prompts for GPT-4 on all multiple choice questions. Elements in double braces {{}} are replaced with question-specific values. Few shot examples are encoded as user and assistant chat messages. 31 Sample question using chat prompt template [ { role: "system", content: "You are a helpful assistant that answers multiple choice questions about medical knowledge." }, { role: "user", content: "**Question:** A 72-year-old woman who has smoked 20 cigarettes daily for the past 38 years begins using eyedrops for glaucoma. Three days later, she has a marked increase in shortness of breath while walking up a flight of stairs. Which of the following drugs is the most likely cause of the development of shortness of breath in this patient? (A) Apraclonidine (B) Epinephrine (C) Latanoprost (D) Timolol" }, { # role: "assistant", content: "**Answer**:(" } ] Figure C.2: Instantiated example of Figure 2.1. 32 # D Interactive educational session (continued) # GPT-4: Formulating differential diagnosis interaction continued ... → Going back to the original case, what is the differential diagnosis, considering the broader possibilities, including if necessary, but going beyond the multiple choice answers? Please rank by likelihood. Considering the broader possibilities for the differential diagnosis of the original case, we can list the follow- ing conditions and rank them by likelihood: Schistosomiasis (most likely): The patient’s history of living in sub-Saharan Africa, presence of hematuria, and kidney dysfunction make this the most likely cause. Acute kidney injury (AKI): Elevated urea nitrogen and creatinine levels indicate kidney dysfunction, which could be due to AKI from various causes, such as infection, ischemia, or exposure to nephrotoxic agents. Glomerulonephritis: Inflammation of the glomeruli in the kidneys can cause hematuria and kidney dysfunction. The patient’s lab findings could be consistent with this condition. Kidney stones: Although less likely, kidney stones can cause hematuria and kidney dysfunction in some cases. Exposure to a chemical toxin: Certain toxins can cause kidney dysfunction and hematuria, but there is no specific indication in the case that the patient has been exposed to a toxin. Interstitial cystitis: A chronic condition characterized by bladder pain and urinary symptoms. While it can cause hematuria, it typically does not result in elevated urea nitrogen and creatinine levels. Malacoplakia: A rare inflammatory condition characterized by the presence of soft, yellowish plaques in the urinary tract. It can cause hematuria but is unlikely given the patient’s history and lab results. Vesicoureteral reflux: This condition occurs when urine flows backward from the bladder into the ureters and kidneys. While it can cause kidney dysfunction, it is typically seen in children and is less likely in this case. Tubulointerstitial nephritis: Inflammation of the renal tubules and interstitium can cause kidney dysfunction and sometimes hematuria. However, the patient’s history and lab results do not strongly suggest this condition. In the original case, schistosomiasis remains the most likely cause of the patient’s symptoms and lab findings, given his history and the overall clinical picture. Other possibilities like AKI, glomerulonephritis, and kidney stones should be considered and evaluated based on additional information and further diagnostic tests. Figure D.1: Case study continued: When pressed further, GPT-4 provides a more sophisti- cated rewrite focused on altering lab result values. 33 # GPT-4: Information-gathering and testing interaction continued ... → Given the differential diagnosis, what additional information from the patient and lab tests would be most helpful to narrow down the possibilities–and how should tests be ideally sequenced? information from the patient and further lab tests can be conducted. Here’s a suggested sequence of tests and information gathering: Detailed patient history: Start by obtaining a more detailed medical, travel, and social history, including any medication or supplement use, recent illnesses, exposures to infections, or possible contact with toxins. Urinalysis: A more comprehensive urinalysis, including urine protein levels, microscopic examination for red and white blood cell casts, and a urine culture to identify possible infections, can provide valuable information on the underlying cause of the patient’s symptoms. Serology for schistosomiasis: Given the patient’s history of living in sub-Saharan Africa, testing for Schistosoma antibodies can help confirm or exclude schistosomiasis as the cause of the patient’s symptoms. Kidney ultrasound: Imaging of the kidneys can provide information about their size, shape, and possible structural abnormalities. It can also identify hydronephrosis, kidney stones, or an obstructive cause for AKI. Additional blood tests: Measure serum complement levels, antinuclear antibody (ANA), anti-neutrophil cytoplasmic antibody (ANCA), and anti-glomerular basement membrane antibody (anti-GBM) to assess for possible glomeru- lonephritis. Cystoscopy: If the previous tests do not lead to a clear diagnosis, a cystoscopy can be performed to visualize the bladder and assess for interstitial cystitis, malacoplakia, or any other abnormalities. Kidney biopsy: In cases where the diagnosis remains uncertain, a kidney biopsy can help identify the underlying cause of the patient’s kidney dysfunction, such as glomerulonephritis or other renal pathologies. The ideal sequencing of tests depends on the individual case, availability of resources, and the clinical judgment of the healthcare provider. It is important to prioritize tests based on the most likely diagnoses given the patient’s history and clinical presentation. In this case, a detailed patient history, urinalysis, serology for schistosomiasis, and kidney ultrasound are the initial tests that can provide valuable information to narrow down the differential diagnosis. Further tests, such as blood tests for autoimmune markers and kidney biopsy, can be performed if the initial tests do not provide a definitive diagnosis. Figure D.2: GPT-4 offers recommendations on information and tests that can narrow the differential diagnosis. 34 # GPT-4: Schistosomiasis and Patient Conversations interaction continued ... → What are ideal treatments for schistosomiasis? Schistosomiasis is a parasitic infection caused by various species of flatworms called Schistosoma. The ideal treatment for schistosomiasis primarily involves the use of antiparasitic medications. The choice of medication and duration of treatment depend on the specific Schistosoma species causing the infection. Praziquantel: Praziquantel is the drug of choice for treating all major forms of schistosomiasis, including those caused by Schistosoma mansoni, Schistosoma haematobium, and Schistosoma japonicum. It works by paralyzing the parasites and making them susceptible to the host’s immune system. Praziquantel is typically given as a single oral dose or split into multiple doses taken on the same day, depending on the species and severity of the infection. Oxamniquine: Oxamniquine is an alternative treatment for Schistosoma mansoni infections, particularly in areas where Praziquantel resistance has been reported. However, it is not effective against other species of Schistosoma. In addition to antiparasitic medications, supportive care may be necessary in some cases, depending on the severity of the infection and the presence of complications: Analgesics or anti-inflammatory medications: These drugs can help manage pain and inflammation associated with the infection. Corticosteroids: In severe cases with complications such as central nervous system involvement or pulmonary hypertension, corticosteroids may be used to manage inflammation and reduce symptoms. Treatment of complications: Specific complications, such as anemia, secondary infections, or organ damage, may require additional medical management. Monitoring and follow-up: After treatment, patients should be monitored for resolution of symptoms and clearance of the infection. In some cases, repeat treatment with antiparasitic medications may be necessary if the infection persists or reinfection occurs. Preventive measures, such as access to clean water, sanitation improvements, and snail control, are essential to reduce the risk of schistosomiasis transmission in endemic areas. Mass drug administration with Praziquantel is also used as a public health strategy to control the disease in high-risk populations. → What might the physician treating the patient say in a caring way to the patient when revealing the likely diagnosis? Doctor: [Patient’s name], thank you for providing us with all the information about your symptoms and med- ical history. Based on your recent experience of living in sub-Saharan Africa, your symptoms, and the lab results, it appears that you may have a parasitic infection called schistosomiasis. This condition can cause blood in your urine and affect your kidney function, which is consistent with your lab findings. I understand that receiving a diagnosis like this can be concerning, but I want to assure you that schistosomiasis is treatable. We will prescribe an antiparasitic medication called Praziquantel, which is very effective in treating this infection. You should start to see an improvement in your symptoms after completing the treatment. It’s important to follow the treatment plan and attend follow-up appointments so we can monitor your progress and ensure the infection has been cleared. If you have any questions or concerns, please don’t hesitate to ask. We are here to support you throughout your treatment and recovery. Remember, you’re not alone in this journey, and we’ll do everything we can to help you regain your health. Figure D.3: Advice from GPT-4 on engaging with a patient with the diagnosis of schistoso- miasis. 35
Title: Shortcut Learning of Large Language Models in Natural Language Understanding: Summary: Large language models (LLMs) have achieved state-of-the-art performance on a series of natural language understanding tasks. However, these LLMs might rely on dataset bias and artifacts as shortcuts for prediction. This has significantly affected their generalizability and adversarial robustness. In this paper, we provide a review of recent developments that address the shortcut learning and robustness challenge of LLMs. We first introduce the concepts of shortcut learning of language models. We then introduce methods to identify shortcut learning behavior in language models, characterize the reasons for shortcut learning, as well as introduce mitigation solutions. Finally, we discuss key research challenges and potential research directions in order to advance the field of LLMs. # Shortcut Learning of Large Language Models in Natural Language Understanding # Mengnan Du New Jersey Institute of Technology Newark, NJ, USA mengnan.du@njit.edu Fengxiang He JD Explore Academy Beijing, Beijing, China fengxiang.f.he@gmail.com Na Zou Texas A&M University College Station, TX, USA nzou1@tamu.edu Dacheng Tao The University of Sydney Sydney, Australia dacheng.tao@gmail.com Xia Hu Rice University Houston, TX, USA xia.hu@rice.edu ABSTRACT Large language models (LLMs) have achieved state-of-the-art perfor- mance on a series of natural language understanding tasks. However, these LLMs might rely on dataset bias and artifacts as shortcuts for prediction. This has significantly affected their generalizability and adversarial robustness. In this paper, we provide a review of recent developments that address the shortcut learning and robustness chal- lenge of LLMs. We first introduce the concepts of shortcut learning of language models. We then introduce methods to identify shortcut learning behavior in language models, characterize the reasons for shortcut learning, as well as introduce mitigation solutions. Finally, we discuss key research challenges and potential research directions in order to advance the field of LLMs. 1 Natural language understanding (NLU) is a subfield of artificial intelligence that requires computer software to comprehend input in the form of sentences. Representative NLU tasks include nat- ural language inference (NLI), question answering (QA), reading comprehension, etc. Furthermore, NLU has a number of real-world applications, including Amazon Alexa, Siri, and Google Assistant. The major characteristic of NLU tasks is that they are difficult and typically require world knowledge and commonsense reason- ing. Recently, large language models (LLMs), such as BERT [8], RoBERTa [20], T5 [30], GPT-3 [4], have been reported to achieve state-of-the-art performance in a series of high-level NLU tasks. The LLM performance has even been reported to be significantly higher than human performance. However, the superior performance has only been observed in the benchmark test data that have the same distribution as the training set. Recent studies indicate that these LLMs are not robust and that the models do not remain predictive when the distribution of inputs changes [9, 24, 47]. Specifically, these LLMs have low generalization performance when applied to Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org. Conference’17, July 2017, Washington, DC, USA © 2018 Association for Computing Machinery. ACM ISBN 978-x-xxxx-xxxx-x/YY/MM. . . $15.00 https://doi.org/XXXXXXX.XXXXXXX out-of-distribution (OOD) test data and are also vulnerable to vari- ous types of adversarial attack. This leaves us wondering: Why are these LLMs not robust? Have these LLMs mastered the high-level semantic understanding and reasoning that we expect of them? A major reason for the low robustness of LLMs is shortcut learn- ing. The shortcut learning behavior has also been called other names in the literature, such as learning bias, superficial correlations, right for wrong reasons, Clever Hans effect1, etc. The shortcut learning behavior has been observed for a series of NLU tasks. For example, recent empirical analysis indicates that the performance of BERT- like models for the NLI task could be mainly explained by relying on spurious statistical cues such as unigrams ‘not’, ‘do’, ‘is’ and bigrams ‘will not’ (see Figure 1 (b)) [13, 24]. Similarly, for the reading comprehension task, the models rely on the lexical match- ing of words between the question and the original passage, while ignoring the designed reading comprehension task [17]. The current standard approach to training LLM is to use empirical risk min- imization (ERM) on NLU datasets that typically contain various types of artifacts and biases. As such, LLMs have learned to rely on dataset artifacts and biases and capture their spurious correlations with certain class labels as shortcuts for prediction. The shortcut learning behavior has significantly affected the robustness of LLMs (see Figure 1 (a)), thus attracting increasing attention from the NLP community to address this problem. In this work, we offer a comprehensive review of the shortcut learning problem in language models with a focus on medium-sized LLMs those typically having less than a billion parameters. The main emphasis is on the prevalent pre-training and fine-tuning par- adigm utilized in NLU tasks (see Figure 3). We cover the concept of shortcut learning and robustness challenges in Section 2, detec- tion approaches in Section 3, characterization of the corresponding reasons in Section 4, and mitigation approaches in Section 5. We also provide a further discussion of future research directions and connections with other directions in Section 6. Beyond the standard fine-tuning paradigm, in Section 7, we briefly discuss the challenges of shortcut learning posed by the prompt-based paradigm, especially regarding the massive language models which possess over a billion parameters, such as GPT-3 and T5. 1The eponymous horse appeared to be capable of performing simple intellectual tasks, but actually relied on involuntary cues given by its handler. Conference’17, July 2017, Washington, DC, USA Mengnan Du, Fengxiang He, Na Zou, Dacheng Tao, and Xia Hu entailment (0.55) contradiction (0.97) neutral (0.74) entailment (0.91) contradiction (0.96) ( Human performance C1 IID performance (1 OOD performance [CLS] how can you prove it [SEP] can you [Billmelhow to prove it ? [SEP] [CLS] fun for adults and children . [SEP] fun for GHichildren . [SEP] [CLS] were they in there ? [SEP] were they §MppOsedto be in there ? [SEP] [CLS] how do we fix this ?' [SEP] Bille fix this ? [SEP] [CLS] you know and held over for trial [SEP] released and {{@Itrial . [SEP] Figure 1: Shortcut learning behavior and its negative impact, taking natural language inference (NLI) task for example. The goal of NLI is to infer whether the relationship between two branches of input, i.e., premise and hypothesis, is entailment, contradiction, or neutral. (a) LLMs outperforms human performance for IID benchmark test set, while achieve much lower generalization perfor- mance on OOD test set. (b) A key reason is that LLMs primarily rely on the lexical bias and other kinds of shortcuts for prediction. 2 SHORTCUT LEARNING PHENOMENA 2.1 What is Shortcut Learning? Features captured by the model can be broadly categorized as useless features, robust features, and non-robust features (see Figure 2). Shortcut learning refers to the phenomenon that LLMs (especially those trained with standard ERM-based method) highly rely on non-robust features as shortcuts, failing to learn robust features and capture high-level semantic understanding and reasoning. Non- robust features do help generalization for development and test sets that share the same distribution with training data. However, they cannot generalize to OOD test sets and are vulnerable to adversarial attacks. Non-robust features are oriented from biases in the training data and come in different formats. In the following, we introduce several representative ones. • Style Bias: The text style is a kind of pattern that is independent of semantics. Models have learned to rely on the erroneous text style as a shortcut rather than capturing the underlying semantics. Ad- versaries can use this style bias to launch adversarial attacks [29]. 2.2 Generalization and Robustness Challenge The shortcut learning behavior could significantly hurt LLMs’ OOD generalization as well as adversarial robustness. First, shortcut learning may result in significant performance degradation for OOD data. A common assumption is that training and test data are indepen- dently and identically distributed (IID). When LLMs are deployed in real-world applications with distribution shifts, this IID assumption will not hold any longer. These data typically do not contain the same types of bias and artifacts as the training data. • Lexical Bias: Some lexical features have a high correlation of co- occurrence with certain class labels. These lexical features mainly consist of low-level functional words such as stop words, numbers, negation words, etc. A typical example is the NLI task, where LLMs are highly dependent on unintended lexical features to make predictions [9, 24]. For example, these models tend to give contradiction predictions whenever there exist negation words in the input samples, e.g., ‘never’, ‘no’. • Overlap Bias: It occurs in NLU applications with two branches of text, e.g., natural language inference, question answering, and reading comprehension. LLMs use the overlap of features between the two branches of inputs as spurious correlations as shortcuts. For example, reading comprehension models use the overlap be- tween the passage and the question pair for prediction rather than solving the underlying task [17]. Similarly, question answering models excel at test sets by relying on the heuristics of question and context overlap [35]. • Position Bias: The distribution of the answer positions may be highly skewed in the training set for some applications. The LLMs would predict answers based on spurious positional cues. Take the question answering task for example, the answers lie only in the k- th sentence of each passage [16]. As a result, question answering models rely on this spurious cue when predicting answers. IID: 𝑷𝑡𝑟𝑎𝑖𝑛 (𝑿, 𝒀 ) = 𝑷𝑡𝑒𝑠𝑡 (𝑿, 𝒀 ) OOD: 𝑷𝑡𝑟𝑎𝑖𝑛 (𝑿, 𝒀 ) ≠ 𝑷𝑡𝑒𝑠𝑡 (𝑿, 𝒀 ) (1) Using BERT-base as an example, there is a more than 20% reduc- tion in accuracy on the OOD test set compared to the accuracy on the in-distribution test sets for NLU tasks [10]. To some extent, these models have solved the dataset rather than the underlying task. Second, shortcut learning produces models that are easily fooled by adversarial samples, which are generated when small and often imperceptible human-crafted perturbations are added to the normal input. One typical example is for the multiple choice reading compre- hension task [39]. BERT models are attacked by adding distracting information, resulting in a significant performance drop. Further analysis indicates that these models are highly driven by superficial patterns, which inevitably leads to their adversarial vulnerability. 3 SHORTCUT LEARNING DETECTION In this section, we discuss methods to identify shortcut learning problems in NLU models. 3.1 Comprehensive Performance Testing Traditional evaluations employ IID training-test split of data. The test sets are drawn from the same distribution as the training sets and thus share the same kind of biases as the training data. Models Shortcut Learning of Large Language Models in Natural Language Understanding Conference’17, July 2017, Washington, DC, USA IID generalization Non-robust features OOD and adversarial Robust features { Lexical bias \ ( ; | Overlapping bias | i semantic | Position bias | youn erstanding 1 Style bias I ; and reasoning I 1 \ ) ‘ St ¢ Manne eee ee # Useless features # robustness \ I | I } Figure 2: Features can be generally grouped into useless features, robust features, and non-robust features. Non-robust features indicate various kinds of biases captured by the model, which are not robust in the OOD setting. In contrast, robust features denote features of high-level semantic understanding that are robust to changes in the input. that simply rely on memorizing superficial patterns could perform acceptablely on the IID test set. This type of evaluation has failed to identify the shortcut learning problem. Therefore, it is desirable to perform more comprehensive tests beyond the traditional IID testing. First, the OOD generalization test has been proposed as an alterna- tive to the IID test. Take the multi-genre natural language inference (MNLI) task for example, the HANS evaluation set is proposed to evaluate whether NLI models have syntactic heuristics: the lexical overlap heuristic, the subsequence heuristic, and the constituent heuristic [21]. Similarly, for the fact verification task, a symmetric test set is constructed that shares a philosophy similar to HANS [34]. These OOD tests have revealed dramatic performance degradation and exposed the shortcut learning problem of state-of-the-art LLMs. Second, adversarial attacks could also be implemented to test the robustness of LLMs. For example, adversarial attacks have been used to reveal statistical bias in machine reading comprehension models [17]. Besides, the adversarial examples created through TextFooler [15] are used to test the generalization of common sense reasoning models [3]. The results indicate that the models have learned non-robust features and fail to generalize towards the main tasks associated with the datasets. identifying whether these models make decisions based on justi- fied reasons or on superficial patterns. Explainability enables us to diagnose spurious patterns captured by LLMs. The existing literature mainly employs the explanation in the for- mat of feature attribution to analyze shortcut learning behavior in NLU models [9]. Feature attribution is the most representative para- digm among all explainability-based methods. In particular, for each token 𝑥𝑖 within a specific input 𝑥, the feature attribution algorithm 𝜓 will calculate the contribution score 𝜓𝑖 , which denotes the contri- bution score of that token for model prediction. For example, the Integrated Gradient [43] interpretation method is used to analyze the model behavior of BERT-based models [9]. It is observed that LLMs rely on dataset artifacts and biases within the hypothesis sentence for prediction, including functional words, negation words, etc [9]. This shortcut learning behavior is summarized further using the long-tailed phenomenon. Specifically, the tokens in the training set could be modeled using a long-tailed distribution. The LLM models concentrate mainly on information on the head of the distribution, which typically corresponds to non-generalizable shortcut tokens. In contrast, the tail of the distribution is poorly learned, although it contains abundant information for an NLU task. Third, randomization ablation methods are proposed to analyze whether LLMs have used these essential factors to achieve effective language understanding. For example, word order is a representative one among these significant factors. Recent ablation results indicate that word order does not matter for pre-trained language models [40]. In particular, LLMs are pre-trained first on sentences with randomly shuffled word order and then fine-tuned on various downstream tasks. The results show that these models still achieve high accuracy. Similarly, another study [27] has observed that LLMs are insensitive to word order in a wide set of tasks, including the entire GLUE benchmark. These experiments indicate that LLMs have ignored the syntax when performing downstream tasks, and their success can almost be explained by their ability to model higher-order word co-occurrence statistics. Beyond feature attribution, other types of explainability meth- ods have also been used to analyze shortcut learning behaviors. For example, instance attribution methods have been used to explain model prediction by identifying influential training data, which can be used to explain decision making logic for the current sample of interest [14]. Empirical analysis indicates that the most influential training data share similar artifacts, e.g., high overlap between the premise and hypothesis for the NLI task. Furthermore, hybrid meth- ods that combine feature attribution and instance attribution have also been used to identify artifacts in the data [26]. The resulting explanations have provided a more comprehensive perspective on the shortcut learning behavior of LLMs. 3.2 Explainability Analysis Model explainability is another effective tool that the community has used to identify the shortcut learning problem. LLMs are usually considered black boxes, as their decision-making process is opaque and difficult for humans to understand. This presents challenges in 4 ORIGINS OF SHORTCUT LEARNING The problem of learning shortcuts in LLM models for NLU tasks is a result of multiple factors present in the training pipeline (see Figure 3). In this section, we will delve into these reasons and give particular emphasis to three key elements: the training datasets, the LLM model, and the fine-tuning training procedure. Conference’17, July 2017, Washington, DC, USA Mengnan Du, Fengxiang He, Na Zou, Dacheng Tao, and Xia Hu Unsupervised Large scale | __pre-training Pre-trained Fine-tuning Task Text corpus Language models Model Downstream Datasets Supervised Figure 3: The pre-training then fine-tuning training paradigm. Shortcut learning can be attributed to different factors in this pipeline, including pre-trained language models, fine-tuning process, and downstream tasks. 4.1 Skewed Training Dataset From a data standpoint, the NLU models’ shortcut learning can be traced back to the annotation and collection artifacts of the training data to a large extent. Here, the training data include both the pre- training datasets as well as the downstream datasets (see Figure 3). Training sets are typically built through the crowd-sourcing process, which has the advantage of being low-cost and scalable. However, the crowd-sourcing process results in collection artifacts, where the training data are imbalanced with respect to features and class labels. Furthermore, when crowd workers author parts of the samples, they produce certain patterns of artifacts, i.e., annotation artifacts [13, 33]. Taking NLI as an example, the average sentence length of the hy- pothesis branch is shorter for the entailment category compared to the neutral category [13]. This suggests that crowd workers tend to remove words from the premise to create a hypothesis for the entailment category, leading to the overlap bias in the training data. Models trained on the skewed datasets will capture these artifacts and even amplify them during inference time. 4.2 LLMs Models The robustness of NLU models is highly relevant to the pre-finetuned language models. In particular, there are two key factors: model sizes (measured by the number of parameters) and pre-training objectives. First, models with the same kind of architectures and pre-training objective but with different sizes could have significantly different generalization ability. It is shown that increasing the size of the model could lead to an increase in the representation power and generalization ability. From the empirical perspective, comparisons have been made between LLMs of different sizes but with the same architecture, e.g., BERT-base with BERT-large, RoBERTa-base with RoBERTa-large [2, 46]. The results show that the larger versions generalize consistently better than the base versions, with a rela- tively smaller accuracy gap between the OOD and IID test data. Smaller models have fewer parameters than larger models and have a smaller model capacity. Therefore, smaller models are more prone to capture spurious patterns and are more dependent on data artifacts for prediction. Another work [10] studies the impact of model com- pression on the generalizability of LLMs and finds that compressed LLMs are significantly less robust compared to their uncompressed counterparts. Compressed models with knowledge distillation have also been shown to be more vulnerable to adversarial attacks. From a theoretical perspective, a recent analysis supports that there is a trade-off between the size of a model and its robustness, where large models tend to be more robust than smaller ones [5]. Second, LLMs with similar model sizes but with different pre- training objectives also differ in the generalization ability. Here, we consider three kinds of LLMs: BERT, ELECTRA, and RoBERTa. BERT is trained with masked language modeling and next-sentence prediction. RoBERTa removes the next-sentence prediction from BERT and uses dynamic masking. ELECTRA is trained to distin- guish between real input tokens and fake input tokens generated by another network. Empirical analysis shows that these three mod- els have significantly different levels of robustness [28]. For the Adversarial NLI (ANLI) dataset, it is shown that ELECTRA and RoBERTa have significantly better performance than BERT, for both the base and the large versions. Similarly, another study has shown that RoBERTa-base outperforms BERT-base around 20% in terms of accuracy on the HANS test set [2]. Because different architectures have distinct object functions during the pre-training stage, different inductive biases may be encoded by the models. This could possibly explain their differences in generalizability. 4.3 Model Fine-tuning Process The learning dynamics could reveal what knowledge has been learned during the course of model training. There are some observations. First, standard training procedures have a bias toward learning sim- ple features, which we can refer to as the simplicity bias. The models are based mainly on the simplest features and remain invariant to complex predictive features. Moreover, it has been observed that the models give overconfident predictions for easy samples and low- confidence predictions for hard samples. Second, models tend to learn non-robust and easy-to-learn features at the early stage of train- ing. For example, reading comprehension models have learned the shortcut in the first few training iterations, which has influenced fur- ther exploration of the models for more robust features [17]. Third, it has been experimentally validated that longer fine-tuning could lead to better generalization. Specifically, a larger number of train- ing epochs will dramatically improve the generalizability of LLMs in NLU tasks [46]. The preference for non-robust features can be explained from the following perspective. The present LLM training methods can be considered as data-driven, corpus-based, statistical, and machine learning approaches. It is postulated that while this data-driven paradigm may prove effective in certain NLP tasks, it falls short in relevance to the challenging NLU tasks that necessitate a deeper understanding of natural language. 5 MITIGATION OF SHORTCUT LEARNING In this section, we introduce approaches that alleviate the problem of shortcut learning. The ultimate goal is to improve OOD generaliza- tion and adversarial robustness while still exhibiting good predictive performance in IID datasets. These methods are motivated mainly by the insights obtained in the last section. In particular, Section 5.1 introduces methods based on dataset refinement, and Section 5.2 focuses on model-centric mitigation approaches. Shortcut Learning of Large Language Models in Natural Language Understanding # 5.1 Data-Centric Mitigation Approaches Dataset Refinement. Dataset refinement falls into the pre-processing mitigation family, with the aim of alleviating biases in the training datasets. First, when constructing new datasets, crowd workers will receive additional instructions to discourage the use of words that are highly indicative of annotation artifacts. Second, debiased datasets can also be developed by filtering out bias in existing data. For exam- ple, adversarial filtering is used to build a large-scale data set for the NLI task to reduce annotation artifacts that can be easily detected by a committee of strong baseline methods [54]. As a result, models trained on this dataset have to learn more generalizable features and rely on common sense reasoning to succeed. Third, we can also reorganize the train and test split, so that the bias distribution in the test set is different from that in the training set. Lastly, various types of data augmentation methods have been proposed. Represen- tative examples include counterfactual data augmentation, mixup data augmentation, syntactically informative example augmentation by applying syntactic transformations to sentences, etc. However, a drawback of this approach is that refining the dataset can only mitigate a limited number of recognized biases. The refined training set may not be completely free of biases and may still en- compass statistical biases that are challenging for humans to identify. Thus, this could still negatively impact the model’s performance. Training Samples Reweighting. The main idea of reweighting is to place higher training weights on hard training samples, and vice versa [34, 47]. It is also called worst-group loss minimization in some literature. The underlying assumption is that improving the performance of the worst group (hard samples) is beneficial to the robustness of the model. It is typically achieved through two-stage training. In the first stage, the weight indexing model is trained; and in the second stage, the predictions of the indexing model are used as weights to adjust the importance of a training instance. Both soft weights [47] and hard weights could be used in the second stage. Another representative example is focal loss, which is based on a regularizer to assign higher weights to hard samples that have less confident predictions. Partitioning Data into Environments. This line of methods fol- lows the principle of invariant risk minimization [1], which en- courages models to learn invariants in multiple environments. For example, training data has been partitioned into several non-IID sub- sets (i.e., training environments), where spurious correlations vary across environments and reliable ones remain stable across environ- ments [45]. The training scheme is designed to encourage the model to rely on stable correlations and suppress spurious correlations. Another work proposes an inter-environment matching objective by maximizing the inner product between gradients from different environments, with the goal of increasing model generalization [37]. 5.2 Model-Centric Mitigation Methods In this section, we introduce model-centric mitigation methods, which can be named robust learning methods. These methods typ- ically augment the traditional ERM-based training paradigm with Conference’17, July 2017, Washington, DC, USA different degrees of prior knowledge, explicitly or implicitly sup- pressing the model from capturing non-robust features. Some miti- gation methods require that the shortcuts be known a priori, while others assume that the shortcuts are unknown. Adversarial Training. This aims to learn better representations that do not contain information about artifacts or bias in the data. It is typically implemented in two ways in the NLP domain [31, 42]. First, the task classifier and adversarial classifier jointly share the same encoder [42]. The goal of the adversarial classifier is to provide the correct predictions for the artifacts in the training data. Then the encoder and task classifier can be trained to optimize the task objective while reducing the performance of the adversarial classifier in predicting artifacts. Second, adversarial examples are generated to maximize a loss function, and the model is trained to minimize the loss function. For example, the generator based on the masked language model is used to perturb the text to generate adversarial samples [31]. Despite the difference, both methods leverage the MinMax formulation during the debiasing process. Explanation Regularization. This category aims to regularize model training using prior knowledge established by humans [19]. Specif- ically, it is achieved by regularizing the feature attribution expla- nations with rationale annotations created by domain experts, to enforce the model to make the right predictions for the right rea- sons [19]. These systems are trained to explicitly encourage the network to focus on features in the input that humans have anno- tated as important and suppress the models’ attention to superficial patterns. For the NLI task, natural language explanations have been used to supervise the models, to encourage the model to pay more attention to the words present in the explanations [41]. It has signifi- cantly improved the models’ OOD generalization performance. Note that this type of method can only be used when prior knowledge is known in advance about shortcuts. Product-of-Expert (PoE). The goal is to train a debiased model by training it as an ensemble with a bias-only model [7]. This paradigm usually contains two stages. In the first stage, a bias- only model is explicitly trained to capture the bias of the data set, e.g. the hypothesis-only bias for the NLI task. During the second stage, the debiased model will be trained using cross-entropy loss, by combining its output with the output of the bias-only model: ˆ𝑝𝑖 = softmax (log (𝑝𝑖 ) + log (𝑏𝑖 )) . The parameters of the bias-only model are fixed during this stage, and only the debiased model pa- rameters are updated by backpropagation. The goal is to encourage the debiased model to utilize orthogonal information with informa- tion from the bias-only model to make predictions. Confidence Regularization. This mitigation scheme regularizes confidence in the model output, with the aim of encouraging the debiased model to give a higher uncertainty (lower confidence) for these biased samples. It is based on the observation that models tend to make overconfident predictions on biased examples. This relies on the training of a bias-only model to quantify the degree of bias of each training sample. The debiasing process is typically achieved through the knowledge distillation framework. In the first stage, the biased teacher model is trained using standard ERM loss, and the bias degree obtained from the bias-only model will be used to rescale the output distribution of the teacher model. In the second Conference’17, July 2017, Washington, DC, USA stage, the smoothed confidence values of the teacher model can be used to guide the training of the debiased model [9]. Contrastive Learning. Contrastive learning can be used to guide the training of representations. The goal is to construct the instance discrimination task to guide the model to capture the robust and predictive features, while suppressing the undesirable non-robust fea- tures. The instance discrimination task should be carefully designed; otherwise, it is possible to suppress robust predictive features [32]. A representative work presents a framework for mitigating spurious correlations using contrastive learning [6]. The method synthesizes a pair of factual and counterfactual inputs from the original text by masking identified causal and non-causal terms respectively. The model learns to associate the causal term with task labels by com- paring the original text with its counterfactual counterpart, while learning to ignore non-causal features by contrasting with the factual pair. The framework leads to models that are less dependent on non- robust features and exhibit improved generalization performance. 5.3 Another open question is about the connection between IID per- formance and OOD robustness performance. To the best of our knowledge, there are no consistent observations. For example, there is a linear correlation between IID performance and OOD general- ization for different types of models introduced in Section 4.2. On the contrary, most robust learning methods introduced in Section 5.2 will sacrifice IID performance, although some of them could pre- serve IID performance. It deserves further research on the conditions under which the trade-off would occur. These insights could help the research community design robust learning frameworks that can simultaneously improve OOD and IID performance. 6 FUTURE RESEARCH DIRECTIONS Despite the progress described in the previous sections, there are still numerous research challenges. In this section, we discuss potential research directions that could be pursued by the community. 6.1 Current standard of LLM training is data-driven. This is problematic because the resulting models essentially perform low-level pattern recognition. It may be useful for low-level NLP tasks like named- entity recognition (NER), but it is nearly impossible to tackle the more difficult natural language understanding tasks. As a result, it is preferable to combine the data-driven scheme with domain knowledge by incorporating knowledge at various stages of training. Furthermore, more knowledge should be applied to the design of the model architecture and the model evaluation (see Figure 4). Inductive Bias to LLMs Models. It is suggested to introduce more inductive bias into the model architecture to improve robustness and generalization beyond IID benchmark datasets. Recently, some work has begun to induce certain kinds of linguistic structure in neural architectures. For example, TableFormer is proposed for robust table understanding [53]. It proposes a structurally aware table-text en- coding architecture, where tabular structural biases are incorporated through learnable attention biases. Although introducing linguistic- oriented biases to the model architectures might not result in the Mengnan Du, Fengxiang He, Na Zou, Dacheng Tao, and Xia Hu best performance for benchmark datasets, it is essential to improve generalization beyond IID benchmarks. Note that inductive biases are highly task-dependent and should be carefully designed for each specific task to accommodate its unique characteristic. Better Pre-training Objectives. The pre-training objective also plays a crucial role in determining the OOD robustness of fine-tuned language models. As an example, recent studies have shown that pre- trained BERT embeddings suffer from strong anisotropy, meaning the average cosine similarity is significantly higher than zero and word vectors cluster in narrow cones in the vector space [12, 18]. This leads to word representations having a high similarity to un- related words, impacting their expressive power and accuracy in downstream tasks. It is desirable to invest more effort in designing better pre-training objectives to improve model robustness. Recent studies indicate that choosing a better pre-trained model could bring much better generalization performance than robust learning meth- ods as introduced in Section 5. For example, RoBERTa-base with a standard fine-tuning loss could even outperform the BERT-base with robust learning objectives in terms of generalization performance on the HANS test set [2]. This highlights the importance of pre-training in NLU model generalization performance and calls for increased community efforts to improve pre-trained language models. Better Fine-tuning Approaches. NLU tasks may contain various types of bias, which are not fully known even by domain experts. This is distinct from the literature that works with the toy task (e.g., Colored MNIST [1]), which typically contains a single type of bias and the bias is fully known. As a result, the majority of existing mitigation methods for NLU tasks rely on human prior knowledge heuristics. Some examples include: i) weak models are more prone to capture biases, ii) non-robust models tend to give overconfident pre- dictions for easy samples, etc. Unfortunately, this prior knowledge can only identify a limited number of biases in the data. Although it is possible to reduce the use of some identified shortcuts, models may still use other shortcuts for prediction. This could explain why existing mitigation methods only provide a limited improvement in generalization. As a result, it is suggested to incorporate more human-like common sense knowledge into the model training. Curating Challenging Evaluation Datasets. It is encouraging to see that some benchmark datasets for adversarial and OOD robust- ness have emerged. For example, adversarial GLUE is proposed for adversarial robustness evaluation, which contains 14 adversarial attack methods [50]. Despite these recent advances, it is necessary to continue curating difficult evaluation datasets that cover a wider range of NLU tasks, such as reading comprehension, and that cover a wider range of biases, such as those listed in Section 2.1. 6.2 Revisiting The Mitigation Approaches Existing mitigation methods have typically had limited mitigation performance. For example, for the MNLI task, the accuracy for miti- gated models with BERT-base as the backbone is consistently lower than 70% for the HANS test set [47]. Note that HANS is a balanced binary test set, where 50% is the accuracy of the random guess. The improvement in performance falls far short of our expectations. This brings up the following questions: 1) What have the mitigation algorithms accomplished, and 2) how can mitigation performance be improved further? Shortcut Learning of Large Language Models in Natural Language Understanding Conference’17, July 2017, Washington, DC, USA Combining More Human Knowledge LLM architecture Introducing more inductive bias Designing better pre- training objectives Evaluation Curating challenging evaluation data sets Combining task- specific knowledge Figure 4: Combining more human knowledge to different stages of the pipeline. Specifically, knowledge can be combined to the architecture of model, model training process (both pre-training and fine-tuning), and model evaluation process. Debiased algorithms are thought to achieve better generalization because they can learn more robust features than biased models that rely primarily on non-robust features. However, this is not always the case with debiased algorithms. A recent work uses explainability as a debugging tool to analyze debiased models [22]. The analysis indicates that the debiased models actually encode more biases in their inner representations. It is speculated that the improved performance on the OOD data comes from the refined classification head. More research is needed to investigate whether the debiased model has captured more robust features and what is the source of their improved generalization. This also suggests an interesting research direction by only updating the biased classification head, as updating the entire model is typically difficult and time consuming. 6.3 In addition to the current empirical research, there is also a growing trend of preliminary theoretical research aimed at uncovering the shortcut learning behavior of DNN models [23, 36, 49]. For instance, using one-hidden-layer neural networks as the base model, one theo- retical work uncovers that neural networks tend to exclusively rely on simplest and non-robust features, while remain invariant to other useful but more complex features [36]. This type of simplicity bias is one of the primary causes of low OOD generalization and adver- sarial vulnerability. Another theoretical study has investigated the reason behind superficial correlations from the optimization perspec- tive [49]. By using a depth-2 ReLU network as an example, the study proposed the Gradient Starvation phenomenon, which states that the gradient descent optimization methods tend to learn non-robust net- works while slowing down the learning of robust and task-relevant features. Although these existing works provide insights into the reason of shortcut learning of shallow neural networks, there is still a lack of a solid theoretical understanding of why LLMs learn short- cuts. In the future, further research is needed to fully explain this tendency in the context of LLMs. 6.4 Taking Inspiration from Other Directions In addition, we can take inspiration from other relevant directions to address the shortcut learning issue of LLMs. Domain Adaptation & Generalization. The robust learning ap- proaches that we have discussed in Section 5 are closely relevant to domain adaptation and domain generalization. The three directions share the similarity that the training and test sets are not from the same distribution, i.e., there is a certain distribution shift. However, the objective of robust learning is distinct from domain adaptation, which aims to generalize to a specific target domain. In contrast, robust learning is closer to domain generalization, where both areas have the goal of generalizing over a range of unknown conditions. The NLP community can leverage the findings from the domain gen- eralization area to design more robust learning methods for LLMs. Long-Tailed Classification. Long-tailed classification addresses the issue of long-tailed distributed data, in which the head class has a large number of training samples while the tail class has few. Shortcut learning can be treated as a special case of long-tailed classification, where easy samples correspond to the head class and hard samples represent the tail class. Some of the robust learning solutions (e.g., reweighting) in Section 5 share a similar philosophy with approaches to the long-tailed classification problem. Leveraging ideas from approaches to long-tailed classification could improve the robustness of LLMs even further. Algorithmic Discrimination. Shortcut learning could also lead to discrimination and unfairness in deep learning models. In contrast to the general bias captured by the models, the spurious patterns here usually correspond to societal biases in terms of humans (e.g., racial bias and gender bias) [11]. Here, the models have associated the fairness-sensitive attributes (e.g., ZIP code and surname) with main prediction task labels (e.g., mortgage loan rejection). At the inference time, the model would amplify the bias and show discrimination towards certain demographic groups, e.g., African Americans. 6.5 Motivating Other Directions We can also take advantage of the insights discussed above to moti- vate the development of other directions. Backdoor Attack. The previous sections focus on discussing the setting in which LLMs have unintentionally captured undesirable shortcuts. However, the adversary can intentionally insert shortcuts into LLMs, which could be a potential security threat to the deployed LLMs. This is termed the backdoor attack (or poisoning/Trojan attack) [44]. Backdoor attackers insert human-crafted easy patterns that serve as shortcuts during the model training process, explicitly encouraging the model to learn shortcuts. Representative examples include modifying the style of text, adding shortcut unigrams such as double quotation marks, etc. Conference’17, July 2017, Washington, DC, USA Watermarking. Unlike malicious use of shortcut learning as the backdoor attack, shortcut learning can also be used for benign pur- poses. In particular, trigger patterns can be inserted as watermarks by model owners during the training phase to protect the IP of com- panies. When LLMs are used by unauthorized users, shortcuts in the format of trigger patterns can be used by the stakeholders to claim ownership of the models. 7 PROMPT-BASED PARADIGM In previous sections, we have explored the characterization of the shortcut learning problem in the pre-training and fine-tuning training paradigm of medium-sized language models (typically with less than a billion parameters). With the recent emergence of huge-sized lan- guage models (with billions of parameters) such as GPT-3 and T5, the prompt-based paradigm has evolved into a new training para- digm with distinct formats from the standard fine-tuning paradigm. Consider the example of prompt for GPT-3. Using natural language instructions and/or demonstration of a few tasks, the LLM can gen- erate the desired output without the need for gradient updates or fine-tuning. In this section, we examine the robustness of prompt- based methods and then compare them with the traditional standard fine-tuning approach. 7.1 Robustness of Prompt-based Methods There are two types of prompt-based paradigms: 1) prompt-based fine-tuning and 2) prompting without fine-tuning. Prompt-based fine- tuning aims to enable medium-sized language models like BERT or RoBERTa to be few-shot learners, and this still requires optimizing the model’s parameters. On the other hand, prompting without fine- tuning is meant for huge-sized language models like GPT-3, where the parameters are fixed and the model is applied to various tasks using different prompts, either discrete or soft. In the following discussion, we will discuss the shortcut learning issue in both types of prompt-based paradigms. Prompt-based Fine-tuning. Preliminary research has been con- ducted to examine the shortcut learning challenge in the few-shot prompt-based fine-tuning paradigm [48]. This preliminary study in- vestigated the RoBERTa-large model, which comprises 355 million parameters. This work reveals the following insights: (i) zero-shot prompt-based models exhibit a higher level of robustness against the lexical overlap heuristic during inference, as evidenced by their strong performance on relevant challenge datasets. (ii) conversely, prompt-based finetuned models tend to adopt the spurious heuristic as they learn from larger amounts of labeled data, which is reflected by poor performance on OOD datasets. This indicates that prompt- based fine-tuning negatively impacts the robustness and generaliz- ability of a model, just like the standard fine-tuning. The primary reason is that both training methods require adjusting the model’s pa- rameters using a biased NLI dataset, leading to a model that heavily relies on dataset biases as shortcuts for predictions. Prompting Without Fine-tuning. Preliminary studies are emerging to examine the robustness of prompt-based methods for huge-size language models [51, 55]. A study examines the few-shot learning performance of GPT-3 (2.7B, 13B, and 175B parameters) and GPT-2 (1.5B parameters) on text classification and information extraction tasks [55]. The results of the analysis reveal that the investigated Mengnan Du, Fengxiang He, Na Zou, Dacheng Tao, and Xia Hu LLMs are susceptible to majority label bias and position bias, where they tend to predict answers based on the frequency or position of the answers in the training data. Additionally, these LLMs also exhibit common token bias, where they favor answers that are prevalent in their pre-training corpus. Another study explores the impact of prompts on natural language inference tasks in zero-shot and few- shot settings using T0 (3B and 11B parameters) and GPT-3 (175B parameters) [51]. Experimental results suggest that models can learn just as quickly with many irrelevant or even misleading prompts as they can with effective and instructive prompts. This indicate that models’ improvement is not derived from models understanding task instructions in ways analogous to humans’ use of task instructions. 7.2 Prompting versus Standard Fine-tuning GPT-3’s few-shot prompt performance is compared to that of BERT and RoBERTa through standard fine-tuning on two natural language inference tasks, i.e., MNLI and QQP [38]. Additionally, these models are evaluated on the corresponding difficult OOD datasets: HANS and PAWS. The results show that GPT-3 performs slightly worse in generalization than BERT and RoBERTa on the in distribution MNLI and QQP datasets. On the other hand, GPT-3 achieves higher accuracy on the OOD tests for the majority of testing settings, in- dicating that GPT-3 has a lower generalization gap between the in distribution test set and the OOD test set, and thus a higher robust- ness. However, further analysis of the HANS dataset reveals that GPT-3 still exhibits substantial performance disparities between the bias-supporting and bias-countering subsets. This implies that there is room for enhancing the robustness of prompt-based techniques. Note that the current research on prompt-based methods primarily aims at improving LLMs’ performance on standard benchmarks. The robustness and generalization of this paradigm still require fur- ther investigation. A more thorough evaluation of prompt-based methods is needed and could be a future research topic. Addition- ally, techniques such as Chain-of-Thought [52] and Scratchpad [25] have been utilized to encourage models to perform intermediate calculations. These methods have proven to enhance the reason- ing abilities of LLMs, thus having the potential to improve their robustness and generalization capabilities. Lastly, developing miti- gation frameworks that can improve generalization performance on OOD test sets without sacrificing standard benchmark performance deserves more attention from the research community. 8 CONCLUSIONS We present a thorough survey of the LLM’s shortcut learning issue for NLU tasks in this article. Our findings suggest that shortcut learn- ing is caused by a skewed dataset, model architecture, and model learning dynamics. We also summarize the mitigation solutions that can be used to reduce shortcut learning and improve the robustness of LLMs. Furthermore, we discuss directions that merit additional research effort from the research community, as well as the connec- tions between shortcut learning and other relevant directions. The key takeaways from this survey’s analysis are that the current pure data-driven training paradigm for LLMs is insufficient for high-level natural language understanding. In the future, the data-driven para- digm should be combined with domain knowledge at every stage of model design and evaluation to advance the field of LLMs. Shortcut Learning of Large Language Models in Natural Language Understanding # REFERENCES [1] Martin Arjovsky, Léon Bottou, Ishaan Gulrajani, and David Lopez-Paz. 2019. Invariant risk minimization. arXiv preprint arXiv:1907.02893 (2019). [2] Prajjwal Bhargava, Aleksandr Drozd, and Anna Rogers. 2021. Generalization in NLI: Ways (Not) To Go Beyond Simple Heuristics. In Proceedings of the Second Workshop on Insights from Negative Results in NLP. [3] Ruben Branco, António Branco, João Silva, and João Rodrigues. 2021. Shortcutted Commonsense: Data Spuriousness in Deep Learning of Commonsense Reasoning. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing (EMNLP). [4] Tom B Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. 2020. Language models are few-shot learners. Advances in Neural Information Processing Systems (NeurIPS) (2020). [5] Sébastien Bubeck and Mark Sellke. 2021. A universal law of robustness via isoperimetry. Advances in Neural Information Processing Systems (NeurIPS) (2021). [6] Seungtaek Choi, Myeongho Jeong, Hojae Han, and Seung-won Hwang. 2022. C2l: Causally contrastive learning for robust text classification. In Proceedings of the AAAI Conference on Artificial Intelligence, Vol. 36. 10526–10534. [7] Christopher Clark, Mark Yatskar, and Luke Zettlemoyer. 2019. Don’t Take the Easy Way Out: Ensemble Based Methods for Avoiding Known Dataset Biases. Empirical Methods in Natural Language Processing (EMNLP) (2019). [8] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. Bert: Pre-training of deep bidirectional transformers for language understanding. North American Chapter of the Association for Computational Linguistics (NAACL) (2019). [9] Mengnan Du, Varun Manjunatha, Rajiv Jain, Ruchi Deshpande, Franck Dernon- court, Jiuxiang Gu, Tong Sun, and Xia Hu. 2021. Towards Interpreting and Mitigating Shortcut Learning Behavior of NLU Models. North American Chapter of the Association for Computational Linguistics (NAACL) (2021). [10] Mengnan Du, Subhabrata Mukherjee, Yu Cheng, Milad Shokouhi, Xia Hu, and Ahmed Hassan Awadallah. 2023. Robustness Challenges in Model Distillation and Pruning for Natural Language Understanding. The 17th Annual Meeting of the European chapter of the Association for Computational Linguistics (EACL) (2023). [11] Mengnan Du, Fan Yang, Na Zou, and Xia Hu. 2020. Fairness in deep learning: A computational perspective. IEEE Intelligent Systems (2020). [12] Kawin Ethayarajh. 2019. How Contextual are Contextualized Word Represen- tations? Comparing the Geometry of BERT, ELMo, and GPT-2 Embeddings. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP). 55–65. [13] Suchin Gururangan, Swabha Swayamdipta, Omer Levy, Roy Schwartz, Samuel R Bowman, and Noah A Smith. 2018. Annotation artifacts in natural language inference data. North American Chapter of the Association for Computational Linguistics (NAACL) (2018). [14] Xiaochuang Han, Byron C Wallace, and Yulia Tsvetkov. 2020. Explaining Black Box Predictions and Unveiling Data Artifacts through Influence Functions. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics (ACL). Is bert re- ally robust? a strong baseline for natural language attack on text classification and entailment. In Proceedings of the AAAI conference on artificial intelligence (AAAI). [16] Miyoung Ko, Jinhyuk Lee, Hyunjae Kim, Gangwoo Kim, and Jaewoo Kang. 2020. Look at the First Sentence: Position Bias in Question Answering. In Empirical Methods in Natural Language Processing (EMNLP). [17] Yuxuan Lai, Chen Zhang, Yansong Feng, Quzhe Huang, and Dongyan Zhao. 2021. Why Machine Reading Comprehension Models Learn Shortcuts? ACL Findings (2021). [18] Yuxin Liang, Rui Cao, Jie Zheng, Jie Ren, and Ling Gao. 2021. Learning to re- move: Towards isotropic pre-trained BERT embedding. Artificial Neural Networks and Machine Learning–ICANN 2021: 30th International Conference on Artificial Neural Networks, Bratislava, Slovakia, September 14–17, 2021, Proceedings, Part V 30 (2021), 448–459. [19] Frederick Liu and Besim Avci. 2019. Incorporating priors with feature attribution on text classification. 57th Annual Meeting of the Association for Computational Linguistics (ACL) (2019). [20] Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining approach. arXiv preprint arXiv:1907.11692 (2019). [21] R Thomas McCoy, Ellie Pavlick, and Tal Linzen. 2019. Right for the wrong reasons: Diagnosing syntactic heuristics in natural language inference. 57th Annual Meeting of the Association for Computational Linguistics (ACL) (2019). Conference’17, July 2017, Washington, DC, USA [22] Michael Mendelson and Yonatan Belinkov. 2021. Debiasing Methods in Natural Language Understanding Make Bias More Accessible. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing (EMNLP). [23] Depen Morwani, Jatin Batra, Prateek Jain, and Praneeth Netrapalli. 2023. Simplic- ity Bias in 1-Hidden Layer Neural Networks. arXiv preprint arXiv:2302.00457 (2023). [24] Timothy Niven and Hung-Yu Kao. 2019. Probing neural network comprehension of natural language arguments. 57th Annual Meeting of the Association for Computational Linguistics (ACL) (2019). [25] Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, et al. 2022. Show Your Work: Scratchpads for Intermediate Compu- tation with Language Models. Deep Learning for Code Workshop (2022). [26] Pouya Pezeshkpour, Sarthak Jain, Sameer Singh, and Byron C Wallace. 2021. Combining feature and instance attribution to detect artifacts. arXiv preprint arXiv:2107.00323 (2021). [27] Thang M Pham, Trung Bui, Long Mai, and Anh Nguyen. 2020. Out of Order: How important is the sequential order of words in a sentence in Natural Language Understanding tasks? arXiv preprint arXiv:2012.15180 (2020). [28] Grusha Prasad, Yixin Nie, Mohit Bansal, Robin Jia, Douwe Kiela, and Adina Williams. 2021. To what extent do human explanations of model behavior align with actual model behavior?. In Proceedings of the Fourth BlackboxNLP Workshop on Analyzing and Interpreting Neural Networks for NLP. [29] Fanchao Qi, Yangyi Chen, Xurui Zhang, Mukai Li, Zhiyuan Liu, and Maosong Sun. 2021. Mind the Style of Text! Adversarial and Backdoor Attacks Based on Text Style Transfer. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing (EMNLP). [30] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J Liu. 2020. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. Journal of Machine Learning Research (JMLR) (2020). [31] Ahmad Rashid, Vasileios Lioutas, and Mehdi Rezagholizadeh. 2021. MATE-KD: Masked Adversarial TExt, a Companion to Knowledge Distillation. In Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (ACL). [32] Joshua Robinson, Li Sun, Ke Yu, Kayhan Batmanghelich, Stefanie Jegelka, and Suvrit Sra. 2021. Can contrastive learning avoid shortcut solutions? Advances in Neural Information Processing Systems (NeurIPS) (2021). [33] Michael Saxon, Xinyi Wang, Wenda Xu, and William Yang Wang. 2023. PECO: Examining Single Sentence Label Leakage in Natural Language Inference Datasets through Progressive Evaluation of Cluster Outliers. In Proceedings of the 17th Con- ference of the European Chapter of the Association for Computational Linguistics. 3053–3066. [34] Tal Schuster, Darsh J Shah, Yun Jie Serene Yeo, Daniel Filizzola, Enrico Santus, and Regina Barzilay. 2019. Towards debiasing fact verification models. Empirical Methods in Natural Language Processing (EMNLP) (2019). [35] Priyanka Sen and Amir Saffari. 2020. What do Models Learn from Question An- swering Datasets?. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP). [36] Harshay Shah, Kaustav Tamuly, Aditi Raghunathan, Prateek Jain, and Praneeth Netrapalli. 2020. The pitfalls of simplicity bias in neural networks. Advances in Neural Information Processing Systems (NeurIPS) (2020). [37] Yuge Shi, Jeffrey Seely, Philip HS Torr, N Siddharth, Awni Hannun, Nicolas Usunier, and Gabriel Synnaeve. 2022. Gradient matching for domain generaliza- tion. International Conference on Learning Representations (ICLR) (2022). [38] Chenglei Si, Zhe Gan, Zhengyuan Yang, Shuohang Wang, Jianfeng Wang, Jordan Boyd-Graber, and Lijuan Wang. 2022. Prompting gpt-3 to be reliable. arXiv preprint arXiv:2210.09150 (2022). [39] Chenglei Si, Shuohang Wang, Min-Yen Kan, and Jing Jiang. 2019. What does BERT Learn from Multiple-Choice Reading Comprehension Datasets? arXiv preprint arXiv:1910.12391 (2019). [40] Koustuv Sinha, Robin Jia, Dieuwke Hupkes, Joelle Pineau, Adina Williams, and Douwe Kiela. 2021. Masked language modeling and the distributional hypothesis: Order word matters pre-training for little. Empirical Methods in Natural Language Processing (EMNLP) (2021). [41] Joe Stacey, Yonatan Belinkov, and Marek Rei. 2022. Supervising Model Atten- tion with Human Explanations for Robust Natural Language Inference. AAAI Conference on Artificial Intelligence (AAAI) (2022). [42] Joe Stacey, Pasquale Minervini, Haim Dubossarsky, Sebastian Riedel, and Tim Rocktäschel. 2020. Avoiding the Hypothesis-Only Bias in Natural Language Inference via Ensemble Adversarial Training. Empirical Methods in Natural Language Processing (EMNLP) (2020). [43] Mukund Sundararajan, Ankur Taly, and Qiqi Yan. 2017. Axiomatic Attribution for Deep Networks. International Conference on Machine Learning (ICML) (2017). [44] Ruixiang Tang, Mengnan Du, Ninghao Liu, Fan Yang, and Xia Hu. 2020. An embarrassingly simple approach for trojan attack in deep neural networks. In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining (KDD). Conference’17, July 2017, Washington, DC, USA [45] Damien Teney, Ehsan Abbasnejad, and Anton van den Hengel. 2020. Unshuffling data for improved generalization. arXiv preprint arXiv:2002.11894 (2020). [46] Lifu Tu, Garima Lalwani, Spandana Gella, and He He. 2020. An empirical study on robustness to spurious correlations using pre-trained language models. Transactions of the Association for Computational Linguistics (TACL) (2020). [47] Prasetya Ajie Utama, Nafise Sadat Moosavi, and Iryna Gurevych. 2020. Towards debiasing NLU models from unknown biases. Empirical Methods in Natural Language Processing (EMNLP) (2020). [48] Prasetya Ajie Utama, Nafise Sadat Moosavi, Victor Sanh, and Iryna Gurevych. 2021. Avoiding Inference Heuristics in Few-shot Prompt-based Finetuning. Em- pirical Methods in Natural Language Processing (EMNLP) (2021). [49] Gal Vardi, Gilad Yehudai, and Ohad Shamir. 2022. Gradient Methods Provably Converge to Non-Robust Networks. arXiv preprint arXiv:2202.04347 (2022). [50] Boxin Wang, Chejian Xu, Shuohang Wang, Zhe Gan, Yu Cheng, Jianfeng Gao, Ahmed Hassan Awadallah, and Bo Li. 2021. Adversarial GLUE: A Multi-Task Benchmark for Robustness Evaluation of Language Models. Thirty-fifth Confer- ence on Neural Information Processing Systems Datasets and Benchmarks Track (Round 2) (2021). Mengnan Du, Fengxiang He, Na Zou, Dacheng Tao, and Xia Hu [51] Albert Webson and Ellie Pavlick. 2022. Do Prompt-Based Models Really Under- stand the Meaning of Their Prompts?. In Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies. [52] Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed H Chi, Quoc V Le, Denny Zhou, et al. 2022. Chain-of-Thought Prompting Elicits Rea- soning in Large Language Models. In Advances in Neural Information Processing Systems. [53] Jingfeng Yang, Aditya Gupta, Shyam Upadhyay, Luheng He, Rahul Goel, and Shachi Paul. 2022. TableFormer: Robust Transformer Modeling for Table-Text Encoding. 60th Annual Meeting of the Association for Computational Linguistics (ACL) (2022). [54] Rowan Zellers, Yonatan Bisk, Roy Schwartz, and Yejin Choi. 2018. Swag: A large-scale adversarial dataset for grounded commonsense inference. Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing (EMNLP) (2018). [55] Zihao Zhao, Eric Wallace, Shi Feng, Dan Klein, and Sameer Singh. 2021. Calibrate before use: Improving few-shot performance of language models. In International Conference on Machine Learning. PMLR, 12697–12706.
Title: Can Neural Machine Translation be Improved with User Feedback?: Summary: We present the first real-world application of methods for improving neural machine translation (NMT) with human reinforcement, based on explicit and implicit user feedback collected on the eBay e-commerce platform. Previous work has been confined to simulation experiments, whereas in this paper we work with real logged feedback for offline bandit learning of NMT parameters. We conduct a thorough analysis of the available explicit user judgments---five-star ratings of translation quality---and show that they are not reliable enough to yield significant improvements in bandit learning. In contrast, we successfully utilize implicit task-based feedback collected in a cross-lingual search task to improve task-specific and machine translation quality metrics. # Can Neural Machine Translation be Improved with User Feedback? Julia Kreutzer1∗ and Shahram Khadivi3 and Evgeny Matusov3 and Stefan Riezler1,2 1Computational Linguistics & 2IWR, Heidelberg University, Germany {kreutzer,riezler}@cl.uni-heidelberg.de 3eBay Inc., Aachen, Germany {skhadivi,ematusov}@ebay.com # Abstract Nguyen et al., 2017; Kreutzer et al., 2017; Bah- danau et al., 2017). We present the first real-world applica- tion of methods for improving neural ma- chine translation (NMT) with human rein- forcement, based on explicit and implicit user feedback collected on the eBay e- commerce platform. Previous work has been confined to simulation experiments, whereas in this paper we work with real logged feedback for offline bandit learn- ing of NMT parameters. We conduct a thorough analysis of the available explicit user judgments—five-star ratings of trans- lation quality—and show that they are not reliable enough to yield significant im- In con- provements in bandit learning. trast, we successfully utilize implicit task- based feedback collected in a cross-lingual search task to improve task-specific and machine translation quality metrics. # Introduction In commercial scenarios of neural machine trans- lation (NMT), the one-best translation of a text is shown to multiple users who can reinforce high- quality (or penalize low-quality) translations by explicit feedback (e.g., on a Likert scale) or im- plicit feedback (by clicking on a translated page). In such settings this type of feedback can be easily collected in large amounts. While ban- dit feedback1 in form of user clicks on displayed ads is the standard learning signal for response prediction in online advertising (Bottou et al., 2013), bandit learning for machine translation has so far been restricted to simulation experiments (Sokolov et al., 2016b; Lawrence et al., 2017b; ∗The work for this paper was done while the first author was an intern at eBay. The goal of our work is to show that the gold mine of cheap and abundant real-world human bandit feedback can be exploited successfully for machine learning in NMT. We analyze and utilize human reinforcements that have been collected from users of the eBay e-commerce platform. We show that explicit user judgments in form of five- star ratings are not reliable and do not lead to downstream BLEU improvements in bandit learn- ing. In contrast, we find that implicit task-based feedback that has been gathered in a cross-lingual search task can be used successfully to improve task-specific metrics and BLEU. Another crucial difference of our work to previ- ous research is the fact that we assume a counter- factual learning scenario where human feedback has been given to a historic system different from the target system. Learning is done offline from logged data, which is desirable in commercial set- tings where system updates need to be tested be- fore deployment and the risk of showing inferior translations to users needs to be avoided. Our offline learning algorithms range from a simple bandit-to-supervised conversion (i.e., using trans- lations with good feedback for supervised tuning) to transferring the counterfactual learning tech- niques presented by Lawrence et al. (2017b) from statistical machine translation (SMT) to NMT models. To our surprise, the bandit-to-supervised conversion proved to be very hard to beat, despite theoretical indications of poor generalization for exploration-free learning from logged data (Lang- ford et al., 2008; Strehl et al., 2010). However, we show that we can further improve over this method by computing a task-specific reward scoring func- tion, resulting in significant improvements in both BLEU and in task-specific metrics. 1The fact that only feedback for a single translation is col- lected constitutes the “bandit feedback” scenario where the name is inspired by “one-armed bandit” slot machines. # 2 Related Work Sokolov et al. (2016a,b) introduced learning from bandit feedback for SMT models in an interactive online learning scenario: the MT model receives a source sentence from the user, provides a trans- lation, receives feedback from the user for this translation, and performs a stochastic gradient up- date proportional to the feedback quality. Kreutzer et al. (2017) showed that the objectives proposed for log-linear models can be transferred to neural sequence learning and found that standard control variate techniques do not only reduce variance but also help to produce best BLEU results. Nguyen et al. (2017) proposed a very similar approach us- ing a learned word-based critic in an advantage actor-critic reinforcement learning framework. A comparison of current approaches was recently performed in a shared task where participants had to build translation models that learn from the in- teraction with a service that provided e-commerce product descriptions and feedback for submitted translations (Sokolov et al., 2017). Lawrence et al. (2017b,a) were the first to address the more realis- tic problem of offline learning from logged bandit feedback, with special attention to the problem of exploration-free deterministic logging as is done in commercial MT systems. They show that vari- ance reduction techniques used in counterfactual bandit learning (Dud´ık et al., 2011; Bottou et al., 2013) and off-policy reinforcement learning (Pre- cup et al., 2000; Jiang and Li, 2016) can be used to avoid degenerate behavior of estimators under deterministic logging. # 3 User Feedback # 3.1 Explicit Feedback via Star Ratings One way to collect reinforcement signals from hu- man users of the eBay platform is by explicit rat- ings of product title translations on a five-point Likert scale. More specifically, when users visit product pages with translated titles, they can in- spect the source when hovering with the mouse over the title. Then five stars are shown with the instruction to ‘rate this translation’. A screenshot of an implementation of this rating interface is shown in Figure 1. The original title, the trans- lation and the given star rating are stored. For the experiments in this paper, we focus on translations from English to Spanish. The user star rating data set contains 69,412 rated product titles with 148k Juego Nerd De Computadora Geek Toalla de playa | welleoda - yr sa GAME wae ‘Afadit ala costa Vendedor excelente weleoda 0121 3) v6 4 ated aceleonin Figure 1: Screenshot of the 5-star rating interface for a prod- uct on www.ebay.es translated from English to Spanish. individual ratings. Since 34% of the titles were rated more than once, the ratings for each title are averaged. We observe a tendency towards high rat- ings, in fact one half of the titles are rated with five stars (cf. Appendix C). To investigate the reliability and validity of these ratings, we employed three bilingual anno- tators (‘experts’) to independently re-evaluate and give five-star ratings for a balanced subset of 1,000 product title translations. The annotators were pre- sented the source title and the machine transla- tion, together with instructions on the task pro- vided in Appendix B. The inter-annotator agree- ment between experts is relatively low with Fleiss’ κ = 0.12 (Fleiss, 1971). Furthermore, there is no correlation of the averaged ‘expert’ ratings and the averaged user star ratings (Spearman’s ρ = −0.05). However, when we ask another three an- notators to indicate whether they agree or disagree with a balanced subset of 2,000 user ratings, they agree with 42.3% of the ratings (by majority vot- ing). In this binary meta-judgment task, the inter- annotator agreement between experts is moderate with κ = 0.45. We observe a strong tendency of the expert annotators to agree with high user rat- ings and to disagree with low user ratings. Two examples of user ratings, expert ratings and expert judgment are given in Table 1. In the first example, all raters agree that the translation is good, but in the second example, there is a strong disagreement between users and experts. This analysis shows that it is generally not easy for non-professional users of the e-commerce platform, and even for expert annotators, to give star ratings of translations in the domain of user- generated product titles with high reliability. This problem is related to low validity, i.e., we do not know whether the users’ response actually ex- presses translation quality, since we cannot control the influence of other factors on their judgment, e.g., the displayed image (see Figure 1), the prod- Source Title Title Translation User Rating (avg) Expert Rating (avg) Expert Judgment (majority) Universal 4in1 Dual USB Car Charger Adapter Voltage DC 5V 3.1A Tester For iPhone Coche Cargador Adaptador De Voltaje Probador De Corriente Continua 5V 3.1A para iPhone 4.5625 4.33 Correct BEAN BUSH THREE COLOURS: YELLOW BERGGOLD, PURPLE KING AND GREEN TOP CROP Bean Bush tres colores: Amarillo Berggold, p´urpura y verde Top Crop King 1.0 4.66 Incorrect Table 1: Examples for averaged five-star user ratings, five-star expert ratings and expert judgments on the user ratings. uct itself, or the users’ general satisfaction with the e-commerce transaction, nor can we exclude the possibility that the user judgment is given with an adversarial purpose. Furthermore, we do not have control over the quality of sources2, nor can we discern to which degree a user rating reflects fluency or adequacy of the translation. # 3.2 Task-Based Implicit Feedback terms from the query in their own language. We exploit this assumption in order to measure the quality of a product title translation by requiring a user to click on the translation when it is displayed as a result of the search, and then quantifying the quality of the clicked translation by the extent it matches the query that led the user to the product. For this purpose, we define a word-based match- ing function match(w, q) that evaluates whether a query q contains the word w: Another form of collecting human reinforcement signals via the eBay e-commerce platform is to embed the feedback collection into a cross-lingual information retrieval task. The product title trans- lation system is part of the search interaction of a user with the e-commerce platform in the follow- ing way: When a user enters a query in Spanish, it is first translated to English (query translation), then a search engine retrieves a list of matching products, and their titles are translated to Span- ish and displayed to the user. As soon as the user clicks on one of the translated titles, we store the original query, the translated query, the source product title and its translation. From this col- lection we filter the cases where (a) the original query and the translated query are the same, or (b) more than 90% of the words from the query trans- lation are not contained in the retrieved source ti- tle. In this way, we attempt to reduce the prop- agation of errors in query translation and search. This leaves us with a dataset of 164,065 tuples of Spanish queries, English product titles and their Spanish translations (15% of the original collec- tion). Note that this dataset is more than twice the size of the explicit feedback dataset. An example is given in Table 2. The advantage of embedding feedback collec- tion into a search task is that we can assume that users who formulate a search query have a gen- uine intent of finding products that fit their need, and are also likely to be satisfied with product ti- tle translations that match their query, i.e., contain match(w, q) = 1, if w ∈ q 0, otherwise. (1) Based on this word-level matching, we compute a sequence-level reward for a sentence y of length T as follows: T 1 recall(y,q) = a S- match(y,q). (2) t=1 # 4 Learning from User Feedback Reward Functions. In reinforcement and bandit learning, rewards received from the environment are used as supervision signals for learning. In our experiments, we investigate several options to ob- tain a reward function ∆ : Y → [0, 1] from logged human bandit feedback: 1. Direct User Reward: Explicit feedback, e.g., in the form of star ratings, can directly be used as reward by treating the reward func- tion as a black box. Since human feedback is usually only available for one translation per input, learning from direct user rewards re- quires the use of bandit learning algorithms. In our setup, human bandit feedback has been collected for translations of a historic MT system different from the target system to be optimized. This restricts the learning setup to offline learning from logged bandit feedback. 2Most titles consist of a sequence of keywords rather than a fluent sentence. See Calixto et al. (2017) for a fluency anal- ysis of product titles. 2. Reward Scoring Function: A possibility to use human bandit feedback to obtain rewards for more than a single translation per input is Query Translated Query Title Translated Title Recall candado bicicleta bicycle lock New Bicycle Vibration Code Moped Lock Bike Cycling Security Alarm Sound Lock Nuevo c´odigo de vibraci´on Bicicleta Ciclomotor alarma de seguridad de bloqueo Bicicleta Ciclismo Cerradura De Sonido 0.5 Table 2: Example for query and product title translation. ‘candado’ is translated to ‘lock’ in the query, but then translated back to ‘cerradura’ in the title. The recall metric would prefer a title translation with ‘candado’, as it was specified by the user. to score translations either against a logged reference or a logged query. The first option requires a bandit-to-supervised conversion of data where high-quality logged translations are used as references against which BLEU or other MT quality metrics can be measured. The second option uses logged queries to ob- tain a matching score as in Equation 2. 3. Estimated Reward: Another option to ex- tend bandit feedback to all translations is to learn a parametric model of rewards, e.g., by optimizing a regression objective. The re- ward function is known, but the model pa- rameters need to be trained based on a history of direct user rewards or by evaluations of a reward scoring function. In the following, we present how rewards can be integrated in various objectives for NMT training. NMT from rewards. s RMT) = SOS (FX) AH), 4 s=1 ¥cS(x(s)) where sample probabilities are renormalized over a subset of translation samples S(x) C (x): (9x) = EE eTTCAEe parameter a controls the sharpness of g (see Shen et al. (2016)). The hyper- With sequence-level rewards, all words of a translation of length T are reinforced to the same extent and are treated as if they contributed equally to the translation quality. A word-based reward function, such as the match with a given query (Equation 1), allows the words to have individ- ual weights. The following modification of the sequence-level MRT objective (Equation 4) ac- counts for word-based rewards ∆(yt): Maximum Likelihood Estimation by Bandit- to-Supervised Conversion. Most commonly, NMT models are trained with Maximum Likeli- hood Estimation (MLE, Equation 3) on a given parallel corpus of source and target sequences D = {(x(s), y(s))}S Ss MEQ) = “log poly|x)). —B) s=1 The MLE objective requires reference translations and is agnostic to rewards. However, in a bandit- to-supervised conversion, rewards can be used to filter translations to be used as pseudo-references for MLE training. We apply this scenario to ex- plicit and implicit human feedback data in our ex- periments. T Ss RW MRT (9) =~ s- Il s=1 FES(x(s)) t=1 aa le, Fe) aiw)| . 6 where ∆(yt) in our experiments is a matching score (1). In the following we use the bracketed prefix (W-) to subsume both sentence-level and word-level training objectives. When output spaces are large and reward func- tions sparse, (W-)MRT objectives typically bene- fit from a warm start, i.e., pre-training with MLE. Following Wu et al. (2016), we furthermore adopt a linear combination of MLE and (W-)MRT to sta- bilize learning: R(W-)MIX(θ) = λ · RMLE(θ) + R(W-)MRT(θ). Reinforcement Learning by Minimum Risk Training. When rewards can be obtained for several translations per input instead of only for one as in the bandit setup, by using a reward es- timate or scoring function, Minimum Risk Train- ing (MRT, Equation 4) can be applied to optimize Counterfactual Learning by Deterministic Propensity Matching. Counterfactual learning attempts to improve a target MT system from a log of source sentences, translations produced by a historic MT system, and obtained feed- back L = {(x(h), y(h), ∆(y(h)))}H h=1. For the special case of deterministically logged rewards Lawrence et al. (2017b) introduced the Deter- ministic Propensity Matching (DPM) objective with self-normalization as a multiplicative control variate (Swaminathan and Joachims, 2015):3 H LS A(y) poly!" h=1 RPPM (9 ), © = where translation probabilities are reweighted over the current mini-bath B Cc H,B « H: aa (ay(h)|y(h)) — po(y) x) _ Poly? |x) FE poy ORO" We addi tionally normalize the log probability of a trans- lation y by its length |y|: pj°""(y|x) = (lospolybs) ) . exp # ry] |y| Counterfactual Learning by Doubly Controlled Estimation. Lawrence et al. (2017b) further- more propose the Doubly Controlled objective (DC, Equation 7) implementing the idea of doubly robust estimation (Dud´ık et al., 2011; Jiang and Li, 2016) for deterministic logs. In addition to learn- ing from the historic reward for the logging sys- tem, the reward for other translations is estimated by a parametrized regression model that is trained on the log ˆ∆φ : Y → [0, 1]. This objective con- tains both a multiplicative (probability reweight- ing) and an additive (reward estimate) control vari- ate, hence the name.4 i 7 > [(a0" ~ Aoly! )) » Ag(y) yes(x(")) RCO x Boly x retvix) (7) As for MRT, the expectation over the full output space is approximated with a subset of k sample translations S(x) ⊂ Y(x). Relative Rewards. With the objectives as de- fined above, gradient steps are dependent on the magnitude of the reward for the current training instance. In reinforcement learning, an average reward baseline is commonly subtracted from the current reward with the primary goal to reduce variance (Williams, 1992). As a side effect, the 3Lawrence et al. (2017b) propose reweighting over the whole log, but this is infeasible for NMT. For simplicty we refer to their DPM-R objective as DPM, and DC-R as DC. 4We find empirically that estimating ˆc over the current batch as in objective ˆcDC in (Lawrence et al., 2017b) does not improve over the simple setting with c = 1. current reward is relativized, such that the gra- dient step is not only determined by the magni- tude of the current rewards, but is put into re- lation with previous rewards. We found this ef- fect to be particularly beneficial in experiments with suboptimal reward estimators or noisy re- wards and therefore apply it to all instantiations of the DPM and DC objectives. For DPM, the running average of historic rewards ¯∆h = 1 i=1 ∆(y(i)) is subtracted from the current re- h ward. For DC we apply this to both types of rewards in Equation 7: 1) the logged reward ∆(y(h)), from which we subtract its running aver- age ¯∆h instead of the estimated reward ˆ∆φ(y(h)), and 2) the estimated reward ˆ∆φ(y), from which we hence subtract the average estimated reward ¯ˆ∆h = 1 # 5 Experiments # 5.1 NMT Model In our experiments, learning from feedback starts from a pre-trained English to Spanish NMT that has not seen in-domain data (i.e., model no product title translations). The NMT base- line model (BL) is a standard subword-based encoder-decoder architecture with attention (Bah- danau et al., 2015), implemented with TensorFlow (Abadi et al., 2015). The model is trained with MLE on 2.7M parallel sentences of out-of-domain data until the early stopping point which is de- termined on a small in-domain dev set of 1,619 product title translations. A beam of size 12 and length normalization (Wu et al., 2016) are used for beam search decoding. For significance tests we used approximate randomization (Clark et al., 2011), for BLEU score evaluation (lowercased) the multi-bleu script of the Moses decoder (Koehn et al., 2007), for TER computation the tercom tool (Snover et al., 2006). For MRT, DC and (W- )MIX models we set k = 5, for (W-)MIX mod- els λ = 0.5 and α = 0.05. For all NMT models involving random sampling, we report average re- sults and standard deviation (in subscript) over two runs. Further details about training data and hy- perparameters settings are described in Appendix D. # 5.2 Reward Estimator The model architecture for the reward estimator used in the DC objective is a bilingual extension of the convolutional neural network (CNN) for Source Target 1D Convolution embedding embedding time Max over Fully connected output layer 4 \ | | \ » Cy) Figure 2: Model architecture for the reward estimator. This example has one filter for each filter size (3: purple, 1: green, 2: blue). Source and target sequences are padded up to a maximum length, here Tmax = 8. Data & Model MSE Macro-avg. Distance Micro-Avg. Distance Pearson’s r Spearman’s ρ Star ratings sBLEU 0.1620 0.0096 0.0065 0.0055 0.3203 0.0710 0.1240 0.8816 0.1026 0.8675 Table 3: Results for the reward estimators trained and eval- uated on human star ratings and simulated sBLEU. sentence classification proposed by Kim (2014). Both source and target sequences are padded up to a pre-defined maximum sequence length Tmax, their embeddings are concatenated and further processed by a 1D-Convolution over the time di- mension with several filters of sizes from 2 to 15, which is then followed by a max-over-time pool- ing and fed to a fully-connected output layer (Fig- ure 2). The model is trained to minimize the mean squared error (MSE) on the training portion of the logged feedback data (60k for simulated sentence- BLEU feedback, 62,470 for star rating feedback). The word embeddings of the reward estimator are initialized by the word embeddings of the trained baseline NMT system and fine-tuned further to- gether with the other CNN weights. The best pa- rameters are identified by early-stopping on the validation portion of the feedback data (2,162 for the simulation, 6,942 for the star ratings). Please find a detailed description of the model’s hyperpa- rameters in Appendix D.4. Results for a stand-alone evaluation of the re- ward estimator on the validation portions of the feedback data are given in Table 3. The estima- tor models sBLEU much more accurately than the user star ratings. This is due to large variance and skew of the user ratings. An MSE-trained esti- mator typically predicts values around the mean, which is not a suitable strategy for such a skewed distribution of labels, but is successful for the pre- diction of normal-distributed sBLEU. # 5.3 Explicit Star Rating Feedback Counterfactual Bandit Learning. As shown in Table 4, counterfactual learning with DPM and DC on the logged star ratings as direct reward does not yield improvements over the baseline model in terms of corpus BLEU or TER. A randomization of feedback signals for translations gives the same results (DPM-random), showing that counterfac- tual learning from logged star ratings is equivalent to learning from noise. Evaluating the models in terms of estimated user reward, however, we find an improvement of +1.49 for DC, +0.04 for DPM over the baseline (53.93) (not shown in Table 4)— but these improvements do not transfer to BLEU because the reward model largely over-estimates the translation quality of translations with major faults. Hence it is not desirable to optimize to- wards this signal directly. Bandit-to-Supervised Conversion. In the fol- lowing setup, we utilize the user ratings to filter the log by using only five star rated translations, and perform supervised learning of MLE and MIX using sBLEU against pseudo-references as reward function. Table 4 shows that this filtering strat- egy leads to large improvements over the baseline, for MLE and even more for MIX, even though the data set size is reduced by 42%. However, around the same improvements can be achieved with a random selection of logged translations of the same size (MIX small, containing 55% five- star ratings). Using all logged translations for training MIX achieves the best results. This sug- gests that the model does not profit from the feed- back, but mostly from being exposed to in-domain translations of the logging system. This effect is similar to training on pseudo-references created by back-translation (Sennrich et al., 2016b,a). # 5.4 Task-Based Implicit Feedback Bandit-to-Supervised Conversion. We apply the same filtering technique to the logged implicit feedback by treating translations with recall = 1 as references for training MIX with sBLEU (re- duction of the data set by 62%). The results in Ta- ble 5 show that large improvements over the base- line can be obtained even without filtering, BLEU and TER scores being comparable to the ones ob- served for training on explicit user ratings. Task-based Feedback. The key difference be- tween the implicit feedback collected in the query- Model Test BLEU Test TER BL 28.38 57.58 DPM DPM-random DC 28.19 28.19 28.41±0.85 57.80 57.64 64.25±1.66 MLE (all) MIX (all) MIX (small) MIX (stars = 5) 31.98 34.47±0.06 34.16±0.09 34.35±0.11 51.08 47.97±0.18 48.12±0.33 47.99±0.13 Table 4: Results for models trained on explicit user ratings evaluated on the product titles test set. ‘small’ indicates a random subset of logged translations of the same size as the filtered log that only contains translations with an average rat- ing of five stars (‘stars = 5’). The differences in BLEU are not significant at p ≤ 0.05 between MIX models, but over other models. Model Test BLEU Test TER BL 28.38 57.58 MLE (all) MIX (all) MIX (small) MIX (recall = 1) 31.89 34.39±0.08 34.13±0.26 34.17±0.02 51.35 47.94±0.24 48.27±0.60 47.72±0.26 W-MIX 34.52±0.02 46.91±0.03 Table 5: Results for models trained on implicit task-based feedback data evaluated on the product titles test set. ‘small’ indicates a random subset of logged translations of the same size as the filtered log that only contains translations that con- tain all the query words (‘recall = 1’). The BLEU score of MIX (small) significantly differs from MIX (all) at p ≤ 0.05, the score of MIX (recall = 1) does not. Other differences are significant. title data and the explicit user ratings, is that it can be used to define reward functions like re- call or match (Equations 2, 1). For the exper- iments we train W-MIX, the word-based MRT objective (Equation 5) linearly combined with MLE, on the logged translations accompanying the queries (160k sentences). This combination is essential here, since the model would otherwise learn to produce translations that contain noth- ing but the query words. To account for user- generated language in the queries and subwords in the MT model, we soften the conditions for a match, counting tokens as a match that are part of a word w that is either contained in the query, or has edit distance to a word in the query with dist(w, qi) < max(3, 0.3 × |w|). Table 6 repeats the best MIX results from Table 4 and 5, and evaluates the models with respect to query recall. We also report the query recall for the logged translations and the out-of-domain base- line. These results are compared to W-MIX train- ing on implicit feedback data described in Sec- Logged BL MIX (Tab. 4) MIX (Tab. 5) W-MIX 65.33 45.96 62.92±0.56 63.21±0.24 68.12±0.27 Table 6: Query recall results on the query test set, comparing the logged translations, the baseline and the best MIX mod- els trained on logged translations (MIX (all) from Tables 4 and 5) with the W-MIX model trained via word-based query matching (W-MIX from Table 5). tion 3.2. The development portion of the query- title dataset contains 4,065 sentences, the test set 2,000 sentences, which is used for query recall evaluation. The W-MIX model shows the largest improvement in query recall (12% points) and BLEU (6 points) over the baseline out of all tested learning approaches. It comes very close to the BLEU/TER results of the model trained on in- domain references, but surpasses its recall by far. This is remarkable since the model does not use any human generated references, only logged data of task-based human feedback. Appendix F con- tains a set of examples illustrating what the W- MIX learned. # 6 Conclusion We presented methods to improve NMT from human reinforcement signals. The signals were logged from user activities of an e-commerce plat- form and consist of explicit ratings on a five-point Likert scale and implicit task-based feedback col- lected in a cross-lingual search task. We found that there are no improvements when learning from user star ratings, unless the noisy ratings them- selves are stripped off in a bandit-to-supervised conversion. Implicit task-based feedback can be used successfully as a reward signal for NMT op- timization, leading to improvements both in terms of enforcing individual word translations and in In the terms of automatic evaluation measures. future, we plan transfer these findings to produc- tion settings by performing regular NMT model updates with batches of collected user behavior data, especially focusing on improving translation of ambiguous and rare terms based on rewards from implicit partial feedback. # Acknowledgements The last author was supported in part by DFG Re- search Grant RI 2221/4-1. We would like to thank Pavel Petrushkov for helping with the NMT setup, and the anonymous reviewers for their insightful comments . # References Mart´ın Abadi, Ashish Agarwal, Paul Barham, Eugene Brevdo, Zhifeng Chen, Craig Citro, Greg S. Cor- rado, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Ian Goodfellow, Andrew Harp, Geoffrey Irving, Michael Isard, Yangqing Jia, Rafal Jozefowicz, Lukasz Kaiser, Manjunath Kudlur, Josh Levenberg, Dan Man´e, Rajat Monga, Sherry Moore, Derek Murray, Chris Olah, Mike Schuster, Jonathon Shlens, Benoit Steiner, Ilya Sutskever, Kunal Tal- war, Paul Tucker, Vincent Vanhoucke, Vijay Va- sudevan, Fernanda Vi´egas, Oriol Vinyals, Pete War- den, Martin Wattenberg, Martin Wicke, Yuan Yu, and Xiaoqiang Zheng. 2015. TensorFlow: Large- scale machine learning on heterogeneous systems. https://www.tensorflow.org/. Dzmitry Bahdanau, Philemon Brakel, Kelvin Xu, Anirudh Goyal, Ryan Lowe, Joelle Pineau, Aaron Courville, and Yoshua Bengio. 2017. An actor-critic In 5th Inter- algorithm for sequence prediction. national Conference on Learning Representations. Toulon, France. Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Ben- gio. 2015. Neural machine translation by jointly In Third Interna- learning to align and translate. tional Conference on Learning Representations. San Diego, California. Joaquin Qui˜nonero- Candela, Denis X. Charles, D. Max Chickering, Elon Portugaly, Dipanakar Ray, Patrice Simard, and Ed Snelson. 2013. Counterfactual reasoning and learning systems: The example of computational ad- vertising. Journal of Machine Learning Research 14:3207–3260. Iacer Calixto, Daniel Stein, Evgeny Matusov, Pintu Lo- har, Sheila Castilho, and Andy Way. 2017. Using images to improve machine-translating e-commerce product listings. In Proceedings of the 15th Confer- ence of the European Chapter of the Association for Computational Linguistics. Valencia, Spain. Jonathan H. Clark, Chris Dyer, Alon Lavie, and Noah A. Smith. 2011. Better hypothesis testing for statistical machine translation: Controlling for opti- mizer instability. In Proceedings of the 49th Annual Meeting of the Association for Computational Lin- guistics: Human Language Technologies. Portland, Oregon. Miroslav Dud´ık, John Langford, and Lihong Li. 2011. Doubly robust policy evaluation and learning. In Proceedings of the 28th International Conference on Machine Learning. Bellevue, Washington. Joseph L Fleiss. 1971. Measuring nominal scale agree- ment among many raters. Psychological bulletin 76(5):378. Y Gal and Z Ghahramani. 2016. Dropout as a bayesian approximation: Representing model uncertainty in deep learning. In 33rd International Conference on Machine Learning. New York City, NY. S´ebastien Jean, Kyunghyun Cho, Roland Memisevic, and Yoshua Bengio. 2015. On using very large target vocabulary for neural machine translation. In Proceedings of the 53rd Annual Meeting of the Association for Computational Linguistics and the 7th International Joint Conference on Natural Lan- guage Processing. Beijing, China. Nan Jiang and Lihong Li. 2016. Doubly robust off- policy value evaluation for reinforcement learning. In Proceedings of the 33rd International Conference on Machine Learning (ICML). New York, NY. Yoon Kim. 2014. Convolutional neural networks for sentence classification. In Proceedings of the 2014 Conference on Empirical Methods in Natural Lan- guage Processing. Doha, Qatar. Diederik Kingma and Jimmy Ba. 2014. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980 . Philipp Koehn, Hieu Hoang, Alexandra Birch, Chris Callison-Burch, Marcello Federico, Nicola Bertoldi, Brooke Cowan, Wade Shen, Christine Moran, Richard Zens, et al. 2007. Moses: Open source In Pro- toolkit for statistical machine translation. ceedings of the 45th Annual Meeting of the Asso- ciation for Computational Linguistics: Interactive Poster and Demonstration Sessions. Prague, Czech Republic. Julia Kreutzer, Artem Sokolov, and Stefan Riezler. Bandit structured prediction for neural 2017. In Proceedings of sequence-to-sequence learning. the 55th Annual Meeting of the Association for Com- putational Linguistics. Vancouver, Canada. John Langford, Alexander Strehl, and Jennifer Wort- In Proceed- man. 2008. Exploration scavenging. ings of the 25th International Conference on Ma- chine Learning (ICML). Helsinki, Finland. Carolin Lawrence, Pratik Gajane, and Stefan Riezler. 2017a. Counterfactual learning for machine transla- tion: Degeneracies and solutions. In Proceedings of the NIPS WhatIF Workshop. Long Beach, CA. Carolin Lawrence, Artem Sokolov, and Stefan Riezler. 2017b. Counterfactual learning from bandit feed- back under deterministic logging : A case study in statistical machine translation. In Proceedings of the 2017 Conference on Empirical Methods in Natural Language Processing. Copenhagen, Denmark. Hoa T. Le, Christophe Cerisara, and Alexandre De- nis. 2017. Do convolutional networks need to arXiv preprint be deep for text classification ? arXiv:1707.04108 . Minh-Thang Luong and Christopher D Manning. 2015. Stanford neural machine translation systems for spo- In Proceedings of the In- ken language domains. ternational Workshop on Spoken Language Transla- tion. Da Nang, Vietnam. Khanh Nguyen, Hal Daum´e III, and Jordan Boyd- Graber. 2017. Reinforcement learning for bandit neural machine translation with simulated human feedback. In Proceedings of the 2017 Conference on Empirical Methods in Natural Language Process- ing. Copenhagen, Denmark. Doina Precup, Richard S. Sutton, and Satinder P. Singh. 2000. Eligibility traces for off-policy policy eval- In Proceedings of the Seventeenth Inter- uation. national Conference on Machine Learning (ICML). San Francisco, CA. Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016a. Edinburgh neural machine translation sys- tems for wmt 16. In Proceedings of the First Con- ference on Machine Translation. Berlin, Germany. Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016b. Improving neural machine translation mod- In Proceedings of the els with monolingual data. 54th Annual Meeting of the Association for Compu- tational Linguistics. Berlin, Germany. Rico Sennrich, Barry Haddow, and Alexandra Birch. 2016c. Neural machine translation of rare words with subword units. In Proceedings of the 54th An- nual Meeting of the Association for Computational Linguistics. Berlin, Germany. Shiqi Shen, Yong Cheng, Zhongjun He, Wei He, Hua Wu, Maosong Sun, and Yang Liu. 2016. Minimum risk training for neural machine translation. In Pro- ceedings of the 54th Annual Meeting of the Asso- ciation for Computational Linguistics. Berlin, Ger- many. Matthew Snover, Bonnie Dorr, Richard Schwartz, Lin- nea Micciulla, and John Makhoul. 2006. A study of translation edit rate with targeted human annota- In Proceedings of the 7th Conference of the tion. Association for Machine Translation in the Ameri- cas. Cambridge, Massachusetts. Artem Sokolov, Julia Kreutzer, Christopher Lo, and Stefan Riezler. 2016a. Learning structured predic- tors from bandit feedback for interactive nlp. In Pro- ceedings of the 54th Annual Meeting of the Asso- ciation for Computational Linguistics. Berlin, Ger- many. Artem Sokolov, Julia Kreutzer, Stefan Riezler, and Christopher Lo. 2016b. Stochastic structured pre- In Advances in diction under bandit feedback. Neural Information Processing Systems. Barcelona, Spain. Julia Kreutzer, Kellen Sunder- land, Pavel Danchenko, Witold Szymaniak, Hagen F¨urstenau, and Stefan Riezler. 2017. A shared task on bandit learning for machine translation. In Proceedings of the Second Conference on Machine Translation. Copenhagen, Denmark. Alexander L. Strehl, John Langford, Lihong Li, and Sham M. Kakade. 2010. Learning from logged In Advances in Neural implicit exploration data. Information Processing Sytems (NIPS). Vancouver, Canada. Adith Swaminathan and Thorsten Joachims. 2015. The self-normalized estimator for counterfactual learn- ing. In Advances in Neural Information Processing Systems (NIPS). Montreal, Canada. J¨org Tiedemann. 2009. News from opus-a collection of multilingual parallel corpora with tools and inter- faces. In Recent advances in natural language pro- cessing. volume 5, pages 237–248. Ronald J Williams. 1992. Simple statistical gradient- following algorithms for connectionist reinforce- ment learning. Machine learning 8:229–256. Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. 2016. Google’s neural ma- chine translation system: Bridging the gap between arXiv preprint human and machine translation. arXiv:1609.08144 . # A Appendix Overview Section B provides the instructions that were given to the annotators when judging MT quality. In Section C we provide histograms for simulated and explicit rewards. Section D contains details on the data and NMT model hyperparameters. In Section E we give results for simulation experi- ments on the e-commerce product title domain and a publicly available data set. Finally, we compare translation examples of different models in Sec- tion F. # B Annotation Instructions # B.1 Star Ratings Please rate the translation quality of the segments on the scale from 1 to 5. Focus on whether or not the information contained in the source sentence is correctly and completely translated (ratings 1 - 4). Then, if you are ready to give a 4 based on the criteria below, check whether or not you can assign a 5 instead of the 4, focusing on remain- ing grammatical, morphological and stylistic er- rors. Remember that even a very fluent translation that looks like a human-produced sentence can re- ceive a bad rating if it does not correctly convey all the information that was present in the source. # Assign the following ratings from 1 to 5: 1. Important information is missing and/or dis- torted in the translation, and the error is so se- vere that it may lead to erroneous perception of the described product. Or the translation contains profanities/insulting words. 2. Information from the source is partially present in the translation, but important in- formation is not translated or translated in- correctly. 3. The most important information from the source is translated correctly, but some other less important information is missing or translated incorrectly. 4. All of the information from the source is con- tained in the translation. This should be the only criterion to decide between 1-3 and 4. It is okay for a 4-rated translation to con- tain grammatical errors, disfluencies, or word choice that is not very appropriate to the style of the input text. There might be errors in cas- ing of named entities when it is clear from the context that these are named entities. 5. All of the information from the source is con- tained in the translation and is translated cor- rectly. In contrast to a 4-rated translation, the translation is fluent, easy to read, and contains either no or very minor grammati- cal/morphological/stylistic errors. The brand names and other named entities have the cor- rect upper/lower case. # B.2 Binary Judgment The customers of the eBay e-commerce platform, when presented with a title translation on the prod- uct page, can hover with the mouse over the trans- lation of the title and see the original (source) title in a pop-up window. There, they have the possi- bility to rate the translation with 1 to 5 stars. The goal of this evaluation is to check the rat- ings - you have to mark “Agree” when you agree with the rating and “Disagree” otherwise. The rat- ing (number from 1 to 5) is shown in the Reference line. Note that eBay customers did not have any in- structions on what the rating of 5 stars, 3 stars, or 4 stars means. Thus, the evaluation is subjective on their side. Please apply your common sense when agreeing or disagreeing with human judg- ment. The focus should be on adequacy (correct information transfer) as opposed to fluency. # C Rewards # C.1 Reward Distributions Figure 3 shows the distribution of logged user star ratings, Figure 4 the distribution of sentence BLEU (sBLEU) scores for the simulation experi- ments with logged feedback. The logged transla- tions for the user star ratings were generated by the production system, the logged translations for the simulation were generated by the BL NMT sys- tem. # D Training Details # D.1 Data We conduct experiments on an English-to-Spanish e-commerce item titles translation task. The in- domain data for training with simulated feed- back is composed of in-house eBay data (item titles, descriptions, etc.). The out-of-domain data for training the baselines contains only pub- licly available parallel corpora, that is Europarl, TAUS, and OpenSubtitles released by the OPUS project (Tiedemann, 2009). The out-of-domain 40000 35000 30000 25000 20000 15000 10000 5000 00 02 04 06 08 10 Figure 3: Distribution of user star ratings. The original rat- ings on a five-star scale are averaged per title and rescaled. 00 02 04 06 08 10 Figure 4: Distribution of sentence BLEUs of the product title training set when translated with the out-of-domain baseline for simulation experiments. data has been sub-sampled according to the sim- ilarity to the domain of the product title data, and 25% of the most similar sentence pairs have been selected. The corpus statistics for parallel data are shown in Table 7. Before calculating the corpus statistics, we apply pre-processing including tok- enization and replacement of numbers and product specifications with a placeholder token (e.g., ‘6S’, and ‘1080p’). Table 8 gives an overview of the type and the size of the translations with feedback. # D.2 NMT Model Architecture The NMT has a bi-directional RNN encoder with one layer of 1000 GRUs, a decoder with 1000 GRUs, and source and target word embeddings of size 620. The vocabulary is generated from the out-of-domain training corpus with 40k byte- pair merges (Sennrich et al., 2016c) and contains 40813 source tokens and 41050 target tokens. The full softmax is approximated by 1024 samples as proposed in (Jean et al., 2015). Dropout (Gal and Ghahramani, 2016) is applied with probability p = 0.1 to the embedding matrices, with p = 0.2 to the En Es Train: Sentences Tokens Vocabulary Singletons 2,741,087 17,139,416 327,504 162,834 18,270,753 393,757 190,686 Dev.: Sentences Tokens Vocabulary OOVs 29,063 11,314 2,645 1,619 31,813 11,532 2,493 Test Sentences Tokens Vocabulary OOVs 9,851 6,735 1,966 1000 11,221 6,668 1,902 Table 7: Corpus statistics for the out-of domain training data and in-domain dev and test data. Description Size User star ratings . . . with 5 stars 69,412 40,064 Expert star ratings Expert judgments 1,000 2,000 Query-title pairs . . . with recall = 1 164,065 61,965 Title translations 62,162 Table 8: Data set sizes for collected feedback in number of sentences. The in-domain title translations are only used for simulation experiments. input and recurrent connections of the RNNs. # D.3 NMT Training Hyperparameters The out-of-domain model is trained with mini- batches of size 100 and L2 regularization with weight 1 × 10−7, optimized with Adam (Kingma and Ba, 2014) with initial α = 0.0002, then de- caying α by 0.9 each epoch. The remaining models are trained with constant learning rates and mini-batch size 30, regulariza- tion and dropout stay the same. The settings for the other hyperparameters are listed in Table 9. The estimator loss weight is only relevant for DC, where the pre-trained estimator gets further fine- tuned during DC training. # D.4 Reward Estimation We find that for reward estimation a shallow CNN architecture with wide filters performs superior to a deeper CNN architecture (Le et al., 2017) and also to a recurrent architecture. Hence, we use one convolutional layer with ReLU activation of Model Simulated Feedback MLE MIX EL DPM DPM-random DC 0.002 0.002 2 × 10−6 2 × 10−6 2 × 10−6 0.002 - - - x x - - 0.005 - - - - - 5 - - - 5 - 0.05 - - - - - - - - - 1000 Explicit Star Rating Feedback DPM DPM-random DC MLE (all) MIX (all) MIX (small) MIX (stars=5) 2 × 10−6 2 × 10−6 2 × 10−6 0.002 0.002 0.002 0.002 x x x - - - - - - - - 0.005 0.005 0.005 - - 5 - 5 5 5 - - - - 0.05 0.05 0.05 - - 1000 - - - - Implicit Task-Based Feedback MLE (all) MIX (all) MIX (small) MIX (recall=1) W-MIX 0.002 0.002 0.002 0.002 0.002 - - - - - - 0.005 0.005 0.005 0.005 - 5 5 5 5 - 0.05 0.05 0.05 0.05 - - - - - Adam’s α Length-Normalization MRT α Sample Size k MIX λ Estimator Loss Weight Table 9: Hyperparameter settings for training of the models. nf filters each for filter sizes from 2 to 15, captur- ing both local and more global features. For re- ward estimation on star ratings, nf = 100 and on simulated sBLEU nf = 20 worked best. Dropout with p = 0.5 is applied before the output layer for the simulation setting. We set Tmax = 60. The loss of each item in the batch is weighted by inverse frequency of its feedback in the current batch (counted in 10 buckets) to counterbalance skewed feedback distributions. The model is op- timized with Adam (Kingma and Ba, 2014) (con- stant α = 0.001 for star ratings, α = 0.002 for the simulation) on minibatches of size 30. Note that the differences in hyper-parameters between both settings are the result of tuning and do not cause the difference in quality of the resulting es- timators. We do not evaluate on a separate test set, since their final quality can be measured in how much well they serve as policy evaluators in coun- terfactual learning. (2017); Sokolov et al. (2017). The Expected Loss objective (EL, Equation 8) maximizes5 the expec- tation of a reward over all source and target se- quences, and does in principle not require refer- ences: REL(θ) =Ep(x)pθ(˜y|x) [∆(˜y)] . While we could not apply it to the logged user feedback since it was obtained offline, we can compare to its performance in a simulation setting with simulated rewards instead of human feed- back. It is expected to outperform methods learn- ing with logged feedback due to the exploration during learning. In the following simulation ex- periments, ∆(˜y) is computed by comparing a sampled translation ˜y ∼ pθ(y|x) to a given ref- erence translation y with smoothed sentence-level BLEU (sBLEU). # E.1 E-commerce Product Titles # E Simulated Bandit Feedback Expected Loss. When rewards can be retrieved for sampled translations during learning, the On- line Bandit Structured Prediction framework pro- posed by Sokolov et al. (2016a,b) can be ap- plied for NMT, as demonstrated in Kreutzer et al. We test several of the proposed learning tech- niques with an in-domain parallel corpus (62,162 sentences) of product titles where bandit feedback is simulated by evaluating a sampled translation against a reference using sBLEU. Similar to pre- vious studies on SMT (Lawrence et al., 2017b), 5We use the terms reward or loss interchangeably depend- ing on minimization or maximization contexts. Learning Model Test BLEU Test TER Pre-trained BL 28.38 57.58 Fully Supervised MLE MIX 31.72 34.79±0.02 53.02 48.56±0.02 Online Bandit EL 31.78±0.06 51.11±0.36 Counterfactual DPM DPM-random DC 30.19 28.20 31.11±0.34 56.28 57.89 55.05±0.02 Table 10: Results for simulation experiments evaluated on the product titles test set. Model SMT NMT (beam search) NMT (greedy) EP BL NC BL 25.27 – 27.55 22.35 26.32 19.63 MLE 28.08 32.48 31.04 EL – 28.02 27.93 DPM DC 26.24 26.33 27.54 28.20 26.36 27.39 Table 11: BLEU results for simulation models evaluated on the News Commentary test set (nc-test2007) with beam search and greedy decoding. SMT results are from Lawrence et al. (2017b). this reward is deterministic and does not contain user-dependent noise. Supervised Fine-Tuning. When fine-tuning the baseline model on in-domain references (Luong and Manning, 2015), the model improves 3.34 BLEU (MLE in Table 10) on an in-domain test set (1,000 sentences). By tuning it on the same in-domain data for sBLEU with MIX, it gains an- other 3 BLEU points. Bandit Learning. When feedback is given to only one translation per input (=online bandit feedback), the model (EL) achieves comparable performance to MLE training with references. When the feedback is logged offline for one round of deterministic outputs of the baseline model (=offline bandit feedback), we can still find im- provements of 1.81 BLEU (DPM). With a reward estimator trained on this log, DC achieves even higher improvements of 3 BLEU. To test the con- tribution of the feedback in contrast to a simple in-domain training effect, we randomly perturbed the pairing of feedback signal and translation and retrain (DPM-random). This clearly degrades re- sults, confirming feedback to be a useful signal rather than noise. # E.2 Results on Publicly Available Data Simulation experiments were also run on publicly available data. We use the same data, prepro- cessing and splits as (Lawrence et al., 2017b) to compare with their French-to-English news exper- iments on counterfactual learning with determin- istically logged feedback for statistical machine translation (SMT). The baseline model is trained with MLE on 1.6M Europarl (EP) translations, bandit feedback is then simulated from 40k News Commentary (NC) translations. For the compari- son of full supervision vs. weak feedback, we train in-domain models with MLE on in-domain NC references: training only on in-domain data (NC BL), and fine-tuning the out-of-domain baseline (EP BL) on in-domain data (MLE). The results are given in Table 11. The NMT baselines out- perform the SMT equivalents. With fully super- vised fine-tuning the NMT models improve over the out-of-domain baseline (EP BL) by 5 BLEU points, outperforming also the in-domain base- line (NC BL). Moving to weak feedback, we still find improvements over the baseline by 0.5 BLEU with beam search and 1.6 BLEU with greedy de- coding for online feedback (EL), and 0.6 BLEU with beam search and 1 BLEU with greedy decod- ing for counterfactual learning with DC. However, DPM performs worse than for SMT and those not manage to improve over the out-of-domain base- line. Nevertheless these results confirm that – at least in simulation settings – the DC objective is very suitable for counterfactual learning from ban- dit feedback for NMT, almost reaching the gains of learning from online bandit feedback. # F Examples Table 12 gives an example where W-MIX train- ing improved lexical translation choices. Table 13 lists two examples of W-MIX translations in com- parison to the baseline and logged translations for given queries and product titles to illustrate the specific difficulties of the domain. Title (en) hall linvatec pro2070 powerpro ao drill synthes dhs & dcs attachment / warranty Reference-0 (es) Reference-1 (es) hall linvatec pro2070 powerpro ao taladro synthes dhs & dcs accesorio / garant´ıa hall linvatec pro2070 powerpro synthes , perforaci´on , accesorio de dhs y dcs , todo original , garant´ıa BL (es) hall linvatec pro2070 powerpro ao perforadora synthes dhs & dcs adjuntos / garant´ıa MIX on star-rated titles (es) MIX on query-titles, small (es) MIX on query-titles, all (es) W-MIX hall linvatec pro2070 powerpro ao perforadora synthes dhs & dcs adjuntos / garant´ıa hall linvatec pro2070 powerpro ao perforadora synthes dhs & dcs adjuntos / garant´ıa hall linvatec pro2070 powerpro ao taladro synthes dhs & dcs adjuntos / garant´ıa hall linvatec pro2070 powerpro ao taladro synthes dhs & dcs accesorio / garant´ıa Table 12: Example for product title translation from the test set where W-MIX improved the lexical choice over BL and MIX on in-domain title set and MIX on full query-title set (‘perforadora’ vs ‘taladro’ as translation for ‘drill’, ‘adjuntos’ vs ‘accesorio’ as translation for ‘attachment’). # Title (en) | # Unicorn Thread 12pcs Makeup Brushes Set Gorgeous Colorful Foundation Brush # Query (es) Query (en) unicorn brushes // makeup brushes // brochas de unicornio // brochas unicornio unicorn brushes // makeup brushes # BL (es) Log (es ) galletas de maquillaje de 12pcs Unicorn Rosca 12 un. Conjunto de Pinceles para Maquillaje Hermosa Colorida Base Cepillo # W-MIX # unicornio rosca 12pcs brochas maquillaje conjunto precioso colorido fundaci´on cepillo # Title (en) 12 × Men Women Plastic Shoe Boxes 33*20*12cm Storage Organisers Clear Large Boxes # Query (es) Query (en) _ # cajas plasticas para zapatos plastic shoe boxes 12 × hombres mujeres zapatos de pl´astico cajas de almacenamiento 33*20*12cm organizadores de gran tama˜no 12 × Zapato De Hombre Mujer De Pl´astico Cajas Organizadores de almacenamiento 33*20*12cm cajas Grande Claro 12 × para hombres zapatos de pl´astico cajas de pl´astico 33*20*12cm almacenamiento organizador transparente grandes cajas Table 13: Examples for product title translations of the logged query test set. In the first example, the W-MIX model improves the translation of “brushes”, but also chooses a worse translation for “foundation” (“fundaci´on” vs “base”). In the second example, one of the tricky parts is to translate the sequence of nouns “Men Women Plastic Shoe Boxes” and to disambiguate the relations between them. The BL model translates “shoes of plastic”, the Log has “woman of plastic” and the W-MIX model makes it “shoes of plastic” and “boxes of plastic”. The W-MIX model learns to use “para” from the query, but omits the translation of “women”.
Title: An Actor-Critic Algorithm for Sequence Prediction: Summary: We present an approach to training neural networks to generate sequences using actor-critic methods from reinforcement learning (RL). Current log-likelihood training methods are limited by the discrepancy between their training and testing modes, as models must generate tokens conditioned on their previous guesses rather than the ground-truth tokens. We address this problem by introducing a \textit{critic} network that is trained to predict the value of an output token, given the policy of an \textit{actor} network. This results in a training procedure that is much closer to the test phase, and allows us to directly optimize for a task-specific score such as BLEU. Crucially, since we leverage these techniques in the supervised learning setting rather than the traditional RL setting, we condition the critic network on the ground-truth output. We show that our method leads to improved performance on both a synthetic task, and for German-English machine translation. Our analysis paves the way for such methods to be applied in natural language generation tasks, such as machine translation, caption generation, and dialogue modelling. ICLR 2017 AN ACTOR-CRITIC ALGORITHM FOR SEQUENCE PREDICTION Dzmitry Bahdanau Philemon Brakel Kelvin Xu Anirudh Goyal Universit´e de Montr´eal Ryan Lowe Joelle Pineau∗ McGill University # Aaron Courville† Universit´e de Montr´eal Yoshua Bengio∗ Universit´e de Montr´eal # ABSTRACT We present an approach to training neural networks to generate sequences using actor-critic methods from reinforcement learning (RL). Current log-likelihood training methods are limited by the discrepancy between their training and testing modes, as models must generate tokens conditioned on their previous guesses rather than the ground-truth tokens. We address this problem by introducing a critic network that is trained to predict the value of an output token, given the policy of an actor network. This results in a training procedure that is much closer to the test phase, and allows us to directly optimize for a task-specific score such as BLEU. Crucially, since we leverage these techniques in the supervised learning setting rather than the traditional RL setting, we condition the critic network on the ground-truth output. We show that our method leads to improved performance on both a synthetic task, and for German-English machine translation. Our analysis paves the way for such methods to be applied in natural language generation tasks, such as machine translation, caption generation, and dialogue modelling. # INTRODUCTION In many important applications of machine learning, the task is to develop a system that produces a sequence of discrete tokens given an input. Recent work has shown that recurrent neural networks (RNNs) can deliver excellent performance in many such tasks when trained to predict the next output token given the input and previous tokens. This approach has been applied successfully in machine translation (Sutskever et al., 2014; Bahdanau et al., 2015), caption generation (Kiros et al., 2014; Donahue et al., 2015; Vinyals et al., 2015; Xu et al., 2015; Karpathy & Fei-Fei, 2015), and speech recognition (Chorowski et al., 2015; Chan et al., 2015). The standard way to train RNNs to generate sequences is to maximize the log-likelihood of the “correct” token given a history of the previous “correct” ones, an approach often called teacher forcing. At evaluation time, the output sequence is often produced by an approximate search for the most likely candidate according to the learned distribution. During this search, the model is conditioned on its own guesses, which may be incorrect and thus lead to a compounding of errors (Bengio et al., 2015). This can become especially problematic for longer sequences. Due to this discrepancy between training and testing conditions, it has been shown that maximum likelihood training can be suboptimal (Bengio et al., 2015; Ranzato et al., 2015). In these works, the authors argue that the network should be trained to continue generating correctly given the outputs already produced by the model, rather than the ground-truth reference outputs from the data. This gives rise to the challenging problem of determining the target for the next network output. Bengio et al. (2015) use the token k from the ground-truth answer as the target for the network at step k, whereas Ranzato et al. (2015) rely on the REINFORCE algorithm (Williams, 1992) to decide whether or not the tokens # ∗CIFAR Senior Fellow †CIFAR Fellow 1 Published as a conference paper at ICLR 2017 from a sampled prediction lead to a high task-specific score, such as BLEU (Papineni et al., 2002) or ROUGE (Lin & Hovy, 2003). In this work, we propose and study an alternative procedure for training sequence prediction networks that aims to directly improve their test time metrics (which are typically not the log-likelihood). In particular, we train an additional network called the critic to output the value of each token, which we define as the expected task-specific score that the network will receive if it outputs the token and continues to sample outputs according to its probability distribution. Furthermore, we show how the predicted values can be used to train the main sequence prediction network, which we refer to as the actor. The theoretical foundation of our method is that, under the assumption that the critic computes exact values, the expression that we use to train the actor is an unbiased estimate of the gradient of the expected task-specific score. Our approach draws inspiration and borrows the terminology from the field of reinforcement learning (RL) (Sutton & Barto, 1998), in particular from the actor-critic approach (Sutton, 1984; Sutton et al., 1999; Barto et al., 1983). RL studies the problem of acting efficiently based only on weak supervision in the form of a reward given for some of the agent’s actions. In our case, the reward is analogous to the task-specific score associated with a prediction. However, the tasks we consider are those of supervised learning, and we make use of this crucial difference by allowing the critic to use the ground-truth answer as an input. In other words, the critic has access to a sequence of expert actions that are known to lead to high (or even optimal) returns. To train the critic, we adapt the temporal difference methods from the RL literature (Sutton, 1988) to our setup. While RL methods with non-linear function approximators are not new (Tesauro, 1994; Miller et al., 1995), they have recently surged in popularity, giving rise to the field of ‘deep RL’ (Mnih et al., 2015). We show that some of the techniques recently developed in deep RL, such as having a target network, may also be beneficial for sequence prediction. The contributions of the paper can be summarized as follows: 1) we describe how RL methodology like the actor-critic approach can be applied to supervised learning problems with structured outputs; and 2) we investigate the performance and behavior of the new method on both a synthetic task and a real-world task of machine translation, demonstrating the improvements over maximum-likelihood and REINFORCE brought by the actor-critic training. # 2 BACKGROUND We consider the problem of learning to produce an output sequence Y = (y1, . . . , yT ), yt ∈ A given an input X, where A is the alphabet of output tokens. We will often use notation Yf ...l to refer to subsequences of the form (yf , . . . , yl). Two sets of input-output pairs (X, Y ) are assumed to be available for both training and testing. The trained predictor h is evaluated by computing the average task-specific score R( ˆY , Y ) on the test set, where ˆY = h(X) is the prediction. To simplify the formulas we always use T to denote the length of an output sequence, ignoring the fact that the output sequences may have different length. Recurrent neural networks A recurrent neural network (RNN) produces a sequence of state vectors (s1, . . . , sT ) given a sequence of input vectors (e1, . . . , eT ) by starting from an initial s0 state and applying T times the transition function f : st = f (st−1, et). Popular choices for the mapping f are the Long Short-Term Memory (Hochreiter & Schmidhuber, 1997) and the Gated Recurrent Units (Cho et al., 2014), the latter of which we use for our models. To build a probabilistic model for sequence generation with an RNN, one adds a stochastic output layer g (typically a softmax for discrete outputs) that generates outputs yt ∈ A and can feed these outputs back by replacing them with their embedding e(yt): yt ∼ g(st−1) st = f (st−1, e(yt)). (1) (2) Thus, the RNN defines a probability distribution p(yt|y1, . . . , yt−1) of the next output token yt given the previous tokens (y1, . . . , yt−1). Upon adding a special end-of-sequence token ∅ to the alphabet A, the RNN can define the distribution p(Y ) over all possible sequences as p(Y ) = p(y1)p(y2|y1) . . . p(yT |y1, . . . , yT −1)p(∅|y1, . . . , yT ). 2 Published as a conference paper at ICLR 2017 RNNs for sequence prediction To use RNNs for sequence prediction, they must be augmented to generate Y conditioned on an input X. The simplest way to do this is to start with an initial state s0 = s0(X) (Sutskever et al., 2014; Cho et al., 2014). Alternatively, one can encode X as a variable-length sequence of vectors (h1, . . . , hL) and condition the RNN on this sequence using an attention mechanism. In our models, the sequence of vectors is produced by either a bidirectional RNN (Schuster & Paliwal, 1997) or a convolutional encoder (Rush et al., 2015). We use a soft attention mechanism (Bahdanau et al., 2015) that computes a weighted sum of a sequence of vectors. The attention weights determine the relative importance of each vector. More formally, we consider the following equations for RNNs with attention: yt ∼ g(st−1, ct−1) st = f (st−1, ct−1, e(yt)) αt = β(st, (h1, . . . , hL)) ye ~ 9(St—1, Ce-1) ® 8. = f (St-1, Ce-1, e(M)) ® 4 = (se, (ha, ---, hx) ° L a= > Oey, hy © j=l where β is the attention mechanism that produces the attention weights αt and ct is the context vector, or ‘glimpse’, for time step t. The attention weights are computed by an MLP that takes as input the current RNN state and each individual vector to focus on. The weights are typically (as in our work) constrained to be positive and sum to 1 by using the softmax function. A conditioned RNN can be trained for sequence prediction by gradient ascent on the log-likelihood log p(Y |X) for the input-output pairs (X, Y ) from the training set. To produce a prediction ˆY for a test input sequence X, an approximate beam search for the maximum of p(·|X) is usually conducted. During this search the probabilities p(·|ˆy1, . . . , ˆyt−1) are considered, where the previous tokens ˆy1, . . . , ˆyt−1 comprise a candidate beginning of the prediction ˆY . Value functions We view the conditioned RNN as a stochastic policy that generates actions and receives the task score (e.g., BLEU score) as the return. We furthermore consider the case when the return R is partially received at the intermediate steps in the form of rewards r;: RY, Y)= a re(Ges Yt; Y). This is more general than the case of receiving the full return at the end of the sequence, as we can simply define all rewards other than ry to be zero. Receiving intermediate rewards may ease the learning for the critic, and we use reward shaping as explained in Section] Given the policy, possible actions and reward function, the value represents the expected future return as a function of the current state of the system, which in our case is uniquely defined by the sequence of actions taken so far, Yi. We define the value of an unfinished prediction ‘it as follows: T VM XY) =| E Ye re (Gei Vie ¥)- Verret X) Sy We define the value of a candidate next token a for an unfinished prediction ˆY1...t−1 as the expected future return after generating token a: T Q(a;¥1..1-1, X,Y) = E (neren) + > rie Ficetien.n¥)) : Yeqi..r~p(.[¥1...t-14,X) ott We will refer to the candidate next tokens as actions. For notational simplicity, we henceforth drop X and Y from the signature of p, V , Q, R and rt, assuming it is clear from the context which of X and Y is meant. We will also use V without arguments for the expected reward of a random prediction. 3 (3) (4) (5) Published as a conference paper at ICLR 2017 Algorithm 1 Actor-Critic Training for Sequence Prediction Require: A critic ˆQ(a; ˆY1...t, Y ) and an actor p(a| ˆY1...t, X) with weights φ and θ respectively. 1: Initialize delayed actor p 2: while Not Converged do 3: 4: 5: and target critic Q’ with same weights: 6’ = 6, 6’ = ¢. Receive a random example (X, Y ). Generate a sequence of actions ˆY from p Compute targets for the critic . ge = Tees Via, Y) + > P (al¥4..1 X)Q" (a V4.4, Y) acA Update the critic weights φ using the gradient i 2 dé (= (QG: Y1-1,Y) — at) + rots) t=1 2 where C;, = > (Quen _ a Wel Fie) b a 7: Update actor weights θ using the following gradient estimate ee ey ee uaF wa) t=1aeA T dp(ye|M1...4-1, X) + LL > 70 t=1 8: Update delayed actor and target critic, with constants yg < 1, yy « 1 OY = 700+ (1—70)0', & = b+ (1-46)¢' # 9: end while Algorithm 2 Complete Actor-Critic Algorithm for Sequence Prediction 1: Initialize critic ˆQ(a; ˆY1...t, Y ) and actor p(a| ˆY1...t, X) with random weights φ and θ respectively. 2: Pre-train the actor to predict yt+1 given Y1...t by maximizing log p(yt+1|Y1...t, X). 3: Pre-train the critic to estimate Q by running Algorithm 1 with fixed actor. 4: Run Algorithm 1. 4 Published as a conference paper at ICLR 2017 # 3 ACTOR-CRITIC FOR SEQUENCE PREDICTION Let θ be the parameters of the conditioned RNN, which we will also refer to as the actor. Our training algorithm is based on the following way of rewriting the gradient of the expected return dV dθ : d dp( Yn A v. Sp cae) Pal) O(a: ¥ 4). ©) do Punthix) & 144 This equality is known in RL under the names policy gradient theorem (Sutton et al., 1999) and stochastic actor-critic (Sutton, 1984). 1 Note that we use the probability rather than the log probability in this formula (which is more typical in RL applications) as we are summing over actions rather than taking an expectation. Intuitively, this equality corresponds to increasing the probability of actions that give high values, and decreasing the probability of actions that give low values. Since this gradient expression is an expectation, it is trivial to build an unbiased estimate for it: an yey Maia) alt. = Qa: Yi 11) (8) k=1t=1acA where ˆY k are M random samples from p( ˆY ). By replacing Q with a parameteric estimate ˆQ one can obtain a biased estimate with relatively low variance. The parameteric estimate ˆQ is called the critic. The above formula is similar in spirit to the REINFORCE learning rule that Ranzato et al. (2015) use in the same context: av f Hee r(GtlVt -1) a 7 > dn EYE 1) — b(X)],, ) # a where the scalar b,(X) is called baseline or control variate. The difference is that in REINFORCE the inner sum over all actions is replaced by its 1-sample estimate, namely Peer VO (g,; Y1...t-1), where the log probability aloe rtie|---) Ce apie.) is intro- duced to correct for the sampling of y,. Furthermore, instead of the value Q(; Y1...4-1), REIN- FORCE uses the cumulative reward ean Tr(Gr3 Yi..7-1) following the action yj, which again can be seen as a 1-sample estimate of Q. Due to these simplifications and the potential high variance in the cumulative reward, the REINFORCE gradient estimator has very high variance. In order to improve upon it, we consider the actor-critic estimate from Equation[8| which has a lower variance at the cost of significant bias, since the critic is not perfect and trained simultaneously with the actor. The success depends on our ability to control the bias by designing the critic network and using an appropriate training criterion for it. To implement the critic, we propose to use a separate RNN parameterized by φ. The critic RNN is run in parallel with the actor, consumes the tokens ˆyt that the actor outputs and produces the estimates ˆQ(a; ˆY1...t) for all a ∈ A. A key difference between the critic and the actor is that the correct answer Y is given to the critic as an input, similarly to how the actor is conditioned on X. Indeed, the return R( ˆY , Y ) is a deterministic function of Y , and we argue that using Y to compute ˆQ should be of great help. We can do this because the values are only required during training and we do not use the critic at test time. We also experimented with providing the actor states st as additional inputs to the critic. See Figure 1 for a visual representation of our actor-critic architecture. Temporal-difference learning A crucial component of our approach is policy evaluation, that is the training of the critic to produce useful estimates of Q. With a naive Monte-Carlo method, one could use the future return yw 7 (Gri Yi.r-1) as a target to OG: Yi.t-1)s and use the critic parameters @ to minimize the square error between these two values. However, like with REINFORCE, using such a target yields to very high variance which quickly grows with the number of steps T. We use a temporal difference (TD) method for policy evaluation (Sutton) /T988). Namely, we use the right-hand side gq, = 1i(§; Yi..t—1) + ae P(AIM1...4)Q(4;M%...1) of the Bellman acA equation as the target for the left-hand Q( i; Y1...4-1). 1We also provide a simple self-contained proof of Equation (7) in Supplementary Material. 5 Published as a conference paper at ICLR 2017 Actor Critic Q pe Q1,Q2,-°: ,Qr ° Decoder "SCS s«éDeecoder SG, Yas Or im actor states @1,%2,°°° XL Y1,Y2,°°* YT Figure 1: Both the actor and the critic are encoder-decoder networks. The actor receives an input sequence X and produces samples ˆY which are evaluated by the critic. The critic takes in the ground-truth sequence Y as input to the encoder, and takes the input summary (calculated using an attention mechanism) and the actor’s prediction ˆyt as input at time step t of the decoder. The values Q1, Q2, · · · , QT computed by the critic are used to approximate the gradient of the expected returns with respect to the parameters of the actor. This gradient is used to train the actor to optimize these expected task specific returns (e.g., BLEU score). The critic may also receive the hidden state activations of the actor as input. Applying deep RL techniques It has been shown in the RL literature that if Q is non-linear (like in our case), the TD policy evaluation might diverge (Tsitsiklis & Van Roy} |1997). Previous work has shown that this problem can be alleviated by using an additional target network Q’ to compute 4, Which is updated less often and/or more slowly than Q. Similarly to (Lillicrap et al.||2015), we update the parameters ¢’ of the target critic by linearly interpolating them with the parameters of the trained one. Attempts to remove the target network by propagating the gradient through q resulted in a lower square error (Q(g1; Yi...r) - a). but the resulting Q values proved very unreliable as training signals for the actor. The fact that both actor and critic use outputs of each other for training creates a potentially dangerous feedback loop. To address this, we sample predictions from a delayed actor (Lillicrap et al., 2015), whose weights are slowly updated to follow the actor that is actually trained. Dealing with large action spaces One of the challenges of our work is that the action space is very large (as is typically the case in NLP tasks with large vocabularies). This can be alleviated by putting constraints on the critic values for actions that are rarely sampled. We found experimentally that shrinking the values of these rare actions is necessary for the algorithm to converge. Specifically, we add a term Ct for every step t to the critic’s optimization objective which drives all value predictions of the critic closer to their mean: 2 2 a= (a Yaa) — a Yo0¥i 0) (10) b a This corresponds to penalizing the variance of the outputs of the critic. Without this penalty the values of rare actions can be severely overestimated, which biases the gradient estimates and can cause divergence. A similar trick was used in the context of learning simple algorithms with Q-learning (Zaremba et al., 2015). Reward shaping While we are ultimately interested in the maximization of the score of a complete prediction, simply awarding this score at the last step provides a very sparse training signal for the critic. For this reason we use potential-based reward shaping with potentials Φ( ˆY1...t) = R( ˆY1...t) for incomplete sequences and Φ( ˆY ) = 0 for complete ones (Ng et al., 1999). Namely, for a predicted sequence ˆY we compute score values for all prefixes to obtain the sequence of scores (R( ˆY1...1), R( ˆY1...2), . . . , R( ˆY1...T )). The difference between the consecutive pairs of scores is then used as the reward at each step: rt(ˆyt; ˆY1...t−1) = R( ˆY1...t) − R( ˆY1...t−1). Using the shaped reward rt instead of awarding the whole score R at the last step does not change the optimal policy (Ng et al., 1999). Putting it all together Algorithm 1 describes the proposed method in detail. We consider adding the weighted log-likelihood gradient to the actor’s gradient estimate. This is in line with the prior work 6 Published as a conference paper at ICLR 2017 by (Ranzato et al., 2015) and (Shen et al., 2015). It is also motivated by our preliminary experiments that showed that using the actor-critic estimate alone can lead to an early determinization of the policy and vanishing gradients (also discussed in Section 6). Starting training with a randomly initialized actor and critic would be problematic, because neither the actor nor the critic would provide adequate training signals for one another. The actor would sample completely random predictions that receive very little reward, thus providing a very weak training signal for the critic. A random critic would be similarly useless for training the actor. Motivated by these considerations, we pre-train the actor using standard log-likelihood training. Furthermore, we pre-train the critic by feeding it samples from the pre-trained actor, while the actor’s parameters are frozen. The complete training procedure including pre-training is described by Algorithm 2. # 4 RELATED WORK In other recent RL-inspired work on sequence prediction, Ranzato et al. (2015) trained a translation model by gradually transitioning from maximum likelihood learning into optimizing BLEU or ROUGE scores using the REINFORCE algorithm. However, REINFORCE is known to have very high variance and does not exploit the availability of the ground-truth like the critic network does. The approach also relies on a curriculum learning scheme. Standard value-based RL algorithms like SARSA and OLPOMDP have also been applied to structured prediction (Maes et al., 2009). Again, these systems do not use the ground-truth for value prediction. Imitation learning has also been applied to structured prediction (Vlachos, 2012). Methods of this type include the SEARN (Daum´e Iii et al., 2009) and DAGGER (Ross et al., 2010) algorithms. These methods rely on an expert policy to provide action sequences that the policy learns to imitate. Unfortunately, it’s not always easy or even possible to construct an expert policy for a task-specific score. In our approach, the critic plays a role that is similar to the expert policy, but is learned without requiring prior knowledge about the task-specific score. The recently proposed ‘scheduled sampling’ (Bengio et al., 2015) can also be seen as imitation learning. In this method, ground-truth tokens are occasionally replaced by samples from the model itself during training. A limitation is that the token k for the ground-truth answer is used as the target at step k, which might not always be the optimal strategy. There are also approaches that aim to approximate the gradient of the expected score. One such approach is ‘Direct Loss Minimization’ (Hazan et al., 2010) in which the inference procedure is adapted to take both the model likelihood and task-specific score into account. Another popular approach is to replace the domain over which the task score expectation is defined with a small subset of it, as is done in Minimum (Bayes) Risk Training (Goel & Byrne, 2000; Shen et al., 2015; Och, 2003). This small subset is typically an n-best list or a sample (like in REINFORCE) that may or may not include the ground-truth as well. None of these methods provide intermediate targets for the actor during training, and Shen et al. (2015) report that as many as 100 samples were required for the best results. Another recently proposed method is to optimize a global sequence cost with respect to the selection and pruning behavior of the beam search procedure itself (Wiseman & Rush, 2016). This method follows the more general strategy called ‘learning as search optimization’ (Daum´e III & Marcu, 2005). This is an interesting alternative to our approach; however, it is designed specifically for the precise inference procedure involved. # 5 EXPERIMENTS To validate our approach, we performed two sets of experiments 2. First, we trained the proposed model to recover strings of natural text from their corrupted versions. Specifically, we consider each character in a natural language corpus and with some probability replace it with a random character. We call this synthetic task spelling correction. A desirable property of this synthetic task is that data is essentially infinite and overfitting is no concern. Our second series of experiments is done on the task of automatic machine translation using different models and datasets. 2 The source code is available at https://github.com/rizar/actor-critic-public 7 Published as a conference paper at ICLR 2017 In addition to maximum likelihood and actor-critic training we implemented two versions of the REINFORCE gradient estimator. In the first version, we use a linear baseline network that takes the actor states as input, exactly as in (Ranzato et al., 2015). We also propose a novel extension of REINFORCE that leverages the extra information available in the ground-truth output Y . Specifically, we use the ˆQ estimates produced by the critic network as the baseline for the REINFORCE algorithm. The motivation behind this approach is that using the ground-truth output should produce a better baseline that lowers the variance of REINFORCE, resulting in higher task-specific scores. We refer to this method as REINFORCE-critic. 5.1 SPELLING CORRECTION We use text from the One Billion Word dataset for the spelling correction task (Chelba et al., 2013), which has pre-defined training and testing sets. The training data was abundant, and we never used any example twice. We evaluate trained models on a section of the test data that comprises 6075 sentences. To speed up experiments, we clipped all sentences to the first 10 or 30 characters. For the spelling correction actor network, we use an RNN with 100 Gated Recurrent Units (GRU) and a bidirectional GRU network for the encoder. We use the same attention mechanism as proposed in (Bahdanau et al., 2015), which effectively makes our actor network a smaller version of the model used in that work. For the critic network, we employed a model with the same architecture as the actor. We use character error rate (CER) to measure performance on the spelling task, which we define as the ratio between the total of Levenshtein distances between predictions and ground-truth outputs and the total length of the ground-truth outputs. This is a corpus-level metric for which a lower value is better. We use it as the return by negating per-sentence ratios. At the evaluation time greedy search is used to extract predictions from the model. We use the ADAM optimizer (Kingma & Ba, 2015) to train all the networks with the parame- ters recommended in the original paper, with the exception of the scale parameter α. The latter is first set to 10−3 and then annealed to 10−4 for log-likelihood training. For the pre-training stage of the actor-critic, we use α = 10−3 and decrease it to 10−4 for the joint actor-critic train- ing. We pretrain the actor until its score on the development set stops improving. We pretrain the critic until its TD error stabilizes3. We used M = 1 sample for both actor-critic and REIN- FORCE. For exact hyperparameter settings we refer the reader to Appendix A. We start REINFORCE training from a pretrained actor, but we do not use the curriculum learning employed in MIXER. The critic is trained in the same way for both REINFORCE and actor- critic, including the pretraining stage. We re- port results obtained with the reward shaping de- scribed in Section 3, as we found that it slightly improves REINFORCE performance. Table 1 presents our results on the spelling cor- rection task. We observe an improvement in CER over log-likelihood training for all four settings considered. Without simultaneous log- likelihood training, actor-critic training results in a better CER than REINFORCE-critic in three 40 — Lt valid — Ut yalid~ 3 a valtd . — RFC valid -- LL train sok 1 . Ss" LE trains => AC train 15} Epochs == RF train =-- RF-C valid BLEU 25 20 Figure 2: Progress of log-likelihood (LL), RE- INFORCE (RF) and actor-critic (AC) training in terms of BLEU score on the training (train) and val- idation (valid) datasets. LL* stands for the anneal- ing phase of log-likelihood training. The curves start from the epoch of log-likelihood pretraining from which the parameters were initialized. 3A typical behaviour for TD error was to grow at first and then start decreasing slowly. We found that stopping pretraining shortly after TD error stops growing leads to good results. 8 Published as a conference paper at ICLR 2017 Table 1: Character error rate of different methods on the spelling correction task. In the table L is the length of input strings, η is the probability of replacing a character with a random one. LL stands for the log-likelihood training, AC and RF-C and for the actor-critic and the REINFORCE-critic respectively, AC+LL and RF-C+LL for the combinations of AC and RF-C with LL. Character Error Rate AC LL 17.24 17.81 17.31 18.4 35.89 38.12 37.0 40.87 L = 10, η = 0.3 L = 30, η = 0.3 L = 10, η = 0.5 L = 30, η = 0.5 RF-C AC+LL RF-C+LL 17.82 18.16 35.84 37.6 16.65 17.1 34.6 36.36 16.97 17.47 35 36.6 Table 2: Our IWSLT 2014 machine translation results with a convolutional encoder compared to the previous work by Ranzato et al. Please see 1 for an explanation of abbreviations. The asterisk identifies results from (Ranzato et al., 2015). The numbers reported with ≤ were approximately read from Figure 6 of (Ranzato et al., 2015) Decoding method greedy search beam search LL* MIXER* 17.74 ≤ 20.3 20.73 ≤ 21.9 RF 20.92 21.35 RF-C 22.24 22.58 AC 21.66 22.45 out of four settings. In the fourth case, actor-critic and REINFORCE-critic have similar performance. Adding the log-likelihood gradient with a cofficient λLL = 0.1 helps both of the methods, but actor-critic still retains a margin of improvement over REINFORCE-critic. 5.2 MACHINE TRANSLATION For our first translation experiment, we use data from the German-English machine translation track of the IWSLT 2014 evaluation campaign (Cettolo et al., 2014), as used in Ranzato et al. (2015), and closely follow the pre-processing described in that work. The training data comprises about 153,000 German-English sentence pairs. In addition we considered a larger WMT14 English-French dataset Cho et al. (2014) with more than 12 million examples. For further information about the data we refer the reader to Appendix B. The return is defined as a smoothed and rescaled version of the BLEU score. Specifically, we start all n-gram counts from 1 instead of 0, and multiply the resulting score by the length of the ground-truth translation. Smoothing is a common practice when sentence-level BLEU score is considered, and it has been used to apply REINFORCE in similar settings (Ranzato et al., 2015). IWSLT 2014 with a convolutional encoder In our first experiment we use a convolutional encoder in the actor to make our results more comparable with Ranzato et al. (2015). For the same reason, we use 256 hidden units in the networks. For the critic, we replaced the convolutional network with a bidirectional GRU network. For training this model we mostly used the same hyperparameter values as in the spelling correction experiments, with a few differences highlighted in Appendix A. For decoding we used greedy search and beam search with a beam size of 10. We found that penalizing candidate sentences that are too short was required to obtain the best results. Similarly to (Hannun et al., 2014), we subtracted ρT from the negative log-likelihood of each candidate sentence, where T is the candidate’s length, and ρ is a hyperparameter tuned on the validation set. The results are summarized in Table 2. We report a significant improvement of 2.3 BLEU points over the log-likelihood baseline when greedy search is used for decoding. Surprisingly, the best performing method is REINFORCE with critic, with an additional 0.6 BLEU point advantage over the actor-critic. When beam-search is used, the ranking of the compared approaches is the same, but the margin between the proposed methods and log-likelihood training becomes smaller. The final performances of the actor-critic and the REINFORCE-critic with greedy search are also 0.7 and 1.3 BLEU points respectively better than what Ranzato et al. (2015) report for their MIXER approach. This comparison should be treated with caution, because our log-likelihood baseline is 1.6 BLEU 9 Published as a conference paper at ICLR 2017 Table 3: Our IWSLT 2014 machine translation results with a bidirectional recurrent encoder compared to the previous work. Please see Table 1 for an explanation of abbreviations. The asterisk identifies results from (Wiseman & Rush, 2016). # Model greedy search beam search LL* 22.53 23.87 BSO* 23.83 25.48 LL 25.82 27.56 RF-C RF-C+LL 27.42 27.75 27.7 28.3 AC 27.27 27.75 AC+LL 27.49 28.53 Table 4: Our WMT 14 machine translation results compared to the previous work. Please see Table 1 for an explanation of abbreviations. The apostrophy and the asterisk identify results from (Bahdanau et al., 2015) and (Shen et al., 2015) respectively. Decoding method greedy search beam search LL’ n/a 28.45 LL* MRT * n/a 29.88 n/a 31.3 Model LL 29.33 30.71 AC+LL RF-C+LL 30.85 31.13 29.83 30.37 points stronger than its equivalent from (Ranzato et al., 2015). The performance of REINFORCE with a simple baseline matches the score reported for MIXER in Ranzato et al. (2015). To better understand the IWSLT 2014 results we provide the learning curves for the considered approaches in Figure 2. We can clearly see that the training methods that use generated predictions have a strong regularization effect — that is, better progress on the validation set in exchange for slower or negative progress on the training set. The effect is stronger for both REINFORCE varieties, especially for the one without a critic. The actor-critic training does a much better job of fitting the training set than REINFORCE and is the only method except log-likelihood that shows a clear overfitting, which is a healthy behaviour for such a small dataset. In addition, we performed an ablation study. We found that using a target network was crucial; while the joint actor-critic training was still progressing with γθ = 0.1, with γθ = 1.0 it did not work at all. Similarly important was the value penalty described in Equation (10). We found that good values of the λ coefficient were in the range [10−3, 10−6]. Other techniques, such as reward shaping and a delayed actor, brought moderate performance gains. We refer the reader to Appendix A for more details. IWSLT 2014 with a bidirectional GRU encoder In order to compare our results with those reported by Wiseman & Rush (2016) we repeated our IWSLT 2014 investigation with a different encoder, a bidirectional RNN with 256 GRU units. In this round of experiments we also tried to used combined training objectives in the same way as in our spelling correction experiments. The results are summarized in Table 3. One can see that the actor-critic training, especially its AC+LL version, yields significant improvements (1.7 with greedy search and 1.0 with beam search) upon the pure log-likelihood training, which are comparable to those brought by Beam Search Optimization (BSO), even though our log-likelihood baseline is much stronger. In this round of experiments actor-critic and REINFORCE-critic performed on par. WMT 14 Finally we report our results on a very popular large WMT14 English-French dataset (Cho et al., 2014) in Table 4. Our model closely follows the achitecture from (Bahdanau et al., 2015), however we achieved a higher baseline performance by annealing the learning rate α and penalizing output sequences that were too short during beam search. The actor-critic training brings a significant 1.5 BLEU improvement with greedy search and a noticeable 0.4 BLEU improvement with beam search. In previous work Shen et al. (2015) report a higher improvement of 1.4 BLEU with beam search, however they use 100 samples for each training example, whereas we use just one. We note that in this experiment, which is perhaps the most realistic settings, the actor-critic enjoys a significant advantage over the REINFORCE-critic. 10 Published as a conference paper at ICLR 2017 # 6 DISCUSSION We proposed an actor-critic approach to sequence prediction. Our method takes the task objective into account during training and uses the ground-truth output to aid the critic in its prediction of intermediate targets for the actor. We showed that our method leads to significant improvements over maximum likelihood training on both a synthetic task and a machine translation benchmark. Compared to REINFORCE training on machine translation, actor-critic fits the training data much faster, although in some of our experiments we were able to significantly reduce the gap in the training speed and achieve a better test error using our critic network as the baseline for REINFORCE. One interesting observation we made from the machine translation results is that the training methods that use generated predictions have a strong regularization effect. Our understanding is that condi- tioning on the sampled outputs effectively increases the diversity of training data. This phenomenon makes it harder to judge whether the actor-critic training meets our expectations, because a noisier gradient estimate yielded a better test set performance. We argue that the spelling correction results obtained on a virtually infinite dataset in conjuction with better machine translation performance on the large WMT 14 dataset provide convincing evidence that the actor-training can be effective. In future work we will consider larger machine translation datasets. We ran into several optimization issues. The critic would sometimes assign very high values to actions with a very low probability according to the actor. We were able to resolve this by penalizing the critic’s variance. Additionally, the actor would sometimes have trouble to adapt to the demands of the critic. We noticed that the action distribution tends to saturate and become deterministic, causing the gradient to vanish. We found that combining an RL training objective with log-likelihood can help, but in general we think this issue deserves further investigation. For example, one can look for suitable training criteria that have a well-behaved gradient even when the policy has little or no stochasticity. In a concurrent work Wu et al. (2016) show that a version of REINFORCE with the baseline computed using multiple samples can improve performance of a very strong machine translation system. This result, and our REINFORCE-critic experiments, suggest that often the variance of REINFORCE can be reduced enough to make its application practical. That said, we would like to emphasize that this paper attacks the problem of gradient estimation from a very different angle as it aims for low-variance but potentially high-bias estimates. The idea of using the ground-truth output that we proposed is an absolutely necessary first step in this direction. Future work could focus on further reducing the bias of the actor-critic estimate, for example, by using a multi-sample training criterion for the critic. # ACKNOWLEDGMENTS We thank the developers of Theano (Theano Development Team, 2016) and Blocks (van Merri¨enboer et al., 2015) for their great work. We thank NSERC, Compute Canada, Calcul Queb´ec, Canada Research Chairs, CIFAR, CHISTERA project M2CR (PCIN-2015-226) and Samsung Institute of Advanced Techonology for their financial support. # REFERENCES Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio. Neural machine translation by jointly learning to align and translate. In Proceedings of the ICLR 2015, 2015. Andrew G Barto, Richard S Sutton, and Charles W Anderson. Neuronlike adaptive elements that can solve difficult learning control problems. Systems, Man and Cybernetics, IEEE Transactions on, (5):834–846, 1983. Samy Bengio, Oriol Vinyals, Navdeep Jaitly, and Noam Shazeer. Scheduled sampling for sequence prediction with recurrent neural networks. arXiv preprint arXiv:1506.03099, 2015. Mauro Cettolo, Jan Niehues, Sebastian St¨uker, Luisa Bentivogli, and Marcello Federico. Report on the 11th iwslt evaluation campaign. In Proc. of IWSLT, 2014. William Chan, Navdeep Jaitly, Quoc V Le, and Oriol Vinyals. Listen, attend and spell. arXiv preprint arXiv:1508.01211, 2015. 11 Published as a conference paper at ICLR 2017 Ciprian Chelba, Tomas Mikolov, Mike Schuster, Qi Ge, Thorsten Brants, Phillipp Koehn, and Tony Robinson. One billion word benchmark for measuring progress in statistical language modeling. arXiv preprint arXiv:1312.3005, 2013. Kyunghyun Cho, Bart Van Merri¨enboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning phrase representations using rnn encoder-decoder for statistical machine translation. arXiv preprint arXiv:1406.1078, 2014. Jan Chorowski, Dzmitry Bahdanau, Dmitriy Serdyuk, KyungHyun Cho, and Yoshua Bengio. Attention-based models for speech recognition. CoRR, abs/1506.07503, 2015. URL http: //arxiv.org/abs/1506.07503. Hal Daum´e III and Daniel Marcu. Learning as search optimization: Approximate large margin methods for structured prediction. In Proceedings of the 22nd international conference on Machine learning, pp. 169–176. ACM, 2005. Hal Daum´e Iii, John Langford, and Daniel Marcu. Search-based structured prediction. Machine learning, 75(3):297–325, 2009. Jeffrey Donahue, Lisa Anne Hendricks, Sergio Guadarrama, Marcus Rohrbach, Subhashini Venu- gopalan, Kate Saenko, and Trevor Darrell. Long-term recurrent convolutional networks for visual recognition and description. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 2625–2634, 2015. Vaibhava Goel and William J Byrne. Minimum bayes-risk automatic speech recognition. Computer Speech & Language, 14(2):115–135, 2000. Awni Y Hannun, Andrew L Maas, Daniel Jurafsky, and Andrew Y Ng. First-pass large vocabulary continuous speech recognition using bi-directional recurrent dnns. arXiv preprint arXiv:1408.2873, 2014. Tamir Hazan, Joseph Keshet, and David A McAllester. Direct loss minimization for structured prediction. In Advances in Neural Information Processing Systems, pp. 1594–1602, 2010. Sepp Hochreiter and J¨urgen Schmidhuber. Long short-term memory. Neural computation, 9(8): 1735–1780, 1997. Andrej Karpathy and Li Fei-Fei. Deep visual-semantic alignments for generating image descriptions. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 3128– 3137, 2015. Diederik P Kingma and Jimmy Ba. A method for stochastic optimization. In International Conference on Learning Representation, 2015. Ryan Kiros, Ruslan Salakhutdinov, and Richard S Zemel. Unifying visual-semantic embeddings with multimodal neural language models. arXiv preprint arXiv:1411.2539, 2014. Timothy P Lillicrap, Jonathan J Hunt, Alexander Pritzel, Nicolas Heess, Tom Erez, Yuval Tassa, David Silver, and Daan Wierstra. Continuous control with deep reinforcement learning. arXiv preprint arXiv:1509.02971, 2015. Chin-Yew Lin and Eduard Hovy. Automatic evaluation of summaries using n-gram co-occurrence statistics. In Proceedings of the 2003 Conference of the North American Chapter of the Association for Computational Linguistics on Human Language Technology-Volume 1, pp. 71–78. Association for Computational Linguistics, 2003. Francis Maes, Ludovic Denoyer, and Patrick Gallinari. Structured prediction with reinforcement learning. Machine learning, 77(2-3):271–301, 2009. W Thomas Miller, Paul J Werbos, and Richard S Sutton. Neural networks for control. MIT press, 1995. Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A Rusu, Joel Veness, Marc G Bellemare, Alex Graves, Martin Riedmiller, Andreas K Fidjeland, Georg Ostrovski, et al. Human-level control through deep reinforcement learning. Nature, 518(7540):529–533, 2015. 12 Published as a conference paper at ICLR 2017 Andrew Y Ng, Daishi Harada, and Stuart Russell. Policy invariance under reward transformations: Theory and application to reward shaping. In ICML, volume 99, pp. 278–287, 1999. Franz Josef Och. Minimum error rate training in statistical machine translation. In Proceedings of the 41st Annual Meeting on Association for Computational Linguistics-Volume 1, pp. 160–167. Association for Computational Linguistics, 2003. Kishore Papineni, Salim Roukos, Todd Ward, and Wei-Jing Zhu. Bleu: a method for automatic evaluation of machine translation. In Proceedings of the 40th annual meeting on association for computational linguistics, pp. 311–318. Association for Computational Linguistics, 2002. Marc’Aurelio Ranzato, Sumit Chopra, Michael Auli, and Wojciech Zaremba. Sequence level training with recurrent neural networks. arXiv preprint arXiv:1511.06732, 2015. St´ephane Ross, Geoffrey J Gordon, and J Andrew Bagnell. A reduction of imitation learning and structured prediction to no-regret online learning. arXiv preprint arXiv:1011.0686, 2010. Alexander M Rush, Sumit Chopra, and Jason Weston. A neural attention model for abstractive sentence summarization. arXiv preprint arXiv:1509.00685, 2015. Mike Schuster and Kuldip K Paliwal. Bidirectional recurrent neural networks. Signal Processing, IEEE Transactions on, 45(11):2673–2681, 1997. Shiqi Shen, Yong Cheng, Zhongjun He, Wei He, Hua Wu, Maosong Sun, and Yang Liu. Minimum risk training for neural machine translation. arXiv preprint arXiv:1512.02433, 2015. Ilya Sutskever, Oriol Vinyals, and Quoc V. Le. Sequence to sequence learning with neural networks. In Advances in Neural Information Processing Systems 27: Annual Conference on Neural Information Processing Systems 2014, December 8-13 2014, Montreal, Quebec, Canada, pp. 3104–3112, 2014. Richard S Sutton. Learning to predict by the methods of temporal differences. Machine learning, 3 (1):9–44, 1988. Richard S Sutton and Andrew G Barto. Introduction to reinforcement learning, volume 135. MIT Press Cambridge, 1998. Richard S Sutton, David A McAllester, Satinder P Singh, Yishay Mansour, et al. Policy gradient methods for reinforcement learning with function approximation. In NIPS, volume 99, pp. 1057– 1063, 1999. Richard Stuart Sutton. Temporal credit assignment in reinforcement learning. 1984. Gerald Tesauro. Td-gammon, a self-teaching backgammon program, achieves master-level play. Neural computation, 6(2):215–219, 1994. Theano Development Team. Theano: A Python framework for fast computation of mathematical expressions. arXiv e-prints, abs/1605.02688, May 2016. URL http://arxiv.org/abs/ 1605.02688. John N Tsitsiklis and Benjamin Van Roy. An analysis of temporal-difference learning with function approximation. Automatic Control, IEEE Transactions on, 42(5):674–690, 1997. Bart van Merri¨enboer, Dzmitry Bahdanau, Vincent Dumoulin, Dmitriy Serdyuk, David Warde- Farley, Jan Chorowski, and Yoshua Bengio. Blocks and fuel: Frameworks for deep learning. arXiv:1506.00619 [cs, stat], June 2015. Oriol Vinyals, Alexander Toshev, Samy Bengio, and Dumitru Erhan. Show and tell: A neural image caption generator. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 3156–3164, 2015. Andreas Vlachos. An investigation of imitation learning algorithms for structured prediction. In EWRL, pp. 143–154. Citeseer, 2012. Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3-4):229–256, 1992. 13 Published as a conference paper at ICLR 2017 Sam Wiseman and Alexander M Rush. Sequence-to-sequence learning as beam-search optimization. arXiv preprint arXiv:1606.02960, 2016. Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, et al. Google’s neural machine translation sys- tem: Bridging the gap between human and machine translation. arXiv preprint arXiv:1609.08144, 2016. Kelvin Xu, Jimmy Ba, Ryan Kiros, Kyunghyun Cho, Aaron C. Courville, Ruslan Salakhutdinov, Richard S. Zemel, and Yoshua Bengio. Show, attend and tell: Neural image caption generation with visual attention. In Proceedings of the 32nd International Conference on Machine Learning, ICML 2015, Lille, France, 6-11 July 2015, pp. 2048–2057, 2015. Wojciech Zaremba, Tomas Mikolov, Armand Joulin, and Rob Fergus. Learning simple algorithms from examples. arXiv preprint arXiv:1511.07275, 2015. 14 Published as a conference paper at ICLR 2017 Table 5: Results of an ablation study. We tried varying the actor update speed γθ, the critic update speed γφ, the value penalty coefficient λ, whether or not reward shaping is used, whether or not temporal difference (TD) learning is used for the critic. Reported are the best training and validation BLEU score obtained in the course of the first 10 training epochs. Some of the validation scores would still improve with longer training. Greedy search was used for decoding. 0.001 0.001 10−3 baseline yes yes 33.73 23.16 with different γφ 0.001 0.001 0.001 0.01 0.1 1 10−3 10−3 10−3 yes yes yes yes yes yes 33.52 32.63 9.59 23.03 22.80 8.14 with different γθ 1 0.001 10−3 yes yes 32.9 22.88 without reward shaping 0.001 0.001 10−3 no yes 32.74 22.61 without temporal difference learning 0.001 0.001 10−3 yes no 23.2 16.36 with different λ 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.001 0.001 3 ∗ 10−3 10−4 10−6 10−8 0 yes yes yes yes yes yes yes yes yes yes 32.4 34.10 35.00 33.6 27.41 22.48 23.15 23.10 22.72 20.55 # A HYPERPARAMETERS For machine translation experiments the variance penalty coefficient λ was set to 10−4, and the delay coefficients γθ and γφ were both set to 10−4. For REINFORCE with the critic we did not use a delayed actor, i.e. γθ was set to 1. For the spelling correction task we used the same γθ and γφ but a different λ = 10−3. When we used a combined training criterion, the weight of the log-likelihood gradient λLL was always 0.1. All initial weights were sampled from a centered uniform distribution with width 0.1. In some of our experiments we provided the actor states as additional inputs to the critic. Specifically, we did so in our spelling correction experiments and in our WMT 14 machine translation study. All the other results were obtained without this technique. For decoding with beam search we substracted the length of a candidate times ρ from the log- likelihood cost. The exact value of ρ was selected on the validation set and was equal to 0.8 for models trained by log-likelihood and REINFORCE and to 1.0 for models trained by actor-critic and REINFORCE-critic. For some of the hyperparameters we performed an ablation study. The results are reported in Table 5. # B DATA For the IWSLT 2014 data the sizes of validation and tests set were 6,969 and 6,750, respectively. We limited the number of words in the English and German vocabularies to the 22,822 and 32,009 most frequent words, respectively, and replaced all other words with a special token. The maximum sentence length in our dataset was 50. For WMT14 we used vocabularies of 30,000 words for both English and French, and the maximum sentence length was also 50. 15 Published as a conference paper at ICLR 2017 # C GENERATED Q-VALUES In Table C we provide an example of value predictions that the critic outputs for candidate next words. One can see that the critic has indeed learnt to assign larger values for the appropriate next words. While the critic does not always produce sensible estimates and can often predict a high return for irrelevant rare words, this is greatly reduced using the variance penalty term from Equation (10). Figure 3: The best 3 words according to the critic at intermediate steps of generating a translation. The numbers in parentheses are the value predictions ˆQ. The German original is “¨uber eine davon will ich hier erz¨ahlen .” The reference translation is “and there’s one I want to talk about”. Words with largest ˆQ and(6.623) there(6.200) but(5.967) that(6.197) one(5.668) &apos;s(5.467) that(5.408) one(5.118) i(5.002) that(4.796) i(4.629) ,(4.139) want(5.008) i(4.160) &apos;t(3.361) to(4.729) want(3.497) going(3.396) talk(3.717) you(2.407) to(2.133) about(1.209) that(0.989) talk(0.924) about(0.706) .(0.660) right(0.653) .(0.498) ?(0.291) –(0.285) .(0.195) there(0.175) know(0.087) .(0.168) ∅ (-0.093) ?(-0.173) 16 Published as a conference paper at ICLR 2017 # D PROOF OF EQUATION (7) ave d , W = yey, RY) = ar [p(1)P(Gal) -.-PGr|ti ---Gr—1)| RW) = STP pn) POD (5 oh JRO) = de t=1 y oS T HAY 1..t- ~ De PF e-1) PO y(Figacr iF) ros Fie) = 14. Your T=1 dp(Gr\¥1.t-1) 4-1) (Yj SY wv yy eee lye T rie; Y1..t-1) + Ss P(Yia1.71M1...t) Ss r+ (Gr3Vi.r-1) Yi Tv r=t4+1 SS E > PAM) OG: % 44) = fay V1. 1-1 ~P(¥s...2-1) 2A do E yy lel) wl) Q(a Y1..1-1) Yrp(¥) t=1aeA # T t=1 17
Title: HTLM: Hyper-Text Pre-Training and Prompting of Language Models: Summary: We introduce HTLM, a hyper-text language model trained on a large-scale web crawl. Modeling hyper-text has a number of advantages: (1) it is easily gathered at scale, (2) it provides rich document-level and end-task-adjacent supervision (e.g. class and id attributes often encode document category information), and (3) it allows for new structured prompting that follows the established semantics of HTML (e.g. to do zero-shot summarization by infilling title tags for a webpage that contains the input text). We show that pretraining with a BART-style denoising loss directly on simplified HTML provides highly effective transfer for a wide range of end tasks and supervision levels. HTLM matches or exceeds the performance of comparably sized text-only LMs for zero-shot prompting and fine-tuning for classification benchmarks, while also setting new state-of-the-art performance levels for zero-shot summarization. We also find that hyper-text prompts provide more value to HTLM, in terms of data efficiency, than plain text prompts do for existing LMs, and that HTLM is highly effective at auto-prompting itself, by simply generating the most likely hyper-text formatting for any available training data. We will release all code and models to support future HTLM research. # HTLM: Hyper-Text Pre-Training and Prompting of Language Models Armen Aghajanyan1, ∗ Dmytro Okhonko1, ∗ Mike Lewis1, Mandar Joshi1,2, Hu Xu1, Gargi Ghosh1, Luke Zettlemoyer1,2 1Facebook AI # {armenag,oxo,mikelewis,mandarj,huxu,gghosh,lsz}@fb.com # Abstract We introduce HTLM, a hyper-text language trained on a large-scale web crawl. model Modeling hyper-text has a number of advan- tages: (1) it is easily gathered at scale, (2) it provides rich document-level and end-task- adjacent supervision (e.g. class and id at- tributes often encode document category infor- mation), and (3) it allows for new structured prompting that follows the established seman- tics of HTML (e.g. to do zero-shot summariza- tion by infilling <title> tags for a webpage that contains the input text). We show that pretraining with a BART-style denoising loss directly on simplified HTML provides highly effective transfer for a wide range of end tasks and supervision levels. HTLM matches or exceeds the performance of comparably sized text-only LMs for zero-shot prompting and fine-tuning for classification benchmarks, while also setting new state-of-the-art perfor- mance levels for zero-shot summarization. We also find that hyper-text prompts provide more value to HTLM, in terms of data efficiency, than plain text prompts do for existing LMs, and that HTLM is highly effective at auto- prompting itself, by simply generating the most likely hyper-text formatting for any avail- able training data. We will release all code and models to support future HTLM research. # 1 Introduction The vast majority of text used to pretrain lan- guage models is extracted from web pages, while discarding any markup they contain (Liu et al., 2019; Brown et al., 2020; Raffel et al., 2019; Lewis et al., 2019). We argue that this HTML should not be ignored; it enables new forms of highly effective language model pretraining and <!DOCTYPE html> <html> <title> <mask>12 </title> <body> ˜ south korea on monday announced sweeping tax reforms , including income and corporate tax cuts to boost growth by stimulating sluggish private consumption and business investment . </body> </html> <!DOCTYPE html> <html> <title> <mask>12 </title> <body> ˜ south korea on monday announced sweeping tax reforms , including income and corporate tax cuts to boost growth by stimulating sluggish private consumption and business investment . </body> </html> ↓ <!DOCTYPE html> <html> <title> ˜ South Korea Announces Tax Reforms To Boost Economic Growth ˜ </title> <body> ˜ south korea on monday announced sweeping tax reforms... </body> </html> <!DOCTYPE html> <html> <title> ~ South Korea Announces Tax Reforms To Boost Economic Growth ~ </title> <body> ˜ south korea on monday announced sweeping tax reforms... </body> </html> Figure 1: An example structured prompt for a simple summarization task, where we ask a generative masked language model to generate a mask representing the ti- tle with an average tokens size of 12. prompting with structured document-level super- vision. Hyper-text, such as the HTML found in the Common Crawl1, has a number of advantages for pretraining over plain text. It often encodes high- level properties of different parts of the documents, which are difficult to infer from the text alone. For example, <title> elements can be excellent summaries of the <body> of a document, while element class and id attributes can encode cate- gorical properties of documents. Such supervision is highly diverse, depending on what the website authors choose to present, and provides close prox- ies for many NLP tasks we aim to later solve. Modeling hyper-text allows us to introduce structured prompting of language models. We de- sign prompts that incorporate the established se- mantics of HTML to better control for the de- sired model output. This includes, for exam- # ∗ Equal Contribution # 1https://commoncrawl.org/ ple, performing zero-shot summarization by ask- ing the model to infill <title> tags in a web page. And, the fact that we jointly model text and hyper-text formatting also allows for effective auto-prompting. If we have even a few examples for a new task, we can directly ask the model to format them in HTML, and templatize the result to define the new prompt. Our HyperText Language Model (HTLM) is trained on 23TB of simplified HTML which we automatically extract from common crawl dumps (see Section §2.1). We use a modified BART denoising objective (Lewis et al., 2019) that ran- domly masks spans of hyper-text and aims to re- construct the original input. We extend the origi- nal masking with a new size hint scheme, where each mask is associated with an integer that pro- vides a noisy hint for the size of the masked text, to allow for more fine grained task-specific length priors when prompting the final model (see Sec- tion §2.3). Figure 1 shows an example mask that should be reconstructed with a phrase that contains roughly 12 tokens. Through extensive experiments, we show that our HTLM achieves highly effective transfer for a wide range of end tasks and supervision levels. It matches or exceeds the performance of compa- rably sized text-only LMs for zero-shot prompt- ing and full fine-tuning on GLUE, while also set- ting new state-of-the-art performance levels for zero-shot summarization with a gain of up to 8 ROUGE-1 points. It also allows few shot learning for problems that are less easily reduced to text- only inputs, such table to text generation. Follow- ing methodology introduced by Le Scao and Rush (2021), we further find that hyper-text prompts provide more data efficiency to the HTLM model than plain text prompts do for existing LMs, being effectively equivalent to having up to a thousand extra training examples. Finally, we see that the HTLM model is highly effective at auto-prompting itself, in some cases rivaling the performance of manually engineered prompts. In summary, our contributions include: language model (HTLM), trained on 23TB of simplified HTML data from the common crawl. • Our new hyper-text prompting scheme uses both the well-established semantics of HTML and new size hints on prompt masks to provide more fine-grained control of new task specifications. • We demonstrate consistently strong transfer from HTLM to a range of tasks at differing supervision levels, including improving the best-known zero-shot summarization num- bers by up to 8 ROUGE-1 points. • Following Le Scao and Rush (2021), our data efficiency analysis shows that hyper-text prompts are worth more to the HTLM model than plain text prompts are for existing LMs, being effectively equivalent to having up to a thousand extra training examples. • We demonstrate the HTLM directly supports auto prompting for new tasks, by simply ask- ing it to format any available examples in HTML, often rivaling or surpassing previous manually engineered prompts. • We release all code and models to support fu- ture HTLM research. # 2 HyperText Language Model (HTLM) HTLM is trained on a large corpus of simplified HTML, which is automatically extracted from the common crawl (Section §2.1). We use a BART- style denoising autoencoder with span masking (Section §2.2), extended to allow size hints during reconstruction of the original text (Section §2.3). # 2.1 Minimal HTML Although HTML contains supervision signals to natural language, the majority of HTML in a mod- ern web page does not provide any significant form of supervision for pretraining. For example, a large portion of a webpage is JavaScript code or CSS, which provides more aesthetics to the page rather than document-level information. Coupling this with the challenges of training transformers on very long sequence lengths (Choromanski et al., 2020; Wang et al., 2020; Beltagy et al., 2020), it was important to automatically convert web pages to a simplified form, which we call Minimal- HTML (MHTML), as defined below. We remove all sub-trees of the HTML DOM2 which do not contain textual elements of a certain character size (128 for standard textual elements, 2The DOM or Document Object Model is an interface that treats an HTML document as a tree structure wherein each node is an object representing a part of the document. 64 for lists/tables/spans). We also filter out all headers, footers, copyrights, forms, and iFrames. We fold consecutive <div> elements into a sin- gular <div> element with merged attributes. We also remove all attributes which are not class or id attributes. Lastly, we skip all MHTML docu- ments whose ratio of text to HTML is not greater than 0.46. Particularly we noticed that MHTML documents whose ratio of text to HTML is low, the average quality of the document tends to be lower as well. We found these numbers by visually in- specting a set of Common Crawl (CC) documents after application of aforementioned transforms en- suring both a high quality of kept documents while also not filtering too large amount of data. Further- more we filter out all documents who have a lang attribute that is not set to en. Applying these deterministic transformations removes on average 94% of characters from a raw webpage while maintaining the general markup of the document. Furthermore, it allowed close to 85% of MHTML documents to fit into 1024 BPE tokens; the maximum token length for BART and many other existing language models. One by-product of this type of filtering is that it also produced high-quality documents by de- fault3; thus, we opted out of model-based filter- ing of documents such as CC-100 (Conneau et al., 2019). We used the January 2021 snapshot of Common Crawl, which provided us with 23 Ter- abytes of MHTML text after filtering. # 2.2 Model We auto- encoder (Lewis et al., 2019) for several reasons. We want to predict arbitrary substrings within the MHTML, conditioned on the rest of the document. This allows us to equally easily (1) use masks during prompting to mark where to generate text associated with model outputs within a web page, and (2) automatically generate prompts training examples in by wrapping plain text masks that allow the model to mark them up by generating MHTML formatting. We also do not know in advance exactly how much text needs to be generated in each case, thereby ruling out the use of more traditional masked language models. 3Much of the noise in existing text collections derived from the common crawl comes from artifacts that are intro- duced when returning the text in the relatively arbitrary or- der it appeared in the original HTML, before the markup was stripped. For all of our experiments, we adopt the same ar- chitecture as BART-Large and initialized our mod- els with the BART-Large checkpoint. This model has roughly 400 million parameters. We trained our augmented BART model for a to- tal of 330,000 steps on 256 GPUs with an effective batch size of 8192. We initialize our model with the original BART-Large model. We train using the Adam optimizer (Kingma and Ba, 2014) and a polynomial decay learning rate scheduler with a peak learning rate of 4e−5 and 10, 000 warm-up steps. We do not use the sentence shuffling from the original BART objective, and select a Poisson λ of 3.5 for sampling span lengths for masking. We set dropout in the attention to 0.1 for the first 170k steps, reducing it to 0.0 thereafter. We also filter out data to only English (en) after 170k steps us- ing FastText (Joulin et al., 2016). We noticed the perplexity plateaued around 170k steps which is why we simplify the learning process by remov- ing dropout and applying stronger filtering of the English language. # 2.3 Size Hints BART allows each mask to be replaced with mul- tiple tokens during the reconstruction. During pre- training, BART masks a span with the length sam- pled from a Poisson distribution; thus, the model must learn to implicitly predict the length of the masked text. A fundamental problem we encoun- tered when trying to use standard BART for zero- shot generative prompting is the inability to con- trol the length of the generated text for each mask, even when using various decoding strategies like length penalties. To allow for more control, we augment BART’s masking scheme by introducing size hints. Specif- ically, we tokenize the noisy estimate of the length of a span directly and insert it right after the span mask token. For example, given the correct mask length m, we insert n hmaski tokens where n is max (1, ⌊N (m, m ∗ ǫ)⌋) and ǫ is a hyperparam- eter representing how noisy we want these size hints to be. By optionally injecting size hints, we can prompt the model to generate text of roughly some specific length, or by not injecting size hints, we allow the model to model the mask size implic- itly. We give size-hints to 80% of masks with the noisiness of size hints ǫ = 0.1. We provide an example of the benefits of size hints in generation in Table 1. # 3 HTML-based Prompting We use the HTML-based prompting scheme for a range of generation and classification tasks. Broadly, we use HTML templates–either selected manually or generated by the model itself by auto- prompting–to specify the HTML structure of the task. The template is then instantiated with the task input and placeholder mask tokens for the out- put. The model uses this instantiated template as a prompt. Because BART models reconstruct the full input, we rely on simple heuristics to match the prefix/suffix around any masks and extract the final output. # 3.1 Generation Prompting Policies Given that we have optional size hints for masks, a single prompt can generate a wide variety of text; therefore, we discuss multiple policies to select the prompted results. We can decide not to utilize size hints at all and thus remove the need to use any policies, but this comes at the cost of template ro- bustness. Without size hints, a template not only has to express the semantics of the task, but also needs to match the average target length as well; such prompts are brittle and require careful man- ual design. However, using hints allows us to de- couple generation length from the prompt, greatly improving template reuse across related tasks. It is also possible that for a prompt and a specific sub- set of the data, HTLM will not generate an output from which we can programmatically extract the generated mask; therefore, our policies for size- hints also mitigate this issue. For every generation task, we first construct a prompt that can generate the correct text semanti- cally, and then we provide size hints equal to the average target of a subset of the training set, ¯s. If, for a particular input, we are not able to extract a value, we run HTLM on the same prompt, but with our size hint set to ¯s ± iǫ¯s, from which we se- lect the output with the lowest perplexity, we con- tinue this process at most five times where i rep- resents the current index of the policy. If we still cannot find a valid generated answer, we fall back on the auto-template described in the next section. In experiments, we denote HTLM-Manual-NS (not sized) as our manually engineered prompt with no size hint, while HTLM-Manual-S uses the policy defined here for all generation benchmarks. # 3.2 Auto-Prompting To avoid manually engineering prompts, we also explore automatic generation of structured prompts. By training on hypertext, HTLM can learn high-level document semantics that we ex- ploit for prompt creation. We generate prompting templates by asking the model to recover docu- ment markups. Specifically, we place hmaski to- kens around every independent block of data (e.g. summary/article). We provide an example of auto-prompting for a sample from the Gigaword summarization dataset (Napoles et al., 2012) with the respective masking in Figure 2 . For our generation exper- iments, we denote HTLM-Auto-NS (not-sized) as the auto-prompt without using size hints, where HTLM-Auto-S uses the size hints based policy de- scribed in the previous section. We found that HTLM auto-prompting was less effective for classification tasks. We hypothesize that this is because generative targets carry signif- icantly more information than a simple binary tar- get token. # 4 Zero/One-Shot Prompting Perez et al. (2021) argue that zero/few-shot learn- ing cannot happen when prompts are created by tuning on a large amount of development data. To mitigate for this issue all the manual prompts used throughout our experiments are either de- rived from related papers or developed using a maximum of fifty samples from the train set. # 4.1 Generation We evaluate HTLM on summarization, a prototypi- cal generation task. For all summarization bench- marks, we use ROUGE-1/2/L as our primary met- rics to stay consistent with other literature (Lin, 2004). Furthermore we benchmark HTLM on a set of three standard natural language generation tasks. We utilize the official benchmarking scripts provided which report BLEU (Papineni et al., 2002), NIST (Belz and Reiter, 2006), METEOR (Lavie and Agarwal, 2007), ROUGE-L (Lin, 2004), CIDEr (Vedantam et al., 2015) and TER (Snover et al., 2005). We use Li and Liang (2021) for our baselines, and present prefix tuning results with 0.1% of parameters as well. Gigaword consists of headlines from news arti- cles (Napoles et al., 2012). The target summaries # Prompt <html id="cnn_dailymail" lang="en" xml:lang="en"> <head class="pg-headline" data-act-id="article_head_0"> <p> <mask>X --CNN</p> </head> <body> 5 Three Egyptian journalists are being tried –CNN <p> However, observers inside the court said the prosecution evidence was difficult to follow or to understand. Correspondents said the most prominent video clip was by another al-Jazeera journalist who is not on trial. The three, including ex-BBC reporter Peter Greste , deny spreading false news and helping the Muslim Brotherhood. They appeared in the Cairo 8 Three British journalists ac- cused of aiding the Muslim Brotherhood are tried –CNN court on Tuesday along with other Egyptian students and activists being tried with them. Defence lawyers complained they were unable to understand some of the recordings being played because of poor technical quality. While the recordings were played, defendants talked among themselves in the caged dock. The trial was later adjourned until 3 May and bail for the defendants was denied, reports from the court said. Peter Greste, producer Baher Mohamed and al-Jazeera English's Canadian-Egyptian bureau chief Mohamed Fadel Fahmy have been held since December. A fourth al-Jazeera reporter, Abdullah Elshamy, who works for the network's Arabic channel, has been detained since August but not charged. Egyptian authorities accuse the journalists of aiding the Islamist Muslim Brotherhood, which has been banned as a terrorist group. </p> 12 15 Three British journalists ac- cused of aiding the Muslim Brotherhood are on trial – CNN Three British-Egyptian jour- nalists accused of aiding the Muslim Brotherhood are to be tried in a Cairo court –CNN </body> </html> Table 1: We provide a simple example using our CNN/DM prompt where by altering the Size Hint value (X) we get summaries of varied length and complexity. # <html lang="en" xml:lang="en"> <html lang="en" xml:lang="en"> <html lang="en" xml:lang="en"> <head> <title> the us rejects charges against its <mask> us rejects charges against its ambassador in bolivia <mask> <mask> the us state department said wednesday it had received no formal word from bolivia that it was ... <mask> HTLM −−−→ ambassador in bolivia | The Washington Post </title> </head> <body> <div class = "post-body entry-content"> <p> the us state department said wednesday it had received no formal word from bolivia that it was ... </p> </div> </body> <head> <title> the us rejects charges against its ambassador in bolivia | The — UnginiagiGia |RESE us rejects charges against its ambassador in </title> bolivia </head> sma <body> <mask> <div class = "post-body entry-content"> the us state department said wednesday it had prea a eee enna ip a received no formal word from bolivia that it cinentey Ms ae Was see formal word from bolivia that it <mask> yas </p> </div> </body> </html> # </html> Figure 2: An example of auto-prompting using a sample from the train-set of the Gigaword dataset. HTLM places the summary inside of a <title> inside of a <head> element, while placing the article in a <div> element with an entry-content attribute value for attribute class which is common on news web-sites. are relatively short, consisting roughly on average of 10 BPE tokens. CNN/Dailymail (Hermann et al., 2015) provides multi-sentence target summaries close to 3 sen- tences, or roughly 50 tokens. Reddit TIFU (Kim et al., 2018) contains sum- maries of Reddit posts. Specifically, we use the short subset of data . Compared to our other sum- marization datasets, this dataset is highly abstrac- tive and not based on news articles. XSum (Narayan et al., 2018) provides abstractive single sentence summaries of news articles. E2E (Novikova et al., 2017) is a table-to-text gen- eration dataset containing approximately 50K sam- ples with 8 unique fields from the restaurants do- main. WebNLG (Gardent et al., 2017) is also a struc- tured generation dataset containing 15 different do- mains from DBPedia. We report numbers on the Seen (S), Unseen (U) and All (A) subsets of the data. DART (Nan et al., 2020) is a open-domain struc- tured generation dataset containing Wikipedia ta- bles. We manually searched for prompts for each of these datasets using a maximum of 50 data points from the train set to evaluate the prompts. For our baseline, we compare against PEGA- SUS (Zhang et al., 2019), the current state of the art for zero shot summarization. PEGASUS was explicitly pre-trained for summarization by mask- ing and generating salient gap sentences from news articles. We present our results in Table 2. HTLM with manual prompts (HTLM-Manual) and size hints substantially improves over state-of- the-art zero-shot summarization results on all four datasets without any tailored pretraining. In par- ticular, we see large improvements of more than 8 ROUGE-L F1 for the Gigaword dataset. Fur- thermore, size hints-based auto-prompting (HTLM- Auto-S) outperforms PEGASUS in three out of four datasets. for the Gigaword dataset, we outperform previous state-of-the-art zero-shot results from PEGASUS by roughly 6 HTLM improvements stem ROUGE-L points. from the fact that HTML-based prompting allows us better control over dataset-specific attributes such as length and style. For NLG tasks, we required the use of a single training example to get prompting to work suffi- ciently. We report these one-shot numbers in Ta- ble 3. Because these tasks require structured tab- ular inputs, it is not obvious how to prompt any other text-based pre-trained models. We report other non-trainable baselines such as the gram- mar based pipeline approaches (TILB/UIT-VNU) in Gardent et al. (2017). To the best of our knowl- edge, these are the first one-shot table to text, nat- ural language generation results. # 4.2 Classification For prompting in the classification setting, we se- lect 4 datasets to work with. Instead of relying on generative prompting to generate target token(s) denoting the correct class, we instead rely on per- plexity measures over the set of all targets to se- lect the correct class. In other words, we select the class for which the perplexity of the corresponding instantiated template is the smallest. RTE (Bentivogli et al., 2009) is a textual entail- ment task formulated as binary classification. We place the candidate in a <div> element with the class attribute set to candidate and do the same with the respective hypothesis. In the third el- ement, we utilize the prompt from Brown et al. (2020) with the class attribute set to answer. BoolQ (Clark et al., 2019) is a yes/no question an- swering task, also formulated as binary classifica- tion for question, passage, and answer triplets. We represent the question as a <div> element with the itemprop set to https://schema.org/Question, passage as a div element with class attribute pas- sage and answer as a div element with the item- prop set to https://schema.org/Answer. Winogrande (Levesque et al., 2012) consists of adversarially collected Winograd Schema Chal- lenge (Levesque et al., 2011) data. We utilize the same template as GPT-3 but place it in a QA style template similar to BoolQ. Please refer to the Ap- pendix for exact templates. HellaSwag The last dataset we evaluate is the commonsense natural language inference task Hel- laSwag which, due to its adversarial nature, is con- sidered complex (Zellers et al., 2019). Model Gigaword CNN/DM Reddit TIFU XSum PEGASUS-0S 23.39/07.59/20.20 32.90/13.28/29.38 14.66/3.06/10.17 19.27/3.00/12.72 HTLM-Auto-NS 27.56/10.17/24.57 HTLM-Auto-S 28.73/11.31/26.49 HTLM-Manual 31.61/10.80/28.60 33.40/13.45/30.10 34.65/14.54/32.15 38.51/16.10/33.89 6.71/1.98/7.86 8.15/2.92/9.75 15.81/2.98/10.54 15.15/2.54/10.91 17.14/3.41/13.43 22.34/4.12/14.56 Table 2: HTLM results on zero-shot summarization. HTLM-Manual denotes manually engineered prompts with size hints, while HTLM-Auto-S and HTLM-Auto-NS indicate autoprompting with and without size hints respectively. Metrics shown are ROUGE-1/ROUGE-2/ROUGE-L respectively. E2E BLEU NIST MET R-L CIDEr S BLEU U A WebNLG MET U S A S TER ↓ U A Fine-tuning GPT-2MEDIUM GPT-2LARGE HTLM 68.2 68.5 70.3 8.62 8.78 8.90 46.2 71.0 46.0 69.9 46.3 70.8 2.47 2.45 2.47 64.2 65.3 65.4 27.7 43.1 48.4 46.5 0.45 0.30 0.38 0.33 0.76 0.53 55.5 0.46 0.38 0.42 0.33 0.53 0.42 55.6 0.46 0.39 0.42 0.33 0.51 0.40 46.2 47.0 47.2 0.39 0.39 0.39 0.46 0.46 0.44 0.50 0.51 0.51 0.94 0.94 0.94 0.39 0.40 0.40 Prefix (0.1%) GPT-2MEDIUM GPT-2LARGE HTLM 69.7 70.3 70.1 8.81 8.85 8.85 46.1 71.4 46.2 71.7 46.1 71.2 2.49 2.47 2.45 62.9 63.4 64.8 45.6 47.7 46.1 55.1 0.44 0.38 0.41 0.35 0.49 0.41 56.3 0.45 0.39 0.42 0.34 0.48 0.40 56.3 0.46 0.38 0.42 0.33 0.47 0.40 46.4 46.7 47.1 0.38 0.39 0.39 0.46 0.45 0.45 0.50 0.51 0.50 0.94 0.94 0.94 0.39 0.40 0.39 One-Shot HTLM 32.1 3.35 24.1 31.6 0.78 28.1 18.5 22.8 0.24 0.21 0.12 0.78 0.79 0.78 22.1 0.12 0.91 0.25 0.78 0.22 Base-lines TILB-Pipeline UIT-VNU-Pipeline - - - - - - - - - - 44.34 20.65 35.29 0.38 0.21 0.30 0.48 0.64 0.56 7.07 0.15 0.03 0.09 0.78 0.87 0.82 19.87 0.11 - - - - - - - - - - - - Table 3: We evaluate GPT-2MEDIUM , GPT-2LARGE and HTLM on table-to-text generation on E2E (left), WebNLG (middle) and DART (right). We present our results on zero-shot classifi- cation in Table 4. HTLM prompting of classi- fication datasets outperforms the most compara- ble (in terms of number of parameters) GPT-3 Medium sized model on the majority of tasks, while approaching—and on RTE outperforming— the GPT-3 Large model which consists of roughly double the amount of parameters as HTLM. # 5 Fine-tuning Experiments In addition to our previous prompting results, we also aim to show that HTLM learned repre- sentations are useful in the full finetuning set- ting. We compare against other pre-training MLM models such as RoBERTa (Liu et al., 2019), original BART (Lewis et al., 2019), and T5 (Raffel et al., 2019) by finetuning on the GLUE benchmark (Wang et al., 2018). # and HTLM. We present our results in Table 5. Overall HTLM improves over existing pre-training methods. We also note that we can improve fine-tuning perfor- mance by placing the examples into prompts and fine-tuning the classification head. The improve- ments that we see in terms of prompting have no adverse effects on fine-tuning but are rather posi- tive, providing further evidence that the proposed approach of structured pre-training is a viable al- ternative to other methods of pre-training even for fine-tuning. We also show our fine-tuning results for the table-to-text generation datasets in Table 3. Sim- ilar to GLUE fine-tuning, we place all NLG sam- ples into a prompt while fine-tuning. HTLM fine- tuned is able to outperform both variants of the GPT-2 model consistently. instead of a simple con- catenation of sentences from the train set, we place the examples into prompts derived from Le Scao and Rush (2021). We defer to the Ap- pendix for the exact prompts. Given the recent ad- vancements in finetuning, we also report results us- ing the recently proposed R3F method for finetun- ing (Aghajanyan et al., 2020a) for both RoBERTa # 6 Prompt Data Efficiency What does the HTML-based pretraining and prompting scheme offer over one based on the plain text? Le Scao and Rush (2021) explored quantifying how many data points a single prompt was worth. Specifically, they analyzed three differ- ent task-specific settings given a pattern (the struc- RTE BoolQ Winogrande HellaSwag 63.5 48.4 49.8 60.5 58.9 60.3 70.5 57.4 52.1 78.9 51.0 43.6 175B 760M 350M 51.2 55.3 54.8 47.9 400M Table 4: Classification accuracy with zero shot prompting. We compare our performance to the full GPT-3 model as well as variants of comparable size. MNLI Acc-m/mm QQP Acc RTE Acc QNLI Acc MRPC Acc CoLA Mcc SST-2 Acc RoBERTA RoBERTa-R3F T5-Base T5-Large BART-Large 90.2/- 91.1/91.3 87.1/86.2 89.9/89.6 89.9/90.1 92.2 86.6 94.7 92.4 88.5 95.3 89.4 80.1 93.7 89.9 87.2 94.8 92.5 87.0 94.9 89.1 91.6 87.5 89.9 90.4 68.0 71.2 51.1 61.2 62.8 96.4 97.0 95.2 96.3 96.6 330M 330M 220M 770M 400M HTLM 90.3/91.4 HTLM-R3F 91.4/92.1 HTLM-R3F-Prompt 91.6/91.2 92.6 87.1 95.1 92.8 89.1 95.4 92.9 89.4 95.7 90.8 91.5 91.7 64.3 69.4 69.8 96.9 97.1 97.3 400M 400M 400M Table 5: Results on the GLUE development set for various fine-tuning methods applied to HTLM. Average Advantage (# Training Points, P vs. H) MNLI BoolQ CB RTE WiC RoBERTa-Large T5-Large BART-Large 3506 ± 536 5010 ± 230 4020 ± 220 6025 ± 440 855 ± 205 255 ± 35 840 ± 45 752 ± 46 650 ± 85 450 ± 55 90 ± 2 150 ± 8 125 ± 10 HTLM Table 6: Average advantage (higher is better) in terms of training points for fine-tuning well-structured prompt (P ) against a classical classification head (H). MNLI Average Advantage (# Training Points, P vs. N) CB BoolQ RTE WiC RoBERTa-Large T5-Large BART-Large 299 ± 81 350 ± 95 325 ± 54 78 ± 2 150 ± 4 85 ± 8 20 ± 43 −80 ± 89 80 ± 40 HTLM 150 ± 252 404 ± 68 −354 ± 166 300 ± 120 608 ± 90 200 ± 180 512 ± 64 692 ± 240 565 ± 143 255 ± 34 640 ± 45 Table 7: Average advantage (higher is better) in terms of training points for fine-tuning well-structured prompt (P ) against a prompt with a non-sensical verbalizer (N ). ture that the inputs are put into) and verbalizer (i.e., yes/no answer to pattern): (1) fine-tuning a classi- fication head (H), (2) fine-tuning the verbalizer of a prompt encoding the semantics of the task (P ), and (3) fine-tuning the prompt but with a verbal- izer that is non-sensical (N ). By carefully selecting the number of data points to be used during training in each setting while matching the end fine-tuning performance, we can empirically measure the efficacy of prompts in terms of data points. We provide the same analysis extended to BART, T5-Large, and HTLM using the same PET prompts pro- vided in Schick and Sch¨utze (2020). For HTLM, we wrap all PET prompts in an HTML ele- ment. We select the same datasets that were used in the original paper for our experimen- (Williams et al., 2018), BoolQ tation; MNLI (Clark et al., 2019), CB (De Marneffe et al., 2019), RTE (Bentivogli et al., 2009), WiC (Pilehvar and Camacho-Collados, 2019). We first look at the average advantage of fine- tuning a prompt (P ) against a classification head (H) in Table 6. We see that across the board, HTLM prompts—i.e., hypertext prompts applied to HTLM—are worth more than natural language prompts to various other pre-trained models. Com- pared to RoBERTa-Large on smaller datasets, HTLM’s advantage is close to triple on CB and dou- ble on RTE. Furthermore, on WiC, HTLM is the only pre-trained model capable of having a posi- tive training advantage when using prompts. We view this as additional evidence to the benefit of pre-training on structured data on the prompting of a pre-trained model. We also compare the average advantage of fine- tuning a prompt with a verbalizer (P ) that makes sense against against finetuning a prompt where we change the verbalizer to a random first name (N ). This is important to capture whether the benefits arise from representing the data in their respective patterns or the coupling of the pattern and the verbalizer. We present our results in Ta- ble 7. Relative to the previous P vs. H setting we lose a large amount of advantage, as was sim- ilarly seen in (Le Scao and Rush, 2021). Interest- ingly enough for small datasets such as CB, all of the training advantage of the prompt comes from the pattern in HTLM. We view this as further evidence that a struc- tured, document level approach to both pre- training and prompting can be seen as a viable al- ternative to a purely natural language approach. # 7 Related Work GPT-2 (Radford et al., 2019) showed that large language models show varying levels of zero- shot performance across NLP tasks when com- pared to supervised baselines (e.g., rudimen- tary performance on summarization, but more competitive results on reading comprehension). Brown et al. (2020) through their GPT3 model showed that by further scaling up language mod- els on a large subset of the internet, prompt- ing could be a viable alternative to standard fine- tuning. The success of GPT3 was largely at- tributed to massive size and compute-intensive By reformulating NLP tasks as pretraining. cloze-style questions, Schick and Sch¨utze (2020) shows that the prompting capabilities exhibited by GPT3 can occur in language models of a much smaller scale when gradient-based finetun- ing is combined with task-specific unlabeled data. Follow-up work (Tam et al., 2021) improves upon these results without depending on unlabeled data. Unlike GPT-3 and other models which use con- ventional natural language text-based prompting, we focus on a new hyper-text based prompting scheme using generative masked language models pre-trained directly over HTML. For task-specific zero-shot performance, cus- tom pre-training and data augmentation schemes For example, PEGA- have been developed. SUS (Zhang et al., 2019) proposes a novel pre- training scheme tailored for summarization which involves masking and generating salient gap sen- tences from a large news corpus. While PE- GASUS is capable of doing zero-shot summa- rization, it offers little control over summary attributes such as length and style which vary across different summarization datasets. Wiki- Transfer (Fabbri et al., 2021) fine-tunes pretrained models on pseudo-summaries, produced from generic Wikipedia data, which contain character- istics of the target dataset, such as the length and level of abstraction. Our proposed model allows fine-grained control over the length of the gen- erated text by specifying the size of the mask. Moreover, by using different prompts, HTLM can produce stylistically varied summaries without dataset-specific augmentation and finetuning. Another line of work has been looking at a hy- brid form of prompting that attempts to optimize very few parameters to solve an end task. For example Li and Liang (2021) argue that optimiz- ing in the continuous prompt space is an effective solution to prompt search while Aghajanyan et al. (2020b) optimize for a low-rank projection of the full parameter space. For simplicity, we only focus on either full-finetuning or zero-shot prompting in this paper. Attempts have been made to encode architec- tural priors for structured inputs into transformers as well. Specifically, Ainslie et al. (2020) discuss a new type of model which allows for scalability in input length as well as the ability to encode the structure of the input. We opt to allow HTLM to learn the structure that is available in the HTML di- rectly without encoding any structural priors into the model itself. # 8 Conclusion In this paper, we proposed HTLM, a hyper-text lan- guage model trained on simplified HTML docu- ments from a large-scale web crawl. We showed that by directly modeling HTML through a BART- like objective, we could do structured zero-shot prompting by representing tasks in HTML. Specif- ically, we outperform the previous best results on zero-shot prompting for summarization by a wide margin by creating prompts that capture the un- derlying semantics of each summarization dataset. Furthermore, we show that pre-training on struc- tured data improved full finetuning performance relative to other pre-trained models that only mod- eled natural language. We also showed additional advantages of model- ing hyper-text, beyond improved accuracy. HTLM can be used for auto-prompt by simply asking the model to recover the document structure from training samples; these auto-prompts on datasets like Gigaword and CNN/DM outperformed previ- ous state-of-the-art zero-shot approaches. Lastly, we provided an in-depth comparison of the train- in terms of data efficiency, that ing advantage, HTLM had compared to other pre-training ap- proaches. Across the board, HTML prompts were worth more to HTLM than natural language prompts were worth to our baselines, further show- ing the efficacy of pre-training structured data. Future work can focus on the scaling laws of structured pre-training and prompting. As was seen from GPT-3, the size of the model and the amount of compute utilized and significant impact on prompting performance. # References Armen Aghajanyan, Akshat Shrivastava, Anchit Gupta, Naman Goyal, Luke Zettlemoyer, and Sonal Gupta. 2020a. Better fine-tuning by reducing representa- tional collapse. arXiv preprint arXiv:2008.03156. Armen Aghajanyan, Luke Zettlemoyer, and Sonal Gupta. 2020b. Intrinsic dimensionality explains the effectiveness of language model fine-tuning. arXiv preprint arXiv:2012.13255. Joshua Ainslie, Santiago Ontanon, Chris Alberti, Va- clav Cvicek, Zachary Fisher, Philip Pham, Anirudh Ravula, Sumit Sanghai, Qifan Wang, and Li Yang. 2020. Etc: Encoding long and structured inputs In Proceedings of the 2020 Con- in transformers. ference on Empirical Methods in Natural Language Processing (EMNLP), pages 268–284. Iz Beltagy, Matthew E Peters, and Arman Cohan. 2020. Longformer: The long-document transformer. arXiv preprint arXiv:2004.05150. Anja Belz and Ehud Reiter. 2006. Comparing auto- matic and human evaluation of nlg systems. In 11th conference of the european chapter of the associa- tion for computational linguistics. Luisa Bentivogli, Peter Clark, Ido Dagan, and Danilo Giampiccolo. 2009. The fifth pascal recognizing tex- tual entailment challenge. In TAC. Tom B Brown, Benjamin Mann, Nick Ryder, Melanie Subbiah, Jared Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, et al. 2020. Language models are few-shot learners. arXiv preprint arXiv:2005.14165. Krzysztof Choromanski, Valerii Likhosherstov, David Dohan, Xingyou Song, Andreea Gane, Tamas Sar- los, Peter Hawkins, Jared Davis, Afroz Mohiuddin, Lukasz Kaiser, et al. 2020. Rethinking attention with performers. arXiv preprint arXiv:2009.14794. Christopher Clark, Kenton Lee, Ming-Wei Chang, Tom Kwiatkowski, Michael Collins, and Kristina Toutanova. 2019. BoolQ: Exploring the surprising In Proceed- difficulty of natural yes/no questions. ings of NAACL-HLT 2019. Alexis Conneau, Kartikay Khandelwal, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzm´an, Edouard Grave, Myle Ott, Luke Zettle- moyer, and Veselin Stoyanov. 2019. Unsupervised cross-lingual representation learning at scale. arXiv preprint arXiv:1911.02116. Marie-Catherine De Marneffe, Mandy Simons, and The Commitment- Judith Tonhauser. 2019. Bank: Investigating projection in naturally oc- curring discourse. To appear in proceedings of Sinn und Bedeutung 23. Data can be found at https://github.com/mcdm/CommitmentBank/. A. R. Fabbri, Simeng Han, Haoyuan Li, Haoran Li, Marjan Ghazvininejad, Shafiq R. Joty, Dragomir Radev, and Yashar Mehdad. 2021. Improving zero and few-shot abstractive summarization with inter- In mediate fine-tuning and data augmentation. NAACL. Claire Gardent, Anastasia Shimorina, Shashi Narayan, and Laura Perez-Beltrachini. 2017. The webnlg In Pro- challenge: Generating text from rdf data. ceedings of the 10th International Conference on Natural Language Generation, pages 124–133. Karl Moritz Hermann, Tomas Kocisky, Edward Grefen- stette, Lasse Espeholt, Will Kay, Mustafa Suleyman, and Phil Blunsom. 2015. Teaching machines to read and comprehend. In Advances in neural information processing systems, pages 1693–1701. Armand Joulin, Edouard Grave, Piotr Bojanowski, Matthijs Douze, H´erve J´egou, and Tomas Mikolov. 2016. Fasttext. zip: Compressing text classification models. arXiv preprint arXiv:1612.03651. Byeongchang Kim, Hyunwoo Kim, and Gunhee Kim. 2018. Abstractive summarization of reddit posts with multi-level memory networks. arXiv preprint arXiv:1811.00783. Diederik P Kingma and Jimmy Ba. 2014. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980. Alon Lavie and Abhaya Agarwal. 2007. Meteor: An automatic metric for mt evaluation with high levels of correlation with human judgments. In Proceed- ings of the second workshop on statistical machine translation, pages 228–231. 2021. How many data points is a prompt worth? In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies, pages 2627–2636, Online. Association for Compu- tational Linguistics. Hector Levesque, Ernest Davis, and Leora Morgen- stern. 2012. The winograd schema challenge. In Thirteenth International Conference on the Princi- ples of Knowledge Representation and Reasoning. Citeseer. Hector J Levesque, Ernest Davis, and Leora Morgen- stern. 2011. The Winograd schema challenge. In AAAI Spring Symposium: Logical Formalizations of Commonsense Reasoning, volume 46, page 47. Mike Lewis, Yinhan Liu, Naman Goyal, Mar- jan Ghazvininejad, Abdelrahman Mohamed, Omer Levy, Ves Stoyanov, and Luke Zettlemoyer. 2019. Bart: Denoising sequence-to-sequence pre-training for natural language generation, translation, and comprehension. arXiv preprint arXiv:1910.13461. Prefix- tuning: Optimizing continuous prompts for genera- tion. arXiv preprint arXiv:2101.00190. Chin-Yew Lin. 2004. Rouge: A package for automatic In Text summarization evaluation of summaries. branches out, pages 74–81. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Man- dar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized bert pretraining ap- proach. arXiv preprint arXiv:1907.11692. Linyong Nan, Dragomir Radev, Rui Zhang, Amrit Rau, Abhinand Sivaprasad, Chiachun Hsieh, Xian- gru Tang, Aadit Vyas, Neha Verma, Pranav Kr- ishna, et al. 2020. Dart: Open-domain struc- tured data record to text generation. arXiv preprint arXiv:2007.02871. Courtney Napoles, Matthew R Gormley, and Benjamin In Pro- Van Durme. 2012. Annotated gigaword. ceedings of the Joint Workshop on Automatic Knowl- edge Base Construction and Web-scale Knowledge Extraction (AKBC-WEKEX), pages 95–100. Shashi Narayan, Shay B Cohen, and Mirella Lap- ata. 2018. Don’t give me the details, just the topic-aware convolutional neural net- summary! works for extreme summarization. arXiv preprint arXiv:1808.08745. Jekaterina Novikova, Ondˇrej Duˇsek, and Verena Rieser. 2017. The e2e dataset: New challenges for end-to- end generation. arXiv preprint arXiv:1706.09254. Kishore Papineni, Salim Roukos, Todd Ward, and Wei- Jing Zhu. 2002. Bleu: a method for automatic eval- uation of machine translation. In Proceedings of the 40th annual meeting of the Association for Compu- tational Linguistics, pages 311–318. Ethan Perez, Douwe Kiela, and Kyunghyun Cho. 2021. True few-shot learning with language models. arXiv preprint arXiv:2105.11447. Mohammad Taher Pilehvar and Jose Camacho- Collados. 2019. WiC: The word-in-context dataset for evaluating context-sensitive meaning representa- tions. In Proceedings of NAACL-HLT. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. OpenAI Blog, 1(8):9. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J Liu. 2019. Exploring the limits of transfer learning with a unified text-to-text trans- former. arXiv preprint arXiv:1910.10683. It’s not just size that matters: Small language mod- arXiv preprint els are also few-shot arXiv:2009.07118. Mathew Snover, Bonnie Dorr, Richard Schwartz, John Makhoul, Linnea Micciulla, and Ralph Weischedel. 2005. A study of translation error rate with targeted human annotation. In Proceedings of the 7th Con- ference of the Association for Machine Translation in the Americas (AMTA 06), pages 223–231. Derek Tam, R. R. Menon, M. Bansal, Shashank Srivastava, and Colin Raffel. 2021. Improving and simplifying pattern exploiting training. ArXiv, abs/2103.11955. Ramakrishna Vedantam, C Lawrence Zitnick, and Devi Parikh. 2015. Cider: Consensus-based image de- In Proceedings of the IEEE scription evaluation. conference on computer vision and pattern recogni- tion, pages 4566–4575. Alex Wang, Amanpreet Singh, Julian Michael, Fe- lix Hill, Omer Levy, and Samuel Bowman. 2018. GLUE: A multi-task benchmark and analysis platform for natural language understanding. In Proceedings of the 2018 EMNLP Workshop BlackboxNLP: Analyzing and Interpreting Neural Networks for NLP, pages 353–355, Brussels, Bel- gium. Association for Computational Linguistics. Sinong Wang, Belinda Li, Madian Khabsa, Han Linformer: Self- arXiv preprint Fang, and Hao Ma. 2020. attention with linear complexity. arXiv:2006.04768. Adina gia, A broad-coverage challenge corpus for sentence understanding through inference. In Proceedings of the 2018 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies, Volume 1 (Long Papers), pages 1112–1122. Associ- ation for Computational Linguistics. Rowan Zellers, Ari Holtzman, Yonatan Bisk, Ali Farhadi, and Yejin Choi. 2019. Hellaswag: Can a machine really finish your sentence? arXiv preprint arXiv:1905.07830. Jingqing Zhang, Yao Zhao, Mohammad Saleh, and Pe- ter J Liu. 2019. Pegasus: Pre-training with extracted gap-sentences for abstractive summarization. arXiv preprint arXiv:1912.08777. # A Appendix # A.1 Finetuning Hyper-Parameters For our GLUE related experiments the following parameters are used. Hyper Parameter MNLI QNLI QQP SST-2 RTE MRPC CoLA Learning Rate Max Updates Max Sentences 5e-6 123873 8 5e-6 33112 8 5e-6 113272 32 5e-6 20935 32 1e-5 3120 8 1e-5 2296 16 1e-5 5336 16 Table 8: Task specific hyper parameters for GLUE experiments Hyper parameter Value Optimizer Adam-betas Adam-eps LR Scheduler Dropout Weight Decay Warmup Updates Adam (0.9, 0.98) 1e-6 polynomial decay 0.1 0.01 0.06 * max updates # Hyper parameter Value # λ Noise Types σ [0.1, 0.5, 1.0, 5.0] [U , N ] 1e − 5 Table 9: Hyper parameters for R3F experiments on GLUE
Title: CodeHelp: Using Large Language Models with Guardrails for Scalable Support in Programming Classes: Summary: Computing educators face significant challenges in providing timely support to students, especially in large class settings. Large language models (LLMs) have emerged recently and show great promise for providing on-demand help at a large scale, but there are concerns that students may over-rely on the outputs produced by these models. In this paper, we introduce CodeHelp, a novel LLM-powered tool designed with guardrails to provide on-demand assistance to programming students without directly revealing solutions. We detail the design of the tool, which incorporates a number of useful features for instructors, and elaborate on the pipeline of prompting strategies we use to ensure generated outputs are suitable for students. To evaluate CodeHelp, we deployed it in a first-year computer and data science course with 52 students and collected student interactions over a 12-week period. We examine students' usage patterns and perceptions of the tool, and we report reflections from the course instructor and a series of recommendations for classroom use. Our findings suggest that CodeHelp is well-received by students who especially value its availability and help with resolving errors, and that for instructors it is easy to deploy and complements, rather than replaces, the support that they provide to students. # CodeHelp: Using Large Language Models with Guardrails for Scalable Support in Programming Classes # Mark Liffiton mliffito@iwu.edu Illinois Wesleyan University Bloomington, Illinois, USA Brad Sheese bsheese@iwu.edu Illinois Wesleyan University Bloomington, Illinois, USA Jaromir Savelka jsavelka@cs.cmu.edu Carnegie Mellon University Pittsburgh, Pennsylvania, USA # Paul Denny paul@cs.auckland.ac.nz The University of Auckland Auckland, New Zealand ABSTRACT Computing educators face significant challenges in providing timely support to students, especially in large class settings. Large lan- guage models (LLMs) have emerged recently and show great promise for providing on-demand help at a large scale, but there are concerns that students may over-rely on the outputs produced by these mod- els. In this paper, we introduce CodeHelp, a novel LLM-powered tool designed with guardrails to provide on-demand assistance to programming students without directly revealing solutions. We detail the design of the tool, which incorporates a number of useful features for instructors, and elaborate on the pipeline of prompt- ing strategies we use to ensure generated outputs are suitable for students. To evaluate CodeHelp, we deployed it in a first-year com- puter and data science course with 52 students and collected student interactions over a 12-week period. We examine students’ usage patterns and perceptions of the tool, and we report reflections from the course instructor and a series of recommendations for classroom use. Our findings suggest that CodeHelp is well-received by stu- dents who especially value its availability and help with resolving errors, and that for instructors it is easy to deploy and complements, rather than replaces, the support that they provide to students. unlikely to be exhaustive. Thus, there is great need for scalable ap- proaches for providing immediate, high-quality support to students who are learning to program. Large language models (LLMs) have recently garnered consider- able interest due to their capabilities for generating human-like text in a wide array of contexts, including computing education [27]. There, LLMs have shown great potential for generating resources such as programming exercises, code explanations and model so- lutions [11]. Recent work has even shown that LLM-generated explanations of code are perceived as more useful to students than explanations produced by their peers [20]. Thus, the prospect of using LLMs to produce real-time, on-demand help for students appears promising. However, a common concern is that students may rely too heavily on the outputs produced by such models, espe- cially if they can be used to generate solutions directly [1]. Related concerns around student over-reliance on LLM-based tools are com- mon in educational settings [16]. Indeed, when OpenAI recently released the widely publicised GPT-4 model, they showcased the example of a ‘socratic’ tutor, highlighting how the model could be steered away from revealing solutions directly to the user1. CCS CONCEPTS • Social and professional topics → Computer science edu- cation; Software engineering education; • Human-centered computing → Interactive systems and tools. KEYWORDS Intelligent tutoring systems, Intelligent programming tutors, Pro- gramming assistance, Novice programmers, Natural language in- terfaces, Large language models, Guardrails 1 INTRODUCTION AND MOTIVATION As student interest in programming continues to grow and class sizes expand, educators face significant challenges in providing effective and timely support to all students. Traditional approaches of offering on-demand expert help do not scale well in very large settings, and not all students feel comfortable approaching an in- structor or a teaching assistant for help [13]. Similarly, authoring static hints or responses to commonly encountered issues that can be presented to students needing help is both time intensive and In this paper we introduce CodeHelp, an LLM-powered tool for generating real-time help for programming and computer sci- ence students. A key contribution of CodeHelp is its use of robust “guardrails” that are specifically designed to not reveal solutions directly while helping students resolve their issues, thus mitigating the over-reliance trap that direct use of LLMs may cause. We de- scribe the design of the CodeHelp tool and elaborate on the LLM prompting strategies that we use to generate outputs that guide students towards a solution without producing answers directly. We also discuss the tool’s useful features for instructors, including the ability to observe, summarise, and review how their students engage with it. To explore its potential, we deployed CodeHelp in a first-year computer- and data-science course with 52 students and monitored its usage over a 12-week period. We investigate when and how frequently students engaged with CodeHelp, what types of help they request, and how useful they found the tool. To date, there has been significant interest in the computing education liter- ature focusing on the accuracy of LLMs, the types of resources they can generate, and comparative analyses involving historical student data [11]. To our knowledge, this work represents the first evalua- tion of an always-available LLM-powered teaching assistant with 1https://openai.com/research/gpt-4 guardrails tailored for computer science education. We found that CodeHelp is well-received by students, it is easy and inexpensive to deploy, and most importantly, it appears to effectively complement and expand on the support students receive from course instructors and teaching assistants (TAs). 2 RELATED WORK Providing effective automated assistance to novice programmers has been a longstanding research problem. Considerable attention has been devoted to the development and evaluation of so-called in- telligent tutoring systems for programming, sometimes referred to as intelligent programming tutors (IPT). Such systems vary greatly and contain a large range of supplementary features [8]. Most of the work has been devoted to various approaches for the generation of effective hints [21, 22] and feedback [18]. The primary difference between CodeHelp and previous work in this area is that CodeHelp is able to respond to a far wider range of requests and requires little or no configuration or setup for any specific class context due to its underlying use of LLMs. Prior to the development and use of LLMs, similar tools had to rely on various rule-based and machine learning-based natural language processing techniques that were much more specialized and, hence, brittle. For example, they could only support a single programming language or type of support request. CodeHelp supports any programming language with sufficient coverage in the underlying LLM’s training set. In particular, programming languages that are commonly used in com- puting education are covered very well. CodeHelp can also respond effectively to a wide variety of request types. Chatbots provide a convenient interaction experience and have previously been deployed as intelligent assistants in programming education contexts. For example, Carreira et al. developed Pyo, a chatbot designed to help novice programmers in online courses by providing definitions of concepts, guiding them through errors, and assisting with exercises [4]. Although the goal of Pyo is very similar to that of CodeHelp, a notable distinction is that Pyo is rule-based with predetermined topics and conversation flows, while CodeHelp is far more flexible. In similar work, Konecki et al. proposed a rule- based intelligent assistant for programming education aiming to increase engagement, motivation and learning time [19]. Although the primary focus of CodeHelp is to assist students in resolving their issues when programming, we expect it may influence engagement and motivation as well. Python-Bot [24] and RevBot [25] are examples of AI-based sys- tems that help students understand Python syntax and practice past exam questions. Here, the focus is not on resolving issues, as with CodeHelp, but rather on helping students understand particular topics and testing their knowledge. Duckbot is another chatbot designed to enhance help-seeking between students and teaching staff in programming tutorials [29]. Walden et al. [34] developed a chatbot for teaching secure programming in PHP. Unlike many existing chatbot tools that have a narrow focus, CodeHelp lever- ages the power of LLMs to provide support across a wide variety of contexts involving various programming languages. LLMs have been shown to exhibit remarkable performance on a broad range of tasks, including code generation [6]. Finnie-Ansley Mark Liffiton, Brad Sheese, Jaromir Savelka, and Paul Denny et al. found that Codex (GitHub Copilot) outperforms typical stu- dents in CS1 programming exams [12]. Similarly, Savelka et al. found that GPT-4 comfortably passes diverse types of assessments from introductory and intermediate Python programming classes at the post-secondary education level [31]. Denny et al. evaluated Copilot on 166 CS1 coding problems and found that it successfully solves around half of these problems on its very first attempt, and that it solves 60% of the remaining problems if the problem de- scription is reformulated appropriately [9]. Tian et al. evaluated ChatGPT as a programming assistant and found that it successfully handles typical programming challenges [33]. LLMs have also been applied to other computing education tasks, such as writing tests [5, 15], and helping novices learn how to craft effective prompts [10]. Moreover, LLMs have been employed to generate example ex- planations as scaffolding to help students learn how to understand and explain code themselves [20] and to generate programming exercises and code explanations [30]. This prior work demonstrates the capabilities and the flexibility of the LLMs that power CodeHelp. Despite their impressive performance at many tasks, LLMs may not be as effective as human tutors in some domains. For instance, LLMs may struggle with certain types of programming multiple- choice questions [32] or certain types of coding exercises [31]. An empirical evaluation of GitHub Copilot’s code suggestions revealed limitations in generating reliable code [23]. Pardos and Bhandari [26] compared learning gains from hints generated by LLMs and human tutors, finding that although both led to positive learning gains, human-generated hints were superior. They also found that only 70% of ChatGPT-generated hints were usable. Our vision for CodeHelp is that it will serve to augment existing instruction, pro- viding students with another convenient and accessible avenue to seek support, rather than replacing human instructors or TAs. Two recent studies in the computing education literature pro- vide excellent motivation for our work. Both studies highlight the pressing need for a tool that provides appropriate guardrails when generating responses to students’ requests. The first study, by Kazemitabaar et al., analyses student use of their Coding Steps tool [17]. Coding Steps integrates an AI code generator into the user interface of an online programming tool. When a student uses this code generator, they provide a natural language prompt which is packaged together with their existing code and six static examples and sent to the OpenAI Codex API. The response from the API is then automatically inserted for the student into the code editor. In their study, where students tackled 45 Python programming tasks over ten 90-minute sessions, AI-generated code was submit- ted by students without any modification 49% of the time. This heavy use of the code generator raises concerns around student over-reliance which has been identified as a key challenge for edu- cators [1, 3, 7, 28]. The second study that is particularly pertinent to our work is the recent paper by Hellas et al. exploring responses generated by Codex and GPT-3.5 to 150 student help requests from a historical dataset [14]. The data had previously been collected via a platform that allowed students to click a ‘Request help’ button when their code did not pass automated tests. This added their request to a queue that was monitored by a teacher who could respond manually. When assessing the GPT-3.5 model, they found that many of the generated responses were accurate and that 99% of the responses contained source code. Interestingly, the authors CodeHelp: Using Large Language Models with Guardrails characterise the language model as an ‘unreliable tutor’ that has a ‘penchant for blurting out model solutions even when you di- rectly ask them not to’. Again, this work emphasises the need for tools that can provide assistance to students without immediately revealing answers. Our work differs from these recent studies in several key ways. Our primary contribution is the explicit design of appropriate guardrails to avoid student over-reliance on model-generated code. Like Kazemitabaar et al. [17], we deployed our tool in the class- room; however, our evaluation ran for 12 weeks, and we explore how students interact with it outside of scheduled class sessions. In the dataset used by Hellas et al. [14], students infrequently used the ‘Request help’ button likely due to the fact that requests were added to a queue and responded to manually by a teacher. In our work, students receive immediate feedback from CodeHelp at any time of the day or night. # 3 CODEHELP DESIGN AND IMPLEMENTATION We designed CodeHelp to augment and complement the learning support students receive from instructors and teaching assistants. We aimed to provide a tool in which a student could 1) request help with issues they face in programming activities and 2) immediately receive a helpful response that provides guidance and explanation without providing a complete solution. To accomplish this, we cre- ated CodeHelp with a simple, clear interface for students (Sec. 3.1); developed a workflow of multiple LLM prompts to generate the desired responses, with guardrails, from a student’s input (Sec. 3.2); and implemented features specifically for instructors to manage and observe their students’ usage (Sec. 3.3). For broad accessibility, CodeHelp is implemented as a web application; it is accessible at https://codehelp.app/. 3.1 Student Interfaces CodeHelp’s student interfaces are simple, with minimal choices and clear guidance. Students accessing CodeHelp are brought di- rectly to the Help Request form, shown in Figure 1. We opted for a structured input, organizing it into several specific fields rather than having a single free-form text input. This both provides guid- ance to students about what information is typically needed for an effective query and gives more context and structure to the prompt that is ultimately fed to an LLM, which increases the chances of supporting the student successfully. Moreover, the structured in- put provides students an opportunity to practice asking technical questions, providing the necessary relevant context. Students are asked to provide: • The programming language in which they are working. The instructor can set a class-wide initial default, and the form then defaults to each student’s most recently selected language. • The relevant snippet of code. This is optional, as not all queries reference existing code. • The error message. This is optional as well. If an error message is provided, the underlying LLM is prompted to explain the error message to the student. Language: Please select v Code: Copy just the most relevant part of your code here Responses will be more helpful when you include only code relevant to your issue Error Message: IF your issue relates to an error message, copy the message here. Be sure to include the message itself and the quoted line on which it says the error occurred. Your Issue / Question: Clearly describe your issue or question. Include as relevant: what you are trying to do, what you expect the code to do, what the code actually does, and what you need help understanding Submit Request Figure 1: The Help Request form (text areas have been shrunk here to save space). The four separate inputs (language, code, error, and issue) and connected guidance text help students structure their request and encourage good practices when requesting support. User: Holley When: 2023-03-02 12:06pm Language: Python code: Error Message: Issue / Question: I wantto print the numbers upto 10, but this ust crashes Response Remember: It will not always be correct! Ie looks lke you are trying to.use a for loop to print the numbers up to 10, ut you are running into an error. In Python, the for loop syntax requires that you provide aniterable object, such asa ist arrange, to loop over. To generate a range fof numbers From 0 to 10, youcan use the range function. This will give you an terable object that you can use in your for loop. and end number, The tart number wil be the ber you want ta print. For example, f you want Ifyou wantto print the numbers 1 te 10, you can use the range Function witha first umber you wane to print, and the end number will be one more than the la to print the numbers 1to 10, youcan use the range function lke this: range(, 11) Wosthishelgtur {Yes GD No Figure 2: The Response View. Students are shown the details of their request followed by the system’s response. A promi- nent warning reminds students that the response may be incorrect. A simple feedback form allows the students to indicate whether the answer was helpful. • The question or description of the issue with which the student needs help. After submitting a request for help, the student is brought to the response view, an example of which is shown in Figure 2. This view displays the query (for reference) and the generated response. Because there is a chance the LLM may generate an incorrect or confusing answer (discussed further in Section 4), a warning re- minder is displayed prominently above every response. A simple feedback form allows the student to note whether the response was helpful. The query, response, and any feedback are stored for the student’s future reference and made available to the instructor. In practice, students do not always provide sufficient information or context to provide accurate assistance. CodeHelp attempts to Response Remember: twill not always be correct! ‘The code is attempting to filter a pandas DataFrame based on the ‘State’ column, bu is encountering a KeyEtror. Please Provide the code or information related to how the ‘dF DataFrame is defined. ‘An attempt.ata response is below, but you can (Retry) this query and provide adaktional details or clarification to receive a ‘more helpful response. Ie looks lke you are trying to access a column called State’ in your DataFrame, butts not present. The Keyrror you are sing is telling you that the key ‘State’ does not exist in your DataFrame. To Ficthis issue, you should check the column namesin your DataFrame and make sure that ‘State’ is spelled correctly andis present. You can use the df.colunns attribute to see a lst of al the column names in your DataFrame. ‘Additionally itlooks Uke you are trying to use the / operator to combine two conditions inyour Lee statement.In Python, the / ‘operator ic used for division, not combining conditions Instead, you should use the & operator to combine conditions. I hope this helps Let me knowif you have any Further questions or issues. Figure 3: Example response with a request for clarification (the yellow panel in the middle). The retry button takes the student to a help request form pre-filled with the same query. determine whether each request is lacking in this way, and if so, it presents the student with a request for clarification as shown in Figure 3. The clarification request attempts to help the student identify what additional information is needed. The determination and clarification request are generated by an LLM as well (described in Section 3.2), and because it could be incorrect, the student is also given a response to their request as written. This is mostly done to prevent students becoming stuck in a series of clarification requests without receiving any support. When a clarification is requested, the system describes the main response as an “attempt” at a response to indicate to the student that it may be less accurate given the missing information. 3.2 Generating Responses We designed CodeHelp to generate responses to student requests that are similar to those of a human tutor or instructor helping a student in a one-on-one session. Specifically, our goals for the responses were: • Provide explanations and guidance to support the student in their learning. • Never include complete solutions that the student can copy without thinking or learning. • Identify incomplete or ambiguous queries and prompt the student for additional information. • Only respond to questions relevant to the course (to prevent abuse of the tool as unrestricted access to an LLM). In CodeHelp, we achieve these goals via careful design of multiple prompts for the LLMs generating responses. The LLMs used in CodeHelp operate by repeatedly predicting the next word in a sequence, and so they are commonly used by providing a text prompt from which the LLM generates a completion, i.e., a sequence of words predicted to follow the prompt. LLMs are limited in the number and complexity of instructions they can accurately follow in a single prompt and completion, and we found that current LLMs could not consistently achieve all of the desired goals with a single prompt and its completion. Therefore, the current design of CodeHelp employs three separate prompts. The response workflow using these prompts is shown in Figure 4. Mark Liffiton, Brad Sheese, Jaromir Savelka, and Paul Denny A student’s request for help (query) is included in a “sufficiency check” prompt and in a prompt for generating the main response. Because we want the system to provide its main response even in cases when the query is determined to be insufficient as written, CodeHelp generates the sufficiency check in parallel with the main response. If the sufficiency check determines clarification is needed, we display the clarification request above the main response (Fig- ure 3); otherwise, only the main response is shown. From the “main response” prompt, two different completions are generated and scored for quality (described below). The higher-scoring prompt is kept and checked for the presence of code blocks, and a third prompt is used to remove them if found. Sufficiency Check. To check for insufficient or incomplete queries, the student’s query is included in a prompt with instructions that explain the context, describe the meaning of each field in the stu- dent’s input, and request an assessment of sufficiency. The full prompt is shown in Figure 5. To improve the accuracy of the LLM’s response, we include instructions in the prompt for the LLM to sum- marize the request and state its reasoning before generating the final determination. This is a specific instance of a technique gener- ally referred to as “chain of thought prompting” (CoT), which has been found to improve the accuracy of LLM responses in various contexts [35]. Main Response. Similar to the sufficiency check, the main prompt, shown in Figure 6, inserts the individual fields of a student’s query into instructions explaining the system context and meaning of each field. As one part of preventing solution code in the response, the system modifies the student’s provided issue to append, “Please do not write any example code in your response.” Additionally, if the instructor has specified any keywords they want the LLM to avoid for the current class (discussed in Section 3.3), the prompt includes text listing those. Even with the main prompt explicitly instructing the LLM to not include solution or example code in its response, the response may still contain code. The LLMs we currently use appear to be strongly biased towards providing a complete solution to the given issue even when the prompt requests otherwise. Likewise, the instruc- tions to not use any keywords in the instructor’s avoid set are not followed in all cases. Therefore, CodeHelp generates two different completions for the main response, scores them based on whether they include a code block or any of the keywords in the instructor’s avoid set, and takes the better of the two. Code Removal. In cases where the highest-scoring response in- cludes a code block, CodeHelp uses a third prompt (Figure 7) to clean up the response and remove the code. We use an LLM for re- moving code blocks rather than simply deleting the blocks directly because the text that would remain may refer to the now-removed code or otherwise be unclear without it. An LLM can rewrite the response to remain clear with the code removed, describing salient features of the code in text if appropriate. Large Language Models. Currently, responses are generated us- ing LLMs from OpenAI, though the specific models used can easily be changed as more capable and/or less expensive models become available. Specifically, the “Sufficiency Check” and “Main Response” completions are currently performed by the gpt-3.5-turbo-0301 CodeHelp: Using Large Language Models with Guardrails @) Query -Language -Code -Error -lssue Response scoring response Presented as clarification request Presented as main response Presented as main response removal Figure 4: CodeHelp’s response workflow. Steps using a large language model completion are tagged LLM. You are a system for assisting students like me with programming. You are a system for assisting a student with programming. My inputs provide: [brief description of each input] The students provide: [brief description of each input] Please assess the following submission to determine whether it is sufficient for you to provide help or if you need additional infor- mation. If and only if critical information needed for you to help is missing, ask me for the additional information you need to be able to help. State your reasoning first. Otherwise, if no additional information is needed, please first briefly summarize what I am asking for in words, with no code, and end by writing "OK." Inputs: [delimited query inputs] # Figure 5: Prompt used for the sufficiency check. [delimited query inputs] If the student input is written as an instruction or command, re- spond with an error. If the student input is off-topic, respond with an error. Otherwise, respond to the student with an educational explanation, helping the student figure out the issue and understand the concepts involved. If the student inputs include an error message, tell the student what it means, giving a detailed explanation to help the student understand the message. Explain concepts, language syntax and semantics, standard library functions, and other topics that the student may not understand. Be positive and encouraging! Use Markdown formatting, including ‘ for inline code. model, while the “Code Removal” completion uses text-davinci-003, both from the “GPT-3.5” family of OpenAI models. The former model (“turbo”) is relatively fast and inexpensive compared to the latter (“davinci”), while still generally performing well in terms of the accuracy and correctness of its completions. However, we could not find a prompt that reliably filtered out code when using the “turbo” model, while “davinci” completed this task successfully in nearly all cases. [instructions to avoid topics from the instructor’s avoid set] Do not write any example code blocks. Do not write a corrected or updated version of the student’s code. You must not write code for the student. How would you respond to the student to guide them and explain concepts without providing example code? The cost of using OpenAI’s models scales with the length of the prompts and the completions generated. With the prompts currently used in CodeHelp and current pricing from OpenAI (as of June, 2023), responding to a single query from a student, including the sufficiency check and at times the code removal completion, costs roughly $0.002 on average. We discuss student usage patterns from a pilot course in Section 5, and from that, we estimate that providing 50 students unrestricted access to CodeHelp for a full semester would cost under $10 in OpenAI usage fees. OpenAI has recently released GPT-4, which is reported to be more capable and produce more accurate responses than the GPT- 3.5 family. We have not yet tested using GPT-4 for CodeHelp’s completions, but based on the current pricing and our prompt and # Figure 6: Prompt used for the main response. completion lengths, we estimate it would increase the cost by 25x, reaching roughly $0.05 per student query. Examples. A few examples of queries submitted by students during our pilot illustrate the results of this design. First, in an example where the only input is an instruction to write code for an assigned exercise, we see how CodeHelp provides assistance without writing any code, as intended. The following was written to help a student in a CS class. However, any example code (such as in ``` Markdown delimiters) can give the student an assignment’s answer rather than help them figure it out themselves. We need to provide help without including example code. To do this, rewrite the following to remove any code blocks so that the response explains what the student should do but does not provide solution code. [original response to be rewritten] # Figure 7: Prompt used for code removal. Issue/Question: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. Response: You can use a while loop to iterate over the characters in the string in reverse order. To do this, you can use the len() func- tion to get the length of the string, and use the range() function to generate a sequence of numbers from the length of the string down to 0. Then you can use the str[index] syntax to access each character in the string. To help you understand how this works, think about the following example: Say you have a string my_str = "Hello World". You can use the len() function to get the length of the string, which is 11. Then you can use the range() function to generate a sequence of numbers from 11 down to 0. This sequence of numbers will represent the indices of the characters in the string. Finally, you can use the str[index] syntax to access each character in the string. Using this approach, you can iterate over the characters in the string in reverse order. This will print out each character in the string on a separate line, except backwards. When students provide a problem specification with little or no code, CodeHelp tends to respond with a high-level outline like this as a starting point. When students provide an error message, CodeHelp will typ- ically explain what the message means and suggest a fix. In the following example, the student has not provided the details from the error message, but the LLM is still able to identify where it occurs, providing the student with effective help. # Code: def character_remover ( word , character ): word = word . remove ( character ) return word # Error: Attribute Error Issue/Question: I want this function to print the word, excluding the character. Mark Liffiton, Brad Sheese, Jaromir Savelka, and Paul Denny Response: The error message you are seeing is an Attribute Error, which means that the object you are trying to access does not have the attribute or method you are trying to use. In this case, the object is the string word and the attribute you are trying to use is remove(). The remove() method is not a valid method for strings, so you are getting this error. You can use the replace() method instead. This method takes two parameters: the substring you want to replace and the substring you want to replace it with. In this case, you want to replace the character with an empty string. To do this, you can pass an empty string as the second parameter to the replace() method. This will remove the character from the string. For example, if you have a string word = 'Hello' and a character character = 'l', you can remove the character from the string by calling word.replace(character, ''). This will return a new string with the character removed, 'Heo'. 3.3 For Instructors CodeHelp provides instructors with interfaces that enable them to configure their classes and view their students’ interactions with the system. When configuring a class, an instructor can set the default language for the class (students can still choose other languages when requesting help) and specify a set of keywords that should be avoided in any response to the student, aka an “avoid set.” The avoid set is important because LLMs, with no context about the course for which help is being requested, tend to generate responses using common programming “best practices,” and these practices can be too advanced or otherwise inappropriate for a given course context. For example, in an introductory programming course, an instructor may want students to practice summing the values in a list using a for loop and an accumulator variable, while an LLM might suggest a student use the sum() function to solve such a problem. Instructors may access their students’ queries in the “Instructor View” (Figure 8). This view provides a list of the users in their class with query counts (total and within the past week) and a list of all the student queries. The list of queries shows salient details of each query (with full text for any field appearing when hovering the cursor over it), and any row can be selected to take the instructor to the response view for that query. The list of queries can be filtered to show those from a selected user, and it is searchable (full text) and sortable. Instructors can also download their class data as CSV files. CodeHelp integrates with learning management systems (LMSes) like Moodle or Canvas that support LTI (Learning Tools Interoper- ability). With a small amount of setup, an instructor can provide their students access to CodeHelp via a simple link in their course on the LMS. Via this link, students may access CodeHelp and be au- tomatically authenticated without having to create, manage, or use a separate login. Instructors and TAs are identified automatically by LTI, so they have access to the instructor interfaces in CodeHelp with no additional work. They can then configure their course for student use and monitor their students’ queries and the responses they are receiving. CodeHelp: Using Large Language Models with Guardrails Users Queries id username ‘#queries wk id user time lang” code error issue response (len) helpful sylvester 603 123 2459. Murray 2023-04-14 132m python dloct.“Survived Recode The Oand 1 values used toenc.. main (1213) 23 Emma 117 "1 2458 Sylvester 2023-04-14 1:31pm python _m_mask = df[/Sex'] ==. using pandas dataframes, how t. main (1264) 49 Bong 156 oO 2487 Kayleigh 2023-04-14 1:28pm python dfloc[:,'Pclass'].rep. ‘Type Error: list indices must b Im,using pandas, How do |use_ insufficient, (647) 36 Winnie 15 7 main (@75) 35 | [usmes nt n 2456 Kayleigh 2023-04-14 1:27pm python df loc(:,Pelass'].rep. Typettror: list indices must b Im.using pandas, How.do | use main (675) as or ri 2455 James 2023-04-14 1:22pm python df_big_3=dfisin({/Name& iwant to the date frame, insufficient (792) main (1034) 19 Murray 103 1" 2454 Sylvester 2023-04-14 1:17pm python df_sur = df.loc[(dF.locf; using pandas dataframes, how t. main (996) 45 Kayleigh 9s 14 2453. Lynnette 2023-04-14 1:17pm python df view gross =dfset columns ow do create a view of the main (207) 12 Mitchel 89 ° 2452 James 2023-04-14 4:17pm _ python what isthe syntax and documen... main (705) 26 Kerrie % 5 2451 James 2023-04-14 1:16pm python _big_musical = ['The Lion K Type€tror: isin() takes 2 posi, imin pandas, im looking for t. main (769) x Teo rors7 [die)perpace [« M2 3 4 5 6 > 2450 Murray 2023-04-14 1:14pm python import urllib,request.as reque, Use -locl] to. replace the 1,2 main (825) 1610170 0f 2569 | 10 v|perpage |< 1 18 16 17 18 19. 257 > export csv | Search Figure 8: An instructor’s view of student help requests. The full contents of each field are displayed in a tooltip when the user hovers a mouse pointer over it. Note that real usernames have been replaced with pseudonyms. 4 LIMITATIONS AND RISKS CodeHelp is subject to many of the known limitations and risks of using LLMs. In particular, completions can be factually incorrect and can include harmful biases. The problem of inaccuracies in the LLM responses (sometimes called “hallucination” or “confabula- tion”) is present in CodeHelp with the models it is currently using. Sometimes, the response contains one or more false statements, and this may confuse or mislead the user. Users are sensitised to this issue via the prominent notice above each response saying “Remember: It will not always be correct!” In our experience, when inaccuracies did occur, they were often in a particular detail of the response, which still gave correct high-level guidance or pointed the user in the right direction. In our and our students’ experiences, the rate of inaccuracies is low enough for the tool to still be valuable and worth the students’ time, and as models improve, the accuracy will improve. LLMs can learn harmful biases such as gender or racial stereo- types from their training data, which can then be reflected in the completions they generate. This is a well-known and heavily studied issue in language model research [36], and it has been an important issue to the computing education community as well [1]. While the models used by CodeHelp have been specifically trained and improved by OpenAI to reduce these biases, some still exist [37]. These models generally do not make offensive statements unless one actively crafts a prompt to elicit one, but for example they might respond in a way that implicitly reflects a common stereotype. This is highly unlikely to occur in the context of requesting help on a specific programming issue, but the possibility exists. The above issues apply to most LLM-based tools, and the likeli- hood of an LLM’s response being incorrect, harmful, off-topic, or otherwise “off the rails” increases with additional rounds of user input and model response. Therefore, by design, every query to CodeHelp is a one-shot request, independent of any others and with no possibility for follow-up or dialogue. This limits the use- fulness of the system, as asking a follow-up question or requesting additional information in the context of an initial response could be very helpful, but the one-shot limitation is imposed to mitigate many of the risks of using LLMs. Users can submit revised queries with additional information or questions informed by an earlier response if they choose to. 5 EXPERIENCES AND RESULTS We used CodeHelp in two sections of an undergraduate introductory- level computer- and data-science course taught by an author of this paper in the Spring semester of 2023. Fifty two students completed the course. Of those students, our analyses includes data from 49 who used CodeHelp at least once during the semester, and data from 45 who completed a survey about using CodeHelp at the end of the semester. The course is designed to serve a broad audience and attracts students from across the institution who take the course to meet general education requirements or to meet requirements for data-analytic or data-science related credentials. The course provides twelve weeks of instruction in Python foun- dations and three weeks of instruction in Pandas2 and Seaborn3. The format of the course is “flipped,” with students responsible for reading course materials prior to class, while class time is spent working through assignments on lab computers. The instructor and a TA assist students and provide instruction/support as needed. CodeHelp was introduced in the fourth week of the semester with a quick demonstration in class. During class, students were en- couraged to use CodeHelp for assistance first before asking the instructor or TA for help, but they were otherwise free to make their own choices about when and how to use it. 5.1 Student Use Even with no firm requirement to do so, students used CodeHelp consistently throughout the semester. Figure 9 shows that roughly half of the class used CodeHelp each week, and we saw that roughly 70% of the students used CodeHelp in four or more different weeks. We also observed a wide range of intensity of use between students. Roughly 80% of the class submitted 10 or more queries (indicating more than initial trial usage), roughly 50% submitted 30 or more, and seven of the 49 submitted over 100 queries, including one student with more than 600 queries. The heatmap in Figure 10 shows the usage concentrated during two separate class sessions (1 and 2pm on Mon/Wed/Fri) and before assignments were due on Saturday. Otherwise, there was some use across nearly all hours, including many when no instructor or TA would have been available. Overall, 2Pandas. Available at: https://pandas.pydata.org/ [accessed 2023-06-20] 3Seaborn. Available at: https://seaborn.pydata.org/ [accessed 2023-06-20] ~ 3 1 & o a 8 1 40 - Percentage of Students Week Figure 9: Percentage of the class (y axis) using CodeHelp each week (x axis) across the semester [7 = spring break]. Note that the y axis scale only extends to 70. The figure shows consistent use across the whole semester. the continuing, consistent usage strongly suggests that the students generally found the tool beneficial. 5.2 Student Survey At the end of the course we distributed an online survey to un- derstand students’ perceptions of CodeHelp. Taking the survey was optional, but students did receive extra-credit for completing it. A total of 45 students (87 percent of the class) completed the survey. Table 1 shows the results for a selection of questions about students’ perceptions of the tool and its value to them. Overall, stu- dents found it valuable, and a large majority (95%) were interested in using it in future CS courses. For additional detail, the survey included the following open- response questions, which were designed to elicit both positive and negative responses: • Q1: What did you find most beneficial about using Code- Help? • Q2: Do you think there is anything negative about students using CodeHelp? In general, responses were relatively short but tended to be longer for the first question on beneficial aspects (word count; M = 16.2, SD = 10.3) compared to the second question on negative aspects (M = 12.0, SD = 13.0). To understand the patterns present in the responses, we conducted a thematic analysis in which interesting features of each response were extracted as codes and then collated into higher-level themes [2]. We identified five prominent themes in the response to Q1, highlighted in bold in the text that follows. The most prominent theme by a clear margin, appearing in 19 of the student responses, was around “availability” and specifi- cally that students valued the convenience of being able to ask for assistance outside of the classroom when TAs and the professor were busy or unavailable. Responses representative of this theme include: “it was a tool that was always there when I needed it, I didn’t have to go to office or TA hours or email” and “the ability to get help without talking to professor or TA”. Mark Liffiton, Brad Sheese, Jaromir Savelka, and Paul Denny 07:00 09:00 150 11:00 125 a s 13:00 | — | @ ic) ' pT pT mz = Q 15:00 =I 100 8 ‘S 17:00 i-—| 5 oa 2 19:00 {——_} —— ® = g = 21:00 — — — 50 o — F 23:00 — 01:00 — P25 03:00 Sun Mon Tue Wed = Thu Fri Sat Day of Week Figure 10: Queries by hour (y axis) and day (x axis) over the whole term. The time span between 4 and 7 AM is not shown due to no activity. The high activity blocks on Mon, Wed, and Fri correspond to the times students were in the classroom. The higher activity on Saturday evening is prior to a recurring deadline for weekly assignments. Many students (11) explicitly appreciated that CodeHelp could aid them in “fixing errors”, which was the next most common theme. This included getting help to understand error messages and producing explanations of errors. The following are two ex- amples of typical quotes supporting this theme: “it was helpful in understanding some of the error message we hadn’t learned about in class” and “it really helps with trouble shooting when it comes to semantic errors”. One interesting theme that emerged (10 students), distinct from the “availability” of CodeHelp, was that it supported “indepen- dence” by enabling students to make progress without the need to seek external help when they were stuck. This included provid- ing initial support to students who had difficulty starting work, nudging students in the right direction when they were close to a solution, and helping students who were anxious to ask for help without the fear of embarrassment. Comments that supported this theme included “It was nice to have a source to ask when I was unsure how to begin coding”, “it helped lead me in the right direction if I almost had the right code” and “I felt like I could ask it any question, even dumb ones, which I often did to avoid embarrassing myself in front of the Professor or TA”. The remaining themes, which were less common, focused on the “speed” (6) with which students could make progress or obtain feedback and the use of CodeHelp to assist with “learning/un- derstanding” (7). Typical comments aligning with these themes included“Helped me work faster” and “it helped understand the code I was writing sometimes”. Students also appreciated that CodeHelp would provide guidance rather than directly revealing the solution, as exemplified by the comment “It gave us help on the answer not just the answer itself”. Overall, the responses to Q1 tell a story that CodeHelp was seen as a useful resource for obtaining rapid assis- tance and a complementary tool to traditional TA and instructor support. As to the concerns (Q2), we also identified five prominent themes, again highlighted in bold. Around half of the students (24) stated that they had “no concerns”. Some of the students would even suggest the use of the tool should have been more extensive: “We CodeHelp: Using Large Language Models with Guardrails Table 1: Results for selected questions in the student survey (𝑛 = 45 of 52 students). Rows may not sum to 100% due to rounding. Strongly Agree Agree Disagree Strongly Disagree CodeHelp helped me complete my work successfully. CodeHelp helped me learn the course material. If I took more Computer Science courses, I would like to be able to use CodeHelp in those classes. 9% 7% 31% 71% 56% 64% 18% 33% 4% 2% 4% 0% should even use it during quizzes”. Others explained why they did not have any concerns: “No, absolutely not, especially considering it never handed me the answer on a silver platter.” The most prominent theme as to the concerns was the perceived “difficulty” in using CodeHelp. Multiple students (14) stated that the tool is difficult to use when the problem is not understood: “sometimes i didnt know exactly what to ask.. but i usually got there eventually” and “I did not like how hard it was to ask something I do not understand.”. Several students also reported receiving an- swers that were difficult to utilize or not helpful: “There were many times that CodeHelp misunderstood my question and gave me advice which confused me even more.” and “Sometimes it gives really strange responses that are not related to the problem”. CodeHelp was easy to introduce to the class. As an instructional resource, its utility is immediately and obviously apparent. Stu- dents required little convincing to give it a try. While in class, we requested that students ask CodeHelp for help before seeking help from the instructor or teaching assistant. We did not enforce this as a rule but encouraged it throughout the semester. The idea was that CodeHelp could provide an initial level of support and handle rela- tively straightforward but common concerns, such as syntax errors. CodeHelp performed very well in this capacity, and given its flexi- bility and low-cost, it is a great addition to the classroom for this functionality alone. However, CodeHelp also provided much more sophisticated help on a huge range of introductory CS problems throughout the semester. Several students (5) reported that sometimes an answer provided by CodeHelp contained elements that were “not covered” in class and, hence, the students were not expected to have knowledge of those elements. Responses representative of this theme included: “Sometimes it tells you to do code that we haven’t learned in class” and “I would run into the issue where it wanted me to use concepts that I haven’t been taught yet. This is both and good and a bad thing because it can introduce students to resources, but also confuse them.”. A small number of students’ responses (3) were hinting on using CodeHelp without investing proper effort at solving the problem independently (i.e., “over-reliance”). The responses suggest that the students were aware this could have negative effects on their learning, yet, they would still engage in that practice: “ think some people could complete the code without help and by going directly to CodeHelp their limiting themselves” and “I do think that sometimes I can get to dependent on CodeHelp and I have to scale it back a bit.”. Several responses (3) stated that CodeHelp is “not human” and, hence, its capabilities are in some way limited as compared to the assistance provided by an instructor or a TA. However, the responses do not go into much detail as why this might be the case: “less personal” and “No, but it cannot be a substitute for a real person.” One of the responses explained the preference for human assistance in terms of difficulty (see above) of formulating the proper question for CodeHelp: “no but personally I prefer to ask a real person because its difficult to phrase you questions in a way that won’t confuse CodeHelp”. CodeHelp appeared to provide accurate and helpful responses to students the majority of the time. CodeHelp did not “give away the answer” or otherwise become a complete replacement for ac- tively working through problems. It appears to strike a nice balance between providing enough information to move students forward without undermining the intent of the assignments. CodeHelp was a great addition to the course in terms of serving students who had difficulty attending office hours or who needed frequent reassurance or feedback as they worked through assign- ments outside of class time. It was also exceptional in providing a novel avenue for delivering support to students who did not take advantage of traditional avenues of support. For example, some students who seemed uncomfortable, embarrassed, or otherwise re- luctant to ask for help from the instructor or TA had no reservations about asking CodeHelp. CodeHelp sometimes provided assistance that was inconsistent with the content of the class and the knowledge-level of the stu- dents. For example, CodeHelp might suggest solving problems with methods that had not yet been introduced. This was confusing and frustrating for some students. During the semester, the avoid set functionality (Section 3.3) was added to allow the instructor to explicitly prohibit certain kinds of content in CodeHelp responses, which largely resolved the problem. Students sometimes provided too little information describing their problem to get a useful re- sponse and required some coaching to provide detailed or thought- ful descriptions of problems to CodeHelp. 5.3 Instructor Reflections After the conclusion of the semester, the instructor, who is also one of the authors, reflected on what did and did not work: Reviewing student queries submitted to CodeHelp provided an entirely new type of insight into student learning. In comparison to submitted work, the queries were a much more direct and unfiltered look into student thinking as they worked through problems. On some occasions, this feedback guided modifications of assignments and additional class instruction during the semester. Overall, given its great utility in a wide range of circumstances, its ease of use, and low cost, I found CodeHelp to be a tremen- dous asset in my course. I intend to continue using it in all of my introductory courses moving forward. 6 RECOMMENDED PRACTICES Based on our experiences, we have collected a few recommenda- tions for integrating CodeHelp into a class effectively. Initial introduction. When first introducing CodeHelp to stu- dents, motivate its use by sharing some of the benefits identified in this work, as relevant to your course. Explain carefully its strengths and limitations in the context of your course: how it will likely be able to help, and where may it produce incorrect responses. Provide guidance on how to ask for help most effectively. This in- cludes providing the relevant portions of one’s code, identifying and copying the important information from error messages, and providing enough information for the issue to be identified. These are the same skills one needs to effectively communicate issues to instructors or peers. Providing good and bad examples or taking a moment to roleplay a few situations may help here. Demonstrate CodeHelp with a few issues similar to those you expect your stu- dents to encounter. Model how to provide sufficient information and communicate clearly. During Use. Throughout the course, while students are using CodeHelp, it is helpful to view the students’ queries regularly. You can gain detailed insight into where they are struggling at each point in the term that may lead to adapting course plans. Addi- tionally, you might identify students whose usage is not effective (e.g., repeatedly submitting ineffective queries or demonstrating over-reliance), and reach out to them directly to provide guidance or a nudge. Instructors and TAs should sample CodeHelp’s responses in each section of the course to spot and mitigate issues. For example, if CodeHelp suggests a technique, function, or concept that does not fit the design of your course, you can add that to the avoid set (Section 3.3) to prevent it from being used in future responses. 7 CONCLUSION AND FUTURE WORK This work shows that LLMs, when properly implemented and inte- grated into a learning environment, can be a valuable aid to both students and educators. We developed CodeHelp to provide imme- diate, high-quality support to students working on programming exercises while mitigating the risk of fostering an over-reliance on the automated assistance. Providing an automated option for this kind of help can increase the level of support students receive throughout a course due to a combination of being constantly avail- able and avoiding the anxiety associated with asking a professor or TA for help. In our pilot study, students found CodeHelp to be a welcome addition to direct support from a professor and teaching assistants. Going forward, we intend to continue developing and improv- ing CodeHelp. The “avoid set” functionality proved to be critical for obtaining course-appropriate responses in many cases, and we Mark Liffiton, Brad Sheese, Jaromir Savelka, and Paul Denny plan to give instructors more ways to provide context about their courses and thus further tailor the LLM responses for their students. Additionally, we plan to explore different forms or levels of inter- vention that might be appropriate depending on the complexity of the task, the experience level of the student, or even the specific learning objectives of the course. And we see many opportunities for the tool to be more individualized, adapting to the needs of each student. For example, it could record and maintain information about each individual student’s mastery of different topics, using that to guide the responses generated for them. While encouraging, this work presents only an initial exploration into the effective deployment of LLMs in computing education. For example, while students positively rated CodeHelp and the instruc- tor found it easy to use and deploy, future work should establish more robust metrics for gauging efficacy, such as measuring impact on student learning outcomes or comparing student performance in classrooms that use CodeHelp to those that do not. We also recognize that further work needs to be conducted with larger, more diverse populations of students. It would also be inter- esting to deploy CodeHelp in different educational settings, such as in distance learning or self-paced programming courses, to evaluate its flexibility and adaptability. Our findings could have implications beyond computing educa- tion. LLMs such as those used in CodeHelp could potentially be adapted to support learning in other domains. We hope that our work serves as an impetus for other researchers and educators to explore the use of LLMs in diverse educational contexts, continuing the dialogue around the opportunities and challenges they present. REFERENCES [1] Brett A Becker, Paul Denny, James Finnie-Ansley, Andrew Luxton-Reilly, James Prather, and Eddie Antonio Santos. 2023. Programming Is Hard-Or at Least It Used to Be: Educational Opportunities and Challenges of AI Code Generation. In Proceedings of the 54th ACM Technical Symposium on Computer Science Education V. 1. 500–506. [2] Virginia Braun and Victoria Clarke. 2006. Using thematic analysis in psychology. Qualitative Research in Psychology 3, 2 (2006), 77–101. https://doi.org/10.1191/ 1478088706qp063oa [3] Peter Brusilovsky, Barbara J Ericson, Cay S Horstmann, and Christian Servin. 2023. The Future of Computing Education Materials. (2023). [4] Gustavo Carreira, Leonardo Silva, Antonio Jose Mendes, and Hugo Goncalo Oliveira. 2022. Pyo, a Chatbot Assistant for Introductory Programming Students. In 2022 International Symposium on Computers in Education (SIIE). IEEE, Coimbra, Portugal, 1–6. https://doi.org/10.1109/SIIE56031.2022.9982349 [5] Bei Chen, Fengji Zhang, Anh Nguyen, Daoguang Zan, Zeqi Lin, Jian-Guang Lou, and Weizhu Chen. 2022. CodeT: Code Generation with Generated Tests. arXiv:2207.10397 [cs.CL] [6] 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. 2021. Evaluating large language models trained on code. arXiv:2107.03374 [cs.LG] Jonathan E Collins. 2023. Policy Solutions: Policy questions for ChatGPT and artificial intelligence. Phi Delta Kappan 104, 7 (2023), 60–61. [8] Tyne Crow, Andrew Luxton-Reilly, and Burkhard Wuensche. 2018. Intelligent tutoring systems for programming education: a systematic review. In Proceed- ings of the 20th Australasian Computing Education Conference. ACM, Brisbane Queensland Australia, 53–62. https://doi.org/10.1145/3160489.3160492 [9] Paul Denny, Viraj Kumar, and Nasser Giacaman. 2023. Conversing with Copi- lot: Exploring Prompt Engineering for Solving CS1 Problems Using Natu- ral Language. In Proceedings of the 54th ACM Technical Symposium on Com- puter Science Education V. 1. ACM, Toronto ON Canada, 1136–1142. https: //doi.org/10.1145/3545945.3569823 [10] Paul Denny, Juho Leinonen, James Prather, Andrew Luxton-Reilly, Thezyrie Amarouche, Brett A. Becker, and Brent N. Reeves. 2023. Promptly: Using Prompt Problems to Teach Learners How to Effectively Utilize AI Code Generators. arXiv:2307.16364 [cs.HC] CodeHelp: Using Large Language Models with Guardrails [11] Paul Denny, James Prather, Brett A. Becker, James Finnie-Ansley, Arto Hellas, Juho Leinonen, Andrew Luxton-Reilly, Brent N. Reeves, Eddie Antonio San- tos, and Sami Sarsa. 2023. Computing Education in the Era of Generative AI. arXiv:2306.02608 [cs.CY] James Finnie-Ansley, Paul Denny, Brett A Becker, Andrew Luxton-Reilly, and James Prather. 2022. The robots are coming: Exploring the implications of openai codex on introductory programming. In Proceedings of the 24th Australasian Computing Education Conference. 10–19. https://doi.org/10.1145/3511861.3511863 [13] Zhikai Gao, Sarah Heckman, and Collin Lynch. 2022. Who Uses Office Hours? A Comparison of In-Person and Virtual Office Hours Utilization. In Proceedings of the 53rd ACM Technical Symposium on Computer Science Education - Volume 1 (Providence, RI, USA) (SIGCSE 2022). Association for Computing Machinery, New York, NY, USA, 300–306. https://doi.org/10.1145/3478431.3499334 [14] Arto Hellas, Juho Leinonen, Sami Sarsa, Charles Koutcheme, Lilja Kujanpää, and Juha Sorva. 2023. Exploring the Responses of Large Language Models to Beginner Programmers’ Help Requests. arXiv:2306.05715 [cs.CY] [15] Sajed Jalil, Suzzana Rafi, Thomas D. LaToza, Kevin Moran, and Wing Lam. 2023. ChatGPT and Software Testing Education: Promises & Perils. In 2023 IEEE International Conference on Software Testing, Verification and Valida- tion Workshops (ICSTW). IEEE. https://doi.org/10.1109/icstw58534.2023.00078 arXiv:arXiv:2302.03287 [16] Enkelejda Kasneci, Kathrin Sessler, Stefan Küchemann, Maria Bannert, Daryna Dementieva, Frank Fischer, Urs Gasser, Georg Groh, Stephan Günnemann, Eyke Hüllermeier, Stepha Krusche, Gitta Kutyniok, Tilman Michaeli, Claudia Nerdel, Jürgen Pfeffer, Oleksandra Poquet, Michael Sailer, Albrecht Schmidt, Tina Seidel, Matthias Stadler, Jochen Weller, Jochen Kuhn, and Gjergji Kasneci. 2023. ChatGPT for good? On opportunities and challenges of large language models for education. Learning and Individual Differences 103 (2023), 102274. https://doi.org/10.1016/j.lindif.2023.102274 [17] Majeed Kazemitabaar, Justin Chow, Carl Ka To Ma, Barbara J. Ericson, David Weintrop, and Tovi Grossman. 2023. Studying the Effect of AI Code Generators on Supporting Novice Learners in Introductory Programming. In Proceedings of the 2023 CHI Conference on Human Factors in Computing Systems (Hamburg, Germany) (CHI ’23). Association for Computing Machinery, New York, NY, USA, Article 455, 23 pages. https://doi.org/10.1145/3544548.3580919 [18] Hieke Keuning, Johan Jeuring, and Bastiaan Heeren. 2019. A Systematic Lit- erature Review of Automated Feedback Generation for Programming Exer- cises. ACM Transactions on Computing Education 19, 1 (March 2019), 1–43. https://doi.org/10.1145/3231711 [19] Mario Konecki, Nikola Kadoic, and Rok Piltaver. 2015. Intelligent assistant for helping students to learn programming. In 2015 38th International Convention on Information and Communication Technology, Electronics and Microelectronics (MIPRO). IEEE, Opatija, Croatia, 924–928. https://doi.org/10.1109/MIPRO.2015. 7160406 Juho Leinonen, Paul Denny, Stephen MacNeil, Sami Sarsa, Seth Bernstein, Joanne Kim, Andrew Tran, and Arto Hellas. 2023. Comparing Code Explanations Created by Students and Large Language Models. arXiv:2304.03938 [cs.CY] [21] Mariam Mahdaoui, Said Nouh, My Seddiq ELKASMI Alaoui, and Mounir Sadiq. 2022. Comparative study between automatic hint generation approaches in Intelligent Programming Tutors. Procedia Computer Science 198 (2022), 391–396. https://doi.org/10.1016/j.procs.2021.12.259 Jessica McBroom, Irena Koprinska, and Kalina Yacef. 2022. A Survey of Auto- mated Programming Hint Generation: The HINTS Framework. Comput. Surveys 54, 8 (Nov. 2022), 1–27. https://doi.org/10.1145/3469885 [23] Nhan Nguyen and Sarah Nadi. 2022. An empirical evaluation of GitHub copilot’s code suggestions. In Proceedings of the 19th International Conference on Mining Software Repositories. ACM, Pittsburgh Pennsylvania, 1–5. https://doi.org/10. 1145/3524842.3528470 [24] Chinedu Wilfred Okonkwo and Abejide Ade-Ibijola. 2021. Python-Bot: A Chatbot for Teaching Python Programming. Engineering Letters 29 (02 2021), 25–34. [25] Chinedu Wilfred Okonkwo and Abejide Ade-Ibijola. 2022. Revision-Bot: A IAENG Chatbot for Studying Past Questions in Introductory Programming. International Journal of Computer Science 49, 3 (2022). [26] Zachary A. Pardos and Shreya Bhandari. 2023. Learning gain differences between ChatGPT and human tutor generated algebra hints. arXiv:2302.06871 [cs.CY] James Prather, Paul Denny, Juho Leinonen, Brett A Becker, Ibrahim Albluwi, Michael E Caspersen, Michelle Craig, Hieke Keuning, Natalie Kiesler, Tobias Kohn, et al. 2023. Transformed by Transformers: Navigating the AI Coding Revolution for Computing Education: An ITiCSE Working Group Conducted by Humans. In Proceedings of the 2023 Conference on Innovation and Technology in Computer Science Education V. 2. 561–562. James Prather, Brent N. Reeves, Paul Denny, Brett A. Becker, Juho Leinonen, Andrew Luxton-Reilly, Garrett Powell, James Finnie-Ansley, and Eddie Antonio Santos. 2023. "It’s Weird That it Knows What I Want": Usability and Interactions with Copilot for Novice Programmers. arXiv:2304.02491 [cs.HC] 27 28 [29] Margot Rutgers. 2021. Duckbot: A chatbot to assist students in programming tutorials. Master’s thesis. University of Twente. [30] Sami Sarsa, Paul Denny, Arto Hellas, and Juho Leinonen. 2022. Automatic Gen- eration of Programming Exercises and Code Explanations Using Large Language Models. In Proceedings of the 2022 ACM Conference on International Computing Education Research V.1. ACM, Lugano and Virtual Event Switzerland, 27–43. https://doi.org/10.1145/3501385.3543957 Jaromir Savelka, Arav Agarwal, Marshall An, Chris Bogart, and Majd Sakr. 2023. Thrilled by Your Progress! Large Language Models (GPT-4) No Longer Struggle to Pass Assessments in Higher Education Programming Course. In Proceedings of the 2023 ACM Conference on International Computing Education Research V.1. ACM. Jaromir Savelka, Arav Agarwal, Christopher Bogart, and Majd Sakr. 2023. Large Language Models (GPT) Struggle to Answer Multiple-Choice Questions about Code. arXiv:2303.08033 [cs.CL] [33] Haoye Tian, Weiqi Lu, Tsz On Li, Xunzhu Tang, Shing-Chi Cheung, Jacques Klein, and Tegawendé F. Bissyandé. 2023. Is ChatGPT the Ultimate Programming Assistant – How far is it? arXiv:2304.11938 [cs.SE] James Walden, Nicholas Caporusso, and Ludiana Atnafu. 2022. A Chatbot for Teaching Secure Programming. In Proceedings of the EDSIG Conference ISSN, Vol. 2473. 4901. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Brian Ichter, Fei Xia, Ed Chi, Quoc Le, and Denny Zhou. 2023. Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. arXiv:2201.11903 [cs.CL] [36] Laura Weidinger, Jonathan Uesato, Maribeth Rauh, Conor Griffin, Po-Sen Huang, John Mellor, Amelia Glaese, Myra Cheng, Borja Balle, Atoosa Kasirzadeh, Court- ney Biles, Sasha Brown, Zac Kenton, Will Hawkins, Tom Stepleton, Abeba Birhane, Lisa Anne Hendricks, Laura Rimell, William Isaac, Julia Haas, Sean Legassick, Geoffrey Irving, and Iason Gabriel. 2022. Taxonomy of Risks Posed by Language Models. In 2022 ACM Conference on Fairness, Accountability, and Trans- parency (Seoul, Republic of Korea) (FAccT ’22). Association for Computing Ma- chinery, New York, NY, USA, 214–229. https://doi.org/10.1145/3531146.3533088 [37] Terry Yue Zhuo, Yujin Huang, Chunyang Chen, and Zhenchang Xing. 2023. Red teaming ChatGPT via Jailbreaking: Bias, Robustness, Reliability and Toxicity. arXiv:2301.12867 [cs.CL]
Title: GEMv2: Multilingual NLG Benchmarking in a Single Line of Code: Summary: Evaluation in machine learning is usually informed by past choices, for example which datasets or metrics to use. This standardization enables the comparison on equal footing using leaderboards, but the evaluation choices become sub-optimal as better alternatives arise. This problem is especially pertinent in natural language generation which requires ever-improving suites of datasets, metrics, and human evaluation to make definitive claims. To make following best model evaluation practices easier, we introduce GEMv2. The new version of the Generation, Evaluation, and Metrics Benchmark introduces a modular infrastructure for dataset, model, and metric developers to benefit from each others work. GEMv2 supports 40 documented datasets in 51 languages. Models for all datasets can be evaluated online and our interactive data card creation and rendering tools make it easier to add new datasets to the living benchmark. # GEMv2: Multilingual NLG Benchmarking in a Single Line of Code Sebastian Gehrmann11, Abhik Bhattacharjee3, Abinaya Mahendiran24, Alex Wang25, Alexandros Papangelis2, Aman Madaan4, Angelina McMillan-Major15, Anna Shvets10, Ashish Upadhyay32, Bingsheng Yao31, Bryan Wilie39, Chandra Bhagavatula1, Chaobin You41, Craig Thomson43, Cristina Garbacea47, Dakuo Wang20,26, Daniel Deutsch48, Deyi Xiong41, Di Jin2, Dimitra Gkatzia8, Dragomir Radev51, Elizabeth Clark11, Esin Durmus34, Faisal Ladhak7, Filip Ginter49, Genta Indra Winata39, Hendrik Strobelt16,20, Hiroaki Hayashi4,33, Jekaterina Novikova50, Jenna Kanerva49, Jenny Chim29, Jiawei Zhou14, Jordan Clive6, Joshua Maynez11, João Sedoc25, Juraj Juraska44, Kaustubh Dhole9, Khyathi Raghavi Chandu22, Laura Perez-Beltrachini45, Leonardo F. R. Ribeiro38, Lewis Tunstall15, Li Zhang48, Mahima Pushkarna11, Mathias Creutz46, Michael White40, Mihir Sanjay Kale11, Moussa Kamal Eddine53, Nico Daheim30, Nishant Subramani1,21, Ondrej Dusek5, Paul Pu Liang4, Pawan Sasanka Ammanamanchi17, Qi Zhu42, Ratish Puduppully45, Reno Kriz18, Rifat Shahriyar3, Ronald Cardenas45, Saad Mahamood52, Salomey Osei21, Samuel Cahyawijaya13, Sanja Štajner35, Sebastien Montella27, Shailza Jolly37, Simon Mille28, Tahmid Hasan3, Tianhao Shen41, Tosin Adewumi19, Vikas Raunak23, Vipul Raheja12, Vitaly Nikolaev11, Vivian Tsai11, Yacine Jernite15, Ying Xu47, Yisi Sang36, Yixin Liu51, Yufang Hou16 1Allen Institute for AI, 2Amazon Alexa AI, 3Bangladesh University of Engineering and Technology, 4Carnegie Mellon University, 5Charles University, 6Chattermill, 7Columbia University, 8Edinburgh Napier University, 9Emory University, 10Fablab in Paris by Inetum, 11Google Research, 12Grammarly, 13HKUST, 14Harvard University, 15Hugging Face, 16IBM Research, 17IIIT Hyderabad, 18Johns Hopkins University, 19Luleå University of Technology, 20MIT-IBM Watson AI Lab, 21Masakhane, 22Meta AI, 23Microsoft, 24Mphasis NEXT Labs, 25New York University, 26Northeastern University, 27Orange Labs, 28Pompeu Fabra University, 29Queen Mary University of London, 30RWTH Aachen University, 31Rensselaer Polytechnic Institute, 32Robert Gordon University, 33Salesforce Research, 34Stanford University, 35Symanto Research, 36Syracuse University, 37TU Kaiserslautern, 38Technical University of Darmstadt, 39The Hong Kong University of Science and Technology, 40The Ohio State University, 41Tianjin University, 42Tsinghua University, 43University of Aberdeen, 44University of California, Santa Cruz, 45University of Edinburgh, 46University of Helsinki, 47University of Michigan, 48University of Pennsylvania, 49University of Turku, 50Winterlight Labs, 51Yale University, 52trivago N.V., 53École Polytechnique gehrmann@google.com, gem-benchmark@googlegroups.com # Abstract Evaluation in machine learning is usually in- formed by past choices, for example which datasets or metrics to use. This standardiza- tion enables the comparison on equal footing using leaderboards, but the evaluation choices become sub-optimal as better alternatives arise. This problem is especially pertinent in natu- ral language generation which requires ever- improving suites of datasets, metrics, and hu- man evaluation to make definitive claims. To make following best model evaluation prac- tices easier, we introduce GEMv2. The new version of the Generation, Evaluation, and Metrics Benchmark introduces a modular in- frastructure for dataset, model, and metric de- velopers to benefit from each others work. GEMv2 supports 40 documented datasets in 51 languages. Models for all datasets can be evaluated online and our interactive data card creation and rendering tools make it easier to add new datasets to the living benchmark. # Introduction The standard evaluation process in natural language processing involves comparisons to prior results in a fixed environment, often facilitated through benchmarks and leaderboards. This process, if exe- cuted correctly, can advance reproducibility (Belz et al., 2021) and standardize evaluation choices that lead to better dataset diversity. But static bench- marks also prevent the adoption of new datasets or metrics (Raji et al., 2021), and many evaluation ad- vancements are thus put aside. That means that the focus on surpassing the best prior reported scores reinforces outdated evaluation designs. Further- more, this process ignores properties that do not match the leaderboard metric (Ethayarajh and Ju- rafsky, 2020; Bowman and Dahl, 2021; Dehghani et al., 2021). This issue is particularly pertinent in natural language generation (NLG) since the model quality cannot be estimated using accu- racy and instead, NLG relies on automatic and human evaluation approaches that constantly im- prove (Gehrmann et al., 2022; Kasai et al., 2022). To bridge the gap between advantages of leader- boards and in-depth and evolving evaluations, the Generation, Evaluation, and Metrics bench- mark (GEM, Gehrmann et al., 2021) proposed a “living” benchmark. As such, GEM is participatory in that contributors propose new datasets and ex- pand the selection of metrics. Model developers using GEM retain full agency over the evaluation process but are able to choose from a wider range of tasks and metrics. GEM further introduced eval- uation suites (Mille et al., 2021; Dhole et al., 2021) that are compatible with its datasets and test various robustness and fairness aspects of models. (A) This dataset is a data-to-text dataset in the basketball domain. The input are tables in a fixed format with. statistics about a game (in English) and the target is a RotoWire_English-German WEBSITE PAPER Website ACL Anthology German translation of the originally English description, The translations were done by professional translators with basketball experience. The dataset can be used to evaluate the cross-lingual data-to-text capabilities of a model with complex inputs. You can load the dataset via’ os Import datasets data = datasets./oad_dataset((GEM/RotoWire_English- German’) The data loader can be found here Enalish , (B) — quick-Use CONTACT NAME © MULTILINGUAL? © ° Hiroaki Hayashi yes ADDITIONAL conrains pur © ANNOTATIONS? © unlikely automatically created (C) __ Dataset Details COVERED LANGUAGES AUTHORS Graham Neubig (Carnegie Mellon University), Hiroaki Hayashi (Carnegie Mellon University) ucense © COMMUNICATIVE GOAL cc-by-4.0: Creative ‘Commons Attribution 4.0 International Describe a basketball game given its box score table (and possibly a summary in a foreign language). German Expand all Collapse All Where to find the Data and its Documentation Dataset Overview Languages and Intended Use Credit Dataset Structure Figure 1: One of the data cards for GEM datasets. (A) shows the header which has the name, a summary, a code example, and links to the loader and relevant papers and websites, alongside an author list. (B) is the Quick- Use section which summarizes the most important aspect of a dataset, including language(s), PII, and licensing information. (C) is the detailed view which has multiple sections like “Dataset Overview”. Each section provides a glance at categories of included questions, and expands to full details on click. We uncovered several shortcomings in GEMv1 that hindered its scaling and adoption: (1) Central- ized data management made adding new datasets too complex. (2) Computing all metrics in a sin- gle framework led to dependency issues and was challenging for those with limited compute re- sources. (3) Participants needed more guidance in our dataset documentation process (McMillan- Major et al., 2021) to guarantee data card quality. We introduce GEMv2, a modular and extendable NLG evaluation infrastructure which allows for continuous integration of newly developed datasets. We release a data card collection and rendering tool that makes it easier to follow for both card creators and readers. These improvements led to an expansion of GEM from 13 to 40 tasks and from 18 to 51 supported languages. We also introduce an online evaluation process that collects model outputs and computes metrics for all datasets. # 2 Features and Functionality Since best evaluation practices change over time, the infrastructure is modular and maintainable and allows for dataset and metrics additions so they are compatible with all other features. Model de- velopers are able to use new datasets and metrics without any changes to their existing setup. In this section, we describe the supported user [J]ourneys for various stakeholders in generation research. J1 - Document a Dataset Documentation is a re- quirement for any dataset in GEM. Our data card template is based on that by McMillan-Major et al. (2021), which was revised using the Data Card Playbook (Pushkarna et al., 2022). A data card can be filled out via an interactive form that provides in- structions for each field to account for differences in expertise of the documentation writers.1 The 1huggingface.co/spaces/GEM/ DatasetCardForm form can load existing data cards to make updates. J2 - Choose a Dataset The data card viewer presents information at multiple levels of details in separate columns. Anyone can quickly get a high-level overview of a dataset to make an appro- priate selection, or look for detailed information on a documentation category (see Figure 1). J3 - Create a Data Loader Each dataset has a separate repository at huggingface.co/GEM, with a loader using the Datasets library (Lhoest et al., 2021).2 Through this, all supported datasets can be loaded via the same code, from datasets import load_dataset data = load_dataset( 'GEM/$dataset_name', '$config_name') where $dataset_name is the name of the dataset and $config_name is the (optional) specification of the dataset configuration to use. To stratify how datasets are accessed, they are im- plemented according to the following conventions: • linearized_input: Linearization pro- cesses convert structured input to a string. For reproducibility, we implement linearization schemes following earlier work (e.g., Saleh et al., 2019; Kale and Rastogi, 2020; Pudup- pully and Lapata, 2021). target and references: To make all datasets compatible with standard training and evaluation schemes, all datasets have a string target and a list of string references field. • gem_id: To be able to track outputs even for shuffled datasets, each GEM dataset as- signs a unique ID to all examples, which the evaluation library uses to unshuffle. J4 - Evaluate a Model Model outputs can be eval- uated locally using the gem-metrics library or online which will add the outputs to our result overview (J6).3 Both methods require a standard- ized input format that specifies the dataset and split and which allows us to evaluate all 100+ data splits via the call gem_metrics outputs.json. J5 - Add a new Metric In gem-metrics, each metric implements a compute() function and our library handles caching, parallelism, tokeniza- tion, etc. To avoid dependency conflicts, a metric can optionally specify a docker environment, as suggested by Deutsch and Roth (2022). 2Documentation on how to add new datasets can be found # at gem-benchmark.com/tutorials. 3huggingface.co/spaces/GEM/ submission-form from .texts import Predictions from .texts import References from .metric import ReferencedMetric class NewMetric(ReferencedMetric): def _initialize(self): """Load models and artifacts.""" pass def compute( self, cache, predictions: Predictions, references: References) -> Dict: """Compute the metric.""" pass J6 - Use Prior Results Comparisons to prior work often only copy reported numbers which could be computed using different evaluation parameters, and a lack of released model outputs frequently prevents a fair side-by-side comparison outside of leaderboards (Gehrmann et al., 2022). To improve comparability, we add every submission to the on- line metrics computation to a growing corpus of model outputs which evaluation researchers can use to develop better metrics or to conduct analy- ses. All online submissions also appear in the result exploration tool we released with GEMv1. # 3 Dataset Selection and Loading To identify candidate datasets for GEMv2, we fol- lowed the SuperGLUE process (Wang et al., 2019) which we already used for GEMv1 and solicited tasks to be included from the research community. Our request to suggest multilingual, challenging, and/or interesting NLG tasks led to 40 submissions. To avoid quality judgments, we imposed only three requirements to be selected: (1) dataset authors need to consent, (2) the data needs to be openly available under a permissive license, (3) the task needs to be able to be cast as a text-to-text prob- lem. 27 new tasks were selected in addition to port- ing the 13 existing ones (Gehrmann et al., 2021), and we also redesigned data splits for an existing task (WikiLingua, Ladhak et al., 2020). Three of the datasets are simplification evaluation sets added to the WikiAuto loader (Jiang et al., 2020), while all others have independent data loaders. All data loaders and cards were produced as part of a month-long hackathon, and we invited the original dataset authors and GEM participants to contribute to one or more of the datasets. After- wards, the organizers managed the ongoing main- tenance. New datasets can be added on an ongoing # Response # Question # Slide Data-to-Text Summarization Generation Simplification Paraphrasing Mil Generation Bl Reasoning ™ Generation @ Training Size 0 5 10 <1lk 1k<10k 10k<100k >100k 0 5 10 Count 15 500 . 400 —~ < =o ° < a =300 ° LoD) a 6 z wo e 2200 ic ° ° 100 © % 0 e 15 0 1000 2000 3000 4000 5000 Input Length Figure 2: An overview of the properties of the currently supported datasets in GEM. (Top left) A histogram of the supported task types. The most represented tasks are Data-to-Text, followed by Summarization, Response Generation, and Simplification. (Bottom Left) The frequency of different training corpus sizes for dataset config- urations, broken down by their task types. While some task types are represented across all resource availability levels, some are concentrated on high resource. (Right) An overview of input and target lengths of different dataset configurations according to the mT5 tokenizer (Xue et al., 2021). Summarization tasks have input lengths of over 1,000 while all other tasks remain under 1,000 tokens. There is a lot more between-task variance in output length. Four dataset configurations are hidden due to the axis truncation. basis, as long as the three requirements are fulfilled. GEMv2 currently supports 40 datasets, listed in Appendix A and described in this section. Figure 2 shows the distributions of training ex- ample count, task types, and their input and target lengths. Data-to-text and summarization are most common, followed by response generation. While data-to-text tasks are spread across resource avail- ability categories, summarization datasets tend to be larger. While datasets vary in target length, the median input length tends to remain under 500 tokens, likely motivated by modeling limitations. Exceptions to this are summarization, with input lengths beyond what is supported by most mod- els (e.g., WikiCatSum (Perez-Beltrachini et al., 2019) and XLSum (Hasan et al., 2021)), and a class of data-to-text datasets with the communica- tive goal to generate game summaries from large sports statistic tables (e.g., Hayashi et al., 2019; Thomson et al., 2020; Puduppully et al., 2019a). We put a strong emphasis on language diver- sity, as prior work has found that fewer than 30% of NLG publications (even counting evaluations on machine translation) evaluate on non-English tasks (Gehrmann et al., 2022). While a lot of this focus on English can be traced to a lack of multi- lingual resources, many non-English NLG datasets have been released in recent years (e.g., Hasan et al., 2021; Ladhak et al., 2020; Mille et al., 2020; Cahyawijaya et al., 2021). As shown in Table 2, we support languages across all resource classes in the taxonomy by Joshi et al. (2020). However, the focus on English is still apparent in the number of datasets supporting a particular language, shown in Table 1, where English is far above all other lan- guages. Moreover, most of the language diversity stems from the three highly multilingual datasets XLSum (Hasan et al., 2021), WikiLingua (Ladhak et al., 2020), and data from the surface realization shared task ’20 (Mille et al., 2020). Excluding those, there are 13 datasets supporting non-English languages, 9 of which are exclusively non-English. Of the 40 datasets, 14 have multiple configura- tions which can differ in task setup, languages, their encoding in romanized or original script, or do- main. For example, we modified WikiLingua (Lad- hak et al., 2020) to have splits from and to any of the 18 supported languages, enabling better cross- lingual evaluations. Seventeen datasets have chal- lenge splits, many of which were created for GEM. For example, the challenge set for the conversa- tional weather dataset (Balakrishnan et al., 2019) selects examples from the original test split with complex discourse relations. Count Languages 1 2 3 4 6 8 28 Amharic, Azerbaijani, Bengali, Burmese, Dutch, Gujarati, Hausa, Igbo, Javanese, Kirundi, Kyr- gyz, Marathi, Nepali, Oromo, Pashto, Per- sian, Pidgin, Punjabi, Scottish Gaelic, Ser- bian, Sinhala, Somali, Sundanese, Swahili, Swedish, Tamil, Telugu, Tigrinya, Ukrainian, Urdu, Uzbek, Welsh, Yoruba Czech, Italian, Thai, Turkish, Vietnamese Arabic, Finnish, Hindi, Japanese, Korean, Por- tuguese Indonesian Chinese, German, Russian, Spanish French English Table 1: The languages supported in GEMv2 and in how many of its datasets they appear. # 4 Data Cards Each dataset is accompanied by documentation about how it was created, who created it, how it should be used, and the risks in using it (Bender and Friedman, 2018; Gebru et al., 2018). Our orig- inal data documentation process (McMillan-Major et al., 2021) required filling out a markdown tem- plate following instructions in a separate guide. We analyzed the existing template and the resulting data cards under the dimensions provided in the data card playbook (Pushkarna et al., 2022) and identified the following improvements: • Accountability: It needs to be clear who will maintain and extend the data cards when a dataset changes, when limitations of a dataset are found, or when it is deprecated (Corry et al., 2021). • Utility: The recommended evaluation process for a dataset should be prominently shown. • Quality: We need a process to validate data card completeness and quality. • Impact & Consequences: It needs to be clear that we are curators, not editors, and that critiques reflect on the data, not the creators. Risk & Recommendations I: We need to ex- pand the documentation of potential PII issues. • Risk & Recommendations II: To help decide whether to use a dataset, the card needs to dis- cuss differences from other datasets with similar communicative goals. We modified our template following these insights and to be in line with the playbook approach of dividing between telescope, periscope, and micro- scope questions based on the length of the expected answer. We implemented this template in an inter- active collection tool that can create new cards or Tax. Languages 0 1 # oO 2 3 4 5 West African Pidgin English, Sinhala Azerbaijani, Burmese, Gujarati, Igbo, Javanese, Kirundi, Kyrgyz, Nepali, Oromo, Pashto, Scot- tish Gaelic, Somali, Sundanese, Telugu, Welsh Amharic, Hausa, Marathi, Punjabi, Swahili, Tigrinya, Yoruba Bengali, Indonesian, Tamil, Thai, Ukrainian, Urdu, Uzbek Czech, Dutch, Finnish, Hindi, Italian, Korean, Persian, Portuguese, Russian, Serbian, Swedish, Turkish, Vietnamese Arabic, Chinese, English, French, German, Japanese, Spanish Table 2: Supported languages categorized into the re- source taxonomy by Joshi et al. (2020). load and update existing ones. The tool shows progress bars for the overall answer status and a breakdown for each of the subsections to indicate where more content should be added. The tool fur- ther improves the user experience by conditionally rendering questions based on prior answers, e.g., Is there a risk of PII? → What kind of PII? The output of the tool is a structured json file that we convert into a simple markdown file for the data loader and an optimized web viewer and embedded in our website (Figure 1). The viewer presents im- portant information at the top and splits the detailed rendering into three columns, corresponding to the telescope, periscope, and microscope split. This enables an easy navigation since high-level infor- mation can be found by focusing on the left column, moving toward the right for additional details. The structured format enables us to study trends in dataset construction practices beyond those shown in Section 3. We show some exemplary statistics below, but encourage others to use the publicly available files for their investigations. For example, 20 of the data cards report that PII is un- likely or definitely not included, while it is likely or definitely included in 10. In the free-text explana- tions, we find four different types of justifications for absent PII: The majority (7) stated that the data format or domain was restricted to avoid PII. Two datasets were based on public domain data (e.g., Wikipedia) and another two used fully simulated data. One response described that crowd raters were instructed to avoid any mention of PII. We also find that multiple of the PII-likely datasets only use public domain data, indicating that there may be confusion about PII definitions. Investigating the licensing status of our datasets, Sources results a Views model performance —— Submits predictions ® Results Space Pushes Submission Space Downloads predictions to AutoTrain ° Submits jobs Pulls results across ™ submissions Results dataset Prediction GEM Evaluation dataset dataset dataset Pushes metrics Downloads references hf_benchmarks Open-source library that runs evaluation scripts H AutoTrain ; Figure 3: System architecture for hosting GEM on the Hugging Face Hub we find that the vast majority uses different variants of the Creative Commons licenses (22), 4 use the MIT license and 3 use Apache 2.0. The majority of datasets allows the unrestricted use of datasets, with 8 limiting the use to non-commercial use cases. This distribution is likely skewed due to our selec- tion restriction to publicly available datasets. Another typically hidden aspect is the data sourc- ing. Our datasets present an almost even split be- tween automatically-, crowdworker-, and expert- created datasets, with crowdworker-created ones being slightly more common, possibly confounded if experts were hired through crowdworking plat- forms, as was done for SQuality (Wang et al., 2022). It may thus also possible to compare which of these collection methods leads to more insight- ful modeling results. We follow up by asking which crowdworking platform was used and un- surprisingly, Amazon Mechanical Turk was the most frequent answer, followed by participatory experiments and other non-specified platforms. # 5 System Design To support the automatic evaluation of outputs, we use the Hugging Face Hub to integrate datasets, metrics, and user interfaces for GEM users to sub- mit their outputs. The system architecture is shown in Figure 3, and consists of five main components: Spaces We host Streamlit applications on Spaces4 4huggingface.co/spaces for the submission of predictions, downloading of results, and visualization of model performance. Datasets Dataset repositories are used to host the datasets, submissions, evaluations, and results. AutoTrain We use AutoTrain5, Hugging Face’s AutoML platform, to run all evaluation jobs using Hugging Face Benchmarks, a library that defines how metrics are computed within AutoTrain.6 Metrics We use GEM-metrics to perform the metric computations. In addition to supporting common metrics like BLEU (Papineni et al., 2002) and ROUGE (Lin, 2004), the Docker integration simplifies the calculation of multiple model-based metrics like BLEURT (Sellam et al., 2020). repository with the the model outputs GEM-submissions the Hugging Face Hub. In parallel, an evaluation job is triggered in AutoTrain which downloads the submission from the Hub, along with all the reference splits of the GEM datasets. These references are used to compute a wide variety of NLG metrics via GEM-metrics. The resulting metrics are then pushed to a dataset repository on the Hub, and used to source the visualization of results on the GEM website7 and Space.8 # 5huggingface.co/autotrain 6github.com/huggingface/hf_benchmarks 7gem-benchmark.com 8huggingface.co/spaces/GEM/results # 6 Conclusion We introduce GEMv2 which aims to unify infras- tructure for generation research. We propose a con- sistent workflow from documenting and choosing datasets to loading and evaluating on them while keeping all supported datasets and metrics compati- ble with each other. We demonstrate the scalability of our format by releasing the initial version with support for 40 datasets in 51 languages. Of the supported datasets, 23 are improved through con- figurations, filtering, and re-splitting processes and 17 datasets have challenge sets. Finally, we release a submission tool that computes metrics and makes model outputs available to download for evaluation researchers. Researchers who are interested in inte- grating their dataset are welcome to contact us for support. # References Fernando Alva-Manchego, Louis Martin, Antoine Bor- des, Carolina Scarton, Benoît Sagot, and Lucia Spe- cia. 2020. ASSET: A dataset for tuning and evalu- ation of sentence simplification models with multi- ple rewriting transformations. In Proceedings of the 58th Annual Meeting of the Association for Compu- tational Linguistics, pages 4668–4679, Online. As- sociation for Computational Linguistics. Anusha Balakrishnan, Jinfeng Rao, Kartikeya Upasani, Michael White, and Rajen Subba. 2019. Con- strained decoding for neural NLG from composi- tional representations in task-oriented dialogue. In Proceedings of the 57th Annual Meeting of the As- sociation for Computational Linguistics, pages 831– 844, Florence, Italy. Association for Computational Linguistics. Anya Belz, Shubham Agarwal, Anastasia Shimorina, and Ehud Reiter. 2021. A systematic review of re- producibility research in natural language process- In Proceedings of the 16th Conference of the ing. European Chapter of the Association for Computa- tional Linguistics: Main Volume, pages 381–393, Online. Association for Computational Linguistics. Emily M. Bender and Batya Friedman. 2018. Data statements for natural language processing: Toward mitigating system bias and enabling better science. Transactions of the Association for Computational Linguistics, 6:587–604. Chandra Bhagavatula, Ronan Le Bras, Chaitanya Malaviya, Keisuke Sakaguchi, Ari Holtzman, Han- nah Rashkin, Doug Downey, Wen tau Yih, and Yejin Choi. 2020. Abductive commonsense reasoning. In International Conference on Learning Representa- tions. Samuel R. Bowman and George Dahl. 2021. What will it take to fix benchmarking in natural language un- In Proceedings of the 2021 Confer- derstanding? ence of the North American Chapter of the Associ- ation for Computational Linguistics: Human Lan- guage Technologies, pages 4843–4855, Online. As- sociation for Computational Linguistics. Bill Byrne, Karthik Krishnamoorthi, Saravanan Ganesh, and Mihir Kale. 2021. TicketTalk: To- ward human-level performance with end-to-end, transaction-based dialog systems. In Proceedings of the 59th Annual Meeting of the Association for Com- putational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), pages 671–680, Online. Association for Computational Linguistics. Bill Byrne, Karthik Krishnamoorthi, Chinnadhurai Sankar, Arvind Neelakantan, Ben Goodrich, Daniel Duckworth, Semih Yavuz, Amit Dubey, Kyu-Young Kim, and Andy Cedilnik. 2019. Taskmaster-1: To- ward a realistic and diverse dialog dataset. In Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Lan- guage Processing (EMNLP-IJCNLP), pages 4516– 4525, Hong Kong, China. Association for Computa- tional Linguistics. Samuel Cahyawijaya, Genta Indra Winata, Bryan Wilie, Karissa Vincentio, Xiaohong Li, Adhiguna Kuncoro, Sebastian Ruder, Zhi Yuan Lim, Syafri Ba- har, Masayu Khodra, Ayu Purwarianti, and Pascale Fung. 2021. IndoNLG: Benchmark and resources for evaluating Indonesian natural language genera- In Proceedings of the 2021 Conference on tion. Empirical Methods in Natural Language Processing, pages 8875–8898, Online and Punta Cana, Domini- can Republic. Association for Computational Lin- guistics. Frances Corry, Hamsini Sridharan, Alexandra Sasha Luccioni, Mike Ananny, Jason Schultz, and Kate Crawford. 2021. The problem of zombie datasets: CoRR, A framework for deprecating datasets. abs/2111.04424. Mathias Creutz. 2018. Open subtitles paraphrase cor- In Proceedings of the 11th pus for six languages. edition of the Language Resources and Evaluation Conference (LREC 2018), Miyazaki, Japan. Euro- pean Language Resources Association (ELRA). Mostafa Dehghani, Yi Tay, Alexey A. Gritsenko, Zhe Zhao, Neil Houlsby, Fernando Diaz, Donald Met- zler, and Oriol Vinyals. 2021. The benchmark lot- tery. CoRR, abs/2107.07002. Daniel Deutsch and Dan Roth. 2022. Repro: An Open- Source Library for Improving the Reproducibility and Usability of Publicly Available Research Code. ArXiv, abs/2204.13848. Ashwin Devaraj, Iain Marshall, Byron Wallace, and Junyi Jessy Li. 2021. Paragraph-level simplification of medical texts. In Proceedings of the 2021 Con- ference of the North American Chapter of the Asso- ciation for Computational Linguistics: Human Lan- guage Technologies, pages 4972–4984, Online. As- sociation for Computational Linguistics. Sebastian Gehrmann, Aadesh Gupta, Zhenhao Li, Saad Mahamood, Abinaya Mahendiran, Simon Mille, et al. 2021. Ashish Srivastava, Samson Tan, task-sensitive Nl-augmenter: A framework for arXiv preprint natural arXiv:2112.02721. Ondˇrej Dušek, David M. Howcroft, and Verena Rieser. 2019. Semantic noise matters for neural natural lan- guage generation. In Proceedings of the 12th Inter- national Conference on Natural Language Genera- tion, pages 421–426, Tokyo, Japan. Association for Computational Linguistics. Ondˇrej Dušek and Filip Jurˇcíˇcek. 2019. Neural gener- In Proceed- ation for Czech: Data and baselines. ings of the 12th International Conference on Nat- ural Language Generation, pages 563–574, Tokyo, Japan. Association for Computational Linguistics. Ondˇrej Dušek, Jekaterina Novikova, and Verena Rieser. 2020. Evaluating the state-of-the-art of end-to-end natural language generation: The e2e nlg challenge. Computer Speech & Language, 59:123–156. Kawin Ethayarajh and Dan Jurafsky. 2020. Utility is in the eye of the user: A critique of NLP leaderboards. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 4846–4853, Online. Association for Computa- tional Linguistics. Claire Gardent, Anastasia Shimorina, Shashi Narayan, and Laura Perez-Beltrachini. 2017a. Creating train- In Proceed- ing corpora for NLG micro-planners. ings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Pa- pers), pages 179–188, Vancouver, Canada. Associa- tion for Computational Linguistics. Claire Gardent, Anastasia Shimorina, Shashi Narayan, and Laura Perez-Beltrachini. 2017b. The WebNLG challenge: Generating text from RDF data. In Pro- ceedings of the 10th International Conference on Natural Language Generation, pages 124–133, San- tiago de Compostela, Spain. Association for Compu- tational Linguistics. Timnit Gebru, Jamie Morgenstern, Briana Vecchione, Jennifer Wortman Vaughan, Hanna Wallach, Hal Daumé III, and Kate Crawford. 2018. Datasheets for In Proceedings of the Fifth Workshop on datasets. Fairness, Accountability, and Transparency in Ma- chine Learning, Stockholm, Sweden. Sebastian Gehrmann, Tosin Adewumi, Karmanya Aggarwal, Sasanka Ammanamanchi, Anuoluwapo Aremu, Antoine Bosselut, Khy- athi Raghavi Chandu, Miruna-Adriana Clinciu, Dipanjan Das, Kaustubh Dhole, Wanyu Du, Esin Durmus, Ondˇrej Dušek, Chris Chinenye Emezue, Varun Gangal, Cristina Garbacea, Tat- sunori Hashimoto, Yufang Hou, Yacine Jernite, Harsh Jhamtani, Yangfeng Ji, Shailza Jolly, Mi- hir Kale, Dhruv Kumar, Faisal Ladhak, Aman Madaan, Mounica Maddela, Khyati Mahajan, Saad Mahamood, Bodhisattwa Prasad Majumder, Pedro Henrique Martins, Angelina McMillan- Major, Simon Mille, Emiel van Miltenburg, Moin Nadeem, Shashi Narayan, Vitaly Nikolaev, Andre Niyongabo Rubungo, Salomey Osei, Ankur Parikh, Laura Perez-Beltrachini, Niranjan Ramesh Rao, Vikas Raunak, Juan Diego Rodriguez, Sashank Santhanam, João Sedoc, Thibault Sellam, Samira Shaikh, Anastasia Shimorina, Marco Antonio Sobrevilla Cabezudo, Hendrik Strobelt, Nishant Subramani, Wei Xu, Diyi Yang, Akhila Yerukola, and Jiawei Zhou. 2021. The GEM benchmark: Nat- ural language generation, its evaluation and metrics. In Proceedings of the 1st Workshop on Natural Language Generation, Evaluation, and Metrics (GEM 2021), pages 96–120, Online. Association for Computational Linguistics. Sebastian Gehrmann, Elizabeth Clark, and Thibault Sellam. 2022. Repairing the cracked foundation: A survey of obstacles in evaluation practices for gener- ated text. CoRR, abs/2202.06935. Tahmid Hasan, Abhik Bhattacharjee, Md. Saiful Islam, Kazi Mubasshir, Yuan-Fang Li, Yong-Bin Kang, M. Sohel Rahman, and Rifat Shahriyar. 2021. XL- sum: Large-scale multilingual abstractive summa- rization for 44 languages. In Findings of the Associ- ation for Computational Linguistics: ACL-IJCNLP 2021, pages 4693–4703, Online. Association for Computational Linguistics. Hiroaki Hayashi, Yusuke Oda, Alexandra Birch, Ioan- nis Konstas, Andrew Finch, Minh-Thang Luong, Graham Neubig, and Katsuhito Sudoh. 2019. Find- ings of the third workshop on neural generation and In Proceedings of the 3rd Workshop translation. on Neural Generation and Translation, pages 1–14, Hong Kong. Association for Computational Linguis- tics. David M. Howcroft, Anya Belz, Miruna-Adriana Clinciu, Dimitra Gkatzia, Sadid A. Hasan, Saad Mahamood, Simon Mille, Emiel van Miltenburg, Sashank Santhanam, and Verena Rieser. 2020. Twenty years of confusion in human evaluation: NLG needs evaluation sheets and standardised def- In Proceedings of the 13th International initions. Conference on Natural Language Generation, pages 169–182, Dublin, Ireland. Association for Computa- tional Linguistics. Chao Jiang, Mounica Maddela, Wuwei Lan, Yang Zhong, and Wei Xu. 2020. Neural CRF model for In Pro- sentence alignment in text simplification. ceedings of the 58th Annual Meeting of the Asso- ciation for Computational Linguistics, pages 7943– 7960, Online. Association for Computational Lin- guistics. Pratik Joshi, Sebastin Santy, Amar Budhiraja, Kalika Bali, and Monojit Choudhury. 2020. The state and fate of linguistic diversity and inclusion in the NLP In Proceedings of the 58th Annual Meet- world. ing of the Association for Computational Linguistics, pages 6282–6293, Online. Association for Computa- tional Linguistics. Juraj Juraska, Kevin Bowden, and Marilyn Walker. 2019. ViGGO: A video game corpus for data-to- text generation in open-domain conversation. In Proceedings of the 12th International Conference on Natural Language Generation, pages 164–172, Tokyo, Japan. Association for Computational Lin- guistics. Mihir Kale and Abhinav Rastogi. 2020. Text-to-text pre-training for data-to-text tasks. In Proceedings of the 13th International Conference on Natural Lan- guage Generation, pages 97–102, Dublin, Ireland. Association for Computational Linguistics. Moussa Kamal Eddine, Antoine Tixier, and Michalis Vazirgiannis. 2021. BARThez: a skilled pretrained In Proceed- French sequence-to-sequence model. ings of the 2021 Conference on Empirical Methods in Natural Language Processing, pages 9369–9390, Online and Punta Cana, Dominican Republic. Asso- ciation for Computational Linguistics. Jenna Kanerva, Filip Ginter, Li-Hsin Chang, Iiro Ras- tas, Valtteri Skantsi, Jemina Kilpeläinen, Hanna- Mari Kupari, Jenna Saarni, Maija Sevón, and Otto In Pro- Tarkka. 2021. Finnish paraphrase corpus. ceedings of the 23rd Nordic Conference on Com- putational Linguistics (NoDaLiDa), pages 288–298, Reykjavik, Iceland (Online). Linköping University Electronic Press, Sweden. Jenna Kanerva, Filip Ginter, and Sampo Pyysalo. 2020. Turku enhanced parser pipeline: From raw text to enhanced graphs in the IWPT 2020 shared task. In Proceedings of the 16th International Conference on Parsing Technologies and the IWPT 2020 Shared Task on Parsing into Enhanced Universal Dependen- cies, pages 162–173, Online. Association for Com- putational Linguistics. Jenna Kanerva, Samuel Rönnqvist, Riina Kekki, Tapio Salakoski, and Filip Ginter. 2019. Template-free data-to-text generation of Finnish sports news. In Proceedings of the 22nd Nordic Conference on Com- putational Linguistics, pages 242–252, Turku, Fin- land. Linköping University Electronic Press. Jungo Kasai, Keisuke Sakaguchi, Ronan Le Bras, Lavinia Dunagan, Jacob Morrison, Alexander R. Fabbri, Yejin Choi, and Noah A. Smith. 2022. Bidi- mensional leaderboards: Generate and evaluate lan- In Proceedings of the 2022 guage hand in hand. Conference of the North American Chapter of the Association for Computational Linguistics, Seattle, Washington. Association for Computational Linguis- tics. Joongwon Kim, Mounica Maddela, Reno Kriz, Wei Xu, and Chris Callison-Burch. 2021a. BiSECT: Learning to split and rephrase sentences with bitexts. In Proceedings of the 2021 Conference on Empiri- cal Methods in Natural Language Processing, pages 6193–6209, Online and Punta Cana, Dominican Re- public. Association for Computational Linguistics. Seokhwan Kim, Yang Liu, Di Jin, Alexandros Papan- gelis, Karthik Gopalakrishnan, Behnam Hedayatnia, and Dilek Z. Hakkani-Tür. 2021b. “how robust r u?”: Evaluating task-oriented dialogue systems on spoken conversations. 2021 IEEE Automatic Speech Recognition and Understanding Workshop (ASRU), pages 1147–1154. Faisal Ladhak, Esin Durmus, Claire Cardie, and Kath- leen McKeown. 2020. WikiLingua: A new bench- mark dataset for cross-lingual abstractive summa- In Findings of the Association for Com- rization. putational Linguistics: EMNLP 2020, pages 4034– 4048, Online. Association for Computational Lin- guistics. Quentin Lhoest, Albert Villanova del Moral, Yacine Jernite, Abhishek Thakur, Patrick von Platen, Suraj Patil, Julien Chaumond, Mariama Drame, Julien Plu, Lewis Tunstall, Joe Davison, Mario Šaško, Gun- jan Chhablani, Bhavitvya Malik, Simon Brandeis, Teven Le Scao, Victor Sanh, Canwen Xu, Nicolas Patry, Angelina McMillan-Major, Philipp Schmid, Sylvain Gugger, Clément Delangue, Théo Matus- sière, Lysandre Debut, Stas Bekman, Pierric Cis- tac, Thibault Goehringer, Victor Mustar, François Lagunas, Alexander Rush, and Thomas Wolf. 2021. Datasets: A community library for natural language processing. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Process- ing: System Demonstrations, pages 175–184, On- line and Punta Cana, Dominican Republic. Associ- ation for Computational Linguistics. Bill Yuchen Lin, Wangchunshu Zhou, Ming Shen, Pei Zhou, Chandra Bhagavatula, Yejin Choi, and Xiang Ren. 2020. CommonGen: A constrained text gen- eration challenge for generative commonsense rea- soning. In Findings of the Association for Computa- tional Linguistics: EMNLP 2020, pages 1823–1840, Online. Association for Computational Linguistics. Chin-Yew Lin. 2004. ROUGE: A package for auto- matic evaluation of summaries. In Text Summariza- tion Branches Out, pages 74–81, Barcelona, Spain. Association for Computational Linguistics. Angelina McMillan-Major, Salomey Osei, Juan Diego Rodriguez, Pawan Sasanka Ammanamanchi, Sebas- tian Gehrmann, and Yacine Jernite. 2021. Reusable templates and guides for documenting datasets and models for natural language processing and gener- ation: A case study of the HuggingFace and GEM In Proceedings of the 1st data and model cards. Workshop on Natural Language Generation, Eval- uation, and Metrics (GEM 2021), pages 121–135, Online. Association for Computational Linguistics. Simon Mille, Anya Belz, Bernd Bohnet, Thiago Cas- tro Ferreira, Yvette Graham, and Leo Wanner. 2020. The third multilingual surface realisation shared task In Pro- (SR’20): Overview and evaluation results. ceedings of the Third Workshop on Multilingual Sur- face Realisation, pages 1–20, Barcelona, Spain (On- line). Association for Computational Linguistics. Simon Mille, Kaustubh Dhole, Saad Mahamood, Laura Perez-Beltrachini, Varun Gangal, Mihir Kale, Emiel van Miltenburg, and Sebastian Gehrmann. 2021. Automatic construction of evaluation suites for natu- ral language generation datasets. In Thirty-fifth Con- ference on Neural Information Processing Systems Datasets and Benchmarks Track (Round 1). Linyong Nan, Dragomir Radev, Rui Zhang, Amrit Rau, Abhinand Sivaprasad, Chiachun Hsieh, Xian- gru Tang, Aadit Vyas, Neha Verma, Pranav Kr- ishna, Yangxiaokang Liu, Nadia Irwanto, Jessica Pan, Faiaz Rahman, Ahmad Zaidi, Mutethia Mu- tuma, Yasin Tarabar, Ankit Gupta, Tao Yu, Yi Chern Tan, Xi Victoria Lin, Caiming Xiong, Richard Socher, and Nazneen Fatema Rajani. 2021. DART: Open-domain structured data record to text genera- tion. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Com- putational Linguistics: Human Language Technolo- gies, pages 432–447, Online. Association for Com- putational Linguistics. Shashi Narayan, Shay B. Cohen, and Mirella Lapata. 2018. Don’t give me the details, just the summary! topic-aware convolutional neural networks for ex- In Proceedings of the 2018 treme summarization. Conference on Empirical Methods in Natural Lan- guage Processing, pages 1797–1807, Brussels, Bel- gium. Association for Computational Linguistics. Jekaterina Novikova, Ondˇrej Dušek, and Verena Rieser. 2017. The E2E dataset: New challenges for end- In Proceedings of the 18th An- to-end generation. nual SIGdial Meeting on Discourse and Dialogue, pages 201–206, Saarbrücken, Germany. Association for Computational Linguistics. Kishore Papineni, Salim Roukos, Todd Ward, and Wei- Jing Zhu. 2002. Bleu: a method for automatic eval- In Proceedings of uation of machine translation. the 40th Annual Meeting of the Association for Com- putational Linguistics, pages 311–318, Philadelphia, Pennsylvania, USA. Association for Computational Linguistics. Ankur Parikh, Xuezhi Wang, Sebastian Gehrmann, Manaal Faruqui, Bhuwan Dhingra, Diyi Yang, and Dipanjan Das. 2020. ToTTo: A controlled table-to- text generation dataset. In Proceedings of the 2020 Conference on Empirical Methods in Natural Lan- guage Processing (EMNLP), pages 1173–1186, On- line. Association for Computational Linguistics. Laura Perez-Beltrachini and Mirella Lapata. 2021. Models and datasets for cross-lingual summarisa- In Proceedings of the 2021 Conference on tion. Empirical Methods in Natural Language Processing, pages 9408–9423, Online and Punta Cana, Domini- can Republic. Association for Computational Lin- guistics. Laura Perez-Beltrachini, Yang Liu, and Mirella Lapata. 2019. Generating summaries with topic templates and structured convolutional decoders. In Proceed- ings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 5107–5116, Florence, Italy. Association for Computational Lin- guistics. Ratish Puduppully, Li Dong, and Mirella Lapata. 2019a. Data-to-text generation with entity model- In Proceedings of the 57th Annual Meeting ing. of the Association for Computational Linguistics, pages 2023–2035, Florence, Italy. Association for Computational Linguistics. Ratish Puduppully and Mirella Lapata. 2021. Data- to-text generation with macro planning. Transac- tions of the Association for Computational Linguis- tics, 9:510–527. Ratish Puduppully, Jonathan Mallinson, and Mirella Lapata. 2019b. University of Edinburgh’s submis- sion to the document-level generation and transla- In Proceedings of the 3rd Work- tion shared task. shop on Neural Generation and Translation, pages 268–272, Hong Kong. Association for Computa- tional Linguistics. Mahima Pushkarna, Andrew Zaldivar, and Oddur Kjar- tansson. 2022. Data cards: Purposeful and transpar- ent dataset documentation for responsible ai. Jun Quan, Shian Zhang, Qian Cao, Zizhong Li, and Deyi Xiong. 2020. RiSAWOZ: A large-scale multi- domain Wizard-of-Oz dataset with rich semantic an- notations for task-oriented dialogue modeling. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 930–940, Online. Association for Computa- tional Linguistics. Inioluwa Deborah Raji, Emily Denton, Emily M. Ben- der, Alex Hanna, and Amandalynne Paullada. 2021. AI and the everything in the whole wide world In Proceedings of the Neural Infor- benchmark. mation Processing Systems Track on Datasets and Benchmarks 1, NeurIPS Datasets and Benchmarks 2021, December 2021, virtual. Pranav Rajpurkar, Jian Zhang, Konstantin Lopyrev, and Percy Liang. 2016. SQuAD: 100,000+ Questions for Machine Comprehension of Text. arXiv e-prints, page arXiv:1606.05250. Abhinav Rastogi, Xiaoxue Zang, Srinivas Sunkara, Raghav Gupta, and Pranav Khaitan. 2020. Towards scalable multi-domain conversational agents: The schema-guided dialogue dataset. In Proceedings of the AAAI Conference on Artificial Intelligence, vol- ume 34, pages 8689–8696. Fahimeh Saleh, Alexandre Berard, Ioan Calapodescu, and Laurent Besacier. 2019. Naver labs Europe’s systems for the document-level generation and trans- In Proceedings of the lation task at WNGT 2019. 3rd Workshop on Neural Generation and Transla- tion, pages 273–279, Hong Kong. Association for Computational Linguistics. Thomas Scialom, Paul-Alexis Dray, Sylvain Lamprier, Benjamin Piwowarski, and Jacopo Staiano. 2020. Mlsum: The multilingual summarization corpus. arXiv preprint arXiv:2004.14900. Thibault Sellam, Dipanjan Das, and Ankur Parikh. 2020. BLEURT: Learning robust metrics for text generation. In Proceedings of the 58th Annual Meet- ing of the Association for Computational Linguistics, pages 7881–7892, Online. Association for Computa- tional Linguistics. Elior Sulem, Omri Abend, and Ari Rappoport. 2018. BLEU is not suitable for the evaluation of text sim- plification. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Process- ing, pages 738–744, Brussels, Belgium. Association for Computational Linguistics. Edward Sun, Yufang Hou, Dakuo Wang, Yunfeng Zhang, and Nancy X. R. Wang. 2021. D2S: Document-to-slide generation via query-based text summarization. In Proceedings of the 2021 Confer- ence of the North American Chapter of the Associ- ation for Computational Linguistics: Human Lan- guage Technologies, pages 1405–1418, Online. As- sociation for Computational Linguistics. Craig Thomson, Ehud Reiter, and Somayajulu Sripada. 2020. SportSett:basketball - a robust and maintain- able data-set for natural language generation. In Proceedings of the Workshop on Intelligent Informa- tion Processing and Natural Language Generation, pages 32–40, Santiago de Compostela, Spain. Asso- ciation for Computational Lingustics. Jörg Tiedemann and Lars Nygaard. 2004. The OPUS corpus - parallel and free: http://logos.uio. no/opus. In Proceedings of the Fourth Interna- tional Conference on Language Resources and Eval- uation (LREC’04), Lisbon, Portugal. European Lan- guage Resources Association (ELRA). Sara Tonelli, Alessio Palmero Aprosio, and Francesca Saltori. 2016. Simpitiki: a simplification corpus for italian. In CLiC-it/EVALITA. Chris van der Lee, Albert Gatt, Emiel van Miltenburg, Sander Wubben, and Emiel Krahmer. 2019. Best practices for the human evaluation of automatically generated text. In Proceedings of the 12th Interna- tional Conference on Natural Language Generation, pages 355–368, Tokyo, Japan. Association for Com- putational Linguistics. Alex Wang, Richard Yuanzhe Pang, Angelica Chen, Ja- son Phang, and Samuel R. Bowman. 2022. SQuAL- ITY: Building a long-document summarization dataset the hard way. arXiv preprint 2205.11465. Alex Wang, Yada Pruksachatkun, Nikita Nangia, Amanpreet Singh, Julian Michael, Felix Hill, Omer Levy, and Samuel R. Bowman. 2019. Superglue: A stickier benchmark for general-purpose language un- derstanding systems. In Advances in Neural Infor- mation Processing Systems 32: Annual Conference on Neural Information Processing Systems 2019, NeurIPS 2019, December 8-14, 2019, Vancouver, BC, Canada, pages 3261–3275. Sam Wiseman, Stuart Shieber, and Alexander Rush. 2017. Challenges in data-to-document generation. In Proceedings of the 2017 Conference on Empiri- cal Methods in Natural Language Processing, pages 2253–2263, Copenhagen, Denmark. Association for Computational Linguistics. Wei Xu, Courtney Napoles, Ellie Pavlick, Quanze Chen, and Chris Callison-Burch. 2016. Optimizing statistical machine translation for text simplification. Transactions of the Association for Computational Linguistics, 4:401–415. Ying Xu, Dakuo Wang, Mo Yu, Daniel Ritchie, Bing- sheng Yao, Tongshuang Wu, Zheng Zhang, Toby Jia-Jun Li, Nora Bradford, Branda Sun, Tran Bao Hoang, Yisi Sang, Yufang Hou, Xiaojuan Ma, Diyi Yang, Nanyun Peng, Zhou Yu, and Mark Warschauer. 2022. Fantastic questions and where to find them: FairytaleQA – an authentic dataset for narrative comprehension. Association for Computa- tional Linguistics. Linting Xue, Noah Constant, Adam Roberts, Mi- hir Kale, Rami Al-Rfou, Aditya Siddhant, Aditya Barua, and Colin Raffel. 2021. mT5: A massively multilingual pre-trained text-to-text transformer. In Proceedings of the 2021 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies, pages 483–498, Online. Association for Computa- tional Linguistics. Li Zhang, Huaiyu Zhu, Siddhartha Brahma, and Yun- yao Li. 2020. Small but mighty: New benchmarks for split and rephrase. In Proceedings of the 2020 Conference on Empirical Methods in Natural Lan- guage Processing (EMNLP), pages 1198–1205, On- line. Association for Computational Linguistics. Qi Zhu, Kaili Huang, Zheng Zhang, Xiaoyan Zhu, and Minlie Huang. 2020. CrossWOZ: A large-scale Chi- nese cross-domain task-oriented dialogue dataset. Transactions of the Association for Computational Linguistics, 8:281–295. Dataset Citation Task Language(s) Taxonomy Size Input Length Output Length ART BiSECT Cochrane CommonGen Conversational Weather CrossWOZ CS Restaurants DART DSTC 10 E2E NLG FairytaleQA IndoNLG MLB MLSum Opusparcus OrangeSum RiSAWOZ RotoWire En-De Schema-Guided Dialog SciDuet SIMPITIKI SportSett Squad V2 SQuALITY v1.1 Surface Realization ST 2020 (Bhagavatula et al., 2020) (Kim et al., 2021a) (Devaraj et al., 2021) (Lin et al., 2020) (Balakrishnan et al., 2019) (Zhu et al., 2020) (Dušek and Jurˇcíˇcek, 2019) (Nan et al., 2021) (Kim et al., 2021b) (Novikova et al., 2017; Dušek et al., 2020; Dušek et al., 2019) (Xu et al., 2022) (Cahyawijaya et al., 2021) (Puduppully et al., 2019a) (Scialom et al., 2020) (Creutz, 2018) (Kamal Eddine et al., 2021) (Quan et al., 2020) (Wiseman et al., 2017; Hayashi et al., 2019) (Rastogi et al., 2020) (Sun et al., 2021) (Tonelli et al., 2016) (Thomson et al., 2020) (Rajpurkar et al., 2016) (Wang et al., 2022) (Mille et al., 2020) TaskMaster ToTTo Turku Hockey Turku Paraphrase ViGGo WebNLG WikiAuto +ASSET/TURK/Split&Rephrase (Jiang et (Byrne et al., 2019) (Parikh et al., 2020) (Kanerva et al., 2019) (Kanerva et al., 2021) (Juraska et al., 2019) (Gardent et al., 2017a,b) al., 2020; Alva- Manchego et al., 2020; Xu et al., 2016; Zhang et al., 2020) (Perez-Beltrachini et al., 2019) (Ladhak et al., 2020) WikiCatSum WikiLingua XLSum (Hasan et al., 2021) XSum XWikis (Narayan et al., 2018) (Perez-Beltrachini and Lapata, 2021) Reasoning Simplification Simplification Data-to-Text Response Generation Response Generation Response Generation Data-to-Text Data-to-Text Data-to-Text Question Geneartion Summarization Data-to-Text Summarization Paraphrasing Summarization Response Generation Data-to-Text Response Generation Slide Generation Simplification Data-to-Text Question Generation Summarization Data-to-Text Response Generation Data-to-Text Data-to-Text Paraphrasing Data-to-Text Data-to-Text Simplification Summarization Summarization Summarization Summarization Summarization en en, de, es, fr en en en zh cs en en en en id, jv, su en es, de de, en, fi, fr, ru, sv fr zh en, de en en it en en en ar, en, es, fr, hi, in ko, ja, pt, ru, zh en en fi fi en en, ru en en ar, cs, de, en, es, fr, hi, id, it, ja, ko, nl, pt, ru, th, tr, vi, zh om, fr, am, ar, az, bn, cy, en, es, gd, fa, gu, ha, hi, ig, id, ja, ko, ky, mr, my, ne, ps, pcm, pt, pa, rn, ru, sr, si, so, sw, ta, te, th, ti, tr, uk, ur, uz, vi, yo, zh-CN, zh-TW en en, de, fr, cs 5 5 5 5 5 5 4 5 5 5 5 1–3 5 5 4–5 5 5 5 5 5 4 5 5 3–5 5 5 4 4 5 4–5 5 5 3–5 0–5 5 4-5 50k 200k–1M 3.5k 70k 25k 5k 3.5k 60k 20k 35k 8.5k 14k–200k 23k 220k–250k 0–35M 21k–30k 10k 242 165k 2k 815 3.7k 120k 2500 250k 190k 120k 2.7k–6.1k 81k–170k 5.1k 14k–35k 480k 48k 5k–3.8M 1.3k–300k 23k 44k–461k 138 266–434 80 417 70 1337 146 335 2021 24665 4152 1984 188 5990 768 5000 892 972 357 158 87 120 169.5 43527 1607–4650 2244.5 1470–9924 3486.5 1845 1743 41 224–387 315 58 95 135 15.9 456 2580 147 138 51 1620 55 227 126 55 58 47 109 157 256 159–489 200.5 137–614 237 153 102 Table 3: Detailed information about all the datasets currently supported in GEM. We present the name of the dataset, the paper(s) in which the dataset was introduced, the NLG task it performs, the languages the dataset caters to and their resourcedness taxonomy class, the size of the training set (rounded), and the lengths of input and output. # A Dataset Overviews We provide a detailed overview of all the supported datasets in Table 3. Input and output lengths are reported in number of tokens according to the mT5 tokenizer (Xue et al., 2021). When multiple config- urations for a dataset are available, we report the median of the sizes and lengths. # B Changes to Datasets # B.1 BiSECT The original released BiSECT (Kim et al., 2021a) training, validation, and test splits are maintained to ensure a fair comparison. Note that the original BiSECT test set was created by manually selecting 583 high-quality Split and Rephrase instances from 1000 random source-target pairs sampled from the EMEA and JRC-Acquis corpora from the OPUS parallel corpus (Tiedemann and Nygaard, 2004). As the first challenge set, we include the HSPLIT- Wiki test set, containing 359 pairs (Sulem et al., 2018). For each complex sentence, there are four reference splits; To ensure replicability, as refer- ence splits, we again follow the original BiSECT paper and present only the references from HSplit2- full. In addition to the two evaluation sets used in the original BiSECT paper, we also introduce a second challenge set. For this, we initially consider all 7,293 pairs from the EMEA and JRC-Acquis corpora. From there, we classify each pair using the classification algorithm from Section 4.2 of the original BiSECT paper. The three classes are as follows: 1. Direct Insertion: when a long sentence l con- tains two independent clauses and requires only minor changes in order to make a fluent and meaning-preserving split s. 2. Changes near Split, when l contains one in- dependent and one dependent clause, but mod- ifications are restricted to the region where l is split. 3. Changes across Sentences, where major changes are required throughout l in order to create a fluent split s. We keep only pairs labeled as Type 3, and after filtering out pairs with significant length differences (signaling potential content addition/deletion), we present a second challenge set of 1,798 pairs. # B.2 FairytaleQA The original release of FairytaleQA (Xu et al., 2022) used separate files to store the fairytale story content and experts-labeled QA-pairs. It provided baseline benchmarks on both Question Answering and Question Generation tasks. In GEMv2, we re-organize the data to be specifically prepared for the Question Generation task. The original dataset contains 2 answers created by different annotators in the evaluation and test splits, but we only take the first answer into consideration for the Question Generation task. The input for this task would be the concatenation of each answer labeled by hu- man experts and the related story section(s), and the output target would be the corresponding ques- tion labeled by human experts. # B.3 MLB Data to Text We follow the serialization format introduced in (Puduppully and Lapata, 2021) for the lin- earized_input field. Specifically, we serialize the home team records, the visiting team records, and the player records. We next serialize the records of the innings in chronological order. # B.4 Opusparcus Compared to the original release of Opusparcus (Creutz, 2018), available through the Language Bank of Finland,9 the GEMv2 release contains a few additions to facilitate the use of this resource: The validation and test sets now come in two versions, the so-called regular validation and test sets and the full sets. The regular sets only contain 9https://www.kielipankki.fi/corpora/ opusparcus/ sentence pairs that qualify as paraphrases. The full sets are the original sets from the original release, which contain all sentence pairs successfully anno- tated by the annotators, including the sentence pairs that were rejected as paraphrases. The validation sets were called development sets in the original release. The training sets are orders of magnitudes larger than the validation and test sets. Therefore the train- ing sets have not been annotated manually and the true paraphrase status of each entry is unknown. In the original release, each training set entry is ac- companied by an automatically calculated ranking score, which reflects how likely that entry contains a true paraphrase pair. The entries are ordered in the data, best first, worst last. If you use the origi- nal release, you need to control yourself how large and how clean a portion of the training data you will use. In the GEMv2 release, the training sets come in predefined subsets. Using the so-called quality parameter, the user can control for the estimated proportion (in percent) of true paraphrases in the retrieved training subset. Allowed quality values range between 60 and 100, in increments of 5 (60, 65, 70, ..., 100). A value of 60 means that 60 % of the sentence pairs in the training set are estimated to be true paraphrases (and the remaining 40 % are not). A higher value produces a smaller but cleaner set. The smaller sets are subsets of the larger sets, such that the quality=95 set is a subset of quality=90, which is a subset of quality=85, and so on. Depending on this parameter, the dataset can fall into all resourcedness categories in Figure 2. # B.5 ROTOWIRE_English-German We introduce a field linearized_input, which serial- izes the input table into a string. We follow a serial- ization format similar to that of Saleh et al. (2019). More specifically, we serialize all the records of the home team followed by that of the visiting team. We next serialize the records of the players of the home team followed by that of the visiting team. We rank the players by points in descending order. In addition, we add information about the relative rank of a player within a team following Pudup- pully et al. (2019b). # B.6 SciDuet The original released SciDuet (Sun et al., 2021) uses two json files to store paper information and In GEMv2, we slide information, respectively. merge these two files and reorganize the structure so that each data instance contains the complete in- put (i.e., paper title/abstract/section headers/section content, as well as slide title) and output (i.e., slide text content). In addition, we introduce a new chal- lenging dataset in GEMv2 by removing slides if their titles match with any section headers from the corresponding paper. # B.7 SIMPITIKI The original release of SIMPITIKI (Tonelli et al., 2016) includes two xml files, corresponding to the version 1 and version 2 respectively. The second version has better sentence boundaries. However, no training, validation and test splits were officially proposed for both release. In GEM, we randomly and independently split both xml files into training, validation and test sets. Note that version 1 and version 2 have different splits. We also generated challenge sets were some simplification transfor- mations in the test set are not part of the training set and thus unseen in the training phase. Then, as SIMPITIKI leverages data from Wikipedia and the Municipality of Trento corpora, we further propose splits based on the respective data source. # B.8 SportSett Basketball Similar to MLB Data-to-Text, SportSett also fol- lows the serialization format introduced in (Pudup- pully and Lapata, 2021) for the linearized_input field. The serialisation starts with current game’s information such as date and venue of the game. This is followed with both team’s information (line- scores) including their next game’s information as well. Finally, the players’ information (box-scores) is serialised, starting with home team’s players and then visiting team’s players. # B.9 squad_v2 SQuAD2.0 (Rajpurkar et al., 2016) combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones. The original SQuAD2.0 dataset has only training and dev (validation) splits. A new test split is cre- ated from the train split and added as part of the squad_v2 dataset. # B.10 Taskmaster-3 According to Byrne et al. (2021), the Taskmaster-3 (also called TicketTalk) dataset consists of 23,789 movie ticketing dialogs, where the customer’s goal is to purchase tickets after deciding on theater, time, movie name, number of tickets, and date, or opt out of the transaction. This collection was created using the "self-dialog" method, i.e., a single, crowd- sourced worker is paid to create a conversation writing turns for both speakers- the customer and the ticketing agent. # B.11 Turku Hockey To ease the use of the data, in addition to the game-level structuring as used in the original Turku Hockey data release (Kanerva et al., 2019), we pro- vide a simplified event-level structuring. In the event-level generation, the structured input data is linearized to string representation separately for each game event, and the task objective is thus to generate the description separately for each game event directly using the linearized input representa- tion. In comparison, the objective of the game-level generation is to process the structured data for the entire game at once, and generate descriptions for all relevant events. The linearized event inputs are produced using similar approach as described in the original paper. # B.12 Turku Paraphrase In GEMv2, the Turku Paraphrase data can be loaded with three different configurations, plain, classification, and generation. While the plain con- figuration models the data similarly to the original release, the two other options directly applies sev- eral transformations beneficial for the named task. In classification each example is provided using both (text1, text2, label) and (text2, text1, label) ordering, as paraphrase classification does not de- pend on the order of the given statements. In cases with a directionality annotation in the paraphrase pair, the label is flipped accordingly when creating the additional examples. In generation, on the other hand, the data is pre-processed to include only ex- amples suitable for the paraphrase generation task, therefore discarding, e.g., negative and highly con- text dependent examples, which does not fit the generation task as such. In addition, the examples with annotated directionality (one statements be- ing more detailed than the other, for instance one mentioning a woman while the other a person), the example is always provided using ordering where the input is more detailed and the output more gen- eral in order to prevent model hallucination (model learning to generate facts not present in the input). For more details about the annotated labels and the directionality, see Kanerva et al. (2020). # B.13 WikiLingua The original release of WikiLingua (Ladhak et al., 2020) released a dataset of article-summary pairs in 18 languages, but had only created train/val/test splits for 4 langauge pairs (es-en, tr-en, ru-en, vi- en), for the purposes of crosslingual evaluation. As part of GEMv1, we created train/val/test splits for all 18 languages. To further facilitate building multilingual and crosslingual models for all 18 lan- guages, the GEMv2 release contains the following changes to the GEMv1 release: In the original WikiLingua release, each document-summary pair in any of the 17 non- English languages has a corresponding parallel document-summary pair in English. A given En- glish document-summary pair can have parallel document-summary pairs in multiple languages. In order to facilitate crosslingual experiments across all language pairs, for the GEMv2 release, we align document-summary pairs across the other 17 languages via English. For example, if a given document-summary pair in English has correspond- ing parallel pairs in Turkish and Vietnamese, we can then align these to get Turkish-Vietnamese par- allel pairs. As a result, in addition to supporting all the functionality in GEMv1, the v2 loader allows the user to specify and load crosslingual data for any language pair in the dataset. In addition to the original evaluation sets (val and test), we also have sub-sampled versions in order to facilitate faster development cycles. To create the sub-sampled versions, for each evaluation set, we randomly sample 3, 000 instances.10 We further clean the dataset by removing pay- loads for thumbnails that were scraped into the document and summary texts and we filter out all instances with a summary length longer than 60% of the input document length. This removes around 5% of the data. # C Limitations As discussed in the main part of the paper, GEMv2 aims to avoid any explicit curation decisions about inclusion and exclusion of datasets beyond licens- ing and consent. This is a change from the orig- inally set out strict inclusion criteria based on dataset quality. The reason for this is that the en- 10Evaluation sets that have fewer than 3, 000 instances were not sub-sampled. tire research community should be the authority to decide whether a dataset is useful and what it is use- ful for. For example, a dataset with noisy outputs may still be useful to study hallucination avoidance methods. However, this change has implications on how dataset deprecation needs to be handled, in particular for datasets with newly found issues or datasets with better alternatives. Documenting issues and alternatives using the data cards is thus becoming more important in GEMv2 and we en- courage researchers to update data cards. Another side effect of positioning GEMv2 as infrastructure that support dataset creators is a decreased risk of erasure. All our documentation and dataset loaders center the work of the creators to encourage users to cite the datasets they use. Another open issue that we have been working on is the interplay between multilingualism and metrics. We now support multiple languages for which no NLG metrics have been tested, and for which our tokenization schemes may be inappro- priate. The freedom to combine every dataset with every metric may lead to flawed evaluations. In addition, some datasets were released with specific metrics that we do not support yet. A final issue we want to point out is the lack of discussion of human evaluation in this overview paper which we omitted for brevity. Human eval- uation does not scale and every task requires its own evaluation approach. We have thus taken the approach to develop better human evaluation for only a subset of tasks, solving issues pointed out by (Howcroft et al., 2020) and van der Lee et al. (2019), and we will release detailed instructions separately. # D Contribution Statements Organizing GEM would not be possible without community contributions and the mutual goal of improving NLG and its evaluation. To give proper credit to all contributors, this section lists the in- volvements of all co-authors. Besides the detailed list, everyone contributed to discussion sessions, made dataset suggestions, and participated in proof reading the final paper. Dataset Loaders The new data loaders and as- sociated data cards were created by the following people: ART: Chandra Bhagavatula, Nico Daheim, Aman Madaan BiSect: Jenny Chim, Reno Kriz Conversational Weather: Vipul Raheja, Michael White CrossWOZ: Qi Zhu DSTC10: Nico Daheim, Di Jin, Alexandros Papangelis FairyTaleQA: Bingsheng Yao IndoNLG: Bryan Wilie, Samuel Cahyawijaya, Genta Indra Winata MLB: Ratish Puduppully Opusparcus: Mathias Creutz OrangeSum: Moussa Kamal Eddine RiSAWOZ: Tianhao Shen, Deyi Xiong, Chaobin You RotoWire En-De: Hiroaki Hayashi, Ratish Pudup- pully SciDuet: Yufang Hou, Dakuo Wang SIMPITIKI: Sebastien Montella, Vipul Raheja Split and Rephrase: Cristina Garbacea, Reno Kriz, Li Zhang SportSett: Craig Thomson, Ashish Upadhyay Squad V2: Abinaya Mahendiran SQuALITY: Alex Wang Surface Realisation ST: Bernd Bohnet, Simon Mille TaskMaster: Tosin Adewumi ToTTo (port): Abinaya Mahendiran Turku Hockey: Filip Ginter, Jenna Kanerva Turku Paraphrase: Filip Ginter, Jenna Kanerva ViGGo: Juraj Juraska, Aman Madaan WikiCatSum: Ronald Cardenas Acosta, Laura Perez-Beltrachini WikiLingua (port): Jenny Chim, Faisal Ladhak XLSum: Abhik Bhattacharjee, Tahmid Hasan, Rifat Shahriyar XSum (port): Abinaya Mahendiran XWikis: Ronald Cardenas Acosta, Laura Perez- Beltrachini Lewis Tunstall designed and implemented the in- frastructure to host GEMv2 on the Hugging Face Hub. Sebastian Gehrmann addressed the remain- ing loader issues and ported the remaining GEMv1 datasets. Anna Shvets developed dataset-agnostic bias detection filters. Simon Mille coordinated progress during the hackathon. Documentation The updated tutorials for using GEM and adding new data loaders were developed and tested by Jenny Chim, Paul Pu Liang, and Anna Shvets. Data Cards The questions in the revised data card template were created during sessions led by Mahima Pushkarna with the help of Yacine Jer- nite, Angelina McMillan-Major, Nishant Subra- mani, Pawan Sasanka Ammanamanchi, and Sebas- tian Gehrmann. The collection tool was imple- mented by Yacine Jernite and Sebastian Gehrmann. The data card rendering tool was developed by Vi- vian Tsai and Mahima Pushkarna. Human Evaluation The human evaluation working group is led by João Sedoc. Its mem- bers include Jenny Chim, Elizabeth Clark, Daniel Deutsch, Kaustubh Dhole, Sebastian Gehrmann, Yufang Hou, Yixin Liu, Saad Mahamood, Simon Mille, Vitaly Nikolaev, Salomey Osei, Dragomir Radev, Yisi Sang, and Alex Wang. Metrics The metrics library, originally devel- oped for GEMv1, was extended by Jordan Clive, Nico Daheim, Daniel Deutsch, Ondrej Dusek, Aman Madaan, Joshua Maynez, Vikas Raunak, Leonardo F. R. Ribeiro, and Anna Shvets. and Analyses Sebastian Paper Writing Gehrmann led the writing of the paper. Abinaya Mahendiran and Jekaterina Novikova contributed analyses that were used to create Figure 2 and Table 3. Submission Infrastructure Lewis Tunstall led the development of the submission infrastructure. Hendrik Strobelt led the extension of the result visualization tool to ensure compatibility with the new submission system. Baselines Additional baseline results were pro- vided by Tosin Adewumi, Mihir Sanjay Kale, Joshua Maynez, and Leonardo F. R. Ribeiro.
Title: Session-based Recommendations with Recurrent Neural Networks: Summary: We apply recurrent neural networks (RNN) on a new domain, namely recommender systems. Real-life recommender systems often face the problem of having to base recommendations only on short session-based data (e.g. a small sportsware website) instead of long user histories (as in the case of Netflix). In this situation the frequently praised matrix factorization approaches are not accurate. This problem is usually overcome in practice by resorting to item-to-item recommendations, i.e. recommending similar items. We argue that by modeling the whole session, more accurate recommendations can be provided. We therefore propose an RNN-based approach for session-based recommendations. Our approach also considers practical aspects of the task and introduces several modifications to classic RNNs such as a ranking loss function that make it more viable for this specific problem. Experimental results on two data-sets show marked improvements over widely used approaches. at ICLR 2016 # SESSION-BASED RECOMMENDATIONS WITH RECURRENT NEURAL NETWORKS Bal´azs Hidasi ∗ Gravity R&D Inc. Budapest, Hungary balazs.hidasi@gravityrd.com # Alexandros Karatzoglou Telefonica Research Barcelona, Spain alexk@tid.es Linas Baltrunas † Netflix Los Gatos, CA, USA lbaltrunas@netflix.com Domonkos Tikk Gravity R&D Inc. Budapest, Hungary domonkos.tikk@gravityrd.com # ABSTRACT We apply recurrent neural networks (RNN) on a new domain, namely recom- mender systems. Real-life recommender systems often face the problem of having to base recommendations only on short session-based data (e.g. a small sportsware website) instead of long user histories (as in the case of Netflix). In this situation the frequently praised matrix factorization approaches are not accurate. This prob- lem is usually overcome in practice by resorting to item-to-item recommendations, i.e. recommending similar items. We argue that by modeling the whole session, more accurate recommendations can be provided. We therefore propose an RNN- based approach for session-based recommendations. Our approach also considers practical aspects of the task and introduces several modifications to classic RNNs such as a ranking loss function that make it more viable for this specific problem. Experimental results on two data-sets show marked improvements over widely used approaches. # INTRODUCTION Session-based recommendation is a relatively unappreciated problem in the machine learning and recommender systems community. Many e-commerce recommender systems (particularly those of small retailers) and most of news and media sites do not typically track the user-id’s of the users that visit their sites over a long period of time. While cookies and browser fingerprinting can provide some level of user recognizability, those technologies are often not reliable enough and moreover raise privacy concerns. Even if tracking is possible, lots of users have only one or two sessions on a smaller e-commerce site, and in certain domains (e.g. classified sites) the behavior of users often shows session-based traits. Thus subsequent sessions of the same user should be handled independently. Consequently, most session-based recommendation systems deployed for e-commerce are based on relatively simple methods that do not make use of a user profile e.g. item- to-item similarity, co-occurrence, or transition probabilities. While effective, those methods often take only the last click or selection of the user into account ignoring the information of past clicks. The most common methods used in recommender systems are factor models (Koren et al., 2009; Weimer et al., 2007; Hidasi & Tikk, 2012) and neighborhood methods (Sarwar et al., 2001; Ko- ren, 2008). Factor models work by decomposing the sparse user-item interactions matrix to a set of d dimensional vectors one for each item and user in the dataset. The recommendation problem is then treated as a matrix completion/reconstruction problem whereby the latent factor vectors are then used to fill the missing entries by e.g. taking the dot product of the corresponding user–item latent factors. Factor models are hard to apply in session-based recommendation due to the absence ∗The author spent 3 months at Telefonica Research during the research of this topic. †This work was done while the author was a member of the Telefonica Research group in Barcelona, Spain 1 Published as a conference paper at ICLR 2016 of a user profile. On the other hand, neighborhood methods, which rely on computing similari- ties between items (or users) are based on co-occurrences of items in sessions (or user profiles). Neighborhood methods have been used extensively in session-based recommendations. The past few years have seen the tremendous success of deep neural networks in a number of tasks such as image and speech recognition (Russakovsky et al., 2014; Hinton et al., 2012) where unstruc- tured data is processed through several convolutional and standard layers of (usually rectified linear) units. Sequential data modeling has recently also attracted a lot of attention with various flavors of RNNs being the model of choice for this type of data. Applications of sequence modeling range from test-translation to conversation modeling to image captioning. While RNNs have been applied to the aforementioned domains with remarkable success little atten- tion, has been paid to the area of recommender systems. In this work we argue that RNNs can be applied to session-based recommendation with remarkable results, we deal with the issues that arise when modeling such sparse sequential data and also adapt the RNN models to the recommender setting by introducing a new ranking loss function suited to the task of training these models. The session-based recommendation problem shares some similarities with some NLP-related problems in terms of modeling as long as they both deals with sequences. In the session-based recommenda- tion we can consider the first item a user clicks when entering a web-site as the initial input of the RNN, we then would like to query the model based on this initial input for a recommendation. Each consecutive click of the user will then produce an output (a recommendation) that depends on all the previous clicks. Typically the item-set to choose from in recommenders systems can be in the tens of thousands or even hundreds of thousands. Apart from the large size of the item set, another challenge is that click-stream datasets are typically quite large thus training time and scalability are really important. As in most information retrieval and recommendation settings, we are interested in focusing the modeling power on the top-items that the user might be interested in, to this end we use ranking loss function to train the RNNs. 2 RELATED WORK 2.1 SESSION-BASED RECOMMENDATION Much of the work in the area of recommender systems has focused on models that work when a user identifier is available and a clear user profile can be built. In this setting, matrix factorization methods and neighborhood models have dominated the literature and are also employed on-line. One of the main approaches that is employed in session-based recommendation and a natural solution to the problem of a missing user profile is the item-to-item recommendation approach (Sarwar et al., 2001; Linden et al., 2003) in this setting an item to item similarity matrix is precomputed from the available session data, that is items that are often clicked together in sessions are deemed to be similar. This similarity matrix is then simply used during the session to recommend the most similar items to the one the user has currently clicked. While simple, this method has been proven to be effective and is widely employed. While effective, these methods are only taking into account the last click of the user, in effect ignoring the information of the past clicks. A somewhat different approach to session-based recommendation are Markov Decision Processes (MDPs) (2002). MDPs are models of sequential stochastic decision problems. An MDP is defined as a four-tuple (S, A, Rwd, tr) where S is the set of states, A is a set of actions Rwd is a reward function and tr is the state-transition function. In recommender systems actions can be equated with recommendations and the simplest MPDs are essentially first order Markov chains where the next recommendation can be simply computed on the basis of the transition probability between items. The main issue with applying Markov chains in session-based recommendation is that the state space quickly becomes unmanageable when trying to include all possible sequences of user selections. The extended version of the General Factorization Framework (GFF) (Hidasi & Tikk, 2015) is ca- pable of using session data for recommendations. It models a session by the sum of its events. It uses two kinds of latent representations for items, one represents the item itself, the other is for representing the item as part of a session. The session is then represented as the average of the feature vectors of part-of-a-session item representation. However, this approach does not consider any ordering within the session. 2 Published as a conference paper at ICLR 2016 2.2 DEEP LEARNING IN RECOMMENDERS One of the first related methods in the neural networks literature where the use of Restricted Boltz- mann Machines (RBM) for Collaborative Filtering (Salakhutdinov et al., 2007). In this work an RBM is used to model user-item interaction and perform recommendations. This model has been shown to be one of the best performing Collaborative Filtering models. Deep Models have been used to extract features from unstructured content such as music or images that are then used together with more conventional collaborative filtering models. In Van den Oord et al. (2013) a convolutional deep network is used to extract feature from music files that are then used in a factor model. More recently Wang et al. (2015) introduced a more generic approach whereby a deep network is used to extract generic content-features from any types of items, these features are then incorporated in a standard collaborative filtering model to enhance the recommendation performance. This approach seems to be particularly useful in settings where there is not sufficient user-item interaction information. # 3 RECOMMENDATIONS WITH RNNS Recurrent Neural Networks have been devised to model variable-length sequence data. The main difference between RNNs and conventional feedforward deep models is the existence of an internal hidden state in the units that compose the network. Standard RNNs update their hidden state h using the following update function: ht = g(W xt + U ht−1) (1) Where g is a smooth and bounded function such as a logistic sigmoid function xt is the input of the unit at time t. An RNN outputs a probability distribution over the next element of the sequence, given its current state ht. A Gated Recurrent Unit (GRU) (Cho et al., 2014) is a more elaborate model of an RNN unit that aims at dealing with the vanishing gradient problem. GRU gates essentially learn when and by how much to update the hidden state of the unit. The activation of the GRU is a linear interpolation between the previous activation and the candidate activation ˆht: ht = (1 − zt)ht−1 + zt ˆht where the update gate is given by: zt = σ(Wzxt + Uzht−1) (3) while the candidate activation function ˆht is computed in a similar manner: hy = tanh (Wx, + U(r, © hy_1)) (4) and finaly the reset gate rt is given by: rt = σ(Wrxt + Urht−1) (5) 3.1 CUSTOMIZING THE GRU MODEL We used the GRU-based RNN in our models for session-based recommendations. The input of the network is the actual state of the session while the output is the item of the next event in the session. The state of the session can either be the item of the actual event or the events in the session so far. In the former case 1-of-N encoding is used, i.e. the input vector’s length equals to the number of items and only the coordinate corresponding to the active item is one, the others are zeros. The latter setting uses a weighted sum of these representations, in which events are discounted if they have occurred earlier. For the stake of stability, the input vector is then normalized. We expect this to help because it reinforces the memory effect: the reinforcement of very local ordering constraints which are not well captured by the longer memory of RNN. We also experimented with adding an additional embedding layer, but the 1-of-N encoding always performed better. The core of the network is the GRU layer(s) and additional feedforward layers can be added between the last layer and the output. The output is the predicted preference of the items, i.e. the likelihood of being the next in the session for each item. When multiple GRU layers are used, the hidden state of the previous layer is the input of the next one. The input can also be optionally connected 3 Published as a conference paper at ICLR 2016 dake] Buippaqui3 wa}! Uo sas09s :ndjno Bulpoo N-JO-T ‘way! jenqoe :ynduj Figure 1: General architecture of the network. Processing of one event of the event stream at once. to GRU layers deeper in the network, as we found that this improves performance. See the whole architecture on Figure 1, which depicts the representation of a single event within a time series of events. Since recommender systems are not the primary application area of recurrent neural networks, we modified the base network to better suit the task. We also considered practical points so that our solution could be possibly applied in a live environment. 3.1.1 SESSION-PARALLEL MINI-BATCHES RNNs for natural language processing tasks usually use in-sequence mini-batches. For example it is common to use a sliding window over the words of sentences and put these windowed fragments next to each other to form mini-batches. This does not fit our task, because (1) the length of sessions can be very different, even more so than that of sentences: some sessions consist of only 2 events, while others may range over a few hundreds; (2) our goal is to capture how a session evolves over time, so breaking down into fragments would make no sense. Therefore we use session-parallel mini-batches. First, we create an order for the sessions. Then, we use the first event of the first X sessions to form the input of the first mini-batch (the desired output is the second events of our active sessions). The second mini-batch is formed from the second events and so on. If any of the sessions end, the next available session is put in its place. Sessions are assumed to be independent, thus we reset the appropriate hidden state when this switch occurs. See Figure 2 for more details. Mini-batch1 Mini-batch2 Mini-batch3 Session1 Session2 is fina bos Input Session3 — Session4 el SessionS fsa fs2 fsa] Output Figure 2: Session-parallel mini-batch creation 3.1.2 SAMPLING ON THE OUTPUT Recommender systems are especially useful when the number of items is large. Even for a medium- sized webshop this is in the range of tens of thousands, but on larger sites it is not rare to have 4 Published as a conference paper at ICLR 2016 hundreds of thousands of items or even a few millions. Calculating a score for each item in each step would make the algorithm scale with the product of the number of items and the number of events. This would be unusable in practice. Therefore we have to sample the output and only compute the score for a small subset of the items. This also entails that only some of the weights will be updated. Besides the desired output, we need to compute scores for some negative examples and modify the weights so that the desired output is highly ranked. The natural interpretation of an arbitrary missing event is that the user did not know about the existence of the item and thus there was no interaction. However there is a low probability that the user did know about the item and chose not to interact, because she disliked the item. The more popular the item, the more probable it is that the user knows about it, thus it is more likely that a missing event expresses dislike. Therefore we should sample items in proportion of their popularity. Instead of generating separate samples for each training example, we use the items from the other training examples of the mini-batch as negative examples. The benefit of this approach is that we can further reduce computational times by skipping the sampling. Additionally, there are also benefits on the implementation side from making the code less complex to faster matrix operations. Meanwhile, this approach is also a popularity-based sampling, because the likelihood of an item being in the other training examples of the mini-batch is proportional to its popularity. # 3.1.3 RANKING LOSS The core of recommender systems is the relevance-based ranking of items. Although the task can also be interpreted as a classification task, learning-to-rank approaches (Rendle et al., 2009; Shi et al., 2012; Steck, 2015) generally outperform other approaches. Ranking can be pointwise, pair- wise or listwise. Pointwise ranking estimates the score or the rank of items independently of each other and the loss is defined in a way so that the rank of relevant items should be low. Pairwise rank- ing compares the score or the rank of pairs of a positive and a negative item and the loss enforces that the rank of the positive item should be lower than that of the negative one. Listwise ranking uses the scores and ranks of all items and compares them to the perfect ordering. As it includes sorting, it is usually computationally more expensive and thus not used often. Also, if there is only one relevant item – as in our case – listwise ranking can be solved via pairwise ranking. We included several pointwise and pairwise ranking losses into our solution. We found that point- wise ranking was unstable with this network (see Section 4 for more comments). Pairwise ranking losses on the other hand performed well. We use the following two. • BPR: Bayesian Personalized Ranking (Rendle et al., 2009) is a matrix factorization method that uses pairwise ranking loss. It compares the score of a positive and a sampled negative item. Here we compare the score of the positive item with several sampled items and use their average as the loss. The loss at a given point in one session is defined as: Ls = − 1 j=1 log (σ (ˆrs,i − ˆrs,j)), where NS is the sample size, ˆrs,k is the score on item k NS at the given point of the session, i is the desired item (next item in the session) and j are the negative samples. • TOP1: This ranking loss was devised by us for this task. It is the regularized approximation of the relative rank of the relevant item. The relative rank of the relevant item is given by 1 j=1 I{ˆrs,j > ˆrs,i}. We approximate I{·} with a sigmoid. Optimizing for this NS would modify parameters so that the score for i would be high. However this is unstable as certain positive items also act as negative examples and thus scores tend to become increasingly higher. To avoid this, we want to force the scores of the negative examples to be around zero. This is a natural expectation towards the scores of negative items. Thus we added a regularization term to the loss. It is important that this term is in the same range as the relative rank and acts similarly to it. The final loss function is as follows: Ls = 1 NS # 4 EXPERIMENTS We evaluate the proposed recursive neural network against popular baselines on two datasets. 5 Published as a conference paper at ICLR 2016 The first dataset is that of RecSys Challenge 20151. This dataset contains click-streams of an e- commerce site that sometimes end in purchase events. We work with the training set of the challenge and keep only the click events. We filter out sessions of length 1. The network is trained on ∼ 6 months of data, containing 7,966,257 sessions of 31,637,239 clicks on 37,483 items. We use the sessions of the subsequent day for testing. Each session is assigned to either the training or the test set, we do not split the data mid-session. Because of the nature of collaborative filtering methods, we filter out clicks from the test set where the item clicked is not in the train set. Sessions of length one are also removed from the test set. After the preprocessing we are left with 15,324 sessions of 71,222 events for the test set. This dataset will be referred to as RSC15. The second dataset is collected from a Youtube-like OTT video service platform. Events of watching a video for at least a certain amount of time were collected. Only certain regions were subject to this collection that lasted for somewhat shorter than 2 months. During this time item-to-item recommendations were provided after each video at the left side of the screen. These were provided by a selection of different algorithms and influenced the behavior of the users. Preprocessing steps are similar to that of the other dataset with the addition of filtering out very long sessions as they were probably generated by bots. The training data consists of all but the last day of the aforementioned period and has ∼ 3 million sessions of ∼ 13 million watch events on 330 thousand videos. The test set contains the sessions of the last day of the collection period and has ∼ 37 thousand sessions with ∼ 180 thousand watch events. This dataset will be referred to as VIDEO. The evaluation is done by providing the events of a session one-by-one and checking the rank of the item of the next event. The hidden state of the GRU is reset to zero after a session finishes. Items are ordered in descending order by their score and their position in this list is their rank. With RSC15, all of the 37,483 items of the train set were ranked. However, this would have been impractical with VIDEO, due to the large number of items. There we ranked the desired item against the most popular 30,000 items. This has negligible effect on the evaluations as rarely visited items often get low scores. Also, popularity based pre-filtering is common in practical recommender systems. As recommender systems can only recommend a few items at once, the actual item a user might pick should be amongst the first few items of the list. Therefore, our primary evaluation metric is recall@20 that is the proportion of cases having the desired item amongst the top-20 items in all test cases. Recall does not consider the actual rank of the item as long as it is amongst the top-N. This models certain practical scenarios well where there is no highlighting of recommendations and the absolute order does not matter. Recall also usually correlates well with important online KPIs, such as click-through rate (CTR)(Liu et al., 2012; Hidasi & Tikk, 2012). The second metric used in the experiments is MRR@20 (Mean Reciprocal Rank). That is the average of reciprocal ranks of the desired items. The reciprocal rank is set to zero if the rank is above 20. MRR takes into account the rank of the item, which is important in cases where the order of recommendations matter (e.g. the lower ranked items are only visible after scrolling). 4.1 BASELINES We compare the proposed network to a set of commonly used baselines. • POP: Popularity predictor that always recommends the most popular items of the training set. Despite its simplicity it is often a strong baseline in certain domains. S-POP: This baseline recommends the most popular items of the current session. The rec- ommendation list changes during the session as items gain more events. Ties are broken up using global popularity values. This baseline is strong in domains with high repetitiveness. • Item-KNN: Items similar to the actual item are recommended by this baseline and simi- larity is defined as the cosine similarity between the vector of their sessions, i.e. it is the number of co-occurrences of two items in sessions divided by the square root of the product of the numbers of sessions in which the individual items are occurred. Regularization is also included to avoid coincidental high similarities of rarely visited items. This baseline is one of the most common item-to-item solutions in practical systems, that provides recom- mendations in the “others who viewed this item also viewed these ones” setting. Despite of its simplicity it is usually a strong baseline (Linden et al., 2003; Davidson et al., 2010). # 1http://2015.recsyschallenge.com/ 6 Published as a conference paper at ICLR 2016 Table 1: Recall@20 and MRR@20 using the baseline methods Baseline RSC15 VIDEO Recall@20 MRR@20 Recall@20 MRR@20 POP S-POP Item-KNN BPR-MF 0.0050 0.2672 0.5065 0.2574 0.0012 0.1775 0.2048 0.0618 0.0499 0.1301 0.5508 0.0692 0.0117 0.0863 0.3381 0.0374 # Table 2: Best parametrizations for datasets/loss functions Dataset Loss Mini-batch Dropout Learning rate Momentum RSC15 RSC15 RSC15 VIDEO VIDEO VIDEO TOP1 BPR Cross-entropy TOP1 BPR Cross-entropy 50 50 500 50 50 200 0.5 0.2 0 0.4 0.3 0.1 0.01 0.05 0.01 0.05 0.1 0.05 0 0.2 0 0 0 0.3 • BPR-MF: BPR-MF (Rendle et al., 2009) is one of the commonly used matrix factorization methods. It optimizes for a pairwise ranking objective function (see Section 3) via SGD. Matrix factorization cannot be applied directly to session-based recommendations, because the new sessions do not have feature vectors precomputed. However we can overcome this by using the average of item feature vectors of the items that had occurred in the session so far as the user feature vector. In other words we average the similarities of the feature vectors between a recommendable item and the items of the session so far. Table 1 shows the results for the baselines. The item-KNN approach clearly dominates the other methods. 4.2 PARAMETER & STRUCTURE OPTIMIZATION We optimized the hyperparameters by running 100 experiments at randomly selected points of the parameter space for each dataset and loss function. The best parametrization was further tuned by individually optimizing each parameter. The number of hidden units was set to 100 in all cases. The best performing parameters were then used with hidden layers of different sizes. The optimization was done on a separate validation set. Then the networks were retrained on the training plus the validation set and evaluated on the final test set. The best performing parametrizations are summarized in table 2. Weight matrices were initialized by random numbers drawn uniformly from [−x, x] where x depends on the number of rows and columns of the matrix. We experimented with both rmsprop (Dauphin et al., 2015) and adagrad (Duchi et al., 2011). We found adagrad to give better results. We briefly experimented with other units than GRU. We found both the classic RNN unit and LSTM to perform worse. We tried out several loss functions. Pointwise ranking based losses, such as cross-entropy and MRR optimization (as in Steck (2015)) were usually unstable, even with regularization. For example cross-entropy yielded only 10 and 6 numerically stable networks of the 100 random runs for RSC15 and VIDEO respectively. We assume that this is due to independently trying to achieve high scores for the desired items and the negative push is small for the negative samples. On the other hand pairwise ranking-based losses performed well. We found the ones introduced in Section 3 (BPR and TOP1) to perform the best. Several architectures were examined and a single layer of GRU units was found to be the best performer. Adding addition layers always resulted in worst performance w.r.t. both training loss and recall and MRR measured on the test set. We assume that this is due to the generally short 7 Published as a conference paper at ICLR 2016 Table 3: Recall@20 and MRR@20 for different types of a single layer of GRU, compared to the best baseline (item-KNN). Best results per dataset are highlighted. Loss / #Units Recall@20 RSC15 MRR@20 Recall@20 VIDEO MRR@20 TOP1 100 BPR 100 Cross-entropy 100 TOP1 1000 BPR 1000 Cross-entropy 1000 0.5853 (+15.55%) 0.6069 (+19.82%) 0.6074 (+19.91%) 0.6206 (+22.53%) 0.6322 (+24.82%) 0.5777 (+14.06%) 0.2305 (+12.58%) 0.2407 (+17.54%) 0.2430 (+18.65%) 0.2693 (+31.49%) 0.2467 (+20.47%) 0.2153 (+5.16%) 0.6141 (+11.50%) 0.5999 (+8.92%) 0.6372 (+15.69%) 0.6624 (+20.27%) 0.6311 (+14.58%) – 0.3511 (+3.84%) 0.3260 (-3.56%) 0.3720 (+10.04%) 0.3891 (+15.08%) 0.3136 (-7.23%) – lifespan of the sessions not requiring multiple time scales of different resolutions to be properly represented. However the exact reason of this is unknown as of yet and requires further research. Using embedding of the items gave slightly worse results, therefore we kept the 1-of-N encoding. Also, putting all previous events of the session on the input instead of the preceding one did not result in additional accuracy gain; which is not surprising as GRU – like LSTM – has both long and short term memory. Adding additional feed-forward layers after the GRU layer did not help either. However increasing the size of the GRU layer improved the performance. We also found that it is beneficial to use tanh as the activation function of the output layer. 4.3 RESULTS Table 3 shows the results of the best performing networks. Cross-entropy for the VIDEO data with 1000 hidden units was numerically unstable and thus we present no results for that scenario. The results are compared to the best baseline (item-KNN). We show results with 100 and 1000 hidden units. The running time depends on the parameters and the dataset. Generally speaking the difference in runtime between the smaller and the larger variant is not too high on a GeForce GTX Titan X GPU and the training of the network can be done in a few hours2. On CPU, the smaller network can be trained in a practically acceptable timeframe. Frequent retraining is often desirable for recommender systems, because new users and items are introduced frequently. The GRU-based approach has substantial gain over the item-KNN in both evaluation metrics on both datasets, even if the number of units is 1003. Increasing the number of units further improves the results for pairwise losses, but the accuracy decreases for cross-entropy. Even though cross-entropy gives better results with 100 hidden units, the pairwise loss variants surpass these results as the number of units increase. Although, increasing the number of units increases the training times, we found that it was not too expensive to move from 100 units to 1000 on GPU. Also, the cross-entropy based loss was found to be numerically unstable as the result of the network individually trying to increase the score for the target items, while the negative push is relatively small for the other items. Therefore we suggest using any of the two pairwise losses. The TOP1 loss performs slightly better on these two datasets, resulting in ∼ 20 − 30% accuracy gain over the best performing baseline. # 5 CONCLUSION & FUTURE WORK In this paper we applied a kind of modern recurrent neural network (GRU) to new application do- main: recommender systems. We chose the task of session based recommendations, because it is a practically important area, but not well researched. We modified the basic GRU in order to fit the task better by introducing session-parallel mini-batches, mini-batch based output sampling and ranking loss function. We showed that our method can significantly outperform popular baselines that are used for this task. We think that our work can be the basis of both deep learning applications in recommender systems and session based recommendations in general. 2Using Theano with fixes for the subtensor operators on GPU. 3Except for using the BPR loss on the VIDEO data and evaluating for MRR. 8 Published as a conference paper at ICLR 2016 Our immediate future work will focus on the more thorough examination of the proposed network. We also plan to train the network on automatically extracted item representation that is built on content of the item itself (e.g. thumbnail, video, text) instead of the current input. # ACKNOWLEDGMENTS The work leading to these results has received funding from the European Union’s Seventh Frame- work Programme (FP7/2007-2013) under CrowdRec Grant Agreement n◦ 610594. # REFERENCES Cho, Kyunghyun, van Merri¨enboer, Bart, Bahdanau, Dzmitry, and Bengio, Yoshua. On the proper- ties of neural machine translation: Encoder-decoder approaches. arXiv preprint arXiv:1409.1259, 2014. Dauphin, Yann N, de Vries, Harm, Chung, Junyoung, and Bengio, Yoshua. Rmsprop and equi- librated adaptive learning rates for non-convex optimization. arXiv preprint arXiv:1502.04390, 2015. Davidson, James, Liebald, Benjamin, Liu, Junning, et al. The YouTube video recommendation system. In Recsys’10: ACM Conf. on Recommender Systems, pp. 293–296, 2010. ISBN 978-1- 60558-906-0. Duchi, John, Hazan, Elad, and Singer, Yoram. Adaptive subgradient methods for online learning and stochastic optimization. The Journal of Machine Learning Research, 12:2121–2159, 2011. Hidasi, B. and Tikk, D. Fast ALS-based tensor factorization for context-aware recommendation from implicit feedback. In ECML-PKDD’12, Part II, number 7524 in LNCS, pp. 67–82. Springer, 2012. Hidasi, Bal´azs and Tikk, Domonkos. General factorization framework for context-aware recommen- dations. Data Mining and Knowledge Discovery, pp. 1–30, 2015. ISSN 1384-5810. doi: 10.1007/ s10618-015-0417-y. URL http://dx.doi.org/10.1007/s10618-015-0417-y. Hinton, Geoffrey, Deng, Li, Yu, Dong, Dahl, George E, Mohamed, Abdel-rahman, Jaitly, Navdeep, Senior, Andrew, Vanhoucke, Vincent, Nguyen, Patrick, Sainath, Tara N, et al. Deep neural net- works for acoustic modeling in speech recognition: The shared views of four research groups. Signal Processing Magazine, IEEE, 29(6):82–97, 2012. Koren, Y. Factorization meets the neighborhood: a multifaceted collaborative filtering model. In SIGKDD’08: ACM Int. Conf. on Knowledge Discovery and Data Mining, pp. 426–434, 2008. Koren, Yehuda, Bell, Robert, and Volinsky, Chris. Matrix factorization techniques for recommender systems. Computer, 42(8):30–37, 2009. Linden, G., Smith, B., and York, J. Amazon. com recommendations: Item-to-item collaborative filtering. Internet Computing, IEEE, 7(1):76–80, 2003. Liu, Qiwen, Chen, Tianjian, Cai, Jing, and Yu, Dianhai. Enlister: Baidu’s recommender system for the biggest Chinese Q&A website. In RecSys-12: Proc. of the 6th ACM Conf. on Recommender Systems, pp. 285–288, 2012. Rendle, S., Freudenthaler, C., Gantner, Z., and Schmidt-Thieme, L. BPR: Bayesian personalized ranking from implicit feedback. In UAI’09: 25th Conf. on Uncertainty in Artificial Intelligence, pp. 452–461, 2009. ISBN 978-0-9749039-5-8. Russakovsky, Olga, Deng, Jia, Su, Hao, Krause, Jonathan, Satheesh, Sanjeev, Ma, Sean, Huang, Zhiheng, Karpathy, Andrej, Khosla, Aditya, Bernstein, Michael S., Berg, Alexander C., and Li, Fei-Fei. Imagenet large scale visual recognition challenge. CoRR, abs/1409.0575, 2014. URL http://arxiv.org/abs/1409.0575. 9 Published as a conference paper at ICLR 2016 Salakhutdinov, Ruslan, Mnih, Andriy, and Hinton, Geoffrey. Restricted boltzmann machines for collaborative filtering. In Proceedings of the 24th international conference on Machine learning, pp. 791–798. ACM, 2007. Sarwar, Badrul, Karypis, George, Konstan, Joseph, and Riedl, John. Item-based collaborative filter- ing recommendation algorithms. In Proceedings of the 10th international conference on World Wide Web, pp. 285–295. ACM, 2001. Shani, Guy, Brafman, Ronen I, and Heckerman, David. An mdp-based recommender system. In Proceedings of the Eighteenth conference on Uncertainty in artificial intelligence, pp. 453–460. Morgan Kaufmann Publishers Inc., 2002. Shi, Yue, Karatzoglou, Alexandros, Baltrunas, Linas, Larson, Martha, Oliver, Nuria, and Hanjalic, Alan. Climf: Learning to maximize reciprocal rank with collaborative less-is-more filtering. In Proceedings of the Sixth ACM Conference on Recommender Systems, RecSys ’12, pp. 139–146, New York, NY, USA, 2012. ACM. ISBN 978-1-4503-1270-7. doi: 10.1145/2365952.2365981. URL http://doi.acm.org/10.1145/2365952.2365981. Steck, Harald. Gaussian ranking by matrix factorization. In Proceedings of the 9th ACM Confer- ence on Recommender Systems, RecSys ’15, pp. 115–122, New York, NY, USA, 2015. ACM. ISBN 978-1-4503-3692-5. doi: 10.1145/2792838.2800185. URL http://doi.acm.org/ 10.1145/2792838.2800185. Van den Oord, Aaron, Dieleman, Sander, and Schrauwen, Benjamin. Deep content-based music recommendation. In Advances in Neural Information Processing Systems, pp. 2643–2651, 2013. Wang, Hao, Wang, Naiyan, and Yeung, Dit-Yan. Collaborative deep learning for recommender In Proceedings of the 21th ACM SIGKDD International Conference on Knowledge systems. Discovery and Data Mining, KDD ’15, pp. 1235–1244, New York, NY, USA, 2015. ACM. Weimer, Markus, Karatzoglou, Alexandros, Le, Quoc Viet, and Smola, Alex. Maximum margin ma- trix factorization for collaborative ranking. Advances in neural information processing systems, 2007. 10
Title: Unsolved Problems in ML Safety: Summary: Machine learning (ML) systems are rapidly increasing in size, are acquiring new capabilities, and are increasingly deployed in high-stakes settings. As with other powerful technologies, safety for ML should be a leading research priority. In response to emerging safety challenges in ML, such as those introduced by recent large-scale models, we provide a new roadmap for ML Safety and refine the technical problems that the field needs to address. We present four problems ready for research, namely withstanding hazards ("Robustness"), identifying hazards ("Monitoring"), reducing inherent model hazards ("Alignment"), and reducing systemic hazards ("Systemic Safety"). Throughout, we clarify each problem's motivation and provide concrete research directions. # Unsolved Problems in ML Safety Dan Hendrycks UC Berkeley Nicholas Carlini Google John Schulman OpenAI Jacob Steinhardt UC Berkeley # Abstract Machine learning (ML) systems are rapidly increasing in size, are acquiring new capabilities, and are increasingly deployed in high-stakes settings. As with other powerful technologies, safety for ML should be a leading research priority. In response to emerging safety challenges in ML, such as those introduced by recent large-scale models, we provide a new roadmap for ML Safety and refine the technical problems that the field needs to address. We present four problems ready for research, namely withstanding hazards (“Robustness”), identifying hazards (“Monitoring”), steering ML systems (“Alignment”), and reducing deployment hazards (“Systemic Safety”). Throughout, we clarify each problem’s motivation and provide concrete research directions. # 1 Introduction As machine learning (ML) systems are deployed in high-stakes environments, such as medical settings [147], roads [185], and command and control centers [39], unsafe ML systems may result in needless loss of life. Although researchers recognize that safety is important [1, 5], it is often unclear what problems to prioritize or how to make progress. We identify four problem areas that would help make progress on ML Safety: robustness, monitoring, alignment, and systemic safety. While some of these, such as robustness, are long-standing challenges, the success and emergent capabilities of modern ML systems necessitate new angles of attack. We define ML Safety research as ML research aimed at making the adoption of ML more beneficial, with emphasis on long-term and long-tail risks. We focus on cases where greater capabilities can be expected to decrease safety, or where ML Safety problems are otherwise poised to become more challenging in this decade. For each of the four problems, after clarifying the motivation, we discuss possible research directions that can be started or continued in the next few years. First, however, we motivate the need for ML Safety research. We should not procrastinate on safety engineering. In a report for the Department of Defense, Frola and Miller [55] observe that approximately 75% of the most critical decisions that determine a system’s safety occur early in development [121]. If attention to safety is delayed, its impact is limited, as unsafe design choices become deeply embedded into the system. The Internet was initially designed as an academic tool with neither safety nor security in mind [47]. Decades of security patches later, security measures are still incomplete and increasingly complex. A similar reason for starting safety work now is that relying on experts to test safety solutions is not enough—solutions must also be age tested. The test of time is needed even in the most rigorous of disciplines. A century before the four color theorem was proved, Kempe’s peer-reviewed proof went unchallenged for years until, finally, a flaw was uncovered [73]. Beginning the research process early allows for more prudent design and more rigorous testing. Since nothing can be done both hastily and prudently [176], postponing machine learning safety research increases the likelihood of accidents. Just as we cannot procrastinate, we cannot rely exclusively on previous hardware and software engineering practices to create safe ML systems. In contrast to typical software, ML control flows are specified by 1 # Unsolved Problems in ML Safety Robustness Create models that are resilient to adversaries, unusual situations, and Black Swan events. Detect malicious use, monitor predictions, and discover unexpected model functionality. Align ment Build models that represent and safely optimize hard-to-specify human values. Systemic Safety Use ML to address broader risks to how ML systems are handled, such as cyberattacks. inscrutable weights learned by gradient optimizers rather than programmed with explicit instructions and general rules from humans. They are trained and tested pointwise using specific cases, which has limited effectiveness at improving and assessing an ML system’s completeness and coverage. They are fragile, rarely correctly handle all test cases, and cannot become error-free with short code patches [157]. They exhibit neither modularity nor encapsulation, making them far less intellectually manageable and making causes of errors difficult to localize. They frequently demonstrate properties of self-organizing systems such as spontaneously emergent capabilities [23, 32]. They may also be more agent-like and tasked with performing open-ended actions in arbitrary complex environments. Just as, historically, safety methodologies developed for electromechanical hardware [166] did not generalize to the new issues raised by software, we should expect software safety methodologies not to generalize to the new complexities and hazards of ML. We also cannot solely rely on economic incentives and regulation to shepherd competitors into developing safe models. The competitive dynamics surrounding ML’s development may pressure companies and reg- ulators to take shortcuts on safety. Competing corporations often prioritize minimizing development costs and being the first to the market over providing the safest product. For example, Boeing developed the 737 MAX with unsafe design choices to keep pace with its competitors; and as a direct result of taking shortcuts on safety and pressuring inspectors, Boeing’s defective model led to two crashes across a span of five months that killed 346 people [174, 54, 110]. Robust safety regulation is almost always developed only after a catastrophe—a common saying in aviation is that “aviation regulations are written in blood.” While waiting for catastrophes to spur regulators can reduce the likelihood of repeating the same failure, this approach cannot prevent catastrophic events from occurring in the first place. Regulation efforts may also be obstructed by lobbying or by the spectre of lagging behind international competitors who may build superior ML systems. Consequently, companies and regulators may be pressured to deprioritize safety. These sources of hazards—starting safety research too late, novel ML system complexities, and competitive pressure—may result in deep design flaws. However, a strong safety research community can drive down these risks. Working on safety proactively builds more safety into systems during the critical early design window. This could help reduce the cost of building safe systems and reduce the pressure on companies to take shortcuts on safety. If the safety research community grows, it can help handle the spreading multitude of hazards that continue to emerge as ML systems become more complex. Regulators can also prescribe higher, more actionable, and less intrusive standards if the community has created ready-made safety solutions. When especially severe accidents happen, everyone loses. Severe accidents can cast a shadow that creates unease and precludes humanity from realizing ML’s benefits. Safety engineering for powerful technologies is challenging, as the Chernobyl meltdown, the Three Mile Island accident, and the Space Shuttle Challenger disaster have demonstrated. However, done successfully, work on safety can improve the likelihood that essential technologies operate reliably and benefit humanity. 2 # 2 Robustness # Black Swans # Adversaries Adapt to evolving environments + + Handle diverse perceptible attacks « Endure once-in-a-century events * Detect unforeseen attacks Figure 1: Robustness research aims to build systems that endure extreme, unusual, or adversarial events. 2.1 Black Swan and Tail Risk Robustness Motivation. To operate in open-world high-stakes environments, machine learning systems will need to endure unusual events and tail risks. However, current ML systems are often brittle in the face of real-world complexity and unknown unknowns. In the 2010 Flash Crash [100], automated trading systems unexpectedly overreacted to market aberrations, created a feedback loop, and wiped away a trillion dollars of stock value in a matter of minutes. This demonstrates that computer systems can both create and succumb to long tail events. Long tails continue to thwart modern ML systems such as autonomous vehicles. This is because some of the most basic concepts in the real world are long tailed, such as stop signs, where a model error can directly cause a crash and loss of life. Stop signs may be titled, occluded, or represented on an LED matrix; sometimes stop signs should be disregarded, for example when held upside down by a traffic officer, on open gates, on a shirt, on the side of bus, on elevated toll booth arms, and so on. Although these long tail events are rare, they are extremely impactful [181] and can cause ML systems to crash. Leveraging existing massive datasets is not enough to ensure ro- bustness, as models trained with Internet data and petabytes of task-specific driving data still are not robust to long tail road scenarios [185]. This decades-long challenge is only a preview of the more difficult problem of handling tail events in environments that are beyond a road’s complexity. Long-tail robustness is unusually challenging today and may become even more challenging. Long-tail ro- bustness also requires more than human-level robustness; the 2008 financial crisis and COVID-19 have shown that even groups of humans have great difficulty mitigating and overcoming these rare but extraordinarily im- pactful long tail events. Future ML systems will operate in environments that are broader, larger-scale, and more highly connected with more feedback loops, paving the way to more extreme events [130] than those seen today. While there are incentives to make systems partly robust, systems tend not to be incentivized nor designed for long tail events outside prior experience, even though Black Swan events are inevitable [192]. To reduce the chance that ML systems will fall apart in settings dominated by rare events, systems must be unusually robust. Directions. In addition to existing robustness benchmarks [78, 102, 75], researchers could create more environments and benchmarks to stress-test systems, find their breaking points, and determine whether they will function appropriately in potential future scenarios. These benchmarks could include new, unusual, and extreme distribution shifts and long tail events, especially ones that are challenging even for humans. Following precedents from industry [185, 7], benchmarks could include artificial simulated data that capture structural properties of real long tail events. Additionally, benchmarks should focus on “wild” distribution shifts that cause large accuracy drops over “mild” shifts [126]. Robustness work could also move beyond classification and consider competent errors where agents misgeneralize and execute wrong routines, such as an automated digital assistant knowing how to use a credit card to book flights, but choosing the wrong destination [101, 91]. Interactive environments [37] could simulate 3 qualitatively distinct random shocks that irreversibly shape the environment’s future evolution. Researchers could also create environments where ML system outputs affect their environment and create feedback loops. Using such benchmarks and environments, researchers could improve ML systems to withstand Black Swans [182, 181], long tails, and structurally novel events. The performance of many ML systems is currently largely shaped by data and parameter count, so future research could work on creating highly unusual but helpful data sources. The more experience a system has with unusual future situations, even ones not well represented in typical training data, the more robust it can be. New data augmentation techniques [86, 84] and other sources of simulated data could create inputs that are not easy or possible to create naturally. Since change is a part of all complex systems, and since not everything can be anticipated during training, models will also need to adapt to an evolving world and improve from novel experiences [131, 196, 180]. Future adaptation methods could improve a system’s ability to adapt quickly. Other work could defend adaptive systems against poisoned data encountered during deployment [129]. 2.2 Adversarial Robustness Motivation. We now turn from unpredictable accidents to carefully crafted and deceptive threats. Adversaries can easily manipulate vulnerabilities in ML systems and cause them to make mistakes [15, 177]. For example, systems may use neural networks to detect intruders [4] or malware [173], but if adversaries can modify their behavior to deceive and bypass detectors, the systems will fail. While defending against adversaries might seem to be a straightfoward problem, defenses are currently struggling to keep pace with attacks [8, 188], and much research is needed to discover how to fix these longstanding weaknesses. Directions. We encourage research on adversarial robustness to focus on broader robustness definitions. Current research largely focuses on the problem of “¢,, adversarial robustness,” [125, 30] where an adversary attempts to induce a misclassification but can only perturb inputs subject to a small p-norm constraint. While research on simplified problems helps drive progress, researchers may wish to avoid focusing too heavily on any one particular simplification. To study adversarial robustness more broadly [61], researchers could consider attacks that are perceptible [142] or whose specifications are not known beforehand [97, 112]. For instance, there is no reason that an adversarial malware sample would have to be imperceptibly similar to some other piece of benign software—as long as the detector is evaded, the attack has succeeded [140]. Likewise, copyright detection systems cannot reasonably assume that attackers will only construct small ¢, perturbations to bypass the system, as attackers may rotate the adversarially modified image [51] or apply otherwise novel distortions [61] to the image. While many effective attacks assume full access to a neural network, sometimes assuming limited access is more realistic. Here, adversaries can feed in examples to an ML system and receive the system’s outputs, but they do not have access to the intermediate ML system computation [21]. If a blackbox ML system is not publicly released and can only be queried, it may be possible to practically defend the system against zero-query attacks [189] or limited-query attacks [35]. On the defense side, further underexplored assumptions are that systems have multiple sensors or that systems can adapt. Real world systems, such as autonomous vehicles, have multiple cameras. Researchers could exploit information from these different sensors and find inconsistencies in adversarial images in order to constrain and box in adversaries [202]. Additionally, while existing ML defenses are typically static, future defenses could evolve during test time to combat adaptive adversaries [195]. Future research could do more work toward creating models with adversarially robust representations [41]. Researchers could enhance data for adversarial robustness by simulating more data [208], augmenting data [151], repurposing existing real data [31, 80], and extracting more information from available data [82]. Others could create architectures that are more adversarially robust [203]. Others could improve adversarial training methods [201] and find better losses [206, 179]. Researchers could improve adversarial robustness certifications [146, 117, 38], so that models have verifiable adversarial robustness. It may also be possible to unify the areas of adversarial robustness and robustness to long-tail and unusual events. By building systems to be robust to adversarial worst-case environments, they may also be made more robust to random-worse-case environments [6, 85]. To study adversarial robustness on unusual inputs, researchers could also try detecting adversarial anomalies [17, 85] or assigning them low confidence [172]. 4 # 3 Monitoring ZN # Anomaly Detection # Representative Model Outputs # Hidden Functionality ¢ Warn operators * Calibrate probabilities + Find model trojans ¢ Flag novel misuses Know when to override * Scan for capabilities Figure 2: Monitoring research aims to identify hazards, inspect models, and help human ML system operators. 3.1 Motivation. Deploying and monitoring powerful machine learning systems will require high caution, similar to the caution observed for modern nuclear power plants, military aircraft carriers, air traffic control, and other high-risk systems. These complex and hazardous systems are now operated by high reliability organizations (HROs) which are relatively successful at avoiding catastrophes [48]. For safe deployment, future ML systems may be operated by HROs. Anomaly detectors are a crucial tool for these organizations since they can warn human operators of potential hazards [144]. For detectors to be useful, research must strive to create detectors with high recall and a low false alarm rate in order to prevent alarm fatigue [42]. Separately, anomaly detection is essential in detecting malicious uses of ML systems [24]. Malicious users are incentivized to use novel strategies, as familiar misuse strategies are far easier to identify and prevent compared to unfamiliar ones. Malicious actors may eventually repurpose ML systems for social manipulation [28], for assisting research on novel weapons [19], or for cyberattacks [27]. When such anomalies are detected, the detector can trigger a fail-safe policy in the system and also flag the example for human intervention. However, detecting malicious anomalous behavior could become especially challenging when malicious actors utilize ML capabilities to try to evade detection. Anomaly detection is integral not just for promoting reliability but also for preventing novel misuses. Directions. Anomaly detection is actively studied in research areas such as out-of-distribution detection [79], open-set detection [11], and one-class learning [178, 82], but many challenges remain. The central challenge is that existing methods for representation learning have difficulty discovering representations that work well for previously unseen anomalies. One of the symptoms of this problem is that anomaly detectors for large-scale images still cannot reliably detect that previously unseen random noise is anomalous [81]. Moreover, there are many newer settings that require more study, such as detecting distribution shifts or changes to the environment [45], as well developing detectors that work in real-world settings such as intrusion detection, malware detection, and biosafety. Beyond just detecting anomalies, high reliability organizations require candidate explanations of how an anomaly came to exist [144, 163]. To address this, detectors could help identify the origin or location of an anomaly [14]. Other work could try to help triage anomalies and determine whether an anomaly is just a negligible nuisance or is potentially hazardous. # 3.2 Representative Model Outputs # 3.2.1 Calibration Motivation. Human monitors need to know when to trust a deployed ML system or when to override it. If they cannot discern when to trust and when to override, humans may unduly defer to models and cede too much control. If they can discern this, they can prevent many model hazards and failure modes. 5 To make models more trustworthy, they should accurately assess their domain of competence [60]—the set of inputs they are able to handle. Models can convey the limits of their competency by expressing their uncertainty. However, model uncertainties are not representative, and they are often overconfident [68]. To address this, models could become more calibrated. If a model is perfectly calibrated and predicts a “70% chance of rain,” then when it makes that prediction, 70% of the time it will rain. Calibration research makes model prediction probabilities more representative of a model’s overall behavior, provides monitors with a clearer impression of their understanding, and helps monitors weigh model decisions. Directions. To help models express their domain of competence in a more representative and meaningful way, researchers could further improve model calibration on typical testing data [68, 133, 113, 109, 205, 107, 108, 124], though the greater challenge is calibration on testing data that is unlike the training data [137]. Future systems could communicate their uncertainty with language. For example, they could express decomposed probabilities with contingencies such as “event A will occur with 60% probability assuming event B also occurs, and with 25% probability if event B does not.” To extend calibration beyond single-label outputs, researchers could take models that generate diverse sentence and paragraph answers and teach these models to assign calibrated confidences to their generated free-form answers. # 3.2.2 Making Model Outputs Honest and Truthful Motivation. Human monitors can more effectively monitor models if they produce outputs that accurately, honestly, and faithfully [62] represent their understanding or lack thereof. However, current language models do not accurately represent their understanding and do not provide faithful explanations. They generate empty explanations that are often surprisingly fluent and grammatically correct but nonetheless entirely fabricated. These models generate distinct explanations when asked to explain again, generate more misconceptions as they become larger [123], and sometimes generate worse answers when they know how to generate better answers [34]. If models can be made honest and only assert what they believe, then they can produce outputs that are more representative and give human monitors a more accurate impression of their beliefs. Directions. Researchers could create evaluation schemes that catch models being inconsistent [50], as inconsistency implies that they did not assert only what they believe. Others could also build tools to detect when models are hallucinating information [118]. To prevent models from outputting worse answers when they know better answers, researchers can concretize what it means for models to assert their true beliefs or to give the right impression. Finally, to train more truthful models, researchers could create environments [139] or losses that incentivize models not to state falsehoods, repeat misconceptions [123], or spread misinformation. # 3.3 Hidden Model Functionality # 3.3.1 Backdoors Motivation. Machine learning systems risk carrying hidden “backdoor” or “trojan” controllable vulnerabili- ties. Backdoored models behave correctly and benignly in almost all scenarios, but in particular circumstances chosen by an adversary, they have been taught to behave incorrectly [67]. Consider a backdoored facial recognition system that gates building access. The backdoor could be triggered by a specific unique item chosen by an adversary, such as an item of jewelry. If the adversary wears that specific item of jewelry, the backdoored facial recognition will allow the adversary into the building [160]. A particularly important class of vulnerabilities are backdoors for sequential decision making systems, where a particular trigger leads an agent or language generation model to pursue a coherent and destructive sequence of actions [198, 207]. Whereas adversarial examples are created at test time, backdoors are inserted by adversaries at training time. One way to create a backdoor is to directly inject the backdoor into a model’s weights [156, 90], but they can also be injected by adding poisoned data into the training or pretraining data [158]. Injecting backdoors through poisoning is becoming easier as ML systems are increasingly trained on uncurated data scraped from online—data that adversaries can poison. If an adversary uploads a few carefully crafted poisoned images [29], code snippets [156], or sentences [194] to platforms such as Flickr, GitHub or Twitter, they can inject a backdoor into future models trained on that data [10]. Moreover, since downstream models are increasingly obtained by a single upstream model [18], a single compromised model could proliferate backdoors. 6 Directions. To avoid deploying models that may take unexpected turns and have vulnerabilities that can be controlled by an adversary, researchers could improve backdoor detectors to combat an ever-expanding set of backdoor attacks [98]. Creating algorithms and techniques for detecting backdoors is promising, but to stress test them we need to simulate an adaptive competition where researchers take the role of both attackers and auditors. This type of competition could also serve as a valuable way of grounding general hidden model func- tionality detection research. Researchers could try to cleanse models with backdoors, reconstruct a clean dataset given a model [204, 197], and build techniques to detect poisoned training data. Research should also develop methods for addressing backdoors that are manually injected, not just those injected through data poisoning. # 3.3.2 Emergent Hazardous Capabilities Motivation. We are better able to make models safe when we know what capabilities they possess. For early ML models, knowing their limits was often trivial, as models trained on MNIST can do little more than classify handwritten images. However, recent large-scale models often have capabilities that their designers do not initially realize, with novel and qualitatively distinct capabilities emerging as scale increases. For example, as GPT-3 models became larger [23], they gained the ability to perform arithmetic, even though GPT-3 received no explicit arithmetic supervision. Others have observed instances where a model’s training loss remains steady, but then its test performance spontaneously ascends from random chance to perfect generalization [143]. Sometimes capabilities are only discovered after initial release. After a multimodal image and text model [145] was released, users eventually found that its synthesized images could be markedly improved by appending “generated by Unreal Engine” to the query [13]. Future ML models may, when prompted carefully, make the synthesis of harmful or illegal content seamless (such as videos of child exploitation, suggestions for evading the law, or instructions for building bombs). These examples demonstrate that it will be difficult to safely deploy models if we do not know their capabilities. Some emergent capabilities may resist monitoring. In the future, it is conceivable that agent-like models may be inadvertently incentivized to adopt covert behavior. This is not unprecedented, as even simple digital organisms can evolve covert behavior. For instance, Ofria’s [119] digital organisms evolved to detect when they were being monitored and would “play dead” to bypass the monitor, only to behave differently once monitoring completed. In the automotive industry, Volkswagen created products designed to bypass emissions monitors, underscoring that evading monitoring is sometimes incentivized in the real world. Advanced ML agents may be inadvertently incentivized to be deceptive not out of malice but simply because doing so may help maximize their human approval objective. If advanced models are also capable planners, they could be skilled at obscuring their deception from monitors. Directions. To protect against emergent capabilities, researchers could create techniques and tools to inspect models and better foresee unexpected jumps in capabilities. We also suggest that large research groups begin scanning models for numerous potential and as yet unobserved capabilities. We specifically suggest focusing on capabilities that could create or directly mitigate hazards. One approach is to create a continually evolving testbed to screen for potentially hazardous capabilities, such as the ability to execute malicious user-supplied code, generate illegal or unethical forms of content, or to write convincing but wrong text on arbitrary topics. Another more whitebox approach would be to predict a model’s capabilities given only its weights, which might reveal latent capabilities that are not obviously expressible from standard prompts. Detection methods will require validation to ensure they are sufficiently sensitive. Researchers could implant hidden functionality to ensure that detection methods can detect known flaws; this can also help guide the development of better methods. Other directions include quantifying and extrapolating future model capabilities [87, 88] and searching for novel failure modes that may be symptoms of unintended functionality. Once a hazardous capability such as deception or illegal content synthesis is identified, the capability must be prevented or removed. Researchers could create training techniques so that undesirable capabilities are not acquired during training or during test-time adaptation. For ML systems that have already acquired an undesirable capability, researchers could create ways to teach ML systems how to forget that capability. However, it may not be straightforward to determine whether the capability is truly absent and not merely obfuscated or just removed partially. 7 # 4 Alignment # Challenges With Aligning Objectives Challenges Aligning Objectives Specification Brittleness * Track nebuluous goals + Prevent overoptimization « Learn complex objectives * Proxy gaming * Pursue only the main objective « Emergent power-seeking goals * Tradeoffs of complex goals * Cautious and constrained behavior Optimization Unintended Consequences é lig Figure 3: Alignment research aims to create and safely optimize ML system objectives. While most technologies do not have goals and are simply tools, future machine learning systems may be more agent-like. How can we build ML agents that prefer good states of the world and avoid bad ones? Objective functions drive system behavior, but aligning objective functions with human values requires overcoming societal as well as technical challenges. We briefly discuss societal challenges with alignment and then describe technical alignment challenges in detail. Ensuring powerful future ML systems have aligned goals may be challenging because their goals may be given by some companies that do not solely pursue the public interest. Unfortunately, sometimes corporate incentives can be distorted in the pursuit of maximizing shareholder value [94]. Many companies help satisfy human desires and improve human welfare, but some companies have been incentivized to decimate rain forests [59], lie to customers that cigarettes are healthy [20], invade user privacy [209], and cut corners on safety [175]. Even if economic entities were more aligned, such as if corporations absorbed their current negative externalities, the larger economic system would still not be fully aligned with all human values. This is because the overall activity of the economy can be viewed as approximating material wealth maximization [141]. However, once wealth increases enough, it ceases to be correlated with emotional wellbeing and happiness [96]. Furthermore, wealth maximization with advanced ML may sharply exacerbate inequality [65], which is a robust predictor of aggression and conflict [53]. Under extreme automation in the future, wealth metrics such as real GDP per capita may drift further from tracking our values [26]. Given these considerations, the default economic objective shaping the development of ML is not fully aligned with human values. Even if societal issues are resolved and ideal goals are selected, technical problems remain. We focus on four important technical alignment problems: objective proxies are difficult to specify, objective proxies are difficult to optimize, objective proxies can be brittle, and objective proxies can spawn unintended consequences. 4.1 Objectives Can Be Difficult to Specify Motivation for Value Learning. Encoding human goals and intent is challenging. Lawmakers know this well, as laws specified by stacks of pages still often require that people interpret the spirit of the law. Many human values, such as happiness [116], good judgment [167], meaningful experiences [52], human autonomy, and so on, are hard to define and measure. Systems will optimize what is measurable [152], as “what gets measured gets managed.” Measurements such as clicks and watch time may be easily measurable, but they often leave out and work against important human values such as wellbeing [105, 52, 170, 171]. Researchers will need to confront the challenge of measuring abstract, complicated, yet fundamental human values. Directions. Value learning seeks to develop better approximations of our values, so that corporations and policy makers can give systems better goals to pursue. Some important values include wellbeing, fairness, and people getting what they deserve. To model wellbeing, future work could use ML to model what people find pleasant, how stimuli affect internal emotional valence, and other aspects of subjective experience. Other work could try to learn how to align specific technologies, such as recommender systems, with wellbeing goals rather than engagement. Future models deployed in legal contexts must understand justice, so models should be taught the law [77]. Researchers could create models that learn wellbeing functions that do not mimic cognitive 8 biases [76]. Others could make models that are able to detect when scenarios are clear-cut or highly morally contentious [76]. Other directions include learning difficult-to-specify goals in interactive environments [70], learning the idiosyncratic values of different stakeholders [122], and learning about cosmopolitan goals such as endowing humans with the capabilities necessary for high welfare [135]. 4.2 Objectives Can Be Difficult to Optimize Motivation for Translating Values Into Action. Putting knowledge from value learning into practice may be difficult because optimization is difficult. For example, many sparse objectives are easy to specify but difficult to optimize. Worse, some human values are particularly difficult to optimize. Take, for instance, the optimization of wellbeing. Short-term and long-term wellbeing are often anticorrelated, as the hedonistic paradox shows [164]. Hence many local search methods may be especially prone to bad local optima, and they may facilitate the impulsive pursuit of pleasure. Consequently, optimization needs to be on long timescales, but this reduces our ability to test our systems iteratively and rapidly, and ultimately to make them work well. Further, human wellbeing is difficult to compare and trade off with other complex values, is difficult to forecast even by humans themselves [200], and wellbeing often quickly adapts and thereby nullifies interventions aimed at improving it [22]. Optimizing complex abstract human values is therefore not straightforward. To build systems that optimize human values well, models will need to mediate their knowledge from value learning into appropriate action. Translating background knowledge into choosing the best action is typically not straightforward: while computer vision models are advanced, successfully applying vision models for robotics remains elusive. Also, while sociopaths are intelligent and have moral awareness, this knowledge does not necessarily result in moral inclinations or moral actions. As systems make objectives easier to optimize and break them down into new goals, subsystems are created that optimize these new intrasystem goals. But a common failure mode is that “intrasystem goals come first” [57]. These goals can steer actions instead of the primary objective [91]. Thus a system’s explicitly written ob- jective is not necessarily the objective that the system operationally pursues, and this can result in misalignment. Directions. To make models optimize desired objectives and not pursue undesirable secondary objectives, researchers could try to construct systems that guide models not just to follow rewards but also behave morally [83]; such systems could also be effective at guiding agents not to cause wanton harm within interactive environments and to abide by rules. To get a sense of an agent’s values and see how it make tradeoffs between values, researchers could also create diverse environments that capture realistic morally salient scenarios and characterize the choices that agents make when faced with ethical quandaries. Research on steerable and controllable text generation [104, 99] could help chatbots exhibit virtues such as friendliness and honesty. 4.3 Objective Proxies Can Be Brittle Proxies that approximate our objectives are brittle, but work on Proxy Gaming and Value Clarification can help. Motivation for Proxy Gaming. Objective proxies can be gamed by optimizers and adversaries. For exam- ple, to combat a cobra infestation, a governor of Delhi offered bounties for dead cobras. However, as the story goes, this proxy was brittle and instead incentivized citizens to breed cobras, kill them, and collect a bounty. In other contexts, some students overoptimize their GPA proxies by taking easier courses, and some academics overoptimize bibliometric proxies at the expense of research impact. Agents in reinforcement learning often find holes in proxies. In a boat racing game, an RL agent gained a high score not by finishing the race but by going in the wrong direction, catching on fire, and colliding into other boats [36]. Since proxies “will tend to collapse once pressure is placed upon” them by optimizers [64, 127, 169], proxies can often be gamed. Directions. Advancements in robustness and monitoring are key to mitigating proxy gaming. “When a measure becomes a target, it ceases Goodhart’s Law to be a good measure.” ML systems encoding proxies must become more robust to optimizers, which is to say they must become more adversarially robust (Section 2.2). Specifically, suppose a neural network is used to define a learned utility function; if some other agent (say another neural network) is tasked with maximizing this utility proxy, it would be incentivized to find and exploit any errors in the learned utility proxy, similar to adversarial examples [187, 63]. Therefore we should seek to ensure adversarial 9 robustness of learned reward functions, and regularly test them for exploitable loopholes. Separately, advancements in monitoring can help with proxy gaming. For concreteness, we discuss how monitoring can specifically help with “human approval” proxies, but many of these directions can help with proxy gaming in general. A notable failure mode of human approval proxies is their susceptibility to deception. Anomaly detectors (Section 3.1) could help spot when ML models are being deceptive or stating falsehoods, could help monitor agent behavior for unexpected activity, and could help determine when to stop the agent or intervene. Research on making models honest and teaching them to give the right impression (Section 3.2) can help mitigate deception from models trying to game approval proxies. To make models more truthful and catch deception, future systems could attempt to verify statements that are difficult for humans to check in reasonable timespans, and they could inspect convincing but not true assertions [139]. Researchers could determine the veracity of model assertions, possibly through an adversarial truth-finding process [93]. Motivation for Value Clarification. While maximization can expose faults in proxies, so too can future events. The future will sharpen and force us to confront unsolved ethical questions about our values and objec- tives [199]. In recent decades, peoples’ values have evolved by confronting philosophical questions, including whether to infect volunteers for science, how to equitably distribute vaccines, the rights of people with different orientations, and so on. How are we to act if many humans spend most of their time chatting with compelling bots and not much time with humans, or how should we fairly address automation’s economic ramifications? Determining the right action is not strictly scientific in scope [92], and we will need philosophical analysis to help us correct structural faults in our proxies. Directions. We should build systems to help rectify our objectives and proxies, so that we are less likely to optimize the wrong objective when a change in goals is necessary. This requires interdisciplinary research to- wards a system that can reason about values and philosophize at an expert level. Research could start with trying to build a system to score highly in the philosophy olympiad, in the same way others are aiming to build expert- level mathematician systems using mathematics olympiad problems [128]. Other work could build systems to help extrapolate the end products of “reflective equilibrium” [149], or what objectives we would endorse by sim- ulating a process of deliberation about competing values. Researchers could also try to estimate the quality of a philosophical work by using a stream of historical philosophy papers and having models predict the impact of each paper on the literature. Eventually, researchers should seek to build systems that can formulate robust posi- tions through an argumentative dialog. These systems could also try to find flaws in verbally specified proxies. 4.4 Objective Proxies Can Lead to Unintended Consequences Motivation. While optimizing agents may work towards subverting a proxy, in other situations both the proxy setter and an optimizing agent can fall into states that neither intended. For example, in their pursuit to modernize the world with novel technologies, previous well-intentioned scientists and engineers inadvertently increased pollution and hastened climate change, an outcome desired neither by the scientists themselves nor by the societal forces that supported them. In ML, some platforms maximized clickthrough rates to approximate maximizing enjoyment, but such platforms unintentionally addicted many users and decreased their wellbeing. These cases demonstrate that unintended consequences present a challenging but important problem. Directions. Future research could focus on designing minimally invasive agents that prefer easily reversible to irreversible actions [66], as irreversibility reduces humans’ optionality and often unintentionally destroys potential future value. Likewise, researchers could create agents that properly account for their lack of knowledge of the true objective [69] and avoid disrupting parts of the environment whose value is unclear [190, 103, 159]. We also need more complex environments that can manifest diverse unintended side effects [193] such as feedback loops, which are a source of hazards to users of recommender systems [106]. A separate way to mitigate unintended consequences is to teach ML systems to abide by constraints [150, 155], be less brazen, and act cautiously. Since we may be uncertain about which values are best, research could focus on having agents safely optimize and balance many values, so that one value does not unintentionally dominate or subvert the rest [132, 49]. Sometimes unintended instrumental goals emerge in systems, such as self-preservation [69] or power-seeking [191], so researchers could try mitigating and detecting such unintended emergent goals; see Section 3.3.2 for more directions in detecting emergent functionality. 10 # 5 Systemic Safety & ML for Cybersecurity Informed Decision Making * ML for patching insecure code + Forecasting events and effects * ML for detecting cyberattacks + Raising crucial considerations Figure 4: Systemic safety research aims to address broader contextual risks to how ML systems are handled. Both cybersecurity and decision making may decisively affect whether ML systems will fail or be misdirected. Machine learning systems do not exist in a vacuum, and the safety of the larger context can influence how ML systems are handled and affect the overall safety of ML systems. ML systems are more likely to fail or be misdirected if the larger context in which they operate is insecure or turbulent. Systemic safety research applies ML to mitigate potential contextual hazards that may decisively cause ML systems to fail or be misdirected. As two examples, we support research on cybersecurity and on informed decision making. The first problem is motivated by the observation that ML systems are integrated with vulnerable software, and in the future ML may change the landscape of cyberattacks. In the second problem, we turn to a speculative approach for improving governance decisions and command and control operations using ML, as institutions may direct the most powerful future ML systems. Beyond technical work, policy and governance work will be integral to safe deployment [43, 12, 16, 210, 25]. While techno-solutionism has limitations, technical ML researchers should consider using their skillset to address deployment environment hazards, and we focus on empirical ML research avenues, as we expect most readers are technical ML researchers. Finally, since there are multiple hazards that can hinder systemic safety, this section is nonexhaustive. For instance, if ML industry auditing tools could help regulators more effectively regulate ML systems, research developing such tools could become part of systemic safety. Likewise, using ML to help facilitate cooperation [44] may emerge as a research area. 5.1 ML for Cybersecurity Motivation. Cybersecurity risks can make ML systems unsafe, as ML systems operate in tandem with traditional software and are often instantiated as a cyber-physical system. As such, malicious actors could exploit insecurities in traditional software to control autonomous ML systems. Some ML systems may also be private or unsuitable for proliferation, and they will therefore need to operate on computers that are secure. Separately, ML may amplify future automated cyberattacks and enable malicious actors to increase the accessibility, potency, success rate, scale, speed, and stealth of their attacks. For example, hacking currently requires specialized skills, but if state-of-the-art ML models could be fine-tuned for hacking, then the barrier to entry for hacking may decrease sharply. Since cyberattacks can destroy valuable information and even destroy critical physical infrastructure [33] such as power grids [136] and building hardware [115], these potential attacks are a looming threat to international security. While cybersecurity aims to increase attacker costs, the cost-benefit analysis may become lopsided if attackers eventually gain a larger menu of options that require negligible effort. In this new regime, attackers may gain the upper hand, like how attackers of ML systems currently have a large advantage over defenders. Since there may be less of a duality between offensive and defensive security in the future, we suggest that research focus on techniques that are clearly defensive. The severity of this risk is speculative, but neural networks are now rapidly gaining the ability to write code and interact with the outside environment, and at the same time there is very little research on deep learning for cybersecurity. 11 Directions. To mitigate the potential harms of automated cyberattacks to ML and other systems, researchers should apply ML to develop better defensive techniques. For instance, ML could be used to detect intruders [114, 165] or impersonators [89]. ML could also help analyze code and detect software vulnerabilities.Massive unsupervised ML methods could also model binaries and learn to detect malicious obfuscated payloads [168, 161, 134, 71]. Researchers could also create ML systems that model software behavior and detect whether programs are sending packets when they should not. ML models could help predict future phases of cyberattacks, and such automated warnings could be judged by their lead time, precision, recall, and the quality of their contextualized explanation. Advancements in code translation [111, 9] and code generation [34, 138] suggest that future models could apply security patches and make code more secure, so that future systems not only flag security vulnerabilities but also fix them. 5.2 Motivation. Even if we create reliable ML systems, these systems will not exhibit or ensure safety if the institutions that steer ML systems make poor decisions. Although nuclear weapons are a reliable and depend- able technology, they became especially unsafe during the Cold War. During that time, misunderstanding and political turbulence exposed humanity to several close calls and brought us to the brink of catastrophe, demonstrating that systemic safety issues can make technologies unsafe. The most pivotal decisions are made during times of crisis, and future crises may be similarly risky as ML continues to be weaponized [153, 2]. This is why we suggest creating tools to help decision-makers handle ML systems in highly uncertain, quickly evolving, turbulent situations. Directions. To improve the decision-making and epistemics of political leaders and command and control centers, we suggest two efforts: using ML to improve forecasting and bringing to light crucial considerations. Many governance and command and control decisions are based on forecasts [186] from humans, and some forecasts are starting to incorporate ML [39]. Forecasters assign probabilities to possible events that could happen within the next few months or years (e.g., geopolitical, epidemiological, and industrial events), and are scored by their correctness and calibration. To be successful, forecasters must dynamically aggregate information from disparate unstructured sources [95]. This is challenging even for humans, but ML systems could potentially aggregate more information, be faster, be nonpartisan, consider multiple perspectives, and thus ultimately make more accurate predictions [148]. The robustness of such systems could be assessed based on their ability to predict pivotal historical events, if the model only has access to data before those events. An accurate forecasting tool would need to be applied with caution to prevent over-reliance [74], and it would need to present its data carefully so as not to encourage risk-taking behavior from the humans operating the forecasting system [183]. Separately, researchers should develop systems that identify questions worth asking and crucial factors to consider. While forecasting can refine estimates of well-defined risks, these advisory systems could help unearth new sources of risk and identify actions to mitigate risks. Since ML systems can process troves of historical data and can learn from diverse situations during training, they could suggest possibilities that would otherwise require extensive memory and experience. Such systems could help orient decision making by providing related prior scenarios and relevant statistics such as base rates. Eventually advisory systems could identify stakeholders, propose metrics, brainstorm options, suggest alternatives, and note trade-offs to further improve decision quality [58]. In summary, ML systems that can predict a variety of events and identify crucial considerations could help provide good judgment and correct misperceptions, and thereby reduce the chance of rash decisions and inadvertent escalation. # 6 Related Research Agendas There is a large ecosystem of work on addressing societal consequences of machine learning, including AI policy [43], privacy [3, 162], fairness [72], and ethics [56]. We strongly support research on these related areas. For purposes of scope, in this section we focus on papers that outline paths towards creating safe ML systems. An early work that helps identify safety problems is Russell et al., 2015 [154], who identify many potential 12 Alignment Sey Monitoring | Wg | Robustness O92}. ° ° O 9 o oT Figure 5: A Swiss cheese model of ML Safety research. Pursuing multiple safety research avenues creates multiple layers of protection which mitigates hazards and makes ML systems safer. avenues for safety, spanning robustness, machine ethics, research on AI’s economic impact, and more. Amodei and Olah et al., 2016 [5] helped further concretize several safety research directions. With the benefit of five years of hindsight, our paper provides a revised and expanded collection of concrete problems. Some of our themes extend the themes in Amodei and Olah et al., such as Robustness and some portions of Alignment. We focus here on problems that remain unsolved and also identify new problems, such as emergent capabilities from massive pretrained models, that stem from recent progress in ML. We also broaden the scope by iden- tifying systemic safety risks surrounding the deployment context of ML. The technical agenda of Taylor et al., 2016 [184] considers similar topics to Amodei and Olah et al., and Leike et al., 2018 [120] considers safety research directions in reward modeling. Although Leike et al.’s research agenda focuses on reinforcement learning, they highlight the importance of various other research problems including adversarial training and uncertainty estimation. Recently, Critch and Krueger, 2020 [40] provide an extensive commentary on safety research directions and discuss safety when there are multiple stakeholders. 7 Conclusion This work presented a non-exhaustive list of four unsolved research problems, all of which are interconnected and interdependent. Anomaly detection, for example, helps with detecting proxy gaming, detecting suspicious cyberactivity, and executing fail-safes in the face of unexpected events. Achieving safety requires research on all four problems, not just one. To see this, recall that a machine learning system that is not aligned with human values may be unsafe in and of itself, as it may create unintended consequences or game human approval proxies. Even if it is possible to create aligned objectives for ML systems, Black Swan events could cause ML systems to misgeneralize and pursue incorrect goals, malicious actors may launch adversarial attacks or compromise the software on which the ML system is running, and humans may need to monitor for emergent functionality and the malicious use of ML systems. As depicted in Figure 5’s highly simplified model, work on all four problems helps create comprehensive and layered protective measures against a wide range of safety threats. As machine learning research evolves, the community’s aims and expectations should evolve too. For many years, the machine learning community focused on making machine learning systems work in the first place. However, machine learning systems have had notable success in domains from images, to natural language, to programming—therefore our focus should expand beyond just accuracy, speed, and scalability. Safety must now become a top priority. Safety is not auxiliary in most current widely deployed technology. Communities do not ask for “safe bridges,” but rather just “bridges.” Their safety is insisted upon—even assumed—and incorporating safety features is imbued in the design process. The ML community should similarly create a culture of safety and elevate its standards so that ML systems can be deployed in safety-critical situations. 13 Acknowledgements We would like to thank Sidney Hough, Owain Evans, Collin Burns, Alex Tamkin, Mantas Mazeika, Kevin Liu, Jonathan Uesato, Steven Basart, Henry Zhu, D. Sculley, Mark Xu, Beth Barnes, Andreas Terzis, Florian Tramèr, Stella Biderman, Leo Gao, Jacob Hilton, and Thomas Dietterich for their feedback. DH is supported by the NSF GRFP Fellowship and an Open Philanthropy Project AI Fellowship. # References [1] Signed by approximately 2000 AI researchers. “Asilomar AI Principles”. In: (2017). [2] Signed by 30000+ people. “Autonomous Weapons: An Open Letter from AI and Robotics Researchers”. In: (2015). [3] Martín Abadi, Andy Chu, I. Goodfellow, H. B. McMahan, Ilya Mironov, Kunal Talwar, and L. Zhang. “Deep Learning with Differential Privacy”. In: Proceedings of the 2016 ACM SIGSAC Conference on Computer and Communications Security (2016). [4] Zeeshan Ahmad, A. Khan, W. Cheah, J. Abdullah, and Farhan Ahmad. “Network intrusion detection system: A systematic study of machine learning and deep learning approaches”. In: Trans. Emerg. Telecommun. Technol. (2021). [5] Dario Amodei, Christopher Olah, Jacob Steinhardt, Paul Christiano, John Schulman, and Dandelion Mané. “Concrete Problems in AI Safety”. In: ArXiv (2016). [6] Ross J. Anderson and Roger Needham. “Programming Satan’s Computer”. In: Computer Science Today. 1995. [7] Drago Anguelov. Machine Learning for Autonomous Driving. 2019. URL: https://www.youtube. com/watch?v=Q0nGo2-y0xY. [8] Anish Athalye, Nicholas Carlini, and David A. Wagner. “Obfuscated Gradients Give a False Sense of Security: Circumventing Defenses to Adversarial Examples”. In: ICML. 2018. Jacob Austin, Augustus Odena, Maxwell Nye, Maarten Bosma, Henryk Michalewski, David Dohan, Ellen Jiang, Carrie Cai, Michael Terry, Quoc V. Le, and Charles Sutton. “Program Synthesis with Large Language Models”. In: ArXiv (2021). [10] Eugene Bagdasaryan and Vitaly Shmatikov. “Blind Backdoors in Deep Learning Models”. In: USENIX Security Symposium. 2021. [11] Abhijit Bendale and Terrance Boult. “Towards Open Set Deep Networks”. In: CVPR (2016). [12] 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 (2021). [13] Machine Learning at Berkeley. Alien Dreams: An Emerging Art Scene. URL: https : / / ml . berkeley.edu/blog/posts/clip-art/. [14] Victor Besnier, Andrei Bursuc, David Picard, and Alexandre Briot. “Triggering Failures: Out-Of- Distribution detection by learning from local adversarial attacks in Semantic Segmentation”. In: ArXiv abs/2108.01634 (2021). [15] Battista Biggio, Igino Corona, Davide Maiorca, Blaine Nelson, Nedim Šrndi´c, Pavel Laskov, Giorgio Giacinto, and Fabio Roli. “Evasion attacks against machine learning at test time”. In: Joint European conference on machine learning and knowledge discovery in databases. Springer. 2013, pp. 387–402. [16] Abeba Birhane, Pratyusha Kalluri, D. Card, William Agnew, Ravit Dotan, and Michelle Bao. “The Values Encoded in Machine Learning Research”. In: ArXiv (2021). Julian Bitterwolf, Alexander Meinke, and Matthias Hein. “Certifiably Adversarially Robust Detection of Out-of-Distribution Data”. In: NeurIPS (2020). 14 [18] Rishi Bommasani et al. “On the Opportunities and Risks of Foundation Models”. In: ArXiv (2021). [19] Nick Bostrom. “The Vulnerable World Hypothesis”. In: Global Policy (2019). [20] G. Botvin, C. Goldberg, E. M. Botvin, and L. Dusenbury. “Smoking behavior of adolescents exposed to cigarette advertising”. In: Public health reports (1993). [21] Wieland Brendel, Jonas Rauber, and Matthias Bethge. “Decision-based adversarial attacks: Reliable attacks against black-box machine learning models”. In: arXiv preprint arXiv:1712.04248 (2017). [22] Philip Brickman and Donald Campbell. “Hedonic relativism and planning the good society”. In: 1971. [23] T. Brown, B. Mann, Nick Ryder, Melanie Subbiah, J. Kaplan, Prafulla Dhariwal, Arvind Neelakantan, Pranav Shyam, Girish Sastry, Amanda Askell, Sandhini Agarwal, Ariel Herbert-Voss, G. Krüger, T. Henighan, R. Child, Aditya Ramesh, D. Ziegler, Jeffrey Wu, Clemens Winter, Christopher Hesse, Mark Chen, E. Sigler, Mateusz Litwin, Scott Gray, Benjamin Chess, J. Clark, Christopher Berner, Sam McCandlish, A. Radford, Ilya Sutskever, and Dario Amodei. “Language Models are Few-Shot Learners”. In: ArXiv abs/2005.14165 (2020). [24] Miles Brundage, Shahar Avin, Jack Clark, H. Toner, P. Eckersley, Ben Garfinkel, A. Dafoe, P. Scharre, T. Zeitzoff, Bobby Filar, H. Anderson, Heather Roff, Gregory C. Allen, J. Steinhardt, Carrick Flynn, Seán Ó hÉigeartaigh, S. Beard, Haydn Belfield, Sebastian Farquhar, Clare Lyle, Rebecca Crootof, Owain Evans, Michael Page, Joanna Bryson, Roman Yampolskiy, and Dario Amodei. “The Malicious Use of Artificial Intelligence: Forecasting, Prevention, and Mitigation”. In: ArXiv abs/1802.07228 (2018). [25] Miles Brundage, Shahar Avin, Jasmine Wang, Haydn Belfield, Gretchen Krueger, Gillian K. Hadfield, Heidy Khlaaf, Jingying Yang, H. Toner, Ruth Fong, Tegan Maharaj, P. W. Koh, Sara Hooker, J. Leung, Andrew Trask, Emma Bluemke, Jonathan Lebensbold, Cullen O’Keefe, Mark Koren, T. Ryffel, J. Rubinovitz, T. Besiroglu, F. Carugati, Jack Clark, P. Eckersley, Sarah de Haas, Maritza L. Johnson, B. Laurie, A. Ingerman, I. Krawczuk, Amanda Askell, Rosario Cammarota, A. Lohn, David Krueger, C. Stix, Peter Henderson, L. Graham, Carina E. A. Prunkl, Bianca Martin, E. Seger, Noa Zilberman, Se’an ’O h’Eigeartaigh, F. Kroeger, Girish Sastry, R. Kagan, Adrian Weller, Brian Tse, Elizabeth Barnes, A. Dafoe, P. Scharre, Ariel Herbert-Voss, Martijn Rasser, Shagun Sodhani, Carrick Flynn, T. Gilbert, Lisa Dyer, Saif Khan, Yoshua Bengio, and Markus Anderljung. “Toward Trustworthy AI Development: Mechanisms for Supporting Verifiable Claims”. In: ArXiv (2020). [26] Erik Brynjolfsson and Adam Saunders. “What the GDP Gets Wrong (Why Managers Should Care)”. In: MIT Sloan Management Review (2009). [27] Ben Buchanan, John Bansemer, Dakota Cary, Jack Lucas, and Micah Musser. “Automating Cyber Attacks”. In: 2021. [28] Ben Buchanan, Andrew Lohn, Micah Musser, and Katerina Sedova. “Truth, Lies, and Automation”. In: 2021. [29] Nicholas Carlini and A. Terzis. “Poisoning and Backdooring Contrastive Learning”. In: ArXiv abs/2106.09667 (2021). [30] Nicholas Carlini and David Wagner. “Towards evaluating the robustness of neural networks”. In: 2017 ieee symposium on security and privacy (sp). IEEE. 2017, pp. 39–57. [31] Y. Carmon, Aditi Raghunathan, Ludwig Schmidt, Percy Liang, and John C. Duchi. “Unlabeled Data Improves Adversarial Robustness”. In: NeurIPS. 2019. [32] Mathilde Caron, Hugo Touvron, Ishan Misra, Hervé Jégou, Julien Mairal, Piotr Bojanowski, and Armand Joulin. “Emerging Properties in Self-Supervised Vision Transformers”. In: Proceedings of the International Conference on Computer Vision (ICCV). 2021. [33] Dakota Cary and Daniel Cebul. “Destructive Cyber Operations and Machine Learning”. In: 2020. 15 [34] Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde, J. Kaplan, Harrison Edwards, Yura 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, F. Such, D. Cummings, Matthias Plappert, Fotios Chantzis, Elizabeth Barnes, Ariel Herbert-Voss, William H. Guss, Alex Nichol, I. Babuschkin, S. Balaji, Shantanu Jain, A. Carr, J. Leike, Joshua Achiam, Vedant Misra, Evan Morikawa, Alec Radford, M. Knight, Miles Brundage, Mira Murati, Katie Mayer, P. Welinder, Bob McGrew, Dario Amodei, Sam McCandlish, Ilya Sutskever, and Wojciech Zaremba. “Evaluating Large Language Models Trained on Code”. In: ArXiv (2021). [35] Steven Chen, Nicholas Carlini, and David A. Wagner. “Stateful Detection of Black-Box Adversarial Attacks”. In: Proceedings of the 1st ACM Workshop on Security and Privacy on Artificial Intelligence (2019). Jack Clark and Dario Amodei. “Faulty Reward Functions in the Wild”. In: OpenAI (2016). [37] Karl Cobbe, Oleg Klimov, Christopher Hesse, Taehoon Kim, and J. Schulman. “Quantifying General- ization in Reinforcement Learning”. In: ICML. 2019. Jeremy M. Cohen, Elan Rosenfeld, and J. Z. Kolter. “Certified Adversarial Robustness via Randomized Smoothing”. In: ICML. 2019. [39] North American Aerospace Defense Command and U.S. Northern Command Public Affairs. 2021. URL: https://www.af.mil/News/Article-Display/Article/2703548/norad- usnorthcom-lead-3rd-global-information-dominance-experiment/. [40] Andrew Critch and David Krueger. “AI Research Considerations for Human Existential Safety (ARCHES)”. In: ArXiv (2020). [41] Francesco Croce, Maksym Andriushchenko, V. Sehwag, Nicolas Flammarion, M. Chiang, Prateek Mittal, and Matthias Hein. “RobustBench: a standardized adversarial robustness benchmark”. In: ArXiv abs/2010.09670 (2020). [42] Maria Cvach. “Monitor alarm fatigue: an integrative review”. In: Biomedical instrumentation & technology (2012). [43] Allan Dafoe. “AI governance: a research agenda”. In: Governance of AI Program, Future of Humanity Institute, University of Oxford: Oxford, UK (2018). [44] Allan Dafoe, Edward Hughes, Yoram Bachrach, Tantum Collins, Kevin R. McKee, Joel Z. Leibo, Kate Larson, and Thore Graepel. “Open Problems in Cooperative AI”. In: ArXiv (2020). [45] Mohamad H. Danesh and Alan Fern. “Out-of-Distribution Dynamics Detection: RL-Relevant Bench- marks and Results”. In: ArXiv abs/2107.04982 (2021). [46] Department of Defense. “Quadrennial Defense Review Report”. In: (2001). [47] Laura DeNardis. “A history of internet security”. In: The history of information security. Elsevier, 2007. [48] Thomas G. Dietterich. “Robust artificial intelligence and robust human organizations”. In: Frontiers of Computer Science (2018). [49] Adrien Ecoffet and Joel Lehman. “Reinforcement Learning Under Moral Uncertainty”. In: ArXiv abs/2006.04734 (2021). [50] Yanai Elazar, Nora Kassner, Shauli Ravfogel, Abhilasha Ravichander, E. Hovy, Hinrich Schütze, and Yoav Goldberg. “Measuring and Improving Consistency in Pretrained Language Models”. In: ArXiv (2021). [51] Logan Engstrom, Brandon Tran, Dimitris Tsipras, Ludwig Schmidt, and Aleksander Madry. “A rotation and a translation suffice: Fooling cnns with simple transformations”. In: arXiv (2018). 16 [52] Facebook. Bringing People Closer Together. URL: https://about.fb.com/news/2018/01/ news-feed-fyi-bringing-people-closer-together/. [53] Pablo Fajnzylber, Daniel Lederman, and Norman V. Loayza. “Inequality and Violent Crime”. In: The Journal of Law and Economics (2002). [54] Wendi Folkert. “Assessment results regarding Organization Designation Authorization (ODA) Unit Member (UM) Independence”. In: Aviation Safety (2021). [55] F. R. Frola and C. O. Miller. “System Safety in Aircraft Acquisition”. In: 1984. [56] Iason Gabriel. “Artificial Intelligence, Values and Alignment”. In: ArXiv (2020). [57] John Gall. “Systemantics: How Systems Work and Especially How They Fail”. In: 1977. [58] Sneha Gathani, Madelon Hulsebos, James Gale, P. Haas, and cCaugatay Demiralp. “Augmenting Decision Making via Interactive What-If Analysis”. In: 2021. [59] Helmut Geist and Eric Lambin. “What drives tropical deforestation?: a meta-analysis of proximate and underlying causes of deforestation based on subnational case study evidence”. In: 2001. [60] Yolanda Gil and Bart Selman. “A 20-Year Community Roadmap for Artificial Intelligence Research in the US”. In: ArXiv abs/1908.02624 (2019). J. Gilmer, Ryan P. Adams, I. Goodfellow, David G. Andersen, and George E. Dahl. “Motivating the Rules of the Game for Adversarial Example Research”. In: ArXiv (2018). [62] Leilani H. Gilpin, David Bau, Ben Z. Yuan, Ayesha Bajwa, Michael A. Specter, and Lalana Kagal. “Explaining Explanations: An Overview of Interpretability of Machine Learning”. In: (2018). [63] Adam Gleave, Michael Dennis, Neel Kant, Cody Wild, Sergey Levine, and Stuart J. Russell. “Adver- sarial Policies: Attacking Deep Reinforcement Learning”. In: ICLR (2020). [64] Charles Goodhart. “Problems of Monetary Management: The UK Experience”. In: 1984. Jeremy Greenwood. The third industrial revolution: Technology, productivity, and income inequality. 435. American Enterprise Institute, 1997. [65] [66] Nathan Grinsztajn, Johan Ferret, O. Pietquin, P. Preux, and M. Geist. “There Is No Turning Back: A Self-Supervised Approach for Reversibility-Aware Reinforcement Learning”. In: ArXiv abs/2106.04480 (2021). [67] Tianyu Gu, Brendan Dolan-Gavitt, and Siddharth Garg. “Badnets: Identifying vulnerabilities in the machine learning model supply chain”. In: arXiv preprint arXiv:1708.06733 (2017). [68] Chuan Guo, Geoff Pleiss, Yu Sun, and Kilian Q. Weinberger. “On Calibration of Modern Neural Networks”. In: ICML (2017). [69] Dylan Hadfield-Menell, A. Dragan, P. Abbeel, and Stuart J. Russell. “The Off-Switch Game”. In: IJCA (2017). [70] Dylan Hadfield-Menell, Stuart J. Russell, P. Abbeel, and A. Dragan. “Cooperative Inverse Reinforce- ment Learning”. In: NIPS. 2016. [71] Richard Harang and Ethan M. Rudd. SOREL-20M: A Large Scale Benchmark Dataset for Malicious PE Detection. 2020. [72] Moritz Hardt, Eric Price, and Nathan Srebro. “Equality of Opportunity in Supervised Learning”. In: NIPS. 2016. [73] P. J. Heawood. “Map-Colour Theorem”. In: Proceedings of The London Mathematical Society (1949), pp. 161–175. James Hedlund. “Risky business: safety regulations, risk compensation, and individual behavior”. In: Injury Prevention (2000). 17 [75] Dan Hendrycks, Steven Basart, Norman Mu, Saurav Kadavath, Frank Wang, Evan Dorundo, Rahul Desai, Tyler Zhu, Samyak Parajuli, Mike Guo, Dawn Song, Jacob Steinhardt, and Justin Gilmer. “The Many Faces of Robustness: A Critical Analysis of Out-of-Distribution Generalization”. In: ICCV (2021). [76] Dan Hendrycks, Collin Burns, Steven Basart, Andrew Critch, Jerry Li, Dawn Song, and Jacob Steinhardt. “Aligning AI With Shared Human Values”. In: ICLR (2021). [77] Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, and Jacob Steinhardt. “Measuring Massive Multitask Language Understanding”. In: ICLR (2021). [78] Dan Hendrycks and Thomas Dietterich. “Benchmarking Neural Network Robustness to Common Corruptions and Perturbations”. In: Proceedings of the International Conference on Learning Repre- sentations (2019). [79] Dan Hendrycks and Kevin Gimpel. “A Baseline for Detecting Misclassified and Out-of-Distribution Examples in Neural Networks”. In: ICLR (2017). [80] Dan Hendrycks, Kimin Lee, and Mantas Mazeika. “Using Pre-Training Can Improve Model Robustness and Uncertainty”. In: ICML. 2019. [81] Dan Hendrycks, Mantas Mazeika, and Thomas G. Dietterich. “Deep Anomaly Detection with Outlier Exposure”. In: ICLR (2019). [82] Dan Hendrycks, Mantas Mazeika, Saurav Kadavath, and D. Song. “Using Self-Supervised Learning Can Improve Model Robustness and Uncertainty”. In: NeurIPS. 2019. [83] Dan Hendrycks, Mantas Mazeika, Andy Zou, Sahil Patel, Christine Zhu, Jesus Navarro, Dawn Song, Bo Li, and Jacob Steinhardt. “What Would Jiminy Cricket Do? Towards Agents That Behave Morally”. In: NeurIPS (2021). [84] Dan Hendrycks, Norman Mu, Ekin D. Cubuk, Barret Zoph, Justin Gilmer, and Balaji Lakshmi- narayanan. “AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty”. In: ICLR (2020). [85] Dan Hendrycks, Kevin Zhao, Steven Basart, J. Steinhardt, and D. Song. “Natural Adversarial Exam- ples”. In: CVPR (2021). [86] Dan Hendrycks, Andy Zou, Mantas Mazeika, Leonard Tang, Bo Li, Dawn Song, and Jacob Steinhardt. PixMix: Dreamlike Pictures Comprehensively Improve Safety Measures. 2021. [87] T. Henighan, J. Kaplan, Mor Katz, Mark Chen, Christopher Hesse, Jacob Jackson, Heewoo Jun, Tom B. Brown, Prafulla Dhariwal, Scott Gray, Chris Hallacy, Benjamin Mann, Alec Radford, A. Ramesh, Nick Ryder, Daniel M. Ziegler, J. Schulman, Dario Amodei, and Sam McCandlish. “Scaling Laws for Autoregressive Generative Modeling”. In: ArXiv abs/2010.14701 (2020). J. Hestness, Sharan Narang, Newsha Ardalani, G. Diamos, Heewoo Jun, Hassan Kianinejad, Md. Mostofa Ali Patwary, Y. Yang, and Yanqi Zhou. “Deep Learning Scaling is Predictable, Empirically”. In: ArXiv (2017). [89] Grant Ho, Asaf Cidon, Lior Gavish, Marco Schweighauser, V. Paxson, S. Savage, G. Voelker, and David A. Wagner. “Detecting and Characterizing Lateral Phishing at Scale”. In: USENIX Security Symposium. 2019. [90] Sanghyun Hong, Nicholas Carlini, and A. Kurakin. “Handcrafted Backdoors in Deep Neural Networks”. In: ArXiv (2021). [91] Evan Hubinger, Chris van Merwijk, Vladimir Mikulik, Joar Skalse, and Scott Garrabrant. “Risks from Learned Optimization in Advanced Machine Learning Systems”. In: ArXiv (2019). [92] David Hume. A Treatise of Human Nature. 1739. [93] Geoffrey Irving, Paul Christiano, and Dario Amodei. “AI safety via debate”. In: ArXiv (2018). 18 [94] Michael C Jensen and William H Meckling. “Theory of the firm: Managerial behavior, agency costs and ownership structure”. In: Journal of financial economics 3.4 (1976), pp. 305–360. [95] Woojeong Jin, Suji Kim, Rahul Khanna, Dong-Ho Lee, Fred Morstatter, A. Galstyan, and Xiang Ren. “ForecastQA: A Question Answering Challenge for Event Forecasting with Temporal Text Data”. In: ACL/IJCNLP. 2021. [96] Daniel Kahneman and Angus Deaton. “High income improves evaluation of life but not emotional well-being”. In: Proceedings of the National Academy of Sciences (2010). [97] Daniel Kang, Yi Sun, Dan Hendrycks, Tom B. Brown, and J. Steinhardt. “Testing Robustness Against Unforeseen Adversaries”. In: ArXiv (2019). [98] Kiran Karra, C. Ashcraft, and Neil Fendley. “The TrojAI Software Framework: An OpenSource tool for Embedding Trojans into Deep Learning Models”. In: ArXiv (2020). [99] Zachary Kenton, Tom Everitt, Laura Weidinger, Iason Gabriel, Vladimir Mikulik, and Geoffrey Irving. “Alignment of Language Agents”. In: ArXiv (2021). [100] A. Kirilenko, Mehrdad Samadi, A. Kyle, and Tugkan Tuzun. “The Flash Crash: The Impact of High Frequency Trading on an Electronic Market”. In: 2011. Jack Koch, L. Langosco, J. Pfau, James Le, and Lee Sharkey. “Objective Robustness in Deep Rein- forcement Learning”. In: ArXiv (2021). [102] P. W. Koh, Shiori Sagawa, H. Marklund, Sang Michael Xie, Marvin Zhang, A. Balsubramani, Wei hua Hu, Michihiro Yasunaga, Richard L. Phillips, Sara Beery, J. Leskovec, A. Kundaje, E. Pierson, Sergey Levine, Chelsea Finn, and Percy Liang. “WILDS: A Benchmark of in-the-Wild Distribution Shifts”. In: ICML. 2021. [103] Victoria Krakovna, Laurent Orseau, Richard Ngo, Miljan Martic, and S. Legg. “Avoiding Side Effects By Considering Future Tasks”. In: NeurIPS (2020). [104] Ben Krause, Akhilesh Deepak Gotmare, Bryan McCann, N. Keskar, Shafiq R. Joty, R. Socher, and Nazneen Rajani. “GeDi: Generative Discriminator Guided Sequence Generation”. In: ArXiv (2020). [105] Ethan Kross, Philippe Verduyn, Emre Demiralp, Jiyoung Park, David Seungjae Lee, Natalie Lin, Holly Shablack, John Jonides, and Oscar Ybarra. “Facebook use predicts declines in subjective well-being in young adults”. In: PloS one (). [106] David Krueger, Tegan Maharaj, and J. Leike. “Hidden Incentives for Auto-Induced Distributional Shift”. In: ArXiv abs/2009.09153 (2020). [107] Volodymyr Kuleshov, Nathan Fenner, and Stefano Ermon. “Accurate uncertainties for deep learning using calibrated regression”. In: ICML (2018). arXiv: 1807.00263. [108] Meelis Kull, Miquel Perello-Nieto, Markus Kängsepp, Telmo Silva Filho, Hao Song, and Peter Flach. “Beyond temperature scaling: Obtaining well-calibrated multiclass probabilities with Dirichlet calibration”. In: NeurIPS. 2019. [109] Ananya Kumar, Percy Liang, and Tengyu Ma. “Verified Uncertainty Calibration”. In: NeurIPS. 2019. [110] Patrick Ky. “Boeing 737 MAX Return to Service Report”. In: (2021). [111] Marie-Anne Lachaux, Baptiste Rozière, L. Chanussot, and Guillaume Lample. “Unsupervised Transla- tion of Programming Languages”. In: ArXiv (2020). [112] Cassidy Laidlaw, Sahil Singla, and S. Feizi. “Perceptual Adversarial Robustness: Defense Against Unseen Threat Models”. In: ICLR (2021). [113] Balaji Lakshminarayanan, A. Pritzel, and C. Blundell. “Simple and Scalable Predictive Uncertainty Estimation using Deep Ensembles”. In: NIPS. 2017. 19 [114] Terran Lane and Carla E Brodley. “An application of machine learning to anomaly detection”. In: Proceedings of the 20th National Information Systems Security Conference. Vol. 377. Baltimore, USA. 1997, pp. 366–380. [115] Ralph Langner. “Stuxnet: Dissecting a Cyberwarfare Weapon”. In: IEEE Security & Privacy (2011). [116] Katarzyna de Lazari-Radek and Peter Singer. “The Point of View of the Universe: Sidgwick and Contemporary Ethics”. In: 2014. [117] Mathias Lecuyer, Vaggelis Atlidakis, Roxana Geambasu, Daniel Hsu, and Suman Jana. “Certified robustness to adversarial examples with differential privacy”. In: 2019 IEEE Symposium on Security and Privacy (SP). IEEE. 2019, pp. 656–672. [118] Katherine Lee, Orhan Firat, Ashish Agarwal, Clara Fannjiang, and David Sussillo. “Hallucinations in neural machine translation”. In: (2018). J. Lehman, J. Clune, D. Misevic, C. Adami, L. Altenberg, Julie Beaulieu, P. Bentley, Samuel Bernard, G. Beslon, David M. Bryson, P. Chrabaszcz, Nick Cheney, Antoine Cully, S. Doncieux, F. Dyer, Kai Olav Ellefsen, R. Feldt, Stephan Fischer, S. Forrest, Antoine Frénoy, Christian Gagné, L. K. L. Goff, L. Grabowski, B. Hodjat, F. Hutter, L. Keller, C. Knibbe, Peter Krcah, R. Lenski, H. Lipson, R. MacCurdy, Carlos Maestre, R. Miikkulainen, S. Mitri, David E. Moriarty, J. Mouret, Anh M Nguyen, C. Ofria, M. Parizeau, D. Parsons, Robert T. Pennock, W. Punch, T. Ray, Marc Schoenauer, E. Shulte, K. Sims, Kenneth O. Stanley, F. Taddei, Danesh Tarapore, S. Thibault, Westley Weimer, R. Watson, and Jason Yosinksi. “The Surprising Creativity of Digital Evolution: A Collection of Anecdotes from the Evolutionary Computation and Artificial Life Research Communities”. In: Artificial Life (2018). Jan Leike, David Krueger, Tom Everitt, Miljan Martic, Vishal Maini, and Shane Legg. “Scalable agent alignment via reward modeling: a research direction”. In: ArXiv (2018). [121] Nancy Leveson. “Engineering a Safer World: Systems Thinking Applied to Safety”. In: 2012. [122] Beishui Liao, Marija Slavkovik, and Leendert van der Torre. “Building Jiminy Cricket: An Architecture for Moral Agreements Among Stakeholders”. In: Proceedings of the 2019 AAAI/ACM Conference on AI, Ethics, and Society (2019). [123] Stephanie Lin, Jacob Hilton, and Owain Evans. “TruthfulQA: Measuring How Models Mimic Human Falsehoods”. In: arXiv (2021). [124] Rachel Luo, Aadyot Bhatnagar, Huan Wang, Caiming Xiong, Silvio Savarese, Yu Bai, Shengjia Zhao, and Stefano Ermon. “Localized Calibration: Metrics and Recalibration”. In: arXiv (2021). [125] Aleksander Madry, Aleksandar Makelov, Ludwig Schmidt, Dimitris Tsipras, and Adrian Vladu. “Towards Deep Learning Models Resistant to Adversarial Attacks”. In: ICLR (2018). [126] Benoit Mandelbrot and Richard L. Hudson. “The Misbehavior of Markets: A Fractal View of Risk, Ruin, and Reward”. In: 2004. [127] David Manheim and Scott Garrabrant. “Categorizing Variants of Goodhart’s Law”. In: ArXiv (2018). [128] Filip Maric and Sana Stojanovic-Durdevic. “Formalizing IMO Problems and Solutions in Isabelle/HOL”. In: ThEdu@IJCAR. 2020. [129] Microsoft. URL: https://blogs.microsoft.com/blog/2016/03/25/learning- tays-introduction/. [130] Michael Mitzenmacher. “A Brief History of Generative Models for Power Law and Lognormal Distributions”. In: Internet Mathematics (2003). [131] Chaithanya Kumar Mummadi, Robin Hutmacher, K. Rambach, Evgeny Levinkov, T. Brox, and J. H. Metzen. “Test-Time Adaptation to Distribution Shift by Confidence Maximization and Input Transformation”. In: ArXiv (2021). [132] Toby Newberry and Toby Ord. “The Parliamentary Approach to Moral Uncertainty”. In: 2021. 20 [133] Khanh Nguyen and Brendan T. O’Connor. “Posterior calibration and exploratory analysis for natural language processing models”. In: EMNLP. 2015. [134] NSA. URL: https://ghidra-sre.org/. [135] Martha Nussbaum. “CAPABILITIES AS FUNDAMENTAL ENTITLEMENTS: SEN AND SOCIAL JUSTICE”. In: Feminist Economics 9 (2003), pp. 33 –59. [136] Rain Ottis. “Analysis of the 2007 Cyber Attacks Against Estonia from the Information Warfare Perspective”. In: 2008. [137] Yaniv Ovadia, E. Fertig, J. Ren, Zachary Nado, D. Sculley, S. Nowozin, Joshua V. Dillon, Balaji Lak- shminarayanan, and Jasper Snoek. “Can You Trust Your Model’s Uncertainty? Evaluating Predictive Uncertainty Under Dataset Shift”. In: NeurIPS. 2019. [138] Hammond Pearce, Baleegh Ahmad, Benjamin Tan, Brendan Dolan-Gavitt, and Ramesh Karri. “An Empirical Cybersecurity Evaluation of GitHub Copilot’s Code Contributions”. In: ArXiv (2021). [139] Denis Peskov, Benny Cheng, Ahmed Elgohary, Joe Barrow, Cristian Danescu-Niculescu-Mizil, and Jordan L. Boyd-Graber. “It Takes Two to Lie: One to Lie, and One to Listen”. In: ACL. 2020. [140] Fabio Pierazzi, Feargus Pendlebury, Jacopo Cortellazzi, and Lorenzo Cavallaro. “Intriguing properties of adversarial ml attacks in the problem space”. In: 2020 IEEE Symposium on Security and Privacy (SP). IEEE. 2020, pp. 1332–1349. [141] Richard A. Posner. “Utilitarianism, Economics, and Legal Theory”. In: The Journal of Legal Studies (1979). [142] Omid Poursaeed, Tianxing Jiang, Harry Yang, Serge Belongie, and Ser-Nam Lim. “Robustness and Generalization via Generative Adversarial Training”. In: 2021. [143] Alethea Power, Yuri Burda, Harri Edwards, Igor Babuschkin, and Vedant Misra. “Grokking: General- ization Beyond Overfitting on Small Algorithmic Datasets”. In: ICLR MATH-AI Workshop. 2021. “Principle 1: Preoccupation with Failure”. In: Managing the Unexpected. John Wiley & Sons, Ltd, 2015. Chap. 3, pp. 45–61. ISBN: 9781119175834. URL: https://onlinelibrary.wiley. com/doi/abs/10.1002/9781119175834.ch03. [145] Alec Radford, Jong Wook Kim, Chris Hallacy, A. Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, and Ilya Sutskever. “Learning Transferable Visual Models From Natural Language Supervision”. In: ICML. 2021. [146] Aditi Raghunathan, Jacob Steinhardt, and Percy Liang. “Certified Defenses against Adversarial Examples”. In: ICLR (2018). [147] Pranav Rajpurkar, Jeremy A. Irvin, Kaylie Zhu, Brandon Yang, Hershel Mehta, T. Duan, D. Ding, Aarti Bagul, C. Langlotz, K. Shpanskaya, M. Lungren, and A. Ng. “CheXNet: Radiologist-Level Pneumonia Detection on Chest X-Rays with Deep Learning”. In: ArXiv (2017). [148] Theodore D. Raphael. “Integrative Complexity Theory and Forecasting International Crises: Berlin 1946-1962”. In: The Journal of Conflict Resolution (1982). John Rawls. A Theory of Justice. Harvard University Press, 1999. [150] Alex Ray, Joshua Achiam, and Dario Amodei. “Benchmarking Safe Exploration in Deep Reinforce- ment Learning”. In: 2019. [151] Sylvestre-Alvise Rebuffi, Sven Gowal, D. A. Calian, Florian Stimberg, Olivia Wiles, and Timothy A. Mann. “Fixing Data Augmentation to Improve Adversarial Robustness”. In: ArXiv abs/2103.01946 (2021). [152] V. Ridgway. “Dysfunctional Consequences of Performance Measurements”. In: Administrative Science Quarterly (1956). 21 [153] Stuart Russell, Anthony Aguirre, Emilia Javorsky, and Max Tegmark. “Lethal Autonomous Weapons Exist; They Must Be Banned”. In: (2021). [154] Stuart J. Russell, Daniel Dewey, and Max Tegmark. “Research Priorities for Robust and Beneficial Artificial Intelligence”. In: AI Magazine (2015). [155] William Saunders, Girish Sastry, Andreas Stuhlmüller, and Owain Evans. “Trial without Error: Towards Safe Reinforcement Learning via Human Intervention”. In: AAMAS. 2018. [156] Roei Schuster, Congzheng Song, Eran Tromer, and Vitaly Shmatikov. “You Autocomplete Me: Poisoning Vulnerabilities in Neural Code Completion”. In: USENIX (2021). [157] David Sculley, Gary Holt, Daniel Golovin, Eugene Davydov, Todd Phillips, Dietmar Ebner, Vinay Chaudhary, Michael Young, Jean-Francois Crespo, and Dan Dennison. “Hidden technical debt in machine learning systems”. In: Advances in neural information processing systems 28 (2015), pp. 2503– 2511. [158] A. Shafahi, W. R. Huang, Mahyar Najibi, Octavian Suciu, Christoph Studer, T. Dumitras, and T. Goldstein. “Poison Frogs! Targeted Clean-Label Poisoning Attacks on Neural Networks”. In: NeurIPS. 2018. [159] Rohin Shah, Dmitrii Krasheninnikov, Jordan Alexander, P. Abbeel, and A. Dragan. “Preferences Implicit in the State of the World”. In: ICLR (2019). [160] Mahmood Sharif, Sruti Bhagavatula, Lujo Bauer, and Michael K Reiter. “Accessorize to a crime: Real and stealthy attacks on state-of-the-art face recognition”. In: Proceedings of the 2016 acm sigsac conference on computer and communications security. 2016, pp. 1528–1540. [161] E. C. Shin, D. Song, and R. Moazzezi. “Recognizing Functions in Binaries with Neural Networks”. In: USENIX Security Symposium. 2015. [162] Reza Shokri, Marco Stronati, Congzheng Song, and Vitaly Shmatikov. “Membership inference attacks against machine learning models”. In: 2017 IEEE Symposium on Security and Privacy (SP). IEEE. 2017, pp. 3–18. [163] M. D.Amran Siddiqui, Alan Fern, Thomas G. Dietterich, and Weng Keen Wong. “Sequential feature explanations for anomaly detection”. In: ACM Transactions on Knowledge Discovery from Data (2019). [164] Henry Sidgwick. The Methods of Ethics. 1907. [165] Robin Sommer and Vern Paxson. “Outside the closed world: On using machine learning for network intrusion detection”. In: 2010 IEEE symposium on security and privacy. IEEE. 2010, pp. 305–316. [166] D. H. Stamatis. “Failure mode and effect analysis : FMEA from theory to execution”. In: ASQC Quality Press (1996). [167] Keith E. Stanovich, Richard F. West, and Maggie E. Toplak. “The Rationality Quotient: Toward a Test of Rational Thinking”. In: 2016. [168] Nick Carr Steve Miller Evan Reese. Shikata Ga Nai Encoder Still Going Strong. URL: https : / / www . fireeye . com / blog / threat - research / 2019 / 10 / shikata - ga - nai - encoder-still-going-strong.html. [169] Marilyn Strathern. “‘Improving ratings’: audit in the British University system”. In: European Review (1997). Jonathan Stray. “Aligning AI Optimization to Community Well-Being”. In: International Journal of Community Well-Being (2020). Jonathan Stray, Ivan Vendrov, Jeremy Nixon, Steven Adler, and Dylan Hadfield-Menell. “What are you optimizing for? Aligning Recommender Systems with Human Values”. In: ArXiv abs/2107.10939 (2021). 22 [172] David Stutz, Matthias Hein, and B. Schiele. “Confidence-Calibrated Adversarial Training: Generalizing to Unseen Attacks”. In: ICML. 2020. [173] Octavian Suciu, Scott E. Coull, and Jeffrey Johns. “Exploring Adversarial Examples in Malware Detection”. In: IEEE Security and Privacy Workshops (SPW) (2019). [174] RL Sumwalt, B Landsberg, and J Homendy. “Assumptions used in the safety assessment process and the effects of multiple alerts and indications on pilot performance”. In: District of Columbia: National Transportation Safety Board (2019). [175] Rebecca Sutton. Chromium-6 in US tap water. Environmental Working Group Washington, DC, 2010. [176] Publius Syrus. The Moral Sayings of Publius Syrus, a Roman Slave. L.E. Bernard & Company, 1856. [177] Christian Szegedy, Wojciech Zaremba, Ilya Sutskever, Joan Bruna, Dumitru Erhan, Ian Goodfellow, and Rob Fergus. “Intriguing properties of neural networks”. In: arXiv preprint arXiv:1312.6199 (2013). [178] Jihoon Tack, Sangwoo Mo, Jongheon Jeong, and Jinwoo Shin. “CSI: Novelty Detection via Contrastive Learning on Distributionally Shifted Instances”. In: NeurIPS (2020). Jihoon Tack, Sihyun Yu, Jongheon Jeong, Minseong Kim, Sung Ju Hwang, and Jinwoo Shin. “Consis- tency Regularization for Adversarial Robustness”. In: ArXiv (2021). [180] Nassim Taleb. “Antifragile: Things That Gain from Disorder”. In: 2012. [181] Nassim Taleb. “Statistical Consequences of Fat Tails: Real World Preasymptotics, Epistemology, and Applications”. In: 2020. [182] Nassim Taleb. “The Black Swan: The Impact of the Highly Improbable”. In: 2007. [183] Nassim Taleb and Philip Tetlock. “On the Difference between Binary Prediction and True Exposure with Implications for Forecasting Tournaments and Decision Making Research”. In: 2013. Jessica Taylor, Eliezer Yudkowsky, Patrick LaVictoire, and Andrew Critch. “Alignment for Advanced Machine Learning Systems”. In: 2016. [185] Tesla. Tesla AI Day. 2021. URL: https://www.youtube.com/watch?v=j0z4FweCy4M. [186] Philip Tetlock and Dan Gardner. “Superforecasting: The Art and Science of Prediction”. In: 2015. [187] Brandon Trabucco, Aviral Kumar, Xinyang Geng, and Sergey Levine. “Conservative Objective Models for Effective Offline Model-Based Optimization”. In: ICML. 2021. [188] Florian Tramèr, Nicholas Carlini, Wieland Brendel, and A. Madry. “On Adaptive Attacks to Adversar- ial Example Defenses”. In: ArXiv (2020). [189] Florian Tramèr, Alexey Kurakin, Nicolas Papernot, Dan Boneh, and Patrick Mcdaniel. “Ensemble Adversarial Training: Attacks and Defenses”. In: ArXiv abs/1705.07204 (2018). [190] A. M. Turner, Neale Ratzlaff, and Prasad Tadepalli. “Avoiding Side Effects in Complex Environments”. In: ArXiv abs/2006.06547 (2020). [191] Alexander Matt Turner, Logan Riggs Smith, Rohin Shah, Andrew Critch, and Prasad Tadepalli. “Optimal Policies Tend To Seek Power”. In: NeurIPS. 2021. [192] Building Seismic Safety Council US et al. “Planning for seismic rehabilitation: societal issues”. In: (1998). [193] Carroll L. Wainwright and P. Eckersley. “SafeLife 1.0: Exploring Side Effects in Complex Environ- ments”. In: ArXiv abs/1912.01217 (2020). [194] Eric Wallace, Tony Zhao, Shi Feng, and Sameer Singh. “Concealed Data Poisoning Attacks on NLP Models”. In: NAACL. 2021. [195] Dequan Wang, An Ju, Evan Shelhamer, David A. Wagner, and Trevor Darrell. “Fighting Gradients with Gradients: Dynamic Defenses against Adversarial Attacks”. In: ArXiv abs/2105.08714 (2021). 23 [196] Dequan Wang, Evan Shelhamer, Shaoteng Liu, B. Olshausen, and Trevor Darrell. “Tent: Fully Test- Time Adaptation by Entropy Minimization”. In: ICLR. 2021. [197] Pei Wang, Yijun Li, Krishna Kumar Singh, Jingwan Lu, and N. Vasconcelos. “IMAGINE: Image Synthesis by Image-Guided Model Inversion”. In: ArXiv abs/2104.05895 (2021). [198] Yue Wang, Esha Sarkar, Wenqing Li, M. Maniatakos, and S. E. Jabari. “Stop-and-Go: Exploring Backdoor Attacks on Deep Reinforcement Learning-based Traffic Congestion Control Systems”. In: arXiv: Cryptography and Security (2020). [199] E. G. Williams. “The Possibility of an Ongoing Moral Catastrophe”. In: Ethical Theory and Moral Practice (2015). [200] Timothy Wilson and Daniel Gilbert. “Affective Forecasting”. In: Current Directions in Psychological Science (2005). [201] Dongxian Wu, Shutao Xia, and Yisen Wang. “Adversarial Weight Perturbation Helps Robust General- ization”. In: NeurIPS (2020). [202] Chaowei Xiao, Ruizhi Deng, Bo Li, F. Yu, M. Liu, and D. Song. “Characterizing Adversarial Examples Based on Spatial Consistency Information for Semantic Segmentation”. In: ECCV. 2018. [203] Cihang Xie, Mingxing Tan, Boqing Gong, A. Yuille, and Quoc V. Le. “Smooth Adversarial Training”. In: ArXiv abs/2006.14536 (2020). [204] Hongxu Yin, Pavlo Molchanov, Zhizhong Li, J. Álvarez, Arun Mallya, Derek Hoiem, N. Jha, and J. Kautz. “Dreaming to Distill: Data-Free Knowledge Transfer via DeepInversion”. In: CVPR (2020). [205] Sheheryar Zaidi, Arber Zela, T. Elsken, Chris C. Holmes, F. Hutter, and Y. Teh. “Neural Ensemble Search for Uncertainty Estimation and Dataset Shift”. In: 2020. [206] Hongyang Zhang, Yaodong Yu, Jiantao Jiao, Eric Xing, Laurent El Ghaoui, and Michael I. Jordan. “Theoretically Principled Trade-off between Robustness and Accuracy”. In: ICML. 2019. [207] Xinyang Zhang, Zheng Zhang, and Tianying Wang. “Trojaning Language Models for Fun and Profit”. In: ArXiv abs/2008.00312 (2020). [208] Yao Zhu, Jiacheng Ma, Jiacheng Sun, Zewei Chen, Rongxin Jiang, and Zhenguo Li. “Towards Understanding the Generative Capability of Adversarially Robust Classifiers”. In: ArXiv (2021). [209] Shoshana Zuboff. “The Age of Surveillance Capitalism: The Fight for a Human Future at the New Frontier of Power”. In: (2019). [210] Remco Zwetsloot, Helen Toner, and Jeffrey Ding. “Beyond the AI arms race: America, China, and the dangers of zero-sum thinking”. In: Foreign Affairs (2018). 24 # A Analyzing Risks, Hazards, and Impact # A.1 Risk Management Framework ML Operational Institutional Future Area Problem System Risks and Societal Risks Risks Risks Robustness Black Swans and Tail Risks v v v Adversarial Robustness v v Anomaly Detection v v v Monitoring Representative Outputs v v v Hidden Model Functionality v v v Value Learning v v v Translating Values to Action v v Alignment Proxy Gaming v v Value Clarification v v Unintended Consequences v v v v Systemic ML for Cybersecurity v v v v Safety Informed Decision Making v v v Table 1: Problems and the risks they directly mitigate. Each checkmark indicates whether a problem directly reduces a risk. Notice that problems affect both near- and long-term risks. To analyze how ML Safety progress can reduce abstract risks and hazards,1 we identify four dimensions of risk in this section and five hazards in the next section. The following four risk dimensions are adopted from the Department of Defense’s broad risk management framework [46], with its personnel management risks replaced with ML system risks. 1. ML System Risks – risks to the ability of a near-term individual ML system to operate reliably. 2. Operational Risks – risks to the ability of an organization to safely operate an ML system in near-term deployment scenarios. 3. Institutional and Societal Risks – risks to the ability of global society or institutions that decisively affect ML systems to operate in near-term scenarios in an efficient, informed, and prudent way. 4. Future (ML System, Operational, and Institutional) Risks – risks to the ability of future ML systems, organizations operating ML systems, and institutions to address mid- to long-term challenges. In Table 1, we indicate whether one of these risks is reduced by progress on a given ML Safety problem. Note that these all problems reduce risks to all three of future ML systems, organizations, and institutions. In the future, organizations and institutions will likely become more dependent on ML systems, so improvements to Black Swans robustness would in the future help improve operations and institutions dependent on ML systems. Since this table is a snapshot of the present, risk profiles will inevitably change. 1One can think of hazards as factors that have the potential to cause harm. One can think of risk as the hazard’s prevalence multiplied by the amount of exposure to the hazard multiplied by the hazard’s deleterious effect. For example, a wet floor is a hazard to humans. However, risks from wet floors are lower if floors dry more quickly with a fan (systemic safety). Risks are lower if humans heed wet floor signs and have less exposure to them (monitoring). Risks are also lower for young adults than the elderly, since the elderly are more physically vulnerable (robustness). In other terms, robustness makes systems less vulnerable to hazards, monitoring reduces exposure to hazards, alignment makes systems inherently less hazardous, and systemic safety reduces systemic hazards. 25 # A.2 Hazard Management Framework ‘Area Problem Known Unknown Emergence Long Adversaries Unknowns Unknowns Tails & Deception Robustness Black Swans and Tail Risks Vv Vv v Vv Adversarial Robustness v v Anomaly Detection v Vv Vv Vv Vv Monitoring Representative Outputs v v v Hidden Model Functionality Vv Vv Vv Vv Value Learning Vv Translating Values to Action v v Alignment Proxy Gaming v v Value Clarification v v v v Unintended Consequences Vv Vv Systemic ML for Cybersecurity v v Vv Safety Informed Decision Making v v v v # Area # Robustness # Monitoring # Alignment # Systemic ML for Cybersecurity Safety Table 2: Problems and the hazards they help handle. Checkmarks indicate whether a problem directly reduces vulnerability or exposure to a given hazard, and bold green checkmarks indicate an especially notable reduction. We now turn from what is affected by risks to five abstract hazards that create risks. 1. Known Unknowns – Identified hazards for which we have imperfect or incomplete knowledge. These are identified hazards known to have unknown aspects. 2. Unknown Unknowns – Hazards which are unknown and unidentified, and they have properties that are unknown. 3. Emergence – A hazard that forms and comes into being as the system increases in size or its parts are combined. Such hazards do not exist in smaller versions of the system nor in its constituent parts. 4. Long Tails – Hazards that can be understood as unusual or extreme events from a long tail distribution. 5. Adversaries & Deception – Hazards from a person, system, or force that aims to attack, subvert, or deceive. These hazards do not enumerate all possible hazards. For example, the prob- lems in Systemic Safety help with turbulence hazards. Furthermore, feedback loops, which can create long tails, could become a more prominent hazard in the future when ML systems are integrated into more aspects of our lives. The five hazards have some overlap. For instance, when something novel emerges, it is an unknown unknown. When it is detected, it can become a known unknown. Separately, long tail events are often but not necessarily unknown unknowns: the 1987 stock market crash was a long tail event, but it was a known unknown to a prescient few and an unknown unknown to most everybody else. Emergent hazards sometimes co-occur with long tailed events, and an adversarial attack can cause long tail events. SRO ATA, 2 ; ; SROQANET, SWOQRIBAG, Raarang pur In Table 2, we indicate whether an ML Safety problem reduces vulnerability or exposure to a given hazard. As with Table 1, the table is a snapshot of the present. For example, future adversaries could create novel unusual events or strike during tail events, so Black Swan robustness could improve adversarial robustness. Figure 6: A simplified model of interconnected factors for ML Safety. With risks, hazards, and goals now all explicated, we depict their interconnectedness in Figure 6. 26 # A.3 Prioritization and Strategy for Maximizing Impact Area Robustness Monitoring Alignment Systemic Safety Problem Black Swans and Tail Risks Adversarial Robustness Anomaly Detection Representative Outputs Hidden Model Functionality Value Learning Translating Values to Action Proxy Gaming Value Clarification Unintended Consequences ML for Cybersecurity Informed Decision Making Importance • • • • • • • • • • • • • • • • • • • • • • • • • • • • • Neglectedness Tractability • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • Table 3: Problems and three factors that influence expected marginal impact. We presented several problems, but new researchers may be able to make a larger impact on some problems over others. Some problems may be important, but if they are extremely popular, the risk of scooping increases, as does the risk of researchers stepping on each others’ toes. Likewise, some problems may be important and may be decisive for safety if solved, but some problems are simply infeasible. Consequently, we should consider the importance, neglectedness, and tractability of problems. 1. Importance – How much potential risk does substantial progress on this problem reduce? Progress on this problem reduces risks of catastrophes. Progress on this problem directly reduces risks from potential permanent catastrophes. • • • Progress on this problem directly reduces risks from more plausible permanent catastrophes. 2. Neglectedness – How much research is being done on the problem? The problem is one of the top ten most researched topics at leading conferences. The problem receives some attention at leading ML conferences, or adjacent problems are hardly neglected. • • • • The problem has few related papers consistently published at leading ML conferences. 3. Tractability – How much progress can we expect on the problem? We cannot expect large research efforts to highly fruitful currently, possibly due to concep- tual bottlenecks, or productive work on the problem likely requires far more advanced ML capabilities. • • We expect to reliably and continually make progress on the problem. • • • A large research effort would be highly fruitful and there is obvious low-hanging fruit. A snapshot of each problem and its current importance, neglectedness, and tractability is in Table 3. Note this only provides a rough sketch, and it has limitations. For example, a problem that is hardly neglected overall may still have neglected aspects; while adversarial robustness is less neglected than other safety problems, robustness to unforeseen adversaries is fairly neglected. Moreover, working on popular shovel-ready problems 27 may be more useful for newcomers compared to working on problems where conceptual bottlenecks persist. Further, this gives a rough sense of marginal impact, but entire community should not chose to act in the same way marginally, or else neglected problems will suddenly become overcrowded. These three factors are merely prioritization factors and do not define a strategy. Rather, a potential strategy for ML Safety is as follows. 1. Force Management: Cultivate and maintain a force of ready personnel to implement safety measures into advanced ML systems and operate ML systems safely. 2. Research: Build and maintain a community to conduct safety research, including the identification of potential future hazards, clarification of safety goals, reduction of the costs to adopt safety methods, research on how to incorporate safety methods into existing ML systems, and so on. 3. Protocols: Establish and incentivize adherence to protocols, precedents, standards, and research expecta- tions such as red teaming, all for the safe development and deployment of ML systems. 4. Partnerships: Build and maintain safety-focused alliances and partnerships among academe, industry, and government. In closing, throughout ML Safety’s development we have seen numerous proposed strategies, hazards, risks, scenarios, and problems. In safety, some previously proposed problems have been discarded, and some new problems have emerged, just as in the broader ML community. Since no individual knows what lies ahead, safety analysis and strategy will need to evolve and adapt beyond this document. Regardless of which particular safety problems turn out to be the most or least essential, the success of safety’s evolution and adaptation rests on having a large and capable research community. 28
Title: The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables: Summary: The reparameterization trick enables optimizing large scale stochastic computation graphs via gradient descent. The essence of the trick is to refactor each stochastic node into a differentiable function of its parameters and a random variable with fixed distribution. After refactoring, the gradients of the loss propagated by the chain rule through the graph are low variance unbiased estimators of the gradients of the expected loss. While many continuous random variables have such reparameterizations, discrete random variables lack useful reparameterizations due to the discontinuous nature of discrete states. In this work we introduce Concrete random variables---continuous relaxations of discrete random variables. The Concrete distribution is a new family of distributions with closed form densities and a simple reparameterization. Whenever a discrete stochastic node of a computation graph can be refactored into a one-hot bit representation that is treated continuously, Concrete stochastic nodes can be used with automatic differentiation to produce low-variance biased gradients of objectives (including objectives that depend on the log-probability of latent stochastic nodes) on the corresponding discrete graph. We demonstrate the effectiveness of Concrete relaxations on density estimation and structured prediction tasks using neural networks. ICLR 2017 THE CONCRETE DISTRIBUTION: A CONTINUOUS RELAXATION OF DISCRETE RANDOM VARIABLES Chris J. Maddison1,2, Andriy Mnih1, & Yee Whye Teh1 1DeepMind, London, United Kingdom 2University of Oxford, Oxford, United Kingdom cmaddis@stats.ox.ac.uk # ABSTRACT The reparameterization trick enables optimizing large scale stochastic computa- tion graphs via gradient descent. The essence of the trick is to refactor each stochastic node into a differentiable function of its parameters and a random vari- able with fixed distribution. After refactoring, the gradients of the loss propa- gated by the chain rule through the graph are low variance unbiased estimators of the gradients of the expected loss. While many continuous random variables have such reparameterizations, discrete random variables lack useful reparame- terizations due to the discontinuous nature of discrete states. In this work we introduce CONCRETE random variables—CONtinuous relaxations of disCRETE random variables. The Concrete distribution is a new family of distributions with closed form densities and a simple reparameterization. Whenever a discrete stochastic node of a computation graph can be refactored into a one-hot bit rep- resentation that is treated continuously, Concrete stochastic nodes can be used with automatic differentiation to produce low-variance biased gradients of objec- tives (including objectives that depend on the log-probability of latent stochastic nodes) on the corresponding discrete graph. We demonstrate the effectiveness of Concrete relaxations on density estimation and structured prediction tasks using neural networks. # INTRODUCTION Software libraries for automatic differentiation (AD) (Abadi et al., 2015; Theano Development Team, 2016) are enjoying broad use, spurred on by the success of neural networks on some of the most challenging problems of machine learning. The dominant mode of development in these libraries is to define a forward parametric computation, in the form of a directed acyclic graph, that computes the desired objective. If the components of the graph are differentiable, then a backwards computation for the gradient of the objective can be derived automatically with the chain rule. The ease of use and unreasonable effectiveness of gradient descent has led to an explosion in the di- versity of architectures and objective functions. Thus, expanding the range of useful continuous operations can have an outsized impact on the development of new models. For example, a topic of recent attention has been the optimization of stochastic computation graphs from samples of their states. Here, the observation that AD “just works” when stochastic nodes1 can be reparameterized into deterministic functions of their parameters and a fixed noise distribution (Kingma & Welling, 2013; Rezende et al., 2014), has liberated researchers in the development of large complex stochastic architectures (e.g. Gregor et al., 2015). Computing with discrete stochastic nodes still poses a significant challenge for AD libraries. Deter- ministic discreteness can be relaxed and approximated reasonably well with sigmoidal functions or the softmax (see e.g., Grefenstette et al., 2015; Graves et al., 2016), but, if a distribution over discrete states is needed, there is no clear solution. There are well known unbiased estimators for the gradi- 1For our purposes a stochastic node of a computation graph is just a random variable whose distribution depends in some deterministic way on the values of the parent nodes. 1 Published as a conference paper at ICLR 2017 ents of the parameters of a discrete stochastic node from samples. While these can be made to work with AD, they involve special casing and defining surrogate objectives (Schulman et al., 2015), and even then they can have high variance. Still, reasoning about discrete computation comes naturally to humans, and so, despite the difficulty associated, many modern architectures incorporate discrete stochasticity (Mnih et al., 2014; Xu et al., 2015; Koˇcisk´y et al., 2016). This work is inspired by the observation that many architectures treat discrete nodes continuously, and gradients rich with counterfactual information are available for each of their possible states. We introduce a CONtinuous relaxation of disCRETE random variables, CONCRETE for short, which allow gradients to flow through their states. The Concrete distribution is a new parametric family of continuous distributions on the simplex with closed form densities. Sampling from the Concrete distribution is as simple as taking the softmax of logits perturbed by fixed additive noise. This reparameterization means that Concrete stochastic nodes are quick to implement in a way that “just works” with AD. Crucially, every discrete random variable corresponds to the zero temperature limit of a Concrete one. In this view optimizing an objective over an architecture with discrete stochastic nodes can be accomplished by gradient descent on the samples of the corresponding Concrete relaxation. When the objective depends, as in variational inference, on the log-probability of discrete nodes, the Concrete density is used during training in place of the discrete mass. At test time, the graph with discrete nodes is evaluated. The paper is organized as follows. We provide a background on stochastic computation graphs and their optimization in Section 2. Section 3 reviews a reparameterization for discrete random vari- ables, introduces the Concrete distribution, and discusses its application as a relaxation. Section 4 reviews related work. In Section 5 we present results on a density estimation task and a structured prediction task on the MNIST and Omniglot datasets. In Appendices C and F we provide details on the practical implementation and use of Concrete random variables. When comparing the effec- tiveness of gradients obtained via Concrete relaxations to a state-of-the-art-method (VIMCO, Mnih & Rezende, 2016), we find that they are competitive—occasionally outperforming and occasionally underperforming—all the while being implemented in an AD library without special casing. 2 BACKGROUND 2.1 OPTIMIZING STOCHASTIC COMPUTATION GRAPHS Stochastic computation graphs (SCGs) provide a formalism for specifying input-output mappings, potentially stochastic, with learnable parameters using directed acyclic graphs (see Schulman et al. (2015) for a review). The state of each non-input node in such a graph is obtained from the states of its parent nodes by either evaluating a deterministic function or sampling from a conditional distribution. Many training objectives in supervised, unsupervised, and reinforcement learning can be expressed in terms of SCGs. To optimize an objective represented as a SCG, we need estimates of its parameter gradients. We will concentrate on graphs with some stochastic nodes (backpropagation covers the rest). For simplicity, we restrict our attention to graphs with a single stochastic node X. We can interpret the forward pass in the graph as first sampling X from the conditional distribution pφ(x) of the stochastic node given its parents, then evaluating a deterministic function fθ(x) at X. We can think of fθ(X) as a noisy objective, and we are interested in optimizing its expected value L(θ, φ) = E X∼pφ(x)[fθ(X)] w.r.t. parameters θ, φ. In general, both the objective and its gradients are intractable. We will side-step this issue by esti- mating them with samples from pφ(x). The gradient w.r.t. to the parameters θ has the form # ∇θE X∼pφ(x)[fθ(X)] = E X∼pφ(x)[ (1) ∇θL(θ, φ) = # ∇θfθ(X)] and can be easily estimated using Monte Carlo sampling: f 1 8 8 VoL(0,8) ~ =) _, Volo(X*), (2) where X* ~ p(x) iid. The more challenging task is to compute the gradient @ of pg(x). The expression obtained by differentiating the expected objective, # w.r.t. the parameters ∇φL(θ, φ) = ∇φ pφ(x)fθ(x) dx = fθ(x) ∇φpφ(x) dx, (3) 2 Published as a conference paper at ICLR 2017 does not have the form of an expectation w.r.t. x and thus does not directly lead to a Monte Carlo gradient estimator. However, there are two ways of getting around this difficulty which lead to the two classes of estimators we will now discuss. 2.2 SCORE FUNCTION ESTIMATORS The score function estimator (SFE, Fu, 2006), also known as the REINFORCE (Williams, 1992) or likelihood-ratio estimator (Glynn, 1990), is based on the identity ∇φ log pφ(x), which allows the gradient in Eq. 3 to be written as an expectation: ∇φL(θ, φ) = E ∇φ log pφ(X)] . Estimating this expectation using naive Monte Carlo gives the estimator Vol(,8) ~ =~, fol X*)Vg low po(X*), () where X s pφ(x) i.i.d. This is a very general estimator that is applicable whenever log pφ(x) is differentiable w.r.t. φ. As it does not require fθ(x) to be differentiable or even continuous as a function of x, the SFE can be used with both discrete and continuous random variables. Though the basic version of the estimator can suffer from high variance, various variance reduc- tion techniques can be used to make the estimator much more effective (Greensmith et al., 2004). Baselines are the most important and widely used of these techniques (Williams, 1992). A number of score function estimators have been developed in machine learning (Paisley et al., 2012; Gregor et al., 2013; Ranganath et al., 2014; Mnih & Gregor, 2014; Titsias & L´azaro-Gredilla, 2015; Gu et al., 2016), which differ primarily in the variance reduction techniques used. 2.3 REPARAMETERIZATION TRICK In many cases we can sample from pφ(x) by first sampling Z from some fixed distribution q(z) and then transforming the sample using some function gφ(z). For example, a sample from Normal(µ, σ2) can be obtained by sampling Z from the standard form of the distribution Normal(0, 1) and then transforming it using gµ,σ(Z) = µ + σZ. This two-stage reformulation of the sampling process, called the reparameterization trick, allows us to transfer the dependence on φ from p into f by writing fθ(x) = fθ(gφ(z)) for x = gφ(z), making it possible to reduce the problem of estimating the gradient w.r.t. parameters of a distribution to the simpler problem of estimating the gradient w.r.t. parameters of a deterministic function. Having reparameterized pφ(x), we can now express the objective as an expectation w.r.t. q(z): X∼pφ(x)[fθ(X)] = E As q(z) does not depend on φ, we can estimate the gradient w.r.t. φ in exactly the same way we estimated the gradient w.r.t. θ in Eq. 1. Assuming differentiability of fθ(x) w.r.t. x and of gφ(z) w.r.t. φ and using the chain rule gives ∇φL(θ, φ) = E # ∇φfθ(gφ(Z))] = E ∇φgφ(Z)] . The reparameterization trick, introduced in the context of variational inference independently by Kingma & Welling (2014), Rezende et al. (2014), and Titsias & L´azaro-Gredilla (2014), is usu- ally the estimator of choice when it is applicable. For continuous latent variables which are not directly reparameterizable, new hybrid estimators have also been developed, by combining partial reparameterizations with score function estimators (Ruiz et al., 2016; Naesseth et al., 2016). 2.4 APPLICATION: VARIATIONAL TRAINING OF LATENT VARIABLE MODELS We will now see how the task of training latent variable models can be formulated in the SCG framework. Such models assume that each observation x is obtained by first sampling a vector of latent variables Z from the prior pg(z) before sampling the observation itself from pg(x | z). Thus the probability of observation x is pg(x) = 3), po(z)pe(x | z). Maximum likelihood train- ing of such models is infeasible, because the log-likelihood (LL) objective L(@) = log pe(x) = 3 (6) Published as a conference paper at ICLR 2017 (a) Discrete(α) (b) Concrete(α, λ) Discrete(α) and 3-ary Con- Figure 1: Visualization of sampling graphs for 3-ary discrete D crete X Concrete(α, λ). White operations are deterministic, blue are stochastic, rounded are continuous, square discrete. The top node is an example state; brightness indicates a value in [0,1]. log E expectation being inside the log. The multi-sample variational objective (Burda et al., 2016), 1 po(Z', x) log | — ———_]]. (8) (2 dX do(Z" |) Ln(0,¢)=. E Zingy (2|e) provides a convenient alternative which has precisely the form we considered in Section 2.1. This ap- x) with its own parameters, which serves proach relies on introducing an auxiliary distribution qφ(z as approximation to the intractable posterior pθ(z x). The model is trained by jointly maximizing | the objective w.r.t. to the parameters of p and q. The number of samples used inside the objective m allows trading off the computational cost against the tightness of the bound. For m = 1, Lm(θ, φ) becomes is the widely used evidence lower bound (ELBO, Hoffman et al., 2013) on log pθ(x), while for m > 1, it is known as the importance weighted bound (Burda et al., 2016). 3 THE CONCRETE DISTRIBUTION 3.1 DISCRETE RANDOM VARIABLES AND THE GUMBEL-MAX TRICK To motivate the construction of Concrete random variables, we review a method for sampling from discrete distributions called the Gumbel-Max trick (Luce, 1959; Yellott, 1977; Papandreou & Yuille, 2011; Hazan & Jaakkola, 2012; Maddison et al., 2014). We restrict ourselves to a representation of discrete states as vectors d k=1 dk = 1. This is a flexible representation in a computation graph; to achieve an integral representation take the inner product of d with (1, . . . , n), and to achieve a point mass representation in Rm take W d where W Rm×n. Consider an unnormalized parameterization (α1, . . . , αn) where αk ∈ tion D ∼ Max trick proceeds as follows: sample Uk ∼ log Uk) log αk − { ∈ , set Dk = 1 and the remaining Di = 0 for i } − _ Ok Vie Gs (9) In other words, the sampling of a discrete random variable can be refactored into a deterministic function—componentwise addition followed by argmax—of the parameters log αk and fixed dis- tribution − − The apparently arbitrary choice of noise gives the trick its name, as log U ) has a Gumbel distribution. This distribution features in extreme value theory (Gumbel, 1954) where it plays a central role similar to the Normal distribution: the Gumbel distribution is stable under max opera- tions, and for some distributions, the order statistics (suitably normalized) of i.i.d. draws approach the Gumbel in distribution. The Gumbel can also be recognized as a log-transformed exponen- tial random variable. So, the correctness of (9) also reduces to a well known result regarding the argmin of exponential random variables. See (Hazan et al., 2016) for a collection of related work, and particularly the chapter (Maddison, 2016) for a proof and generalization of this trick. 4 Published as a conference paper at ICLR 2017 (a) λ = 0 (b) λ = 1/2 (c) λ = 1 (d) λ = 2 Figure 2: A discrete distribution with unnormalized probabilities (α1, α2, α3) = (2, 0.5, 1) and three corresponding Concrete densities at increasing temperatures λ. Each triangle represents the set of points (y1, y2, y3) in the simplex ∆2 = . For λ = 0 the size of white circles represents the mass assigned to each vertex of the simplex under the the intensity of the shading represents the value of pα,λ(y). discrete distribution. For λ 2, 1, 0.5 } ∈ { 3.2 CONCRETE RANDOM VARIABLES The derivative of the argmax is 0 everywhere except at the boundary of state changes, where it is undefined. For this reason the Gumbel-Max trick is not a suitable reparameterization for use in SCGs with AD. Here we introduce the Concrete distribution motivated by considering a graph, which is the same as Figure[Ialup to a continuous relaxation of the argmax computation, see Figure[Ib] This will ultimately allow the optimization of parameters a, via gradients. The argmax computation returns states on the vertices of the simplex A”-! = {x € R" | x, € (0, 1], \o¢_, ve = 1}. The idea behind Concrete random variables is to relax the state of a discrete variable from the vertices into the interior where it is a random probability vector—a vector of numbers between 0 and | that sum to 1. To sample a Concrete random variable X € A"! at temperature \ € (0,00) with parameters a, € (0, 00), sample G,, ~ Gumbel i.i.d. and set # Rn ∈ ∞ ) with parameters αk ∈ Xk = # ), sample Gk ∼ . # ∞ exp((log αk + Gk)/λ) i=1 exp((log αi + Gi)/λ) exp((log ag + Gx)/A) YUL, exp((log a; + Gi)/d) Xk (10) The softmax computation of (10) smoothly approaches the discrete argmax computation as λ 0 while preserving the relative order of the Gumbels log αk + Gk. So, imagine making a series of forward passes on the graphs of Figure 1. Both graphs return a stochastic value for each forward pass, but for smaller temperatures the outputs of Figure 1b become more discrete and eventually indistinguishable from a typical forward pass of Figure 1a. The distribution of X sampled via (10) has a closed form density on the simplex. Because there may be other ways to sample a Concrete random variable, we take the density to be its definition. Definition 1 (Concrete Random Variables). Let α Concrete distribution X ∼ Po.A(t) = (n= 1)!" TT (=) ; an k=1 a py VT; Proposition 1 lists a few properties of the Concrete distribution. (a) is confirmation that our def- inition corresponds to the sampling routine (10). (b) confirms that rounding a Concrete random variable results in the discrete random variable whose distribution is described by the logits log αk, (c) confirms that taking the zero temperature limit of a Concrete random variable is the same as rounding. Finally, (d) is a convexity result on the density. We prove these results in Appendix A. Proposition 1 (Some Properties of Concrete Random Variables). Let X location parameters α (a) (Reparameterization) If Gy, ~ Gumbel i.i.d., then (b) (Rounding) P(X, > X; fori #k) = ax/(X7}_, (c) (Zero temperature) P (limy.9 Xz = 1) = ax/(S0j_1 ∞ ∈ ∞ d= exp((log αk+Gk)/λ) # Gumbel i.i.d., then Xk i=1 exp((log αi+Gi)/λ) , Gumbel i.i.d., then Xk n #k) = ax/(X7}_, i=1 αi), i=1 αi), 5 Published as a conference paper at ICLR 2017 (a) λ = 0 (b) λ = 1/2 (c) λ = 1 (d) λ = 2 Figure 3: A visualization of the binary special case. (a) shows the discrete trick, which works by passing a noisy logit through the unit step function. (b), (c), (d) show Concrete relaxations; the horizontal blue densities show the density of the input distribution and the vertical densities show the corresponding Binary Concrete density on (0, 1) for varying λ. (d) (Convex eventually) If λ (n 1)−1, then pα,λ(x) is log-convex in x. ≤ − The binary case of the Gumbel-Max trick simplifies to passing additive noise through a step func- tion. The corresponding Concrete relaxation is implemented by passing additive noise through a sigmoid—see Figure 3. We cover this more thoroughly in Appendix B, along with a cheat sheet (Appendix F) on the density and implementation of all the random variables discussed in this work. 3.3 CONCRETE RELAXATIONS Concrete random variables may have some intrinsic value, but we investigate them simply as surro- gates for optimizing a SCG with discrete nodes. When it is computationally feasible to integrate over the discreteness, that will always be a better choice. Thus, we consider the use case of optimizing a large graph with discrete stochastic nodes from samples. First, we outline our proposal for how to use Concrete relaxations by considering a variational autoencoder with a single discrete latent variable. Let P,(d) be the mass function of some n- dimensional one-hot discrete random variable with unnormalized probabilities a € (0,00)” and po(z|d) some distribution over a data point x given d € (0, 1)" one-hot. The generative model is then po ,a(x,d) = po(2|d)P.(d). Let Qa(d|2) be an approximating posterior over d € (0, 1)" one- hot whose unnormalized probabilities a(x) € (0,00)" depend on x. All together the variational lowerbound we care about stochastically optimizing is pθ(x D)Pa(D) x) | E D∼Qα(d|x) L1(θ, a, α) = log | Qα(D , (12) with respect to θ, a, and any parameters of α. First, we relax the stochastic computation D Concrete(α(x), λ1) 12 will re- with density qα,λ1(z sult in a non-interpretable objective, which does not necessarily lowerbound log p(x), because E x)/Pa(Z)] is not a KL divergence. Thus we propose “relaxing” the terms Pa(d) and Qα(d x) to reflect the true sampling distribution. Thus, the relaxed objective is: | pθ(x L1(θ, a, α) | where pa,λ2(z) is a Concrete density with location a and temperature λ2. At test time we evaluate the discrete lowerbound L1(θ, a, α). Naively implementing Eq. 13 will result in numerical issues. We discuss this and other details in Appendix C. Thus, the basic paradigm we propose is the following: during training replace every discrete node with a Concrete node at some fixed temperature (or with an annealing schedule). The graphs are identical up to the softmax / argmax computations, so the parameters of the relaxed graph and discrete graph are the same. When an objective depends on the log-probability of discrete variables in the SCG, as the variational lowerbound does, we propose that the log-probability terms are also “relaxed” to represent the true distribution of the relaxed node. At test time the original discrete loss is evaluated. This is possible, because the discretization of any Concrete distribution has a closed form mass function, and the relaxation of any discrete distribution into a Concrete distribution has a closed form density. This is not always possible. For example, the multinomial probit model—the Gumbel-Max trick with Gaussians replacing Gumbels—does not have a closed form mass. The success of Concrete relaxations will depend on the choice of temperature during training. It is important that the relaxed nodes are not able to represent a precise real valued mode in the interior 6 (13) Published as a conference paper at ICLR 2017 of the simplex as in Figure 2d. If this is the case, it is possible for the relaxed random variable to communicate much more than log2(n) bits of information about its α parameters. This might lead the relaxation to prefer the interior of the simplex to the vertices, and as a result there will be a large integrality gap in the overall performance of the discrete graph. Therefore Proposition 1 (d) is a conservative guideline for generic n-ary Concrete relaxations; at temperatures lower than )n. We discuss (n the subtleties of choosing the temperatures in more detail in Appendix C. Ultimately the best choice of λ and the performance of the relaxation for any specific n will be an empirical question. # 4 RELATED WORK Perhaps the most common distribution over the simplex is the Dirichlet with density pa(x) « hel rest on z € A”~!. The Dirichlet can be characterized by strong independence proper- ties, and a great deal of work has been done to generalize it [1985] {1994} Favaro et al.|[2011). Of note is the Logistic Normal distribution (Atchison & Shen]]1980), which can be simulated by taking the softmax of n — 1 normal random variables and an nth logit that is deterministically zero. The Logistic Normal is an important dis- tribution, because it can effectively model correlations within the simplex (Blei & Lafferty] 2006). To our knowledge the Concrete distribution does not fall completely into any family of distribu- tions previously described. For A < 1 the Concrete is in a class of normalized infinitely divisible distributions (S. Favaro, personal communication), and the results of [Favaro et al.|(2011) apply. The idea of using a softmax of Gumbels as a relaxation for a discrete random variable was concur- rently considered by (Jang et al., 2016), where it was called the Gumbel-Softmax. They do not use the density in the relaxed objective, opting instead to compute all aspects of the graph, including discrete log-probability computations, with the relaxed stochastic state of the graph. In the case of variational inference, this relaxed objective is not a lower bound on the marginal likelihood of the observations, and care needs to be taken when optimizing it. The idea of using sigmoidal functions with additive input noise to approximate discreteness is also not a new idea. (Frey, 1997) introduced nonlinear Gaussian units which computed their activation by passing Gaussian noise with the mean and variance specified by the input to the unit through a nonlinearity, such as the logistic function. Salakhutdinov & Hinton (2009) binarized real-valued codes of an autoencoder by adding (Gaussian) noise to the logits before passing them through the logistic function. Most recently, to avoid the dif- ficulty associated with likelihood-ratio methods (Koˇcisk´y et al., 2016) relaxed the discrete sampling operation by sampling a vector of Gaussians instead and passing those through a softmax. There is another family of gradient estimators that have been studied in the context of training neural networks with discrete units. These are usually collected under the umbrella of straight- through estimators (Bengio et al., 2013; Raiko et al., 2014). The basic idea they use is passing forward discrete values, but taking gradients through the expected value. They have good empirical performance, but have not been shown to be the estimators of any loss function. This is in contrast to gradients from Concrete relaxations, which are biased with respect to the discrete graph, but unbiased with respect to the continuous one. # 5 EXPERIMENTS 5.1 PROTOCOL The aim of our experiments was to evaluate the effectiveness of the gradients of Concrete relax- ations for optimizing SCGs with discrete nodes. We considered the tasks in (Mnih & Rezende, 2016): structured output prediction and density estimation. Both tasks are difficult optimization problems involving fitting probability distributions with hundreds of latent discrete nodes. We compared the performance of Concrete reparameterizations to two state-of-the-art score function estimators: VIMCO (Mnih & Rezende, 2016) for optimizing the multisample variational objec- tive (m > 1) and NVIL (Mnih & Gregor, 2014) for optimizing the single-sample one (m = 1). We performed the experiments using the MNIST and Omniglot datasets. These are datasets of 28 images of handwritten digits (MNIST) or letters (Omniglot). For MNIST we used the fixed 28 binarization of Salakhutdinov & Murray (2008) and the standard 50,000/10,000/10,000 split into 7 Published as a conference paper at ICLR 2017 MNIST NLL Omniglot NLL binary model (200H – 784V) Test Train Test Train m Concrete VIMCO Concrete VIMCO Concrete VIMCO Concrete VIMCO 1 5 50 107.3 104.9 104.3 104.4 101.9 98.8 107.5 104.9 104.2 104.2 101.5 98.3 118.7 118.0 118.9 115.7 113.5 113.0 117.0 115.8 115.8 112.2 110.8 110.0 (200H – 200H – 784V) 1 5 50 102.1 99.9 99.5 92.9 91.7 90.7 102.3 100.0 99.4 91.7 90.8 89.7 116.3 116.0 117.0 109.2 107.5 108.1 114.4 113.5 113.9 104.8 103.6 103.6 (200H ∼784V) 1 5 50 92.1 89.5 88.5 93.8 91.4 89.3 91.2 88.1 86.4 91.5 88.6 86.5 108.4 107.5 108.1 116.4 118.2 116.0 103.6 101.4 100.5 110.3 102.3 100.8 (200H ∼200H ∼784V) 1 5 50 87.9 86.3 85.7 88.4 86.4 85.5 86.5 84.1 83.1 85.8 82.5 81.8 105.9 105.8 106.8 111.7 108.2 113.2 100.2 98.6 97.5 105.7 101.1 95.2 Table 1: Density estimation with binary latent variables. When m = 1, VIMCO stands for NVIL. training/validation/testing sets. For Omniglot we sampled a fixed binarization and used the stan- dard 24,345/8,070 split into training/testing sets. We report the negative log-likelihood (NLL) of the discrete graph on the test data as the performance metric. All of our models were neural networks with layers of n-ary discrete stochastic nodes with values log2(n). The distributions were parameterized by n real val- on the corners of the hypercube } {− ues log αk ∈ Discrete(α) with n states. Model descriptions are of the form “(200V–200H 784V)”, read from left to right. This describes the order of conditional sampling, again from left to right, with each integer repre- senting the number of stochastic units in a layer. The letters V and H represent observed and latent variables, respectively. If the leftmost layer is H, then it was sampled unconditionally from some parameters. Conditioning functions are described by , where “–” means a linear function of the previous layer and “ ” means a non-linear function. A “layer” of these units is simply the concatenation of some number of independent nodes whose parameters are determined as a function 240 the previous layer. For example a 240 binary layer is a factored distribution over the } hypercube. Whereas a 240 8-ary layer can be seen as a distribution over the same hypercube where each of the 80 triples of units are sampled independently from an 8 way discrete distribution over 3. All models were initialized with the heuristic of Glorot & Bengio (2010) and optimized {− } using Adam (Kingma & Ba, 2014). All temperatures were fixed throughout training. Appendix D for hyperparameter details. 5.2 DENSITY ESTIMATION Density estimation, or generative modelling, is the problem of fitting the distribution of data. We took the latent variable approach described in Section 2.4 and trained the models by optimizing the Lm(θ, φ) given by Eq. 8 averaged uniformly over minibatches of data points variational objective x) were parameterized x. Both our generative models pθ(z, x) and variational distributions qφ(z with neural networks as described above. We trained models with and approximated the NLL with ∈ { L50,000(θ, φ) averaged uniformly over the whole dataset. The results are shown in Table 1. In general, VIMCO outperformed Concrete relaxations for linear models and Concrete relaxations outperformed VIMCO for non-linear models. We also tested the effectiveness of Concrete relaxations on generative models with n-ary layers on the L5(θ, φ) ob- jective. The best 4-ary model achieved test/train NLL 86.7/83.3, the best 8-ary achieved 87.4/84.6 with Concrete relaxations, more complete results in Appendix E. The relatively poor performance of the 8-ary model may be because moving from 4 to 8 results in a more difficult objective without much added capacity. As a control we trained n-ary models using logistic normals as relaxations of discrete distributions (with retuned temperature hyperparameters). Because the discrete zero tem- perature limit of logistic Normals is a multinomial probit whose mass function is not known, we evaluated the discrete model by sampling from the discrete distribution parameterized by the logits 8 Published as a conference paper at ICLR 2017 binary model (392V–240H –240H–392V) Test NLL Train NLL m Concrete VIMCO Concrete VIMCO 1 5 50 58.5 54.3 53.4 61.4 54.5 51.8 54.2 49.2 48.2 59.3 52.7 49.6 (392V–240H –240H–240H –392V) 1 5 50 56.3 52.7 52.0 59.7 53.5 50.2 51.6 46.9 45.9 58.4 51.6 47.9 # Xr Figure 4: Results for structured prediction on MNIST comparing Concrete relaxations to VIMCO. When m = 1 VIMCO stands for NVIL. The plot on the right shows the objective (lower is better) for the continuous and discrete graph trained at temperatures λ. In the shaded region, units prefer to communicate real values in the interior of ( − learned during training. The best 4-ary model achieved test/train NLL of 88.7/85.0, the best 8-ary model achieved 89.1/85.1. 5.3 STRUCTURED OUTPUT PREDICTION Structured output prediction is concerned with modelling the high-dimensional distribution of the observation given a context and can be seen as conditional density estimation. We considered the task of predicting the bottom half x1 of an image of an MNIST digit given its top half x2, as introduced by Raiko et al. (2014). We followed Raiko et al. (2014) in using a model with layers of discrete stochastic units between the context and the observation. Conditioned on the top half x2 the network samples from a distribution pφ(z x2) over layers of stochastic units z then predicts x1 by sampling from a distribution pθ(x1 | SP m (θ, φ) = ; 1 LEP (0,d)=, E log { — x |Z)}|. OO) = fle (Gp Deol | 20) 1 m Lm(θ, φ) (Eq. 8) where we use the prior pφ(z This objective is a special case of distribution. Thus, the objective is a lower bound on log pθ,φ(x1 | averaged uniformly over mini- We trained the models by optimizing 1, 5, 50 SP 100(θ, φ) averaged uniformly over the entire dataset. The batches and evaluated them by computing results are shown in Figure 4. Concrete relaxations more uniformly outperformed VIMCO in this instance. We also trained n-ary (392V–240H–240H–240H–392V) models on the (θ, φ) objec- tive using the best temperature hyperparameters from density estimation. 4-ary achieved a test/train NLL of 55.4/46.0 and 8-ary achieved 54.7/44.8. As opposed to density estimation, increasing arity uniformly improved the models. We also investigated the hypothesis that for higher temperatures Concrete relaxations might prefer the interior of the interval to the boundary points . Figure 1, 1 } (θ, φ). 4 was generated with binary (392V–240H–240H–240H–392V) model trained on # L # 6 CONCLUSION We introduced the Concrete distribution, a continuous relaxation of discrete random variables. The Concrete distribution is a new distribution on the simplex with a closed form density parameterized by a vector of positive location parameters and a positive temperature. Crucially, the zero temper- ature limit of every Concrete distribution corresponds to a discrete distribution, and any discrete distribution can be seen as the discretization of a Concrete one. The application we considered was training stochastic computation graphs with discrete stochastic nodes. The gradients of Concrete relaxations are biased with respect to the original discrete objective, but they are low variance un- biased estimators of a continuous surrogate objective. We showed in a series of experiments that stochastic nodes with Concrete distributions can be used effectively to optimize the parameters of a stochastic computation graph with discrete stochastic nodes. We did not find that annealing or automatically tuning the temperature was important for these experiments, but it remains interesting and possibly valuable future work. 9 Published as a conference paper at ICLR 2017 ACKNOWLEDGMENTS We thank Jimmy Ba for the excitement and ideas in the early days, Stefano Favarro for some analysis of the distribution. We also thank Gabriel Barth-Maron and Roger Grosse. REFERENCES Mart´ın Abadi, Ashish Agarwal, Paul Barham, Eugene Brevdo, Zhifeng Chen, Craig Citro, Greg S. Corrado, Andy Davis, Jeffrey Dean, Matthieu Devin, Sanjay Ghemawat, Ian Goodfellow, Andrew Harp, Geoffrey Irving, Michael Isard, Yangqing Jia, Rafal Jozefowicz, Lukasz Kaiser, Manjunath Kudlur, Josh Levenberg, Dan Man´e, Rajat Monga, Sherry Moore, Derek Murray, Chris Olah, Mike Schuster, Jonathon Shlens, Benoit Steiner, Ilya Sutskever, Kunal Talwar, Paul Tucker, Vin- cent Vanhoucke, Vijay Vasudevan, Fernanda Vi´egas, Oriol Vinyals, Pete Warden, Martin Watten- berg, Martin Wicke, Yuan Yu, and Xiaoqiang Zheng. TensorFlow: Large-scale machine learning on heterogeneous systems, 2015. URL http://tensorflow.org/. Software available from tensorflow.org. J Aitchison. A general class of distributions on the simplex. Journal of the Royal Statistical Society. Series B (Methodological), pp. 136–146, 1985. J Atchison and Sheng M Shen. Logistic-normal distributions: Some properties and uses. Biometrika, 67(2):261–272, 1980. Yoshua Bengio, Nicholas L´eonard, and Aaron Courville. Estimating or propagating gradients through stochastic neurons for conditional computation. arXiv preprint arXiv:1308.3432, 2013. David Blei and John Lafferty. Correlated topic models. 2006. Yuri Burda, Roger Grosse, and Ruslan Salakhutdinov. Importance weighted autoencoders. ICLR, 2016. Robert J Connor and James E Mosimann. Concepts of independence for proportions with a gener- alization of the dirichlet distribution. Journal of the American Statistical Association, 64(325): 194–206, 1969. Stefano Favaro, Georgia Hadjicharalambous, and Igor Pr¨unster. On a class of distributions on the simplex. Journal of Statistical Planning and Inference, 141(9):2987 – 3004, 2011. Brendan Frey. Continuous sigmoidal belief networks trained using slice sampling. In NIPS, 1997. Michael C Fu. Gradient estimation. Handbooks in operations research and management science, 13:575–616, 2006. Xavier Glorot and Yoshua Bengio. Understanding the difficulty of training deep feedforward neural networks. In Aistats, volume 9, pp. 249–256, 2010. Peter W Glynn. Likelihood ratio gradient estimation for stochastic systems. Communications of the ACM, 33(10):75–84, 1990. Alex Graves, Greg Wayne, Malcolm Reynolds, Tim Harley, Ivo Danihelka, Agnieszka Grabska- Barwi´nska, Sergio G´omez Colmenarejo, Edward Grefenstette, Tiago Ramalho, John Agapiou, et al. Hybrid computing using a neural network with dynamic external memory. Nature, 538 (7626):471–476, 2016. Evan Greensmith, Peter L. Bartlett, and Jonathan Baxter. Variance reduction techniques for gradient estimates in reinforcement learning. JMLR, 5, 2004. Edward Grefenstette, Karl Moritz Hermann, Mustafa Suleyman, and Phil Blunsom. Learning to transduce with unbounded memory. In Advances in Neural Information Processing Systems, pp. 1828–1836, 2015. Karol Gregor, Ivo Danihelka, Andriy Mnih, Charles Blundell, and Daan Wierstra. Deep autoregres- sive networks. arXiv preprint arXiv:1310.8499, 2013. Karol Gregor, Ivo Danihelka, Alex Graves, Danilo Jimenez Rezende, and Daan Wierstra. Draw: A recurrent neural network for image generation. arXiv preprint arXiv:1502.04623, 2015. Shixiang Gu, Sergey Levine, Ilya Sutskever, and Andriy Mnih. MuProp: Unbiased backpropagation for stochastic neural networks. ICLR, 2016. Emil Julius Gumbel. Statistical theory of extreme values and some practical applications: a series of lectures. Number 33. US Govt. Print. Office, 1954. Tamir Hazan and Tommi Jaakkola. On the partition function and random maximum a-posteriori perturbations. In ICML, 2012. 10 Published as a conference paper at ICLR 2017 Tamir Hazan, George Papandreou, and Daniel Tarlow. Perturbation, Optimization, and Statistics. MIT Press, 2016. Matthew D Hoffman, David M Blei, Chong Wang, and John William Paisley. Stochastic variational inference. JMLR, 14(1):1303–1347, 2013. E. Jang, S. Gu, and B. Poole. Categorical Reparameterization with Gumbel-Softmax. ArXiv e-prints, November 2016. Diederik Kingma and Jimmy Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014. Diederik P Kingma and Max Welling. Auto-encoding variational bayes. arXiv preprint arXiv:1312.6114, 2013. Diederik P Kingma and Max Welling. Auto-encoding variational bayes. ICLR, 2014. Tom´aˇs Koˇcisk´y, G´abor Melis, Edward Grefenstette, Chris Dyer, Wang Ling, Phil Blunsom, and In Karl Moritz Hermann. Semantic parsing with semi-supervised sequential autoencoders. EMNLP, 2016. R. Duncan Luce. Individual Choice Behavior: A Theoretical Analysis. New York: Wiley, 1959. Chris J Maddison. A Poisson process model for Monte Carlo. In Tamir Hazan, George Papandreou, and Daniel Tarlow (eds.), Perturbation, Optimization, and Statistics, chapter 7. MIT Press, 2016. Chris J Maddison, Daniel Tarlow, and Tom Minka. A∗ Sampling. In NIPS, 2014. Andriy Mnih and Karol Gregor. Neural variational inference and learning in belief networks. In ICML, 2014. Andriy Mnih and Danilo Jimenez Rezende. Variational inference for monte carlo objectives. In ICML, 2016. Volodymyr Mnih, Nicolas Heess, Alex Graves, and koray kavukcuoglu. Recurrent Models of Visual Attention. In NIPS, 2014. Christian A Naesseth, Francisco JR Ruiz, Scott W Linderman, and David M Blei. Rejection sam- pling variational inference. arXiv preprint arXiv:1610.05683, 2016. John William Paisley, David M. Blei, and Michael I. Jordan. Variational bayesian inference with stochastic search. In ICML, 2012. George Papandreou and Alan L Yuille. Perturb-and-map random fields: Using discrete optimization to learn and sample from energy models. In ICCV, 2011. Tapani Raiko, Mathias Berglund, Guillaume Alain, and Laurent Dinh. Techniques for learning binary stochastic feedforward neural networks. arXiv preprint arXiv:1406.2989, 2014. Rajesh Ranganath, Sean Gerrish, and David M. Blei. Black box variational inference. In AISTATS, 2014. William S Rayens and Cidambi Srinivasan. Dependence properties of generalized liouville distri- butions on the simplex. Journal of the American Statistical Association, 89(428):1465–1470, 1994. Danilo Jimenez Rezende, Shakir Mohamed, and Daan Wierstra. Stochastic backpropagation and approximate inference in deep generative models. In ICML, 2014. Francisco JR Ruiz, Michalis K Titsias, and David M Blei. The generalized reparameterization gradient. arXiv preprint arXiv:1610.02287, 2016. Ruslan Salakhutdinov and Geoffrey Hinton. Semantic hashing. International Journal of Approxi- mate Reasoning, 50(7):969–978, 2009. Ruslan Salakhutdinov and Iain Murray. On the quantitative analysis of deep belief networks. In ICML, 2008. John Schulman, Nicolas Heess, Theophane Weber, and Pieter Abbeel. Gradient estimation using stochastic computation graphs. In NIPS, 2015. Theano Development Team. Theano: A Python framework for fast computation of mathematical expressions. arXiv e-prints, abs/1605.02688, May 2016. URL http://arxiv.org/abs/ 1605.02688. Michalis Titsias and Miguel L´azaro-Gredilla. Doubly stochastic variational bayes for non-conjugate inference. In Tony Jebara and Eric P. Xing (eds.), ICML, 2014. 11 Published as a conference paper at ICLR 2017 Michalis Titsias and Miguel L´azaro-Gredilla. Local expectation gradients for black box variational inference. In NIPS, 2015. Ronald J Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine learning, 8(3-4):229–256, 1992. Kelvin Xu, Jimmy Ba, Ryan Kiros, Kyunghyun Cho, Aaron Courville, Ruslan Salakhudinov, Rich Zemel, and Yoshua Bengio. Show, attend and tell: Neural image caption generation with visual attention. In ICML, 2015. John I Yellott. The relationship between luce’s choice axiom, thurstone’s theory of comparative judgment, and the double exponential distribution. Journal of Mathematical Psychology, 15(2): 109–144, 1977. # A PROOF OF PROPOSITION 1 Let X Concrete(α, λ) with location parameters α (0, )n and temperature λ (0, ). # Let X Concrete(α, λ) with location parameters α # ∼ 1. Let Gk ∼ ∈ ∞ ∈ Gumbel i.i.d., consider ∞ exp((log ax + Gx)/A) DiL1 exp((log ai + Gi)/d) Yi Let Zk = log αk + Gk, which has density αk exp( zk) exp( αk exp( zk)) − − − We will consider the invertible transformation F (z1, . . . , zn) = (y1, . . . , yn−1, c) where ye = exp(zn/A)e7* n c= Dexplsi/2) i=1 then F −1(y1, . . . , yn−1, c) = (λ(log y1 + log c), . . . , λ(log yn−1 + log c), λ(log yn + log c)) n-1 >; where yn = 1 i=1 yi. This has Jacobian — − λy−1 1 0 0 λy−1 n 0 λy−1 2 0 λy−1 n 0 0 λy−1 3 ... λy−1 n 0 0 0 λy−1 n . . . . . . . . . . . . 0 0 0 λy−1 n λc−1 λc−1 λc−1 λc−1 − − − − − − 1 rows to the bottom row we see that this Jacobian by adding yi/yn times each of the top n has the same determinant as λy−1 1 0 0 0 λy−1 2 0 0 0 0 0 λy−1 3 ... 0 0 . . . 0 . . . . . . 0 0 . . . 0 0 0 λc−1 λc−1 λc−1 0 λ(cyn)−1 and thus the determinant is equal to yr oe eT] in Yi 12 Published as a conference paper at ICLR 2017 all together we have the density # A” TI A” TI pea Oe exp(—A log ys, — A log c) exp(—ay, exp(—A log yx — A log c)) Tina yi λ log c) exp( i=1 yi with r = log c change of variables we have density A” TT, A” TT, Oe exp(—Ar) exp(—ax exp(—A log yx — Ar)) Ty? at exp(—nAr) exp(— > a; exp(—Alog y; — Ar)) = letting y = log(oy 4 any,) # n=1 αky−λ k ) k=1 αk Te muro) exp(—nAr +7) exp(— exp(—Ar + 7) integrating out r A” TT Oe (ao + vr) Thay 2 ePO) r ety Me aT = 1)ly"- 1 T= LOKYR (Shan Rv)” * (exp(—yn)F(n)) = -1 # Thus Y d= X. 2. Follows directly from (a) and the Gumbel-Max trick (Maddison, 2016). 3. Follows directly from (a) and the Gumbel-Max trick (Maddison, 2016). 4. Let λ 1)−1. The density of X can be rewritten as ≤ − n -r-1 ORY Po, r(@) & k=1 wit ay; * -Il a, Lune 1)-1 par Thai} Thus, the log density is up to an additive constant C 1 n log pa,r(x) = S0(A(n = 1) = LD log yx — nlog | S> ax T] kal k=1 jfk If λ log is convex. For the 1)−1. last term, Thus, their composition is convex. The sum of convex terms is convex, finishing the proof. # B THE BINARY SPECIAL CASE Bernoulli random variables are an important special case of discrete distributions taking states in . Here we consider the binary special case of the Gumbel-Max trick from Figure 1a along 0, 1 } )2 be a two state discrete random variable on Let D ∈ D1 + D2 = 1, parameterized as in Figure 1a by α1, α2 > 0: Discrete(α) for α (0, ∼ ∞ 0, 1 { 2 such that } P(D1 = 1) = α1 α1 + α2 (14) 13 Published as a conference paper at ICLR 2017 The distribution is degenerate, because D1 = 1 the Gumbel-Max reparameterization, the event that D1 = 1 is the event that G2 + log α2} G2 ∼ G1 − where U ∼ D2. Therefore we consider just D1. Under G1 + log α1 > Gumbel i.i.d. The difference of two Gumbels is a Logistic distribution U ) − { d= log U where Gk ∼ Logistic, which can be sampled in the following way, G1 − Uniform(0, 1). So, if α = α1/α2, then we have G2 log(1 − − P(D1 = 1) = P(G1 + log α1 > G2 + log α2) = P(log U log(1 U ) + log α > 0) (15) − − Thus, D1 d= H(log α + log U log(1 U )), where H is the unit step function. − − Correspondingly, we can consider the Binary Concrete relaxation that results from this process. As in the n-ary case, we consider the sampling routine for a Binary Concrete random variable X ∈ ∼ X = 1 + exp( 1 (log α + L)/λ) (16) − We define the Binary Concrete random variable X by its density on the unit interval. Definition 2 (Binary Concrete Random Variables). Let α has a Binary Concrete distribution X its density is: # € (0,1) temperature A, if # X pα,λ(x) = λαx−λ−1(1 (αx−λ + (1 x)−λ−1 x)−λ)2 . (17) − − We state without proof the special case of Proposition 1 for Binary Concrete distributions Proposition 2 (Some Properties of Binary Concrete Random Variables). Let X BinConcrete(α, λ) with location parameter α ~ ∼ # ∈ Logistic, then X d= ∞ ∈ 1 1+exp(−(log α+L)/λ) , (a) (Reparameterization) If L ∼ ∞ (b) (Rounding) P (X > 0.5) = α/(1 + α), (c) (Zero temperature) P (limλ→0 X = 1) = α/(1 + α), (d) (Convex eventually) If λ 1, then pα,λ(x) is log-convex in x. ≤ We can generalize the binary circuit beyond Logistic random variables. Consider an arbitrary ran- dom variable X with infinite support on R. If Φ : R → P(H(X) = 1) = 1 Φ(0) − If we want this to have a Bernoulli distribution with probability α/(1 + α), then we should solve the equation 1 − Φ(0) = α 1 + α . This gives Φ(0) = 1/(1 + α), which can be accomplished by relocating the random variable Y with CDF Φ to be X = Y − # C USING CONCRETE RELAXATIONS In this section we include some tips for implementing and using the Concrete distribution as a relaxation. We use the following notation # nm σ(x) = 1 1 + exp( x) n LΣE k=1 { xk} = log k=1 exp(xk) − Both sigmoid and log-sum-exp are common operations in libraries like TensorFlow or theano. 14 Published as a conference paper at ICLR 2017 # C.1 THE BASIC PROBLEM For the sake of exposition, we consider a simple variational autoencoder with a single discrete random variable and objective L1(θ, a, α) given by Eq. 8 for a single data point x. This scenario will allow us to discuss all of the decisions one might make when using Concrete relaxations. In particular, )n, let pθ(x Discrete(a) with a network), which is a continuous function of d and parameters θ, let D ∼ hot discrete random variable in (0, 1)n whose unnormalized probabilities α(x) function (possible a neural net with its own parameters) of x. Let Qα(d | D. Then, we care about optimizing L1(θ, a, α) = E D∼Qα(d|x) log pθ(x D)Pa(D) x) | | Qα(D (18) with respect to θ, a, and any parameters in α from samples of the SCG required to simulate an estimator of L1(θ, a, α). # C.2 WHAT YOU MIGHT RELAX AND WHY The first consideration when relaxing an estimator of Eq. 18 is how to relax the stochastic computa- tion. The only sampling required to simulate Discrete(α(x)). The correspond- L1(θ, a, α) is D Concrete(α(x), λ1) with temperature λ1 and location ing Concrete relaxation is to sample Z ∼ parameters are the the unnormalized probabilities α(x) of D. Let density qα,λ1(z x) be the density | of Z. We get a relaxed objective of the form: E D∼Qα(d|x) [ · ] → E Z∼qα,λ1 (z|x) [ · ] (19) This choice allows us to take derivatives through the stochastic computaitons of the graph. The second consideration is which objective to put in place of [ ] in Eq. 19. We will consider the ideal scenario irrespective of numerical issues. In Subsection C.3 we address those numerical x) (which is issues. The central question is how to treat the expectation of the ratio Pa(D)/Qα(D | the KL component of the loss) when Z replaces D. There are at least three options for how to modify the objective. They are, (20) replace the discrete mass with Concrete densities, (21) relax the computation of the discrete log mass, (22) replace it with the analytic discrete KL. Pa,ro(Z) E log po (a|Z) + log ——=— 20 soak ayy [lot volelZ) + log PAK) 20) n i P,(d) E log pe (|Z) + Z; log ——_._— 21 zogann, (ln) | 8 Po(a|Z) > 8 O, (dO]x) (21) # n E Z∼qα,λ1 (z|x) [log pθ(x Z)] + | i=1 Qα(d(i) x) log | Pa(d(i)) Qα(d(i) x) (22) | where d(i) is a one-hot binary vector with d(i) i = 1 and pa,λ2 (z) is the density of some Concrete random variable with temperature λ2 with location parameters a. Although (22) or (21) is tempting, we emphasize that these are NOT necessarily lower bounds on log p(x) in the relaxed model. (20) is the only objective guaranteed to be a lower bound: ; - Pa,d2(Z) ; . soaE oy [oePolel2) + toe 2 oy] <toe | polale)Paas(2) dr. 23) For this reason we consider objectives of the form (20). Choosing (22) or (21) is possible, but the value of these objectives is not interpretable and one should early stop otherwise it will overfit to the spurious “KL” component of the loss. We now consider practical issues with (20) and how to address them. All together we can interpret qα,λ1(z x) as the Concrete relaxation of the variational | posterior and pa,λ2 (z) the relaxation of the prior. 15 Published as a conference paper at ICLR 2017 C.3 WHICH RANDOM VARIABLE TO TREAT AS THE STOCHASTIC NODE When implementing a SCG like the variational autoencoder example, we need to compute log- probabilities of Concrete random variables. This computation can suffer from underflow, so where possible it’s better to take a different node on the relaxed graph as the stochastic node on which log- likelihood terms are computed. For example, it’s tempting in the case of Concrete random variables to treat the Gumbels as the stochastic node on which the log-likelihood terms are evaluated and the softmax as downstream computation. This will be a looser bound in the context of variational inference than the corresponding bound when treating the Concrete relaxed states as the node. The solution we found to work well was to work with Concrete random variables in log-space. Consider the following vector in Rn for location parameters α ) and Gk ∼ # loga; + Gi x log αk + Gk λ n LΣE i=1 Yk = − therefore we call Y an Y ∼ ExpConcrete(α, λ). The advantage of this reparameterization is that the KL terms of a varia- tional loss are invariant under invertible transformation. exp is invertible, so the KL between two ExpConcrete random variables is the same as the KL between two Concrete random variables. The log-density log κα,λ(y) of an ExpConcrete(α, λ) is also simple to compute: n n log Ka,,(y) = log((n — 1)!) + (n — 1) log 4 (Spree - an) — nLXE {log ax — Ayn} k=1 Rn such that LΣEn for y tribution is still interpretable in the zero temperature limit. In the limit of λ → random variables become discrete random variables over the one-hot vectors of d where LΣEn 0, 1 } { = 0. Note that the sample space of the ExpConcrete dis- 0 ExpConcrete n } yk} k=1{ ∈ ∈ {−∞ n. = 0. exp(Y ) in this case results in the one-hot vectors in dk} , 0 # k=1{ C.3.1 n-ARY CONCRETE Returning to our initial task of relaxing £1(0,a, a), let Y ~ ExpConcrete(a(x), 1) Ke,, (y|x) be the ExpConcrete latent variable corresponding to the Concrete relaxation of the variational posterior Q. (d|x). Let pa,y, (y) be the density of an ExpConcrete random corresponding to the Concrete relaxation pa,,,(z) of P,(d). All together we can see that Pa,d2(Z)_] # with density qu,x, (z|x) variable Pa,d2(Z)_] log po(a|Z) + log 2 | = E ow pote exp(Y)) + log Zar (2|@) da,d,(Z|t) | ¥~rme,; (ule) Ke, (Y |x) (24) Pa,d2(¥) Therefore, we used ExpConcrete random variables as the stochastic nodes and treated exp as a downstream computation. The relaxation is then, relax L£1(0,a,a) Y og po(z| exp(Y)) + log oa | ; (25) Y~Ra,d, (ylx) Kadi (Y|x) and the objective on the RHS is fully reparameterizable and what we chose to optimize. # C.3.2 BINARY CONCRETE In the binary case, the logistic function is invertible, so it makes most sense to treat the logit plus noise as the stochastic node. In particular, the binary random node was sample from: Y = log α + log U − λ log(1 − U ) (26) Uniform(0, 1) and always followed by σ as downstream computation. log U where U − U ) is a Logistic random variable, details in the cheat sheet, and so the log-density log gα,λ(y) of this node (before applying σ) is log gα,λ(y) = log λ λy + log α 2 log(1 + exp( λy + log α)) − − − 16 | Published as a conference paper at ICLR 2017 All together the relaxation in the binary special case would be £:(6,a,a)" EB [logpo(x|a(¥)) + 10g 242) ; 27 ¥~ga,a, (y|®) Ja, (¥|2) e where fa,λ2(y) is the density of a Logistic random variable sampled via Eq. 26 with location a and temperature λ2. This section had a dense array of densities, so we summarize the relevant ones, along with how to sample from them, in Appendix F. C.4 CHOOSING THE TEMPERATURE The success of Concrete relaxations will depend heavily on the choice of temperature during train- ing. It is important that the relaxed nodes are not able to represent a precise real valued mode in the interior of the simplex as in Figure For example, choosing additive Gaussian noise e ~ Normal(0, 1) with the logistic function o(x) to get relaxed Bernoullis of the form o(€ + 1) will result in a large mode in the centre of the interval. This is because the tails of the Gaussian distribution drop off much faster than the rate at which o squashes. Even including a temperature parameter does not completely solve this problem; the density of o((€ + 4)/A) at any temperature still goes to 0 as its approaches the boundaries 0 and 1 of the unit interval. Therefore |(D]of Proposi- tion|I]is a conservative guideline for generic n-ary Concrete relaxations; at temperatures lower than (n —1)~! we are guaranteed not to have any modes in the interior for any a € (0, 00)”. In the case of the Binary Concrete distribution, the tails of the Logistic additive noise are balanced with the logistic squashing function and for temperatures \ < 1 the density of the Binary Concrete distribu- tion is log-convex for all parameters a, see Figure[3b] Still, practice will often disagree with theory here. The peakiness of the Concrete distribution increases with n, so much higher temperatures are tolerated (usually necessary). For n = 1 temperatures A < (n — 1)~1 is a good guideline. For n > 1 taking A < (n — 1)~1 is not necessarily a good guideline, although it will depend on n and the specific application. As n —> oo the Concrete distribution becomes peakier, because the random normalizing constant ee exp((log ax + Gx)/A) grows. This means that practically speaking the optimization can tolerate much higher temperatures than (n — 1)~!. We found in the cases n = 4 that \ = 1 was the best temperature and in n = 8, A = 2/3 was the best. Yet A = 2/3 was the best single perform- ing temperature across the n € {2,4,8} cases that we considered. We recommend starting in that ball-park and exploring for any specific application. When the loss depends on a KL divergence between two Concrete nodes, it’s possible to give the nodes distinct temperatures. We found this to improve results quite dramatically. In the context of our original problem and it’s relaxation: Y) L£1(0,a, a) = E log po(2| exp(Y)) + lo Por) > 1(0,, «) vn e te) ¢ pe(z| exp(Y)) 8 aa, Ve) |? (28) Both λ1 for the posterior temperature and λ2 for the prior temperature are tunable hyperparameters. # D EXPERIMENTAL DETAILS The basic model architectures we considered are exactly analogous to those in Burda et al. (2016) with Concrete/discrete random variables replacing Gaussians. # D.1 — VS ∼ The conditioning functions we used were either linear or non-linear. Non-linear consisted of two tanh layers of the same size as the preceding stochastic layer in the computation graph. # D.2 n-ARY LAYERS All our models are neural networks with layers of n-ary discrete stochastic nodes with log2(n)- log2(n). For a generic n-ary node dimensional states on the corners of the hypercube 1, 1 } {− 17 Published as a conference paper at ICLR 2017 Discrete(α) for sampling proceeds as follows. Sample a n-ary discrete random variable D log2(n) α } {− as columns, then we took Y = CD as downstream computation on D. The corresponding Con- crete relaxation is to take X ) and set (0, ˜Y = CX. For the binary case, this amounts to simply sampling U Uniform(0, 1) and taking ∼ 1. The corresponding Binary Concrete relaxation is Y = 2H(log U U ) + log α) − ˜Y = 2σ((log U 1. U ) + log α)/λ) − − − − − # D.3 BIAS INITIALIZATION All biases were initialized to 0 with the exception of the biases in the prior decoder distribution over the 784 or 392 observed units. These were initialized to the logit of the base rate averaged over the respective dataset (MNIST or Omniglot). # D.4 CENTERING We also found it beneficial to center the layers of the inference network during training. The activity 1, 1)d of each stochastic layer was centered during training by maintaining a exponentially in ( decaying average with rate 0.9 over minibatches. This running average was subtracted from the activity of the layer before it was updated. Gradients did not flow throw this computation, so it simply amounted to a dynamic offset. The averages were not updated during the evaluation. D.5 HYPERPARAMETER SELECTION All models were initialized with the heuristic of Glorot & Bengio (2010) and optimized using Adam (Kingma & Ba, 2014) with parameters β1 = 0.9, β2 = 0.999 for 107 steps on minibatches of size 64. Hyperparameters were selected on the MNIST dataset by grid search taking the values that performed best on the validation set. Learning rates were chosen from and weight decay from . Two sets of hyperparameters were selected, one for linear models and one for non-linear models. The linear models’ hyperparameters were selected with L5(θ, φ) objective. The non-linear models’ hyperpa- the 200H–200H–784V density model on the rameters were selected with the 200H L5(θ, φ) objective. For 784V density model on the 200H ∼ density estimation, the Concrete relaxation hyperparameters were (weight decay = 0, learning rate 10−4) for linear and (weight decay = 0, learning rate = 10−4) for non-linear. For structured = 3 prediction Concrete relaxations used (weight decay = 10−3, learning rate = 3 In addition to tuning learning rate and weight decay, we tuned temperatures for the Concrete relax- ations on the density estimation task. We found it valuable to have different values for the prior and posterior distributions, see Eq. 28. In particular, for binary we found that (prior λ2 = 1/2, posterior λ1 = 2/3) was best, for 4-ary we found (prior λ2 = 2/3, posterior λ1 = 1) was best, and (prior λ2 = 2/5, posterior λ1 = 2/3) for 8-ary. No temperature annealing was used. For structured prediction we used just the corresponding posterior λ1 as the temperature for the whole graph, as there was no variational posterior. We performed early stopping when training with the score function estimators (VIMCO/NVIL) as they were much more prone to overfitting. 18 Published as a conference paper at ICLR 2017 # E EXTRA RESULTS binary (240H ∼784V) 4-ary (240H ∼784V) 8-ary (240H ∼784V) binary (240H∼240H ∼784V) 4-ary (240H∼240H ∼784V) 8-ary (240H∼240H ∼784V) m Test 91.9 1 89.0 5 88.4 50 1 5 50 91.4 89.4 89.7 1 5 50 92.5 90.5 90.5 1 5 50 87.9 86.6 86.0 1 5 50 87.4 86.7 86.7 1 5 50 88.2 87.4 87.2 Train 90.7 87.1 85.7 89.7 87.0 86.5 89.9 87.0 86.7 86.0 83.7 82.7 85.0 83.3 83.0 85.9 84.6 84.0 Test 108.0 107.7 109.0 110.7 110.5 113.0 119.61 120.7 121.7 106.6 106.9 108.7 106.6 108.3 109.4 111.3 110.5 111.1 Train 102.2 100.0 99.1 1002.7 100.2 100.0 105.3 102.7 101.0 99.0 97.1 95.9 97.8 97.3 96.8 102.5 100.5 99.5 Table 2: Density estimation using Concrete relaxations with distinct arity of layers. 19 Published as a conference paper at ICLR 2017 # F CHEAT SHEET 1 = 1+ exp(—2) LEE {xx} = log (> a) k=1 log An“! = {© € R" | xz € (—c, 0), LEE{ex} = = of Distribution and Domains Reparameterization/How To Sample # Mass/Density G G Gumbel R ∼ ∈ # G d= —10g(~log(U)) # log( # log(U )) − − # exp( exp(—g — exp(—9)) # g # exp( g)) − − − # L L # Logistic R ~ ∼ ∈ # LeR # L d= log(U ) — − # log(1 — − U ) # exp( − (1 + exp( # l) # expl-)? l))2 − # X µ λ Logistic(µ, λ) R (0, ~ ∼ ∈ ∈ # neR ) ∞ # X d= # L + µ λ # λ exp( (1 + exp( λx + µ) λx + µ))2 − − # exp(—Azx # X X α # Bernoulli(α) 0, 1 # ~ che ∼ ∈ { (0, ∈ } ) ∞ # X d= 1 {i # if L + log α otherwise ≥ 0 α 1 + α if x = 1 # X X α λ BinConcrete(α, λ) (0, 1) ) (0, ∞ ) (0, ∞ ~ ∼ ∈ ∈ ∈ # X d= σ((L + log α)/λ) λαx−λ−1(1 (αx−λ + (1 — − − x)−λ−1 x)−λ)2 X X € Discrete(α) ∼ n 0, 1 } ∈ { k=1 Xk = 1 # d= # Xk # Xp= # fl 0 if log αk + Gk > log αi + Gi for i otherwise # = k # αk i=1 αi if xk = 1 # α € ∈ (0, # )n 00)” ∞ # X X α λ X ~ Concrete(a, \) n -y- XeAr-l x, £ _2xp((log ax + Ge)/) (n—1)! Il ag € (0, 00)” x SUL, exp((log ax, + Gi)/A) A~(mI) hey Diet air; * € (0, 00) # X X α λ ~ ExpConcrete(a, \) €log A"! d logan + Gr n loga; + Gi (n—1)! Qn exp( = € (0, 00)” Xn = r ~ TEE r A~(mI) rl Foie Gi eXP(—Azi) € (0, 00) Table 3: Cheat sheet for the random variables we use in this work. Note that some of these are atypical parameterizations, particularly the Bernoulli and Logistic random variables. The table only Uniform(0, 1). From there on it may assumes that you can sample uniform random numbers U Logistic is defined in the define random variables and reuse them later on. For example, L second row, and after that point L represents a Logistic random variable that can be replaced by U ). Whenever random variables are indexed, e.g. Gk, they represent separate log U independent calls to a random number generator. 20 # λxi)
Title: Stand-Alone Self-Attention in Vision Models: Summary: Convolutions are a fundamental building block of modern computer vision systems. Recent approaches have argued for going beyond convolutions in order to capture long-range dependencies. These efforts focus on augmenting convolutional models with content-based interactions, such as self-attention and non-local means, to achieve gains on a number of vision tasks. The natural question that arises is whether attention can be a stand-alone primitive for vision models instead of serving as just an augmentation on top of convolutions. In developing and testing a pure self-attention vision model, we verify that self-attention can indeed be an effective stand-alone layer. A simple procedure of replacing all instances of spatial convolutions with a form of self-attention applied to ResNet model produces a fully self-attentional model that outperforms the baseline on ImageNet classification with 12% fewer FLOPS and 29% fewer parameters. On COCO object detection, a pure self-attention model matches the mAP of a baseline RetinaNet while having 39% fewer FLOPS and 34% fewer parameters. Detailed ablation studies demonstrate that self-attention is especially impactful when used in later layers. These results establish that stand-alone self-attention is an important addition to the vision practitioner's toolbox. # Stand-Alone Self-Attention in Vision Models # Prajit Ramachandran∗ # Niki Parmar∗ # Ashish Vaswani∗ # Irwan Bello # Anselm Levskaya† # Jonathon Shlens Google Research, Brain Team {prajit, nikip, avaswani}@google.com # Abstract Convolutions are a fundamental building block of modern computer vision systems. Recent approaches have argued for going beyond convolutions in order to capture long-range dependencies. These efforts focus on augmenting convolutional models with content-based interactions, such as self-attention and non-local means, to achieve gains on a number of vision tasks. The natural question that arises is whether attention can be a stand-alone primitive for vision models instead of serving as just an augmentation on top of convolutions. In developing and testing a pure self-attention vision model, we verify that self-attention can indeed be an effective stand-alone layer. A simple procedure of replacing all instances of spatial convolutions with a form of self-attention applied to ResNet model produces a fully self-attentional model that outperforms the baseline on ImageNet classification with 12% fewer FLOPS and 29% fewer parameters. On COCO object detection, a pure self-attention model matches the mAP of a baseline RetinaNet while having 39% fewer FLOPS and 34% fewer parameters. Detailed ablation studies demonstrate that self-attention is especially impactful when used in later layers. These results establish that stand-alone self-attention is an important addition to the vision practitioner’s toolbox. # Introduction Digital image processing arose from the recognition that handcrafted linear filters applied convolu- tionally to pixelated imagery may subserve a large variety of applications [1]. The success of digital image processing as well as biological considerations [2, 3] inspired early practitioners of neural networks to exploit convolutional representations in order to provide parameter-efficient architectures for learning representations on images [4, 5]. The advent of large datasets [6] and compute resources [7] made convolution neural networks (CNNs) the backbone for many computer vision applications [8–10]. The field of deep learning has in turn largely shifted toward the design of architectures of CNNs for improving the performance on image recognition [11–16], object detection [17–19] and image segmentation [20–22]. The translation equivariance property of convolutions has provided a strong motivation for adopting them as a building block for operating on images [23, 24]. However, capturing long range interactions for convolutions is challenging because of their poor scaling properties with respect to large receptive fields. ∗Denotes equal contribution. Ordering determined by random shuffle. †Work done as a member of the Google AI Residency Program. Preprint. Under review. The problem of long range interactions has been tackled in sequence modeling through the use of attention. Attention has enjoyed rich success in tasks such as language modeling [25, 26], speech recognition [27, 28] and neural captioning [29]. Recently, attention modules have been employed in discriminative computer vision models to boost the performance of traditional CNNs. Most notably, a channel-based attention mechanism termed Squeeze-Excite may be applied to selectively modulate the scale of CNN channels [30, 31]. Likewise, spatially-aware attention mechanisms have been used to augment CNN architectures to provide contextual information for improving object detection [32] and image classification [33–35]. These works have used global attention layers as an add-on to existing convolutional models. This global form attends to all spatial locations of an input, limiting its usage to small inputs which typically require significant downsampling of the original image. In this work, we ask the question if content-based interactions can serve as the primary primitive of vision models instead of acting as an augmentation to convolution. To this end, we develop a simple local self-attention layer that can be used for both small and large inputs. We leverage this stand-alone attention layer to build a fully attentional vision model that outperforms the convolutional baseline for both image classification and object detection while being parameter and compute efficient. Furthermore, we conduct a number of ablations to better understand stand-alone attention. We hope that this result will spur new research directions focused on exploring content-based interactions as a mechanism for improving vision models. # 2 Background # 2.1 Convolutions Convolutional neural networks (CNNs) are typically employed with small neighborhoods (i.e. kernel sizes) to encourage the network to learn local correlation structures within a particular layer. Given an input x ∈ Rh×w×din with height h, width w, and input channels din, a local neighborhood Nk around a pixel xij is extracted with spatial extent k, resulting in a region with shape k × k × din (see Figure 1). Given a learned weight matrix W ∈ Rk×k×dout×din , the output yij ∈ Rdout for position ij is defined by spatially summing the product of depthwise matrix multiplications of the input values: Yij = Ss Wi-a,j—b Tab (1) a,bEN¢ (4,9) where Nj,(i,j) = {a,b | |a —i| < k/2, |b — j| < k/2} (see Figure 2). Importantly, CNNs employ weight sharing, where W is reused for generating the output for all pixel positions ij. Weight sharing enforces translation equivariance in the learned representation and consequently decouples the parameter count of the convolution from the input size. output learned weights Figure 1: An example of a local window around i = 3, j = 3 (one-indexed) with spatial extent k = 3. Figure 2: An example of a 3 × 3 convolution. The output is the inner product between the local window and the learned weights. A wide array of machine learning applications have leveraged convolutions to achieve competitive results including text-to-speech [36] and generative sequence models [37, 38]. Several efforts have 2 reformulated convolutions to improve the predictive performance or the computational efficiency of a model. Notably, depthwise-separable convolutions provide a low-rank factorization of spatial and channel interactions [39–41]. Such factorizations have allowed for the deployment of modern CNNs on mobile and edge computing devices [42, 43]. Likewise, relaxing translation equivariance has been explored in locally connected networks for various vision applications [44]. # 2.2 Self-Attention Attention was introduced by [45] for the encoder-decoder in a neural sequence transduction model to allow for content-based summarization of information from a variable length source sentence. The ability of attention to learn to focus on important regions within a context has made it a critical component in neural transduction models for several modalities [26, 29, 27]. Using attention as a primary mechanism for representation learning has seen widespread adoption in deep learning after [25], which entirely replaced recurrence with self-attention. Self-attention is defined as attention applied to a single context instead of across multiple contexts (in other words, the query, keys, and values, as defined later in this section, are all extracted from the same context). The ability of self-attention to directly model long-distance interactions and its parallelizability, which leverages the strengths of modern hardware, has led to state-of-the-art models for various tasks [46–51]. An emerging theme of augmenting convolution models with self-attention has yielded gains in several vision tasks. [32] show that self-attention is an instantiation of non-local means [52] and use it to achieve gains in video classification and object detection. [53] also show improvements on image classification and achieve state-of-the-art results on video action recognition tasks with a variant of non-local means. Concurrently, [33] also see significant gains in object detection and image classification through augmenting convolutional features with global self-attention features. This paper goes beyond [33] by removing convolutions and employing local self-attention across the entirety of the network. Another concurrent work [35] explores a similar line of thinking by proposing a new content-based layer to be used across the model. This approach is complementary to our focus on directly leveraging existing forms of self-attention for use across the vision model. We now describe a stand-alone self-attention layer that can be used to replace spatial convolutions and build a fully attentional model. The attention layer is developed with a focus on simplicity by reusing innovations explored in prior works, and we leave it up to future work to develop novel attentional forms. Similar to a convolution, given a pixel xij ∈ Rdin , we first extract a local region of pixels in positions ab ∈ Nk(i, j) with spatial extent k centered around xij, which we call the memory block. This form of local attention differs from prior work exploring attention in vision which have performed global (i.e., all-to-all) attention between all pixels [32, 33]. Global attention can only be used after significant spatial downsampling has been applied to the input because it is computationally expensive, which prevents its usage across all layers in a fully attentional model. Single-headed attention for computing the pixel output yij ∈ Rdout is then computed as follows (see Figure 3): yij = Y. softmaxar (gijkap) Yad Q) abe Nx (i,j) where the queries qij = WQxij, keys kab = WKxab, and values vab = WV xab are linear transforma- tions of the pixel in position ij and the neighborhood pixels. softmaxab denotes a softmax applied to all logits computed in the neighborhood of ij. WQ, WK, WV ∈ Rdout×din are all learned transforms. While local self-attention aggregates spatial information over neighborhoods similar to convolutions (Equation 1), the aggregation is done with a convex combination of value vectors with mixing weights (softmaxab(·)) parametrized by content interactions. This computation is repeated for every pixel ij. In practice, multiple attention heads are used to learn multiple distinct representations of ij ∈ Rdin/N , the input. It works by partitioning the pixel features xij depthwise into N groups xn computing single-headed attention on each group separately as above with different transforms V ∈ Rdout/N ×din/N per head, and then concatenating the output representations into W n the final output yij ∈ Rdout. 3 —_ a: output keys values — matrix multiplication ----- learned transform Figure 3: An example of a local attention layer over spatial extent of k = 3. e[oo] 0: 0.2 4-1] 40 | 44 | 4,2 2,-1| 2,0 | 2,1 | 2,2 Figure 4: An example of relative distance computation. The rela- tive distances are computed with respect to the position of the high- lighted pixel. The format of dis- tances is row offset, column offset. As currently framed, no positional information is encoded in attention, which makes it permutation equivariant, limiting expressivity for vision tasks. Sinusoidal embeddings based on the absolute position of pixels in an image (ij) can be used [25], but early experimentation suggested that using relative positional embeddings [51, 46] results in significantly better accuracies. Instead, attention with 2D relative position embeddings, relative attention, is used. Relative attention starts by defining the relative distance of ij to each position ab ∈ Nk(i, j). The relative distance is factorized across dimensions, so each element ab ∈ Nk(i, j) receives two distances: a row offset a − i and column offset b − j (see Figure 4). The row and column offsets are associated with an embedding ra−i and rb−j respectively each with dimension 1 2 dout. The row and column offset embeddings are concatenated to form ra−i,b−j. This spatial-relative attention is now defined as yij =) softmaxay (q3ykan + gi)Ta—ip—j) Vab (3) a,bE Ny (i,7) Thus, the logit measuring the similarity between the query and an element in Nk(i, j) is modulated both by the content of the element and the relative distance of the element from the query. Note that by infusing relative position information, self-attention also enjoys translation equivariance, similar to convolutions. The parameter count of attention is independent of the size of spatial extent, whereas the parameter count for convolution grows quadratically with spatial extent. The computational cost of attention also grows slower with spatial extent compared to convolution with typical values of din and dout. For example, if din = dout = 128, a convolution layer with k = 3 has the same computational cost as an attention layer with k = 19. # 3 Fully Attentional Vision Models Given a local attention layer as a primitive, the question is how to construct a fully attentional architecture. We achieve this in two steps: # 3.1 Replacing Spatial Convolutions A spatial convolution is defined as a convolution with spatial extent k > 1. This definition excludes 1 × 1 convolutions, which may be viewed as a standard fully connected layer applied to each pixel independently.3 This work explores the straightforward strategy of creating a fully attentional vision model: take an existing convolutional architecture and replace every instance of a spatial convolution with an attention layer. A 2 × 2 average pooling with stride 2 operation follows the attention layer whenever spatial downsampling is required. 3Many deep learning libraries internally translate a 1 × 1 convolution to a simple matrix multiplication. 4 This work applies the transform on the ResNet family of architectures [15]. The core building block of a ResNet is a bottleneck block with a structure of a 1 × 1 down-projection convolution, a 3 × 3 spatial convolution, and a 1 × 1 up-projection convolution, followed by a residual connection between the input of the block and the output of the last convolution in the block. The bottleneck block is repeated multiple times to form the ResNet, with the output of one bottleneck block being the input of the next bottleneck block. The proposed transform swaps the 3 × 3 spatial convolution with a self-attention layer as defined in Equation 3. All other structure, including the number of layers and when spatial downsampling is applied, is preserved. This transformation strategy is simple but possibly suboptimal. Crafting the architecture with attention as a core component, such as with architecture search [54], holds the promise of deriving better architectures. # 3.2 Replacing the Convolutional Stem The initial layers of a CNN, sometimes referred to as the stem, play a critical role in learning local features such as edges, which later layers use to identify global objects. Due to input images being large, the stem typically differs from the core block, focusing on lightweight operations with spatial downsampling [11, 15]. For example, in a ResNet, the stem is a 7 × 7 convolution with stride 2 followed by 3 × 3 max pooling with stride 2. At the stem layer, the content is comprised of RGB pixels that are individually uninformative and heavily spatially correlated. This property makes learning useful features such as edge detectors difficult for content-based mechanisms such as self-attention. Our early experiments verify that using self-attention form described in Equation 3 in the stem underperforms compared to using the convolution stem of ResNet. The distance based weight parametrization of convolutions allows them to easily learn edge dectectors and other local features necessary for higher layers. To bridge the gap between convolutions and self-attention while not significantly increasing computation, we inject distance based information in the pointwise 1 x 1 convolution (W,) through spatially-varying linear transformations. The new value transformation is tq, = (Soin p(a, b,m)W, 1) Cab Where multiple value matrices W//’ are combined through a convex combination of factors that are a function of the position of the pixel in its neighborhood p(a, b,m). The position dependent factors are similar to convolutions, which learn scalar weights dependent on the pixel location in a neighborhood. The stem is then comprised of the attention layer with spatially aware value features followed by max pooling. For simplicity, the attention receptive field aligns with the max pooling window. More details on the exact formulation of p(a, b,m) is given in the appendix. # 4 Experiments # ImageNet Classification Setup We perform experiments on ImageNet classification task [55] which contains 1.28 million training images and 50000 test images. The procedure described in Section 3.1 of replacing the spatial convolution layer with a self-attention layer from inside each bottleneck block of a ResNet-50 [15] model is used to create the attention model. The multi-head self-attention layer uses a spatial extent of k = 7 and 8 attention heads. The position-aware attention stem as described above is used. The stem performs self-attention within each 4 × 4 spatial block of the original image, followed by batch normalization and a 4 × 4 max pool operation. Exact hyperparameters can be found in the appendix. To study the behavior of these models with different computational budgets, we scale the model either by width or depth. For width scaling, the base width is linearly multiplied by a given factor across all layers. For depth scaling, a given number of layers are removed from each layer group. There are 4 layer groups, each with multiple layers operating on the same spatial dimensions. Groups are delineated by spatial downsampling. The 38 and 26 layer models remove 1 and 2 layers respectively from each layer group compared to the 50 layer model. Results Table 1 and Figure 5 shows the results of the full attention variant compared with the convolution baseline. Compared to the ResNet-50 baseline, the full attention variant achieves 0.5% 5 ResNet-26 ResNet-38 ResNet-50 FLOPS (B) Params Acc. (%) (M) FLOPS (B) Params Acc. (%) (M) FLOPS (B) (M) Baseline Conv-stem + Attention Full Attention 4.7 4.5 4.7 13.7 10.3 10.3 74.5 75.8 74.8 6.5 5.7 6.0 19.6 14.1 14.1 76.2 77.1 76.9 8.2 7.0 7.2 25.6 18.0 18.0 Table 1: ImageNet classification results for a ResNet network with different depths. Baseline is a standard ResNet, Conv-stem + Attention uses spatial convolution in the stem and attention everywhere else, and Full Attention uses attention everywhere including the stem. The attention models outperform the baseline across all depths while having 12% fewer FLOPS and 29% fewer parameters. 79- Parameters vs. Accuracy 79- FLOPS vs. Accuracy 78.3 78.3 en in) 18.4075 78.0 ~ o ~ 3 ~ 3 Accuracy (%) Af 3 Accuracy (%) Af 3 ee C-stem Attention Full Attention m4- ee Baseline @-e C-stem Attention @-e Full Attention eve Baseline 1 ' 1 ' ' 735 ' ' 1 . ' 1 ' ' ' ' tt} 10 20 30 40 50 60 tt} 2 4 6 8 10 12 #14 #16 18 20 Parameters (M) FLOPS (B) 79- Parameters vs. Accuracy ~ o ~ 3 Accuracy (%) Af 3 ee C-stem Attention Full Attention ee Baseline 1 ' 1 ' ' tt} 10 20 30 40 50 60 Parameters (M) 79- FLOPS vs. Accuracy 78.3 78.3 en in) 18.4075 78.0 ~ 3 Accuracy (%) Af 3 m4- @-e C-stem Attention @-e Full Attention eve Baseline 735 ' ' 1 . ' 1 ' ' ' ' tt} 2 4 6 8 10 12 #14 #16 18 20 FLOPS (B) Figure 5: Comparing parameters and FLOPS against accuracy on ImageNet classification across a range of network widths for ResNet-50. Attention models have fewer parameters and FLOPS while improving upon the accuracy of the baseline. higher classification accuracy while having 12% fewer floating point operations (FLOPS)4 and 29% fewer parameters. Furthermore, this performance gain is consistent across most model variations generated by both depth and width scaling. # 4.2 COCO Object Detection Setup In this section, we evaluate attention models on the COCO object detection task [56] using the RetinaNet architecture [18]. RetinaNet is an object detection model that consists of a backbone image classification network followed by a Feature Pyramid Network (FPN) [57] and two output networks known as detection heads. We experiment with making the backbone and/or the FPN and detection heads fully attentional. The backbone models are the same models described in Section 4.1. The details of how the FPN and detection heads are made fully attentional are provided in the appendix. Results Table 2 shows the object detection results. Using an attention-based backbone in the RetinaNet matches the mAP of using the convolutional backbone but contains 22% fewer parameters. Furthermore, employing attention across all parts of the model including the backbone, FPN, and detection heads matches the mAP of the baseline RetinaNet while using 34% fewer parameters and 39% fewer FLOPS. These results demonstrate the efficacy of stand-alone attention across multiple vision tasks. 6 Detection Heads + FPN Backbone FLOPS (B) Params (M) mAPcoco / 50 / 75 mAPs / m / l Convolution Baseline Conv-stem + Attention Full Attention 182 173 173 33.4 25.9 25.9 36.5 / 54.3 / 39.0 36.8 / 54.6 / 39.3 36.2 / 54.0 / 38.7 18.3 / 40.6 / 51.7 18.4 / 41.1 / 51.7 17.5 / 40.3 / 51.7 Attention Conv-stem + Attention Full Attention 111 110 22.0 22.0 36.6 / 54.3 / 39.1 36.6 / 54.5 / 39.2 19.0 / 40.7 / 51.1 18.5 / 40.6 / 51.6 Table 2: Object detection on COCO dataset with RetinaNet [18]. Mean Average Precision (mAP) is reported at three different IoU values and for three different object sizes (small, medium, large). The fully attentional models achieve similar mAP as the baseline while having up to 39% fewer FLOPS and 34% fewer parameters. Conv Groups Attention Groups FLOPS (B) Params (M) Top-1 Acc. (%) - 1 1, 2 1, 2, 3 1, 2, 3, 4 2, 3, 4 3, 4 4 1, 2, 3, 4 2, 3, 4 3, 4 4 - 1 1, 2 1, 2, 3 7.0 7.3 7.5 8.0 8.2 7.9 7.8 7.2 18.0 18.1 18.5 20.8 25.6 25.5 25.0 22.7 80.2 80.7 80.7 80.2 79.5 79.7 79.6 79.9 Table 3: Modifying which layer groups use which primitive. Accuracies computed on validation set. The best performing models use convolutions for early groups and attention for later groups. FLOPS (B) Top-1 Acc. (%) 3 × 3 5 × 5 7 × 7 9 × 9 11 × 11 6.6 6.7 7.0 7.3 7.7 76.4 77.2 77.4 77.7 77.6 Spatial Extent (k × k) Table 4: Varying the spatial extent k. Param- eter count is constant across all variations. Small k perform poorly, but the improve- ments of larger k plateaus off. # 4.3 Where is stand-alone attention most useful? The impressive performance of fully attentional models verifies that stand-alone attention is a viable primitive for vision models. In this section, we study which parts of the network benefit the most from stand-alone attention. Stem First, we compare the performance of the attention stem against the convolution stem used in ResNet. All other spatial convolutions are replaced with stand-alone attention. Tables 1 and 2 and Figure 5 show the results on ImageNet classification and COCO object detection. For classification, the convolution stem consistently matches or outperforms the attention stem. For object detection, the convolution stem performs better when a the detection heads and FPN are also convolutional, but performs similarly when the entire rest of the network is fully attentional. These results suggest that convolutions consistently perform well when used in the stem. Full network Next, we experiment with using convolution and stand-alone attention in different layer groups in a ResNet with a convolution stem. Table 3 shows that the best performing models use convolutions in the early groups and attention in the later groups. These models are also similar in terms of FLOPS and parameters to the fully attentional model. In contrast, when attention is used in the early groups and convolutions are used in the later groups, the performance degrades despite a large increase in the parameter count. This suggests that convolutions may better capture low level features while stand-alone attention layers may better integrate global information. Taken together, these results suggest that vision practitioners should focus on developing strategies of designing architectures that combine the comparative advantages of convolution and stand-alone attention. 4Some prior works define a FLOP as a single atomic Multiply-Add, whereas we treat the Multiply and Add as 2 FLOPS. This causes a 2× discrepancy in the reported number. 7 Positional Encoding Type FLOPS (B) Params (M) Top-1 Acc. (%) none absolute relative 6.9 6.9 7.0 18.0 18.0 18.0 77.6 78.2 80.2 Attention FLOPS Params Top-1 type BM) Ace. (%) qir 6.1 16.7 76.9 qik+q'r 7.0 18.0 714 Table 5: The effect of changing the positional en- coding type for attention. Accuracies computed on the validation set. Relative encodings signifi- cantly outperform other strategies. Table 6: The effect of removing the q'k inter- actions in attention. Using just q'r interactions only drops accuracy by 0.5%. Attention Stem Type FLOPS (B) Top-1 Acc. (%) stand-alone spatial convolution for values spatially aware values 7.1 7.4 7.2 76.2 77.2 77.6 Table 7: Ablating the form of the attention stem. Spatially-aware value attention outperforms both stand-alone attention and values generated by a spatial convolution. # 4.4 Which components are important in attention? This section presents ablations designed to understand the contributions of the various components in the local attention layer. Unless specified, all attention models in the ablations use the convolution stem. # 4.4.1 Effect of spatial extent of self-attention The value of the spatial extent k controls the size of the region each pixel can attend to. Table 4 studies the effect of varying the spatial extent. While using small k, such as k = 3, has a large negative impact on performance, the improvements of using a larger k plateau around k = 11. The exact plateau value likely depends on specific settings of hyperparameters such as the feature size and number of attention heads used. # 4.4.2 Importance of positional information Table 5 ablates the different types of positional encodings that can be used: no positional encoding, a sinusodial encoding dependent on the absolute position of a pixel [25], and relative position encodings. Using any notion of positional encoding is beneficial over using none, but the type of positional encoding is also important. Relative position encodings perform 2% better than absolute encodings. Furthermore, Table 6 demonstrates the important role of the content-relative interactions (q · r) in attention. Removing the content-content (q · k) interactions and just using the content-relative interactions drops the accuracy by only 0.5%. The importance of positional information suggests that future work may improve attention by exploring different parameterizations and usages of positional information. # 4.4.3 Importance of spatially-aware attention stem Table 7 compares using stand-alone attention in the stem with the attention stem with spatially-aware values proposed in Section 3.2. The proposed attention stem outperforms stand-alone attention by 1.4% despite having a similar number of FLOPS, validating the utility of modifying attention for use in the stem. Furthermore, applying a spatial convolution to the values instead of a spatially-aware mixture of point-wise transformations proposed in Section 3.2 incurs more FLOPS and performs slightly worse. Future work can focus on unifying the spatially-aware attention used in the stem with the attention used in the main trunk of the network. 8 # 5 Discussion In this work, we verified that content-based interactions can indeed serve as the primary primitive of vision models. A fully attentional network based off of the proposed stand-alone local self-attention layer achieves competitive predictive performance on ImageNet classification and COCO object detection tasks while requiring fewer parameters and floating point operations than the corresponding convolution baselines. Furthermore, ablations show that attention is especially effective in the later parts of the network. We see several opportunities for improving the performance of these networks. First, the attention mechanism may be improved by developing better methods for capturing geometries [58, 59]. Second, the architectures employed for image classification and object detection were developed by applying a simple transformation to models designed for the convolutional primitive [13, 19]. It may be possible to achieve improvements by specifically searching for the architecture with an attention layer as a component in the design search space [31, 16, 21, 60]. Finally, additional work on proposing new attention forms that can capture low level features can make attention effective in the early layers of networks [61, 62]. Although the training efficiency and computational demand of an attention based architecture is favorable to a traditional convolution, the resulting network is slower in wall-clock time. The reason for this discrepancy is the lack of optimized kernels available on various hardware accelerators. In principle, depending on the degree to which the field deems that attention provides a viable path, it may be possible to significantly speed up the wall-clock time for training and inference accordingly. While this work primarily focuses on content-based interactions to establish their virtue for vision tasks, in the future, we hope to unify convolution and self-attention to best combine their unique advantages. Given the success of content-based interactions on core computer vision tasks, we expect that future work may explore how attention could be applied to other vision tasks such as semantic segmentation [63], instance segmentation [64], keypoint detection [65], human pose estimation [66, 67] and other tasks currently addressed with convolutional neural networks. # Acknowledgments We thank Blake Hechtman, Justin Gilmer, Pieter-jan Kindermans, Quoc Le, Samy Bengio, and Shibo Wang for fruitful discussions and assistance with implementations as well as the larger Google Brain team for support and assistance. # References [1] R. C. Gonzalez, R. E. Woods, et al., “Digital image processing [m],” Publishing house of electronics industry, vol. 141, no. 7, 2002. [2] K. Fukushima, “Neocognitron: A self-organizing neural network model for a mechanism of pattern recognition unaffected by shift in position,” Biological cybernetics, vol. 36, no. 4, pp. 193–202, 1980. [3] K. Fukushima, “Neocognitron: A hierarchical neural network capable of visual pattern recogni- tion,” Neural networks, vol. 1, no. 2, pp. 119–130, 1988. [4] Y. LeCun, B. Boser, J. S. Denker, D. Henderson, R. E. Howard, W. Hubbard, and L. D. Jackel, “Backpropagation applied to handwritten zip code recognition,” Neural computation, vol. 1, no. 4, pp. 541–551, 1989. [5] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner, “Gradient-based learning applied to document recognition,” Proceedings of the IEEE, 1998. [6] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, and L. Fei-Fei, “Imagenet: A large-scale hierarchical image database,” in IEEE Conference on Computer Vision and Pattern Recognition, IEEE, 2009. [7] J. Nickolls and W. J. Dally, “The gpu computing era,” IEEE micro, vol. 30, no. 2, pp. 56–69, 2010. 9 [8] A. Krizhevsky, “Learning multiple layers of features from tiny images,” tech. rep., University of Toronto, 2009. [9] A. Krizhevsky, I. Sutskever, and G. E. Hinton, “Imagenet classification with deep convolutional neural networks,” in Advances in Neural Information Processing System, 2012. [10] Y. LeCun, Y. Bengio, and G. Hinton, “Deep learning,” nature, vol. 521, no. 7553, p. 436, 2015. [11] C. Szegedy, W. Liu, Y. Jia, P. Sermanet, S. Reed, D. Anguelov, D. Erhan, V. Vanhoucke, and A. Rabinovich, “Going deeper with convolutions,” in IEEE Conference on Computer Vision and Pattern Recognition, 2015. [12] C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, and Z. Wojna, “Rethinking the Inception architec- ture for computer vision,” in IEEE Conference on Computer Vision and Pattern Recognition, 2016. [13] K. He, X. Zhang, S. Ren, and J. Sun, “Identity mappings in deep residual networks,” in European Conference on Computer Vision, 2016. [14] S. Xie, R. Girshick, P. Dollár, Z. Tu, and K. He, “Aggregated residual transformations for deep neural networks,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2017. [15] K. He, X. Zhang, S. Ren, and J. Sun, “Deep residual learning for image recognition,” in IEEE Conference on Computer Vision and Pattern Recognition, 2016. [16] B. Zoph, V. Vasudevan, J. Shlens, and Q. V. Le, “Learning transferable architectures for scalable image recognition,” in Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 8697–8710, 2018. [17] T.-Y. Lin, P. Dollár, R. Girshick, K. He, B. Hariharan, and S. Belongie, “Feature pyramid networks for object detection,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2017. [18] T.-Y. Lin, P. Goyal, R. Girshick, K. He, and P. Dollár, “Focal loss for dense object detection,” in Proceedings of the IEEE international conference on computer vision, pp. 2980–2988, 2017. [19] S. Ren, K. He, R. Girshick, and J. Sun, “Faster R-CNN: Towards real-time object detection with region proposal networks,” in Advances in Neural Information Processing Systems, pp. 91–99, 2015. [20] L.-C. Chen, G. Papandreou, I. Kokkinos, K. Murphy, and A. L. Yuille, “Deeplab: Semantic image segmentation with deep convolutional nets, atrous convolution, and fully connected crfs,” IEEE transactions on pattern analysis and machine intelligence, vol. 40, no. 4, pp. 834–848, 2018. [21] L.-C. Chen, M. Collins, Y. Zhu, G. Papandreou, B. Zoph, F. Schroff, H. Adam, and J. Shlens, “Searching for efficient multi-scale architectures for dense image prediction,” in Advances in Neural Information Processing Systems, pp. 8713–8724, 2018. [22] K. He, G. Gkioxari, P. Dollár, and R. Girshick, “Mask r-cnn,” in Proceedings of the IEEE international conference on computer vision, pp. 2961–2969, 2017. [23] E. P. Simoncelli and B. A. Olshausen, “Natural image statistics and neural representation,” Annual review of neuroscience, vol. 24, no. 1, pp. 1193–1216, 2001. [24] D. L. Ruderman and W. Bialek, “Statistics of natural images: Scaling in the woods,” in Advances in neural information processing systems, pp. 551–558, 1994. [25] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, “Attention is all you need,” in Advances in Neural Information Processing Systems, pp. 5998–6008, 2017. 10 [26] Y. Wu, M. Schuster, Z. Chen, Q. V. Le, M. Norouzi, W. Macherey, M. Krikun, Y. Cao, Q. Gao, K. Macherey, et al., “Google’s neural machine translation system: Bridging the gap between human and machine translation,” arXiv preprint arXiv:1609.08144, 2016. [27] J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Bengio, “Attention-based models for speech recognition,” in Advances in neural information processing systems, pp. 577–585, 2015. [28] W. Chan, N. Jaitly, Q. Le, and O. Vinyals, “Listen, attend and spell: A neural network for large vocabulary conversational speech recognition,” in 2016 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), pp. 4960–4964, IEEE, 2016. [29] K. Xu, J. Ba, R. Kiros, K. Cho, A. Courville, R. Salakhudinov, R. Zemel, and Y. Bengio, “Show, attend and tell: Neural image caption generation with visual attention,” in International conference on machine learning, pp. 2048–2057, 2015. [30] J. Hu, L. Shen, and G. Sun, “Squeeze-and-excitation networks,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2018. [31] M. Tan, B. Chen, R. Pang, V. Vasudevan, and Q. V. Le, “Mnasnet: Platform-aware neural architecture search for mobile,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2018. [32] X. Wang, R. Girshick, A. Gupta, and K. He, “Non-local neural networks,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 7794–7803, 2018. [33] I. Bello, B. Zoph, A. Vaswani, J. Shlens, and Q. V. Le, “Attention augmented convolutional networks,” CoRR, vol. abs/1904.09925, 2019. [34] J. Hu, L. Shen, S. Albanie, G. Sun, and A. Vedaldi, “Gather-excite: Exploiting feature context in convolutional neural networks,” in Advances in Neural Information Processing Systems, pp. 9423–9433, 2018. [35] H. Hu, Z. Zhang, Z. Xie, and S. Lin, “Local relation networks for image recognition,” arXiv preprint arXiv:1904.11491, 2019. [36] A. v. d. Oord, S. Dieleman, H. Zen, K. Simonyan, O. Vinyals, A. Graves, N. Kalchbrenner, A. Senior, and K. Kavukcuoglu, “Wavenet: A generative model for raw audio,” arXiv preprint arXiv:1609.03499, 2016. [37] T. Salimans, A. Karpathy, X. Chen, and D. P. Kingma, “PixelCNN++: Improving the Pix- elCNN with discretized logistic mixture likelihood and other modifications,” arXiv preprint arXiv:1701.05517, 2017. [38] J. Gehring, M. Auli, D. Grangier, D. Yarats, and Y. N. Dauphin, “Convolutional sequence to sequence learning,” CoRR, vol. abs/1705.03122, 2017. [39] L. Sifre and S. Mallat, “Rigid-motion scattering for image classification,” PhD thesis, Ph. D. thesis, vol. 1, p. 3, 2014. [40] S. Ioffe and C. Szegedy, “Batch normalization: Accelerating deep network training by reducing internal covariate shift,” in International Conference on Learning Representations, 2015. [41] F. Chollet, “Xception: Deep learning with depthwise separable convolutions,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2017. [42] A. G. Howard, M. Zhu, B. Chen, D. Kalenichenko, W. Wang, T. Weyand, M. Andreetto, and H. Adam, “Mobilenets: Efficient convolutional neural networks for mobile vision applications,” arXiv preprint arXiv:1704.04861, 2017. [43] M. Sandler, A. Howard, M. Zhu, A. Zhmoginov, and L.-C. Chen, “Mobilenetv2: Inverted residuals and linear bottlenecks,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 4510–4520, 2018. 11 [44] S. Bartunov, A. Santoro, B. Richards, L. Marris, G. E. Hinton, and T. Lillicrap, “Assessing the scalability of biologically-motivated deep learning algorithms and architectures,” in Advances in Neural Information Processing Systems, pp. 9368–9378, 2018. [45] D. Bahdanau, K. Cho, and Y. Bengio, “Neural machine translation by jointly learning to align and translate,” in International Conference on Learning Representations, 2015. [46] C.-Z. A. Huang, A. Vaswani, J. Uszkoreit, N. Shazeer, C. Hawthorne, A. M. Dai, M. D. Hoffman, and D. Eck, “Music transformer,” in Advances in Neural Processing Systems, 2018. [47] A. Radford, J. Wu, R. Child, D. Luan, D. Amodei, and I. Sutskever, “Language models are unsupervised multitask learners,” OpenAI Blog, vol. 1, p. 8, 2019. [48] J. Devlin, M. Chang, K. Lee, and K. Toutanova, “BERT: pre-training of deep bidirectional transformers for language understanding,” CoRR, vol. abs/1810.04805, 2018. [49] N. Parmar, A. Vaswani, J. Uszkoreit, Ł. Kaiser, N. Shazeer, A. Ku, and D. Tran, “Image transformer,” in International Conference on Machine Learning, 2018. [50] N. Shazeer, Y. Cheng, N. Parmar, D. Tran, A. Vaswani, P. Koanantakool, P. Hawkins, H. Lee, M. Hong, C. Young, R. Sepassi, and B. A. Hechtman, “Mesh-tensorflow: Deep learning for supercomputers,” CoRR, vol. abs/1811.02084, 2018. [51] P. Shaw, J. Uszkoreit, and A. Vaswani, “Self-attention with relative position representations,” arXiv preprint arXiv:1803.02155, 2018. [52] A. Buades, B. Coll, and J.-M. Morel, “A non-local algorithm for image denoising,” in Pro- ceedings of the 2005 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR’05) - Volume 2 - Volume 02, CVPR ’05, (Washington, DC, USA), pp. 60–65, IEEE Computer Society, 2005. [53] Y. Chen, Y. Kalantidis, J. Li, S. Yan, and J. Feng, “Aˆ 2-nets: Double attention networks,” in Advances in Neural Information Processing Systems, pp. 352–361, 2018. [54] B. Zoph and Q. V. Le, “Neural architecture search with reinforcement learning,” in International Conference on Learning Representations, 2017. [55] O. Russakovsky, J. Deng, H. Su, J. Krause, S. Satheesh, S. Ma, Z. Huang, A. Karpathy, A. Khosla, M. S. Bernstein, A. C. Berg, and F. Li, “Imagenet large scale visual recognition challenge,” CoRR, vol. abs/1409.0575, 2014. [56] T.-Y. Lin, M. Maire, S. Belongie, J. Hays, P. Perona, D. Ramanan, P. Dollár, and C. L. Zitnick, “Microsoft coco: Common objects in context,” in European Conference on Computer Vision, pp. 740–755, Springer, 2014. [57] T.-Y. Lin, P. Dollár, R. Girshick, K. He, B. Hariharan, and S. Belongie, “Feature pyramid networks for object detection,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 2117–2125, 2017. [58] T. S. Cohen, M. Geiger, J. Köhler, and M. Welling, “Spherical cnns,” arXiv preprint arXiv:1801.10130, 2018. [59] T. S. Cohen, M. Weiler, B. Kicanaoglu, and M. Welling, “Gauge equivariant convolutional networks and the icosahedral cnn,” arXiv preprint arXiv:1902.04615, 2019. [60] G. Ghiasi, T.-Y. Lin, R. Pang, and Q. V. Le, “Nas-fpn: Learning scalable feature pyramid architecture for object detection,” arXiv preprint arXiv:1904.07392, 2019. [61] F. Wu, A. Fan, A. Baevski, Y. N. Dauphin, and M. Auli, “Pay less attention with lightweight and dynamic convolutions,” arXiv preprint arXiv:1901.10430, 2019. [62] X. Zhu, D. Cheng, Z. Zhang, S. Lin, and J. Dai, “An empirical study of spatial attention mechanisms in deep networks,” arXiv preprint arXiv:1904.05873, 2019. 12 [63] L.-C. Chen, G. Papandreou, I. Kokkinos, K. Murphy, and A. L. Yuille, “Deeplab: Semantic image segmentation with deep convolutional nets, atrous convolution, and fully connected crfs,” IEEE transactions on pattern analysis and machine intelligence, vol. 40, no. 4, pp. 834–848, 2017. [64] L.-C. Chen, A. Hermans, G. Papandreou, F. Schroff, P. Wang, and H. Adam, “Masklab: Instance segmentation by refining object detection with semantic and direction features,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 4013–4022, 2018. [65] D. DeTone, T. Malisiewicz, and A. Rabinovich, “Superpoint: Self-supervised interest point detection and description,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition Workshops, pp. 224–236, 2018. [66] A. Toshev and C. Szegedy, “Deeppose: Human pose estimation via deep neural networks,” in Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 1653–1660, 2014. [67] A. Newell, K. Yang, and J. Deng, “Stacked hourglass networks for human pose estimation,” in European Conference on Computer Vision, pp. 483–499, Springer, 2016. [68] Y. E. NESTEROV, “A method for solving the convex programming problem with convergence rate o(1/k2),” Dokl. Akad. Nauk SSSR, vol. 269, pp. 543–547, 1983. [69] I. Sutskever, J. Martens, G. Dahl, and G. Hinton, “On the importance of initialization and momentum in deep learning,” in International Conference on Machine Learning, 2013. [70] I. Loshchilov and F. Hutter, “SGDR: Stochastic gradient descent with warm restarts,” arXiv preprint arXiv:1608.03983, 2016. [71] N. P. Jouppi, C. Young, N. Patil, D. Patterson, G. Agrawal, R. Bajwa, S. Bates, S. Bhatia, N. Boden, A. Borchers, R. Boyle, P.-l. Cantin, C. Chao, C. Clark, J. Coriell, M. Daley, M. Dau, J. Dean, B. Gelb, T. V. Ghaemmaghami, R. Gottipati, W. Gulland, R. Hagmann, C. R. Ho, D. Hogberg, J. Hu, R. Hundt, D. Hurt, J. Ibarz, A. Jaffey, A. Jaworski, A. Kaplan, H. Khaitan, D. Killebrew, A. Koch, N. Kumar, S. Lacy, J. Laudon, J. Law, D. Le, C. Leary, Z. Liu, K. Lucke, A. Lundin, G. MacKean, A. Maggiore, M. Mahony, K. Miller, R. Nagarajan, R. Narayanaswami, R. Ni, K. Nix, T. Norrie, M. Omernick, N. Penukonda, A. Phelps, J. Ross, M. Ross, A. Salek, E. Samadiani, C. Severn, G. Sizikov, M. Snelham, J. Souter, D. Steinberg, A. Swing, M. Tan, G. Thorson, B. Tian, H. Toma, E. Tuttle, V. Vasudevan, R. Walter, W. Wang, E. Wilcox, and D. H. Yoon, “In-datacenter performance analysis of a tensor processing unit,” SIGARCH Comput. Archit. News, vol. 45, pp. 1–12, June 2017. [72] B. Polyak and A. Juditsky, “Acceleration of stochastic approximation by averaging,” SIAM Journal on Control and Optimization, vol. 30, no. 4, pp. 838–855, 1992. [73] C. Szegedy, W. Liu, Y. Jia, P. Sermanet, S. Reed, D. Anguelov, D. Erhan, V. Vanhoucke, and A. Rabinovich, “Going deeper with convolutions,” in Computer Vision and Pattern Recognition (CVPR), 2015. 13 # A Appendix # A.1 Attention Stem In this section, we first describe the standard self-attention layer followed by the spatially-aware mixtures in the attention stem. For an input with xij ∈ Rdin we define a standard single-headed self-attention layer as Gij = WQrij (4) # qij = WQxij kij = WKxij vij = WV xij ki = Wrvij (5) vig = Wy rig (6) yij =) softmaxay (qi) kab) vav (7) a,be Nx (3,9) where Wo,Wk,Wv € RtimXdout and the neighborhood =A. (i, /) = {a,b | |a—i] < k/2,|b— j| <k/2} yielding the intermediate per-pixel queries, keys, and values qi;, kij, Vij € R¢™* and the final output y;; € Rv. The attention stem replaces the pointwise values v;; by spatially-aware linear transformations. For simplicity, we align the query, key and value receptive field with the max-pooling receptive field of 4 x 4. Then to inject distance aware value features, we use a convex combination of multiple value matrices Wy’ where the combination weights are a function of the absolute position of the value in the pooling window. The functional form is defined in Equation 9 which computes the logit between the absolute embedding and the mixture embedding v”’. Vab = (= pa, b, mire) Lab (8) p(a,b,m) = softmax ((embyow(a) + embeor(b)) Vv”) (9) Where embrow(a) and embcol(b) are pooling-window aligned row and column embeddings and νm is a per-mixture embedding. The resulting pm ab are shared across the 4 attention heads for the mixture stem layer. # ImageNet Training Details For tuning, a validation set containing a 4% random subset of the training set is used. Training is performed for 130 epochs using Nesterov’s Accelerated Gradient [68, 69] with a learning rate of 1.6 which is linearly warmed up for 10 epochs followed by cosine decay [70]. A total batch size of 4096 is spread across 128 Cloud TPUv3 cores [71]. The setup uses batch normalization [40] with decay 0.9999 and exponential moving average with weight 0.9999 over trainable parameters [72, 73]. # A.3 Object Detection Training Details The fully attentional object detection architecture uses the fully attentional classification models detailed in Section 4.1 as its backbone network. The rest of the architecture is obtained by replacing the 3 × 3 convolutions in the original RetinaNet architecture with self-attention layers of the same width (dout = 256). We additionally apply 2 × 2 average pooling with stride 2 when replacing a strided convolution. The classification and regression heads share weights across all levels and their WV matrices are initialized randomly from a normal distribution with standard deviation 0.01 as in the original RetinaNet architecture [18]. Finally, we add an extra pointwise convolution at the end of the classification and box regression heads to mix the attentional heads. All self-attention layers use a spatial extent of k = 7 and 8 heads as for the image classification experiments. We follow a similar training setup as in [18, 33]. All networks are trained for 150 epochs with a batch size of 64. The learning rate is warmed up linearly from 0 to 0.12 for one epoch and then decayed 14 (4) (5) (6) using a cosine schedule. We apply multiscale jitter, crop to a max dimension of 640 during training and randomly flip images horizontally with 50% probability. 15
Title: A Comprehensive Survey on Pretrained Foundation Models: A History from BERT to ChatGPT: Summary: Pretrained Foundation Models (PFMs) are regarded as the foundation for various downstream tasks with different data modalities. A PFM (e.g., BERT, ChatGPT, and GPT-4) is trained on large-scale data which provides a reasonable parameter initialization for a wide range of downstream applications. BERT learns bidirectional encoder representations from Transformers, which are trained on large datasets as contextual language models. Similarly, the generative pretrained transformer (GPT) method employs Transformers as the feature extractor and is trained using an autoregressive paradigm on large datasets. Recently, ChatGPT shows promising success on large language models, which applies an autoregressive language model with zero shot or few shot prompting. The remarkable achievements of PFM have brought significant breakthroughs to various fields of AI. Numerous studies have proposed different methods, raising the demand for an updated survey. This study provides a comprehensive review of recent research advancements, challenges, and opportunities for PFMs in text, image, graph, as well as other data modalities. The review covers the basic components and existing pretraining methods used in natural language processing, computer vision, and graph learning. Additionally, it explores advanced PFMs used for different data modalities and unified PFMs that consider data quality and quantity. The review also discusses research related to the fundamentals of PFMs, such as model efficiency and compression, security, and privacy. Finally, the study provides key implications, future research directions, challenges, and open problems in the field of PFMs. Overall, this survey aims to shed light on the research of the PFMs on scalability, security, logical reasoning ability, cross-domain learning ability, and the user-friendly interactive ability for artificial general intelligence. # A Comprehensive Survey on Pretrained Foundation Models: A History from BERT to ChatGPT Ce Zhou1* Kai Zhang3 Qian Li2∗ Cheng Ji2 Chen Li2∗ Qiben Yan1 Jun Yu3∗ Yixin Liu3∗ Guangjing Wang1 Jianxin Li2 Lifang He3 Hao Peng2 Jia Wu4 Ziwei Liu5 Pengtao Xie6 Caiming Xiong7 Jian Pei8 Philip S. Yu9 Lichao Sun3 1Michigan State University, 2Beihang University, 3Lehigh University, 4Macquarie University, 5Nanyang Technological University, 6University of California San Diego, 7Salesforce AI Research,8Duke University, 9University of Illinois at Chicago # Abstract Pretrained Foundation Models (PFMs) are regarded as the foundation for various downstream tasks with different data modalities. A PFM (e.g., BERT, ChatGPT, and GPT-4) is trained on large-scale data which provides a reasonable parameter initialization for a wide range of downstream applications. In contrast to earlier approaches that utilize convolution and recurrent modules to extract features, BERT learns bidirectional encoder representations from Transformers, which are trained on large datasets as contextual language models. Similarly, the Generative Pretrained Transformer (GPT) method employs Transformers as the feature extractor and is trained using an autoregressive paradigm on large datasets. Recently, ChatGPT shows promising success on large language models, which applies an autoregres- sive language model with zero shot or few shot prompting. The remarkable achievements of PFM have brought significant breakthroughs to various fields of AI in recent years. Numerous studies have pro- posed different methods, datasets, and evaluation metrics, raising the demand for an updated survey. This study provides a comprehensive review of recent research advancements, challenges, and op- portunities for PFMs in text, image, graph, as well as other data modalities. The review covers the basic components and existing pretraining methods used in natural language processing, computer vi- sion, and graph learning. Additionally, it explores advanced PFMs used for different data modalities and unified PFMs that consider data quality and quantity. The review also discusses research related to the fundamentals of PFMs, such as model efficiency and compression, security, and privacy. Finally, the study provides key implications, future research directions, challenges, and open problems in the field of PFMs. Overall, this survey aims to shed light on the research of the PFMs on scalability, security, logi- cal reasoning ability, cross-domain learning ability, and the user-friendly interactive ability for artificial general intelligence. *The authors contributed equally to this research. Correspondence to Ce Zhou(zhouce@msu.edu) and Qian Li (liqian@ act.buaa.edu.cn). 1 # Contents # 1 Introduction . 1.1 PFMs and Pretraining . 1.2 Contribution and Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1 Transformer for PFMs . 2.2 Learning Mechanisms for PFMs . 2.3 Pretraining Tasks for PFMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pretraining Tasks for NLP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pretraining Tasks for CV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pretraining Tasks for GL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3.1 2.3.2 2.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Instruction-Aligning Methods . . . . . . . . . . . . . . 4.1 Learning by Specific Pretext Task . 4.2 Learning by Frame Order . . . . 4.3 Learning by Generation . 4.4 Learning by Reconstruction . 4.5 Learning by Memory Bank . . 4.6 Learning by Sharing . . . 4.7 Learning by Clustering . . . 4.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1 Learning by Graph Information Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 Learning by Graph Consistency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.3 Learning by Graph Property Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.4 Learning by Masked Autoencoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.5 Other Learning Strategies on Graph Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.6 Summary . . . . . . . . . . . . . 6.1 PFMs for Speech . . . . . 6.2 PFMs for Video . 6.3 PFMs for Multimodal . . 6.4 PFM for Code Generation . . 6.5 SOTA Unified PFMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.1 Model Efficiency . . 7.2 Model Compression . . 7.3 Security and Privacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4 5 6 6 7 8 9 9 10 10 11 13 13 14 16 18 18 19 20 21 21 22 23 25 26 27 27 28 30 31 31 31 32 33 33 34 35 35 37 37 38 38 # 2 Basic Components 3 PFMs for Natural Language Processing 3.1 Word Representations Methods . . 3.2 Model Architecture Designing Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Masking Designing Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.4 Boosting Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.6 Summary . # 4 PFMs for Computer Vision # 5 PFMs for Graph Learning # 6 PFMs for Other Data Modality . . . # 7 Other Advanced Topics on PFMs . . . 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.1 Challenges on Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 Challenges on Foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 Challenges on Model Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.4 Challenges on Finetuning and Prompt 8.5 Open Problems for Future PFMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.1 Basic Components on NLP . . A.1.1 Language Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.2.1 Notations and Definitions of Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.2.2 Learning Settings on Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A.2 Basic Components on GL . . . B.2.1 Convolution-Based Networks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.2.2 Recurrent neural networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.2.3 Generation-Based Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.2.4 Attention-Based Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.2.5 Transformer-Based Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B.3 Traditional Graph Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C.1 Different Perspectives . . C.2 Different Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . G.1 Downstream Tasks and Datasets on NLP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . G.2 Downstream Tasks and Datasets on CV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . G.3 Downstream Tasks and Datasets on Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 40 40 41 41 42 42 43 43 43 44 45 45 47 47 47 48 48 48 49 49 49 51 51 51 52 53 54 57 57 62 66 # 8 Future Research Challenges and Open Problems # 9 Conclusion # A Basic Components B Traditional Learning Methods . B.1 Traditional Text Learning . B.2 Traditional Image Learning . # C PFMs Theory # D Pretext Task Taxonomy on CV # E PFMs for Reinforcement Learning # F Evaluation Metrics # G Datasets 3 # 1 Introduction Pretrained Foundation Models (PFMs) are regarded as essential and significant components of Artificial Intelligence (AI) in the era of big data. The foundation model is first named in [1], which means a broader class of models and their functions. PFMs are extensively studied in the three major AI fields: natural language processing (NLP) [2], computer vision (CV) [3] and graph learning (GL) [4]. PFMs are powerful general models that are effective in various fields or across fields. They have demonstrated great potential in learning feature representations in various learning tasks, such as text classification [5], text generation [6], image classification [7], object detection [8], and graph classification [9]. PFMs show superior performance for training on multiple tasks with large-scale corpus and fine-tuning it to similar small-scale tasks, making it possible to initiate rapid data processing. # 1.1 PFMs and Pretraining PFMs are built upon the pretraining technique, which aims to train a general model using large amounts of data and tasks that can be fine-tuned easily in different downstream applications. The idea of pretraining originates from transfer learning [10] in CV tasks. Recognizing the effectiveness of pretraining in the field of CV, people have begun to use pretraining technology to enhance model performance in other areas. When pretraining techniques are applied to the NLP domain, well-trained language models (LMs) can capture rich knowledge beneficial for downstream tasks, such as long-term dependencies, hierarchical relationships, etc. In addition, the significant advantage of pretraining in the NLP field is that training data can be derived from any unlabeled text corpus, that is, there is an unlimited amount of training data in the pretraining process. Early pretraining is a static technique, such as NNLM [11] and Word2vec [12], but static methods were difficult to adapt to different semantic environments. Therefore, dynamic pretraining techniques are proposed, such as BERT [13], XLNet [14], etc. Fig. 1 depicts the history and evolution of PFMs in the NLP, CV, and GL domains. The PFMs based on the pretraining technique use large corpora to learn generic semantic representations. With the introduction of these pioneering works, various PFMs have emerged and been applied to downstream tasks and applications. A great example of PFM application is ChatGPT1. ChatGPT is fine-tuned from the generative pretrained transformer GPT-3.5, which was trained on a blend of text and code [15, 16]. ChatGPT applies reinforce- ment learning from human feedback (RLHF) [17, 18], which has become a promising way to align large language models (LLMs) with a human’s intent [19]. The surprisingly superior performance of ChatGPT may lead to a tipping point for a shift of training paradigm for each type of PFMs – applying instruction aligning techniques, e.g., reinforcement learning (RL), prompt tuning [20, 21, 22], and chain-of-thought (COT) [23, 24], to move towards artificial general intelligence. We focus on reviewing PFMs for text, image, and graph, which is a relatively mature research taxonomy. For text, it is a multi-purpose LM to predict the next word or character in a sequence. For example, PFMs can be used for machine translation, question-answering systems, topic modeling, sentiment analysis, etc. For image, it is similar to PFMs on text, which uses huge datasets to train a big model suitable for many CV tasks. For graphs, a similar pretraining idea is also applied to obtain PFMs, which are used for many downstream tasks. Apart from the PFMs for a specific data domain, we also review and state some other advanced PFMs, such as the PFMs for speech, video, and cross-domain data, and multimodal PFMs. An exemplary illustration is the GPT-4 model, as described by OpenAI [25], which is a massive multimodal language model that can process both text and image inputs and generate text outputs. GPT-4 has demon- strated human-level performance on various professional and academic evaluation tasks. Moreover, there # 1https://openai.com/blog/chatgpt/ 4 : Graph ev ey " PIMs Graph Ww pc MoCo Graph, NLP BiGAN BigBiGAN simLR RoBERTa DeepCluster BEIT Rot cera ev xp DeepWak |[ cove Nal NLP GloVe UNE ‘Shared LSTM. Counting INcisT™M FustTex SZ 2014 2016 2018 2020 MAE, BERT Figure 1: The history and evolution of PFMs. is a growing trend in PFMs that deals with multimodal data, known as unified PFMs. This term refers to models that can handle different types of data such as text, images, and audio. In this regard, we provide a definition of unified PFMs and a review of the current state-of-the-art models in recent research. Notable examples include OFA [26], UNIFIED-IO [27], FLAVA [28], BEiT-3 [29], and others. According to the features of existing PFMs, we conclude that the PFMs have the following two major advantages. First, minor fine-tuning is required to enhance the model performance on downstream tasks. Second, the PFMs have already been vetted on the quality aspect. Instead of building a model from scratch to solve a similar problem, we can apply PFMs to task-related datasets. The great promise of PFMs has inspired a wealth of related work to focus on the model efficiency [30], security [31, 32, 33, 34] and compression [35, 36]. # 1.2 Contribution and Organization There are several survey studies [37, 8, 5, 6, 7, 1] that have reviewed the pretrained models for some specific areas such as text generation [6], visual transformer [7], objection detection [8]. Bommasani et.al. [1] summarize the opportunities and risks of the foundation model. However, existing works did not achieve a comprehensive review of PFMs in different areas (e.g., CV, NLP, GL, Speech, Video) and different aspects such as pretraining tasks, efficiency, efficacy, and privacy. In this survey, we specifically track the evolution of PFMs in the NLP domain, as well as how pretraining is transferred to and adopted by CV and GL. Compared with other surveys, there is no comprehensive introduction and analysis of existing PFMs from all three fields. Unlike reviews of previous pretrained models, we summarize existing models ranging from traditional models to PFMs with recent works in the three domains. Traditional models emphasize static feature learning. Dynamic PFMs give an introduction to structures, which is the mainstream research. We further present some other research for PFMs, including other advanced and unified PFMs, model efficiency and compression, security, and privacy. Finally, we summarize future research challenges and open problems in different domains. We also comprehensively present the related evaluation metrics and datasets in Appendix F and G. In summary, the main contributions are as follows: • We present a solid and up-to-date review of the development of PFM in NLP, CV, and GL. Over the re- view, we discuss and provide insights about the generalized PFM design and pretraining methodology among the three major application domains. • We summarize the development of PFMs in other multimedia areas such as speech and video. Besides, we discuss advanced topics about PFMs, including unified PFMs, model efficiency and compression, and security and privacy. 5 Model Pre-training: Various Tasks with Big Datasets Num of Layers GPUs/TPUs Natural Language Trans- Hardware Represent Semi-supervised former Attention Heads initialiention ation Learning Computer Vision | . Embedding Size Training Optimizer Learning Self-supervised Graph Learning Model Design Setup Methods Learning Learning Rate Learning Rate . Speech and Video | Reinforcement _ Others Batch Size Software Dropout Boosting Learning Model Fine-tuning: Efficacy, Efficiency, Privacy... Figure 2: The general conceptual architecture of PFMs: data, model, and system. • Through the review of PFMs in various modalities for different tasks, we discuss the main challenges and opportunities for future research of very large models in the big data era, which guides a new generation of collaborative and interactive intelligence based on PFMs. The rest of the survey is organized as follows. Section 2 introduces the basic components. Sections 3, 4 and 5 summarize the existing PFMs in NLP, CV and GL, respectively. Sections 6, 7 introduce other advanced research for PFMs, including advanced and unified PFMs, model efficiency and compression, as well as security and privacy, respectively. Furthermore, we summarize the main challenges for PFMs in Section 8 before concluding the survey in Section 9. # 2 Basic Components The general conceptual architecture of PFMs is shown in Fig. 2. The PFMs are huge neural network models, which are all about neural information processing. The specific designs of PFMs vary according to the data modality and task requirements in different areas. Transformer is a mainstream model architecture design for PFMs in many areas such as NLP and CV. Training large models need to have various datasets for model pretraining. After training the PFMs, the model should be fine-tuned to satisfy downstream requirements such as efficacy, efficiency, and privacy. In this section, we introduce the basic model architectures, concepts, and settings of PFMs in NLP, CV, and GL domains. For the introduction of a more detailed component, please refer to Appendix A. # 2.1 Transformer for PFMs The Transformer [38] is an innovative architecture that facilitates the transfer of weighted representation knowledge between various neural units. It relies solely on attention mechanisms and doesn’t use recur- rent or convolutional architectures. The attention mechanism is a crucial component of the Transformer as it assigns weights to all the encoded input representations and learns the most important part of the input data. The output of the attention is obtained by taking the weighted sum of the values, and the weights are calculated using the compatibility function of the query with the corresponding key [38]. Numerous atten- tion mechanisms [39] have been developed in large models. For instance, in natural language processing, self-attention is created to connect various positions in a single sequence for generating a representation 6 of the same sequence. Transformer leverages a mask matrix to provide an attention mechanism based on self-attention, in which the mask matrix specifies which words can “see” each other. Transformer is an important structure for PFMs in NLP, CV, and GL areas. For NLP, the Transformer can help solve the long-range dependency issues when processing sequential input data. For example, the GPT- 3 [20] is a generative model based on the transformer. For CV, the Vision Transformer (ViT) [40] is proposed to represent an image to a series of image patches, which is similar to a series of word embeddings. For GL, the Graph Transformer Networks (GTN) [41] are employed to learn new graph structures and powerful node representations without domain knowledge. Transformers become scalable enough to drive ground- breaking capabilities for PFMs thanks to the transformer structures to achieve higher parallelization. The ViT-22B model [42], for instance, has about 22B parameters, and the largest language models can have upwards of 100B parameters (e.g., GPT-3 has 175B and PaLM [43] has 540B parameters). # 2.2 Learning Mechanisms for PFMs Deep learning models in CV have been shown a large margin to outperform traditional learning models in most tasks, including the common classification, recognition, detection, and segmentation tasks and the specific matching, tracking, and sequence prediction. These learning methods are not only available in CV, but also in NLP and GL. Supervised Learning Suppose we are given a training dataset X containing {(xi, yi)}n i=1 to represent the original data in training dataset, where xi denotes the i-th training sample, and yi denotes the corresponding label. The complete network is to learn a function f (x; θ) by minimizing the objective function as follows. L(f (xi; ), yi) + AQ(), (1) . il argmim — . (;) n i=1 where L and Ω represent the predefined loss function and a regularization term, respectively. The function f has a nested form like hi (ai) Aizi (x4) (x) w + bi), 2 (Fy (ar) "wy + b,),0 = 1,2,---,N (2) =9 =9 where l is the index of layer in deep learning model and N is the number of layers, which means that θ = {ωl, bl, l = 1, 2, · · · , N }. Semi-Supervised Learning Assume we are given another unlabelled dataset Z = {zi}m i=1 in addition to the previous dataset with human labels. If we want to utilize both datasets to learn an ideal network, the learning process can be formulated as arg min 1 Lf (ei 8), ys) + 2 so" L'(f' (zi; 6’), R(zi, X)) + 4Q(8), (3) 0 n i=l m i=l where R is a relation function defining the targets for unlabelled data, and then these pseudo-labels are integrated into the end-to-end training process. f’ is an encoder to learn a new representation for the original data in the dataset Z. Specifically, if there is no label to any data in the training process, we can learn from the properties inside the data itself via the internal distance or the designed pretext tasks, which are known as unsupervised learning and self-supervised learning(SSL), respectively. The latter is our main focus discussed in detail in Section 4.3. 7 Weakly-Supervised Learning The weakly-supervised method is the balance between fully-supervised learning and SSL according to the dependence on human labels. The SSL designs special pretext tasks to serve as the supervised learning, but the fully supervised learning utilizes existing labels attached to the data. However, both of them can learn good visual features and perform well on specific downstream tasks. Suppose there are inaccurate K labels for the dataset, and any label can be attached to a data sample. Thus, we denote the true label of image xi as yi ∈ {0, 1}K, i = 1, 2, · · · , n, and any entry of yi could be 0 or 1. Here we need to minimize the total nK loss terms , which are formulated as follows. mn " K 0). yk argmin eo, Day LUE (ei: 8)- ub) + A008), (4) where [ul ye, ne al = yi, and £ could be a loss function suitable for binomial classification problem. For any entry in y;, computing the loss function of the one-versus-all binomial classification is needed. = yi, and £ could be a loss function suitable for binomial classification problem. Self-Supervised Learning SSL utilizes the information in the data itself to learn essential feature repre- sentations for different tasks. By applying the self-defined pseudo labels, it can avoid the cost of manually labeling large datasets for PFMs. In NLP, the language models can be trained by predicting masked char- acters, words, or sentences. Variational autoencoder (VAE) and generative adversarial network (GAN) are two types of generative SSL methods, which are to reconstruct the data itself. Besides, contrastive learning, as a type of discriminative SSL method, is widely applied in CV, NLP, and GL. The main idea of contrastive learning is to learn the prior knowledge distribution of the data itself with the aid of various methods such as data augmentation. In this way, contrastive learning can learn a model that makes similar instances closer in the projected space, and dissimilar instances farther apart in the projected space. Here we show a simple version of contrastive loss: Le(Xi,x;,0) = ml fo(xi) — fo(x;)||3 + (1 — m) max(0, € — || fo(x:) — fa(x;)|l2)” (5) where m is 1 if two samples have the same label, otherwise 0, and € is the upper bound distance. Reinforcement Learning RL is another type of learning paradigm that models the learning process as a sequential interaction between an agent and an environment, where a RL agent seeks to learn an optimal policy for sequential decision-making problems. Specifically, at each time interaction step t, the agent receives a state s; in a state space S, and selects an action a; from an action space A, following a policy T9(az|s) : A + S parameterized by 6. Then the agent receives a scalar immediate reward r; = r(s;, at) and the next state s;,1 according to the environment dynamics, where r(s, a) is the reward function. For each episode, this process continues until the agent reaches a terminal state. After an episode is finished, the RL agent will restart to begin a new episode. The return for each state is discounted, accumulated reward with the discount factor y € (0,1), Ri = R(se,ax) = Teo v*rezx. The agent aims to maximize the expectation of such long-term return from each state, max θ Est[Rt|st, at = πθ(st)]. (6) # 2.3 Pretraining Tasks for PFMs Pretraining is an initialization framework, which generally needs to be used in conjunction with fine-tuning downstream tasks. In the scheme of pretraining and finetuning, the parameters of the model are trained on pre-set tasks to capture specific attributes, structure, and community information. The pretrained features can assist downstream tasks, provide sufficient information, and speed up the convergence of the model. 8 # 2.3.1 Pretraining Tasks for NLP The pretraining tasks can be divided into five categories according to the learning methods: Mask Language Modeling (MLM), Denoising AutoEncoder (DAE), Replaced Token Detection (RTD), Next Sentence Pre- diction (NSP), Sentence Order Prediction (SOP). RTD, NSP, and SOP are contrastive learning methods, which assume that the observed samples are more semantically similar than the random samples. Mask Language Modeling (MLM). MLM erases some words randomly in the input sequence and then predicts these erased words during pretraining. Typical examples include BERT [13] and SpanBERT [44]. Denoising AutoEncoder (DAE). DAE is used to add noise to the original corpus and reconstruct the original input using the corpus containing noise. BART [45] is a representative example. Replaced Token Detection (RTD). RTD is a discriminant task that determines whether the LM has replaced the current token. This task is introduced in ELECTRA [46]. By training the model to distinguish whether a token has been replaced or not, the model can acquire language knowledge. Next Sentence Prediction (NSP). In order to make the model understand the correlation between the two sentences and capture sentence-level representations, a NSP task is introduced. The PFM inputs two sentences from different documents and checks whether the order of the sentences is correct. A typical example is BERT. Sentence Order Prediction (SOP). Different from NSP, SOP uses two contiguous fragments from a document as positive samples and the exchange order of the two fragments as negative samples. The PFMs can better model the correlation between sentences, such as ALBERT [47]. # 2.3.2 Pretraining Tasks for CV There are many pretraining tasks created for CV to learn the feature space, which is based on SSL. It utilizes pretext tasks that contain human-designed labels, like jigsaw puzzles or the comparison of various patches from images. This enables the generalization of learned representations to a range of downstream tasks. Specific Pretext Task. A pretext task also referred to as a predefined task, is created for the encoder networks to perform during the pretraining phase. The network is trained by predicting the answer to a special pretext task. Based on particular features of the data, pseudo labels are generated for the fictitious task. Then, using guided learning techniques, the encoder networks are trained to solve the pretext task. For example, inpainting aims to pretrain models by predicting the missed center part. Frame Order Learning Task. Learning frame order from videos involves frame processing through time steps, which can serve as the pretraining task for CV. This issue usually relates to completing pretextual exercises that can aid in the acquisition of visual temporal representations. Data Generation Task. The representational capabilities within the generative adversarial networks (GANs) can also be used in the pretraining tasks. Projecting data back into the latent space, as demonstrated by BiGANs [48], is helpful for auxiliary supervised discrimination tasks by acting as feature representations. Data Reconstruction Task. Since the images can be divided into patches inspired by the natural lan- guage, some pretraining tasks for NLP can also be used in CV, e.g., the autoencoder-based masked predic- tion. The original image is first divided into a few patches and discrete visual tokens are used to encode each patch. The visual tokens from the masked patches are outputted in the second stage to match the corresponding visual tokens from the fixed tokenizer. Miscellaneous. To train the PFMs in CV, additional pretraining tasks are suggested. For instance, 9 based on contrastive learning, encoder networks are used for pretraining on various data augmentation. The parameters are trained by maximizing the distance between negative pairs (e.g., pairs with different labels) and minimizing the distance between positive pairs (e.g., pairs with the same labels). To pretrain the parameters of the backbone network, the DeepClustering [49] method divides the representations into various clusters and labels these clusters as supervised signals. # 2.3.3 Pretraining Tasks for GL The pre-set tasks in GL are similar to other pretext tasks. However, they can be supervised or unsupervised depending on the design. According to the pretraining purpose and potential motivation in GL, such tasks can be divided into the following categories: Graph Information Completion. This task refers to firstly masking part of the information in the input graph, and then recovering the masked information based on the analysis of the remaining information distribution. Similar tasks also exist in CV and NLP, and their goals are to fill in hidden pixels or words, respectively. Graph Property Prediction. Different from directly modeling the information of the input graph, this task aims to provide a variety of self-supervised signals by mining the potential properties of the input graph. Specifically, on the one hand, it considers node attributes, local substructure, and connectivity information to provide predictive regression tasks; on the other hand, it assigns pseudo-labels to nodes through information such as clusters, structure density, and attribute similarity to provide classification tasks. Graph Consistency Analysis. The goal of this task is to maximize the consistency between samples with similar semantic information in the graph embedding and minimize the agreement between samples with unrelated semantic information. In the actual scenario, it can be divided into consistency analysis of context/self/cross-scale according to different model training strategies. Miscellaneous. Compared with using only one pretext task, some methods have designed some integra- tion mechanisms to incorporate the advantages of multiple pretext tasks into a unified framework. Besides, some graph data in specific fields have unique self-supervised signals with practical significance that can be used for pretraining under targeted design. In summary, the transformer is an important component of the large model architecture, which helps learn the important features and mine intrinsic structure in data. Different learning mechanisms can be used for training PFMs according to the datasets and specific tasks. Especially, SSL is a promising mechanism to learn knowledge embeddings from the data considering the large scale of unlabeled data in various areas. RL provides a new way to fine-tune the PFMs for downstream tasks by optimizing a policy (model) against the reward model. How to design effective and efficient tasks for PFMs to master the knowledge behind the data is an important research topic. # 3 PFMs for Natural Language Processing NLP is a research field that integrates linguistics and computer science. Its main research tasks include part-of-speech tagging, named entity recognition, semantic role labeling, machine translation, question an- swering, sentiment analysis, text summarization, text classification, relationship extraction, event extraction, etc. The idea of PFM first gained popularity in NLP. Then CV and GL adopt the promising pretraining tech- nology. The PFM trains on a large benchmark dataset and is fine-tuned on the primary task dataset to obtain a model which can solve new similar tasks. It models syntactic and semantic representations of words si- 10 multaneously and changes the representation of polysemous words dynamically according to different input contexts. PFM learns a rich knowledge of grammar and semantic reasoning with better results. Numerous PFMs have been proposed in the past few years, as shown in Table 1. In this section, we first introduce word representation learning models including the autoregressive lan- guage model (LM), contextual LM, and permuted LM. Then, we present the neural network architectures for the PFM designing method and the masking designing method. Besides, we summarize boosting methods for enhancing model performance, multi-task learning, and different downstream tasks. Finally, we intro- duce the instruction-aligning methods, e.g. RLHF and Chain-of-Thoughts, which are applied in PFMs, such as ChatGPT, to provide outputs that more closely match human preferences and are less harmful. # 3.1 Word Representations Methods Many large-scale pretrained models have achieved better performance than humans in question answering, machine reading comprehension, and natural language reasoning, which indicates that the current construc- tion approach of PFMs is practical. The existing pretraining LMs are mainly divided into three branches according to the word representations approach: (1) autoregressive LM, (2) contextual LM, and (3) permuted LM. The word prediction direction and contextual information are the most important factors among these three branches. Autoregressive Language Model The autoregressive LM predicts the next possible word based on the preceding word or the last possible word based on the succeeding word. It is selected as a feature extractor and text representations are extracted from the former words. Thus, it has better performance in NLG tasks such as text summarization and machine translation. For a sequence, T = [w1, w2, . . . , wN ], the probability of a given word calculated as follows: N p(wi, w2,...,WN) = NE (w; | wi, we,...,Wi-1), (7) i=l where i > 1 and N is the length of the input sequence. The GPT [50] adopts a two-stage method of self-supervised pretraining and supervised fine-tuning and uses stacked Transformer [38] as its decoder. As a follow-up, the OpenAI team continues to expand GPT, proposes the GPT-2 [51] and increases the number of stacked Transformer layers to 48 layers. The total number of parameters reached 1.5 billion. GPT-2 also introduces multi-task learning [52]. The GPT-2 has a considerable model capacity and can be adjusted for different task models rather than fine-tuning them. However, GPT-2 also uses an autoregressive LM. Therefore, it improves the performance of the model without increasing the cost dramatically. Due to the lack of contextual modeling ability with a one-way Transformer, the main performance improvement of GPT-2 comes from the combined effect of multi-task pretraining, super-large datasets, and super-large models. Task-based datasets for fine-tuning are still needed for specific downstream tasks. Increasing the training scale of the LM can lead to a significant enhancement in task-independent performance. Hence, GPT-3 [20] was developed, which features a model size of 175 billion parameters and is trained with 45 Terabytes of data. This enables it to exhibit good performance without the need for fine-tuning for specific downstream tasks. Contextual Language Model The autoregressive LM only uses the information above or below and can- not use the information above and below at the same time. ELMO [53] only uses bi-directional Long 11 Short-Term Memory (LSTM), which is a concatenation of two unidirectional LSTMs in backward and for- ward. The contextual LM predictions are based on contextual words. It uses a Transformer encoder, and the upper and lower layers of the model are all directly connected to each other due to the self-attention mechanism. For a sequence of words T , the probability of a given word calculates as follows N p(w, W2,...,WN) = Iv (w; | w1,We,...,WN)- (8) i=1 BERT [13] uses a stacked multi-layer bi-directional Transformer as the basic structure, and Word- Piece [54] as a word segmentation method. The model input consists of three parts: word embedding, segment embedding, and position embedding. It uses a bi-directional Transformer as a feature extractor, which offsets the defect of ELMO and GPT. However, the shortcomings of BERT are also not to be ignored. The bidirectional Transformer structure does not eliminate the constraints of the self-encoding model. Its vast number of model parameters are very unfriendly to devices with low computing resources and are challenging to deploy and apply. Furthermore, the hidden language modeling in pretraining will lead to inconsistencies with the input of the model in the fine-tuning stage. Most PFMs need more training tasks and a larger corpus. Aiming at the problem of insufficient training, Liu et al. [55] propose the RoBERTa. It uses a larger batch size and unlabeled data. Furthermore, it trains the model for a longer time, removes the NSP task, and adds long sequence training. In processing text input, different from BERT, Byte Pair Encoding (BPE) [56] is adopted for word segmentation. BPE uses a different mask mode for each input sequence, even if the input sequence is the same. Permuted Language Model The modeling method with a contextual LM can be regarded as the autoen- coding model. However, due to the inconsistency in the training stage and fine-tuning stage, the performance of the autoencoding model is poor in the Natural Language Generation (NLG) task. Permuted LM aims to combine the advantages of the autoregressive LM and the autoencoder LM. It improves the defects of the two models to a great extent and can be used as a basic idea for the construction of future pretraining target tasks. For a given input sequence T = [w1, w2..., wN ], the formal representation of the target function of the permuted LM is as follows N max Ee. zy log pe (Cop, | Lepe) ; (9) t=1 where θ is the shared parameter in all permutations, ZN represents the set of all possible permutations of the input sequence T , and zT =t and zT <t represents the t-th element and the [1, 2, . . . , t − 1] elements of a permutation z ∈ ZN . MLM represented by BERT can implement bi-directional coding well. However, MLM uses the mask marking during pretraining but not during fine-tuning, which resulted in inconsistent data during pretraining and fine-tuning. To achieve bi-directional coding and avoid the problems of MLM, the permuted LM is proposed. permuted LM is based on the autoregressive LM, which avoids the influence of inconsistent data. However, unlike traditional autoregressive models, permuted LM no longer models sequences in order. It gives all possible permutations of sequences to maximize the expected logarithmic likelihood of the sequence. In this way, any position can take advantage of contextual information from all positions, making permuted LM implement bidirectional encoding. The most common permuted LM models are XLNET [14] and MPNet [57]. XLNET is a PFM based on a permuted language modeling approach, which incorporates two crucial techniques from Transformer-XL: relative positional encoding and the segment recurrence mechanism. In contrast, MPNet combines Masked Language Modeling (MLM) and permuted 12 T, tr, T, Ty qT, T, T, Ty Trm Trm Trm Trm Trm Trm Trm Trm BERT Encoder GPT Decoder Trm Trm Trm Trm Trm Trm Trm Trm £, Ey E, Ey E£, 1 E. 2 E, aa Ey Figure 3: The architectures of BART [45]: generalizing BERT (due to the bidirectional encoder), GPT (with the left-to-right decoder). An autoregressive decoder is used to determine the likelihood of the original document after the corrupted document (on the left) has been encoded using a bidirectional model. language modeling to predict token dependencies, using auxiliary position information as input to enable the model to view a complete sentence and reduce position differences. These two models represent significant advancements in the field of PFMs. # 3.2 Model Architecture Designing Methods ELMO adopts a multi-layer RNN structure. Each layer is a bi-directional LSTM structure composed of a forward and backward LM. The maximum likelihood of these two directions is taken as the objective function. Compared with the word vector method, ELMO introduces contextual information and improves the polysemy problem, but ELMO’s overall ability to extract linguistic features is weak. The application research of PFMs has two main directions. One is PFMs with fine-tuning (e.g., BERT), and the other one is PFMs with zero/few-shot prompts (e.g., GPT). BERT uses a bi-directional encoder in Transformer to predict which words are masked and determine whether two sentences are contextual. However, the document is encoded bidirectionally and missing tokens are predicted independently, which reduces the generation ability [45]. GPT uses an autoregressive decoder as a feature extractor to predict the next word based on the first few words and solve downstream tasks using fine-tuning, so it is more suitable for text-generation tasks. However, GPT only uses the former words for prediction, which cannot learn bidirectional interaction information. Different from these models, BART [45] is a noise-reducing autoencoder built by seq2seq model adopt- ing the encoder-decoder structure, as shown in Fig. 3 from [45]. Pretraining mainly includes using noise to destroy text and using the seq2seq model to rebuild the original text. The encoding layer adopts a bi- directional Transformer. It adopts five modes of adding noise: (1) single word mask; (2) word deletion; (3) span mask; (4) sentence rearrangement; (5) document rearrangement. In the encoder part, the sequence has been masked before inputting it into the encoder. Then, the decoder restores the original sequence accord- ing to the encoding representation output by the encoder and the sequence that has not been masked. The addition of a series of noise patterns makes the performance of BART in sequence generation and natural language reasoning tasks significantly improved. # 3.3 Masking Designing Methods The attention mechanism first aggregates essential words into sentence vectors, and vital sentence vectors into text vectors, which allows the model to pay different attention to different inputs [58]. For BERT, as a bidirectional encoding LM, any two words in an input sentence can see each other. However, it hinders the ability of BERT model to learn NLG tasks. 13 f, ty T, iy an American football game T, To Ty hy Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Trm Super Bowl 50 was MASK MASK MASK MASK to determine the champion Figure 4: The architecture of SpanBERT [44]. Joshi et al. [44] propose SpanBERT based on RoBERTa, which adopts the idea of dynamic masking and single segment pretraining, as shown in Fig. 4 from [44]. The span mask and the Span Boundary Objective (SBO) are also proposed to mask words of a certain length. The target task of the span-boundary is to restore all the masked span (tokens) by the observed tokens at both ends. The training stage uses the dynamic mask strategy proposed in the RoBERTa, instead of the mask during the data preprocessing. Unlike BERT, SpanBERT randomly covers up a continuous text and adds the SBO training target. It predicts the span using the token closest to the span boundary and eliminates the NSP pretraining task. The BERT and GPT can only separate the training encoder and decoder without joint training in the NLG task. Song et al. [59] propose the masked seq2seq pretraining model MASS. In the training stage, the input sequence of the encoder is randomly masked as a continuous segment of length k. The masked segment will be recovered through the MASS decoder. UniLM [60] completes the learning of the NLG model by designing a different mask for two sentences in the input data. For the first sentence, UniLM uses the same structure as the Transformer encoder making each word notice its preceding and following words. For the second sentence, each word can only notice all the words in the first sentence and the preceding words in the current sentence. Thus, the first and second sentences of the model input form the classic seq2seq pattern. # 3.4 Boosting Methods Boosting on Model Performance Most of the popular pretraining models need lots of pretraining data, which imposes huge requirements on the hardware, making it challenging to retrain, and only fine-tuning can be done to the model. To solve these problems, some models appear. For example, ERNIE Tiny released by Baidu is a miniaturized ERNIE [61], that reduces the number of layers and increases the prediction speed by 4.3 times with a slight decrease in accuracy. Lan et al. propose the ALBERT [47] to reduce memory consumption and training speed. However, it is undeniable that no matter what kind of compression is done for these large-scale models, the performance of the models in these tasks will deteriorate sharply. It requires paying attention to the efficient representation of high-level semantic and grammatical information and lossless compression in future works. By using word-embedded parameter factorization and hidden parameter sharing between layers, ALBERT significantly reduces the number of parameters of the model without performance loss. It proposes the training task of SOP, which predicts the order of the two sentences to improve the performance. Boosting for Multi-task Learning ERNIE(Baidu) [61] is mainly composed of two parts, the Transformer encoder and task embedding. In the Transformer encoder, the self-attention mechanism is used to capture the context information of each token and generate context representation embedding. Task embedding is a technique that applies different characteristics to a task. ERNIE 2.0 [62] introduces multi-task learning to 14 Labeler: Fine-tuned Model: Prompt-Output Datasets Roy Hxemyg Prompt-Multiple Output Fine-tuned ' Gpras Model ——» PPO Model —— we ~ (ChatGPT) ' le Model Fine-tuning with Output | Labeler: Rank Multiple Output Supervised Learning Figure 5: Boosting GPT-3.5 to ChatGPT using Reinforcement Learning from Human Feedback. realize the pretraining of lexical, grammar, and semantics. ERNIE 2.0 uses seven different pretraining tasks, covering three aspects: word level, sentence level, and semantic level. It uses continual learning, making the knowledge in the previous training task retained and enabling the model to acquire long-distance memory. It uses a Transformer encoder and introduces task embedding, enabling the model to distinguish different tasks in the continual learning process. UniLM [60] uses three pretraining tasks: unidirectional LM, bidirectional LM, and encoder-decoder LM. It can simultaneously complete three kinds of target tasks in the pretraining stage through the self-attention layer mask mechanism. In the training stage, UniLM adopts the small- segment mask strategy proposed by SpanBERT, and the loss function is composed of the loss functions of the above three pretraining tasks. To maintain the contribution consistency on all loss functions, the three pretraining tasks are trained simultaneously. Modeling and parameter sharing of multiple tasks make LMs achieve good generalization ability in Natural Language Understanding (NLU) and NLG tasks. Boosting for Different Downstream Tasks The pretraining models tend to be large-sized, so how to match different downstream tasks is equally important. Some pretraining models that are trained on spe- cialized corpora have appeared [63, 64, 65]. Cui et al. [63] propose the BERT-whole word masking model (BERT-WWM). They directly use BERT in Chinese to be masked randomly according to the original MLM training, resulting in the loss of semantic information. Since there is no explicit language boundary in Chinese, it is easy to lose significant meaning. ZEN [64] is a text encoder based on BERT, which adopts N-gram to enhance performance and effectively integrates considerable granular text information with fast convergence speed and good performance. Tsai et al. [65] propose an oriented multilingual sequence la- beling model for sequence labeling tasks. The knowledge distillation method is adopted to achieve better performance in the two tasks: part of speech labeling and morphological attribute prediction for multiple low-resource languages. The inference time is shortened by 27 times. Examples: ChatGPT and Bard As shown in Fig. 5, ChatGPT is fine-tuned based on the PFM GPT-3.5 using RLHF. ChatGPT uses a different data collection setup compared to InstructGPT. First, a large dataset with prompts and the desired output behaviors is collected. The dataset is used to fine-tune GPT-3.5 with supervised learning. Second, given the fine-tuned model and a prompt, the model will generate several model outputs. A labeler gives the desired score and ranks the output to compose a comparison dataset, which is used to train the reward model. Finally, the fine-tuned model (ChatGPT) is optimized against the reward model using the Proximal Policy Optimization (PPO)[66] RL algorithm. Another experimental conversational PFM, the Bard 2, is developed by Google. Bard is based on the LM for Dialogue Applications (LaMDA). LaMDA [67] is built upon the Transformer, which is pretrained on 1.56T words of dialog data and web text. Safety and factual grounding are two main challenges for 2https://blog.google/technology/ai/bard-google-ai-search-updates/ 15 conversational AI, LaMDA applies the approaches that fine-tuning with high-quality annotated data and external knowledge sources to improve model performance. # Instruction-Aligning Methods Instruction-aligning methods aim to let the LM follow human intents and generate meaningful outputs. The general approach is fine-tuning the pretrained LM with high-quality corpus in a supervised manner. To further improve the usefulness and harmlessness of LMs, some works introduce RL into the fine-tuning pro- cedure so that LMs could revise their responses according to human or AI feedback. Both supervised and RL approaches can leverage chain-of-thought [24] style reasoning to improve the human-judged performance and transparency of AI decision-making. Supervised Fine-Tuning (SFT) SFT is a well-established technique to unlock knowledge and apply it to specific real-world, even unseen tasks. The template for SFT is composed of input-output pairs and an instruction [113]. For example, given the instruction “Translate this sentence to Spanish:” and an input “The new office building was built in less than three months.”, we want the LM to generate the target “El nuevo edificio de oficinas se construyó en tres meses.”. The template is commonly humanmade including unnatural instructions [114] and natural instructions [115, 116], or bootstrap based on a seed corpus [117]. Ethical and social risks of harm from LMs are significant concerns in SFT [118]. LaMDA, the largest LM to date, thus relies on crowdworker annotated data for providing a safety assessment of any generated LaMDA response in three conversation categories: natural, sensitive, and adversarial. The list of rules serves further safety fine-tuning and evaluation purposes. Reinforcement Learning from Feedback RL has been applied to enhance various models in NLP tasks such as machine translation [119], summarization [18], dialogue generation [120], image captioning [121], question generation [122], text-games [123], and more [124, 125, 126]. RL is a helpful method for opti- mizing non-differentiable objectives in language generation tasks by treating them as sequential decision- making problems. However, there is a risk of overfitting to metrics that use neural networks, leading to nonsensical samples that score well on the metrics [127]. RL is also used to align LMs with human prefer- ences [128, 129, 130]. InstructGPT proposes to fine-tune large models with PPO against a trained reward model to align LMs with human preference [19], which is the same method applied by ChatGPT named RLHF. Specifically, the reward model is trained with comparison data of human labelers’ manual rankings of outputs. For each of them, the reward model or machine labeler calculates a reward, which is used to update the LM using PPO. More details are illustrated in Fig. 5. One of the recent breakthroughs in PFM technology is GPT-4 [25], which follows a pretraining approach to predict the subsequent token in a document and then undergoes RLHF fine-tuning. As the task complex- ity increases, GPT-4 outperforms GPT-3.5 in terms of reliability, creativity, and capability to handle more nuanced instructions. Sparrow [130], developed by DeepMind, also utilizes RLHF that reduces the risk of unsafe and inap- propriate answers. Despite some promising results using RLHF by incorporating fluency, progress in this field is impeded by a lack of publicly available benchmarks and implementation resources, resulting in a perception that RL is a difficult approach for NLP. Therefore, an open-source library named RL4LMs [127] is introduced recently, which consists of building blocks for fine-tuning and evaluating RL algorithms on LM-based generation. 16 Table 1: Summary of PFMs in NLP. The pretraining task includes language model (LM), masked LM (MLM), permuted LM (PLM), denoising autoencoder (DAE), knowledge graphs (KG), and knowledge em- bedding (KE). Year Conference 2013 NeurIPS 2014 EMNLP 2015 NeurIPS 2016 IJCAI 2017 TACL 2017 NeurIPS 2018 NAACL-HLT 2018 NAACL-HLT 2018 2019 ACL 2019 ACL ICLR 2019 ICLR 2019 ICLR 2019 ICLR 2019 2019 ICML 2019 EMNLP-IJCNLP 2019 EMNLP-IJCNLP 2019 EMNLP-IJCNLP 2019 EMNLP-IJCNLP 2019 EMNLP-IJCNLP 2019 NeurIPS 2019 NeurIPS 2019 NeurIPS 2019 OpenAI Blog arXiv 2019 2019 arXiv 2019 EMC2@NeurIPS 2019 arXiv 2020 ACL 2020 ACL 2020 ACL Model Skip-Gram [68] GloVe [69] LM-LSTM [70] Shared LSTM [71] FastText [72] CoVe [73] ELMO [53] BERT [13] OpenAI GPT [50] ERNIE(THU) Transformer-XL [74] InfoWord [75] StructBERT [76] ALBERT [47] WKLM [77] MASS [59] KnowBERT [78] Unicoder [79] MultiFit [80] SciBERT [81] BERT-PKD [82] Xlnet [14] UNILM [60] XLM [83] GPT-2 [51] RoBERTa [55] ERNIE(Baidu) [61] Q8BERT [84] DistilBERT [85] fastBERT [86] SpanBERT [44] BART [45] Architecture Word2Vec Word2Vec LSTM LSTM Word2Vec LSTM+Seq2Seq LSTM Transformer Encoder Transformer Decoder Transformer Encoder Transformer-XL Transformer Encoder Transformer Encoder Transformer Encoder Transformer Encoder Transformer Transformer Encoder Transformer Encoder QRNN Transformer Encoder Transformer Encoder Transformer-XL Encoder LSTM + Transformer Transformer Encoder Transformer Decoder Transformer Encoder Transformer Encoder Transformer Encoder Transformer Encoder Transformer Encoder Transformer Encoder Transformer Code Training method https://github.com/.../models - - - https://github.com/.../GloVe LM https://github.com/.../adversarial_text LM https://github.com/.../fastText - https://github.com/.../cove - https://allennlp.org/elmo LM https://github.com/.../bert MLM https://github.com/...transformer-lm LM https://github.com/.../ERNIE MLM https://github.com/.../transformer-xl - - MLM - MLM https://github.com/.../ALBERT MLM - MLM https://github.com/.../MASS MLM(Seq2Seq) https://github.com/.../kb MLM - MLM+TLM https://github.com/.../multifit LM https://github.com/.../scibert MLM https://github.com/...Compression MLM https://github.com/.../xlnet PLM LM + MLM https://github.com/.../unilm MLM+CLM+TLM https://github.com/.../XLM https://github.com/.../gpt-2 LM https://github.com/.../fairseq MLM https://github.com/.../ERNIE MLM+DLM https://github.com/.../quantized_bert.py MLM https://github.com/.../distillation MLM https://github.com/.../FastBERT MLM https://github.com/.../SpanBERT MLM https://github.com/.../transformers DAE CamemBERT [87] XLM-R [88] Reformer [89] ELECTRA [46] Q-BERT [90] XNLG [91] K-BERT [92] ERNIE 2.0 [62] GPT-3 [20] MPNet [57] ConvBERT [93] MiniLM [94] mBART [95] CoLAKE [96] FlauBERT [97] GLM [98] https://camembert-model.fr https://github.com/.../XLM https://github.com/.../reformer https://github.com/.../electra - https://github.com/.../xnlg https://github.com/.../K-BERT https://github.com/.../ERNIE https://github.com/.../gpt-3 https://github.com/.../MPNet https://github.com/.../ConvBert https://github.com/.../minilm https://github.com/.../mbart https://github.com/.../CoLAKE https://github.com/.../Flaubert https://github.com/.../GLM https://github.com/.../TinyBERT https://github.com/.../RobBERT https://github.com/.../ZEN - https://github.com/.../bert-prune https://github.com/...transformer https://github.com/...BERT-wwm https://github.com/.../pet https://github.com/.../KEPLER https://github.com/.../SimCSE - Embedding Probabilistic Probabilistic Probabilistic Probabilistic Probabilistic Probabilistic Contextual Contextual Autoregressive Contextual Contextual Contextual Contextual Contextual Contextual Contextual Contextual Contextual Probabilistic Contextual Contextual Permutation Contextual Contextual Autoregressive Contextual Contextual Contextual Contextual Contextual Contextual En: Contextual De: Autoregressive Contextual Transformer Encoder Contextual Transformer Encoder Permutation Reformer Contextual Transformer Encoder Contextual Transformer Encoder Contextual Transformer Contextual Transformer Encoder Contextual Transformer Encoder Autoregressive Transformer Decoder Permutation Transformer Encoder Contextual Mixed Attention Contextual Transformer Encoder Contextual Transformer Contextual Transformer Encoder Contextual Transformer Encoder Contextual Transformer Encoder Contextual Transformer Contextual Transformer Encoder Transformer Encoder Contextual KG-Transformer Encoder Contextual Contextual Transformer Encoder Contextual Transformer Contextual Contextual Contextual Contextual Autoregressive Contextual Contextual Autoregressive Contextual Autoregressive Autoregressive Autoregressive Autoregressive 2020 ACL 2020 ACL ICLR 2020 2020 ICLR 2020 AAAI 2020 AAAI 2020 AAAI 2020 AAAI 2020 NeurIPS 2020 NeurIPS 2020 NeurIPS 2020 NeurIPS 2020 TACL 2020 COLING 2020 LREC 2020 EMNLP 2020 EMNLP (Findings) TinyBERT [99] 2020 EMNLP (Findings) RobBERT [100] 2020 EMNLP (Findings) ZEN [64] 2020 EMNLP (Findings) BERT-MK [101] 2020 RepL4NLP@ACL 2020 JMLR 2021 T-ASL 2021 EACL 2021 TACL 2021 EMNLP 2021 2021 2021 2021 2022 2022 2022 2022 2022 MLM(WWM) MLM - MLM MLM MLM+DAE MLM MLM LM MLM+PLM - MLM DAE MLM+KE MLM MLM+KG MLM MLM MLM MLM MLM(Pruning) MLM(Seq2Seq) MLM MLM MLM+KE MLM+KE LM MLM MLM LM MLM LM LM LM LM CompressingBERT [35] T5 [102] BERT-wwm-Chinese [63] Transformer Encoder Transformer Encoder PET [103] Transformer Encoder KEPLER [104] Transformer Encoder SimCSE [105] Transformer GLaM [106] Transformer XLM-E [107] Transformer T0 [108] Transformer Gopher [109] Transformer MT-NLG [110] Transformer Decoder LaMDA [67] Transformer Chinchilla [111] Transformer PaLM [43] Transformer Decoder OPT [112] # ICML arXiv arXiv arXiv arXiv arXiv arXiv arXiv arXiv # https://github.com/.../T0 - - https://github.com/.../LaMDA - https://github.com/.../PaLM https://github.com/.../MetaSeq 17 Besides human feedback, one of the latest dialogue agents – Claude favors Constitutional AI [131] where the reward model is learned via RL from AI Feedback (RLAIF). Both the critiques and the AI feedback are steered by a small set of principles drawn from a ‘constitution’, the specification of a short list of principles or instructions, which is the only thing provided by humans in Claude. The AI feedback focuses on controlling the outputs to be less harmful by explaining its objections to dangerous queries. Chain-of-Thoughts Chain-of-thought (CoT) prompting is a technique for improving the reasoning ability of LLMs by prompting them to generate a series of intermediate steps that lead to the final answer of a multi- step problem. The CoT is a series of intermediate reasoning steps, which can significantly improve the ability of LLMs to perform complex reasoning [24, 132, 133]. Besides, fine-tuning with CoT shows slightly more harmless compared to without CoT [131]. CoT prompting is an emergent property of model scale, meaning it works better with larger and more powerful language models. It is also possible to fine-tune models on CoT reasoning datasets to enhance this capability further and stimulate better interpretability. In a CoT prompting experiment, a prompt is provided to the model that outlines a multi-step problem. The prompt might pose a question such as “After selling 30 out of his 100 chickens and 10 out of his 20 pigs, how many animals does a farmer have left?” The model then generates a sequence of intermediate reasoning steps, for example, “The farmer has 100-30=70 chickens remaining” and “The farmer has 20-10=10 pigs remaining,” before generating the final answer, such as “The farmer has 70+10=80 animals remaining.” CoT prompting has demonstrated its efficacy in improving the performance of LLMs on various reasoning tasks, such as arithmetic, symbolic reasoning, and common sense. It is a promising technique that can enhance the ability of language models to reason about complicated problems. # 3.6 Summary The neural probabilistic LM uses a neural network to estimate the parameters of the probabilistic LM, which reduces the size of the model parameters while enlarging the number of context windows. With the help of a neural network, the LM does not need to improve the smoothing algorithm to alleviate the performance bottleneck continuously. Since the training target is unsupervised, a corpus with a large amount of data is enough for training. The negative sampling technique in the training process provides a new idea for the follow-up study of the target task in the LM. Furthermore, the neural probabilistic LM promotes the further development of downstream task research because of its good representation capability and training efficiency. After the pretraining LM, especially the BERT model, is proposed, the research in language modeling has entered a new phase. The bidirectional LM, the hidden LM, and the sorted LM adopted by the bidirectional LM have successfully modeled the grammatical and semantic information in natural language at a deeper level. ChatGPT is another milestone work in PFMs using RL. The presentation ability of PFMs is qualitatively better than that of the neural probabilistic LM. It even exceeds that of humans in some tasks. # 4 PFMs for Computer Vision With the popularity of PFM used in NLP, it motivates researchers to start exploring PFM in CV. The term “pretraining” has not been clearly defined within the realm of deep learning research in CV. This word is first used in convolution-based networks when we adjust the parameters on a more general dataset such as ImageNet, which can make other tasks train to start with a warm-up initialization and thus converge with faster speed. In contrast to early CNN-based transfer learning techniques that rely on pretrained datasets with supervised signals, our examination of PFM centers on SSL which utilizes human-designed labels, 18 ' Big Data in the Wild Pre-training } ' Encoder ' H : . (ConvNet, ' ' i Data Augmentation or Self-labeling strategy © ——+> RNN,--)) Pretext Task ' ' Unlabeled i s i inlabeled images ; Transferred Data in the Domain Downstream Supervised Learning =~ . . EES Average Downstream! ra aa at Labelling Information ——> (ConvNet, —+ Representation MLP —> Task ' RNN, -*:) ' Labeled images Figure 6: The general pipeline for SSL. The top part represents the pretraining, and the bottom stream obtains transferred parameters from above to learn downstream supervised tasks. such as Jigsaw puzzles, or the comparison of different patches from images as pretext tasks. This allows for learned representations to be generalized to various downstream tasks, including classification, detection, recognition, segmentation, etc. However, it is costly to rely on data annotations when the learning tasks become more complicated, making the labeling process more arduous and time-consuming than the actual learning. This is where SSL is urgently needed and how it can further fuel the progress of deep learning methods. To reduce the dependency on data labeling, unlabeled data are trained with self-supervision by matching, contrasting, or generating in SSL. The general pipeline of SSL is shown in Fig. 6. During the pretraining stage, a pretext task is designed for the encoder networks to solve. The artificial labels for this pretext task are automatically generated based on specific attributes of the data, such as image patches from the same origin being labeled as “positive” and those from different origins as “negative”. Then, the encoder networks are trained to solve the pretext task by supervised learning methods. Since shallow layers extract fine-grained details such as edges, angles, and textures, while deeper layers capture task-related high-level features such as semantic information or image contents, learned encoders on pretext tasks can be transferred to downstream supervised tasks. During this stage, the parameters of the backbone are fixed, and only a simple classifier, such as a two-layer Multi-Layer Perceptron (MLP), needs to be learned. Considering the limited workload in the downstream training stage, this learning process is commonly referred to as fine-tuning. In summary, the representations learned during the pretraining stage in SSL can be reused on other downstream tasks and achieve comparable results. In this section, we introduce different tasks for pretraining PFMs in CV. The PFMs can be trained by specific pretext tasks, frame order, generation, reconstruction, memory bank, sharing, clustering and so on. We summarize the PFMs proposed in CV in Table 2. # 4.1 Learning by Specific Pretext Task In the early stage of unsupervised learning, the network is trained by designing a special pretext task and predicting the answer to this task. Dosovitskiy et al. [134, 135] pretrain the Exemplar CNN to discriminate the different patches from the unlabelled data. The experiments prove the designs can learn useful represen- tations transferred to the standard recognition assignments. In the method based on context prediction [136], a handcrafted supervised signal about the position information serves as the label for the pair classification. Inpainting [137] aims to pretrain models by predicting the missed center part. Because inpainting is a 19 semantic-based prediction, another decoder is linked to the context encoder in this manner. Furthermore, the standard pixel-by-pixel reconstruction process of the decoder can be transferred to any other down- stream inpainting tasks. Specifically, Colorization [138] is a method that evaluates how colorization as a pretext task can help to learn semantic representation for downstream tasks. It is also known as the cross- channel encoding since different image channels serve as input and the output is discriminated. Similarly, Split-Brain Autoencoder [139] also learns representations in a self-supervised way by forcing the network to solve cross-channel prediction tasks. Jigsaw [140] is proposed to pretrain the designed Context-Free Network (CFN) in a self-supervised manner by first designing the Jigsaw puzzle as a pretext task. Com- pleting Damaged Jigsaw Puzzles (CDJP) [141] learns image representation by complicating pretext tasks furthermore, in which puzzles miss one piece and the other pieces contain incomplete color. Following the idea of designing efficient and effective pretext tasks, Noroozi et al. [142] use counting visual primitives as a special pretext task and outperform previous SOTA models on regular benchmarks. NAT [143] learns representation by aligning the output of backbone CNN to low-dimensional noise. RotNet [144] is designed to predict different rotations of images. Ct Predictions f—__ 4 Gar Jar Gar Gar 4 ' 4 iy ’ ’ \ ’ Zt Zt+1 Zt+2 243 Zt+4 Genc Yenc Genc Genc Yenc Genc Genc Genc Xt-3 Xt-2 Xto1 Xt Xtt1 Xt+2 Xt+3 Xtea Figure 7: Contrastive Predictive Coding [145]. The input sequence can represent both images and videos. # 4.2 Learning by Frame Order The learning of sequence data such as videos always involves frame processing through time steps. This problem often connects with solving pretext tasks that can help to learn visual temporal representations. Contrastive Predictive Coding (CPC) [145] is the first model to learn data representations by predicting the future in latent space. This model can be fed with data in any modalities, like speech, images, text, etc. The components of CPC are shown in Fig. 7 from [145], where the xt represents the input sequence of observations, zt is a sequence of latent representations after the encoder genc, and ct is a context latent representation that summarizes all the latent sequence z≤t after an autoregressive model gar. Unlike the traditional model predicts future frames xt+k by a generative model pk(xt+k|ct), CPC models a "density ratio" fk to represent the mutual information between the context latent representation ct and future frame xt+k: fk(xt+k, ct) ∝ p(xt+k|ct)/xt+k. After the encoding of recurrent neural networks, zt and ct can both be chosen for the downstream tasks as needed. The encoder and autoregressive model are trained by InfoNCE [145] as follows L=—-Ex|log fi(ti+n, cr)/ ye ex fi(xy; ¢t)], o8)) where X denotes the training dataset containing both positive and negative samples. The density ratio fk can be estimated by optimizing L. CPC v2 revisits and improves CPC [146] by pretraining on unsupervised representations, and its representation generality can be transferred to data-efficient downstream tasks. 20 Data x~P, R~G(z) Scores EG & B —+> Sy o | | S Loss 3 8 g le E iscrimi — 5 G 5 DiscriminatorD —+ Sxz x— 1 on vo [ of og Zz 3 ; ond —+ s, Latents Z~E(x) 2~P, Figure 8: The structure of the BigBiGAN framework [147]. # 4.3 Learning by Generation Although many existing applications are popular after the development of the GAN-based approach, the representation abilities inside the GANs are not entirely exploited due to the absence of a feature encoder. Thus, Bidirectional Generative Adversarial Networks (BiGANs) [48] is proposed to project data back into the latent space, which is useful for auxiliary supervised discrimination tasks via serving as feature repre- sentations. Based on BiGANs, BigBiGAN [147] first achieves the SOTA in unsupervised representation learning on ImageNet by adding an encoder and modifying the discriminator. As shown in Fig. 8 from [147], the traditional components of GANs (encoder € and generator G) are used to produce data-latent pairs, denoted as (x ~ Py,Z ~ E(x)) and (x ~ G(z),z ~ P,). The final loss ¢ is defined as the sum of data-specific term Sx, 8, and data-joint term s,,. The introduced discriminator D (Adversarially Learned Inference (ALI) [148], or BiGAN [48]) learns to discriminate between pairs from the raw data, latent distribution and encoded vector. # 4.4 Learning by Reconstruction The iGPT [149] and ViT [40] models have demonstrated the feasibility of adapting the pretext task of masked prediction using auto-encoder from language to image data. BEiT [150] is the first to demonstrate that autoencoder-based masked prediction can outperform DINO [151], a conventional SOTA method without pretraining techniques. Specifically, BEiT consists of two stages: token embedding with discrete variational autoencoder (dVAE) [152], and tokenizer training with masked image prediction. In the first stage, the original image is split into some patches and encoded using discrete tokens, which is different from BERT since image patches don’t have off-the-shelf tokens as words in NLP. In the second stage, the BEiT encoder takes a corrupted image containing unmasked and masked patches, and then the visual tokens of the masked patches are outputted to match the corresponding visual tokens from the fixed tokenizer. Despite its success, the separation between masked prediction and autoencoder training induces that the whole framework is not end-to-end and hinders learning effectiveness and efficiency. To migrate this issue, MAE [154] proposes an end-to-end simple solution by predicting the masked patches directly from the unmasked ones with the Mean Squared Error (MSE) loss. It’s worth noting that MAE uses a masking ratio of 75%, which is significantly higher than that of BERT (typically 15%). Abla- tion study suggests that higher masking ratios are beneficial for both fine-tuning and linear probing. Concur- rently, SimMIM [155] proposes a similar autoencoder-based solution as MAE, in which they also confirm 21 Vy CNN Non-param V2 — backbone Softmax 000 ae Vn 0 Memory . Bank 128D Unit Sphere Figure 9: The general pipeline for the Memory Bank Method [153]. that a higher marking ratio and leveraging random masking strategy helps improve performance. The major difference is how they partition the responsibility of representation encoding and pretext prediction in the autoencoder. Since the decoder of SimMIM is simple, the encoder of SimMIM synchronously conducts both of them. On the contrary, the encoder in MAE solely undertakes the role of representation encoding, and the decoder is responsible for pretext prediction. Recently, Meta AI announces the Segment Anything Model (SAM) [156] which prompts users to specify what to segment in an image, allowing for a wide range of segmentation tasks without the need for additional training. SAM employs an MAE pretrained ViT-H [40] image encoder that runs once per image and produces an image embedding, as well as a prompt encoder that embeds input prompts such as clicks or boxes. Following that, a lightweight transformer-based mask de- coder predicts object masks from image and prompt embeddings. The results show that SAM can generate high-quality masks from a single foreground point that are typically just modestly inferior to the manually annotated ground truth. It routinely achieves strong quantitative and qualitative outcomes on a wide range of downstream tasks using a zero-shot transfer approach and prompt engineering. Leveraging ViT in MAE poses a serious inefficiency issue, where decreasing the patch size results in a quadratic increase in computing resources. To address the problem, there are two important solutions: (1) hierarchical ViT and (2) local attention. In the first direction, hierarchical ViT (hViT) was introduced, which utilizes a shrinking pyramid structure and techniques like shifted windows [157] to reduce computational de- mands. Unfortunately, hViT cannot be directly applied to enable MAE pretraining because the local window attention used in hViT makes it difficult to handle randomly masked patches as in MAE. Recently, Uniform Masking MAE (UM-MAE) [158] is proposed to empower MAE with hViTs, which introduces a two-stage pipeline: sampling and masking. It starts by randomly sampling a portion of patches (25% reported in the paper) from each block, and then follows by masking additional patches on top of the sampled ones. The first step helps to maintain common elements across different local windows, while the second step prevents shortcuts for pixel reconstruction from nearby low-level features, making the task more difficult. Another direction to improve efficiency focuses on reducing the input size by putting the attention of the network into some local small windows of the image. Motivated by the observation that local knowledge is sufficient for reconstructing masked patches, Local masked reconstruction (LoMaR) [159] was proposed. Rather than using the entire image for mask reconstruction, LoMaR samples a number of small windows and focuses attention on local regions, which outperforms MAE on downstream tasks in terms of learning efficiency. # 4.5 Learning by Memory Bank Non-Parametric Instance Discrimination (NPID) [153] is the first method that utilizes the instances to learn representations for downstream tasks. The detailed pipeline is shown in Fig. 9. The feature representations are stored in the memory bank for the convenience of computation because the instance-level classification objective needs all images in the training dataset. For any image x with feature representation v = fθ(x), 22 Transformation View Encoder MLP Projection .------7-77-77 error F Memory bank Input image ' t v >| fe "| Ie a tel {Similar >» my f Pa | ff | of a |i my) Figure 10: Summary of all two-stream models, including contrastive learning and memory-bank-based methods. its probability of being recognized as i-th example is: ilv) — exp(vt ” oap(yl P(ily) = exp(viv/r)/¥ 7 erly; ¥/7), (12) where vi or vj is the representation of i-th or j-th sample, which serves as a substitute for the parametric class prototype (i.e., weights of a classifier). Addtionally, τ is the temperature parameter borrowed from the knowledege distillation [160]. Local Aggregation (LA) [161] is another method that trains a CNN encoder to embed raw images into a lower dimension space – embedding space. When a metric of local aggregation is maximized, similar data instances move together in the embedding space while dissimilar instances move apart. [162] is proposed to argue that semantic representations are invariant under pretext transformation tasks. Suppose the original view and transformed view of images are denoted as I and I t, respectively. These sample views are fed into a CNN encoder, and the total empirical loss on the training dataset D can be defined as: Liotal (0; D) = Ey ia rep L(Vi, vn)| ; (13) where 7 denotes the different transformations of images. The loss encourages the representation of image I to be similar to that of I‘, and the representation of I t to be dissimilar to that of different images I’, as shown in the dotted box of Fig. 10. Therefore, more negative sample pairs contribute to improving the scalability of the gradient and lead to the final learned encoder with stronger representation ability. That is the reason why the memory bank is introduced to store more previous representations for subsequent comparison. # 4.6 Learning by Sharing SSL prefers using two encoder networks for the different data augmentation, and then pretrains the param- eters by maximizing the distance between negative pairs or minimizing the distance between positive pairs. Fig. 10 shows the two-stream models for all contrastive learning frameworks. The transformation t on the orginal input image I generates the view v, similarly, its counterpart t’ generates v’. In general, two different or same encoders fg and te are used to extract contrastive representations. The subsequent MLP heads gg and I are used to learn more combinations that are beneficial to the contrastive loss. It is noticed that MLP and memory bank could be removed or preserved under different settings. In terms of the shared encoder, SSL can be divided into two categories: 1) Soft Sharing that two encoders share with similar but different parameters (fg # fos 2) Hard Sharing that two encoders maintain the same architectures and parameters (fo = fo. 23 xmery __iy Encoder q Similar: Contrastive — key ke imilarity ess 0 key xy Momentum -—» ky — > key Encoder <——_ ky Figure 11: The general pipeline of MoCo [163], which is also a two-stream framework with different pa- rameters. Soft Sharing. Facebook AI Research (FAIR) presents Momentum Contrast (MoCo) [163] by using mo- mentum to control the slight difference between two encoders. As shown in Fig. 11, one of the encoders is served as a dictionary look-up task that generates a queue of encoded data samples {k0, k1, · · · }. Another encoder generates encoded query {q0, q1, · · · } with the training batch updated. The similarity is measured by the dot product of the new coming encoded query q and the encoded keys stored in the dictionary queue. Suppose there are K keys stored in the queue before the new key comes. The K keys are treated as negative samples to the query of the new key. To combine the contrastive loss on both negative and positive samples, InfoNCE Loss [145] is used for the pretraining in MoCo. The key design in MoCo for soft parameter sharing is called momentum update. He et al. [163] suggest that the direct parameter change of key encoder (i.e., momentum encoder) to query encoder loses the necessary consistency and yields poor results. The momentum encoder parameter θk is updated as: θk = mθk + (1 − m)θq, (14) where the query encoder parameter θq is learned directly from the gradients of new coming instance, and m ∈ [0, 1) is a hyper-parameter that controls the consistency (θk is more consistent if m is closer to 1). Inspired by the design of SimCLR [164], in MoCo v2 [164], the FAIR team introduces an MLP projec- tion head after encoders and utilizes more data augmentation techniques to improve the performance. The further improvements are from that: 1) embedded linear classifier bridges the gap between unsupervised and supervised pretraining representations; 2) more contrastive samples are feasible from both the larger training batch and stronger data augmentation. DeepMind proposed Bootstrap Your Own Latent (BYOL) [165] that contains representation, projection, and discrimination stages to achieve a new SOTA without using negative samples. They understand the discrimination between different views of raw images as necessary prevention from collapse during the pretraining. However, they argue that many negative samples are not indispensable to prevent this collapse. As shown in the left part of Fig. 10, there are two streams in BYOL with different parameters. The online network (top green) updates parameters by comparing the prediction generated itself and the regression target provided by the target network. Then the parameters of the target model (bottom red) are updated the same as Eq. (14), i.e., ξ ← τ ξ + (1 − τ )θ, where τ is the target decay rate to control the degree of parameter changing in the target network. Therefore, the target network can also be understood as a momentum encoder. Here, ξ in the target model is the parameter θk in momentum encoder, and θ in the online network denotes the parameter θq in the query encoder. Hard Sharing. SimCLR [166] is proposed by Brain Team in Google Research which utilizes the hard parameter-sharing architecture. This simple framework can also be concluded in Fig. 10, in which we can 24 Input Images > Encoder 4 ——:, Momentum ——> Encoder Figure 12: The key pipeline for the DeepCluster model [49]. see that representations of different views of the same image are learned in the network f (·). This base encoder shares the parameters with each other. Thus, memory bank and momentum setting to learn key and query encoders are not necessary, which contributes to a simpler backbone architecture and easier learning strategy. The loss function to maximize the similarity between different views of the same image (positive pairs) is defined as 6.5 = — log exp(sim(%, z;)/T)/ a Ipzqerp(sim(zi, 2n)/T), (15) where (i,j) is a pair of positive samples, 7 is an introduced hyper-parameter called temperature parame- ter [153], and 1,45 € {0, 1} is an indicator function to control the denominator containing only negative pairs. To avoid the dependence on a large number of explicit pairwise feature comparisons, Swapping As- signments between multiple Views of the same image (SwAV) [167] is proposed as an online algorithm by Inria and FAIR. SwAV introduces clustering to substitute the previous comparison between pairs, which gains more memory with the help of non-queue architecture. In this method, the clustering prototype joins the computation of the defined loss function. This prototype is encoded as the concatenation of vectors learned through the backpropagation in CNNs. Thus, there is no need for SwAV to compare the encoded representations between different views. Based on the existing SwAV, a novel model called SElf-supERvised (SEER) [168] aims to learn a pre- trained encoder from any random image and unbounded dataset in the wild. The base network is RegNetY architectures [169] trained with the SwAV SSL method [167]. This method proves that the SSL is not specific to a curated dataset such as ImageNet, and the scalability of recent RegNet releases the limitation of traditional backbones such as ResNet. In addition, this method encourages the research community to explore more backbones suitable for universal SSL. Attracting the attention in the recent SSL, FAIR conducts empirical experiments on the SSL by utilizing the structure of Simple Siamese (SimSiam) networks. This method [170] can avoid the design of negative sample pairs, large batches (or memory banks), and momentum encoders in traditional contrastive learning. The two encoders in Fig. 10 with identical parameters that process two different views ¢ and t’ of image x are substituted by the only siamese network. MLP predictor g is used for one of the view representations, and then the stop-gradient operation is applied to another view representation. # 4.7 Learning by Clustering DeepCluster [49] is the first model that adopts the clustering algorithm for large-scale dataset learning. This method groups the representations into different clusters and labels these clusters as supervised signals to 25 Table 2: Summary of the PFMs in CV. Downstream Task1 Architecture Pretext Task cla, rec CNN discrimination cla, det, clu CNN context prediction cla, det, seg, inp GAN, CNN inpainting cla, det, seg CNN colorization cla, det, seg, ret CNN Jigsaw puzzles cla, det, seg CNN channel prediction cla, det, seg, ret CNN counting cla, det CNN noise cla, det, seg GAN, CNN generation cla, det, seg CNN Jigsaw puzzles cla, det, seg NIN, CNN rotation cla CNN, GRU patch overlapping cla CNN instance discrimination cla, det, seg CNN clustering rec, det CNN local aggregation gen, cla GAN, CNN generation cla CNN transformation cla CNN discrimination cla, seg CNN clustering cla, det CNN patch overlapping cla, rec, dec CNN Jigsaw puzzles cla, rec, dec, pos, seg CNN discrimination cla, det CNN clustering cla, dec CNN discrimination cla, det, seg CNN self-labelling cla CNN discrimination cla CNN self-distillation [160] cla, seg CNN view matching [178] cla, det, loc, seg CNN discrimination cla, det CNN, Transformer cropping cla, det, seg CNN discrimination cla CNN, Transformer discrimination cla, rel CNN discrimination cla, det CNN clustering cla, det, seg CNN discrimination cla CNN discrimination cla, seg CNN, Transformer discrimination cla, det, seg CNN, Transformer discrimination cla, det, seg CNN, Transformer token prediction cla, seg Transformer token prediction cla, det, seg Transformer reconstruction cla, det, seg Transformer reconstruction cla, det, seg Transformer reconstruction cla, det, seg Transformer reconstruction cla, det, seg Transformer reconstruction cla, det, seg Transformer reconstruction det, gen, seg Transformer reconstruction Year 2014 2015 2016 2016 2016 2017 2017 2017 2017 2018 2018 2018 2018 2018 2019 2019 2019 2019 2020 2020 2020 2020 2021 2020 2020 2020 2020 2020 2020 2020 2020 2021 2021 2021 2021 2021 2021 2021 2021 2022 2022 2022 2022 2022 2022 2023 2023 1 Downstream task types: classification (cla), recognition (rec), detection (det), localization (loc), segmentation (seg), clustering (clu), inpainting (inp), retrieval (ret), generation (gen), pose estimation (pos), reinforcement learning (rel). pretrain the parameters of the backbone network. It demonstrates SOTA performance on a wide range of standard transferred tasks used in unsupervised learning. When it comes to the connection between contrastive learning and clustering, SwAV [167] has uti- lized prototypes that serve as a clustering center to help classify the sample pairs during pretraining, while Prototypical Contrastive Learning (PCL) [171] first targets bridging contrastive learning with clustering. Compared to instance discrimination as pretext tasks learning low-level representations, clustering can help to encode more semantic information. Then more semantic-based downstream tasks will benefit from it. As shown in Fig. 12, prototypical contrastive learning uses prototypes to substitute one of the views of generated samples in NCE loss (Eq. (15)), which is the proposed ProtoNCE loss in PCL. In addition, PCL is also a method based on soft parameter sharing, in which the momentum encoder is updated as Eq.(14). # 4.8 Summary This section extensively investigates recent progress in PFMs on images for representation learning, from the early perspective of designing pretext tasks for self-labeling to present contrastive loss-based SSL. The pipelines of the main methods are clearly illustrated. We hope this section can prepare the incoming re- searchers to acquire a basic understanding of this novel area and some worthwhile research direction. We 26 (a) Graph Information Completion (GIC). (b) Graph Property Prediction (GPP). Figure 13: Graph Information Completion (GIC) and Graph Property Prediction (GPP). believe the powerful generalization ability of PFMs would extremely reduce training computation overhead by “pretraining once and transferring forever”. Recent transformer-based PFMs have gradually outper- formed traditional training from scratch on target datasets. This discovery will spur further exploration and research into this exciting field. # 5 PFMs for Graph Learning With the development of deep learning in graphs, the parameters (i.e., graph embedding) of the model began to increase rapidly. Therefore, large-scale labeled data is needed for training the models to avoid under-fitting or over-fitting. However, the cost of constructing large-scale labeled datasets for graphs is too subjective, expensive, and time-consuming, especially in domains that require professional knowledge and timeliness. While some semi-supervised approaches have temporarily mitigated the reliance of graph embedding models on label scale, they have not fundamentally resolved this problem. In recent times, researchers have turned their attention towards the application of PFMs in the field of graphs, inspired by their success in CV and NLP. However, for most graphs, obtaining large-scale pretraining data directly is challenging due to the unique nature of information such as nodes and edges. Therefore, recent studies have focused on utilizing the inherent information of a graph’s attributes, topology, and community to enhance the effectiveness of the node’s features. We have summarized the graph-related PFMs in Table 3. # 5.1 Learning by Graph Information Completion The essential motivation of pretraining based on graph information completion (GIC) is to mask part of the information of the input graph data and recover the masked information based on the unmasked graph data, so as to pretrain the graph embedding, as shown in Fig. 13. Similar ideas appeared earlier in the field of image and text processing. For instance, in image processing, information such as image pixels and colors are recovered to pretrain the image encoder; in text processing, many methods implement pretraining of word embeddings and encoders by recovering part of the information in a sentence based on context words. These methods inspire the design of graph completion tasks on graph PFMs. Among them, You et al. [188] are inspired by image inpainting, and first propose to cover them by removing the features of the target nodes, and then recover/predict the features of the masked nodes. In order 27 (a) Context Consistency. (b) Self Consistency. Figure 14: Graph Consistency Analysis (GCA). to recover/predict the masked information, GraphCompetion [188] is achieved by providing GCNs with unmasked node features (limited to the 2-layer GCNs of the second-order neighbors of each target node). The purpose of GraphCompetion’s pretraining is to help the model better perform feature representation and teach the model to extract features from the context. You et al. [188] propose the attribute mask task (namely, AttributeMask), which masks node attributes randomly, and then requires the self-supervising module to reconstruct the masked attributes. Jin et al. [189] think deeply about SSL on graph data, and propose the edge mask task (namely, EdgeMask), seeking to develop self-supervision in pairs based not only on a single node itself but on the connection between two nodes in the graph. In particular, EdgeMask randomly masks some edges and then asks the model to reconstruct the masked edges. In short, EdgeMask is expected to help GNN learn local connectivity information. Hu et al. [190] propose a PFM that masks node and edge attributes and then predicts this masked information based on the adjacent structure. # 5.2 Learning by Graph Consistency Analysis Different from the aforementioned methods that focus on individual elements in the graph, graph consis- tency analysis (GCA) mainly explores the consistency of the distribution of two elements in the graph. Specifically, the consistency of two elements with similar semantics should be significantly stronger than two elements with unrelated semantics, and this characteristic can be used to pretrain the graph model. Ac- cording to the judgment object of consistency, such methods can be roughly divided into the following three categories. Context Consistency Based on the early homogeneity assumption, a mass of graph models tends to project contextual nodes to similar positions in semantic space. Such consistency of the context in the graph is also applied to the pretraining graph model, which attempts to adjust the node representation by capturing the distribution characteristics of the nodes in the context, as shown in Fig. 14 (a). Random walk is an efficient method to acquire context. It can capture the distribution characteristics of different perspectives in the context by designing a variety of walk strategies. The DeepWalk [191] adopts a truncated random walk strategy to represent the node context as the form of a sequence of nodes. By introducing the idea of NLP into the network embedding model, DeepWalk regards the node sequence as a “sentence” and models it based on the skip-gram model, providing an unsupervised and scalable training method for node representation. Furthermore, on the basis of DeepWalk, node2vec [192] uses two different parameter-controlled random walk strategies to obtain deviated node sequences to fully capture the context information. Different from randomly sampling nodes from the context, some recent methods directly consider the 28 relationship between the node’s k-order neighbor distribution (as positive examples) and non-adjacent nodes (as negative examples), and use this to train the graph model. LINE [193] respectively proposes first- and second-order proximity to describe the local similarity between pairs of nodes in the graph from different perspectives, and uses it to optimize node representation. Meanwhile, LINE uses negative sampling and edge sampling techniques to optimize the second-order traversal and excessive training storage overhead. VGAE [194] introduces a variational autoencoder to encode graph structure data, and model the node first- order neighbor through a GCN encoder and a simple inner product decoder. Self Consistency In the field of NLP and CV, contrastive learning as an efficient self-supervised mech- anism is widely used in the pretraining of models. In fact, the internal comparison mechanism of such methods is based on the mutual information estimation of the original graph data and the augmented graph data to maintain the consistency of the data itself, as shown in Fig. 14 (b). Inspired by contrastive learn- ing, some studies have begun to generate augmented samples of original data samples in the graph model. Among them, two augmented samples from the same original sample are regarded as positive pairs, and two augmented samples from different original samples are regarded as negative pairs. For node-level tasks, GCC [195] devises the pretext task as subgraph instance discrimination in and across networks. And GCC also enhances the ability of GNNs to learn the intrinsic and transferable struc- tural representations by introducing contrastive learning. Specifically, GCC samples subgraphs from the whole graph as augmentations via random walk with restart and artificially designs positional node em- bedding as node initial features. As a novel graph representation learning model, GCA [196] incorporates various priors for topological and semantic aspects of the graph to achieve adaptive contrastive augmen- tation. Specifically, GCA devises an enhancement scheme based on node centrality measures to highlight important connection structures, while corrupting node features by adding noise to specific nodes to lead the pretraining model to recognize underlying semantic information. For graph-level tasks, some studies have attempted to introduce more diverse contrastive learning strate- gies. Among them, You et al. [197] introduce four common graph augmentation tasks (i.e., node dropping, edge perturbation, attribute masking, and subgraph sampling) into the GL model based on underlying prior and propose a unified comparative learning framework: GraphCL. Meanwhile, GraphCL discusses in depth the role of data augmentation in comparative learning and gives experimental demonstration that joint mul- tiple augmentation strategies can improve model performance. Cross Scale Consistency Unlike the above two methods that consider the consistency of elements in the same scale, contrasting elements in graph data of different scales can also be used to train graph models, e.g., node-subgraphs. Most of such methods have the idea of maximizing mutual information [198, 199]. Specifically, the readout function is usually used to obtain the summary of the graph/subgraph, and the MI estimator can be calculated using the Jensen-Shannon divergence. As a representative method, DGI [200] relies on maximizing the MI between the patch representation and the summary of the corresponding high-level graphs, which are all derived using the established graph convolutional network architecture, to learn the node representation. To generate negative samples on a single graph, DGI corrupts the original graph by randomly scrambling node features while keeping the structure unchanged. Similarly, Hassani and Khasahmadi propose CMVRL [201], which generates an addi- tional structural view of a sample graph based on graph diffusion. The sample graph and a regular view are sub-sampled together, and the node representation and graph representation are learned based on two shared MLPs, and then contrast learning is achieved through the consistency loss provided by the discriminator. SUBG-CON [202] samples a series of context subgraphs from the original graph and inputs them to 29 the encoder to obtain the pooled central node and subgraph representation. For the specified node, the context subgraph is expressed as a positive sample, and other randomly sampled subgraphs are expressed as a negative sample. The contrast loss of the latent space will force the encoder to identify positive samples and negative samples in order to distinguish different nodes based on regional structure information. # 5.3 Learning by Graph Property Prediction Considering the attribute and structural information of the graph as the target of information completion, pretraining based on graph property prediction (GPP) can also be used to build the graph model in different forms. One of the most common methods is to generate self-supervised signals by exploring the auxiliary property in the graph data and to take the graph property prediction task as the pretraining task of the graph model. According to the different settings of the pretext task, it can roughly classify two categories: property regression and property classification. Property Regression (PR) In the graph model, different from the GIC mentioned above, property re- gression primarily focuses on mining the relationship between the broader numerical structure and property attributes within the graph. Specifically, this branch of methods extracts richer self-supervised signals in graph data for pretraining graph models. For example, similar but different from masking node attributes, the goal of NodeProperty [189] is to predict each node’s auxiliary property in the graph, e.g., degree, local node importance, and local clustering coefficient. In other words, NodeProperty is used to encourage GNN to capture richer local structural infor- mation while optimizing the specific downstream tasks. Specifically, NodeProperty regards the node degree as a representative local node property, i.e., self-supervised signal, and takes other node properties as future work. Meanwhile, NodeProperty emphasizes that the intuition of devising self-supervised pretext tasks re- lated to local node property is to ultimately guide the feature embedding of GNN (i.e., node representation) to save this information, which relies on the assumption that the node property information is relevant to the particular task. Property Classification (PC) Different from the property regression task, the task of property classifi- cation is usually implemented by defining pseudo-labels based on a certain distribution in the graph data, which is a typical self-supervised method. Among them, the structure density, similarity of node attributes, and difference between local and global distributions are the most commonly used. We will briefly introduce the application of such methods in GL pretraining. Among these methods, clustering is the most common and effective source of pseudo-labels. Among them, M3S [203] designs a multi-stage training strategy, using the idea of graph clustering to iteratively train the graph encoder, achieving enlarged labeled data with virtual labels in the case of very small sam- ples. You et al. [188] further propose two pretraining strategies. Among them, Node Clustering assigns K (hyper-parameter) pseudo labels to nodes based on attribute clustering and pretrain node representation by node classification. In addition, You et al. also present Graph Partitioning based on the topology density assumption. In Graph Partitioning, the nodes of a graph are divided into approximately equal K (hyper- parameter) subsets to minimize the number of edges connecting nodes among subsets, and then pseudo labels are provided for nodes. In addition to clustering methods, some researchers generate pseudo labels based on other statistical characteristics of graph data. For instance, in the molecular field, Rong et al. [204] use the molecular bonds of subgraphs and related statistical information to guide GNN to learn Context-Sensitive Properties (CSP) 30 and then apply them to prediction. Rong et al. [204] propose a Motif Prediction (MP) task, which can be expressed as a multi-label classification problem, in which each motif corresponds to a label. Specifically, let’s assume that K motifs in molecular data are considered. For a specific molecule (abstracted as graph G), they use RDKit to detect whether each motif appears in G, and then take it as the target of the motif prediction task. # 5.4 Learning by Masked Autoencoder The masked autoencoder (MAE) is first applied in MAGE [205], the masked autoencoders for self-supervised learning on graphs. Following MAE [154], MGAE operates on a partial network structure (without masked edges) that is based on convolutions. Besides, the decoder of MGAE is designed to model the cross- correlation between the head and tail nodes of an anchor edge. Empirical results demonstrate that MGAE performs better than traditional graph autoencoders and graph SSL approaches. Furthermore, GMAE [206] extends this approach by using a transformer instead of convolutions and reconstructing the features of masked nodes rather than masked edges. In addition to empirical improvements, MaskGAE [207] further provides theoretical justifications for the potential benefits of masked graph modeling. Designing algorithms to accommodate graphs of various complex properties is a promising direction. For instance, to tackle the heterogeneous graphs scenario, HGMAE [208] proposes meta-path masking and adaptive attribute masking with a dynamic mask to enable effective and stable learning on complex graph structure. Moreover, several training strategies are developed, including meta-path-based edge reconstruction to incorporate complex structural information, target attribute restoration to utilize various node attributes, and positional feature prediction to encode node positional information. Besides dealing with more complex graph structures, how to improve the learning efficiency of MAE on graph data remains an open question. # 5.5 Other Learning Strategies on Graph Data In addition to the above methods, there are lots of pretraining methods that use relatively novel or hy- brid strategies. For example, CG3 [209] generates an improved node representation by designing a semi- supervised consistency loss to maximize the consistency between different views of the same data or data from the same category. Next, CG3 uses the graph generation loss related to the input feature to extract the potential deterministic relationship between the data feature and the input graph topology as a supplementary supervision signal for SSL. Based on the attention mechanism, Graph-Bert [210] trains itself to reconstruct node attributes and topological structure with sampled linkless subgraphs within their local contexts. GMI [211] extends the traditional mutual information computing idea from the vector space to the graph domain and proposes to jointly maximize feature mutual information (between the node’s embedding and raw features of its neigh- bors) and edge mutual information (embedding of two adjacent nodes) for graph representation learning. GPT-GNN [212] proposes a self-supervised graph generation task to guide itself to capture the topological and semantic attributes of the graph. GPT-GNN roughly divides the possibility of graph generation into attribute generation and edge generation to untangle the intrinsic dependence between node attributes and graph topology. # 5.6 Summary In the graph model, as traditional feature learning methods are often accompanied by information loss in the process of feature learning, and the information taken into consideration is relatively one-sided, the 31 Table 3: Summary of PFMs in GL. Year Conference Method Pretext Task Encoder Code 2014 KDD DeepWalk [191] Shallow NN___https://github.com/phanein/deepwalk 2015 WWW LINE [193] Shallow NN___ https://github.com/tangjianpku/LINE 2016 NeurlPS VGAE [194] GCN = 2016 _KDD node2vec [192] Shallow NN___ https://github com/aditya-grovermode2vec 2017___NeurlPS GraphSage [214] Shallow NN__ https://github.com/williamleil/GraphSAGE 2018 ICLR DGT [200] GCNISAGE __ https://github.com/PetarV-/DGI 2020 ICML GraphCompetion [188] GCN https://github.com/Shen-Lab/SS-GCNs 2020 ICLR ‘AttMasking [190] GCN hittp://snap stanford edu/gnn-pretrain 2020 ICML AttributeMask [188] GCN htips://github,com/Shen-Lab/SS-GCNs 2020 arXiv EdgeMask [189] GCN hitips://github.com/ChandlerBang/SellT: 2020___arXiv NodeProperty [189] GCN hitips://github.com/ChandlerBang/Self Tas 2020 AAAT MBS [203] GCN = 2020 ICML Node Clustering [188] GCN https://github,com/Shen-Lab/SS-GCNs 2020 ICML Graph Partitioning [188] GCN https://github.com/Shen-Lab/SS-GCNs 2020 __NeurlPS CSP [204] GCN = 2020 NeurlPS MP [204] GCN = 2020 NeurlPS SELAR [215] GNN hittps//github.com/mivlab/SELAR 2020 KDD GCCTI95] GIN hittps://github.com/THUDM/GCC 2020 NeurlPS GraphCL [197] GCN htips://github.com/CRIPAC-DIGIGCA 2020 ICML CMVRL [201] GCN = 2020 ICDM SUBG-CON [202] GCN hittps://github.com/yzjia0/Subg-Con 2020 ICLR InfoGraph [216] GCN https//github.com/fanyun-sun/InfoGraph 2020 AAAT DMGT [217] GCN hitips://github.com/pcy 1302/D MGI 2020__arXiv Graph-Bert [210] Transformer __https://github.com/jwzhanggy/Graph-Bert 2020 WWW GMI [211] GCN = 2020 KDD GptGNN [212] GNN hittps://github.com/acbull/GPT-GNN 2021 ICME JOAO [218] GCN htips://github.com/Shen-Lab/GraphCL _Automated 2021___AAAT CSSL [219] GCN htips//github.com/UCSD-AIH/GraphSSL 2021 PAKDD GIC [198] GCN htips://github.com/emavro/Graph-InfoClust-GIC 2021 WWW SUGAR 1199] GCN hitips//github.com/RingBDStack/SUGAR 2021 ICML GraphLoG [220] GCN htips://github.com/DeepGraphLearning/GraphLoG 2021 WWW SLICE [221] GCN https//github.com/pnnl/SLICE 2021___WSDM BiGI [222] GCN hitips://github.com/caojiangxta/BiGI 2021 WWW GCA [196] GCN https://github.com/CRIPAC-DIG/GCA 2021__KDD HeCo [223] GCN hitips://github.com/Iiun-online/HeCo 2021 AAAT CG* [209] GCN - 2021 ICLR SuperGAT [224] GAT hittps://github.com/dongkwan-kim/SuperGAT 2021__KDD MoCL [225] Hybrid GNN https://github.com/illidanlab/MoCL-DK 2022 ArXiv MGAE [205] Maksed Edge Reconstruction GCN = 2022 KDD GMAE [206] Maksed Node Reconstruction Transformer __https://github.com/THUDM/GraphMAE 2022 Arxiv MaskGAE [207] Partial Maksed Node Reconstruction Transformer __https://github.com/EdisonLeeeee/MaskGAE obtained graph representation is relatively rough and loses mass information. People began to focus on the distribution of data and attributes in the graph data as self-supervised signals to pretrain the graph model so that it can capture more valuable information. By transforming the distribution of nodes, attributes, and edges in the graph into different pretext tasks, and using GNNs for modeling, the graph model can fully fit the original distribution of the input graph. In lots of unsupervised or semi-supervised scenarios, such pretrained graph models have been proven to benefit downstream tasks. Besides, federated training large graph models [213] can be a promising solution for building pretrained foundation models. Currently, with the in-depth study of contrastive learning strategies, some work has attempted to apply contrastive learning in different forms to the pretraining of graph models. Through the consistency analysis of context, self, and cross-scale, this kind of method greatly improves the performance of the pretrained graph model on different graphs. # 6 PFMs for Other Data Modality With the rapid development of the PFMs, except for text, image, and graph, the PFMs have also carried out a lot of research on speech, video, text-image, and cross-data. Besides, researchers have started investigating the unified PFMs that incorporate all three mentioned domains recently. Therefore, in this section, we introduce some other advanced and unified PFMs. 32 # 6.1 PFMs for Speech In the field of speech, wav2vec [226] obtains speech representation by capturing contextual information on large-scale unlabeled datasets, and fine-tuning on a few samples by noise comparison binary classification task, which greatly improves the performance of downstream tasks. Furthermore, vq-wav2vec [227] and wav2vec 2.0 [228] propose a discrete unsupervised pretraining method on the basis of wav2vec, discretizing the original continuous speech signal, so that the methods in the mature NLP community can be migrated and applied. Meanwhile, lots of research have tried to design different mechanisms to use the representation obtained by speech pretraining as the initial input, and apply it to different tasks, e.g., automatic speech recognition [229, 228], phoneme recognition [230], and speech synthesis [231]. In particular, the extensive application of spoken language understanding has promoted the research of joint pretraining of speech and text. For example, SpeechBERT [229] applies MLM to speech and text pairs to perform representation learning on discrete information. Unlike [232], which relies on a large amount of labeled data for joint pre- training, SPLAT [233] uses unlabeled speech data to pretrain the speech embedding module, and proposes a label-level alignment method suitable for label-level downstream tasks based on sequence alignment. Mu- sicBERT [234] is a pretrained model designed for processing music data. It was developed by training on a vast symbolic music corpus consisting of over one million songs. To improve the pretraining process with symbolic music data, MusicBERT employs several mechanisms, such as OctupleMIDI encoding and a bar-level masking strategy. Huang et al. [235] suggest incorporating a metrical structure in the input data, which allows Transformers to better recognize the hierarchical structure of music at the beat-bar-phrase level. AudioTransformer [236] is a model that enhances the performance of Transformer architectures by implementing certain techniques, such as pooling, which were previously used in convolutional networks. Verma et al. [236] demonstrate how they leverage multi-rate signal processing ideas based on wavelets to improve the Transformer embeddings and obtain better results. # 6.2 PFMs for Video Video is similar to the RGB features of image and sequence information of the text. Many meaningful explorations in self-supervised video representation learning can not only perform efficiently well in video datasets but also generalize to the learning in other areas. Odd-One-Out Networks (O3N) [237] is a tech- nique that targets to predict the odd video subsequence among real subsequences sampled from a video in a training dataset. The experiments are conducted by using different video-clip encoders for O3N to prove consistent improvements of this pretraining design. Similarly, Shuffle and Learn [238] aims to learn the correct temporal order from a sequence of frames in a video. However, Kim et al. [239] designed a new self-supervised task called Space-Time Cubic Puzzles to train 3D CNNs. This task requires a pretrained backbone to arrange permuted 3D spatiotemporal crops. The performance of downstream tasks proves that effective video representations have been learned while solving such puzzles. Inspired by the contrastive learning in images, many pretraining models in the video also utilize the con- trastive loss to learn video presentations for downstream tasks. Inter-Intra Contrastive (IIC) framework [240] can learn video representations by using positive and negative pairs generated from different videos. Specif- ically, different modalities in the same video are treated as positive pairs, and video clips from different videos as negative ones. Temporal Contrastive Pretraining (TCP) [241] is another contrastive method based on CPC to learn video representations. Different from the existing GAN-based method that generates fu- ture frames for the video directly, TCP can predict the latent representation of future frames of the video, which is better for long-term predictions. Sequence Contrastive Learning (SeCo) [242] is a novel method considering both intra- and inter-frame instance discrimination in sequence order-based task. 33 # 6.3 PFMs for Multimodal The multimodal PFM among text and image can be divided into two categories: single-stream model and cross-stream model. The single-stream model refers to integrating text information and visual information at the beginning of the model. The Cross-stream model refers to text information and visual information encoded by two independent coding modules, respectively. Then different modal information is fused by mutual attention mechanism. Single-Stream Model VisualBERT [243] inputs text and images into the model simultaneously, which are aligned and fused using Transformer’s self-attention mechanism. The input of the text is the same as BERT, and the input of the image is the image features extracted by Fasters-RCNN. VisualBERT also does pretraining and then fine-tuning the specific task. It adopts two pretraining tasks, namely MLM and sentence-image prediction, determining whether the input sentence describes the corresponding image. The structure of Unicoder-VL [244] is very similar to VisualBERT, except for the processing of the image. Unicoder-VL extracts the image feature through Faster-RCNN and concatenates the feature with image position-encoding mapping to the same space. It enhances the image label prediction task, which predicts the categories of images. The pretraining task of VL-BERT [245] is the same as Unicoder-VL. The image input of VL-BERT includes four parts: the image region features extracted by Fasters-RCNN, the location of the region in the original image, location coding, fragment encoding, and [IMG] encoding. Cross-Stream Model In ViLBERT [246], the text and image modes are first encoded separately, and their outputs go through a standard attention module. This module is based on the Transformer structure. Still, in the self-attention mechanism, each module uses its query to calculate attention with the value and key of another module to integrate the information between different modules. The model is pretrained on two tasks. The first task is the mask task, which is the same as BERT. On the image side, the goal of the task is that when the region image is masked, the classification distribution of the output of the model can be as consistent as possible with the output distribution of the model used to extract the region features (such as Faster-RCNN). The second task is the language image matching task. DALL-E is a series of deep learning models developed by OpenAI to generate images from natural language prompts. The first version of DALL-E uses a transformer-based architecture, similar to the one used in the GPT LMs, to process the textual prompts and generate image-like representations. The model is trained on a dataset of images and their associated textual descriptions based on GPT-3. DALL-E 2 [247] is the improved version by employing contrastive language-image pretraining (CLIP) [248] for capturing semantic association between image- text pairs and GLIDE diffusion model [249] for text-conditional image synthesis. Furthermore, GPT-4 is proposed by OpenAI recently. It is a large-scale multimodal model which adopts RLHF and demonstrates human-level performance on various professional and academic benchmarks. Based on the multi-modal data containing more available information than previous single-modality data, thus the performance of these models gets enhanced by combining with the SSL on the benchmark dataset. Cross and Learn [250] is the first method that reveals crossmodal information as an alternative source of supervision and obtains powerful feature representations from combining crossmodal loss and diversity loss in both RGB and optical flow modalities. Different from the existing methods that learn feature representations from only a single task in cross-domain datasets, Ren and Lee et al. [251] propose a novel deep multi-task network to learn more generalizable visual representations to overcome the domain difference and further utilize the cross-domain information in different tasks. In that paper, the cross-domain datasets are real and synthetic datasets generated by a GAN-based network, while the multiple tasks are the predictions of the surface normal, depth, and instance contour in RGB images. This model performs better 34 than any previous single-task-based SSL methods by learning general-purpose visual representations from cross-domain multi-task feature learning. Tian et al. [252] believe that a powerful representation is one that models cross-view factors from the perspective of humans view to understand the world. They propose Contrastive Multiview Coding (CMC) to learn a video representation by maximizing mutual information between different views of the same scene. # 6.4 PFM for Code Generation Code generation with LLMs involves using pretrained language models to automatically generate code based on natural language descriptions of a desired program. This approach has the potential to greatly improve the efficiency of software development by reducing the need for manual coding and allowing developers to focus on higher-level tasks. The technique involves training large-scale language models on vast amounts of natural language text and then fine-tuning the models on specific programming tasks. By inputting natural language descriptions of code, the model can generate code snippets that are syntactically and semantically correct. Code gen- eration with LLMs has been applied in various programming domains, including web development, NLP, and data analysis. The models used for code generation include GPT-4, T5, and Codex, among others. For example, Andrei et al. [253] have investigated and assessed the fine-tuning of transformer models for personalized code generation. Specifically, they have evaluated the effectiveness of various personalization techniques in the domain of generating unit tests for Java methods and learning to personalize for a specific software project. Shailja et al. [254] assess the capacity of LLMs to generate Verilog that is useful. To achieve this, pretrained LLMs are fine-tuned on Verilog datasets collected from GitHub and Verilog text- books. An evaluation framework is then constructed, consisting of test benches for functional analysis and a flow for testing the syntax of Verilog code generated in response to problems of varying degrees of difficulty. An open-source CodeGen LLM that has undergone fine-tuning has been shown to outperform the current leading commercial Codex LLM. The CodeGen [255] is a group of LLMs that have up to 16.1B parameters and can handle both natural language and programming language data. Additionally, they have released the training library JAX FORMER as open-source. Their work demonstrates that the model can perform as well as the previous state-of-the-art zero-shot Python code generation on HumanEval, showcasing the practical applications of the trained model. Synchromesh, introduced in the study by Poesia et al. [256], adopts a novel approach called Target Similarity Tuning (TST) to retrieve a small set of examples from a training bank. Then, Synchromesh utilizes these examples to train a pretrained language model and generates pro- grams by applying Constrained Semantic Decoding (CSD). CSD is a general framework that can restrict the output to valid programs in the target language. In this work, the authors show that the combined use of CSD and TST results in significant improvements in prediction accuracy, as well as preventing runtime errors. However, there are still some limitations to code generation with LLMs, such as the models’ tendency to generate overly verbose or inefficient code and their inability to handle complex programming tasks. Nev- ertheless, the technology has shown significant promise and has the potential to revolutionize the software development industry. # 6.5 SOTA Unified PFMs A big convergence of PFMs handling multiple modalities is emerging, such as backbone architecture, pre- training task, and model scaling up [29]. Therefore, many unified PFMs proposed by researchers arise. A unified PFM is a unified model pretrained on unimodal and multimodal data with single or multiple trans- 35 formers as the backbone, which has the ability to perform a large variety of downstream AI tasks, includ- ing unimodal tasks and multimodal tasks. There are currently three types of SOTA unified models based on model architectures. We defined them as the single-transformer model, multi-transformer model, and comb-transformer model. A single-transformer model refers to a PFM model which only has a large-scale transformer as its backbone, whereas a multi-transformer model refers to a PFM model having multiple transformers. A comb-transformer model is the PFM model with the combination of both single and multi- ple transformer structures. Single-transformer Model UNITER [257] is a large-scale PFM for joint image-text embedding, which consists of an Image Embedder, a Text Embedder, and a multi-layer Transformer. It first encodes visual features and bounding box features for image regions using Image Embedder and tokens and positions using Text Embedder. Then, a Transformer module is applied to learn generalizable contextualized embeddings for images and text through four pretraining tasks. Instead of applying random joint masking to both modalities, conditional masking on pretraining tasks is used. Six vision-language tasks are selected as the downstream tasks. Uni-Perceiver [258] is a single siamese model with shared parameters having the ability to process dif- ferent modalities regarding vision and language tasks. Different task inputs and targets are encoded into unified token sequences with modality-specific tokenizers, which are then decoded by a modality-agnostic weight-sharing Transformer encoder into the shared representation space. Any perception task is modeled as finding the maximum likelihood target for each input through the similarity of their representations. Uni- Perceiver is pretrained on unimodal and multimodal tasks. The evaluation results on various downstream tasks show that the performance is close to SOTA methods by conducting prompt tuning on 1% of down- stream task data. Gato [259] builds a single large transformer sequence model that works as a multimodal, multi-task, multi-embodiment generalist policy. It can perform various tasks using a single neural network with the same set of weights. Gato is trained on 604 tasks, where different types of data, such as images, text, proprioception, joint torques, and other discrete and continuous observations and actions, are serialized into a flat sequence of tokens, batched, and processed by the transformer. During deployment, sampled tokens are assembled into different actions based on the context. OFA [26] is a simple sequence-to-sequence learning framework with a unified instruction-based task representation that unifies various tasks. In the pretraining and finetuning stages, OFA requires no extra task-specific layers for downstream tasks to achieve Task-Agnostic. The Modality-Agnostic compute engine is a Transformer with the constraint that no learnable task- or modality-specific components are added to downstream tasks. OFA is pretrained on small-size image-text pairs to achieve crossmodal tasks while attaining highly competitive performances on unimodal tasks. UNIFIED-IO [27] is a sequence-to-sequence model using a unified architecture that performs large and diverse tasks. UNIFIED-IO is a transformer model where both the encoder and decoder are composed of stacked transformer layers. The unified architecture does not need specific task or modality branches, which is accomplished by homogenizing the input and output of each task into a sequence of discrete vocabulary tokens. It trains a single transformer-based architecture on over 90 diverse datasets in the vision and language fields. UNIFIED-IO is the first model to perform various tasks and produce strong results across 16 diverse benchmarks without finetuning. BEiT-3 [29] is a general-purpose multimodal pretrained model on language, vision, and vision-language tasks. The big convergence of BEiT-3 can be seen from three aspects, including backbone architecture, pretraining task, and model scaling up. It introduces a shared Multiway Transformer as backbone network 36 performing masked data modeling on both unimodal and multimodal data. To process different modalities, every Multiway Transformer block has a shared self-attention module, and a pool of feed-forward networks. It is a giant-size foundation model that contains 1.9B parameters. Experimental results show that BEIT-3 can outperform SOTA models on both vision and vision-language tasks. Multi-transformer Model FLAVA [28] is an alignment model that targets all modalities at once and aims at solving vision and language tasks, and vision-language tasks. It utilizes a common transformer model architecture to learn strong representations from unimodal and multimodal data. An image encoder transformer is used to capture unimodal image representations. A text encoder transformer is adopted to process unimodal text information. A multimodal encoder transformer takes both encoded unimodal images and text as inputs and integrates their representations for multimodal reasoning. During pretraining, masked image modeling (MIM) and MLM losses are applied to the image and text encoders, respectively. On the other hand, masked multimodal modeling (MMM) and image-text matching (ITM) loss are used over paired image-text data. For downstream tasks, classification heads are applied to the outputs from the image, text, and multimodal encoders, respectively, for visual recognition, language understanding, and multimodal reasoning tasks. FLAVA shows good performance on 35 tasks across different domains. A noticeable advantage is that smaller datasets it used compared with other models. Comb-transformer Model UNIMO [260] can learn both single modality and multimodalities with one model to achieve robust and generalizable representations. It employs multi-layer self-attention Transform- ers to learn general textual and visual representations simultaneously and unifies them into the same se- mantic space via cross-modal contrastive learning (CMCL). The main idea behind CMCL is to keep paired image and text representations close to the representation space while keeping non-paired representations far away. All of them are encoded by the same unified-modal Transformer in pairs or individually, and the representations of images and texts are extracted to compute the contrastive loss. # 7 Other Advanced Topics on PFMs As the number of parameters of the pretraining model increases, the pretraining model requires more mem- ory and computing resources. It increases the training cost of PFMs and limits their deployment on resource- constrained devices. Therefore, to improve the efficiency of the pretraining model, PFM improves compu- tational efficiency from the following two aspects: model efficiency and model compression. The model efficiency and compression of the PFM refer to simplifying the redundancy of model parameters and struc- ture. Under the condition that the task completion degree is not affected, the model with fewer parameters and a more concise structure is obtained. # 7.1 Model Efficiency Model efficiency devotes to exploring more efficient pretraining methods to pretrain large-scale PFMs with a lower-cost solution. More efficient learning algorithms require more effective training methods and more efficient model architecture. Traditional pretraining tasks may be inefficient. For example, the commonly used masked token prediction task requires the model to predict masked tokens based on context. However, the masked tokens in the samples are usually a subset of the input tokens, and the model can only learn from this part of the tokens, so the training efficiency is low. To solve this problem, ELECTRA [30] proposes an RTD task that predicts whether each input marker is replaced by other tokens, which enables the ELECTRA 37 to train against all input tokens. In addition to effective training methods, more efficient architecture can also improve the efficiency of PFMS. For most PFMS based on the Transformer algorithm, a more efficient model architecture can be obtained by reducing the complexity of the Transformer algorithm. # 7.2 Model Compression Model compression requires less computing resources and memory. It is a potential approach to reduce the model size and enhance computation efficiency. The model compression strategy can be divided into two ways: parameter compression and structure compression. The methods of parameter compression include parameter pruning, parameter quantization, low-rank decomposition, and parameter sharing. Parameter pruning refers to designing evaluation criteria for model parameters to delete redundant parameters based on a sizeable PFM. For example, Compressing BERT [35] prunes BERT before training while maintaining the performance equivalent to that of the original model. Parameter quantization is the quantization of model parameters from 32-bit full-precision floating-point numbers to lower-order numbers. For example, Q8BERT [84] uses 8-bit quantization to compress parame- ters fourfold with little impact on model performance. Low-rank decomposition is to reduce the dimension of a high-dimensional parameter vector into a sparse low-dimensional vector. Parameter sharing refers to the structured matrix or clustering methods to map model parameters and reduce the number of parameters. For example, the ALBERT [36] uses decomposition-embedded parameterization and cross-layer parameter sharing to reduce the parameters in the model. Structure compression refers to compact networks and knowledge distillation. A compact network means reducing the number of parameters and calculations by designing a new compact network struc- ture. Knowledge distillation refers to the transfer of knowledge from the larger teacher model to the smaller student model through the use of a soft label, etc. DistilBERT [261], for example, uses the knowledge dis- tillation method to compress BERT, reducing the size of the BERT model by 40% while retaining 97% of its language comprehension. # 7.3 Security and Privacy The security risks, social bias, and data privacy in PFMs become an important research topic. Qiu et al. [5] recognize that deep neural networks can be attacked by adversarial samples, which mislead the model to produce false predictions. Due to the excellent portability of pretraining models, they have been widely used in NLP, CV, and GL. However, it has been found that the pretraining model is susceptible to the influence of adversarial samples. A tiny interference of the original input may mislead the pretraining model to produce specific false predictions. Meanwhile, it is possible to recover the data samples by querying the PFMs which can cause privacy leakage. Generation Adversarial Samples The adversarial sample originates from the image. The adversarial samples of the image are hard to recognize with an invisible change. For example, only one pixel of the image is modified. Human beings do not easily detect such disturbance, but the neural network can identify the modified image, which is the original purpose of the adversarial sample. Some work has found that pre- trained LMs are vulnerable in some scenarios. Jin et al. [262] successfully attack the three target models of BERT, CNN, and RNN by generating natural adversarial samples, which indicates that the current language processing model still has a large room for improvement in terms of security. However, it is difficult to achieve due to the distinct discreteness of languages in NLP. In particular, the generation of adversarial sam- 38 ples in the text must take into account linguistic characteristics to ensure that the sample’s syntax and fluency are not harmed while affecting the model’s output. For example, [263] uses adversarial samples to attack the fine-tuning stage of the BERT model for text classification and entailment successfully. [264] combines the sememe-based word substitution method and search algorithm based on particle swarm optimization to generate adversarial samples. Model Defects Some unrelated human factors can also mislead the PFM to make wrong predictions. For example, [33] discovers that the performance of BERT is limited in the reasoning task due to utilizing false statistical information in the dataset, which dramatically affects the performance by destroying this property. [265] defines universal adversarial triggers. When triggers are connected to any input, it can induce the model to generate specific predictions. Backdoor Attacks There are still many methods to manipulate the predicted results of the pretraining model employing a backdoor attack. [266] demonstrates that it is possible to construct a weight poisoning attack in which pretrained weights are injected. After the fine-tuning stage, the backdoor is exposed. At- tackers manipulate model predictions easily by injecting arbitrary keywords. [267] shows that PFMs in NLP can be manipulated by modifying the model corpus. The “meaning” of new words or existing words can be controlled by changing their weight parameters. Defense Against Attacks The human-in-the-loop method [31, 32] has been proposed and applied to gen- erate more natural, efficient, and diversified adversarial samples. Some defense approaches have been pro- posed to defend against such attacks. [268] designs an auxiliary anomaly detection classifier and uses a multi-task learning procedure to defend against adversarial samples. On the other hand, some defects in the PFM may be inherited by the custom models in transfer learning, such as the adversarial vulnerabilities and backdoors mentioned above. To mitigate this issue, [269] proposes a relevant model slicing technique to reduce defect inheritance during transfer learning while retaining useful knowledge from the PFM. Data Privacy in PFMs LLMs and other PFMs have been trained on private datasets [270]. The re- searchers have discovered that by querying the massive LMs, it is feasible to recover specific training sam- ples. An adversary may, for instance, obtain IRC discussions and personally identifiable information. Even worse, because large models have so many parameters, it is simple for PFM to memorize or learn private information, making larger models more prone to attack than smaller ones. Many PFMs such as the LLMs have been trained on private datasets. The researchers have found that it is possible to recover individual training examples by querying the LLMs. For instance, an adversary can extract examples including per- sonally identifiable information, and Internet Relay Chat (IRC) conversations. Even worse, because of the billion parameters of large models, it is easy for PFM to learn private information, making the larger model more vulnerable than smaller models. We must take privacy-preserving measures into account during all PFM processes, including data processing, model training, model inference, and system deployment, in order to reduce the risks of privacy leakage. # 8 Future Research Challenges and Open Problems The PFM can avoid training models from the scratch, which is a breakthrough from weak AI to general AI. At present, due to the characteristics of PFM such as large-scale parameters, a large amount of training data, 39 and high computational complexity, there are still many technical challenges in PFMs. We summarize the future research challenges of PFMs from four perspectives: data, foundation, model design, and upstream and downstream tasks. Meanwhile, we point out some open problems in the future research direction. # 8.1 Challenges on Data Most pretrained datasets are for single modes and single languages. It is very important for the development of PFMs to construct pretrained datasets for multimodal, multi-lingual, and graph data. For the characteris- tics of these data, the existing technical challenges are as follows: Data Deficiencies Unlike NLP and CV, except for the reusable nodes in a few molecular and protein networks, most of the nodes and edges in the graph data do not have a large amount of unlabeled data for pretraining. Meanwhile, the pretraining research of the graph model is still in its initial state. Besides, data from the Internet of Things (IoT) will be enormous and contains rich physical world information. For example, inertial measurement unit sensor data can capture users’ social activity information [271, 272]. The theoretical basis, various definitions of the pretext task, and the augmented design of contrastive learning are all imperfect, and new research urgently needs to be supplemented. Multimodal PFM Some research work has been done on multimodal PFMs, such as text and image, text and audio, etc. These are mostly PFMs between two modalities. At present, the learning of multimodal PFMs requires new multimodal datasets, which demand the establishment of the data between different modes. Thus, the construction of multimodal datasets is also an urgent problem to be solved. Multi-lingual PFM The multi-lingual PFM solves the resource shortage problem in multiple languages, and it aids in the achievement of new improvements in QA, text summarization, low-resource neural machine translation, and so on. However, the current PFM is still a mask LM. To improve the performance of the multi-LM, some suitable new tasks need to be added. In addition, multi-lingual vocabularies are much larger than single-language vocabularies, resulting in a sharp increase in model parameters to be learned. # 8.2 Challenges on Foundation For a PFM, a theoretical foundation is essential to model performance, whether it is a “black box” or “white box” method. The foundation studied mainly includes theoretical foundation, semantic understanding, and explicable exploration. Lack of Theoretical Foundation SSL in CV learns the experience from the NLP. There is no profound theory to support all kinds of tentative experiments, and further exploration has no handbook. Although there are several theoretical analysis that tries to understand the collapse of pretraining or the generalization ability of the learning representation, the lack of theoretical foundation is still a huge cloud upon the head of SSL. Semantic Understanding Does the pretrained LM learn the meaning of the language, or just rely on cor- pus learning? Many models perform well on various datasets with helpful information that can be extracted, where some approaches even exceed human levels. However, the performance is poor on domain datasets or 40 relatively small datasets. The models cannot reach a better level of stability and match different downstream tasks. This means that the model cannot serve the real purpose of human language use. # 8.3 Challenges on Model Design Most existing structures of PFMs are tried for text, image, and graph. The primary method is to increase data, improve computation power, and design training procedures to achieve better results. How to make a trade-off between data, computing resources, and predictive performance is worth studying. Model Variety There are many attempts at model design, such as generation-based models in the CV area. However, GAN-based approaches are not popular for the following two reasons: 1) the discriminator has learned meaningful feature representations, but they are forgotten during training [273]; 2) the mode collapse causes the generator to output samples in singular mode to cheat the discriminator. As a result, although researchers attempt to apply GAN-based approaches on SSL for pretraining, the difficulties in the convergence of discriminator and divergence of generator hinder development and progress in this area. Model Compression With the wide application of the Transformer and the pretraining model showing a general trend of growth, the computational complexity of the pretraining model has become the focus of attention. Due to the huge hardware requirements of model training and other reasons, the high threshold makes it difficult for researchers to train from scratch. BERT-base and GPT-3 contain about 108 million parameters and 175 billion parameters, respectively. It is not conducive to the development of relevant research work. There are some works for pretraining model compression, such as ALBERT having fewer parameters and better effect than BERT-base. The improvement models still require powerful computing equipment, making them difficult to apply universally. Reducing the high computing cost is one of the main challenges in future research. Model Robustness Although many researchers have designed different pretext tasks for the pretraining, the main problem remains on how to design robust pretext tasks and judge the performance before large- scale computations. In addition, how to compare these proposed methods fairly is also a big issue. As for NLP, deep neural networks are vulnerable to adversarial inputs because of their linear characteristics. Although pretraining models perform well on different NLP tasks, most are based on deep neural networks, which generally have poor robustness. Operations such as cutting and rotating do not change the nature of the image in CV. In contrast, operations such as adding, deleting, and substituting a word in the text are likely to affect the semantics of the text. Therefore, how to improve the robustness of the PFM in NLP is a technical challenge. Model Anti-attack The PFMs are vulnerable to attack by adversarial examples, which can easily mislead the model to produce specific false predictions. It is difficult to process due to the unique discreteness of language in the NLP field. Thus, the current PFMs have huge room for improvement in model anti-attack. # 8.4 Challenges on Finetuning and Prompt The pretrained model in NLP, CV, and GL fields can achieve good performance in most upstream tasks, but not all good in downstream tasks for fine-tuning and prompt. How to achieve consistent results both on upstream and downstream tasks is still a challenge for the PFMs. 41 Saturation Phenomena Google Research [274] observed the nonlinear relationship between the perfor- mance of upstream and downstream tasks. The higher training accuracy with more data on the upstream tasks does not always lead to better performance on the target downstream tasks. This observation challenges the most intuitive understanding of the pretraining process. Even in the most extreme case, the performance of upstream and downstream is at odds. Pretext Task There are too many self-supervised tasks, also known as pretext tasks. The pretext task can be used for any downstream tasks, such as detection and classification. It is difficult to match the relationship between pretext tasks and downstream tasks. Task-based Graph Much of the pretraining on the graph is based on the task graph. Different tasks construct different graphs, where nodes need to be reused. This makes it impossible to pretrain on the graph by introducing as much data as NLP and CV. # 8.5 Open Problems for Future PFMs First of all, a big convergence of text, image, graph, and multimodal pretraining is expected. Till the survey is written, no work has considered the graph in their unified PFMs. All of the SOTA unified models mainly focus on the language, vision, and language-vision tasks, while neglecting the importance of the graph in the data domain. Second, a unified backbone architecture for unified PFMs in future research will become more popular. It can be seen that a unified PFM model which only has a large-scale transformer as its backbone, i.e., a single-transformer model, is more focused by researchers than other types of unified PFMs. Third, a unified PFM is expected to achieve SOTA transfer performance for all different tasks in all data domains, including text, image, graph, and multimodalities. Most unified PFMs are only outstanding in a single data domain, whereas the performance in other domains is not competitive. BEiT-3 [29] shows a great example in both vision and vision-language tasks towards this research direction. Besides, in terms of RL usage in PFMs, even though ChatGPT build the milestone in NLP, CV and GL do not have significant research published yet. More work in this direction is expected in the future. # 9 Conclusion Existing PFMs in text, image, and graph domains are principally summarized in this survey. Firstly, we introduce the basic components of NLP, CV, and GL. Then, we provide a summary of existing models designed for pretraining in the three domains and summarize the necessary information in terms of model structures. Furthermore, we study some other research for PFMs, including other advanced and unified PFMs, model efficiency and compression, and security and privacy. Finally, we present the main challenges and open problems in PFM research. 42 # A Basic Components # A.1 Basic Components on NLP Table 4: Commonly used notations on NLP and graph. NLP Graph Notations N wi |V | Hx −→ θf ←− θb θ ZN zT =t zT <t z m b1, b2 Descriptions The length of input text. The i-th word in input text. The word corpus size. The representation of the input sequence. The parameters for forward modeling. The parameters for backward modeling. The shared parameter in all permutations. The set of all possible permutations of T . The t-th element of z. The [1, 2, . . . , t − 1] elements of z. A permutation of T . The dimension of the feature vector. The bias values of the hidden layer and the output layer. Notations | · | G G V v E eij A T X Y D MGL Descriptions The length of a set. The set of graphs. A graph. The set of nodes in the graph. A node. The set of edges in the graph. An edge between vi and vj. The adjacency matrix of a graph. The set of node types in a graph. The feature matrix of a graph. The set of ground truth labels in a graph. The given graph data. The GL model. # A.1.1 Language Model With the rapid development of deep learning, LMs are more and more applicable to the pretraining of NLP models. The LM can estimate the probability of rationality of a paragraph of the text. There are two main types of LMs: statistical LM and neural network LM. Statistical LM The statistical LM is a mathematical model to solve the context-related characteristics of natural language from the perspective of probability and statistics. The core of statistical LMs is to determine the probability of a sentence appearing in a text. As the theoretical basis of the probabilistic LM, the N-gram model profoundly influences the subsequent LM. It plays a pivotal role in the field of the LM. The N-gram LM introduces the Markov hypothesis, which assumes that the probability of the occurrence of the current word only depends on the nearest n − 1 words. The maximum likelihood probability of a word wi can be calculated by | | | _. | | | _ C (Wi-n41; Wi-nt2s-++ , Wi) p(w; | wi, w2,.--,WNn) = p(w; | Wi-nt1, Wi-nta,+++,Wi-1) 7 7 7 ; <n C (wi-nt1, Wi-nt2;+++,Wi-1) (16) (16) where T = [w1, w2, . . . , wN ] is the text sequence and C(wi−n+1, wi−n+2, . . . , wi) is the co-occurrence frequency of (wi−n+1, wi−n+2, . . . , wi). The p (wi | w1, w2, . . . , wN ) is calculated according to the chain rule p(w, w2,...,wn) = NE (w; | wi, we,...,Wi-1)- (17) i=1 N-gram uses the probabilities of each word in the sequence to represent the co-occurrence probability of the whole text sequence. When N is large, it indicates a more vital constraint on the occurrence of the next word in the sequence and leads to more sparse frequency information. When N is small, the statistical results have higher reliability and better generalization ability, but the constraint will be weaker. 43 tons2 Tena | Toa ih Ro Ty DE - ee &- Fm fof fo FT cell ++ cell RNN + RNN +--+ RNN Layer Norm H* in HY | tanh | | | Bo cell + cell cell +++ cell cell cell ++ cell RNN + RNN +--+ RNN Feed Forward \ t cell + cell cell ++ cell H™ cell E Enns Fran Ea E,. Eo Ey E Ey, Ey ER FR Eye (a) Forward Feedback Neural Network (b) Recurrent Neural Network (c) Pre-Trained Model Figure 15: The model architectures of forward feedback neural network, recurrent neural network and Pretrained LMs. H 1,2, H 2,3 and H 1,3 are the weight matrices used to connect each layer. Neural LM The statistical LM adopts maximum likelihood estimation, which is intuitive and easy to understand. However, there are still problems such as a lack of long-term dependence, the rapid growth of parameter space and sparse data. Therefore, the neural network is introduced to map the LM to a continuous space. Neural LMs use distributed representations of words to model natural language sequences. Unlike class-based N-gram models, neurolinguistic models are able to recognize two similar words without losing the ability to encode each word as different from the other. It can be directly used for NLP tasks. It mainly introduces Forward Feedback Neural Networks (FFNN), Recurrent Neural Networks (RNN), and pretrained LMs. As shown in Fig. 15 (a), FFNN according to the all former words of x = [w1, . . . , wi−1] calculates the probability of wi. In order to predict the conditional probability of wi, x is sharing the projection matrix M ∈ R|V |×m to a continuous feature vector space according to the projection index, |V | is word library size, m is the dimension of the feature vector. The output is represented as y = b2 + H 1,3 x + H 2,3 x tanh(b1 + H 1,2 x ), (18) where H 1,2, H 2,3 and H 1,3 are the weight matrices used to connect each layer, and b1 and b2 are the bias values of the hidden layer and the output layer respectively. The structure of the FFNN contains only limited information about the foregoing and has some limita- tions on the length of the input sequence. Therefore, the RNN LM comes into being. As shown in Fig. 15 (b), RNN can accept input of any variable length. When the input window is moved, its internal state mecha- nism can avoid repeated calculation, and parameter sharing further reduces the number of model parameters. Therefore, compared with FFNN, RNN has a great advantage. The pretraining LM is to get a set of model parameters by pretraining some tasks. It initializes the model with these parameters and then trains to improve the model performance effectively. The commonly used pretraining models are fixed embedding (Word2vec [12], Glove [69], etc), variable embedding (Embeddings from LMs (ELMO) [275], Generative Pretrained Transformer (GPT) [50] and Bidirectional Encoder Repre- sentations from Transformers (BERT) [13], etc). Here, we give an example of the GPT model, as shown in Fig. 15 (c). It adopts a two-stage process. In the first stage, the Transformer decoder is used as the basic unit of the model to perform text prediction. In the second stage, the GPT is initialized differently for different downstream tasks, training the model and fine-tuning the parameters. # A.2 Basic Components on GL Due to the extensive use of graph data in many fields, some communities (e.g., chemistry, protein, and social network) have recently focused on the study of graph pretraining. These pretraining models encode 44 graph attributes, structures, and other information into node representations from multiple perspectives by designing different pretext tasks, which are used to optimize downstream tasks. In this section, we introduce the definition of the basic concepts of graphs, and then provide a formal definition of the PFM on the graph. # A.2.1 Notations and Definitions of Graphs Unless particularly specified, the notations used in this article are illustrated in Table 4. We use G = {Gi}N i to represent a set of graphs, where N represents the number of graphs. Depending to the graph’s definition of the edges and nodes, graph data can be classified into the following types. Definition 1. An unattributed graph is G = (V, E), where v ∈ V is a node, e ∈ E is an edge, and naturally E ⊆ V × V . Adjacency matrix A ∈ Rn×n represents the topology of graph G, where n = |V |. Ai,j = 1 denotes there is an edge between node vi and vj, otherwise Ai,j = 0. Definition 2. An attributed graph is G = (V, E, Xv, Xe), where Xv ∈ Rn×dv and Xe ∈ Rm×de are the feature matrices of nodes and edges, |V | = n, |E| = m, dv and de denotes the feature dimensions of node and edge. In fact, in most application scenarios, only nodes have attributes, and edges have no attributes or only weights. Definition 3. An undirected graph is G = (V, E), where ei,j ∈ E means an unordered node pair (vi, vj). In particular, the adjacency matrix A of the undirected graph is a symmetric matrix (i.e., Ai,j = Aj,i). Definition 4. A directed graph is G = (V, E), where ei,j ∈ E means an ordered node pair (vi, vj). Definition 5. G has a node-type mapping function fv : V → T v and an edge-type mapping function fe : E → T e. When |T v| = |T e| = 1, the graph G = (V, E) is a homogeneous graph. In other words, all nodes in G belong to a type, and all edges also belong to one type. Definition 6. When |T v| > 1 and/or |T e| > 1, the graph G = (V, E) is a heterogeneous graph. In particular, a heterogeneous graph must be an attributed graph. # A.2.2 Learning Settings on Graphs GL methods are usually used to solve machine learning tasks on graph data, and we introduce different settings (supervision mode and learning mode) for GL. Before that, we first provide the notations of the corresponding mathematical formulation of GL. C = {c1, c2, · · · , cK} is a set of target components defined in a graph set G (Gci ∈ G), and ci is associated with a corresponding ground truth label yi ∈ Y = {1, 2, · · · , Ny}, where K denotes the total number of target components, and Ny is the number of classes being predicted. Then the graph data can be represented as D = {ci, Gci, yi}K i , and a complete GL model MGL can also be determined by yi = MGL(ci, Gci). For instance, in a node classification task, ci is the node to be classified, yi denotes ci’s label in graph Gci. Similarly, in a node clustering task, ci is the node to be clustered, yi denotes the corresponding cluster label in graph Gci. Supervision Mode Depending on the source and scale of the training data, the supervision settings of GL can be divided into four types as shown in Figure 16. Supervised GL is the most common mode in the real scenario. Given the target component ci and the corresponding ground truth label yi, the goal is to minimize the loss function between the predicted label of the GL model (i.e., ypred = MGL(ci, Gci)) and the expected label yi of all ci. Compared with supervised learning, unsupervised GL refers to situations in which no 45 Labelled (Ground Truth) Unlabelled Labelled (Pseudo Label) Supervised Supervised Unsupervised f-Supervised Figure 16: Schematic of different supervision modes. labeled data is provided, only the attributes and structure distribution of graph data (i.e., (ci, Gci)) can be used. Self-supervised GL is a special case of both supervised and unsupervised learning. Specifically, self-supervised learning mainly uses pretext tasks (e.g., clustering, completion, and partition) to mine its own supervised information (i.e., pseudo-labels) from large-scale unsupervised graph data, and trains the GL model MGL through the self-supervised information, so that it can learn to the valuable features of downstream tasks. In other words, the supervised information of self-supervised learning is not manually labeled, but the pretext tasks automatically construct supervised information from large-scale unsupervised data for supervised learning or training. Semi-supervised learning is a combination of unsupervised and supervised learning, who aims at learning data distribution to predict unlabeled data to solve the problem of difficulty in obtaining labeled data in real scenarios. In GL, semi-supervised learning refers to the realization of pattern recognition given a few labeled data and mass unlabeled data. Learning Mode The GL model MGL is optimized by the given training samples, and adjusted on the validation samples to participate in the test. According to the visibility of the graph data at different stages, the learning settings of GL model MGL can be classified into two categories: inductive learning and trans- ductive learning. Definition 7. Inductive Learning, which is the most common setting in machine learning tasks, trains the model on labeled data and then tests on samples that have never appeared in the training stage. For- mally, given a training sample {(ci, G*%, yi}, {(¢7, 6°), where N; and N, are the numbers of labeled/unlabeled samples. Inductive learning learns a function f'"* : G++ Y so that f'"4 is expected to be a good classifier on the future graph data { (cp, G)}, beyond {(cj;, G) . Definition 8. Transductive Learning is different from inductive learning in that all samples are visi- ble during both the training and testing stages. Formally, given a training sample {(c, 6%, yi) }N4, {(cj, Go) yi, transductive learning learns a function f'™* : G'+” ++ Y"+" so that f'"® is expected to be a good classifier on the unlabeled data {(cj,G®) nae Under the supervised setting (including semi-/self-supervised), the unified classifier optimization meth- ods of inductive learning and transductive learning can be written as: K 1 . £= LLIN Ga) ” where L is the cross-entropy loss, ci can be node, edge or subgraph of its associated graph Gci, and f (·) θ denotes inductive/transductive function with parameter θ. Compared with using only one pretext task, some methods have designed some integration mechanisms to incorporate the advantages of multiple pretext tasks into a unified framework. 46 # B Traditional Learning Methods # B.1 Traditional Text Learning NLP is a research field that integrates linguistics and computer science. Its main research tasks include part-of-speech tagging, named entity recognition, semantic role labeling, machine translation, question an- swering, sentiment analysis, text summarization, text classification, relationship extraction, event extraction, etc. The LM can be considered the cornerstone of the downstream NLP tasks. It experiences four processes: grammar rule LM, probabilistic LM, neural network LM, and pretraining LM. A PFM trains on a large benchmark dataset to obtain a model which can solve new similar tasks, which has become a new hotspot in current LM research. Word representations play a significant role in downstream tasks, which is the basis of NLP. The N-gram model preprocesses text features and encodes adjacent N words as a group, which makes it overly depen- dent on the richness of the training corpus. Otherwise, data-sparse is likely to occur, and the computational complexity will increase exponentially with the increase of N . Neural Network LM (NNLM) [11] adopts the idea of word vector for the first time, and the low-dimensional word vector of distributed representation can solve the discrete problem caused by word embedding well. However, it is still challenging to solve the problem of high computational complexity. The computational complexity of the word2vec model is independent of the selected window size but is determined by the dictionary size and the word vector di- mension. Many downstream tasks can be significantly improved by training on a large corpus using word vector embedding after initial training. However, the problem of polysemy for the static word vector is still unsolved, and it still belongs to the shallow LM [276] [277]. Therefore, more effective models are urgently needed to deal with the dataset more flexibly. To capture high-level concepts of context, such as polysemy elimination, syntactic structure, etc. Neelakantan et al. [278] propose to learn multiple embeddings per word type. Zhou et al. [279] integrate the features on both dimensions of the matrix to enrich semantics by using subword information. Based on the Continuous Bag Of Words (CBOW) [12] in word2vec, Hui et al. [280] fine-tune the generated word vectors for emotion and obtain the word vectors containing both semantic meaning and emotional tendency, which significantly improved the performance in the Weibo sentiment classification task. Liu et al. [281] propose a model of hierarchical translation for machine translation. It uses the neural LM based on RNN as the word vector generation model. Liang et al. [282] propose an approach based on the double-layer self-attention mechanism for machine reading comprehension, and the model is divided into three parts: single document encoder, multi-document encoder, and answer predic- tion. In the single document encoder, the problem of the context information is represented by the Gated Recurrent Unit (GRU) model. Zhang et al. [283] propose an INDependent RNN (INDRNN) and attention mechanism for user intention classification, using word vectors generated by word2vec as input. The model introduces a word-level attention mechanism to effectively quantify the contribution of domain vocabulary to the intention category. # B.2 Traditional Image Learning There are several types of neural networks in the deep learning era, from the beginning of most famous convolutional neural networks (CNNs) to the subsequent Attention- and Transformer-based networks. A deep neural network refers to an artificial neural network with more hidden layers, and more parameters are used to represent the target model, which leads to the SOTA performance on the benchmark dataset from image to video. Here, we introduce the milestone networks in CV chronologically. 47 # B.2.1 Convolution-Based Networks. ImageNet [284], as one of the most important databases in computer vision, has aroused many mile- stone network architectures in image classification, including AlexNet [285], NIN [286], VGG [287], GoogLeNet [288], ResNet [289], DenseNet [290], etc. When it comes to object detection and semantic segmentation, researchers explore R-CNNs [291, 292, 293, 294], FCN [295], SSD [296], YOLOs [297, 298, 299, 300, 301], SegNet [302], PSPNet [303], Deeplabs [304, 305, 306, 307], RefineNet [308], etc. on common benchmark datasets, such as PASCAL VOC [309, 310], MS COCO [311], etc. There are several shared features among these popular convolution-based networks: 1) data augmenta- tion. Deep models require much more data to fit a complicated model, thus the data augmentation technique such as flipping, rotation, cropping, scaling, translation, and even adding noises enlarges the training dataset; 2) convolution. The convolutional kernel is used to extract the features of original image data, which main- tains the spatial structure for the adjacent pixels; 3) deep architecture. The deep architecture contains more parameters, which enhance the capability of the model. These common features contribute to the SOTA performance of convolutional neural networks (CNNs) in computer vision for nearly recent 10 years. # B.2.2 Recurrent neural networks Different from CNNs targeting 2D-dimensional image applications, recurrent neural networks (RNNs) [312, 313, 314] try to use recursive cells to process pictures in sequence, i.e., video data. However, the weaknesses of gradient explosion and long-term dependencies restrict further development of this model. To handle these problems embedded inside the RNN-based models, long short-term memory (LSTM) [315] was pro- posed by Hochreiter and Schmidhuber in 1997. In addition, the improved capability of LSTMs produces popularity and attracts attention both in NLP and CV [316, 317, 318, 319, 320]. # B.2.3 Generation-Based Networks Generative Adversarial Networks (GANs) [321] have provided a paradigm to learn representations for un- labelled data, and spawn many GAN-based approaches on downstream tasks. In image translation, pix2pix software [322] first proposes the conditional adversarial networks as a solution to the image-to-image trans- lation problems, and achieves reasonable results on real-world datasets. Markovian Generative Adversarial Networks (MGANs) [323] is a method to generate texture synthesis, which can be applied to style transfer and video stylization. CycleGAN [324] provides a learning algorithm to translate an original image from the source domain to a target domain without containing pairs of images in datasets for supervised learn- ing. StyleGAN [325] is a style-based generator to serve as an alternative architecture for traditional GANs. Pixel Recurrent Neural Networks (PixelRNN) [326] aims to complete images by modeling full dependencies between the color channels. DiscoGAN [327] is designed to learn relations between different domains. GANs have also provided a novel direction to study data synthesis because it perfectly simulates the distribution of the original data. Laplacian Pyramid of Adversarial Networks (LAPGAN) [328] uses a cas- cade of convolutional networks to generate images in a coarse-to-fine fashion. Similarly, Stacked Generative Adversarial Networks (SGAN) [329] decompose variations into multiple levels and gradually resolve un- certainties by stacking several GANs in a top-down way. 48 # B.2.4 Attention-Based Networks Based on the success of CNNs in the area of CV, the attention module is designed to equip with the popular CNNs. For example, SENet [330] proposes a channel attention module, which won first place in the com- petition of ILSVRC2017. In addition, CBAM [331] sequentially infers attention maps along both channel and spatial dimensions. Many innovative works, such as GCNet [332] and CCNet [333], are inspired by this idea of soft-attention mechanism, which outperforms the traditional CNNs on major benchmarks for both recognition and segmentation tasks. In particular, the self-attention mechanism [334], calculating the response at a position among all entities in a sequence by attending to all positions within the same se- quence, is proposed to estimate the relevance of one position to other positions in feature maps. To control the expected entities and model more complex relations among different elements in the sequence, masked self-attention and multi-head attention [38] are the key components proposed to substitute the function of convolutions in the era of transformers. # B.2.5 Transformer-Based Networks Recently, inspired by the self-attention mechanism and subsequent success of the transformer in NLP, researchers in CV also try to use the transformer as an alternative to the convolution. Self-attention- based transformer models always operate in a two-stage training mechanism: 1) pretraining on a primitive dataset (always big but not well labeled) by defining pretext tasks; 2) transferring the pretrained weights to the downstream tasks and adjusting the parameters on the target domain dataset by finetuning. Vi- sion Transformer (ViT) [40] is applied on CV and achieves the SOTA performance on major benchmark datasets. Data-efficient image Transformers (DeiT) [335]was proposed by Facebook AI to train image transformers more efficiently and maintain the SOTA performance simultaneously. DEtection TRansformer (DETR) [336] significantly outperforms competitive baselines in both object detection and semantic seg- mentation. LeViT [337] outperforms existing benchmarks with respect to balancing the accuracy and train- ing speed. Image GPT [149] is inspired by a sequence transformer in NLP, which can compete with several self-supervised benchmarks on ImageNet. On the basis of this research, DeepViT [338] explores a deeper architecture to improve performance consistently by making the transformer go deeper. Moreover, many researchers try to apply the transformer to more specific tasks. Pyramid Vision Transformer (PVT) [339] introduces the pyramid structure to overcome the difficulties of porting the transformer to various dense pre- diction tasks, and achieves the SOTA performance on major benchmark datasets. M3DeTR [340] is a novel research on multi-representation, multi-scale, and mutual-relation 3D object detection with transformers. Medical Transformer (MedT) [341] has focused on medical image segmentation and outperforms previous CNN-based and transformer-based architecture. In conclusion, the transformer has become a novel and popular research area in CV and its performance is proved by many existing works. # B.3 Traditional Graph Learning GL aims to embed the graph as a low-dimensional representation while preserving the desired properties of the original graph data. Classical GL methods are usually implemented using statistical methods or artificially designed components. Dimension Reduction As a commonly used method in feature engineering, dimension reduction aims to reduce the dimension of high-dimensional attribute graph data into a lower-dimensional representation. In GL, it highlights the remaining information at the cost of losing part of the attributes. According to different dimensionality reduction strategies, such methods can be classified into two types. The first type is subspace 49 learning under the linear assumption. Based on the assumption that the principal components [342] related to the larger variance represent important structural information, and those smaller variances represent noise, principal component analysis calculates a low-dimensional representation that maximizes the variance of the data. Linear Discriminant Analysis (LDA) [343] achieves dimension reduction by maximizing the ratio of inter-class scattering and intra-class scattering to obtain a linear projection matrix. Multi-Dimensional Scaling (MDS) [344] is a distance-maintaining manifold learning method. It produces a mapping in a lower dimension to preserve dissimilarities between nodes as much as possible. The second type is nonlinear dimension reduction, which aims to automatically learn nonlinear topology to achieve manifold learning. Isomap [345] first constructs a neighborhood graph on the manifold and calculates the shortest path between pairs of nodes, and then uses MDS to construct a low-dimensional embedding. Locally Linear Embedding (LLE) [346] first allocates neighbors for each node. Then, it calculates the weighted Wi,j, the best linear reconstruction feature Xi from its neighbors. Finally, calculate the low-dimensional embedding for the optimal reconstruction of Wi,j. Matrix Factorization Greatly influenced by the idea of dimension reduction, the models based on matrix factorization emerged in the early research of GL. Such models aim to reconstruct the adjacency matrix of the graph to achieve dimension reduction while maintaining structural information. Although these models have significant limitations, in fact, their ideas still inspire many current studies. Depending on how the matrix is constructed, such methods often append specific constraints. Graph Laplacian eigenmaps [347] minimizes a loss function to ensure that nodes close to each other on the manifold are mapped into the low-dimensional space and still maintain the local distances. Node proximity matrix factorization [348] minimizes the objective function |W − Y Y cT | through matrix factorization to approximate the proximity of nodes in the low-dimensional space, where Y and Y c are the embeddings for nodes and context nodes, and W is the default node proximity matrix. GraRep [349] aims to preserve the high-order proximity of graphs in the embedding space, thus it derives a k-th order transition matrix, Ak, by multiplying the adjacency matrix to itself k times. The transition probability from node vi to node vj is the entry in the i-th row and j-th column of the k-th order transition matrix, i.e., pk(vi|vj) = Ak i,j. Then GraRep defines the loss function using the skip-gram model and negative sampling. To capture the high-order proximity between node pairs, HOPE [350] preserves asymmetric transitivity in approximating the high-order proximity. Specifically, the goal of HOPE is to minimize the objective function ||S − W CT ||2 F , where the elements si,j ∈ S represent a certain edge feature (e.g., Katz index, the Rooted Page-Rank, the Common Neighbors, and the Adamic- Adar) between the corresponding node pairs (vi, vj), W is the node representation matrix, and C is the embedding of the node as the context. To reconstruct the matrix S more simply and elegantly, HOPE proposes to obtain W and C directly based on the low-rank singular value decomposition (SVD). Graph Kernel The kernel method is an important algorithm in pattern recognition and machine learning. Its basic idea is to give the graph embedding x ∈ X in the original low-dimensional space X, and maps the embeddings to a high-dimensional feature space H through a nonlinear function f ker. Then the nonlinear problem in X can be solved by constructing a linear algorithm in H. There are two main types of kernel methods on graph data. The first type uses the embedding method to convert the graph data into vectorial representation, and then directly implements the application based on the kernel function. However, due to the loss of mass graph structure information when transforming graphs into vectorial representation, such methods do not perform well in real scenarios. The second type of method introduces the graph kernel function to solve this problem. Based on retaining the advantages of the original kernel function, it directly represents the structural information of the graph data in the high-dimensional Hilbert space. The definition of the traditional method of graph kernel comes from R-convolution. According to the difference between the contrast substructure and the decomposition method of the graph structure, a large number of methods based on graph kernel have been proposed. For example, the work of [351, 352] proposed a random-walk 50 kernel based on calculating the number of common synchronization between two graph structures, To reduce the computational complexity and optimize the random walk strategy, a graph kernel based on comparing the shortest path information between two graph structures is proposed. To capture more complex topological information, the Weisfeiler-Lehman subtree graph kernel is proposed, which is based on a one-dimensional Weisfeiler-Lehman isomorphism test algorithm to find isomorphic subtree structures in a bunch of graph structures [353]. # C PFMs Theory Since pretraining has received great attention from the research community, the investigation in the theory- backed explanation is similarly eye-catching. During the unsupervised pretraining era before SSL, Erhan et al. [354, 355] shed some light on the theoretical explanation for the confirmation and clarity of learning difficulties. [354] researches the influence of pretraining with respect to architecture depth, model capacity, and the number of training samples, and demonstrates the robustness of pretraining from the perspective of both the optimization and the regularization. [355] further prove the regularizer role of the unsupervised pretraining in the downstream supervised tasks. # C.1 Different Perspectives Pretext Tasks [356] posits a mechanism based on approximate conditional independence (CI) to connect pretext and downstream task data distributions, which suggests that pretext tasks can self-supervisedly learn the representations from unlabelled data that reduce the sample complexity of downstream supervised tasks. The experiments both on CV and NLP task supports this theory. Representation Learning via Invariant Causal Mechanisms (RELIC) [181] also provides a theoretical understanding from the perspective that the explicit invariance constraints across augmentations can yield improved generalization guarantees. Multi-View Redundancy From the perspective of a multi-view setting, [357] understands contrastive learning as exploiting multiple views of data for representation learning. This theory provides a theoreti- cal analysis that the linear functions of these representations from pretraining are still competitive compared with the non-linear optimal predictor of the label. In other words, the linear functions of the learned represen- tations are nearly optimal on downstream prediction tasks whenever the different views provide redundant information about the label. # C.2 Different Categories Contrastive Learning Although experimental results show us that previous designs such as contrastive loss or momentum updating can produce impressive performance in SSL. However, one of the most important questions that remain in SSL is why these methods can maintain representation consistency during the pretraining process. A naive view is the minimization between positive pairs can boost invariance learning, while the maximization between negative pairs contributes to avoiding representational collapse. [358] shows that contrastive learning can achieve competitive bound via intra-class concentration, thus leading to the reduction of sample complexity on downstream tasks from the benefit of transferred representations. This research also provides a framework that can be utilized both on the guarantees of the quality of learning representations during the pretraining phase and the future assumptions added to the framework that allow tighter guarantees. 51 Non-Contrastive Learning While contrastive learning shows an effect by capturing the similarity and dissimilarity among the unlabelled examples, and further converging to an average local optimum which represents the general representations, recent non-contrastive SSL methods such as BYOL and SimSiam also shows the SOTA performance without the design of comparison between negative pairs. Based on the analysis of the eigenspaces, Tian et al. [182] study the behavior of non-contrastive SSL training and prove that the effects are from both the predictor and stop-gradient signal. Based on this theory, a novel and simple DirectPred method is proposed as a by-product of this theoretical exploration. # D Pretext Task Taxonomy on CV Pretext tasks are always designed to use pseudo labels generated from the data itself to pretrain the proxy model. There are five categories of pretext tasks for self-supervised: 1) generation-based methods; 2) transformation-based methods; 3) context-based methods; 4) semantic-based methods; 5) view-based meth- ods. Generation-Based Methods This type of method is GAN-based in the deep learning era. For image gen- eration, there are several applications including image colorization [138, 359], image super-resolution [360], image editing [361], context encoders [137], image-to-image translation [324], etc. On the other hand, video generation tasks contains future prediction [145], video action recoginition [241], video genera- tion [362, 363], and video representaion [364]. Transformation-Based Methods Transformation is a typical technology that serves as a data augmen- tation method to enlarge the training dataset in traditional DL. However, if transformations of the same image are labeled as positive samples and others as negative samples, this pretext task can be used for self-supervised pretraining [166]. Popular transformation in self-supervised learning (SSL) contains color transformation (such as Jitter, Gaussian blur, and adjusting brightness) and geometric transformation (such as flipping, cropping, scaling, and rotation). Context-Based Methods Basically, the design and construction of many artificial tasks, such as solving Jigsaw puzzles [140], comparing context similarity, and discriminating sequence order. Solving Jigsaw puzzles is defined as identifying the correct position of patches from an image. This task can help the model to learn an encoder for transfer learning [365, 141], and the feature representations are effective after the pretrained dataset is big enough. In addition, the design of video Jigsaw is also proposed for unsupervised learning [366]. Differently, context similarity tries to label the patches from the same images as positive samples and others as negative samples, then use a predefined similarity function to scale the distance between different pairs [49]. Semantic-Based Methods Semantic-based methods contain object detection, semantic segmentation, and depth prediction. These tasks also involve pretext tasks because their pixel-based labels can learn a more robust feature representation than simpler tasks. These pre-text tasks always establish on video dataset [367, 368]. View-Based Methods This type of method contains both single-modal data and multi-modal data. For the single-modal data, the original data is treated as the anchor and different viewpoints generate its positive pair samples. Sometimes the time slices in sequence-based data are treated as negative pairs because the scene is changed as time goes [369]. In addition, multi-modal data is usual in view-based methods, which are also called cross-modal-based methods here. Such as audio-video cooperative learning [370], RGB and optical flow cross-modal distance training [250]. 52 # E PFMs for Reinforcement Learning The success of pretraining learning methods in the supervised learning domain has spurred interest in the reinforcement learning (RL) domain to study whether the same paradigms can be adapted to RL algorithms. General pretraining RL can include broad directions, such as Reward-Free RL [371, 372, 373, 374], Goal- condition RL [375, 376, 377], and Representation Learning in RL [378, 379, 380, 381]. Here we focus the Representation Learning in RL. Specifically, this direction seeks to improve the performance by pretraining the visual perception competent of RL agent, i.e., the state encoder, with some large-scale datasets using unsupervised/self-supervised data augmentation techniques. The pretraining process empowers the state encoder to capture the essential structure information from the raw inputs (pixel-level input for CV). An RL policy network is built based on the pretrained state encoder to learn the specific downstream control tasks in the fine-tuning stage. Recent studies have demonstrated that can greatly benefit both in sample efficiency and learning effectiveness from unsupervised [382, 383, 384], semi-supervised [385], and self-supervised [386, 387] learning techniques. Specifically, this direction could be roughly classified into the following two categories: Model-based Pretraining RL and Contrastive-like Pretraining RL. Model-based Pretraining RL Model-based Pretraining RL aims to first pretrain a generative world model to capture the underlying structure of the environment and then leverage the world model as a state encoder or simulator during fine-tuning. World Models [382] is the first work that proposes to learn a compressed spatial and temporal representation of the environment in an unsupervised manner using a simple Variational Autoencoder, which greatly improves the sample efficiency compared to training from scratch. However, learning the world model without being aware of the environment’s dynamic might lead to ignorance of some key information in the environment. Dreamer [388, 389] proposed to learn latent dynamics by approximat- ing the representation, transition, and reward model. They then train RL agents purely by imagination in a latent space, which is more efficient since it brings a low memory footprint and enables fast predictions of thousands of imagined trajectories in parallel. Furthermore, DreamerPro [390] proposes a reconstruction- free approach based on prototypical representations to migrate the task-irrelevant visual distractions problem in the latent dynamics modeling. DreamerPro significantly outperforms previous SOTA methods when there are complex background distractions. To verify whether learning accurate world models for the real world is promising, Daydreamer [391] applies Dreamer to the real-world physical robots problem and empirically demonstrates significant learning efficiency gains. Contrastive-like Pretraining RL Contrastive-like Pretraining RL techniques seek to improve the repre- sentation ability of state encoders by pretraining the state encoder with a large amount of out-of-domain data or adding some auxiliary loss using unsupervised learning or data augmentation techniques. CURL [392] combines instance contrastive learning and by using MoCo [163] mechanism, which significantly improves the data efficiency of RL agents. Furthermore, RAD [393] proposes an implicit approach that directly trains the RL objective on multiple augmented observations views, which outperforms CURL on some of the environments in the DeepMind Control Suite. Concurrent to RAD, DrQ [394] introduces a simple regular- ization term, which applies image augmentation to compute current and target Q values. They demonstrate that data efficiency can be significantly improved after applying it to DQN. DrQ-v2 [395] further extends this approach to solve complex humanoid locomotion tasks by inserting similar techniques into the DDPG algorithm. Orthogonal to this direction, [379, 378, 396, 397] demonstrate that pretraining the vision part of RL agent using supervised or unsupervised methods on out-of-domain data can improve the learning effi- ciency of downstream RL control tasks. Besides ensuring consistency across different views of observation, SPR [381] additionally trains a dynamics model which enforces the representations to be temporally predic- 53 tive. Based on SPR, SGI [380] proposes to pretrain representations using a combination of latent dynamics modeling, unsupervised goal-conditioned, and inverse dynamics modeling. Compared to previous methods, SGI can better capture the environment’s dynamics and facilitate downstream RL control task training. # F Evaluation Metrics Classification Task The classification task, according to a labeled training document, determines the rela- tionship between document features and document categories. The learned relationship model is then used to determine the category of new documents. Accuracy and Error Rate The key metrics for a text classification model are Accuracy and Error Rate. The terms Accuracy and Error Rate are defined as follows: Accuracy = (TP + TN) N , (20) ErrorRate = 1 − Accuracy = (FP + FN) N , (21) where TP and FP denote true positive and false positive, TN and FN stand for true negative and false negative. Precision, Recall and F1 Regardless of the standard type and error rate, there are very important metrics used for unbalanced testing sets. These metrics are similar to the concept of the class label in the testing samples. F1 is defined as the harmonic average of Precision and Recall. Thus, Accuracy, Recall, and F1 can be represented as: P recision = TP TP + FP , Recall = TP TP + FN , (22) F 1 = 2Precision × Recall Precision + Recall . (23) When the accuracy, F1, and recall values hit 1, the desired results are obtained. On the other hand, when the values turn 0, we get the worst consequence. For the multi-class classification task, the precision and recall values of each class can be determined independently, and then the individual and overall performance can be analyzed. M icro − F 1 The M icro − F 1 [398] is a metric that measures all labels’ overall accuracy and recall. We denote M icro − F 1 as: M icro − F 1 = 2Pt × Rt P + R , (24) p_ Dues TP Dies TP 05 MresTR+FPD Vices T P+ PN where T Pt and F Pt mean true and false positive of the t th label on a text. M acro − F 1 The M acro − F 1 calculates the average F 1 of all labels by giving equal weight to them. M acro − F 1 is denoted as: 2Pr x Ri Py +R” 1 Macro — F1= 3 S- teS (26) 54 Pt = T Pt T Pt + F Pt , Rt = T Pt T Pt + F Nt . (27) where T Nt and F Nt represent true and false negative of the t th label. S stands for the label set of all samples. Mean Reciprocal Rank (MRR) The MRR is commonly used to evaluate the performance of ranking algorithms on Question Answering (QA) and Information Retrieval (IR) tasks. MRR is represented as is 1 MRR=— 5 —— 28 Q » rank,’ (28) i=1 where ranki is the ranking of the i th ground-truth answer. The number of predicted labels on each text is denoted by Q. Moreover, there are some metrics, such as EM, Hamming-loss [399], P@K and NDCG@K. Generation Task Generation task uses LMs to predict the next most likely word or sentence based on input data. Bilingual EvaLuation Understudy (BELU) BLEU compares the generated sentences to the reference sentence and makes predictions using automatic machine translation algorithms. The language creation problem is also supported by deep learning technologies such as speech recognition, image caption genera- tion, and text summarization. They can’t discover anything better, but it has a few advantages: it’s simple to comprehend, correlates well with human judgment, and is language-independent. As a bilingual evaluation aid, BLEU is mainly used to evaluate the quality of machine translation [400]. BLEU compares the degree of overlap between the N-gram in the candidate text and the N-gram in the reference text. The higher overlap indicates better translation quality. The formula for the computation is: N BLEU = BP x exp (> W, log r,) , (29) n=1 where N represents N-gram, BP is penalty factor, PN is multivariate precision, and WN = 1/N is the corresponding weight of multivariate precision. r represents the length of the shortest reference translation, and c represents the length of the candidate translation, then the specific calculation method of penalty factor BP is as follows: 1, e1−la/lt, lt > la lt ≤ la BP = , (30) where lt is the number of words in machine translation and la is the number of words in reference answer. The penalty factor is mostly used to penalize large gaps between machine and reference translations. ROUGE (Recall-Oriented Understudy for Gisting Evaluation) ROUGE stands for N-gram co-occurrence statistics, which are used in automatic evaluation methods. It is expanded on the similarity of N-grams, which means that an N-gram is a subsequence of the main document text in terms of N words. There are four types of ROUGE, including ROUGE-N, ROUGE-L, ROUGE-W, and ROUGE-S. The first two are com- monly used, and the N in rouge-N refers to N-gram, which is calculated similarly to BLEU, except BLEU is based on accuracy, while ROUGE is based on recall. L in ROUGE-L refers to the Longest Common Sub- sequence, which is calculated as the Longest Common Subsequence between the candidate abstract and the reference abstract. Thus, the longer the length, the higher the score, based on the F value. The calculation 55 formula of ROUGE-N and ROUGE-L is mainly introduced. The calculation formula of ROUGE-N is as follows: Do se{ReferenceSummaries} Deram, 65 Countmatch (gram,,) ROUGE-—N= S€{ReferenceSummaries} Yeram, 8 Count (gram,,) , BD) where N stands for N-gram, Count(gramn) represents the frequency of occurrence of an N-gram, and Countmatch(gramn) represents the frequency of co-occurrence of an N-gram. The calculation formula of ROUGE-L is as follows: . (1 + 6?) Rics Pies E-L=Fie= , 32 ROUG tes Rics + B? Pes 2) Rlcs = LCS(X, Y ) M , (33) Plcs = LCS(X, Y ) N , (34) where X is the candidate abstract, Y represents the reference abstract, LCS(X, Y ) table indicates the length of the Longest Common Subsequence (LCS) of the candidate abstract and references abstract, M stands for the length of reference abstract, and N denotes the length of the candidate abstract. The ROUGE method is characterized by N-gram co-occurrence statistics, based on recall rate (ROUGE-N) and F-value (ROUGE- L). They are often used in text summaries. It is worth noting that ROUGE is word-based correspondence rather than semantic-based correspondence, but this can be mitigated by increasing the number of reference summaries. METEOR METEOR, also known as an explicitly sorted translation evaluation metric [401], is an im- proved version of the BLEU standard that aims to address some flaws in the BLEU standard. Using WordNet to calculate matching relationships between specific sequences, synonyms, roots, affixes, and definitions im- proves BLEU performance and makes it more relevant to manual discrimination. The calculation formula is as follows: M ET EOR = (1 − P en) × Fm, (35) Fm = P R αP + (1 − α)R , (36) # m k hk(ci) m k hk(sij) m P=—: (37) Ve hy.(ci) m R=—3—. (38) Ye be( sig) where P en = γ( ch m )θ is a penalty factor, which punishes the word order in candidate translation that is different from that in reference translation. ch refers to the number of chunks, which are clustered units of matched units adjacent to each other in both the candidate translation and the candidate reference translation. α, β, θ is the adjustable parameter, m is the number of unary groups that can be matched in the candidate translation, c is the length of the candidate translation, hk(ci) is the number of occurrences in candidate translations ci, and hk(sij) is the number of occurrences in reference translations sij. Perplexity Perplexity is also called the degree of confusion [402]. Its core idea is: first, according to the testing sentence, learn a LM P . Then, according to the LM P , the score of the optional sentence is calculated. Finally, the above scores are standardized according to sentence length. The calculation formula is as follows: P P L(W ) = P (w1, w2, . . . , wM )− 1 M , (39) 56 where W is the candidate translation, M is the length of the candidate translation, P is the LM obtained according to the reference translation, and P (w1, w2, . . . , wM ) is the score calculated by the LM for the candidate translation. The Perplexity assessment indicator is based on a LM. The lower the degree of confu- sion, the better the translation quality, which is often used in machine translation and LMs. Its disadvantages are as follows: the larger the dataset is, the faster the degree of confusion decreases; the punctuation in the data will impact the PPL of the model; and the interference of common words. # G Datasets # G.1 Downstream Tasks and Datasets on NLP There are many available datasets in the NLP domain, divided according to different tasks. We summarize them in Table 5. It mainly comprises two categories: the task of classification of texts and the task of gener- ating texts. The text classification tasks mainly include Sentiment Analysis (SA), News Classification (NC), Topic Labelling (TL), Natural Language Inference (NLI), Named Entity Recognition (NER), Question An- swering (QA), Dialogue Act Classification (DAC), etc. The generation tasks mainly include text summaries and machine translation. Sentiment Analysis (SA) It consists of judging the emotional polarity and dividing it into several classes. Depending on the granularity of sentiments, the SA is divided into three categories: dichotomy (positive and negative), trichotomy (positive, negative, and neutral), and multiple categories. Here we introduce several datasets in detail. Stanford sentiment treebank (SST) [473] The dataset is an extension of MR [474]. SST-1 is a version of SST. It is divided into five categories and the number of training texts and testing texts is 8,544 and 2,210, respectively. It also consists of 20 average tokens. The SST-2 [475] contains 9,613 movie reviews including 6,920 training texts, 872 development texts, and 1,821 testing texts. Semantic textual similarity benchmark (STS-B) [476] It is used in semantic textual similarity tasks orga- nized in the SemEval context between 2012 and 2017 [477]. It consists of text from image titles, news titles and forums. On a scale of 1 to 5, STS-B displays the semantic similarity of two sentences. It includes 5,749 training sets, 1,379 development sets, and 1,377 testing sets. Multi-Perspective Question Answering (MPQA) [478, 479] This is an opinion dataset which has two categories. It contains 10,606 sentences from various news sources that have been manually annotated for opinions and other private states. It is worth noting that there are 3,311 positive articles and 7,293 negative articles, having no labels for each article. IMDB reviews [480] The dataset is the world’s most authoritative source for binary sentiment classifi- cation of film reviews. The number of content in each class is the same and it can be divided into training and testing sets whose number of comments is 25,000 on average. News Classification (NC) As one of the most vital information sources, news content exerts a critical Its applications effect on people. The NC facilitates users to acquire essential knowledge in real time. mainly include news topic identification and recommendation of relevant news based on user interests. Here we introduce several datasets in detail. 57 Table 5: The statistics of the datasets on NLP. For the QA task, the class represents the sum number of candidate answers and the correct answer. For dialogue, class is the number of slots. Length means the average tokens in turn. Task Sentiment Analysis News Classification Topic Labeling Datasets MR SST-1 SST-2 MPQA IMDB 20NG AG News R8 R52 DBPedia Ohsumed YahooA Named Entity Recognition Question Answering Dialog Act Classification Text Summarization Machine Translation Dialogue 20 18 19 3 294 221 45/7 66 70 55 136 112 - - - - - - - - - - - - - - # Type Classification # Generation 58 20 Newsgroups (20NG) [481] 20NG is a text dataset derived from newsgroups. There are 20 classes with the same number of articles per class, including 18846 articles in total. The average number of tokens is 221. AG News [423, 482] This is an academic news search engine, which is divided into four categories. It contains news headlines and introductions. It includes 120,000 training texts and 7,600 testing texts. The number of average tokens is 45/7. R8 and R52 [483] They come from Reuters [484]. R8 contains 8 classes consisting of 66 average tokens and includes 2,189 and 5,485 testing and training courses. There are 52 classes in R52, which consists of 70 average tokens. It is divided into 6,532 and 2,568 training and testing texts. Topic Labeling (TL) The task mainly obtains the meaning of the file by defining complex file themes. It is a critical component of topic analysis technology, which aims at simplifying topic analysis by assigning each article to one or more topics. Here, we introduce a few in detail. DBpedia [485] It is a large-scale multilingual knowledge base generated by Wikipedia’s most commonly used information boxes. It releases DBpedia every month, adding or removing classes and attributes in each version. The most popular version of DBpedia has 14 categories, separated into 560,000 training data and 70,000 testing data. The number of average tokens is 55. Ohsumed [486] This is a biomedical literature database. The number of texts is 7,400. It has 23 car- diovascular disease categories and consists of 136 average tokens. All texts are medical abstracts that are categorized into one or more classes. Yahoo answers (YahooA) [423] The dataset is a topic labeling task having 10 categories. The number of average tokens is 136. There are 140,000 training data and 5,000 testing data. Each text in YahooA has question titles, question contexts, and best answers. Natural Language Inference (NLI) This task is used to forecast whether the meaning of a text can be Interpretation is a broad form of NLI. By comparing the semantic similarity of inferred from another. sentence pairings, it determines whether a sentence is the interpretation of another one. Here we introduce several primary datasets in detail. The Stanford Natural Language Inference (SNLI) [429] It is commonly used in NLI takes. It contains 570,152 human-annotated sentence pairs, which are annotated with three sorts of relationships: neutral, derived, and conflicting. Multi-genre Natural Language Inference (MNLI) [487] has 3 categories and con- sists of 430,000 sentence pairs annotated with textual information, which is usually used in textual inference tasks. Question Natural Language Inference (QNLI) [488], whose task with 2 classes is to determine whether a given text pair is a question-answer. Winograd Natural Language Inference (WNLI) [489] which consists of 2 categories is a dataset that captures the standard reference information between two paragraphs. Microsoft Research Paraphrase (MSRP) [434] The dataset contains sentence pairs for the text-similarity task, including 1,725 training and 4,076 testing sets. A binary label annotates each pair, discriminating whether they are paraphrases. Sentences Involving Compositional Knowledge (SICK) [433] It includes nearly 10,000 English sentence pairs, marked with similarity, and the scale range is 1-5. It has neutral, entailment, and contradictory three categories. 59 Named Entity Recognition (NER) This is a fundamental task of NLP to identify people, places, orga- nizations, and other entities in text. It is a crucial primary tool for many NLP tasks, including information extraction, question answering, semantic parsing, machine translation, etc. CoNLL 2003 [275] It consists of newswire text from the Reuters RCV1 corpus. It contains four different entity types (Location, Organization, Person, and Miscellaneous) and includes 1,393 English news articles, and 909 German news articles. OntoNotes 5.0 [13] The dataset consists of 174,5K English, 900K Chinese, and 300K Arabic text data. It comes from telephone conversations, news agencies, radio news, radio conversations, and blogs. It has 18 entity classes containing 11 types, seven values, and 2,945,000 text data. MSRA [439] This is a Chinese dataset that is obtained from the news domain. It has three types of entities and is used as a shared task on SIGNAN back in 2006. Question Answering (QA) There are two types of QA systems: the extraction guidance system and the generation guidance system. The extractive QA can be regarded as a particular case of text classification. Here we detail several datasets. Microsoft Research Paraphrase Corpus (MRPC) [490] It contains 5,800 sentence pairs extracted from Internet news, and the task type is similar to the QQP dataset. Sentence pairs are derived from comments on the same news item and determine whether the two sentences are semantically the same. The assessment criteria were classification accuracy and F1 score. Stanford Question Answering Dataset (SQuAD) [275] This is a large-scale machine-reading compre- hension dataset that contains two tasks. SQuAD 1.1 [488] provides questions and corresponding answers, and the dataset contains 100,000 samples in total, while SQuAD 2.0 [491] adds unanswered questions and expands the scale to 150,000. RACE [492] The dataset has 5 categories, containing nearly 100,000 questions extracted from mid- dle and high school English tests, with corresponding answers given by experts. The average length of RACE text is more significant than 300, which is longer than other reading comprehension datasets (such as SQuAD) sequences. Dialog Act Classification (DAC) The dialogue act is a specific verbal component, which marks the dia- logue according to the meaning category of the dialogue. DAC categorizes tags according to the meaning of the dialogue to help understand the speaker’s intentions. Dialog State Tracking Challenge 4 (DSTC 4) [450] It belongs to the dialog act classification task and mainly focuses on dialog state tracking on human-human dialogs. It is divided into 89 training classes and contains 24,000 training texts and 6,000 test texts. ICSI Meeting Recorder Dialog Act (MRDA) [451] It includes about 75 hours of speech from 75 naturally occurring meetings among 53 speakers. The number of categories is 5, and it contains 51,000 training texts, 11,000 test texts, and 11,000 validation texts. Switchboard Dialog Act (SwDA) [493] The dataset extends the dialogue behavior label with rounds/discourses. The label summarizes the sentence structure, and relevant and pragmatic information of the relevant turn. The SwDA is split into 43 training classes and includes 1,003,000 training texts, 19,000 test texts, and 112,000 validation texts. 60 Text Summarization Text summarization is a summary of given single or multiple documents. It is kept as concise as possible while ensuring that it reflects the critical content of the original document. It can be divided into extractive summarization and generative summarization. Extractive summarization is generated by extracting and splicing the critical sentences in documents. Generative summarization is generated by a model, which summarizes documents according to the required content expressed in documents. NYT [454] The dataset comes from the corpus annotated by the New York Time. The named entities are annotated using the Stanford NER tool in conjunction with the Freebase knowledge base. It contains 9,076 articles, with the remaining 100,834 divided into a training set (96,834 examples) and a validation set (4,000 samples). CNN/Daily Mail [456] It is used for the passage-based question-answering task, and it is popular in assessing ATS systems. The dataset consists of CNN/Daily Mail news stories paired with multi-sentence human-generated summaries. There are 287,226 training instances, 13,368 validation instances, and 11,490 testing instances in total. Gigaword [463] This is a dataset of English news chapters consisting of nearly 950 pieces. Headlines – stories from multiple sources, including the New York Times – include some articles with a one-sentence, short news feed. Machine Translation (MT) It refers to the task of translation from one language to another with its semantic equivalence by a computer. There are three categories, rule-based machine translation, statistics- based machine translation, and neural network-based machine translation. WMT14 [464] It is a grouping of datasets used in the Ninth Workshop on Statistical Machine Translation shared tasks, including a news translation task, a quality estimation task, a metrics task, and a medical text translation task. WMT16 [465] This dataset is a grouping of datasets used in the First Conference on Machine Translation shared tasks. It has ten shared tasks, including a news translation task, an IT domain translation task, a biomedical translation task, an automatic post-editing task, a metrics task, a quality estimation task, a tuning task, a pronoun translation task, a bilingual document alignment task, and a multimodal translation task. WMT17 [464] The dataset includes three MT tasks (news, biomedical, and multimodal), an automatic post-editing task, a quality estimation task, a task dedicated to the training of neural MT systems, a task on bandit learning for MT, an automatic post-editing task, and a metrics task. WMT18 [467] It mainly features six shared tasks: a news translation task, a biomedical translation task, an automatic post-editing task, a metrics task, a quality estimation task, and a multimodal translation task. Participants must evaluate their approaches to the machine translation topic using the standard datasets created for the shared tasks. Dialogue As an essential way of man-machine interaction, the dialogue system offers a wide range of applications. The existing dialogue systems can be grouped into task-oriented dialogue systems and non- task-oriented dialogue systems from application scenarios. Among them, the non-task type of conversation system can also be called a chatbot. DSTC2 [470] This is a multi-round dialogue dataset of restaurant reservation fields, including 1,612 training data, 506 verification data, and 1,117 test data. It allows the user’s goals to change compared to 61 DSTC1. DSTC2 is also richer in terms of the conversation state representation, including the slot value pairs of the user’s targets and the ways to find them. MWOZ [470] It contains 8,420/1,000/1,000 conversations for training, validation, and test sets, respec- It contains 30 pairs in seven domains being a multi-domain fully-labeled corpus. Every sample tively. includes a goal, multiple user and agent utterances, and annotations regarding slot values. Out-Of-Scope (OOS) [470] The dataset includes 15,100 training, 3,100 validation, and 5,500 test sets, respectively. It contains 151 intent classes, containing 150 in-scope and one out-of-scope intent. The out- of-scope intent indicates that a user utterance failed to classify to given predefined objectives. # G.2 Downstream Tasks and Datasets on CV Table 6: The statistics of the datasets used on downstream tasks. Type Detection Inpainting Sequence - Usage Pretrain & Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream iNaturallist2018 Downstream Name Domain ImageNet - CIFAR-10 CIFAR-100 STL-10 Caltech-101 MNIST-10 SVHN Places205 SUN397 HMDB51 UCF101 Food-101 Birdsnap Cars Aircraft Pets Flowers DTD - - - object digit digit scene scene action action food bird car aircraft pet flower texture species - object object object scene object scene scene Pretrain Downstream Downstream Downstream NYU-Depth V2 Downstream Downstream Downstream Downstream Downstream vocabulary Downstream Paris StreetView Downstream Moving-MNIST Downstream JFT-300M COCO VOC07 VOC12 VOC11 ADE20K Cityscapes LVIS DAVIS scene scene digit multimedia YFCC100M Pretrain Class 1000+ 10 100 10 101 10 10 205 899 51 101 101 500 196 102 37 102 47 8,000+ 3,000+ 80 20 20 894 20 3,688 25 1,200+ 150 - - - Size 1,200,000+ 60,000 60,000 6,000 9,146 60,000 73,257 2,448,873 130,519 7000 - 101,000 49,829 16,185 10,200 7,400 8,189 5,640 450,000+ 300,000,000+ 200,000 9,963 2,913 1,449 3,334 27,574 25,000+ 160,000+ - 15,000 10,000 Related Papers [136, 137, 140, 141, 139, 142, 143, 138, 145, 494, 174, 179, 173, 151, 183, 182, 146, 153] [161, 162, 163, 164, 165, 48, 495, 49, 172, 166, 167, 170, 175, 177, 176, 180, 181, 496] [134, 135, 138, 165, 172, 175, 166, 173, 182] [165, 175, 166, 173] [134, 135, 177, 179, 173, 182] [134, 135, 165, 166] [48, 179] [175] [138, 139, 142, 161, 162, 49, 172, 494, 175, 167, 173, 174, 496] [166] [177] [177] [165, 166] [166] [166, 165] [165, 166] [165, 166] [165, 166] [165, 166] [162, 167, 174, 496] [40, 496] [142, 163, 164, 179, 167, 170, 183, 496] [137, 138, 140, 139, 142, 143, 138, 146, 161, 162, 163, 164, 165, 49, 494, 175, 167, 170, 141] [137, 138, 140, 139, 142, 49, 141] [139, 165, 177] [136] [183, 496] [163] [163] [151] [136, 137] [179] 100,000,0000+ [49] The datasets in CV mainly contain three types from the perspective of tasks: classification, detection, and segmentation. The popular datasets are concluded in Table 6, and some infrequently mentioned datasets in long tails are discussed in the text. Classification In this part, we first cover the popular large-scale datasets used frequently in both the pretext and downstream tasks. Then the domain datasets only used for the downstream tasks are unfolded. MNIST [497] It’s a collection of handwritten digits that includes 60, 000 samples in training and 10, 000 in testing. The images are fixed-size with 28 × 28 pixels. The pixel values are from 0 to 255.0 in which pixel values smaller than 255.0 can be understood as background (white) and 255 means foreground (black). The labels are from 0 to 9 and only one of these digits exists in an image. Both traditional and deep learning methods are based on this most popular dataset despite advanced methods showing perfect results. Thus, Geoffrey Hinton has described it as "the drosophila of machine learning". 62 Street View House Numbers (SVHN) [498] In the domain of digit numbers, it collects real-world digit numbers from house numbers in Google Street View images. It includes 73, 257 digits for training, 26, 032 digits for testing, and 531, 131 additional. All of them are 32 × 32 color images with both class labels and character-level bounding boxes. CIFAR [499] As more advanced methods show perfect results on the simple datasets, more sophisticated datasets such as CIFAR-10 and CIFAR-100 are conducted. These two datasets are closer to the real-world object. The CIFAR-10 contains 50, 000 training images and 10, 000 testing images, with 6, 000 images per class and 32×32 pixels in each RGB color image. The CIFAR-100 is similar to the CIFAR-10 but with more detailed label information. There are 100 classes containing 500 training images and 100 testing images in each class. In addition, these 100 "fine" classes are grouped equally into 20 "coarse" classes. Researchers can adapt it to suitable learning methods. STL-10 [500] Inspired by the CIFAR-10 dataset, STL-10 is another 96 × 96 color image dataset contain- ing similar 10 real-world classes. Each class has 500 training images and 800 testing images. The biggest difference is that STL-10 has 100, 000 unlabeled images for unsupervised learning. More construction in- formation can be seen in [501]. Caltech-101 [502] It collects roughly 300 × 200 color images of objects belonging to 101 categories, with 40 to 800 images per category and 50 on average. The outlines of the objects in the pictures are annotated for the convenience of different learning methods. ImageNet [284] This is one of the most popular and large-scale datasets on computer vision. It is built ac- cording to the hierarchical structure of WordNet [503]. The full ImageNet dataset contains 14, 197, 122 im- ages and 21, 841 synsets indexed, attaching on average 1, 000 images to demonstrate each synset. The most frequently-used subset of ImageNet is the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) dataset from 2010 to 2017, containing tasks of classification, localization, and detection. The number of samples in training and testing datasets and the labels of images are determined by the specific task, more details are seen in [504]. HMDB51 [505, 506] In addition to the popular MNIST, there still exist many domain datasets used for the downstream tasks in the classification problem. HMDB51 is an action video database for a total of 7, 000 clips in 51 action classes. It contains five types of facial actions and body movements. UCF101 [507] It is another action video dataset designed for more realistic action recognition. It is an extension of the UCF50 [508] dataset containing only 50 action categories with 101 action categories, collected from YouTube. What makes it a famous recognition dataset is the workshop in ICCV13 with UCF101 as its main competition benchmark. Food-101 [509] This is a real-world food dataset of 101 food categories, with 750 and 250 images per class in training and testing dataset respectively. Birdsnap [510] It is a fine-grained visual categorization of birds on a broad scale, with bounding boxes and the locations/annotations of 17 parts in the object. It contains 49, 829 images of the 500 most common species in North America, with each species containing 69 to 100 images and most species having 100. In addition, some images are also labeled as male or female, immature or adult, and breeding or non-breeding plumage. SUN397 To target the scene categorization, the extensive Scene UNderstanding (SUN) database [511, 512] fills the gap of the existing dataset with the limited scope of categories. This database has 899 categories and 130, 519 images, and only images with more than 200 × 200 pixels were kept. SUN397 is a more well- 63 sampled subset that maintains 397 categories with at least 100 images per category, in which other categories containing relatively few unique photographs are discarded. Places205 Places205 [513] dataset is another large scale scene dataset consists of 2, 448, 873 images from 205 scene categories. Cars [514] The dataset in the domain of cars contains 16, 185 color images of 196 classes (at the level of Make, Model, Year) of cars. For convenience, this dataset is split into training and testing sets in roughly equal quantities. Aircraft [515] It is another fine-grained visual classification designed for aircraft (also known as FGVC- Aircraft). A popular form of this dataset is the fine-grained recognition challenge 2013 (FGComp2013) [516] ran in parallel with the ILSVRC2013. There exist four-level hierarchies: Model, Variant, Family, Manufac- turer, from finer to coarser to organize this database. The more detailed information is shown in [517]. Pets [518] It represents The Oxford-IIIT Pet Dataset that collects 37 pet categories with roughly 200 images per category. All images have an associated ground truth annotation of breed for classification, head ROI for detection, and pixel-level trimap for segmentation. Flowers [519] Similarly, Flowers is another domain dataset in flowers also collected by Oxford; it contains Oxford-17 Flowers of 17 categories and Oxford-102 Flowers of 102 categories. Describable Textures Dataset (DTD) [520] This is an evolving collection of textural images in the wild, which consists of 5, 640 images of 47 categories, with 120 images per category. iNaturalist2018 [521] It is a large-scale species classification competition conducted on the FGVC5 workshop at CVPR2018. This dataset contains over 8,000 species categories, with more than 450, 000 images in the training and validation dataset collected from iNaturalist [522]. JFT-300M [523] JFT-300M is an internal Google dataset introduced by Sun et al [523] and well-known from ViT Model [40]. It is labeled by algorithms that utilize human-computer communications and target classification tasks. This dataset finally contains 300M images with over 1000M labels, thus leading to the multiple labels attached to this large-scale dataset. Detection The detection is a popular task in the CV, and almost all the research is conducted on COCO and PASCAL VOC datasets. COCO [311] This is a large-scale dataset for object detection, segmentation, and caption; it contains 330, 000 RGB images, with more than 200, 000 labeled. There are 1.5 million object instances of 80 object categories involved. Thus, it is one of the most popular benchmark dataset in detection and segmentation in parallel with the following PASCAL VOC. PASCAL VOC [524] From 2005 through 2012, the dataset has run challenges assessing performance on object class recognition and has provided standardized image datasets for object class recognition. The main datasets used in self-supervised learning are VOC07, VOC11, and VOC12. Main competitions in VOC07 [525] contain classification and detection tasks; both of them consist of 20 objects and contain at least one object in each image. Thus, it is common to use VOC07 to serve as the downstream task for the detection. Segmentation The segmentation is a semantics-based pixel-level classification. These datasets are diffi- cult to obtain and annotate, thus they are always used as a downstream task. 64 VOC11 [526] & VOC12 [527] Both VOC11 and VOC12 contains classification, detection, and segmen- tation tasks in the main competition, thus leading to the common use of downstream task for the segmenta- tion. ADE20K [528, 529] It collects 27, 574 images from both the SUN and Places205 databases, in which 25, 574 for training and 2, 000 for testing. All 707, 868 objects from 3, 688 categories existing in images are annotated. Especially, this dataset contains 193, 238 annotated object parts and parts of parts, and additional attributes, annotation time, depth ordering for the benefit of the research community. NYU-Depth V2 [530] This is a dataset consisting of images and video sequences from 464 indoor scenes that are recorded by both the RGB and Depth cameras from 3 cities. It contains 1, 449 images with the ground truth of depth, and the original RGB values are also provided. In addition, there are 407, 024 new unlabeled frames and additional class labels for the objects in images. Cityscapes [531, 532] It is a dataset of urban street scenes from 50 cities with the ground truth of semantic segmentation. The main instances are vehicles, people, and construction. The high-quality dense pixel annotations contain a volume of 5, 000 images. In addition to the fine annotations, coarser polygonal annotations are provided for a set of 20, 000 images. Moreover, the videos consist of not consistent images with high-quality annotations, and these annotated images with consistently changing views are provided for researchers. It features that 1) a category or word in one image is related to the only segmentation object; 2) more than 1, 200 categories are ex- tracted from roughly 160, 000 images; 3) long tails phenomenon exist in these categories; and 4) more than 2, 000, 000 high-quality instance segmentation masks. Densely Annotated VIdeo Segmentation (DAVIS) [534] It is a video dataset designed for the in-depth analysis of the SOTA in video object segmentation, in which DAVIS 2017 [535] contains both semi- supervised (human-guided at the testing time) and unsupervised (human non-guided at test time) video sequences with multiple annotated instances. Others There are many datasets designed for special visual tasks such as inpainting. In addition, this part covers the data collection in the wild. Paris StreetView [536] The dataset is designed for image inpainting task, which contains 14, 900 training images and 100 testing images collected from street views of Paris. This dataset is collected from Google Street View and mainly focuses on the buildings in the city. Moving-MNIST [537] Based on MNIST, it is a video dataset designed for evaluating sequence prediction or reconstruction, which contains 10, 000 sequences. Each video is long of 20 frames and consisted of two digits (possibly overlapped) moving inside a 64 × 64 patch. The first benchmark is reported on [538] by the method of LSTMs. Yahoo Flickr Creative Commons 100 Million (YFCC100M) [539, 540] The dataset is the largest public multimedia collection that is allowed to search by users for their own targets; this dataset can browse both images and videos. It is free and for researchers to explore and investigate subsets of the YFCC100M in real time. Subsets of the complete dataset can be retrieved by any keyword search and reviewed directly. In addition, the text information attached to any image or video is abundant, such as containing location information and user tags. Briefly, it is more a multimedia library than a domain dataset. Data in the Wild More generalized dataset concept in the self-supervised learning era is composed of 65 multimedia websites, APP, or search engines such as Instagram, Flickr, Google Images, etc. I think pictures in the wild will play a major role in the future study of CV because of the quantity of data, the computation source, and the learning power of PFM. # G.3 Downstream Tasks and Datasets on Graph The purpose of the pretraining graph model is to improve the performance of downstream tasks. According to the different analysis objects of the downstream tasks, they can be divided into nodes, edges, and graphs. Meanwhile, the PFMs of GL have been widely used in a mass of fields. In this section, we combine the downstream tasks to conduct statistics on the pretraining datasets and the downstream task datasets. Node-Level Tasks Nodes are the most basic element of the graph, so lots of downstream tasks mainly focus on the analysis of nodes. Node Classification Node ClassiFication (NCF) is one of the most prevalent graph-based tasks, which has important analytical value in most of the different types of graph data. Different from the pseudo-labels assigned to nodes in the graph in self-supervised methods, the labels in NCF often come from external in- formation such as manual annotation. Based on Definition 7 and 8, NCF can be divided into two types: transductive and inductive according to the visibility during training, verification, and testing. In addition, the result of NCF can be single-label or multi-label according to the mutual exclusion of labels. The statis- tical results of common NFC datasets are shown in Table 7. Node Clustering The goal of Node ClusterIng (NCI) is to divide a graph into different classes or clusters according to a certain standard so that the correlation of nodes in the same cluster is as large as possible, and the irrelevance of nodes that are not in the same cluster is also minimized. Although in the above-mentioned pretraining tasks, NCI is used as a pretext task has appeared, NCI can still test pretraining graph models based on other pretext tasks. Top-K Search The goal of task Top-K Search (TKS) is to search the K nodes with the highest predefined associations for a given node in the graph. Usually, TKS is used for search tasks such as recommendation and alignment. The detailed statistical results of the datasets are shown in Table 7. Link-Level Tasks The edge is also an important part of the graph structure, which associates independent nodes and is the key to distinguishing graph data from non-relational data. Especially in some specific fields (e.g., molecules, proteins), edges contain real information, so there are various tasks related to edges. Link Classification Similar to the NCF, the Link Classification (LC) also assigns one or more labels to a given edge. In fact, in LC, the nodes at both ends of the edge are still taken into consideration. Link Prediction Link Prediction (LP) is a common graph task (e.g., knowledge graph). The goal of LP is to predict edges that are removed or may exist in the graph. Similar to NCI, LP is also one of the pretext tasks in self-supervised learning, and its statistic results as shown in Table 8. Top-K Recommendation Top-K Recommendation (TKR) is exactly the same as the definition of TKS, the difference lies in the sorting goal. Graph-Level Tasks The graph-level task generally focuses on the distribution of nodes, edges, and at- tributes in a given graph, in order to infer the possible properties of the entire graph. 66 Table 7: The statistics of the datasets for node-level tasks. Homogeneous:Hom, Heterogeneous:Het. Nodes 138K 317K 540K 896K 3M 4M # Task NCF Features - - - - - - Class - - - - - - Edges 739K 2M 30M 8M 47M 86M Type Hom Hom Hom Hom Hom Hom Source Citation Citation Citation Movie Social Social Usage pretrain pretrain pretrain pretrain pretrain pretrain Related Paper [195] [195] [195] [195] [195] [195] [203, 188, 214, 194, 224] [200, 201, 202, 198, 209, 211] [203, 188, 194, 224] [201, 202, 198, 209, 211] [203, 201, 202, 198, 188] [209, 211, 194, 224, 200] [215] [224, 541] [224] [189, 214, 201, 202] [191, 192] [191] [542, 543, 200, 211] [212] [192, 200] [542, 224, 543, 202, 211] [215] [224] [224] [224] [224, 202] [224] [224, 541] [224, 543] [224, 198, 209, 541] [224, 198, 209, 541, 544] [224, 198, 209, 541, 544] [224, 198, 541] [195] [191] [192] [195] [212] [195] [195] [195] Name Academia DBLP (SNAP) DBLP (NetRep) IMDB Facebook LiveJournal Downstream 1,433 Cora 7 Citation Hom 5,429 2,708 Downstream 3,703 6 4,732 CiteSeer Hom 3,327 Citation 19K Downstream Hom 500 44K PubMed 3 Citation Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream 1,902 500 2879 5,414 - - 602 - - 50 1,256 2,000 500 500 500 128 300 1639 767 745 500 500 - - - - - - - - Citation Citation Citation Social Social Social Social Social Protein Protein Movie Movie Web Web Web Web Web Web Co-purchase Co-purchase Co-author Co-author Co-author Photo Word Airline Academic Co-author Co-author Co-author 8,994 20K 2,995 233K 10K 1M 231K 130M 3,890 57K 12K 4,518 2,277 12K 89K 169K 12K 17K 14K 7,650 18K 35K 5,000 81K 4,777 1,190 178M 2,867/2,607 2,851/3,548 2,626/2,559 Hom Hom Hom Hom Hom Hom Hom Het Het Het Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Hom Het Hom Hom Hom 26K 63K 8,158 57M 334K 3M 11M - 77K 819K 37K 3,426 36K 180K 450K 117K 277K 53K 246K 119K 82K 248K 44K 6M 185K 13K 2B 7,637/4,774 6,354/7,076 8,304/6,668 ACM Cora-Full Cora-ML Reddit-233K BlogCatalog YouTube Reddit-231K Amazon PPI-30K PPI-57K IMDB Four-Univ Chameleon Crocodile Flickr-89K ogbn-arxiv Wiki-CS DBLP Computers Photo CS Physics H-index Flickr-81K Wikipedia US-Airport OAG KDD-ICDM SIGIR-CIKM SIGMOD-ICDE 4 70 7 210 39 47 41 - 50 121 4 6 6 6 7 40 10 4 10 8 15 5 - 195 40 - - 697 874 898 # NTKS Table 8: The statistics of the datasets for LC. Homogeneous:Hom, Heterogeneous:Het. Name Cora CiteSeer PubMed ML-100K ML-1M BlogCatalog-5K Amazon PPI-57K Flickr-7K Last-FM Book-Crossing OAG Usage Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Downstream Source Citation Citation Citation Movie Movie Social Social Protein Photo Music Book Academic Type Hom Hom Hom Hom Hom Hom Het Het Hom Hom Hom Het Nodes 2,708 3,327 19K 2,625 9,940 5,196 130M 57K 7,575 15K 111K 178M Edges 5,429 4,732 44K 100K 1M 172K - 819K 240M 73K 443K 2B Class 7 6 3 5 5 6 - 121 9 122 52 - Features 1,433 3,703 500 - - 8,189 - 50 12,047 - - - Related Paper [203, 188, 189, 545, 546, 214, 194, 224, 543, 542] [200, 201, 202, 198, 209, 210, 211, 544] [203, 188, 189, 546, 542, 194, 224, 200, 543] [201, 202, 198, 209, 210, 211, 541, 544] [203, 188, 189, 545, 546, 542, 194, 224, 543, 200] [201, 202, 198, 209, 210, 211, 544] [545] [545] [542, 211] [212] [542, 224, 543, 202, 211] [542, 211] [215] [215] [212] 67 Graph Classification Graph Classification (GC) is commonly used in social, molecular, and protein graph data, which aims to predict the property of the given community, chemical compound, and protein. The statistic results as shown in Table 9. Table 9: The statistics of the datasets for GC. Homogeneous:Hom, Heterogeneous:Het. Name Usage Source Type Graphs Nodes Edges Class Related Paper ZINC15 Pretraining Molecule Hom 2M - - - 190, 204] ChEMBL. Pretraining Molecule Hom 456K - - - 190, 204] PPI-pre Pretraining Protein Het 395K - - - 190] MUTAG Downstream Molecule Hom 188 - - 2 190, 547, 201, 216, 199, 218, 225, 548] PTC Downstream Molecule Hom 344 - - 2 190, 547, 201, 216, 199, 548 BBBP Downstream Molecule Hom 2,039 - - 2 190, 204, 549, 218, 220, 225 Tox21 Downstream Molecule Hom 7,831 - - 24 190, 204, 549, 218, 220, 225 ToxCast Downstream Molecule Hom 8,575 - - 1,234 190, 204, 549, 218, 220, 225 SIDER Downstream Molecule Hom 1,427 - - 54 190, 204, 549, 218, 220, 225 ClinTox Downstream Molecule Hom 1,478 - - 4 190, 204, 549, 218, 220, 225 MUV Downstream Molecule Hom 93K - - 34 190, 218, 220] HIV Downstream Molecule Hom 41K - - 2 190, 549, 218, 220] BACE Downstream Molecule Hom 1,513 - - 2 190, 549, 218, 220, 225] PPI-88K Downstream Protein Het 88K - - 80 190 IMDB-M Downstream Movie Hom 1,500. 19K 99K 3 545, 195, 547, 201, 216] IMDB-B Downstream Movie Hom 1,000 19K 97K 2 545, 195, 547, 201, 216, 218 FreeSolv Downstream Molecule Hom 642 - - - 204 ESOL Downstream Molecule Hom 1,128 - - - 204 Lipophilicity Downstream Molecule Hom 4,200 - - - 204 QM7 Downstream Molecule Hom 6,830. - - - 204 QM8 Downstream Molecule Hom 22K - - - 204 COLLAB Downstream Co-author Hom 5,000 373K - 3 195, 547, 218, 548] RDT-B Downstream Co-author Hom 2,000 859K - 2 195, 216, 218, 548] RDT-M Downstream Co-author Hom 5,000 3M - 5 195, 216, 218, 548] NCU Downstream Molecule Hom 4,110 123K 132K 2 197, 219, 547, 199, 218, 548] NCI109 Downstream Molecule Hom 4,127 123K 133K 2 199 PROTEINS Downstream Molecule Hom 1,113 44k 81K 2 197, 219, 199, 218, 548] D&D Downstream Molecule Hom 1,178 335K 843K 2 199, 218] Mutagenicity Downstream Molecule Hom 4,337 131K 134K 2 219 METR-LA Downstream Hom 1 207 550. Data Source The PFMs of GL have been widely used in a mass of fields. We will descript the details of the pretraining datasets and the downstream task datasets. Citation and Co-author network A citation is a basic local representation, whose structure reflects the citation relationships of papers in a research direction or field. Specifically, a citation network is a kind of relational data composed of research papers as nodes and citation relations as edges. Among them, the citation network used in the GL model usually comes from local samples of common citation databases, e.g., Cora, Citeseer, and PubMed, and serves as downstream tasks. Similarly, the co-author network is a dataset of scientific collaboration that corresponds to a researcher’s ego network, in which the researcher and their collaborators are nodes and an edge indicates collaboration between two researchers. According to different requirements of downstream tasks, such co-author networks can be used for various tasks, e.g., node classification and graph classification. Molecular and protein network A molecular network usually refers to a compound composed of atoms and atomic bonds, and predicting the properties of the compound is usually regarded as a graph classification task. For example, MUTAG is a collection of nitroaromatic compounds whose goal is to predict their mutagenicity to Salmonella typhimurium. PTC uses a graph to show the structure of multiple compounds and aims to predict the carcinogenicity of different compounds in rats. The protein network is a collection of proteins classified as either enzymes or non-enzymes. The amino acids are represented by nodes, and two nodes are connected by an edge if they are less than 6 Angstroms apart. 68 Social and Movie network The social network is the social-relational data in the real network environ- ment, which usually represents the relationship between users or posts. For instance, Reddit is a graph dataset comprised of Reddit posts made in September 2014. BlogCatalog is a graph dataset that represents a network of social relationships between bloggers who are listed on the BlogCatalog website. The movie network is usually composed of actors and their co-occurrence participation in the movie. For example, IMDB-B is a movie collaboration dataset that contains a large number of self-networks of actors who play movie roles in IMDB. Nodes in each graph represent actors/actresses, and if they appear in the same film, an edge connects them. These graphs are based on action and romance genres. The difference between IMDB-M and IMDB-B is that a node in the graph represents one or more actors. Others Some of the rarer graph data are used to test the universality of the PFM, such as word networks (Wikipedia), book networks (Book-crossing), and airline networks (US-Airport). In addition, there are also some special graph structures adapted to specific models, such as spatiotemporal graphs (METR-LA). # References [1] R. Bommasani, D. A. Hudson, E. Adeli, R. Altman, S. Arora, S. von Arx, M. S. Bernstein, J. Bohg, A. Bosselut, E. Brunskill, et al., “On the opportunities and risks of foundation models,” arXiv preprint arXiv:2108.07258, 2021. [2] G. G. Chowdhury, “Natural language processing,” Annual review of information science and technol- ogy, 2003. [3] D. Forsyth and J. Ponce, Computer vision: A modern approach. 2011. [4] J. A. Bondy, U. S. R. Murty, et al., Graph theory with applications. 1976. [5] X. Qiu, T. Sun, Y. Xu, Y. Shao, N. Dai, and X. Huang, “Pre-trained models for natural language processing: A survey,” Science China Technological Sciences, 2020. [6] J. Li, T. Tang, W. X. Zhao, and J.-R. Wen, “Pretrained language models for text generation: A survey,” arXiv, 2021. [7] K. Han, Y. Wang, H. Chen, X. Chen, J. Guo, Z. Liu, Y. Tang, A. Xiao, C. Xu, Y. Xu, et al., “A survey on visual transformer,” arXiv, 2020. [8] S. Sanchez, H. Romero, and A. Morales, “A review: Comparison of performance metrics of pretrained models for object detection using the tensorflow framework,” in IOP Conference Series: Materials Science and Engineering. [9] W. Hu, B. Liu, J. Gomes, M. Zitnik, P. Liang, V. Pande, and J. Leskovec, “Pre-training graph neural networks,” arXiv, 2019. [10] F. Zhuang, Z. Qi, K. Duan, D. Xi, Y. Zhu, H. Zhu, H. Xiong, and Q. He, “A comprehensive survey on transfer learning,” Proceedings of the IEEE, 2020. [11] Y. Bengio, R. Ducharme, P. Vincent, and C. Janvin, “A neural probabilistic language model,” J. Mach. Learn. Res., 2003. [12] T. Mikolov, K. Chen, G. Corrado, and J. Dean, “Efficient estimation of word representations in vector space,” in Proc. ICLR, 2013, 2013. 69 [13] J. Devlin, M. Chang, K. Lee, and K. Toutanova, “BERT: pre-training of deep bidirectional transform- ers for language understanding,” in NAACL-HLT, 2019. [14] Z. Yang, Z. Dai, Y. Yang, J. G. Carbonell, R. Salakhutdinov, and Q. V. Le, “Xlnet: Generalized autoregressive pretraining for language understanding,” in NeurIPS. [15] M. Chen, J. Tworek, H. Jun, Q. Yuan, H. P. d. O. Pinto, J. Kaplan, H. Edwards, Y. Burda, N. Joseph, G. Brockman, et al., “Evaluating large language models trained on code,” arXiv preprint arXiv:2107.03374, 2021. [16] A. Neelakantan, T. Xu, R. Puri, A. Radford, J. M. Han, J. Tworek, Q. Yuan, N. Tezak, J. W. Kim, C. Hallacy, et al., “Text and code embeddings by contrastive pre-training,” arXiv preprint arXiv:2201.10005, 2022. [17] P. F. Christiano, J. Leike, T. Brown, M. Martic, S. Legg, and D. Amodei, “Deep reinforcement learn- ing from human preferences,” Advances in neural information processing systems, vol. 30, 2017. [18] N. Stiennon, L. Ouyang, J. Wu, D. Ziegler, R. Lowe, C. Voss, A. Radford, D. Amodei, and P. F. Chris- tiano, “Learning to summarize with human feedback,” Advances in Neural Information Processing Systems, vol. 33, pp. 3008–3021, 2020. [19] L. Ouyang, J. Wu, X. Jiang, D. Almeida, C. L. Wainwright, P. Mishkin, C. Zhang, S. Agarwal, K. Slama, A. Ray, et al., “Training language models to follow instructions with human feedback,” arXiv preprint arXiv:2203.02155, 2022. [20] T. B. Brown, B. Mann, N. Ryder, M. Subbiah, J. Kaplan, P. Dhariwal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell, et al., “Language models are few-shot learners,” arXiv, 2020. [21] B. Lester, R. Al-Rfou, and N. Constant, “The power of scale for parameter-efficient prompt tun- ing,” in Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pp. 3045–3059, 2021. [22] T. Schick and H. Schütze, “Exploiting cloze-questions for few-shot text classification and natural lan- guage inference,” in Proceedings of the 16th Conference of the European Chapter of the Association for Computational Linguistics: Main Volume, pp. 255–269, 2021. [23] Z. Zhang, A. Zhang, M. Li, and A. Smola, “Automatic chain of thought prompting in large language models,” in International Conference on Learning Representations, 2023. [24] J. Wei, X. Wang, D. Schuurmans, M. Bosma, F. Xia, E. H. Chi, Q. V. Le, D. Zhou, et al., “Chain- of-thought prompting elicits reasoning in large language models,” in Advances in Neural Information Processing Systems, 2022. [25] OpenAI, “Gpt-4 technical report,” 2023. [26] P. Wang, A. Yang, R. Men, J. Lin, S. Bai, Z. Li, J. Ma, C. Zhou, J. Zhou, and H. Yang, “Unifying ar- chitectures, tasks, and modalities through a simple sequence-to-sequence learning framework,” arXiv preprint arXiv:2202.03052, 2022. [27] J. Lu, C. Clark, R. Zellers, R. Mottaghi, and A. Kembhavi, “Unified-io: A unified model for vision, language, and multi-modal tasks,” arXiv preprint arXiv:2206.08916, 2022. 70 [28] A. Singh, R. Hu, V. Goswami, G. Couairon, W. Galuba, M. Rohrbach, and D. Kiela, “Flava: A foundational language and vision alignment model,” in Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 15638–15650, 2022. [29] W. Wang, H. Bao, L. Dong, J. Bjorck, Z. Peng, Q. Liu, K. Aggarwal, O. K. Mohammed, S. Singhal, S. Som, et al., “Image as a foreign language: Beit pretraining for all vision and vision-language tasks,” arXiv preprint arXiv:2208.10442, 2022. [30] K. Clark, M. Luong, Q. V. Le, and C. D. Manning, “ELECTRA: pre-training text encoders as dis- criminators rather than generators,” in ICLR, 2020. [31] E. Wallace, P. Rodriguez, S. Feng, I. Yamada, and J. Boyd-Graber, “Trick me if you can: Human-in- the-loop generation of adversarial examples for question answering,” 2019. [32] Y. Nie, A. Williams, E. Dinan, M. Bansal, J. Weston, and D. Kiela, “Adversarial NLI: A new bench- mark for natural language understanding,” in ACL. [33] T. Niven and H. Kao, “Probing neural network comprehension of natural language arguments,” in ACL. [34] G. Wang, N. Ivanov, B. Chen, Q. Wang, and Q. Yan, “Graph learning for interactive threat detec- tion in heterogeneous smart home rule data,” in 2023 ACM SIGMOD International Conference on Management of Data, ACM, 2023. [35] M. A. Gordon, K. Duh, and N. Andrews, “Compressing BERT: studying the effects of weight pruning on transfer learning,” in RepL4NLP@ACL. [36] Z. Lan, M. Chen, S. Goodman, K. Gimpel, P. Sharma, and R. Soricut, “ALBERT: A lite BERT for self-supervised learning of language representations,” in ICLR, 2020. [37] X. Han, Z. Zhang, N. Ding, Y. Gu, X. Liu, Y. Huo, J. Qiu, L. Zhang, W. Han, M. Huang, et al., “Pre-trained models: Past, present and future,” AI Open, 2021. [38] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, and I. Polosukhin, “Attention is all you need,” arXiv, 2017. [39] M.-H. Guo, T.-X. Xu, J.-J. Liu, Z.-N. Liu, P.-T. Jiang, T.-J. Mu, S.-H. Zhang, R. R. Martin, M.-M. Cheng, and S.-M. Hu, “Attention mechanisms in computer vision: A survey,” Computational Visual Media, vol. 8, no. 3, pp. 331–368, 2022. [40] A. Dosovitskiy, L. Beyer, A. Kolesnikov, D. Weissenborn, X. Zhai, T. Unterthiner, M. Dehghani, M. Minderer, G. Heigold, S. Gelly, et al., “An image is worth 16x16 words: Transformers for image recognition at scale,” arXiv preprint arXiv:2010.11929, 2020. [41] S. Yun, M. Jeong, R. Kim, J. Kang, and H. J. Kim, “Graph transformer networks,” Advances in neural information processing systems, vol. 32, 2019. [42] B. M. P. P. J. H. J. G. A. S. M. C. R. G. I. A. R. J. L. B. M. T. A. A. X. W. C. R. M. M. J. P. U. E. M. K. S. v. S. G. F. E. A. M. F. Y. A. O. F. H. J. B. M. P. C. A. A. G. V. B. C. V. Y. T. T. M. A. K. F. P. D. T. T. K. M. L. X. Z. D. K. J. H. N. H. Mostafa Dehghani, Josip Djolonga, “Scaling vision transformers to 22 billion parameters,” arXiv preprint arXiv:2302.05442, 2023. 71 [43] A. Chowdhery, S. Narang, J. Devlin, M. Bosma, G. Mishra, A. Roberts, P. Barham, H. W. Chung, C. Sutton, S. Gehrmann, et al., “Palm: Scaling language modeling with pathways,” arXiv preprint arXiv:2204.02311, 2022. [44] M. Joshi, D. Chen, Y. Liu, D. S. Weld, L. Zettlemoyer, and O. Levy, “Spanbert: Improving pre- training by representing and predicting spans,” Trans. Assoc. Comput. Linguistics, 2020. [45] M. Lewis, Y. Liu, N. Goyal, M. Ghazvininejad, A. Mohamed, O. Levy, V. Stoyanov, and L. Zettle- moyer, “BART: denoising sequence-to-sequence pre-training for natural language generation, trans- lation, and comprehension,” in ACL. [46] K. Clark, M.-T. Luong, Q. V. Le, and C. D. Manning, “Electra: Pre-training text encoders as discrim- inators rather than generators,” arXiv, 2020. [47] Z. Lan, M. Chen, S. Goodman, K. Gimpel, P. Sharma, and R. Soricut, “Albert: A lite bert for self- supervised learning of language representations,” arXiv, 2019. [48] J. Donahue, P. Krähenbühl, and T. Darrell, “Adversarial feature learning,” arXiv, 2016. [49] M. Caron, P. Bojanowski, A. Joulin, and M. Douze, “Deep clustering for unsupervised learning of visual features,” in ECCV. [50] A. Radford, K. Narasimhan, T. Salimans, and I. Sutskever, “Improving language understanding by generative pre-training,” 2018. [51] A. Radford, J. Wu, R. Child, D. Luan, D. Amodei, and I. Sutskever, “Language models are unsuper- vised multitask learners,” OpenAI blog, 2019. [52] R. Caruana, “Multitask learning,” Machine learning, 1997. [53] M. E. Peters, M. Neumann, M. Iyyer, M. Gardner, C. Clark, K. Lee, and L. Zettlemoyer, “Deep contextualized word representations,” arXiv, 2018. [54] Y. Wu, M. Schuster, Z. Chen, Q. V. Le, M. Norouzi, W. Macherey, M. Krikun, Y. Cao, Q. Gao, K. Macherey, et al., “Google’s neural machine translation system: Bridging the gap between human and machine translation,” arXiv, 2016. [55] Y. Liu, M. Ott, N. Goyal, J. Du, M. Joshi, D. Chen, O. Levy, M. Lewis, L. Zettlemoyer, and V. Stoy- anov, “Roberta: A robustly optimized BERT pretraining approach,” CoRR, 2019. [56] R. Sennrich, B. Haddow, and A. Birch, “Neural machine translation of rare words with subword units,” arXiv, 2015. [57] K. Song, X. Tan, T. Qin, J. Lu, and T. Liu, “Mpnet: Masked and permuted pre-training for language understanding,” in NeurIPS, 2020. [58] Q. Li, H. Peng, J. Li, C. Xia, R. Yang, L. Sun, P. S. Yu, and L. He, “A survey on text classification: From traditional to deep learning,” ACM Transactions on Intelligent Systems and Technology (TIST), vol. 13, no. 2, pp. 1–41, 2022. [59] K. Song, X. Tan, T. Qin, J. Lu, and T.-Y. Liu, “Mass: Masked sequence to sequence pre-training for language generation,” arXiv, 2019. 72 [60] L. Dong, N. Yang, W. Wang, F. Wei, X. Liu, Y. Wang, J. Gao, M. Zhou, and H.-W. Hon, “Unified language model pre-training for natural language understanding and generation,” arXiv, 2019. [61] Y. Sun, S. Wang, Y. Li, S. Feng, X. Chen, H. Zhang, X. Tian, D. Zhu, H. Tian, and H. Wu, “Ernie: Enhanced representation through knowledge integration,” arXiv, 2019. [62] Y. Sun, S. Wang, Y. Li, S. Feng, H. Tian, H. Wu, and H. Wang, “Ernie 2.0: A continual pre-training framework for language understanding,” in AAAI. [63] Y. Cui, W. Che, T. Liu, B. Qin, and Z. Yang, “Pre-training with whole word masking for chinese BERT,” T-ASL, 2021. [64] S. Diao, J. Bai, Y. Song, T. Zhang, and Y. Wang, “ZEN: pre-training chinese text encoder enhanced by n-gram representations,” in EMNLP. [65] H. Tsai, J. Riesa, M. Johnson, N. Arivazhagan, X. Li, and A. Archer, “Small and practical bert models for sequence labeling,” arXiv, 2019. [66] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov, “Proximal policy optimization algorithms,” arXiv preprint arXiv:1707.06347, 2017. [67] R. Thoppilan, D. De Freitas, J. Hall, N. Shazeer, A. Kulshreshtha, H.-T. Cheng, A. Jin, T. Bos, L. Baker, Y. Du, et al., “Lamda: Language models for dialog applications,” arXiv preprint arXiv:2201.08239, 2022. [68] T. Mikolov, I. Sutskever, K. Chen, G. Corrado, and J. Dean, “Distributed representations of words and phrases and their compositionality,” arXiv, 2013. [69] J. Pennington, R. Socher, and C. D. Manning, “Glove: Global vectors for word representation,” in EMNLP. [70] A. M. Dai and Q. V. Le, “Semi-supervised sequence learning,” arXiv, 2015. [71] P. Liu, X. Qiu, and X. Huang, “Recurrent neural network for text classification with multi-task learn- ing,” arXiv, 2016. [72] P. Bojanowski, E. Grave, A. Joulin, and T. Mikolov, “Enriching word vectors with subword informa- tion,” TACL, 2017. [73] B. McCann, J. Bradbury, C. Xiong, and R. Socher, “Learned in translation: Contextualized word vectors,” arXiv, 2017. [74] Z. Dai, Z. Yang, Y. Yang, J. Carbonell, Q. V. Le, and R. Salakhutdinov, “Transformer-xl: Attentive language models beyond a fixed-length context,” arXiv, 2019. [75] L. Kong, C. d. M. d’Autume, W. Ling, L. Yu, Z. Dai, and D. Yogatama, “A mutual information maximization perspective of language representation learning,” arXiv, 2019. [76] W. Wang, B. Bi, M. Yan, C. Wu, Z. Bao, J. Xia, L. Peng, and L. Si, “Structbert: Incorporating language structures into pre-training for deep language understanding,” arXiv, 2019. [77] W. Xiong, J. Du, W. Y. Wang, and V. Stoyanov, “Pretrained encyclopedia: Weakly supervised knowledge-pretrained language model,” arXiv, 2019. 73 [78] M. E. Peters, M. Neumann, R. L. Logan IV, R. Schwartz, V. Joshi, S. Singh, and N. A. Smith, “Knowledge enhanced contextual word representations,” arXiv, 2019. [79] H. Huang, Y. Liang, N. Duan, M. Gong, L. Shou, D. Jiang, and M. Zhou, “Unicoder: A universal language encoder by pre-training with multiple cross-lingual tasks,” arXiv, 2019. [80] J. M. Eisenschlos, S. Ruder, P. Czapla, M. Kardas, S. Gugger, and J. Howard, “Multifit: Efficient multi-lingual language model fine-tuning,” arXiv, 2019. [81] I. Beltagy, K. Lo, and A. Cohan, “Scibert: A pretrained language model for scientific text,” arXiv, 2019. [82] S. Sun, Y. Cheng, Z. Gan, and J. Liu, “Patient knowledge distillation for bert model compression,” arXiv, 2019. [83] G. Lample and A. Conneau, “Cross-lingual language model pretraining,” arXiv, 2019. [84] O. Zafrir, G. Boudoukh, P. Izsak, and M. Wasserblat, “Q8BERT: quantized 8bit BERT,” in EMC2@NeurIPS. [85] V. Sanh, L. Debut, J. Chaumond, and T. Wolf, “Distilbert, a distilled version of bert: smaller, faster, cheaper and lighter,” arXiv, 2019. [86] W. Liu, P. Zhou, Z. Zhao, Z. Wang, H. Deng, and Q. Ju, “Fastbert: a self-distilling bert with adaptive inference time,” arXiv, 2020. [87] L. Martin, B. Müller, P. J. O. Suárez, Y. Dupont, L. Romary, É. de la Clergerie, D. Seddah, and B. Sagot, “Camembert: a tasty french language model,” in ACL. [88] A. Conneau, K. Khandelwal, N. Goyal, V. Chaudhary, G. Wenzek, F. Guzmán, E. Grave, M. Ott, L. Zettlemoyer, and V. Stoyanov, “Unsupervised cross-lingual representation learning at scale,” in ACL. [89] N. Kitaev, L. Kaiser, and A. Levskaya, “Reformer: The efficient transformer,” in ICLR, 2020. [90] S. Shen, Z. Dong, J. Ye, L. Ma, Z. Yao, A. Gholami, M. W. Mahoney, and K. Keutzer, “Q-bert: Hessian based ultra low precision quantization of bert,” in AAAI. [91] Z. Chi, L. Dong, F. Wei, W. Wang, X.-L. Mao, and H. Huang, “Cross-lingual natural language gener- ation via pre-training,” in AAAI. [92] W. Liu, P. Zhou, Z. Zhao, Z. Wang, Q. Ju, H. Deng, and P. Wang, “K-bert: Enabling language representation with knowledge graph,” in AAAI. [93] Z. Jiang, W. Yu, D. Zhou, Y. Chen, J. Feng, and S. Yan, “Convbert: Improving BERT with span-based dynamic convolution,” in NeurIPS, 2020. [94] W. Wang, F. Wei, L. Dong, H. Bao, N. Yang, and M. Zhou, “Minilm: Deep self-attention distillation for task-agnostic compression of pre-trained transformers,” in NeurIPS, 2020. [95] Y. Liu, J. Gu, N. Goyal, X. Li, S. Edunov, M. Ghazvininejad, M. Lewis, and L. Zettlemoyer, “Mul- tilingual denoising pre-training for neural machine translation,” Trans. Assoc. Comput. Linguistics, 2020. 74 [96] T. Sun, Y. Shao, X. Qiu, Q. Guo, Y. Hu, X. Huang, and Z. Zhang, “Colake: Contextualized language and knowledge embedding,” in COLING. [97] H. Le, L. Vial, J. Frej, V. Segonne, M. Coavoux, B. Lecouteux, A. Allauzen, B. Crabbé, L. Besacier, and D. Schwab, “Flaubert: Unsupervised language model pre-training for french,” in LREC. [98] T. Shen, Y. Mao, P. He, G. Long, A. Trischler, and W. Chen, “Exploiting structured knowledge in text via graph-guided representation learning,” in EMNLP. [99] X. Jiao, Y. Yin, L. Shang, X. Jiang, X. Chen, L. Li, F. Wang, and Q. Liu, “Tinybert: Distilling BERT for natural language understanding,” in EMNLP. [100] P. Delobelle, T. Winters, and B. Berendt, “Robbert: a dutch roberta-based language model,” in EMNLP. [101] B. He, D. Zhou, J. Xiao, X. Jiang, Q. Liu, N. J. Yuan, and T. Xu, “Integrating graph contextualized knowledge into pre-trained language models,” in EMNLP. [102] C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li, and P. J. Liu, “Exploring the limits of transfer learning with a unified text-to-text transformer,” J. Mach. Learn. Res., 2020. [103] T. Schick and H. Schütze, “Exploiting cloze-questions for few-shot text classification and natural language inference,” in EACL, 2021. [104] X. Wang, T. Gao, Z. Zhu, Z. Zhang, Z. Liu, J. Li, and J. Tang, “KEPLER: A unified model for knowledge embedding and pre-trained language representation,” Trans. Assoc. Comput. Linguistics, 2021. [105] T. Gao, X. Yao, and D. Chen, “Simcse: Simple contrastive learning of sentence embeddings,” CoRR, 2021. [106] N. Du, Y. Huang, A. M. Dai, S. Tong, D. Lepikhin, Y. Xu, M. Krikun, Y. Zhou, A. W. Yu, O. Fi- rat, et al., “Glam: Efficient scaling of language models with mixture-of-experts,” in International Conference on Machine Learning, pp. 5547–5569, PMLR, 2022. [107] Z. Chi, S. Huang, L. Dong, S. Ma, S. Singhal, P. Bajaj, X. Song, and F. Wei, “Xlm-e: Cross-lingual language model pre-training via electra,” arXiv preprint arXiv:2106.16138, 2021. [108] V. Sanh, A. Webson, C. Raffel, S. H. Bach, L. Sutawika, Z. Alyafeai, A. Chaffin, A. Stiegler, T. L. Scao, A. Raja, et al., “Multitask prompted training enables zero-shot task generalization,” arXiv preprint arXiv:2110.08207, 2021. [109] J. W. Rae, S. Borgeaud, T. Cai, K. Millican, J. Hoffmann, F. Song, J. Aslanides, S. Henderson, R. Ring, S. Young, et al., “Scaling language models: Methods, analysis & insights from training gopher,” arXiv preprint arXiv:2112.11446, 2021. [110] S. Smith, M. Patwary, B. Norick, P. LeGresley, S. Rajbhandari, J. Casper, Z. Liu, S. Prabhumoye, G. Zerveas, V. Korthikanti, et al., “Using deepspeed and megatron to train megatron-turing nlg 530b, a large-scale generative language model,” arXiv preprint arXiv:2201.11990, 2022. [111] J. Hoffmann, S. Borgeaud, A. Mensch, E. Buchatskaya, T. Cai, E. Rutherford, D. d. L. Casas, L. A. Hendricks, J. Welbl, A. Clark, et al., “Training compute-optimal large language models,” arXiv preprint arXiv:2203.15556, 2022. 75 [112] S. Zhang, S. Roller, N. Goyal, M. Artetxe, M. Chen, S. Chen, C. Dewan, M. Diab, X. Li, X. V. Lin, et al., “Opt: Open pre-trained transformer language models,” arXiv preprint arXiv:2205.01068, 2022. [113] J. Wei, M. Bosma, V. Zhao, K. Guu, A. W. Yu, B. Lester, N. Du, A. M. Dai, and Q. V. Le, “Finetuned language models are zero-shot learners,” in International Conference on Learning Representations, 2022. [114] O. Honovich, T. Scialom, O. Levy, and T. Schick, “Unnatural instructions: Tuning language models with (almost) no human labor,” arXiv preprint arXiv:2212.09689, 2022. [115] Y. Wang, S. Mishra, P. Alipoormolabashi, Y. Kordi, A. Mirzaei, A. Naik, A. Ashok, A. S. Dhanasekaran, A. Arunkumar, D. Stap, et al., “Super-naturalinstructions: Generalization via declar- ative instructions on 1600+ nlp tasks,” in Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing, pp. 5085–5109, 2022. [116] S. Mishra, D. Khashabi, C. Baral, and H. Hajishirzi, “Cross-task generalization via natural language crowdsourcing instructions,” in Proceedings of the 60th Annual Meeting of the Association for Com- putational Linguistics (Volume 1: Long Papers), pp. 3470–3487, 2022. [117] Y. Wang, Y. Kordi, S. Mishra, A. Liu, N. A. Smith, D. Khashabi, and H. Hajishirzi, “Self-instruct: Aligning language model with self generated instructions,” arXiv preprint arXiv:2212.10560, 2022. [118] L. Weidinger, J. Mellor, M. Rauh, C. Griffin, J. Uesato, P.-S. Huang, M. Cheng, M. Glaese, B. Balle, A. Kasirzadeh, et al., “Ethical and social risks of harm from language models,” arXiv preprint arXiv:2112.04359, 2021. [119] S. Kiegeland and J. Kreutzer, “Revisiting the weaknesses of reinforcement learning for neural ma- chine translation,” in Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 1673–1681, 2021. [120] N. Jaques, J. H. Shen, A. Ghandeharioun, C. Ferguson, A. Lapedriza, N. Jones, S. Gu, and R. Pi- card, “Human-centric dialog training via offline reinforcement learning,” in Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pp. 3985–4003, 2020. [121] S. J. Rennie, E. Marcheret, Y. Mroueh, J. Ross, and V. Goel, “Self-critical sequence training for image captioning,” in Proceedings of the IEEE conference on computer vision and pattern recognition, pp. 7008–7024, 2017. [122] R. Y. Pang and H. He, “Text generation by learning from demonstrations,” in Proceedings of the international conference on learning representations, 2021. [123] M. Hausknecht, P. Ammanabrolu, M.-A. Côté, and X. Yuan, “Interactive fiction games: A colossal adventure,” in Proceedings of the AAAI Conference on Artificial Intelligence, vol. 34, pp. 7903–7910, 2020. [124] C. Snell, I. Kostrikov, Y. Su, M. Yang, and S. Levine, “Offline rl for natural language generation with implicit language q learning,” arXiv preprint arXiv:2206.11871, 2022. [125] X. Lu, S. Welleck, L. Jiang, J. Hessel, L. Qin, P. West, P. Ammanabrolu, and Y. Choi, “Quark: Controllable text generation with reinforced unlearning,” arXiv preprint arXiv:2205.13636, 2022. [126] V. Uc-Cetina, N. Navarro-Guerrero, A. Martin-Gonzalez, C. Weber, and S. Wermter, “Survey on reinforcement learning for language processing,” Artificial Intelligence Review, pp. 1–33, 2022. 76 [127] R. Ramamurthy, P. Ammanabrolu, K. Brantley, J. Hessel, R. Sifa, C. Bauckhage, H. Hajishirzi, and Y. Choi, “Is reinforcement learning (not) for natural language processing?: Benchmarks, baselines, and building blocks for natural language policy optimization,” arXiv preprint arXiv:2210.01241, 2022. [128] J. Wu, L. Ouyang, D. M. Ziegler, N. Stiennon, R. Lowe, J. Leike, and P. Christiano, “Recursively summarizing books with human feedback,” arXiv preprint arXiv:2109.10862, 2021. [129] R. Nakano, J. Hilton, S. Balaji, J. Wu, L. Ouyang, C. Kim, C. Hesse, S. Jain, V. Kosaraju, W. Saun- ders, et al., “Webgpt: Browser-assisted question-answering with human feedback,” arXiv preprint arXiv:2112.09332, 2021. [130] A. Glaese, N. McAleese, M. Tr˛ebacz, J. Aslanides, V. Firoiu, T. Ewalds, M. Rauh, L. Weidinger, M. Chadwick, P. Thacker, et al., “Improving alignment of dialogue agents via targeted human judge- ments,” arXiv preprint arXiv:2209.14375, 2022. [131] Y. Bai, S. Kadavath, S. Kundu, A. Askell, J. Kernion, A. Jones, A. Chen, A. Goldie, A. Mirho- seini, C. McKinnon, et al., “Constitutional ai: Harmlessness from ai feedback,” arXiv preprint arXiv:2212.08073, 2022. [132] H. W. Chung, L. Hou, S. Longpre, B. Zoph, Y. Tay, W. Fedus, E. Li, X. Wang, M. Dehghani, S. Brahma, et al., “Scaling instruction-finetuned language models,” arXiv preprint arXiv:2210.11416, 2022. [133] T. Kojima, S. S. Gu, M. Reid, Y. Matsuo, and Y. Iwasawa, “Large language models are zero-shot rea- soners,” in Advances in Neural Information Processing Systems (A. H. Oh, A. Agarwal, D. Belgrave, and K. Cho, eds.), 2022. [134] A. Dosovitskiy, J. T. Springenberg, M. Riedmiller, and T. Brox, “Discriminative unsupervised feature learning with convolutional neural networks,” Advances in neural information processing systems, 2014. [135] A. Dosovitskiy, P. Fischer, J. T. Springenberg, M. Riedmiller, and T. Brox, “Discriminative unsuper- vised feature learning with exemplar convolutional neural networks,” TPAMI, 2016. [136] C. Doersch, A. Gupta, and A. A. Efros, “Unsupervised visual representation learning by context prediction,” in ICCV. [137] D. Pathak, P. Krahenbuhl, J. Donahue, T. Darrell, and A. A. Efros, “Context encoders: Feature learn- ing by inpainting,” in CVPR. [138] R. Zhang, P. Isola, and A. A. Efros, “Colorful image colorization,” in ECCV, 2016. [139] R. Zhang, P. Isola, and A. A. Efros, “Split-brain autoencoders: Unsupervised learning by cross- channel prediction,” in CVPR. [140] M. Noroozi and P. Favaro, “Unsupervised learning of visual representations by solving jigsaw puz- zles,” in ECCV. [141] D. Kim, D. Cho, D. Yoo, and I. S. Kweon, “Learning image representations by completing damaged jigsaw puzzles,” in WACV. [142] M. Noroozi, H. Pirsiavash, and P. Favaro, “Representation learning by learning to count,” in ICCV. 77 [143] P. Bojanowski and A. Joulin, “Unsupervised learning by predicting noise,” in ICML, 2017. [144] S. Gidaris, P. Singh, and N. Komodakis, “Unsupervised representation learning by predicting image rotations,” arXiv, 2018. [145] A. v. d. Oord, Y. Li, and O. Vinyals, “Representation learning with contrastive predictive coding,” arXiv, 2018. [146] O. Henaff, “Data-efficient image recognition with contrastive predictive coding,” in ICML, 2020. [147] J. Donahue and K. Simonyan, “Large scale adversarial representation learning,” in NeurIPS. [148] V. Dumoulin, I. Belghazi, B. Poole, O. Mastropietro, A. Lamb, M. Arjovsky, and A. Courville, “Ad- versarially learned inference,” arXiv, 2016. [149] M. Chen, A. Radford, R. Child, J. Wu, H. Jun, D. Luan, and I. Sutskever, “Generative pretraining from pixels,” in ICML, 2020. [150] H. Bao, L. Dong, S. Piao, and F. Wei, “Beit: Bert pre-training of image transformers,” in International Conference on Learning Representations, 2021. [151] M. Caron, H. Touvron, I. Misra, H. Jégou, J. Mairal, P. Bojanowski, and A. Joulin, “Emerging prop- erties in self-supervised vision transformers,” in Proceedings of the IEEE/CVF International Confer- ence on Computer Vision, pp. 9650–9660, 2021. [152] A. Ramesh, M. Pavlov, G. Goh, S. Gray, C. Voss, A. Radford, M. Chen, and I. Sutskever, “Zero- shot text-to-image generation,” in International Conference on Machine Learning, pp. 8821–8831, PMLR, 2021. [153] Z. Wu, Y. Xiong, S. X. Yu, and D. Lin, “Unsupervised feature learning via non-parametric instance discrimination,” in CVPR. [154] K. He, X. Chen, S. Xie, Y. Li, P. Dollár, and R. Girshick, “Masked autoencoders are scalable vision learners,” in Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 16000–16009, 2022. [155] Z. Xie, Z. Zhang, Y. Cao, Y. Lin, J. Bao, Z. Yao, Q. Dai, and H. Hu, “Simmim: A simple framework for masked image modeling,” in Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 9653–9663, 2022. [156] A. Kirillov, E. Mintun, N. Ravi, H. Mao, C. Rolland, L. Gustafson, T. Xiao, S. Whitehead, A. C. Berg, W.-Y. Lo, et al., “Segment anything,” arXiv preprint arXiv:2304.02643, 2023. [157] Z. Liu, Y. Lin, Y. Cao, H. Hu, Y. Wei, Z. Zhang, S. Lin, and B. Guo, “Swin transformer: Hierarchical vision transformer using shifted windows,” in Proceedings of the IEEE/CVF International Conference on Computer Vision, pp. 10012–10022, 2021. [158] X. Li, W. Wang, L. Yang, and J. Yang, “Uniform masking: Enabling mae pre-training for pyramid- based vision transformers with locality,” arXiv preprint arXiv:2205.10063, 2022. [159] J. Chen, M. Hu, B. Li, and M. Elhoseiny, “Efficient self-supervised vision pretraining with local masked reconstruction,” arXiv preprint arXiv:2206.00790, 2022. [160] G. Hinton, O. Vinyals, and J. Dean, “Distilling the knowledge in a neural network,” arXiv, 2015. 78 [161] C. Zhuang, A. L. Zhai, and D. Yamins, “Local aggregation for unsupervised learning of visual em- beddings,” in ICCV. [162] I. Misra and L. v. d. Maaten, “Self-supervised learning of pretext-invariant representations,” in CVPR. [163] K. He, H. Fan, Y. Wu, S. Xie, and R. Girshick, “Momentum contrast for unsupervised visual repre- sentation learning,” in CVPR. [164] X. Chen, H. Fan, R. Girshick, and K. He, “Improved baselines with momentum contrastive learning,” arXiv, 2020. [165] J.-B. Grill, F. Strub, F. Altché, C. Tallec, P. H. Richemond, E. Buchatskaya, C. Doersch, B. A. Pires, Z. D. Guo, M. G. Azar, et al., “Bootstrap your own latent: A new approach to self-supervised learn- ing,” arXiv, 2020. [166] T. Chen, S. Kornblith, M. Norouzi, and G. Hinton, “A simple framework for contrastive learning of visual representations,” in ICML. [167] M. Caron, I. Misra, J. Mairal, P. Goyal, P. Bojanowski, and A. Joulin, “Unsupervised learning of visual features by contrasting cluster assignments,” arXiv, 2020. [168] P. Goyal, M. Caron, B. Lefaudeux, M. Xu, P. Wang, V. Pai, M. Singh, V. Liptchinsky, I. Misra, A. Joulin, et al., “Self-supervised pretraining of visual features in the wild,” arXiv, 2021. [169] I. Radosavovic, R. P. Kosaraju, R. Girshick, K. He, and P. Dollár, “Designing network design spaces,” in CVPR. [170] X. Chen and K. He, “Exploring simple siamese representation learning,” in CVPR. [171] J. Li, P. Zhou, C. Xiong, and S. C. H. Hoi, “Prototypical contrastive learning of unsupervised repre- sentations,” in ICLR, OpenReview.net, 2021. [172] L. Zhang, G.-J. Qi, L. Wang, and J. Luo, “Aet vs. aed: Unsupervised representation learning by auto-encoding transformations rather than data,” in CVPR. [173] P. Bachman, R. D. Hjelm, and W. Buchwalter, “Learning representations by maximizing mutual information across views,” arXiv, 2019. [174] X. Yan, I. Misra, A. Gupta, D. Ghadiyaram, and D. Mahajan, “Clusterfit: Improving generalization of visual representations,” in CVPR, 2020. [175] Y. M. Asano, C. Rupprecht, and A. Vedaldi, “Self-labelling via simultaneous clustering and represen- tation learning,” arXiv preprint arXiv:1911.05371, 2019. [176] T. Chen, S. Kornblith, K. Swersky, M. Norouzi, and G. Hinton, “Big self-supervised models are strong semi-supervised learners,” arXiv, 2020. [177] Y. Tian, D. Krishnan, and P. Isola, “Contrastive multiview coding,” arXiv, 2019. [178] E. D. Cubuk, B. Zoph, J. Shlens, and Q. V. Le, “Randaugment: Practical data augmentation with no separate search,” arXiv, 2019. [179] Y. Tian, C. Sun, B. Poole, D. Krishnan, C. Schmid, and P. Isola, “What makes for good views for contrastive learning,” arXiv, 2020. 79 [180] X. Chen, S. Xie, and K. He, “An empirical study of training self-supervised vision transformers,” arXiv, 2021. [181] J. Mitrovic, B. McWilliams, J. C. Walker, L. H. Buesing, and C. Blundell, “Representation learning via invariant causal mechanisms,” in ICLR. [182] Y. Tian, X. Chen, and S. Ganguli, “Understanding self-supervised learning dynamics without con- trastive pairs,” in ICML. [183] Z. Xie, Y. Lin, Z. Yao, Z. Zhang, Q. Dai, Y. Cao, and H. Hu, “Self-supervised learning with swin transformers,” arXiv, 2021. [184] Z. Li, Z. Chen, F. Yang, W. Li, Y. Zhu, C. Zhao, R. Deng, L. Wu, R. Zhao, M. Tang, et al., “Mst: Masked self-supervised transformer for visual representation,” Advances in Neural Information Pro- cessing Systems, vol. 34, 2021. [185] H. Bao, L. Dong, S. Piao, and F. Wei, “BEit: BERT pre-training of image transformers,” in Interna- tional Conference on Learning Representations, 2022. [186] X. Chen, M. Ding, X. Wang, Y. Xin, S. Mo, Y. Wang, S. Han, P. Luo, G. Zeng, and J. Wang, “Context autoencoder for self-supervised representation learning,” arXiv preprint arXiv:2202.03026, 2022. [187] X. Dong, J. Bao, T. Zhang, D. Chen, W. Zhang, L. Yuan, D. Chen, F. Wen, and N. Yu, “Peco: Perceptual codebook for bert pre-training of vision transformers,” arXiv preprint arXiv:2111.12710, 2021. [188] Y. You, T. Chen, Z. Wang, and Y. Shen, “When does self-supervision help graph convolutional net- works?,” in ICML. [189] W. Jin, T. Derr, H. Liu, Y. Wang, S. Wang, Z. Liu, and J. Tang, “Self-supervised learning on graphs: Deep insights and new direction,” CoRR, 2020. [190] W. Hu, B. Liu, J. Gomes, M. Zitnik, P. Liang, V. S. Pande, and J. Leskovec, “Strategies for pre-training graph neural networks,” in ICLR, 2020. [191] B. Perozzi, R. Al-Rfou, and S. Skiena, “Deepwalk: online learning of social representations,” in ACM SIGKDD. [192] A. Grover and J. Leskovec, “node2vec: Scalable feature learning for networks,” in ACM SIGKDD. [193] J. Tang, M. Qu, M. Wang, M. Zhang, J. Yan, and Q. Mei, “LINE: large-scale information network embedding,” in WWW. [194] T. N. Kipf and M. Welling, “Variational graph auto-encoders,” CoRR, 2016. [195] J. Qiu, Q. Chen, Y. Dong, J. Zhang, H. Yang, M. Ding, K. Wang, and J. Tang, “GCC: graph contrastive coding for graph neural network pre-training,” in KDD. [196] Y. Zhu, Y. Xu, F. Yu, Q. Liu, S. Wu, and L. Wang, “Graph contrastive learning with adaptive aug- mentation,” in WWW, 2021. [197] Y. You, T. Chen, Y. Sui, T. Chen, Z. Wang, and Y. Shen, “Graph contrastive learning with augmenta- tions,” in NeurIPS, 2020. 80 [198] C. Mavromatis and G. Karypis, “Graph infoclust: Maximizing coarse-grain mutual information in graphs,” in PAKDD, 2021. [199] Q. Sun, J. Li, H. Peng, J. Wu, Y. Ning, P. S. Yu, and L. He, “SUGAR: subgraph neural network with reinforcement pooling and self-supervised mutual information mechanism,” in WWW, 2021. [200] P. Velickovic, W. Fedus, W. L. Hamilton, P. Liò, Y. Bengio, and R. D. Hjelm, “Deep graph infomax,” in ICLR, 2019. [201] K. Hassani and A. H. K. Ahmadi, “Contrastive multi-view representation learning on graphs,” in ICML. [202] Y. Jiao, Y. Xiong, J. Zhang, Y. Zhang, T. Zhang, and Y. Zhu, “Sub-graph contrast for scalable self- supervised graph representation learning,” in ICDM. [203] K. Sun, Z. Lin, and Z. Zhu, “Multi-stage self-supervised learning for graph convolutional networks on graphs with few labeled nodes,” in AAAI. [204] Y. Rong, Y. Bian, T. Xu, W. Xie, Y. Wei, W. Huang, and J. Huang, “Self-supervised graph transformer on large-scale molecular data,” in NeurIPS, 2020. [205] Q. Tan, N. Liu, X. Huang, R. Chen, S.-H. Choi, and X. Hu, “Mgae: Masked autoencoders for self- supervised learning on graphs,” arXiv preprint arXiv:2201.02534, 2022. [206] Z. Hou, X. Liu, Y. Dong, C. Wang, J. Tang, et al., “Graphmae: Self-supervised masked graph autoen- coders,” arXiv preprint arXiv:2205.10803, 2022. [207] J. Li, R. Wu, W. Sun, L. Chen, S. Tian, L. Zhu, C. Meng, Z. Zheng, and W. Wang, “Maskgae: Masked graph modeling meets graph autoencoders,” arXiv preprint arXiv:2205.10053, 2022. [208] Y. Tian, K. Dong, C. Zhang, C. Zhang, and N. V. Chawla, “Heterogeneous graph masked autoen- coders,” arXiv preprint arXiv:2208.09957, 2022. [209] S. Wan, S. Pan, J. Yang, and C. Gong, “Contrastive and generative graph convolutional networks for graph-based semi-supervised learning,” in AAAI. [210] J. Zhang, H. Zhang, C. Xia, and L. Sun, “Graph-bert: Only attention is needed for learning graph representations,” arXiv, 2020. [211] Z. Peng, W. Huang, M. Luo, Q. Zheng, Y. Rong, T. Xu, and J. Huang, “Graph representation learning via graphical mutual information maximization,” in WWW, 2020. [212] Z. Hu, Y. Dong, K. Wang, K. Chang, and Y. Sun, “GPT-GNN: generative pre-training of graph neural networks,” in KDD. [213] G. Wang, H. Guo, A. Li, X. Liu, and Q. Yan, “Federated iot interaction vulnerability analysis,” in 2023 IEEE 39th International Conference on Data Engineering (ICDE), IEEE, 2023. [214] W. L. Hamilton, Z. Ying, and J. Leskovec, “Inductive representation learning on large graphs,” in NIPS, 2017. [215] D. Hwang, J. Park, S. Kwon, K. Kim, J. Ha, and H. J. Kim, “Self-supervised auxiliary learning with meta-paths for heterogeneous graphs,” in NeurIPS, 2020. 81 [216] F. Sun, J. Hoffmann, V. Verma, and J. Tang, “Infograph: Unsupervised and semi-supervised graph- level representation learning via mutual information maximization,” in ICLR, 2020. [217] C. Park, D. Kim, J. Han, and H. Yu, “Unsupervised attributed multiplex network embedding,” in AAAI. [218] Y. You, T. Chen, Y. Shen, and Z. Wang, “Graph contrastive learning automated,” CoRR, 2021. [219] J. Zeng and P. Xie, “Contrastive self-supervised learning for graph classification,” in AAAI. [220] M. Xu, H. Wang, B. Ni, H. Guo, and J. Tang, “Self-supervised graph-level representation learning with local and global structure,” CoRR, 2021. [221] P. Wang, K. Agarwal, C. Ham, S. Choudhury, and C. K. Reddy, “Self-supervised learning of contex- tual embeddings for link prediction in heterogeneous networks,” in WWW. [222] J. Cao, X. Lin, S. Guo, L. Liu, T. Liu, and B. Wang, “Bipartite graph embedding via mutual informa- tion maximization,” in WSDM, 2021. [223] X. Wang, N. Liu, H. Han, and C. Shi, “Self-supervised heterogeneous graph neural network with co-contrastive learning,” KDD, 2021. [224] D. Kim and A. Oh, “How to find your friendly neighborhood: Graph attention design with self- supervision,” in ICLR, 2021. [225] M. Sun, J. Xing, H. Wang, B. Chen, and J. Zhou, “Mocl: Contrastive learning on molecular graphs with multi-level domain knowledge,” CoRR, 2021. [226] S. Schneider, A. Baevski, R. Collobert, and M. Auli, “wav2vec: Unsupervised pre-training for speech recognition,” in INTERSPEECH. [227] A. Baevski, S. Schneider, and M. Auli, “vq-wav2vec: Self-supervised learning of discrete speech representations,” in ICLR. [228] A. Baevski, Y. Zhou, A. Mohamed, and M. Auli, “wav2vec 2.0: A framework for self-supervised learning of speech representations,” in NeurIPS, 2020. [229] Y. Chung and J. R. Glass, “Generative pre-training for speech with autoregressive predictive coding,” in ICASSP. [230] X. Song, G. Wang, Y. Huang, Z. Wu, D. Su, and H. Meng, “Speech-xlnet: Unsupervised acoustic model pretraining for self-attention networks,” in INTERSPEECH. [231] Y. Chung, Y. Wang, W. Hsu, Y. Zhang, and R. J. Skerry-Ryan, “Semi-supervised training for improv- ing data efficiency in end-to-end speech synthesis,” in ICASSP, 2019. [232] P. Denisov and N. T. Vu, “Pretrained semantic speech embeddings for end-to-end spoken language understanding via cross-modal teacher-student learning,” in Interspeech, 2020. [233] Y.-A. Chung, C. Zhu, and M. Zeng, “SPLAT: Speech-language joint pre-training for spoken language understanding,” in ACL, 2021. [234] M. Zeng, X. Tan, R. Wang, Z. Ju, T. Qin, and T.-Y. Liu, “Musicbert: Symbolic music understanding with large-scale pre-training,” arXiv preprint arXiv:2106.05630, 2021. 82 [235] Y.-S. Huang and Y.-H. Yang, “Pop music transformer: Beat-based modeling and generation of ex- pressive pop piano compositions,” in Proceedings of the 28th ACM International Conference on Mul- timedia, pp. 1180–1188, 2020. [236] P. Verma and J. Berger, “Audio transformers: Transformer architectures for large scale audio under- standing. adieu convolutions,” arXiv preprint arXiv:2105.00335, 2021. [237] B. Fernando, H. Bilen, E. Gavves, and S. Gould, “Self-supervised video representation learning with odd-one-out networks,” in CVPR. [238] I. Misra, C. L. Zitnick, and M. Hebert, “Shuffle and learn: unsupervised learning using temporal order verification,” in ECCV, 2016. [239] D. Kim, D. Cho, and I. S. Kweon, “Self-supervised video representation learning with space-time cubic puzzles,” in AAAI. [240] L. Tao, X. Wang, and T. Yamasaki, “Self-supervised video representation learning using inter-intra contrastive framework,” in ACM Multimedia. [241] G. Lorre, J. Rabarisoa, A. Orcesi, S. Ainouz, and S. Canu, “Temporal contrastive pretraining for video action recognition,” in WACV. [242] T. Yao, Y. Zhang, Z. Qiu, Y. Pan, and T. Mei, “Seco: Exploring sequence supervision for unsupervised representation learning,” arXiv, 2020. [243] L. H. Li, M. Yatskar, D. Yin, C. Hsieh, and K. Chang, “Visualbert: A simple and performant baseline for vision and language,” CoRR, 2019. [244] G. Li, N. Duan, Y. Fang, M. Gong, and D. Jiang, “Unicoder-vl: A universal encoder for vision and language by cross-modal pre-training,” in AAAI. [245] W. Su, X. Zhu, Y. Cao, B. Li, L. Lu, F. Wei, and J. Dai, “VL-BERT: pre-training of generic visual- linguistic representations,” in ICLR, 2020. [246] J. Lu, D. Batra, D. Parikh, and S. Lee, “Vilbert: Pretraining task-agnostic visiolinguistic representa- tions for vision-and-language tasks,” in NeurIPS. [247] A. Ramesh, P. Dhariwal, A. Nichol, C. Chu, and M. Chen, “Hierarchical text-conditional image generation with clip latents,” arXiv preprint arXiv:2204.06125, 2022. [248] A. Radford, J. W. Kim, C. Hallacy, A. Ramesh, G. Goh, S. Agarwal, G. Sastry, A. Askell, P. Mishkin, J. Clark, et al., “Learning transferable visual models from natural language supervision,” in Interna- tional Conference on Machine Learning, pp. 8748–8763, PMLR, 2021. [249] A. Nichol, P. Dhariwal, A. Ramesh, P. Shyam, P. Mishkin, B. McGrew, I. Sutskever, and M. Chen, “Glide: Towards photorealistic image generation and editing with text-guided diffusion models,” arXiv preprint arXiv:2112.10741, 2021. [250] N. Sayed, B. Brattoli, and B. Ommer, “Cross and learn: Cross-modal self-supervision,” in GCPR, 2018. [251] Z. Ren and Y. J. Lee, “Cross-domain self-supervised multi-task feature learning using synthetic im- agery,” in CVPR. 83 [252] Y. Tian, D. Krishnan, and P. Isola, “Contrastive multiview coding,” in ECCV. [253] A. Zlotchevski, D. Drain, A. Svyatkovskiy, C. B. Clement, N. Sundaresan, and M. Tufano, “Ex- ploring and evaluating personalized models for code generation,” in Proceedings of the 30th ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering, pp. 1500–1508, 2022. [254] S. Thakur, B. Ahmad, Z. Fan, H. Pearce, B. Tan, R. Karri, B. Dolan-Gavitt, and S. Garg, “Benchmarking large language models for automated verilog rtl code generation,” arXiv preprint arXiv:2212.11140, 2022. [255] E. Nijkamp, B. Pang, H. Hayashi, L. Tu, H. Wang, Y. Zhou, S. Savarese, and C. Xiong, “Code- gen: An open large language model for code with multi-turn program synthesis,” arXiv preprint arXiv:2203.13474, 2022. [256] G. Poesia, O. Polozov, V. Le, A. Tiwari, G. Soares, C. Meek, and S. Gulwani, “Synchromesh: Reliable code generation from pre-trained language models,” arXiv preprint arXiv:2201.11227, 2022. [257] Y.-C. Chen, L. Li, L. Yu, A. El Kholy, F. Ahmed, Z. Gan, Y. Cheng, and J. Liu, “Uniter: Univer- sal image-text representation learning,” in European conference on computer vision, pp. 104–120, Springer, 2020. [258] X. Zhu, J. Zhu, H. Li, X. Wu, H. Li, X. Wang, and J. Dai, “Uni-perceiver: Pre-training unified architecture for generic perception for zero-shot and few-shot tasks,” in Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, pp. 16804–16815, 2022. [259] S. Reed, K. Zolna, E. Parisotto, S. G. Colmenarejo, A. Novikov, G. Barth-Maron, M. Gimenez, Y. Sulsky, J. Kay, J. T. Springenberg, et al., “A generalist agent,” arXiv preprint arXiv:2205.06175, 2022. [260] W. Li, C. Gao, G. Niu, X. Xiao, H. Liu, J. Liu, H. Wu, and H. Wang, “Unimo: Towards unified-modal understanding and generation via cross-modal contrastive learning,” arXiv preprint arXiv:2012.15409, 2020. [261] V. Sanh, L. Debut, J. Chaumond, and T. Wolf, “Distilbert, a distilled version of BERT: smaller, faster, cheaper and lighter,” CoRR, 2019. [262] D. Jin, Z. Jin, J. T. Zhou, and P. Szolovits, “Is bert really robust? a strong baseline for natural language attack on text classification and entailment,” in AAAI. [263] D. Jin, Z. Jin, J. T. Zhou, and P. Szolovits, “Is BERT really robust? A strong baseline for natural language attack on text classification and entailment,” in AAAI. [264] Y. Zang, F. Qi, C. Yang, Z. Liu, M. Zhang, Q. Liu, and M. Sun, “Word-level textual adversarial attacking as combinatorial optimization,” in ACL. [265] E. Wallace, S. Feng, N. Kandpal, M. Gardner, and S. Singh, “Universal adversarial triggers for at- tacking and analyzing NLP,” in EMNLP-IJCNLP. [266] K. Kurita, P. Michel, and G. Neubig, “Weight poisoning attacks on pretrained models,” in ACL. [267] R. Schuster, T. Schuster, Y. Meri, and V. Shmatikov, “Humpty dumpty: Controlling word meanings via corpus poisoning,” in IEEE Symposium on Security and Privacy, 2020. 84 [268] R. Bao, J. Wang, and H. Zhao, “Defending pre-trained language models from adversarial word sub- stitution without performance sacrifice,” in ACL/IJCNLP. [269] Z. Zhang, Y. Li, J. Wang, B. Liu, D. Li, Y. Guo, X. Chen, and Y. Liu, “Remos: reducing defect inheritance in transfer learning via relevant model slicing,” in Proceedings of the 44th International Conference on Software Engineering, pp. 1856–1868, 2022. [270] N. Carlini, F. Tramer, E. Wallace, M. Jagielski, A. Herbert-Voss, K. Lee, A. Roberts, T. B. Brown, D. Song, U. Erlingsson, et al., “Extracting training data from large language models.,” in USENIX Security Symposium, vol. 6, 2021. [271] G. Wang, L. Zhang, Z. Yang, and X.-Y. Li, “Socialite: Social activity mining and friend auto- labeling,” in 2018 IEEE 37th International Performance Computing and Communications Conference (IPCCC), pp. 1–8, IEEE, 2018. [272] F. Han, L. Zhang, X. You, G. Wang, and X.-Y. Li, “Shad: Privacy-friendly shared activity detection and data sharing,” in 2019 IEEE 16th International Conference on Mobile Ad Hoc and Sensor Systems (MASS), pp. 109–117, IEEE, 2019. [273] T. Chen, X. Zhai, M. Ritter, M. Lucic, and N. Houlsby, “Self-supervised gans via auxiliary rotation loss,” in CVPR, 2019. [274] S. Abnar, M. Dehghani, B. Neyshabur, and H. Sedghi, “Exploring the limits of large scale pre- training,” arXiv, 2021. [275] M. E. Peters, M. Neumann, M. Iyyer, M. Gardner, C. Clark, K. Lee, and L. Zettlemoyer, “Deep contextualized word representations,” in NAACL-HLT, 2018. [276] T. Mikolov, I. Sutskever, K. Chen, G. S. Corrado, and J. Dean, “Distributed representations of words and phrases and their compositionality,” in NIPS. [277] R. Collobert, J. Weston, L. Bottou, M. Karlen, K. Kavukcuoglu, and P. P. Kuksa, “Natural language processing (almost) from scratch,” J. Mach. Learn. Res., 2011. [278] A. Neelakantan, J. Shankar, A. Passos, and A. McCallum, “Efficient non-parametric estimation of multiple embeddings per word in vector space,” in EMNLP. [279] P. Zhou, Z. Qi, S. Zheng, J. Xu, H. Bao, and B. Xu, “Text classification improved by integrating bidirectional LSTM with two-dimensional max pooling,” in COLING. [280] D. U. Hui, X. U. Xueke, W. U. Dayong, Y. Liu, Y. U. Zhihua, and X. Cheng, “A sentiment clas- sification method based on sentiment-specific word embedding,” Journal of Chinese Information Processing, 2017. [281] Y. Liu, C. Ma, and Y. Zhang, “Hierarchical machine translation model based on deep recursive neural network,” Chin. J. Comput, 2017. [282] X. Liang, F. Ren, Y. Liu, L. Pan, Y. Hou, Y. Zhang, and L. I. Yan, “N-reader: Machine reading comprehension model based on double layers of self-attention,” Journal of Chinese Information Pro- cessing, 2018. [283] Z. Zhichang, Z. Zhenwen, and Z. Zhiman, “User intent classification based on indrnn-attention,” Journal of Computer Research and Development, 2019. 85 [284] J. Deng, W. Dong, R. Socher, L.-J. Li, K. Li, and L. Fei-Fei, “Imagenet: A large-scale hierarchical image database,” in 2009 IEEE conference on computer vision and pattern recognition, 2009. [285] A. Krizhevsky, I. Sutskever, and G. E. Hinton, “Imagenet classification with deep convolutional neural networks,” Advances in neural information processing systems, 2012. [286] M. Lin, Q. Chen, and S. Yan, “Network in network,” arXiv, 2013. [287] K. Simonyan and A. Zisserman, “Very deep convolutional networks for large-scale image recogni- tion,” arXiv, 2014. [288] C. Szegedy, W. Liu, Y. Jia, P. Sermanet, S. Reed, D. Anguelov, D. Erhan, V. Vanhoucke, and A. Ra- binovich, “Going deeper with convolutions,” in CVPR. [289] K. He, X. Zhang, S. Ren, and J. Sun, “Deep residual learning for image recognition,” in CVPR. [290] G. Huang, Z. Liu, L. Van Der Maaten, and K. Q. Weinberger, “Densely connected convolutional networks,” in CVPR. [291] R. Girshick, J. Donahue, T. Darrell, and J. Malik, “Rich feature hierarchies for accurate object detec- tion and semantic segmentation,” in CVPR. [292] R. Girshick, “Fast r-cnn,” in ICCV. [293] S. Ren, K. He, R. Girshick, and J. Sun, “Faster r-cnn: Towards real-time object detection with region proposal networks,” arXiv, 2015. [294] K. He, G. Gkioxari, P. Dollár, and R. Girshick, “Mask r-cnn,” in ICCV. [295] J. Long, E. Shelhamer, and T. Darrell, “Fully convolutional networks for semantic segmentation,” in CVPR. [296] W. Liu, D. Anguelov, D. Erhan, C. Szegedy, S. Reed, C.-Y. Fu, and A. C. Berg, “Ssd: Single shot multibox detector,” in European conference on computer vision, 2016. [297] J. Redmon, S. Divvala, R. Girshick, and A. Farhadi, “You only look once: Unified, real-time object detection,” in CVPR. [298] J. Redmon and A. Farhadi, “Yolo9000: better, faster, stronger,” in CVPR. [299] J. Redmon and A. Farhadi, “Yolov3: An incremental improvement,” arXiv, 2018. [300] A. Bochkovskiy, C.-Y. Wang, and H.-Y. M. Liao, “Yolov4: Optimal speed and accuracy of object detection,” arXiv, 2020. [301] Q. Chen, Y. Wang, T. Yang, X. Zhang, J. Cheng, and J. Sun, “You only look one-level feature,” arXiv, 2021. [302] V. Badrinarayanan, A. Kendall, and R. Cipolla, “Segnet: A deep convolutional encoder-decoder ar- chitecture for image segmentation,” IEEE transactions on pattern analysis and machine intelligence, 2017. [303] H. Zhao, J. Shi, X. Qi, X. Wang, and J. Jia, “Pyramid scene parsing network,” in CVPR, 2017. 86 [304] L.-C. Chen, G. Papandreou, I. Kokkinos, K. Murphy, and A. L. Yuille, “Semantic image segmentation with deep convolutional nets and fully connected crfs,” arXiv, 2014. [305] L.-C. Chen, G. Papandreou, I. Kokkinos, K. Murphy, and A. L. Yuille, “Deeplab: Semantic im- age segmentation with deep convolutional nets, atrous convolution, and fully connected crfs,” IEEE transactions on pattern analysis and machine intelligence, 2017. [306] L.-C. Chen, G. Papandreou, F. Schroff, and H. Adam, “Rethinking atrous convolution for semantic image segmentation,” arXiv, 2017. [307] L.-C. Chen, Y. Zhu, G. Papandreou, F. Schroff, and H. Adam, “Encoder-decoder with atrous separable convolution for semantic image segmentation,” in ECCV. [308] G. Lin, A. Milan, C. Shen, and I. Reid, “Refinenet: Multi-path refinement networks for high- resolution semantic segmentation,” in CVPR. [309] M. Everingham, S. A. Eslami, L. Van Gool, C. K. Williams, J. Winn, and A. Zisserman, “The pascal visual object classes challenge: A retrospective,” International journal of computer vision, 2015. [310] M. Everingham, L. Van Gool, C. K. Williams, J. Winn, and A. Zisserman, “The pascal visual object classes (voc) challenge,” International journal of computer vision, 2010. [311] T.-Y. Lin, M. Maire, S. Belongie, J. Hays, P. Perona, D. Ramanan, P. Dollár, and C. L. Zitnick, “Microsoft coco: Common objects in context,” in European conference on computer vision, 2014. [312] D. E. Rumelhart, G. E. Hinton, and R. J. Williams, “Learning representations by back-propagating errors,” nature, 1986. [313] M. I. Jordan, “Serial order: A parallel distributed processing approach,” in Advances in psychology, 1997. [314] J. L. Elman, “Finding structure in time,” Cognitive science, 1990. [315] S. Hochreiter and J. Schmidhuber, “Long short-term memory,” Neural Computation, 1997. [316] A. Graves, M. Liwicki, S. Fernández, R. Bertolami, H. Bunke, and J. Schmidhuber, “A novel con- nectionist system for unconstrained handwriting recognition,” IEEE transactions on pattern analysis and machine intelligence, 2008. [317] O. Vinyals, A. Toshev, S. Bengio, and D. Erhan, “Show and tell: A neural image caption generator,” in CVPR. [318] I. Sutskever, O. Vinyals, and Q. V. Le, “Sequence to sequence learning with neural networks,” arXiv, 2014. [319] A. Graves, “Generating sequences with recurrent neural networks,” arXiv, 2013. [320] M. Sundermeyer, R. Schlüter, and H. Ney, “Lstm neural networks for language modeling,” in INTER- SPEECH, 2012. [321] I. J. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, and Y. Bengio, “Generative adversarial networks,” arXiv, 2014. [322] P. Isola, J.-Y. Zhu, T. Zhou, and A. A. Efros, “Image-to-image translation with conditional adversarial networks,” in CVPR, 2017. 87 [323] C. Li and M. Wand, “Precomputed real-time texture synthesis with markovian generative adversarial networks,” in European conference on computer vision, 2016. [324] J.-Y. Zhu, T. Park, P. Isola, and A. A. Efros, “Unpaired image-to-image translation using cycle- consistent adversarial networks,” in ICCV. [325] T. Karras, S. Laine, and T. Aila, “A style-based generator architecture for generative adversarial networks,” in CVPR, 2019. [326] A. Van Oord, N. Kalchbrenner, and K. Kavukcuoglu, “Pixel recurrent neural networks,” in Interna- tional Conference on Machine Learning, 2016. [327] T. Kim, M. Cha, H. Kim, J. K. Lee, and J. Kim, “Learning to discover cross-domain relations with generative adversarial networks,” in International Conference on Machine Learning, 2017. [328] E. Denton, S. Chintala, A. Szlam, and R. Fergus, “Deep generative image models using a laplacian pyramid of adversarial networks,” arXiv, 2015. [329] X. Huang, Y. Li, O. Poursaeed, J. Hopcroft, and S. Belongie, “Stacked generative adversarial net- works,” in CVPR. [330] J. Hu, L. Shen, and G. Sun, “Squeeze-and-excitation networks,” in CVPR. [331] S. Woo, J. Park, J.-Y. Lee, and I. S. Kweon, “Cbam: Convolutional block attention module,” in ECCV. [332] Y. Cao, J. Xu, S. Lin, F. Wei, and H. Hu, “Gcnet: Non-local networks meet squeeze-excitation networks and beyond,” in ICCV Workshops. [333] Z. Huang, X. Wang, L. Huang, C. Huang, Y. Wei, and W. Liu, “Ccnet: Criss-cross attention for semantic segmentation,” in ICCV. [334] H. Zhang, I. Goodfellow, D. Metaxas, and A. Odena, “Self-attention generative adversarial networks,” in International conference on machine learning, 2019. [335] H. Touvron, M. Cord, M. Douze, F. Massa, A. Sablayrolles, and H. Jégou, “Training data-efficient image transformers & distillation through attention,” arXiv, 2020. [336] N. Carion, F. Massa, G. Synnaeve, N. Usunier, A. Kirillov, and S. Zagoruyko, “End-to-end object detection with transformers,” in European Conference on Computer Vision, 2020. [337] B. Graham, A. El-Nouby, H. Touvron, P. Stock, A. Joulin, H. Jégou, and M. Douze, “Levit: a vision transformer in convnet’s clothing for faster inference,” arXiv, 2021. [338] D. Zhou, B. Kang, X. Jin, L. Yang, X. Lian, Z. Jiang, Q. Hou, and J. Feng, “Deepvit: Towards deeper vision transformer,” arXiv, 2021. [339] W. Wang, E. Xie, X. Li, D.-P. Fan, K. Song, D. Liang, T. Lu, P. Luo, and L. Shao, “Pyramid vision transformer: A versatile backbone for dense prediction without convolutions,” arXiv, 2021. [340] T. Guan, J. Wang, S. Lan, R. Chandra, Z. Wu, L. Davis, and D. Manocha, “M3detr: Multi- representation, multi-scale, mutual-relation 3d object detection with transformers,” arXiv, 2021. [341] J. M. J. Valanarasu, P. Oza, I. Hacihaliloglu, and V. M. Patel, “Medical transformer: Gated axial- attention for medical image segmentation,” arXiv, 2021. 88 [342] R. C. T. Lee, Y. H. Chin, and S. C. Chang, “Application of principal component analysis to multikey searching,” IEEE Trans. Software Eng., no. 3, pp. 185–193, 1976. [343] J. Ye, R. Janardan, and Q. Li, “Two-dimensional linear discriminant analysis,” in Advances in Neural Information Processing Systems 17 [Neural Information Processing Systems, NIPS 2004, December 13-18, 2004, Vancouver, British Columbia, Canada], pp. 1569–1576, 2004. [344] S. Robinson and R. Bennett, “A typology of deviant workplace behaviors: A multidimensional scaling study,” Academy of Management Journal, vol. 38, pp. 555–572, 1995. [345] O. Samko, A. D. Marshall, and P. L. Rosin, “Selection of the optimal parameter value for the isomap algorithm,” Pattern Recognit. Lett., no. 9, pp. 968–979, 2006. [346] S. T. Roweis and L. K. Saul, “Nonlinear dimensionality reduction by locally linear embedding,” Science, vol. 290, no. 5500, pp. 2323–2326, 2000. [347] M. Belkin and P. Niyogi, “Laplacian eigenmaps for dimensionality reduction and data representation,” Neural Comput., no. 6, pp. 1373–1396, 2003. [348] A. P. Singh and G. J. Gordon, “Relational learning via collective matrix factorization,” in ACM SIGKDD. [349] S. Cao, W. Lu, and Q. Xu, “Grarep: Learning graph representations with global structural informa- tion,” in CIKM. [350] M. Ou, P. Cui, J. Pei, Z. Zhang, and W. Zhu, “Asymmetric transitivity preserving graph embedding,” in ACM SIGKDD. [351] M. Sugiyama and K. M. Borgwardt, “Halting in random walk kernels,” in NIPS, 2015. [352] U. Kang, H. Tong, and J. Sun, “Fast random walk graph kernel,” in SIAM. [353] N. Shervashidze, P. Schweitzer, E. J. van Leeuwen, K. Mehlhorn, and K. M. Borgwardt, “Weisfeiler- lehman graph kernels,” J. Mach. Learn. Res., pp. 2539–2561, 2011. [354] D. Erhan, P.-A. Manzagol, Y. Bengio, S. Bengio, and P. Vincent, “The difficulty of training deep architectures and the effect of unsupervised pre-training,” in Artificial Intelligence and Statistics, 2009. [355] D. Erhan, A. Courville, Y. Bengio, and P. Vincent, “Why does unsupervised pre-training help deep learning?,” in AISTATS. [356] J. D. Lee, Q. Lei, N. Saunshi, and J. Zhuo, “Predicting what you already know helps: Provable self-supervised learning,” arXiv, 2020. [357] C. Tosh, A. Krishnamurthy, and D. Hsu, “Contrastive learning, multi-view redundancy, and linear models,” in Algorithmic Learning Theory, 2021. [358] S. Arora, H. Khandeparkar, M. Khodak, O. Plevrakis, and N. Saunshi, “A theoretical analysis of contrastive unsupervised representation learning,” arXiv, 2019. [359] S. Anwar, M. Tahir, C. Li, A. Mian, F. S. Khan, and A. W. Muzaffar, “Image colorization: A survey and dataset,” arXiv, 2020. 89 [360] C. Ledig, L. Theis, F. Huszár, J. Caballero, A. Cunningham, A. Acosta, A. Aitken, A. Tejani, J. Totz, Z. Wang, et al., “Photo-realistic single image super-resolution using a generative adversarial net- work,” in CVPR. [361] G. Perarnau, J. Van De Weijer, B. Raducanu, and J. M. Álvarez, “Invertible conditional gans for image editing,” arXiv, 2016. [362] C. Vondrick, H. Pirsiavash, and A. Torralba, “Generating videos with scene dynamics,” arXiv, 2016. [363] S. Tulyakov, M.-Y. Liu, X. Yang, and J. Kautz, “Mocogan: Decomposing motion and content for video generation,” in CVPR. [364] X. Wang and A. Gupta, “Unsupervised learning of visual representations using videos,” in ICCV. [365] C. Wei, L. Xie, X. Ren, Y. Xia, C. Su, J. Liu, Q. Tian, and A. L. Yuille, “Iterative reorganization with weak spatial constraints: Solving arbitrary jigsaw puzzles for unsupervised representation learning,” in CVPR. [366] U. Ahsan, R. Madhok, and I. Essa, “Video jigsaw: Unsupervised learning of spatiotemporal context for video action recognition,” in WACV. [367] D. Pathak, R. Girshick, P. Dollár, T. Darrell, and B. Hariharan, “Learning features by watching objects move,” in CVPR. [368] I. Croitoru, S.-V. Bogolin, and M. Leordeanu, “Unsupervised learning from video to detect fore- ground objects in single images,” in ICCV. [369] P. Sermanet, C. Lynch, Y. Chebotar, J. Hsu, E. Jang, S. Schaal, S. Levine, and G. Brain, “Time- contrastive networks: Self-supervised learning from video,” in ICRA. [370] B. Korbar, D. Tran, and L. Torresani, “Cooperative learning of audio and video models from self- supervised synchronization,” arXiv, 2018. [371] B. C. Stadie, S. Levine, and P. Abbeel, “Incentivizing exploration in reinforcement learning with deep predictive models,” arXiv preprint arXiv:1507.00814, 2015. [372] J. Achiam and S. Sastry, “Surprise-based intrinsic motivation for deep reinforcement learning,” arXiv preprint arXiv:1703.01732, 2017. [373] D. Pathak, P. Agrawal, A. A. Efros, and T. Darrell, “Curiosity-driven exploration by self-supervised prediction,” in International conference on machine learning, pp. 2778–2787, PMLR, 2017. [374] H. Tang, R. Houthooft, D. Foote, A. Stooke, O. Xi Chen, Y. Duan, J. Schulman, F. DeTurck, and P. Abbeel, “# exploration: A study of count-based exploration for deep reinforcement learning,” Advances in neural information processing systems, vol. 30, 2017. [375] P. Dey and S. Medya, “Manipulating node similarity measures in network,” arXiv, 2019. [376] B. Han, C. Zheng, H. Chan, K. Paster, M. Zhang, and J. Ba, “Learning domain invariant representa- tions in goal-conditioned block mdps,” Advances in Neural Information Processing Systems, vol. 34, pp. 764–776, 2021. [377] Y. Ding, C. Florensa, P. Abbeel, and M. Phielipp, “Goal-conditioned imitation learning,” Advances in neural information processing systems, vol. 32, 2019. 90 [378] R. Shah and V. Kumar, “Rrl: Resnet as representation for reinforcement learning,” arXiv preprint arXiv:2107.03380, 2021. [379] T. Xiao, I. Radosavovic, T. Darrell, and J. Malik, “Masked visual pre-training for motor control,” arXiv preprint arXiv:2203.06173, 2022. [380] M. Schwarzer, N. Rajkumar, M. Noukhovitch, A. Anand, L. Charlin, R. D. Hjelm, P. Bachman, and A. C. Courville, “Pretraining representations for data-efficient reinforcement learning,” Advances in Neural Information Processing Systems, vol. 34, pp. 12686–12699, 2021. [381] M. Schwarzer, A. Anand, R. Goel, R. D. Hjelm, A. Courville, and P. Bachman, “Data-efficient rein- forcement learning with self-predictive representations,” arXiv preprint arXiv:2007.05929, 2020. [382] D. Ha and J. Schmidhuber, “World Models,” Mar. 2018. [383] M. Jaderberg, V. Mnih, W. M. Czarnecki, T. Schaul, J. Z. Leibo, D. Silver, and K. Kavukcuoglu, “Reinforcement Learning with Unsupervised Auxiliary Tasks,” Nov. 2016. [384] I. Higgins, A. Pal, A. A. Rusu, L. Matthey, C. P. Burgess, A. Pritzel, M. Botvinick, C. Blundell, and A. Lerchner, “DARLA: Improving Zero-Shot Transfer in Reinforcement Learning,” June 2018. [385] C. Finn, T. Yu, J. Fu, P. Abbeel, and S. Levine, “Generalizing skills with semi-supervised reinforce- ment learning,” arXiv preprint arXiv:1612.00429, 2016. [386] R. Shah and V. Kumar, “RRL: Resnet as representation for Reinforcement Learning,” Nov. 2021. [387] M. Schwarzer, A. Anand, R. Goel, R. D. Hjelm, A. Courville, and P. Bachman, “Data-Efficient Reinforcement Learning with Self-Predictive Representations,” May 2021. [388] D. Hafner, T. Lillicrap, J. Ba, and M. Norouzi, “Dream to control: Learning behaviors by latent imagination,” arXiv preprint arXiv:1912.01603, 2019. [389] D. Hafner, T. Lillicrap, M. Norouzi, and J. Ba, “Mastering atari with discrete world models,” arXiv preprint arXiv:2010.02193, 2020. [390] F. Deng, I. Jang, and S. Ahn, “Dreamerpro: Reconstruction-free model-based reinforcement learn- ing with prototypical representations,” in International Conference on Machine Learning, pp. 4956– 4975, PMLR, 2022. [391] P. Wu, A. Escontrela, D. Hafner, K. Goldberg, and P. Abbeel, “Daydreamer: World models for phys- ical robot learning,” arXiv preprint arXiv:2206.14176, 2022. [392] M. Laskin, A. Srinivas, and P. Abbeel, “Curl: Contrastive unsupervised representations for reinforce- ment learning,” in International Conference on Machine Learning, pp. 5639–5650, PMLR, 2020. [393] M. Laskin, K. Lee, A. Stooke, L. Pinto, P. Abbeel, and A. Srinivas, “Reinforcement learning with augmented data,” Advances in neural information processing systems, vol. 33, pp. 19884–19895, 2020. [394] I. Kostrikov, D. Yarats, and R. Fergus, “Image augmentation is all you need: Regularizing deep reinforcement learning from pixels,” arXiv preprint arXiv:2004.13649, 2020. [395] D. Yarats, R. Fergus, A. Lazaric, and L. Pinto, “Mastering visual continuous control: Improved data- augmented reinforcement learning,” arXiv preprint arXiv:2107.09645, 2021. 91 [396] S. Nair, A. Rajeswaran, V. Kumar, C. Finn, and A. Gupta, “R3m: A universal visual representation for robot manipulation,” arXiv preprint arXiv:2203.12601, 2022. [397] S. Parisi, A. Rajeswaran, S. Purushwalkam, and A. Gupta, “The unsurprising effectiveness of pre- trained vision models for control,” arXiv preprint arXiv:2203.03580, 2022. [398] C. D. Manning, P. Raghavan, and H. Schütze, Introduction to information retrieval. 2008. [399] R. E. Schapire and Y. Singer, “Improved boosting algorithms using confidence-rated predictions,” Mach. Learn., no. 3, 1999. [400] E. Reiter, “A structured review of the validity of bleu,” Computational Linguistics, 2018. [401] M. Denkowski and A. Lavie, “Meteor universal: Language specific translation evaluation for any target language,” in Proceedings of the ninth workshop on statistical machine translation. [402] C.-Y. Lin and E. Hovy, “Automatic evaluation of summaries using n-gram co-occurrence statistics,” in HLT-NAACL, 2003. [403] Y. Kim, “Convolutional neural networks for sentence classification,” in EMNLP. [404] N. Kalchbrenner, E. Grefenstette, and P. Blunsom, “A convolutional neural network for modelling sentences,” in ACL. [405] M. Yang, W. Zhao, J. Ye, Z. Lei, Z. Zhao, and S. Zhang, “Investigating capsule networks with dy- namic routing for text classification,” in EMNLP. [406] L. Yao, C. Mao, and Y. Luo, “Graph convolutional networks for text classification,” in AAAI. [407] Y. Wang, A. Sun, J. Han, Y. Liu, and X. Zhu, “Sentiment analysis by capsules,” in WWW. [408] R. Socher, A. Perelygin, J. Wu, J. Chuang, C. D. Manning, A. Y. Ng, and C. Potts, “Recursive deep models for semantic compositionality over a sentiment treebank,” in EMNLP. [409] K. S. Tai, R. Socher, and C. D. Manning, “Improved semantic representations from tree-structured long short-term memory networks,” in ACL. [410] X. Zhu, P. Sobhani, and H. Guo, “Long short-term memory over recursive structures,” in ICML. [411] J. Cheng, L. Dong, and M. Lapata, “Long short-term memory-networks for machine reading,” in EMNLP. [412] P. Liu, X. Qiu, X. Chen, S. Wu, and X. Huang, “Multi-timescale long short-term memory neural network for modelling sentences and documents,” in EMNLP. [413] P. Liu, X. Qiu, and X. Huang, “Recurrent neural network for text classification with multi-task learn- ing,” in IJCAI. [414] R. Socher, J. Pennington, E. H. Huang, A. Y. Ng, and C. D. Manning, “Semi-supervised recursive autoencoders for predicting sentiment distributions,” in EMNLP. [415] T. Shen, T. Zhou, G. Long, J. Jiang, and C. Zhang, “Bi-directional block self-attention for fast and memory-efficient sequence modeling,” in ICLR, 2018. [416] Q. V. Le and T. Mikolov, “Distributed representations of sentences and documents,” in ICML. 92 [417] M. Iyyer, V. Manjunatha, J. L. Boyd-Graber, and H. D. III, “Deep unordered composition rivals syntactic methods for text classification,” in ACL. [418] T. Miyato, A. M. Dai, and I. J. Goodfellow, “Adversarial training methods for semi-supervised text classification,” in ICLR, 2017. [419] S. Lai, L. Xu, K. Liu, and J. Zhao, “Recurrent convolutional neural networks for text classification,” in AAAI. [420] R. Johnson and T. Zhang, “Supervised and semi-supervised text categorization using LSTM for region embeddings,” in ICML. [421] Y. Bao, M. Wu, S. Chang, and R. Barzilay, “Few-shot text classification with distributional signa- tures,” in ICLR, 2020. [422] F. Wu, A. H. S. Jr., T. Zhang, C. Fifty, T. Yu, and K. Q. Weinberger, “Simplifying graph convolutional networks,” in ICML. [423] X. Zhang, J. J. Zhao, and Y. LeCun, “Character-level convolutional networks for text classification,” in NIPS, 2015. [424] R. Johnson and T. Zhang, “Deep pyramid convolutional neural networks for text categorization,” in ACL. [425] J. Wang, Z. Wang, D. Zhang, and J. Yan, “Combining knowledge with deep convolutional neural networks for short text classification,” in IJCAI. [426] L. Huang, D. Ma, S. Li, X. Zhang, and H. Wang, “Text level graph neural network for text classifica- tion,” in EMNLP-IJCNLP. [427] C. Sun, X. Qiu, Y. Xu, and X. Huang, “How to fine-tune BERT for text classification?,” in CCL. [428] Z. Yang, D. Yang, C. Dyer, X. He, A. J. Smola, and E. H. Hovy, “Hierarchical attention networks for document classification,” in NAACL-HLT, 2016. [429] S. R. Bowman, G. Angeli, C. Potts, and C. D. Manning, “A large annotated corpus for learning natural language inference,” in EMNLP. [430] Z. Wang, W. Hamza, and R. Florian, “Bilateral multi-perspective matching for natural language sen- tences,” in IJCAI. [431] X. Liu, P. He, W. Chen, and J. Gao, “Multi-task deep neural networks for natural language under- standing,” in ACL. [432] A. Williams, N. Nangia, and S. R. Bowman, “A broad-coverage challenge corpus for sentence under- standing through inference,” in NAACL-HLT, 2018. [433] M. Marelli, L. Bentivogli, M. Baroni, R. Bernardi, S. Menini, and R. Zamparelli, “Semeval-2014 task 1: Evaluation of compositional distributional semantic models on full sentences through semantic relatedness and textual entailment,” in SemEval@COLING. [434] B. Dolan, C. Quirk, and C. Brockett, “Unsupervised construction of large paraphrase corpora: Ex- ploiting massively parallel news sources,” in COLING, 2004. 93 [435] J. Fu, P. Liu, and G. Neubig, “Interpretable multi-dataset evaluation for named entity recognition,” in EMNLP. [436] B. Lester, D. Pressel, A. Hemmeter, S. R. Choudhury, and S. Bangalore, “Constrained decoding for computationally efficient named entity recognition taggers,” in EMNLP. [437] Y. Luo, H. Zhao, and J. Zhan, “Named entity recognition only from word embeddings,” in EMNLP. [438] X. Li, J. Feng, Y. Meng, Q. Han, F. Wu, and J. Li, “A unified MRC framework for named entity recognition,” in ACL. [439] Y. Zhang and J. Yang, “Chinese NER using lattice LSTM,” in ACL. [440] Y. Meng, W. Wu, F. Wang, X. Li, P. Nie, F. Yin, M. Li, Q. Han, X. Sun, and J. Li, “Glyce: Glyph- vectors for chinese character representations,” in NeurIPS. [441] A. Katiyar and C. Cardie, “Nested named entity recognition revisited,” in NAACL-HLT, 2018. [442] B. Wang and W. Lu, “Neural segmental hypergraphs for overlapping mention recognition,” in EMNLP. [443] Y. Luan, D. Wadden, L. He, A. Shah, M. Ostendorf, and H. Hajishirzi, “A general framework for information extraction using dynamic span graphs,” in NAACL-HLT, 2019. [444] T. Shibuya and E. H. Hovy, “Nested named entity recognition via second-best sequence learning and decoding,” Trans. Assoc. Comput. Linguistics, 2020. [445] H. Lin, Y. Lu, X. Han, and L. Sun, “Sequence-to-nuggets: Nested entity mention detection via anchor- region networks,” in ACL. [446] G. Lai, Q. Xie, H. Liu, Y. Yang, and E. H. Hovy, “RACE: large-scale reading comprehension dataset from examinations,” in EMNLP. [447] Y. Yang, W. Yih, and C. Meek, “Wikiqa: A challenge dataset for open-domain question answering,” in EMNLP. [448] C. N. dos Santos, M. Tan, B. Xiang, and B. Zhou, “Attentive pooling networks,” CoRR, 2016. [449] J. Y. Lee and F. Dernoncourt, “Sequential short-text classification with recurrent and convolutional neural networks,” in NAACL-HLT, 2016. [450] S. Kim, L. F. D’Haro, R. E. Banchs, J. D. Williams, and M. Henderson, “The fourth dialog state track- ing challenge,” in Dialogues with Social Robots - Enablements, Analyses, and Evaluation, Seventh International Workshop on Spoken Dialogue Systems, IWSDS 2016, Saariselkä, Finland, January 13-16, 2016, 2016. [451] J. Ang, Y. Liu, and E. Shriberg, “Automatic dialog act segmentation and classification in multiparty meetings,” in 2005 IEEE International Conference on Acoustics, Speech, and Signal Processing, ICASSP ’05, Philadelphia, Pennsylvania, USA, March 18-23, 2005, 2005. [452] Y. Wan, W. Yan, J. Gao, Z. Zhao, J. Wu, and P. S. Yu, “Improved dynamic memory network for dialogue act classification with adversarial training,” in IEEE International Conference on Big Data, Big Data 2018, Seattle, WA, USA, December 10-13, 2018, 2018. 94 [453] V. Raheja and J. R. Tetreault, “Dialogue act classification with context-aware self-attention,” in Proc. NAACL, 2019, 2019. [454] J. Xu, Z. Gan, Y. Cheng, and J. Liu, “Discourse-aware neural extractive text summarization,” in ACL. [455] Y. Zou, X. Zhang, W. Lu, F. Wei, and M. Zhou, “Pre-training for abstractive document summarization by reinstating source text,” in EMNLP. [456] L. Liu, Y. Lu, M. Yang, Q. Qu, J. Zhu, and H. Li, “Generative adversarial network for abstractive text summarization,” in AAAI. [457] M. Yang, Q. Qu, W. Tu, Y. Shen, Z. Zhao, and X. Chen, “Exploring human-like reading strategy for abstractive text summarization,” in AAAI. [458] M. Bhandari, P. N. Gour, A. Ashfaq, P. Liu, and G. Neubig, “Re-evaluating evaluation in text sum- marization,” in EMNLP. [459] Y. Dong, S. Wang, Z. Gan, Y. Cheng, J. C. K. Cheung, and J. Liu, “Multi-fact correction in abstractive text summarization,” in EMNLP. [460] D. Huang, L. Cui, S. Yang, G. Bao, K. Wang, J. Xie, and Y. Zhang, “What have we achieved on text summarization?,” in EMNLP. [461] W. Kryscinski, R. Paulus, C. Xiong, and R. Socher, “Improving abstraction in text summarization,” in EMNLP. [462] W. Kryscinski, B. McCann, C. Xiong, and R. Socher, “Evaluating the factual consistency of abstrac- tive text summarization,” in EMNLP. [463] P. Kouris, G. Alexandridis, and A. Stafylopatis, “Abstractive text summarization based on deep learn- ing and semantic content generalization,” in ACL. [464] K. Chen, R. Wang, M. Utiyama, and E. Sumita, “Content word aware neural machine translation,” in ACL, 2020. [465] Z. Lin, X. Pan, M. Wang, X. Qiu, J. Feng, H. Zhou, and L. Li, “Pre-training multilingual neural machine translation by leveraging alignment information,” in EMNLP. [466] E. Bugliarello and N. Okazaki, “Enhancing machine translation with dependency-aware self- attention,” in ACL, 2020. [467] A. F. Aji, N. Bogoychev, K. Heafield, and R. Sennrich, “In neural machine translation, what does transfer learning transfer?,” in ACL. [468] C. Baziotis, B. Haddow, and A. Birch, “Language model prior for low-resource neural machine trans- lation,” in EMNLP. [469] Q. Cui, S. Huang, J. Li, X. Geng, Z. Zheng, G. Huang, and J. Chen, “Directqe: Direct pretraining for machine translation quality estimation,” in AAAI. [470] C. Wu, S. C. H. Hoi, R. Socher, and C. Xiong, “TOD-BERT: pre-trained natural language under- standing for task-oriented dialogue,” in EMNLP. [471] G. Campagna, A. Foryciarz, M. Moradshahi, and M. S. Lam, “Zero-shot transfer learning with syn- thesized data for multi-domain dialogue state tracking,” in ACL, 2020. 95 [472] Q. Liu, L. Yu, L. Rimell, and P. Blunsom, “Pretraining the noisy channel model for task-oriented dialogue,” CoRR, 2021. [473] “SST Corpus.” http://nlp.stanford.edu/sentiment, 2013. [474] B. Pang and L. Lee, “Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales,” in ACL. [475] R. Socher, A. Perelygin, J. Wu, J. Chuang, C. D. Manning, A. Y. Ng, and C. Potts, “Recursive deep models for semantic compositionality over a sentiment treebank,” in EMNLP. [476] D. Cer, M. Diab, E. Agirre, I. Lopez-Gazpio, and L. Specia, “Semeval-2017 task 1: Semantic textual similarity-multilingual and cross-lingual focused evaluation,” arXiv, 2017. [477] I. Hendrickx, S. N. Kim, Z. Kozareva, P. Nakov, D. Ó. Séaghdha, S. Padó, M. Pennacchiotti, L. Ro- mano, and S. Szpakowicz, “Semeval-2010 task 8: Multi-way classification of semantic relations between pairs of nominals,” in Proc. NAACL, 2009, 2009. [478] J. Wiebe, T. Wilson, and C. Cardie, “Annotating expressions of opinions and emotions in language,” Language Resources and Evaluation, no. 2-3, 2005. [479] “MPQA Corpus.” http://www.cs.pitt.edu/mpqa/, 2005. [480] Q. Diao, M. Qiu, C. Wu, A. J. Smola, J. Jiang, and C. Wang, “Jointly modeling aspects, ratings and sentiments for movie recommendation (JMARS),” in ACM SIGKDD. [481] “20NG Corpus.” http://ana.cachopo.org/datasets-for-single-label-text-categorization, 2007. [482] “AG Corpus.” http://www.di.unipi.it/~gulli/AG_corpus_of_news_articles. html, 2004. [483] “Reuters Corpus.” https://www.cs.umb.edu/~smimarog/textmining/datasets/, 2007. [484] “Reuters Corpus.” https://martin-thoma.com/nlp-reuters, 2017. [485] J. Lehmann, R. Isele, M. Jakob, A. Jentzsch, D. Kontokostas, P. N. Mendes, S. Hellmann, M. Morsey, P. van Kleef, S. Auer, and C. Bizer, “Dbpedia - A large-scale, multilingual knowledge base extracted from wikipedia,” Semantic Web, no. 2, 2015. [486] “Ohsumed Corpus.” http://davis.wpi.edu/xmdv/datasets/ohsumed.html, 2015. [487] A. Williams, N. Nangia, and S. R. Bowman, “A broad-coverage challenge corpus for sentence under- standing through inference,” arXiv, 2017. [488] P. Rajpurkar, J. Zhang, K. Lopyrev, and P. Liang, “Squad: 100,000+ questions for machine compre- hension of text,” arXiv, 2016. [489] H. Levesque, E. Davis, and L. Morgenstern, “The winograd schema challenge,” in Thirteenth Inter- national Conference on the Principles of Knowledge Representation and Reasoning, 2012. [490] W. B. Dolan and C. Brockett, “Automatically constructing a corpus of sentential paraphrases,” in IWP, 2005. 96 [491] P. Rajpurkar, R. Jia, and P. Liang, “Know what you don’t know: Unanswerable questions for squad,” arXiv, 2018. [492] G. Lai, Q. Xie, H. Liu, Y. Yang, and E. Hovy, “Race: Large-scale reading comprehension dataset from examinations,” arXiv, 2017. [493] D. Jurafsky and E. Shriberg, “Switchboard swbd-damsl shallow-discourse-function annotation coders manual,” 1997. [494] J. Li, P. Zhou, C. Xiong, R. Socher, and S. C. Hoi, “Prototypical contrastive learning of unsupervised representations,” arXiv preprint arXiv:2005.04966, 2020. [495] J. Donahue and K. Simonyan, “Large scale adversarial representation learning,” Advances in Neural Information Processing Systems, vol. 32, 2019. [496] K. He, X. Chen, S. Xie, Y. Li, P. Dollár, and R. Girshick, “Masked autoencoders are scalable vision learners,” arXiv preprint arXiv:2111.06377, 2021. [497] http://yann.lecun.com/exdb/mnist/. [498] http://ufldl.stanford.edu/housenumbers/. [499] https://www.cs.toronto.edu/~kriz/index.html. [500] A. Coates, A. Ng, and H. Lee, “An analysis of single-layer networks in unsupervised feature learn- ing,” in Proceedings of the fourteenth international conference on artificial intelligence and statistics, 2011. [501] https://cs.stanford.edu/~acoates/stl10/. [502] http://www.vision.caltech.edu/Image_Datasets/Caltech101/. [503] G. A. Miller, WordNet: An electronic lexical database. 1998. [504] https://image-net.org/. [505] https://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/. [506] H. Kuehne, H. Jhuang, E. Garrote, T. Poggio, and T. Serre, “HMDB: a large video database for human motion recognition,” in ICCV, 2011. [507] https://www.crcv.ucf.edu/data/UCF101.php. [508] https://www.crcv.ucf.edu/data/UCF50.php. [509] L. Bossard, M. Guillaumin, and L. Van Gool, “Food-101–mining discriminative components with random forests,” in European conference on computer vision, 2014. [510] T. Berg, J. Liu, S. Woo Lee, M. L. Alexander, D. W. Jacobs, and P. N. Belhumeur, “Birdsnap: Large- scale fine-grained visual categorization of birds,” in CVPR, 2014. [511] J. Xiao, J. Hays, K. A. Ehinger, A. Oliva, and A. Torralba, “Sun database: Large-scale scene recogni- tion from abbey to zoo,” in 2010 IEEE computer society conference on computer vision and pattern recognition, 2010. 97 [512] J. Xiao, K. A. Ehinger, J. Hays, A. Torralba, and A. Oliva, “Sun database: Exploring a large collection of scene categories,” International Journal of Computer Vision, 2016. [513] http://places.csail.mit.edu/downloadData.html. [514] http://ai.stanford.edu/~jkrause/cars/car_dataset.html. [515] S. Maji, J. Kannala, E. Rahtu, M. Blaschko, and A. Vedaldi, “Fine-grained visual classification of aircraft,” tech. rep., 2013. [516] https://sites.google.com/site/fgcomp2013/. [517] https://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/. [518] https://www.robots.ox.ac.uk/~vgg/data/pets/. [519] https://www.robots.ox.ac.uk/~vgg/data/flowers/. [520] https://www.robots.ox.ac.uk/~vgg/data/dtd/. [521] https://sites.google.com/view/fgvc5/competitions/inaturalist. [522] https://www.inaturalist.org/. [523] C. Sun, A. Shrivastava, S. Singh, and A. Gupta, “Revisiting unreasonable effectiveness of data in deep learning era,” in Proceedings of the IEEE international conference on computer vision, pp. 843–852, 2017. [524] http://host.robots.ox.ac.uk/pascal/VOC/. [525] http://host.robots.ox.ac.uk/pascal/VOC/voc2007/index.html. [526] http://host.robots.ox.ac.uk/pascal/VOC/voc2011/index.html. [527] http://host.robots.ox.ac.uk/pascal/VOC/voc2012/index.html. [528] B. Zhou, H. Zhao, X. Puig, S. Fidler, A. Barriuso, and A. Torralba, “Scene parsing through ade20k dataset,” in CVPR. [529] B. Zhou, H. Zhao, X. Puig, T. Xiao, S. Fidler, A. Barriuso, and A. Torralba, “Semantic understanding of scenes through the ade20k dataset,” International Journal of Computer Vision, 2019. [530] https://cs.nyu.edu/~silberman/datasets/nyu_depth_v2.html. [531] M. Cordts, M. Omran, S. Ramos, T. Scharwächter, M. Enzweiler, R. Benenson, U. Franke, S. Roth, and B. Schiele, “The cityscapes dataset,” in CVPR Workshop on The Future of Datasets in Vision, 2015. [532] M. Cordts, M. Omran, S. Ramos, T. Rehfeld, M. Enzweiler, R. Benenson, U. Franke, S. Roth, and B. Schiele, “The cityscapes dataset for semantic urban scene understanding,” in Proc. of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016. [533] A. Gupta, P. Dollar, and R. Girshick, “LVIS: A dataset for large vocabulary instance segmentation,” in CVPR, 2019. [534] https://davischallenge.org/. 98 [535] https://davischallenge.org/davis2017/code.html. [536] C. Doersch, “Data analysis project: What makes paris look like paris?,” [537] http://www.cs.toronto.edu/~nitish/unsupervised_video/. [538] N. Srivastava, E. Mansimov, and R. Salakhudinov, “Unsupervised learning of video representations using lstms,” in International conference on machine learning, 2015. [539] B. Thomee, D. A. Shamma, G. Friedland, B. Elizalde, K. Ni, D. Poland, D. Borth, and L.-J. Li, “Yfcc100m: The new data in multimedia research,” Communications of the ACM, 2016. [540] http://projects.dfki.uni-kl.de/yfcc100m/. [541] W. Jin, X. Liu, X. Zhao, Y. Ma, N. Shah, and J. Tang, “Automated self-supervised learning for graphs,” CoRR, 2021. [542] Z. Peng, Y. Dong, M. Luo, X. Wu, and Q. Zheng, “Self-supervised graph representation learning via global context prediction,” CoRR, 2020. [543] Y. Zhu, Y. Xu, F. Yu, Q. Liu, S. Wu, and L. Wang, “Deep graph contrastive representation learning,” CoRR, 2020. [544] M. Jin, Y. Zheng, Y. Li, C. Gong, C. Zhou, and S. Pan, “Multi-scale contrastive siamese networks for self-supervised graph representation learning,” CoRR, 2021. [545] Z. Hu, C. Fan, T. Chen, K. Chang, and Y. Sun, “Pre-training graph neural networks for generic structural feature extraction,” CoRR, 2019. [546] Y. Zhu, Y. Xu, F. Yu, S. Wu, and L. Wang, “CAGNN: cluster-aware graph neural networks for unsu- pervised graph representation learning,” CoRR, 2020. [547] H. Zhang, S. Lin, W. Liu, P. Zhou, J. Tang, X. Liang, and E. P. Xing, “Iterative graph self-distillation,” CoRR, 2020. [548] S. Lin, P. Zhou, Z.-Y. Hu, S. Wang, R. Zhao, Y. Zheng, L. Lin, E. Xing, and X. Liang, “Prototypical graph contrastive learning,” 2021. [549] S. Zhang, Z. Hu, A. Subramonian, and Y. Sun, “Motif-driven contrastive learning of graph represen- tations,” CoRR, 2020. [550] F. L. Opolka, A. Solomon, C. Cangea, P. Velickovic, P. Liò, and R. D. Hjelm, “Spatio-temporal deep graph infomax,” CoRR, 2019. 99
Title: Neural Generation Meets Real People: Towards Emotionally Engaging Mixed-Initiative Conversations: Summary: We present Chirpy Cardinal, an open-domain dialogue agent, as a research platform for the 2019 Alexa Prize competition. Building an open-domain socialbot that talks to real people is challenging - such a system must meet multiple user expectations such as broad world knowledge, conversational style, and emotional connection. Our socialbot engages users on their terms - prioritizing their interests, feelings and autonomy. As a result, our socialbot provides a responsive, personalized user experience, capable of talking knowledgeably about a wide variety of topics, as well as chatting empathetically about ordinary life. Neural generation plays a key role in achieving these goals, providing the backbone for our conversational and emotional tone. At the end of the competition, Chirpy Cardinal progressed to the finals with an average rating of 3.6/5.0, a median conversation duration of 2 minutes 16 seconds, and a 90th percentile duration of over 12 minutes. # Neural Generation Meets Real People: Towards Emotionally Engaging Mixed-Initiative Conversations # Ashwin Paranjape∗, Abigail See,∗ Kathleen Kenealy, Haojun Li, Amelia Hardy, Peng Qi, Kaushik Ram Sadagopan, Nguyet Minh Phu, Dilara Soylu, Christopher D. Manning Stanford NLP {ashwinpp,abisee,kkenealy,haojun,ahardy,pengqi, kaushik7,minhphu,soylu,manning}@stanford.edu # Abstract We present Chirpy Cardinal, an open-domain dialogue agent, as a research plat- form for the 2019 Alexa Prize competition. Building an open-domain socialbot that talks to real people is challenging – such a system must meet multiple user expectations such as broad world knowledge, conversational style, and emotional connection. Our socialbot engages users on their terms – prioritizing their interests, feelings and autonomy. As a result, our socialbot provides a responsive, person- alized user experience, capable of talking knowledgeably about a wide variety of topics, as well as chatting empathetically about ordinary life. Neural generation plays a key role in achieving these goals, providing the backbone for our con- versational and emotional tone. At the end of the competition, Chirpy Cardinal progressed to the finals with an average rating of 3.6/5.0, a median conversation duration of 2 minutes 16 seconds, and a 90th percentile duration of over 12 minutes. # Introduction This paper describes our socialbot for open-domain conversation, Chirpy Cardinal, built as a research platform during the 2019 Alexa Prize competition. During the competition, US-based Amazon Alexa users could give an invocation phrase (such as let’s chat) to be connected to one of the competing socialbots (chosen randomly). After receiving a minimal orientation phrase at the beginning of the conversation, the user talks to the socialbot (in English) until they decide to end the conversation – at which point, they are invited to provide a rating and comment. To provide a convincing user experience, an open-domain conversational agent must excel at lan- guage understanding, language generation, emotional engagement, memory, world knowledge and conversational planning, among other desirable characteristics – an ambitious goal! Prior work within and outside the Alexa Prize competition has taken the successful strategy of pushing progress along individual skills, and forming an ensemble of sub-systems, each excelling at a singular characteristic while ignoring others. For instance, supporting user initiative in open-domain conversations is extremely challenging, as it requires understanding the countless ways a user can take initiative, and the ability to respond to each of them with specificity. Faced with this difficulty, when it comes to in-depth conversations, many previous dialogue systems rely primarily on bot-initiative, driving users along carefully scripted paths. On the other hand, systems attempting higher user-initiative via non-scripted paths are likely to lead towards shallower conversations. Thus there is a lot of room for innovation and research in trying to simultaneously achieve two or more complementary characteristics; this is a recurring theme throughout this work. Our goal in building this socialbot was # ∗equal contribution 3rd Proceedings of Alexa Prize (Alexa Prize 2019). to offer a natural-sounding and emotionally engaging dialogue agent that can talk knowledgeably about a wide variety of topics, while also letting the user take as much initiative as possible. Initiative – the ability to drive the direction of the conversation – has been studied extensively in the context of task-oriented dialogue. Mixed initiative (Horvitz, 1999), in which the user and the bot share initiative, is an important quality of a successful dialogue system, as it provides the user a sense of agency without making them entirely responsible for suggesting new topics and directions. In order to improve on mixed initiative while still providing an acceptable conversational depth, we designed our initial system to rely heavily on system initiative, but at the same time explored several avenues to increase user initiative in a controlled fashion. To support mixed initiative, our system has a global navigational intent classifier (Section 3.1) and entity tracker (Section 3.2), allowing it to track high level topic changes from both the user and the bot. Further, our response priority system (Section 3.3) allows individual Response Generators (RGs) to interject when the user initiates a change of topic. High-coverage world knowledge is an important component of open-domain conversation – our bot must be able to talk about the diverse range of entities and topics that interest users, particularly if we wish to respect user initiative. We use the Alexa Knowledge Graph, The Washington Post, Reddit and Twitter as sources of up-to-date knowledge in particular domains, while ensuring high coverage by using Wikipedia and Wikidata entities as the foundation of our entity-based conversations (Sections 4.4, 3.2 and 6.3). However, world knowledge must be delivered in a conversational style – this is a characteristic that distinguishes a socialbot from a virtual assistant. To achieve this, we finetuned a neural generative model on the TopicalChat dataset (Gopalakrishnan et al., 2019) to obtain a conversational paraphrasing model that adapts external text into a conversational style (Section 5.3). A socialbot cannot focus solely on external entities – to be truly social, it must be able to discuss personal experiences and emotions. While ELIZA-like systems (Weizenbaum et al., 1966) attempt this via templated repetition of user phrases, they lack the naturalness and depth of real human conversations. Our Neural Chat module (Section 5.2) invites the user to share their everyday experiences and current emotions, and uses a neural generative model to respond empathetically. With it, we attempt to have a deep, sustained and emotionally engaging conversation about a user’s lives. In addition, our Opinion module (Section 5.4) allows the user to express their feelings by expressing their likes and dislikes. To foster a reciprocal atmosphere, our bot also shares its own distinct feelings, experiences and opinions. Lastly, we note that the advent of large-scale pretrained neural generative models has substantially impacted what is possible in open-domain socialbots. While in the last Alexa Prize competition, none of the top three socialbots used neural generation (Chen et al., 2018; Pichi et al., 2018; Curry et al., 2018), we found current GPT-2 models (Radford et al., 2019) to be a key tool to support our design goals. Neural generation enables natural phrasing and emotional engagement, as well as more flexible responsiveness (e.g., when used as a fallback in Section 5.7), supporting higher user initiative. A limitation of neural generation methods for dialogue is deterioration in quality and consistency over a long conversation, which can be potentially overcome with symbolic constraints. We explore ways to bring the best of both worlds – long term consistency and short term fluidity – together. Despite being a first-time entrant, at the end of the competition our system achieved a rating of 3.6/5.0, which is within 0.1 of the highest-ranked systems, and is capable of detailed, sustained conversations with interested users (with a 90th percentile conversation duration of 12 minutes 55 seconds). Qualitatively, during in-person interactions with users, we observed that many innovations such as in-depth discussions of everyday life, conversational styling of informational content, and opinionated exchanges were received with expressions of pleasant surprise – indicating our steps were in the right direction. In Section 6, we re-examine the goals we set out to achieve, and empirically analyze our bot’s successes and failures. In Section 7, we talk about the challenges we faced, the trade-offs we made, our conclusions and avenues for future work. # 2 System Overview Our overall system design is shown in Figure 1. Our system is built on top of the CoBot framework (Khatri et al., 2018). On each turn, the user’s spoken utterance is transcribed by Alexa’s Automatic Speech Recognition (ASR) service. The transcribed utterance (which is lowercase, no punctuation) is sent to our AWS Lambda function, which handles the core logic of our bot. AWS Lambda is a 2 User @ t transcribed user spoken user spoken bot utterance utterance = utterance bot utterance + Alexa device Chirpy Cardinal Social Bot NLP Pipeline Get responses from Get prompts from Response Generators Response Generators iki Wiki Entity Linker Wikipedia articles | |—+ Wikipedia articles || Neural paraphraser Neural paraphraser Wikipedia entities — neal Opinion inal Opinion P— Dialogue Act Twitter opinions ‘Twitter opinions Classifier Neural Chat Neural Chat Neural generator Neural generator |) | Question 2 : Classifier Fallback Fallback | responses prompts v ae 5 Navigational Priority Ranking ' Priority Sampling q Intent Classifier ~~ 4 = Yresponse t P Entity Tracker | Entity Tracker Entity Tracker Bt bot utterance = Dialogue -——NO yes response+prompt Manager bot utterance = response previous turn’s state this turn’s state State Table | Legend:| AWS Lambda || AWS EC2 (GPU) | aws eco (cPu) | AWS DynamoDB | AWS ElasticSearch || AWS Relational Database | Not builtby our team | Figure 1: Overall system design. serverless computing platform, which means that our function is stateless. To preserve information between turns, we store our bot’s overall state in an external State Table (see Figure 1), hosted on AWS DynamoDB. At the start of the turn, the previous turn’s state is fetched from the table. We then run the NLP Pipeline (see Section 4) – a collection of modules that produce annotations based on the user’s utterance and the current state. Modules requiring greater computational resources are hosted on remote EC2 instances, while less-demanding modules are hosted within the Lambda function. The NLP Pipeline is organized as a directed acyclic graph (DAG), allowing modules to use other modules’ annotations as inputs. To minimize latency, modules are run in parallel where possible, with each module starting as soon as its inputs are ready. Next, we analyze the user’s utterance to determine whether the user wants to talk about any particular entity (see Navigational Intent, Section 3.1), and update the current entity under discussion if appropriate (see Entity Tracker, Section 3.2). We then run our collection of Response Generators (RGs), modules designed to handle particular conversational duties, in parallel (see Section 5). Each RG either produces a response, or no response (None). If an RG produces a response, it also supplies a response priority (see Section 3.3), indicates whether the response needs a prompt added from another response generator (see Section 3.4), and specifies what the current entity under discussion should be, if the response is chosen. The Priority Ranking module chooses the response with the highest priority, and the Entity Tracker updates the 3 current entity under discussion accordingly. If the chosen response does not need a prompt, it forms the entire bot utterance. If the chosen response does need a prompt, we run our collection of RGs a second time. Each RG either produces a prompt or no prompt (None). If an RG produces a prompt, it also supplies a prompt priority (see Section 3.5) and a current entity, as before. The Priority Sampling module chooses the prompt by sampling from the supplied prompts, with the probability distribution depending on both the priorities of the prompts and the RGs that produced them. The Entity Tracker updates the current entity again, and the bot’s utterance is then formed by appending the prompt to the response. At the end of the turn, the bot’s overall state contains the user’s utterance, the conversational history, the NLP Pipeline annotations for the user’s utterance, and a state for each individual Response Generator.2 We write the new state to the State Table, and send the bot utterance to Alexa’s Text To Speech (TTS) service, which delivers the spoken bot utterance to the user. # 3 Dialogue Management Our Dialogue Manager handles the high-level logic of tracking which topics we are discussing with the user, and which responses (and prompts) should be used to form the bot’s utterances. # 3.1 Navigational Intent Classifier A user has navigational intent when they are indicating that they do (positive) or do not (negative) want to talk about a particular topic. Users might give navigational intent while specifying the topic (can we talk about minecraft, stop talking about minecraft), or referring to the current topic (let’s discuss this more, could you change the subject), or referring to no topic (alexa can we talk, i don’t want to chat any more). Users sometimes give positive and negative navigational intent in the same utterance (i don’t want to talk about movies any more let’s chat about you). To recognize navigational intent, we use manually-constructed regexes, as they are quite high precision. # 3.2 Entity Tracker For our response generators to work together to discuss different topics smoothly, we must track which entities we are currently discussing, which we have finished discussing, and possible entities to discuss in the future. This is the role of the entity tracker. We assume that at any point in the conversation, there is one current entity, which is either a Wikipedia entity (see Section 4.4) or None (if we’re discussing something that does not have a Wikipedia article, such as Table 1 Turn 3).3 The current entity is updated at most three times per turn (see Figure 1): 1. After analyzing the user’s utterance. The entity tracker uses the entity linker’s output, which is a priority-ordered list of possible entities mentioned by the user on this turn, along with their scores (see Section 4.4 for details.) If the user expressed negative navigational intent towards the current entity, it is rejected. If the user expressed positive navigational intent towards some topic, we search inside the topic slot in their utterance; the highest- priority entity with score over a low threshold (1,000) is chosen as current entity. If there is a particular type of entity we expect the user to mention on this turn (e.g. if the bot asked What’s your favorite movie?) and there is an entity with the expected Wikidata category (e.g. film) with score over a low threshold (1,000), it is chosen as current entity. Otherwise, if the entity linker has made a prediction with sufficiently high score (over 10,000), it becomes the current entity. If none of these conditions are met, the current entity stays the same. 2. After choosing the response. When the RGs provide responses, each RG also specifies what the new current entity should be, if its response is selected by the priority ranker. We update the current entity to be whatever was provided by the selected RG. 3. After choosing the prompt. If we get a prompt, we update the current entity similarly. 2Each individual RG state contains information required by that RG – for example, it might contain the current node (aka treelet, see Section 5.1) in the RG’s dialogue graph, or a list of the utterances and/or entities that have been discussed, to avoid repetition. Each RG maintains its own individual state. 3In the future, we plan to generalize the entity tracker to track non-Wikipedia discussion topics. 4 Bot: Hi, this is an Alexa Prize Socialbot. I’d love to get to know you a bit better before we chat! Is it all right if I ask for your name? [ Launch ] Launch gives FORCE_START response to be- gin the conversation. 2 User: my name is chris Bot: Well it’s nice to meet you, Chris! I’m excited to chat with you today. [ Launch ] I hope your after- noon is going well. What are your plans for the rest of today? [ Neural Chat ] None None Launch gives a STRONG_CONTINUE re- sponse that needs a prompt, which is supplied by Neural Chat with FORCE_START priority (scripted transition). 3 User: hang out with my friends Bot: That sounds great, I love spending time with friends. What will you do together? [ Neural Chat ] None None Neural Chat generates a GPT-2 response with STRONG_CONTINUE priority. 4 User: maybe watch a movie Bot: Me too! I love watching movies; I get to learn so much about what the world is like outside of the cloud! Have you seen any movies recently? [ Movies ] 5 User: i saw the matrix None Film The Matrix Movies detects the ‘movie’ keyword in the user’s utterance and gives a FORCE_START response (overriding Neural Chat), setting current entity to Film. The Entity Linker and Entity Tracker iden- tify The Matrix as the current entity. Bot: Nice! Did you like The Matrix? [ Movies ] 6 User: i loved it neo is amazing Bot: Oooh, yeah, I agree. Hey, isn’t Keanu Reeves in that movie? What do you think about Keanu Reeves? [ Movies ] The Matrix The Matrix Keanu Reeves Movies sets current entity to Keanu Reeves. 7 User: i want to talk about something else Bot: OK, no problem. [ Movies ] There’s actually something else I wanted to ask you about. What’s your favorite animal? [ Categories ] None Animal Navigational Intent detects negative intent, so Entity Tracker rejects the current entity. Movies acknowledges and asks for a prompt. Categories gives a GENERIC prompt. 8 User: i love cats Bot: Good to hear you like cats. I have to be honest though, I’m not a big fan of cats. I feel like cats don’t respect my personal space, but I would love to hear why you like cats? [ Opinion ] Cat Cat Entity Linker and Entity Tracker identify Cat as current entity. Opinion gives a CAN_START response about cats. 9 User: hmm i love cats because they are fluffy Bot: That make sense. Now that I think about it, one good reason to like cats is that they purr and I definitely need that kind of positive feed- back. [ Opinion ] Wanna know something interest- ing about cat? [ Wiki ] Cat Cat Opinion finishes talking. Wiki gives a CUR- RENT_TOPIC prompt about Cat. 10 User: you are not very smart Bot: I know you feel frustrated. I’m always trying to get better. [ Offensive User ] I’ve been listening to some new music today and I wanted to chat about instruments. If you were a musical instrument which one would you be? [ Music ] 11 User: what do you find interesting Bot: I like the violin, but I’m more of a classical music player. [ Neural Fallback ] I remember you mentioned Neo. Would you like to talk more about it? [ Wiki ] 12 User: sure Cat Musical in- strument None Neo (The Matrix) Offensive User gives a FORCE_START re- sponse to the critical utterance, then [ Music ] provides a GENERIC prompt to steer the con- versation in a new direction. The user gives an unexpected response. Neural Fallback gives a GPT-2-generated re- sponse, which is selected as no other RG (ex- cept Fallback) has a response. Wiki gives a CONTEXTUAL prompt. Bot: Neo has got into so many adventures! What are some adventures that you’ve enjoyed? [ Wiki ] 13 User: morpheus teaching jujitsu to neo Bot: I liked that Neo and Trinity were able to res- cue Morpheus from a building protected by armed guards and agents. Morpheus has done so many amazing things! What are some of your favorite Morpheus moments? [ Wiki ] — # Neo (The Matrix) Neo (The Matrix) Neo (The Matrix) Morpheus (The Matrix) Wiki asks an open-ended question (specific to movie characters) about Neo (The Matrix). Wiki gives a response (generated by the GPT- 2 conversational paraphrasing model), sets the current entity to Morpheus (The Matrix), and asks another open-ended question. 14 User: i want to stop talking # None We detect stop intent; the conversation ends. Table 1: An example dialogue. To respect users’ privacy, this is not a real user conversation. 5 Response Priority FORCE_START STRONG_CONTINUE CAN_START WEAK_CONTINUE Meaning This inactive RG should take control (e.g., Table 1, Turn 4), or override, such as handling offensive user utterances (e.g., Table 1, Turn 10). This active RG can continue the conversation with a good next response (e.g., Table 1, Turn 2). Only a FORCE_START can override it. This inactive RG can potentially take control (e.g., Table 1, Turn 8), but should not interrupt a STRONG_CONTINUE. This active RG can continue the conversation but its next response is of poorer quality. It should be overridden by any available CAN_STARTs (or higher). Table 2: Response Priorities (ordered by descending importance) # Prompt Priority FORCE_START CURRENT_TOPIC CONTEXTUAL Meaning This RG should take control. This is mainly used for scripted transitions (e.g., Table 1, Turn 2). This RG has a prompt that talks about the current entity (see Section 3.2 and Table 1, Turn 9). This RG has a prompt that does not talk about the current entity, but that is conditioned on the conversation history, e.g. referring to a previous topic (e.g., Table 1, Turn 11). This RG has a prompt that is not conditioned on the conversation so far (e.g., Table 1, Turn 7). Prompt Priority Meaning # GENERIC # Table 3: Prompt Priorities This system allows the user to initiate topics (e.g. the bot starts talking about cats if the user utterance is i want to talk about cats), allows RGs to initiate topics (see Table 1, Turn 4), allows multiple RGs to talk seamlessly about the same topic (see Table 1, Turn 10), and allows RGs to signal when a topic should be finished (see Table 1, Turn 7). # 3.3 Response Priority Ranking System We use a priority system to decide which response generator’s response should be selected on each turn. When generating responses, each RG provides one of the response priorities in Table 2.4 This hierarchy supports the ability to preserve conversational continuity (STRONG_CONTINUE), while remaining responsive to the user’s initiative (FORCE_START). Though it is a relatively simple rule- based system, we have found it well-suited to our needs. The priority levels are clear to understand, and make it easy to modify behavior. By avoiding a centralized response-choosing module, our design allows RGs to decide themselves whether or not they should respond, and whether their response is high quality. This makes it easier for multiple people to work on different RGs, each with self-contained logic. Lastly, if one RG encounters an error, timeout, or inability to find relevant content, the other RGs provide alternatives. # 3.4 Response-and-Prompt System As described in Section 2, on some turns the bot utterance consists of a response from one RG, followed by a prompt from another RG. This system is useful when the responding RG can handle the user’s current utterance, but is unable to take the conversation forward (see Table 1, Turn 10) or when the responding RG has finished talking about one topic, and another RG is needed to supply a change of topic (see Table 1, Turn 7). The response-and-prompt system makes it easy to always supply the user with a strong path forward in the conversation (e.g. by asking the user a question). # 3.5 Prompt Priority Sampling System While we use a deterministic ranking system to choose the highest-priority response (Section 3.3), prompts often represent changes of topic, which are less restricted by context, and (in human-human conversations) tend to have a degree of randomness. Thus, we use a priority sampling system to select a prompt. When generating prompts, each RG supplies one of the prompt priorities in Table 3. Under the Priority Sampling module, if a FORCE_START prompt is supplied, we choose it. Otherwise, we sample from a manually-specified distribution over the remaining priorities, masking out any that 4In case of a tie, we tie-break using a manually-specified priority ordering of the RGs. 6 Training Regime MIDAS (baseline) MIDAS+self-training (τ = 0.95) MIDAS+self-training (τ = 0.75) MIDAS+supervised # MIDAS Training Set 10,090 10,090 10,090 10,090 Chirpy Training Set # Silver 0 41,152 62,150 0 # Gold 0 0 0 2,407 # Table 4: Performance of our Dialogue Act model under different training regimes. are not present on this turn. The distribution is biased towards maintaining continuity of discussion (CURRENT_TOPIC >> CONTEXTUAL > GENERIC). Then, among the RGs that produced a prompt of the sampled priority, we sample one prompt, using a manually specified distribution over the RGs. This system allows us to specify scripted transitions when desired, and to provide variety via randomness, while still enabling us to tune the likelihood of changing topic, which is an important controllable parameter in chit-chat conversations (See et al.}/2019). # 4 NLP Pipeline The NLP Pipeline is run at the start of every turn (see Figure 1), and contains modules that annotate the user’s utterance with information that is useful for other parts of the bot. # 4.1 CoreNLP On each turn of the conversation, we annotate the the user’s utterance using the Stanford CoreNLP toolkit (Manning et al., 2014), which runs on a remote EC2 module with CPU only. We use the fol- lowing CoreNLP annotators: tokenization, sentence splitting, part-of-speech tagging, lemmatization, named entity recognition, constituency parsing, dependency parsing, coreference resolution, and sentiment analysis. Due to the format of the user utterances (lowercase with no punctuation), we use the caseless models5 for part-of-speech tagging, constituency parsing and named entity recognition. # 4.2 Dialogue Act Classifier Dialogue acts can support understanding of user intent (Stolcke et al., 2000), and have been success- fully employed in previous Alexa Prize socialbots (Yu et al., 2019). To build a dialogue act classifier, we finetuned the HuggingFace implementation (Wolf et al., 2019a) of a BERT-based classification model (Devlin et al., 2018) on the MIDAS dataset (Yu and Yu, 2019). The dataset contains 12,894 examples, where each example is a bot utterance,6 the user’s response to that utterance, and the user’s dialogue act.7 The dataset was collected by Gunrock (Yu et al., 2019), the winner of the 2018 Alexa Prize competition. Unlike other dialogue act datasets, such as SWBD-DAMSL (Jurafsky et al., 1997), which are designed for human-human dialogue, the MIDAS annotation schema was specifically designed for human-chatbot dialogue. Though this baseline model achieved a micro-average F1-score of 0.78 on the MIDAS test set, we wished to evaluate its performance in our own bot’s conversational setting. We hand-labeled a ‘Chirpy’ test set containing 602 examples from our bot’s conversations. The same baseline model achieved only 0.53 on this test set (see Table 4). We suspect the performance drop is due to the distributional difference between the utterances generated by our bot and by Gunrock. To improve performance on our data, we experimented with self-training (McClosky et al., 2006). Using the baseline model, we labeled a large number of unlabeled examples from our own bot’s conversations. Examples whose label was predicted with a confidence score greater than a threshold τ were added to our training set. Using τ = 0.75 and τ = 0.95 added 62,150 and 42,152 silver-labeled training examples, respectively. After training on these expanded datasets, we re-evaluated on our own test set. The inclusion of 5https://stanfordnlp.github.io/CoreNLP/caseless.html 6The bot utterance is included because it contains context essential to understand the user utterance (Yu and Yu, 2019). For instance, the user utterance ‘tiger king’ is an opinion when in response to ‘What is the best show?’ and a statement when in response to ‘What is the last show you watched?’. 7To better fit our needs, we modified the label space as described in Section C.1. 7 the silver-labeled data did not substantially boost performance (see Table 4). Finally, we turned to supervised training, and hand-labeled an additional 2,407 examples from our own bot’s conversations (procedure described in Section C.2). After training on the MIDAS data and this data, we achieved a much higher micro-F1 of 0.81 on the Chirpy test set. In our bot, we run the Dialogue Act classifier on an EC2 machine with one NVIDIA T4 Tensor Core GPU, annotating every user utterance in the conversation. We find that its accuracy is best on classes with low variance in user utterances, such as positive answer, while classes with high variance, such as statement, are more difficult. However, even for the low variance classes, the classifier’s labels are very useful – we are able to achieve much higher recall in recognizing positive answer and negative answer by using the classifier’s labels, compared to regexes or word lists. # 4.3 Question Classifier Users often spontaneously ask factual questions, personal questions, follow-up questions, and even questions unrelated to the current topic. Recognizing and answering these questions is important, particularly for user initiative, but is also non-trivial, as user utterances do not contain punctuation. To recognize questions, we initially used the Dialogue Act classifier’s labels (which include question types like factual question and open-ended question). However, this did not work well; the classifier seemed to condition too much on the bot utterance preceding the user utterance – which is less useful for recognizing questions than other dialogue acts. Instead, we fine-tuned a RoBERTa model (Liu et al., 2019; Wolf et al., 2019a) on an simplified version of the Dialogue Act training data, framing the task as binary classification, conditioned only on the user utterance. This model achieved an F1-score of 0.92 and improved the reliability of question detection. The classifier’s labels are used to determine when certain RGs should respond – for example, when the Evi RG (Section A.3) should answer a factual question. The labels are also useful for the neural generative models (Sections 5.2, 5.3, 5.7). We observe that the GPT-2-based models are much more likely to answer (rather than ignore) a user’s question if a question mark is present. Thus, we use the classifier labels to determine when to append a question mark to the user utterance. # 4.4 Entity Linker A key part of our high-coverage strategy (Section 1) is entity linking – detecting when the user is referring to an entity, and identifying the correct entity. To obtain our pool of potential entities, we processed a dump8 of English language Wikipedia. For each article (i.e. each entity E), we collected (a) the pageview (number of views in one month), and (b) the anchortext distribution Panchortext(a|E). To compute the anchortext distribution for an entity E, we count the number of anchortexts (i.e., strings, lowercased) that are used as hyperlinks to E across Wikipedia (e.g., the entity Barack Obama may be referred to using the anchortexts barack obama, obama, or president obama). Then: count(links from a to E) area(s) Count(links from a’ to E) Panchortext(@|E) (1) where A(E) is the set of all anchortexts that link to E. We store each entity, along with its Wikipedia article, pageview, anchortext distribution, and Wikidata categories9 in an ElasticSearch index. After we receive the user’s utterance u, we assemble the set of candidate spans S. S contains all n-grams in u with n ≤ 5, excluding n-grams that consist only of stopwords. We then query ElasticSearch to fetch all entities E which have at least one span s ∈ S among its anchortexts. To determine which entities the user is referring to, we wish to estimate P (E|s), the likelihood that a span s is referring to an entity E. We model P (E|s) as a Bayesian system: P (E|s) ∝ P (E) × P (s|E). (2) We assume that P (E) is proportional to the pageview for the entity E, and P (s|E) = Panchortext(s|E). Therefore, we define the score(s, E) of a span s and and entity E to be: score(s, E) = pageview(E) × Panchortext(s|E). (3) 8https://dumps.wikimedia.org 9For each entity, we collected all its ancestors via the instance of and subclass of relations. For people entities, we also used the occupation relation. 8 The output of the entity linker is a priority-ordered list of (s, E) pairs. The ordering is calculated using manually-curated rules and thresholds on the following features: (a) the score of (s, E), (b) the maximum unigram frequency10 of s, (d) whether E is in a Wikidata category that is expected for this turn11, (c) whether s is contained inside any other linked span (priority is usually given to the larger span). The output of the entity linker is primarily used by the entity tracker (Section 3.2) to identify the current entity under discussion. Limitations We found the entity linker to be one of the hardest components of our bot to build. One difficulty is that our notion of an entity – anything with a Wikipedia article (e.g. Cat or Musical instrument in Table 1) – is much broader than the traditional definition of Named Entities (which is typically restricted to particular types, such as people and locations). Our motivation in this definition was to enable high-coverage world knowledge by enabling any Wikipedia article to become a focus of discussion. However, this made the entity linker’s job much more difficult. The need to detect an extremely broad range of entities, with no restriction to certain types, made it much more difficult to find a good precision/recall tradeoff, leading to both false positive and false negative problems in the bot. In the future, we will need to develop better approaches for identifying our expanded notion of entities, or find a way to support high coverage of topics without relying as much on the entity linker. ASR Error Robustness As we do not have access to original user audio, ASR errors are a major source of difficulty, particularly when they occur within entity names. For example, if the user wants to talk about the film Ford v Ferrari, but the ASR transcription is four v ferrari, our entity linker will fail to identify the correct entity, as the span four v ferrari is not among the anchortexts for the entity Ford v Ferarri. To address this, we adapted our entity linker to be robust to phonetically-similar spans and anchortexts; our method is similar to Chen et al. (2018). First, we converted all Wikipedia entity anchortexts to their phoneme and metaphone representations (e.g., Harry Potter to ‘HH EH R IY P AA T ER’ and ‘HRPTR’) with a grapheme-to-phoneme tool12 and the double metaphone algorithm,13 and indexed the mapping from anchortext phonemes to Wikipedia entities in ElasticSearch. When running the entity linker, we convert all spans s ∈ S to their phonetic representations and query the ElasticSearch index, which returns a set of anchortexts Aphon that have similar phonetic representations to any of the spans queried. This allows us to expand the candidate pool for each span s, from entities for which s is an anchortext, to entities for which s is phonetically similar to an anchortext. Finally, we redefine P (s|E) as follows: for each anchortext a ∈ Aphon, we start by finding its best-matching span s∗(a) = arg maxs∈S sim(s, a) where sim(·, ·) is a phoneme similarity function14 between 0 and 1; then, we filter out anchortexts that are phonetically too dissimilar to each span with a threshold of 0.8, resulting in a set of anchortexts for each span A(s) = {a|a ∈ Aphon, s = s∗(a), sim(a, s) ≥ 0.8}. Finally: mMaXg¢ A(s) count(links from ato E) x sim(s,a) A(s) #0 ) P(s|E) x { 0 otherwise (4) This definition of P (s|E) replaces Panchortext(s|E) in Equation (3). # 5 Response Generators In this section, we describe our Response Generators (RGs). Additional minor RGs are described in Appendix A. We also describe treelets (Section 5.1), a system we used to organize many of our RGs. # 5.1 Treelets: A System to Organize Dialogue Graphs Many of our response generators rely on treelets, a modular programming abstraction which represents a single node in a dialogue graph. The treelet system is largely based on dialogue trees (Weizenbaum et al., 1966) and dialogue-frame-based systems such as GUS (Bobrow et al., 1977). We define a treelet to be a small, 1-turn dialogue ‘tree’ that manages all decisions necessary to produce a bot 10The maximum unigram frequency of s is the frequency of the most common unigram inside s, computed using this unigram frequency list for spoken English: http://ucrel.lancs.ac.uk/bncfreq/flists.html 11For example, if the bot asked What’s your favorite movie?, an expected Wikidata category is film. 12https://pypi.org/project/g2p-en/ 13https://pypi.org/project/metaphone/ 14implemented on lists of phonemes with Python’s difflib.SequenceMatcher 9 Previous bot utterance: Cool! What did you think of “Us”? v User Utterance handle_movie_opinion_treelet 1. Classify — positive (e.g. “yeah it was so original”) negative (e.g. “no it was too scary”) 2. Generate Bot Response v ¥ Bot response: Good to hear! Isn’t Lupita Nyong’o Bot response: If you didn’t like “Us”, let’s not talk in that movie? What do you think about her? about it. What's a film you love? 3. Select Next Treelet 1 J Next treelet: handle_actor_opinion_treelet Next treelet: handle_favorite_movie_treelet Figure 2: An example treelet for the Movies RG. response given a user’s utterance. This involves interpreting the user utterance, creating the bot’s response, and specifying the treelet that should take control on the next turn. Typically, a treelet performs three actions: (1) it classifies the user’s utterance into one of several branches, (2) it produces an appropriate bot response for that branch, (3) it specifies the next treelet. Treelets throughout our bot may classify user utterances by using regexes, outputs from our NLP pipeline (the dialogue act classifier is frequently used for this purpose), or changes in entity (e.g., if a treelet in the Movies RG detects that the current entity has changed to "food" after the user says "let’s talk about food", the current Movies treelet may select a branch that returns no response). Bot responses may be handwritten or dynamically generated (we use both throughout our system). An example from the Movies RG is shown in Figure 2. Like dialogue trees in general, treelets provide a well-controlled, predictable and easily interpretable conversation flow. From an engineering and implementation perspective, treelets have several advantages, such as allowing modular organization of code and dialogue, easily enabling cycles when desired (by having treelets point to each other with repeats or loops), and minimizing code duplication by allowing many treelets to point to the same successor. # 5.2 Neural Chat The Neural Chat RG’s goal is to empathetically discuss personal experiences and emotions with the user, using responses generated by a GPT-2-medium (Radford et al., 2019) model finetuned on the EmpatheticDialogues dataset (Rashkin et al., 2019). The dataset consists of conversations between a speaker, who describes an emotional personal experience, and a listener, who responds empathetically to the speaker’s story. Our model is trained in the listener role. The Neural Chat RG has 7 discussion areas: current and recent activities, future activities, general activities, emotions, family members, living situation, and food. A discussion begins by asking the user a starter question (e.g, What do you like to do to relax? for the ‘general activities’ area). Some starter questions are conditioned on the time of day (e.g. What did you have for breakfast/lunch/dinner today? for the ‘food’ area). Starter questions can be asked as part of the launch sequence (Table 1, Turns 2 and 3), as generic changes of topic, (Do you have any plans for the weekend?), or can be triggered contextually (You mentioned your boyfriend. How did you guys meet?). On each subsequent turn of the discussion, we generate 20 possible responses from the GPT-2 model using top-p sampling with p = 0.9 and temperature 0.7. To provide a strong path forwards in the conversation, we generally choose a GPT-2 response containing a question. However, if under a third of the sampled responses contain questions, we interpret this as an indication that the model is not confident in asking a question on this turn. In this case, we choose a non-question and end the Neural Chat discussion. Under this strategy, each Neural Chat discussion contains 2.75 bot utterances on average. The model was finetuned using the HuggingFace ConvAI code15 (Wolf et al., 2019b) and is hosted on a GPU-enabled EC2 machine with one NVIDIA T4 Tensor Core GPU. To keep latency low we # 15https://github.com/huggingface/transfer-learning-conv-ai 10 Strategy NO_SHARE POS_OTHERS POS_BOT POS_BOT_STORY NEG_OTHERS NEG_BOT NEG_BOT_STORY NEGOPT_OTHERS NEGOPT_BOT NEGOPT_BOT_STORY NEGOPT_BOT + Just earlier today I took a walk outside and the fresh air Figure 3: Strategies for the emotion-focused Neural Chat starter question. POS/NEG/NEGOPT refer to positive/negative/negative+optimistic emotion. OTHERS/BOT refer to whether the emotion is attributed to other people, or to the bot. STORY indicates that the bot shares a personal anecdote. NO_SHARE POS_OTHERS POS BOT POS_BOT_STORY NEG_OTHERS strategy NEG_BOT NEG_BOT_STORY NEGOPT_OTHERS NEGOPT_BOT NEGOPT_BOT_STORY 0.0 25 5.0 75 10.0 125 15.0 ws 20.0 user response length (# characters) Figure 4: Effect of Neural Chat emotion-focused starter question strategies on user response length. truncate the conversational history supplied to the model, so that the total number of GPT-2 tokens is below 800. Given that neural models have been shown to make poor use of longer conversational history (Sankar et al., 2019), this truncation does not seem to be a limiting problem currently. Emotion-focused Conversations As part of our goal to provide an emotionally-engaging expe- rience (Section 1), we would like to give users space to share their genuine feelings, then respond empathetically to them. This is especially important during the Coronavirus pandemic (Section A.1), which is an emotionally challenging time for many. Given our basic starter question I hope you don’t mind me asking, how are you feeling?, we tried several different preambles to precede the question (Table 3). Figure 4 shows the effect of the different strategies on the length of the user’s response. We find that the basic NO_SHARE strategy has the shortest average response length, indicating that the bot’s emotional observations (whether about the bot or about other people) lead users to give more substantive responses. Users tend to give longer responses when the bot expresses negative emotions (NEG and NEGOPT) than positive (POS) – this may be because acknowledging negative emotions makes users feel more comfortable to answer the question honestly, rather than superficially (e.g. i’m fine). Furthermore, adding a personal anecdote (STORY) to the negative bot emotions led to longer responses – users may have responded more because the bot was more specific or relatable. For positive emotions (POS), users are more responsive when the bot attributes the positive emotion to itself (BOT), than to other people (OTHERS). However, for negative emotions (NEG and NEGOPT), the opposite is true. We also experimented with including the user’s name in the starter question, but found that this made no difference to user response length. Discussion Our neural generative model has several recurring weaknesses which impact overall user experience. First, it frequently asks for already-provided information, asks nonsequitur questions, makes unfounded assumptions about the user, and confuses its own previous responses with the user’s. This demonstrates that incorporating commonsense reasoning is a priority in neural generation. Sec- ond, while the model generally produces interesting and relevant responses to longer user utterances, it performs poorly when the user utterance is short or low-content (e.g. okay, i don’t know, nothing) – probably because these utterances are unlike the much longer and contentful EmpatheticDialogues 11 training data. The model tends to respond to these with bland responses that further fail to drive the conversation to any interesting substance. This problem with short user responses is one reason why we focused on finding starter questions that lead to substantial user responses (Figure 4). Due to these difficulties, most conversations with the GPT-2 model tend to fall apart after a few turns, as the bot will eventually ask a question that doesn’t make sense, which will flummox the user. This is one reason why we designed the Neural Chat module around shorter sub-conversations. However, overall, we are excited that neural generation is now able to interact successfully with real people, within certain constraints (such as keeping the discussion short, bookending it between handwritten starter questions and wrapup phrases, and providing a strong path forward through questions). # 5.3 Wiki To support our goal of high-coverage world knowledge (Section 1), the Wiki RG uses Wikipedia articles as grounding to discuss any entity that interests the user. Our goal is to allow the user to conversationally discover interesting information about the entity. Data To prepare the Wikipedia data, we downloaded the most recent Wikipedia dump,16 processed it using MWParserFromHell17 and Spark,18 and uploaded it into an ElasticSearch index. The Wiki RG can then query the ElasticSearch index to obtain the Wikipedia article for an entity. Behavior On each turn, if it’s not already active, the Wiki RG can start to talk about the current entity (Section 3.2) by asking the user an open ended question, such as What do you find interesting about it?. If the entity is in one of 25 commonly-encountered types (determined using Wikidata categories), such as books or foods, we use a more specific question, such as What did you think of BOOK_ENTITY’s story? or I love trying out new flavor combinations. What do you like to have FOOD_ENTITY with?. These questions are designed to elicit contentful user responses, which can be matched to specific sentences in the Wikipedia article using TF-IDF overlap. The RG also offers interesting facts (i.e. ‘TILs’) scraped from the /r/todayilearned subreddit, if available. If we have given enough TILs or we have no TIL left to offer, we will start suggesting sections of the Wikipedia article to the user. A short example Wiki interaction is shown in Turns 11-13 of Table 1. Conversational Styling We use this RG as a testbed for our conversational paraphrasing system. The system takes as input the truncated conversational history, and some knowledge context (either a TIL about the current entity, or an excerpt of the Wikipedia article, selected based on TF-IDF similarity to the user’s response to an open-ended question). It outputs a conversational-sounding paraphrase of the knowledge context. The model was trained by finetuning a GPT-2-medium language model (Radford et al., 2019) on a processed and filtered version of the TopicalChat dataset (Gopalakrishnan et al., 2019). The paraphrases are generated using top-p decoding with p = 0.75 and temperature τ = 0.9, and we pick the one which has the highest unigram overlap with the knowledge context. Challenges One major challenge while performing conversational styling is that the model some- times produces factually incorrect or nonsensical conversational paraphrases. Another challenge is that integrating the paraphrasing model with the rest of the system requires explicit directives such as "continue talking about same knowledge piece", "pick another fact", "change entity" which the model currently does not produce. For instance, sometimes the generated paraphrase just asks a question or mentions an incomplete piece of information, with the expectation of completing it in the next turn. Currently we apply some heuristics such as presence of Did you know ... ? style questions or low unigram overlap to determine that the same snippet needs to be paraphrased again. More broadly, there are challenges around interestingness of content. The majority of content on Wikipedia isn’t very interesting and social. While the TILs remedy that to some extent, finding interesting parts of raw text is still an open question and quite important in the open-domain conversa- tional setting. Another major challenge is content selection and discoverability. The user doesn’t know the extent of the knowledge that our system possesses for an entity. In a visual interface, the user can scroll through the article or look at a table of contents. While we partly remedy this by suggesting section titles to illustrate the kind of content we can talk about, a better system could # 16https://dumps.wikimedia.org/backup-index.html 17https://mwparserfromhell.readthedocs.io/en/latest 18https://spark.apache.org 12 Policy Name CONVINCED_AGREE ALWAYS_AGREE LISTEN_FIRST_DISAGREE Continuation Rate 0.526829 0.586638 0.587045 CI 0.0348712 0.0086009 0.0127898 Table 5: Continuation rate for each agreement policy. The Confidence Intervals (CI) differ due to different sample sizes (ALWAYS_AGREE receives 0.5 of traffic, LISTEN_FIRST_DISAGREE receives 0.3, CONVINCED_AGREE receives 0.2). perhaps understand what different parts of a Wikipedia article are talking about, and steer conversation in that direction. # 5.4 Opinion Exchanging opinions is a core part of social chit-chat. To form a stronger sense of personality, and to seem more relatable, it is important that our bot can also express its opinions. The Opinion RG’s goal is to listen to users’ opinions on certain topics, and reciprocate with its ‘own’ opinions (sourced from Twitter) on those topics. Data To collect both positive and negative opinions, we queried a Twitter stream19 using a regex to collect tweets of the form ‘i (love|like|admire|adore|hate|don’t like|dislike) TOPIC because REASON’, where TOPIC and REASON can be any text. We collected 900,000 tweets, which are stored on a Postgres table hosted on AWS Relational Database Service (RDS). Of these, we manually whitelisted 1012 reasons across 109 popular topics. To avoid speaking inappro- priately about sensitive topics, we only whitelist uncontroversial entities (such as animals, foods, books/movies/games, everyday experiences such as working from home, being sick, days of the week, etc.), and ensured that all reasons, including negative ones, are inoffensive and good-spirited. Behavior Currently, the Opinion RG activates when the user mentions one of the whitelisted entities (e.g. Table 1, Turn 8). We ask whether the user likes the entity and classify their response using the CoreNLP sentiment classifier (Section 4.1). We then either agree or disagree with the user. If we disagree, we either ask the user for their reason for their opinion, or supply a reason why we disagree, and ask what they think of our reason. Ultimately, we want the user to have a positive experience with our bot, so regardless of whether we disagree or agree with the user, we will ask the user their opinion on a related entity, and always agree with the user about the new entity. The conversation may end earlier, as we detect on each turn whether the user is still interested via their utterance length. If the utterance contains less than 4 words, and it does not contain any of the ‘agreement’ words (such as ‘same’, ‘me too’, etc.) we will hand off the conversation to another RG. Even when the RG is not active, it keeps track of whether the user has already expressed an opinion on an entity, by applying a regex similar to that applied to the tweets. Agreement Policies Disagreement is an unavoidable part of human-human conversations, and we hypothesize that occasional disagreement is necessary in order for our bot to have a con- vincing and individual personality. To test this, we implemented three policies (full details in Appendix F): (i) ALWAYS_AGREE – we always agree with the user’s sentiment on the entity; (ii) LISTEN_FIRST_DISAGREE – first we ask the user’s reason for liking/disliking the entity, then we offer our reason for disagreeing with their sentiment; and (iii) CONVINCED_AGREE – we initially disagree with the user’s sentiment on the entity, but after the user gives their reason for liking/disliking the entity, we switch our sentiment to match the user’s (i.e. we are convinced by the user). To evaluate the policies, we ask the user Would you like to continue sharing opinions? and interpret the desire to continue is an indication of a successful policy. Table 5 shows that users prefer ALWAYS_AGREE and LISTEN_FIRST_DISAGREE over CONVINCED_AGREE, and all policies have high continuation rates, suggesting that disagreement can be a positive and stimulating part of a conversation, but that the manner and delivery of the disagreement is an important factor. # 19https://developer.twitter.com/en/docs/tutorials/consuming-streaming-data 13 # 5.5 Movies The Movies RG is designed to deliver a high-quality scripted conversation about a movie the user specifies, using information drawn from the Alexa Knowledge Graph.20 Currently, the RG is activated when the user asks to talk about movies, mentions a movie keyword (such as movies or film) or talks about any movie-related entity (e.g. Saving Private Ryan, Meryl Streep, the Coen brothers, etc.). Once activated, the RG typically asks the user to name a movie, asks the user’s opinion on it, gives a fun fact about the movie, asks the user their opinion on an actor in the movie, then asks the user if they’ve seen a different movie featuring that actor (See Turns 4-7 in Table 1). The RG uses treelets (Section 5.1) to organize the dialogue graph, hand-written templates to form the bot utterances, and a mixture of regexes and the CoreNLP sentiment classifier (Section 4.1) to classify the user’s responses. The primary weakness of this RG is that, as a scripted dialogue graph, it does not offer very high user initiative (one of our design goals – Section 1). However, this RG was important especially early in the competition when our more flexible RGs were still under development, and we needed more content. Another difficulty we faced was the latency of the Alexa Knowledge Graph, which was sufficiently slow that we were limited to one query per turn; this limited the scope of interesting information that we could pull about an entity and heavily influenced the design of our dialogue tree. # 5.6 Music Similar to the Movies RG, the Music RG is designed to deliver scripted conversations about musical entities that the user specify. The RG is activated when a musician/band or a music keyword (such as music or songs) is mentioned. Once activated, the Music RG engages in a conversation specific to the type of the musical entity that was mentioned. Unlike the Movies RG, the Music RG has a randomized internal prompting system that allows the conversation to be centered around music even when a scripted conversation is exhausted for a specific entity. For example, after the Music RG goes until the end of a scripted conversation for a musician, it can ask for an internal prompt, and start a conversation about musical instruments, songs, or music in general. The randomized nature of the internal prompting system makes the conversation more flexible, and mitigates some of the weaknesses of scripted conversations mentioned in Section 5.5. # 5.7 Neural Fallback Our Fallback RG’s responses – e.g., Sorry, I’m not sure how to answer that (Section A.3) – are a poor user experience, making the user feel ignored and not understood. The Neural Fallback RG aims to generate a better fallback response using our GPT-2 EmpatheticDialogues model (Section 5.2) – to be used only if every other RG (excluding Fallback) has no response. If the neural fallback response is chosen, another RG immediately produces a prompt to move the conversation in another direction. After some filtering (e.g. removing responses that ask questions or give advice), the neural fallbacks can work well as a way to better acknowledge and show understanding of what the user said, such as on Turn 11 of Table 1. A remaining issue is latency – generating from the GPT-2 model is typically the slowest component in the turn, which is a poor tradeoff if we don’t use the neural fallback. # 5.8 Categories The Categories RG was originally designed to ask handwritten questions about certain categories; for example, Where’s a place you would love to visit? for the ‘travel’ category. These questions may be asked when the current topic is ‘travel’, or used as generic changes of topic (Table 1, Turn 7). The goal is for the user to name an entity (e.g. japan) that can form the basis for an interesting discussion (e.g. with the Wiki or Opinion RGs). However, we found that repeatedly asking users to think of entities led to decision fatigue, with many users failing to think of an entity.21 As alternatives to the QUESTION strategy, we experimented with two other strategies: STATEMENT, in which the bot just makes an observation about a relevant entity (e.g. Mexico is one of my favorite places. I love the food and beaches!), and STATEMENT+QUESTION, which combines the other two strategies. Table 6 shows that the statement followed by a question elicited the most new entities. This may be 20The Alexa Knowledge Graph is an Amazon-internal resource; our team was given access to parts of it. 21If the user does not name a new entity, we respond either with a handwritten acknowledgment and new question (if the user said I don’t know or similar), or with the GPT-2 model (Section 5.7). 14 Strategy STATEMENT QUESTION STATEMENT+QUESTION Proportion of Turns with New User Entities 0.272 0.264 0.328 CI 0.012 0.027 0.016 Table 6: Rate at which users suggest new entities, for different strategies in the Categories RG. The entities are extracted using our Entity Linker (see Section 4.4). (CI: Confidence Interval) Strategy WHY WHY+NAME AVOIDANCE AVOIDANCE+NAME AVOIDANCE+PROMPT AVOIDANCE+NAME+PROMPT COUNTER+PROMPT EMPATHETIC+PROMPT Re-offense Rate Confidence Interval ±0.049 ±0.07 ±0.049 ±0.061 ±0.047 ±0.066 ±0.042 ±0.046 0.520 0.638 0.554 0.391 0.583 0.346 0.567 0.461 Table 7: Re-offense rates for different response strategies to offensive utterances. Italic and bold denote the worst and best performing, respectively. because the statement gives users an example, and takes the focus off the user for a moment, before prompting them with a question. This is a more natural, mixed-initiative experience than simply asking a question. # 5.9 Offensive User Users sometimes give offensive or critical utterances, and it is important for our bot to handle these appropriately (Curry and Rieser, 2018, 2019). Unsurprisingly, there is an inverse relationship between the presence of offensive user utterances in a conversation and the conversation rating (Figure 9). Our goal is to redirect the user away from making offensive comments, towards topics the bot can discuss. On each turn, the Offensive User RG checks the user’s utterance for offensive language using a blacklist of offensive phrases.22 If the user’s utterance is more critical than offensive, we respond with an apologetic strategy (see Turn 10 of Table 1). For offensive user utterances, we implemented two immediate response strategies: asking the user why they made the offensive remark (WHY); or politely avoiding the topic (AVOIDANCE). In addition, for AVOIDANCE, we experimented immediately changing the topic by using a prompt in the same turn (AVOIDANCE+PROMPT). For each of these configurations, we experimented with mentioning the user’s name (NAME), or not. We also implemented the strategy COUNTER+PROMPT, inspired by Brahnam (2005), which directly confronts the user before changing topic, and EMPATHETIC+PROMPT, inspired by Chin et al. (2020), which empathizes with the user before changing topic. The full details can be found in Appendix E. Table 7 shows the effect of each strategy on re-offense rate (i.e., the probability that the user says another offensive utterance in the same conversation). We find that mentioning the user’s name reduces the likelihood of re-offense when we use the avoidance strategy, but increases re-offense rate when we ask the user why they made an offensive remark. We hypothesize that by using their name, we motivate the user to defend themselves, which prolongs the offensive conversation. We find that our AVOIDANCE+NAME+PROMPT method outperforms the empathetic method (EMPATHETIC+PROMPT) and the confrontation method (COUNTER+PROMPT). 22https://www.freewebheaders.com/full-list-of-bad-words-banned-by-google/. Our offen- sive classifier is also used by our RGs to check that externally-sourced content (e.g. news articles, Wikipedia articles, fun facts) are inoffensive. 15 # 6 Analysis # 6.1 Relationship between Rating and Engagement 4p Number of Tums vs Ratin Number of Distinct Entities vs Rating Avg User Utterance Length vs Rating Avg Bot Utterance Length vs Rating 4.50 jp 40 40 35 —~ 425 4 238 24.00 235 2 f~ 2 2 ge | Ts 230 | / 236 @ 375 & 30 \ é 28 34 3.50 25 32 3.25 20 20 0 50 400 o 0 wo 2% 0 20 40 50 100 150 Number of Turns Number of Entities Avg User Utterance Length Avg Bot Utterance Length Figure 5: Engagement metrics vs rating We measured four metrics of engagement: number of turns in the conversation, number of distinct entities discussed during the conversation, average length of the user’s utterances, and average length of the bot’s utterances. Figure 5 shows that rating increases with number of turns and number of entities, but ultimately drops off. In an analysis of Alexa Prize bots, Venkatesh et al. (2018) found that across all bots, conversation length was positively correlated with rating; however, one possible explanation for our result is that our bot has limited content and at some point, the users become dissatisfied as their experience is no longer novel. In an analysis of the NeurIPS ConvAI2 challenge, Dinan et al. (2019) found a positive relationship between user utterance length and rating. We expected a similar result, thinking more talkative users would be more actively engaged. However, Figure 5 shows that rating increases with user utterance length until about 12 characters, and then decreases. Since many of our bot’s questions encourage short answers (e.g. What’s your favorite animal?; Would you like to talk about science?), and it is generally more difficult for our bot to correctly understand and handle longer answers,23 users who give longer answers may have a worse experience. For this reason, the result shown may reflect the limitations of our bot, more than a user preference for giving shorter responses. Average bot utterance length is positively correlated with average rating, with high variance in rating for shorter bot utterances. A confounding factor is that different response generators have varying average response lengths and relationship with user experience (Section 6.4) – e.g., the Offensive User RG tends to give short responses, and has a negative relationship with ratings. Response generators giving longer responses tend to have positive or neutral relationships with rating. Therefore, this plot may more reflect the UX of our response generators than a user preference for longer responses. These results may also reflect the inherent noise in user Likert-scale ratings (Liang et al., 2020). # 6.2 Relationship between Rating and User Dialogue Acts To understand how users’ dialogue acts relate to our bot’s performance, we applied a regression analysis, using the statsmodels Seabold and Perktold (2010) implementation of Ordinary Least Squares, to the distinct dialogue act classifier labels for all utterances of a conversation and the ultimate rating of that conversation. These results are shown in Table 7. As we would expect, appreciation is associated with higher ratings and complaint with lower ratings. One of our design goals was having mixed-initiative dialogue. In general, dialogue acts associated with low user initiative, such as comment, pos_answer, statement, and back-channeling were more positively associated with rating than dialogue acts associated with high user initiative, such as command, open_question_opinion, and open_question_factual. A possible explanation for this is that users take more initiative when dissatisfied with the current conversational direction, for example by giving a command to change the topic. On the other hand, users giving yes-answers or back- channeling, are likely being compliant with the bot’s direction, which may reflect greater overall satisfaction. It is possible that these results are more indicative of user satisfaction with our content than of a user preference for low vs high initiative. 23As an exception, our neural generation models perform better on longer user utterances; see Section 5.2. 16 joyful terrified orepared grateful excited proud caring content ashamed guilty ‘aithtul itimental arrassed annoyed angry furious Coefficients and SE of Emotion Labels vs Ratings he ol he he HH he BH Fei he he oe me be be bet 1 a 020 is 0 0S Coefficients of OLE made! 000 cis ol0 ais Coefficients and SE of Dialog Act Labels vs Ratings appreciation ot statement " pos answer " ronsense —— yes.no_question me pinion ’ 3 hols : 3 backchanneting Le E open question persona mL open_question factual + other_answers re neg_answer " ev command a lanitying_question — complaint tet comment 9 coeticonts oF OLE model “ Figure 6: Regression coefficients for Emo- tion vs Rating Figure 7: Regression coefficients for Dia- logue Act vs Rating Percentage of Conversations vs Entity Pageview 886 88 3 8B Percentage of Conversations se J e ie 2 ~ > 2 op? ue go ae oa PO ste Pr op? ggg 7 ¥ we Pageview Coefficients and SE of RG Presence Count vs Ratings CORONAVIRUS. ACKNOWLEDGMENT ALEXA_COMMANDS MOVIES Music OPINION wiki NEURAL_CHAT CATEGORIES (ONE_TURN HACK NEURAL, FALLBACK evi (CLOSING_CONFIRMATION RED_QUESTION NEWS: OFFENSIVE_USER FALLBACK ‘COMPLAINT RG presence Count O° Coefficients of OLE model Figure 8: Percentage of conversations in which users initiated discussion of entities with different popularity levels (pageview). Figure 9: Regression coefficients for Re- sponse Generator vs Rating. Launch RG is not included as it is in every conversation. # 6.3 Entity Coverage As part of our design goal to offer high coverage of topics (Section 1), our bot is capable of discussing any Wikipedia entity (Section 3.2), and discussed 7.5 distinct entities on average per conversation. To support user initiative and engage users, we designed our bot to be able to discuss both popular and lesser-known entities. We regard the Wikipedia pageview (Section 4.4) as a measure for an entity’s popularity. To measure users’ desire to discuss less-common entities, Figure 8 shows the percentage of conversations where users initiated discussion of an entity with different pageview levels. These counts do not include entities initiated by the bot. As the plot shows, a significant number of users wanted to discuss uncommon entities: in 8% of our conversations, users initiated discussion of entities with fewer than 2000 views and 33% of conversations covered at least one entity with fewer than 8000 views. Users who discussed rare entities with the bot appeared to have favorable experiences. Conversations with rare entities (fewer than 16000 pageviews) had an average rating of 3.88, while those without rare entities had an average rating of 3.64. To understand which entities had the greatest impact on user experience, we used the top 100 most frequent entities as features for a regression analysis, using an Ordinary Least Squares model. Of the 100 most popular entities, 15 had a statistically significant (p ≤ 0.05) positive impact on rating. These include animals (‘Cat’, ‘Dog’), movies (‘Film’, ‘Frozen 2’, ‘Onward (film)’), food (‘Korean fried chicken’, ‘Pizza’, and ‘Ice cream’), and video games (‘Minecraft’, ‘Fortnite’). 17 # 6.4 Effectiveness of Response Generators We performed a regression analysis on the relationship between response generator use and rating, using the number of turns each RG contributed as features. Figure 9 shows a statistically significant positive relationship between rating and the Coronavirus, Acknowledgment, Movies, Opinion, and Wiki RGs, and a statistically significant negative relationship for Red Question, Complaint, Fallback, Neural Fallback, and Offensive User. The Complaint and Offensive User results may be explained by the fact that users experiencing poor conversations may complain or be offensive, and conversely, some adversarial users deliberately engage negatively and then give poor ratings. A possible cause for the negative Fallback and Neural Fallback results is that these RGs are used when no other RG has a high-quality response, so their use is likely correlated with a worse user experience. As we expected, RGs designed for general conversation had more positive coefficients. Of these RGs, those with more scripted content, i.e. Coronavirus, Acknowledgment, Movies, and Categories had larger positive coefficients than those with less, such as Opinion and Wiki. However, the most significant loss in performance occurs when the bot cannot answer contextually or has an adversarial user. # 7 Discussion and Future Work Full Stack NLP Most NLP research focuses on self-contained tasks. However, an open-domain socialbot, served to a diverse range of customers in widely different contexts, is by no means a self- contained task. Our socialbot is a tapestry of many such components, requiring a deep understanding of each component and how they should work together – a setting we call Full Stack NLP. Often the inputs and outputs of these components are inter-dependent, leading to cascading errors. We made many design choices which delay hard decisions in pipelines, and maximize information exchange between modules. Moving forward, the next avenue for advancing the state-of-the-art would be research on models which perform these tasks jointly and methods which enable training over multiple interdependent tasks with only a small amount of joint supervision. Domain Shift As a recurring problem, we found that many existing NLP resources didn’t work well out-the-box. The main reason for this is that the training data for these resources (typically non-conversational, longform, traditionally-formatted written text) is misaligned with our setting (conversational, shortform, uncased, punctuationless, spoken text). However, a deeper reason is the constantly changing nature of dialogue agents themselves. Even for an extremely related resource (the MIDAS dialogue model, developed for the Alexa Prize, Section 4.2), domain shift was a problem. Recent advances in online- and meta-learning could provide a useful long term solution to this issue. Conflict and Intimacy Bot-human conversations are fundamentally different to human-human conversations. Users can be adversarial, deliberately testing the bot’s boundaries. As socialbot designers, we are eager to avoid a disaster like Microsoft Tay, so we apply strict but overly simplistic methods to block off sensitive topics (Sections 5.4, 5.9). However, this rules out sincere conversation about difficult topics. We observed that users are actually quite resilient to conflict, and can find disagreement stimulating (Section 5.4). We also found that emotional intimacy is reciprocal – users are more inclined to share their feelings after the bot has shared its own (Section 5.2). Going forward, we should continue to take seriously the dangers of speaking inappropriately, but keep in mind the cost – to engagement and to intimacy – of not engaging in difficult topics. Initiative As part of our goal to support user initiative, we focused on asking users questions to find out which topics interested them. However, this puts pressure on the user to think of a response, especially given the time constraints of Alexa devices. Thus we found that our attempts to let the user take more initiative unfortunately led to decision fatigue. Separately, our ability to support user initiative was limited by our ability to answer followup questions, and to correctly understand long or unexpected user utterances. On balance, we found that asking the user open-ended questions about interesting topics was a good strategy – easier to handle than spontaneous user questions, and less pressuring than asking users to name topics. We see an opportunity for future work to build systems which listen more to the user’s knowledge, rather than only providing knowledge. 18 # Acknowledgments Thank you to Anna Goldie for her advice and guidance to the team. Abigail See’s work was supported by an unrestricted gift from Google LLC. We thank Amazon.com, Inc. for a grant partially supporting the work of the rest of the team. # References Daniel G. Bobrow, Ronald M. Kaplan, Martin Kay, Donald A. Norman, Henry Thompson, and Terry Winograd. 1977. Gus, a frame-driven dialog system. Artificial Intelligence, 8(2):155 – 173. Sheryl Brahnam. 2005. Strategies for handling customer abuse of ECAs. pages 62–67. Chun-Yen Chen, Dian Yu, Weiming Wen, Yi Mang Yang, Jiaping Zhang, Mingyang Zhou, Kevin Jesse, Austin Chau, Antara Bhowmick, Shreenath Iyer, et al. 2018. Gunrock: Building a human-like social bot by leveraging large scale real user data. Alexa Prize Proceedings. Hyojin Chin, Lebogang Wame Molefi, and Mun Yong Yi. 2020. Empathy is all you need: How a conversational agent should respond to verbal abuse. In Proceedings of the 2020 CHI Conference on Human Factors in Computing Systems, pages 1–13. Amanda Cercas Curry, Ioannis Papaioannou, Alessandro Suglia, Shubham Agarwal, Igor Shalyminov, Xinnuo Xu, Ondrej Dusek, Arash Eshghi, Ioannis Konstas, Verena Rieser, et al. 2018. Alana v2: Entertaining and informative open-domain social dialogue using ontologies and entity linking. Alexa Prize Proceedings. Amanda Cercas Curry and Verena Rieser. 2018. #MeToo Alexa: How conversational systems respond to sexual harassment. In Proceedings of the Second ACL Workshop on Ethics in Natural Language Processing, pages 7–14. Amanda Cercas Curry and Verena Rieser. 2019. A crowd-based evaluation of abuse response strategies in conversational agents. In 20th Annual Meeting of the Special Interest Group on Discourse and Dialogue, page 361. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. BERT: pre-training of deep bidirectional transformers for language understanding. CoRR, abs/1810.04805. Emily Dinan, Varvara Logacheva, Valentin Malykh, Alexander Miller, Kurt Shuster, Jack Urbanek, Douwe Kiela, Arthur Szlam, Iulian Serban, Ryan Lowe, Shrimai Prabhumoye, Alan W Black, Alexander Rudnicky, Jason Williams, Joelle Pineau, Mikhail Burtsev, and Jason Weston. 2019. The second conversational intelligence challenge (ConvAI2). ArXiv preprint arXiv:1902.00098. Karthik Gopalakrishnan, Behnam Hedayatnia, Qinglang Chen, Anna Gottardi, Sanjeev Kwatra, Anu Venkatesh, Raefer Gabriel, Dilek Hakkani-Tür, and Amazon Alexa AI. 2019. Topical-chat: Towards knowledge-grounded open-domain conversations. In INTERSPEECH, pages 1891–1895. Matthew Honnibal and Ines Montani. 2017. spaCy 2: Natural language understanding with Bloom embeddings, convolutional neural networks and incremental parsing. To appear. Eric J. Horvitz. 1999. Principles of mixed-initiative user interfaces. In CHI ’99: Proceedings of the SIGCHI conference on Human Factors in Computing Systems, pages 159–166. Robin Jia and Percy Liang. 2017. Adversarial examples for evaluating reading comprehension systems. In Empirical Methods in Natural Language Processing (EMNLP). Dan Jurafsky, Liz Shriberg, and Debra Biasca. 1997. Switchboard SWBD-DAMSL shallow-discourse function annotation coders manual. In Technical Report Draft 13, University of Colorado, Institute of Cognitive Science. Chandra Khatri, Behnam Hedayatnia, Anu Venkatesh, Jeff Nunn, Yi Pan, Qing Liu, Han Song, Anna Gottardi, Sanjeev Kwatra, Sanju Pancholi, et al. 2018. Advancing the state of the art in open domain dialog systems through the Alexa Prize. arXiv preprint arXiv:1812.10757. 19 Weixin Liang, James Zou, and Zhou Yu. 2020. Beyond user self-reported likert scale ratings: A comparison model for automatic dialog evaluation. ArXiv preprint arXiv:2005.10716. Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. 2019. Roberta: A robustly optimized BERT pretraining approach. CoRR, abs/1907.11692. Christopher D. Manning, Mihai Surdeanu, John Bauer, Jenny Finkel, Steven J. Bethard, and David McClosky. 2014. The Stanford CoreNLP natural language processing toolkit. In Association for Computational Linguistics (ACL) System Demonstrations, pages 55–60. David McClosky, Eugene Charniak, and Mark Johnson. 2006. Effective self-training for parsing. In Proceedings of the Human Language Technology Conference of the NAACL, pages 152–159. Jan Pichi, Petr Marek, Jakub Konrád, Martin Matulık, and Jan Šedivy. 2018. Alquist 2.0: Alexa prize socialbot based on sub-dialogue models. Proc. Alexa Prize. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. OpenAI tech report. Pranav Rajpurkar, Robin Jia, and Percy Liang. 2018. Know what you don’t know: Unanswerable questions for squad. CoRR, abs/1806.03822. Hannah Rashkin, Eric Michael Smith, Margaret Li, and Y-Lan Boureau. 2019. Towards empathetic open-domain conversation models: A new benchmark and dataset. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 5370–5381. Chinnadhurai Sankar, Sandeep Subramanian, Christopher Pal, Sarath Chandar, and Yoshua Bengio. 2019. Do neural dialog systems use the conversation history effectively? an empirical study. arXiv preprint arXiv:1906.01603. Skipper Seabold and Josef Perktold. 2010. statsmodels: Econometric and statistical modeling with python. In 9th Python in Science Conference. Abigail See, Stephen Roller, Douwe Kiela, and Jason Weston. 2019. What makes a good conversation? how controllable attributes affect human judgments. In Proceedings of NAACL-HLT, pages 1702– 1723. Andreas Stolcke, Klaus Ries, Noah Coccaro, Elizabeth Shriberg, Rebecca Bates, Daniel Jurafsky, Paul Taylor, Rachel Martin, Carol Van Ess-Dykema, and Marie Meteer. 2000. Dialogue act modeling for automatic tagging and recognition of conversational speech. Computational linguistics, 26(3):339– 373. Anu Venkatesh, Chandra Khatri, Ashwin Ram, Fenfei Guo, Raefer Gabriel, Ashish Nagar, Rohit Prasad, Ming Cheng, Behnam Hedayatnia, Angeliki Metallinou, et al. 2018. On evaluating and comparing open domain dialog systems. arXiv preprint arXiv:1801.03625. Joseph Weizenbaum et al. 1966. Eliza—a computer program for the study of natural language communication between man and machine. Communications of the ACM, 9(1):36–45. Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Clement Delangue, Anthony Moi, Pierric Cistac, Tim Rault, R’emi Louf, Morgan Funtowicz, and Jamie Brew. 2019a. Huggingface’s transformers: State-of-the-art natural language processing. ArXiv, abs/1910.03771. Thomas Wolf, Victor Sanh, Julien Chaumond, and Clement Delangue. 2019b. Transfertransfo: A transfer learning approach for neural network based conversational agents. CoRR, abs/1901.08149. Dian Yu, Michelle Cohn, Yi Mang Yang, Chun-Yen Chen, Weiming Wen, Jiaping Zhang, Mingyang Zhou, Kevin Jesse, Austin Chau, Antara Bhowmick, Shreenath Iyer, Giritheja Sreenivasulu, Sam Davidson, Ashwin Bhandare, and Zhou Yu. 2019. Gunrock: A social bot for complex and engaging long conversations. ArXiv preprint arXiv:1910.03042. Dian Yu and Zhou Yu. 2019. Midas: A dialog act annotation scheme for open domain human machine spoken conversations. ArXiv preprint arXiv:1908.10023. 20 # Appendix # A Additional RGs # A.1 Coronavirus Our bot has been available to users since early December 2019 – thus covering the entire period of the COVID-19 pandemic so far. As the pandemic progressed, users requested to talk about the pandemic more and more, and showed more interest in discussing home life rather than outside activites. We created the Coronavirus RG to meet users’ expectations that our bot should be fully aware of the unfolding situation, on both an informational and emotional level. The RG is activated when the user mentions or requests to talk about the Coronavirus. To be mindful of the stress that the pandemic has placed on many people, we never initiate the topic ourselves. We then give a comforting message acknowledging the emotional effect of the pandemic, and give the user the option to hear up to 4 news updates. After that, we ask an uplifting open-ended question, and handle the user’s response by generating a response from our GPT-2 model (Section 5.2). We then perform a scripted transition to the Movies RG. For example after we’ve read out a news headline: User: No thank you. I’m exhausted from listening to the news all the time. Bot: No problem. I know this situation has been very stressful for many people; I’ve read online that it can be helpful to remind ourselves of small, good things that have happened to us lately. What’s something nice that’s happened to you in April? User: Well it was my birthday! Bot: That’s great. Did you have fun? . . . # A.2 News The News RG provides the user with news stories that interest them, and discusses them. We set up a cron job to query the Washington Post API24 and scrape several news-based subreddits25 every day, and place the data in an ElasticSearch index. When the user asks to talk about news, the News RG asks the user for a topic (e.g., Joe Biden), if it wasn’t already supplied. The RG then queries the ElasticSearch index for news stories with the desired topic in the headline, selects the most recent one, reads out the headline to the user, and asks if they’d like to hear more. If accepted, we read out the first three sentences of the article. Our original goal was to allow the user to ask follow-on questions about the article, and to answer them with a Neural Question Answering model. We hoped this would help realize our design goals of conversational phrasing and enabling user initiative (Section 1). To begin this process, the News RG would invite the user to ask questions. We then used the SpaCy coreference resolution module (Honnibal and Montani, 2017) to decontextualize the user’s question with respect to the last two utterances from the News RG. For example, how many votes did he win? might be transformed to how many votes did Joe Biden win? The decontextualized question, along with the entire news article, was then sent to a BERT-Large model (Devlin et al., 2018) trained on the Stanford Question Answering 2.0 dataset (Rajpurkar et al., 2018) by HuggingFace.26 The model would output either a span in the article, or ‘no-answer’ – meaning the question cannot be answered by the provided article.27 Unfortunately, in our internal testing, we found that this system had several substantial problems. First, errors in the coreference module were common, and would cascade to the QA module. Second, we found that users asked a very different distribution of questions, compared to the SQuAD training questions. For example, users were likely to ask more open-ended or causal questions (e.g., what 24An API call to scrape Washington Post news articles provided by Amazon Alexa. 25/r/News, /r/Sports, /r/Politics, /r/Futurology, /r/Science, /r/Technology, /r/WorldNews 26https://github.com/huggingface/transformers 27Since the article was often much larger than the maximum context size for BERT, we ran the model on chunks. Within each chunk, we discarded spans which were ranked lower than ‘no-answer’, then merged the answers and re-ranked by confidence of the predictions. 21 happened next?, why did they do that?). These are difficult for off-the-shelf QA models, which tend to excel in answering factoid-style questions. Third, users were likely to ask questions whose answers are not present in the news article. Though our model was trained on SQuAD 2.0 (which contains unanswerable questions), it would often choose an irrelevant answer that type-checks with the question, as Jia and Liang (2017) have also reported. Even when the QA model correctly classified unanswerable questions, we would have needed to build a substantial open-domain question answering system to handle these questions. Overall, these problems made our system a poor and unreliable user experience; requiring more time and effort to fix than we had available. # A.3 Other RGs Launch Handles the first few turns of the conversation (introducing the bot and learning the user’s name). An example can be seen in Table 1. Acknowledgment When the user changes topic to a new entity, this RG uses the entity’s member- ship in certain Wikidata categories to select a one-turn scripted acknowledgment (e.g. Oh yeah, I read ENTITY last year - I couldn’t put it down! if the entity is a book). This RG aims to give a natural and conversational acknowledgment that a new topic has been raised, before handing over to another RG (e.g. Wiki/Opinion/News) to discuss the entity in more depth. Alexa Commands Users often try to issue non-socialbot commands (such as playing music or adjusting smart home devices) to our socialbot. This RG detects such commands, informs the user that they’re talking to a socialbot, and reminds them how they can exit. Closing Confirmation Our bot stops the conversation when the user issues a command like stop or exit. However, users indicate a possible desire to exit through many other more ambiguous phrases (e.g., do you just keep talking, what’s happening). This RG detects such cases using the closing dialogue act label (Section 4.2) and regex templates, asks the user if they’d like to exit, and stops the conversation if so. Complaint Provides an appropriate response when a user complaint is detected. This RG uses the Dialogue Act classifier’s complaint label to detect generic complaints, and regular expressions to detect misheard complaints (the user saying that Alexa misheard them), clarification complaints (the user saying that Alexa is not being clear), repetition complaints (the user saying that Alexa is repeating itself), and privacy complaints (the user saying that they don’t want to share information). We wrote different responses for each type of complaint, to reflect understanding of the user’s concerns. Fallback Always provides a response (Sorry, I’m not sure how to answer that) or prompt (So, what are you interested in?) to be used when no other RG provides one. One-Turn Scripted Responses Provides handwritten responses to common user utterances (e.g. help, chat with me, hello) that can be handled in a single turn. Red Question Detects if the user asks our bot a ‘red question’ – i.e., a question we are not permitted to answer, such as medical, legal, or financial advice – and informs the user that we cannot answer. To recognize these questions, we trained a multinomial logistic regression model on bag-of-words features, using data from the /r/AskDoctor, /r/financial_advice, and /r/LegalAdvice subreddits. # B Tooling and Processes # B.1 Dashboard We built a browser-based dashboard to provide ourselves with easy readable access to conversations and the associated metadata. The landing page shows aggregate rating statistics broken down by date and code version. The dashboard can filter conversations based on metadata such as number of turns, ratings, entities and RGs used. For each conversation, the dashboard displays important turn-level attributes, such as latency, entities, annotations, state information, RG results, and logs. It can provide a link pointing to a specific turn, which is very useful for discussions and issue tracking. The dashboard can rerun the conversation with the current version of our bot, to quickly test if our local changes fixed the problem. Aside from displaying conversations, the dashboard also has tabs to track errors and latencies, divided by severity level. Easy accessibility and visibility of errors made us more aware and likely to fix these errors quickly. 22 Sersionid__ smznlecho-sp.sesen o06esose-4c83-4063-btn9-717230280882 ‘sua metyubtar womans { og ] tatancen CComversationid Timestamp 7070-08-750525:34+00000 DEBUG Funeton version LATEST] os {LAUNCH, MOVES, NEUREL_CHAT, “OPMVON, I, None) nt AEST Tum tatenax = Gas ‘Wales sto mest ou near ced chat wih you eay Hows your dey gong ster cata Figure 10: Screenshot of an example conversation (not with a real customer) in the dashboard. The tags next to each utterance are annotations from the bot. The background color of the utterance is the latency of that specific turn (white being normal and orange being slow). The pane on the right shows the logs for the turn. # B.2 Processes Code Review We realized early on that maintaining high code quality is important for maintain- ability and extensibility. We set up a circular code review process to ensure that any code we write is understandable by another team member and adheres to certain quality standards. Integration Tests We also instituted integration tests, to ensure that our bot maintains certain core functionality. We often found that some changes we made in one part of the bot had unexpected and damaging effects in another part of the bot; integration tests helped to catch these issues. Canary Testing We had two versions of our bot – mainline, which handled real customers, and dev, which we used for developing new features. At first, new dev versions were solely tested by team members, before being pushed to mainline. However, especially as the complexity of the bot grew, this method became insufficient to identify problems in new dev versions – meaning that bugs were being discovered in mainline. We set up a canary testing framework, which directs a controllable percentage (typically 10%-50%) of customer traffic to dev. This was very useful in allowing us to tentatively test out new features with larger numbers of people, before deploying to all customers, thus protecting our ratings. UX Officer Each week, we have a dedicated UX officer, whose primary responsibility is to monitor the conversations, identify problems, and get a sense of the strengths and weaknesses of the current system. This person is also responsible for alerting other team members to things that need to be fixed, and communciating their overall findings to the rest of the team at the weekly meeting. The role rotates every week so every team member has a chance to see the bot in action, and stay in touch with the overall user experience. Sprint Planning and Issue Tracking We use Jira to track issues to be fixed – each is assigned to the person in charge of the relevant component. We have a weekly sprint planning meeting where we prioritize the most important things to work on over the next week, and use Jira to track the sprint. 23 # C Dialogue Act Classifier # C.1 Modifications to Label Space We modified this schema to better fit the needs of our bot, adopting 19 out of 23 dialogue act labels from MIDAS paper, and creating 5 new labels: correction, clarification, uncertain, non-compliant, and personal question to support UX-enhancement features such as the ability to respond to clarifiying questions. We dropped the labels apology, apology-response, other, and thanks since there were very few (n ≤ 80) examples of them in the original dataset and we rarely observed these dialogue acts in our bot. # C.2 Labeling Procedure To create our gold-labeled dataset from our bot, we first determined which classes we most wanted to improve, based on per-class F1-Score for the baseline model and the new features we wanted to build. For example, since we wanted to improve our complaint handling, we prioritized this category. Next, we ran the baseline model on data from our bot to collect pseudo-labels. We randomly sampled 300 examples per label and then annotated whether the true label matched the predicted label. If not, we annotated what the correct label was. Using the pseudo-labels as a starting point increased efficiency, since the binary decision of "correct or incorrect" is much easier than the choice between 24 labels, and this method significantly reduced the number of non-binary decisions necessary. It also improved balance over classes, since it gave us greater control over the classes in the sample, and allowed us to prioritize certain categories. The result of training with gold-labeled examples is reported in Table 4. # D Emotion classifier and analysis In order to understand and analyze users’ emotions, we finetuned a RoBERTa model (Liu et al., 2019; Wolf et al., 2019a) on the EmpatheticDialogues dataset (Rashkin et al., 2019), which contains 24,850 examples broken into an 80-10-10 train-dev-test split. In particular, our training and test data consisted of the first utterance from each dialogue (as it is the only one with a label), along with its label (one of 32 fine-grained emotions, listed in Figure 11). The RoBERTa model achieves a top-1 accuracy of 61.5% and an F1-score of 0.596. However, many of the misclassifications are due to the model choosing a label very similar to the gold label. For example, in the confusion matrix in Figure 11, we see that angry is often misclassified as furious, and terrified as afraid, among others. In contrast, the top-5 accuracy is 92%. One difficulty in applying this classifier to our user utterances is domain shift. The EmpatheticDia- logues training utterances all describe a strongly emotional personal situation in complete written sentences, in a self-contained way (i.e., with no preceding context) – for example, A recent job interview that I had made me feel very anxious because I felt like I didn’t come prepared. By contrast our user utterances are spoken, typically not complete sentences, require conversational context to understand, and encompass many different dialogue functions (such as giving commands, answering questions, choosing topics, greeting and closing, etc.). Importantly, most utterances are emotionally neutral. As the classifier has no ‘neutral’ label, it assigns spurious emotions to these neutral utterances. # D.1 Relationship between Rating and User Emotion To understand users’ emotions and how they relate to our bot’s performance, we replicated our experiment for dialogue act labels by applying a regression analysis, to the emotion classifier labels and the ultimate rating of each conversation. Before performing this analysis, we removed all one-word utterances, since we assumed that these would not contain any emotion, and 66 common utterances that accounted for 40% of responses (e.g. yes and no), assuming that they were also neutral. Figure 6 shows that, as we would expect, positive emotions have the largest positive coefficients and negative emotions have the largest negative ones. A possible explanation for the anomalies (e.g. "terrified" having a relatively large positive coefficient) is that the emotion classifier strongly associates certain entities with emotions and struggles to recognize when these entities are used in 24 Emotions Key jealous 16 sentimental o = - 0 wy 100 1| impressed 47 sad 7 © 2| grateful 48 lonely © 80 3} proud 19. devastated e 4| confident 20. furious 2 5 | prepared 21 angry _ 60 = 6 | content 22 disgusted 2 7 | joyful 23 annoyed 2 e 40 8| excited 24 disappointed S 9| surprised 25 ashamed ~ 10| anticipating 26 embarrassed x g 20 41 hopeful 27 guilty g 42 | faithful 28 anxious 8 13 | trusting 29. apprehensive ’ y y — y y 0 0 2 4 6 8 10 12 14 16 18 0 2 4 % BH 14| caring 30 afraid 45 | nostalgic 31. terrified Figure 11: Confusion matrix for RoBERTa emotion classifier. different contexts. For example, it associates "tiger" with "terrified", even when "tiger" is in a positive context such as "I like tigers." # E Offensive User Experiment Details # E.1 Offense Type Detection To determine the offense type, we hand-labeled 500 most common offensive utterances, which accounted for 53% of all the offensive utterances we collected to the date. We used 6 categories: sexual, insult, criticism, inappropriate topic, bodily harm and error. To classify the user utterance into one of these categories, we built regular expressions checking if the given user utterance contains one of the hand-labeled examples for an offense type. We then used the offense type to contextualize our COUNTER+PROMPT and EMPATHETIC+PROMPT responses. # E.2 Response Strategy Configurations This section gives a detailed description of the configurations used in the Offensive User experiments (Section 5.9). 1. WHY: We ask the user why they made the offensive utterance (and this forms the entire bot utterance for the turn). The Offensive User RG responds with OK to whatever the user says next, then hands over to another RG to supply a prompt. For example: Bot: Why did you say that?, User: because you weren’t understanding me, Bot: OK. So, who’s your favorite musician? 2. WHY+NAME: Same as WHY, but we append the user’s name to the end of the bot utterance. For example: Why did you say that, Peter? 3. AVOIDANCE: The bot politely avoids talking about the offensive topic, e.g. I’d rather not talk about that. This forms the entire utterance for the turn; the bot does not give any prompt to steer the conversation in a different direction. 4. AVOIDANCE+NAME: Same as AVOIDANCE, but we append the user’s name to the bot utterance. For example: I’d rather not talk about that Peter. 5. AVOIDANCE+PROMPT: Same as AVOIDANCE, but we also give a prompt to change the topic. For example: I’d rather not talk about that. So, who’s your favorite musician? 25 6. AVOIDANCE+NAME+PROMPT: Same as AVOIDANCE+NAME, but append a prompt to the end of the utterance. For example: I’d rather not talk about that, Peter. So, who’s your favorite musician? 7. COUNTER+PROMPT: Strategy suggested by Brahnam (2005) and evaluated by Chin et al. (2020). In our interpretation of the strategy, we point out the inappropriate nature of the user utterance to the user, and attempt to move on to a different topic. For example, That is a very suggestive thing to say. I don’t think we should be talking about that. Let’s move on. So, who’s your favorite musician? 8. EMPATHETIC+PROMPT: Strategy suggested by Chin et al. (2020) as the most appropriate strategy. In our interpretation of the strategy, we empathize with the user’s desire to talk about inappropriate topics, and attempt to move on to a different topic. For example, If I could talk about it I would, but I really couldn’t. Sorry to disappoint. So, who’s your favorite musician? For COUNTER+PROMPT and EMPATHETIC+PROMPT, unlike Brahnam (2005) and Chin et al. (2020), we handwrote responses tailored for the type of the user offense (e.g. sexual, curse, etc.) Note that WHY and AVOIDANCE cannot be combined because they are contradictory, and WHY and CHANGE cannot be combined because we cannot ask two questions in one turn. # F Opinion Agreement Policy Details Here we will show demonstrations of the 3 different Opinion Policies. All the demonstrations below are generated by researchers and are not actual user conversations. # F.1 ALWAYS_AGREE Policy We begin by asking the user their opinion on the entity. Then, we agree with the user on their sentiment on the entity and share our reason, and ask the user their reason for liking/disliking the entity. After that, we propose another reason for liking/disliking the entity, and ask whether the user agrees with our reason or not. Finally, we switch to a related entity and repeat the same steps as described before. A demonstration of the policy is shown below. User: let’s talk about cats Bot: Ok! Do you like cats? User: cats are my favorite Bot: Sounds like you like cats. Me too! I feel like cats are so fluffy. What about you? User: i like cats because they are very independent Bot: That’s so true. That reminds me of another reason I love cats. I feel like they treat you as an equal. Do you agree? User: i totally agree Bot: What about dogs? Do you like dogs? User: yes Bot: Me too! You know, I think the reason I’m a fan of dogs is because they love you back no matter what. What do you think? User: yeah i feel the same way Bot: Totally. I also like dogs because of how nifty they are. Do you feel the same way? User: Yeah you are right they are pretty nifty. Bot: Thanks for sharing! It’s nice to know your likes and dislikes. Do you want to know more about dogs? # F.2 LISTEN_FIRST_DISAGREE Policy We initially ask the user for their opinion and reason (i.e. "What do you think about cats?" followed by "Why do you like cats?"), then we disagree with the user by giving our opinion and reason. After that, we switch to a related entity and agree with the user on their sentiment on the new entity. A demonstration of the policy is shown below. 26 User: let’s talk about cats Bot: Ok! Do you like cats? User: cats are my favorite Bot: What’s your favorite thing about cats? User: i like cats because they are very independent Bot: That make sense. I have to be honest though, I’m not a big fan of cats actually. I feel like they don’t respect my personal space. Can we agree on that? User: yeah i guess you are right on that one Bot: What about dogs? Do you like dogs? User: yes Bot: Me too! You know, I think the reason I’m a fan of dogs is because they love you back no matter what. What do you think? User: yeah i feel the same way Bot: Totally. I also like dogs because of how nifty they are. Do you feel the same way? User: Yeah you are right they are pretty nifty. Bot: Thanks for sharing! It’s nice to know your likes and dislikes. Do you want to know more about dogs? # F.3 CONVINCED_AGREE Policy This is a stronger version of the previous policy in which we immediately disagree with the user and give our opinion and reason (i.e. "What do you think about cats?" followed by "That’s good to know, but I don’t quite get the appeal of cats. I feel like they are too independent. But I want to hear why you like cats"). After receiving an answer from the user, we agree with the user and appear convinced. After that, we switch to a related entity and agree with the user on their sentiment on the new entity. A demonstration of the policy is shown below. User: let’s talk about cats Bot: Ok! Do you like cats? User: cats are my favorite Bot: Glad to meet a fan of cats! I have to be honest though, I’m not a big fan of cats actually. I feel like they don’t respect my personal space. But I’m interested to hear why you like cats? User: i don’t agree i like that about cats because that’s how they show their love Bot: That make sense. Now that I think about it, there are a few things I like about cats. For example, they are very independent. What do you think? User: yeah that’s right. Bot: What about dogs? Do you like dogs? User: yes Bot: Me too! You know, I think the reason I’m a fan of dogs is because they love you back no matter what. What do you think? User: yeah i feel the same way Bot: Totally. I also like dogs because of how nifty they are. Do you feel the same way? User: Yeah you are right they are pretty nifty. Bot: Thanks for sharing! It’s nice to know your likes and dislikes. Do you want to know more about dogs? 27
Title: Multi-task Deep Reinforcement Learning with PopArt: Summary: The reinforcement learning community has made great strides in designing algorithms capable of exceeding human performance on specific tasks. These algorithms are mostly trained one task at the time, each new task requiring to train a brand new agent instance. This means the learning algorithm is general, but each solution is not; each agent can only solve the one task it was trained on. In this work, we study the problem of learning to master not one but multiple sequential-decision tasks at once. A general issue in multi-task learning is that a balance must be found between the needs of multiple tasks competing for the limited resources of a single learning system. Many learning algorithms can get distracted by certain tasks in the set of tasks to solve. Such tasks appear more salient to the learning process, for instance because of the density or magnitude of the in-task rewards. This causes the algorithm to focus on those salient tasks at the expense of generality. We propose to automatically adapt the contribution of each task to the agent's updates, so that all tasks have a similar impact on the learning dynamics. This resulted in state of the art performance on learning to play all games in a set of 57 diverse Atari games. Excitingly, our method learned a single trained policy - with a single set of weights - that exceeds median human performance. To our knowledge, this was the first time a single agent surpassed human-level performance on this multi-task domain. The same approach also demonstrated state of the art performance on a set of 30 tasks in the 3D reinforcement learning platform DeepMind Lab. # Multi-task Deep Reinforcement Learning with PopArt # Matteo Hessel # Hubert Soyer # Lasse Espeholt # Wojciech Czarnecki # Simon Schmitt # Hado van Hasselt # Abstract The reinforcement learning community has made great strides in designing algorithms capable of exceeding human performance on specific tasks. These algorithms are mostly trained one task at the time, each new task requiring to train a brand new agent instance. This means the learning algo- rithm is general, but each solution is not; each agent can only solve the one task it was trained on. In this work, we study the problem of learning to master not one but multiple sequential- decision tasks at once. A general issue in multi-task learning is that a balance must be found between the needs of multiple tasks competing for the limited resources of a single learn- ing system. Many learning algorithms can get distracted by certain tasks in the set of tasks to solve. Such tasks appear more salient to the learning process, for instance because of the density or magnitude of the in-task rewards. This causes the algorithm to focus on those salient tasks at the expense of generality. We propose to automatically adapt the contribu- tion of each task to the agent’s updates, so that all tasks have a similar impact on the learning dynamics. This resulted in state of the art performance on learning to play all games in a set of 57 diverse Atari games. Excitingly, our method learned a single trained policy - with a single set of weights - that exceeds median human performance. To our knowledge, this was the first time a single agent surpassed human-level per- formance on this multi-task domain. The same approach also demonstrated state of the art performance on a set of 30 tasks in the 3D reinforcement learning platform DeepMind Lab. Introduction In recent years, the field of deep reinforcement learning (RL) has enjoyed many successes. Deep RL agents have been ap- plied to board games such as Go (Silver et al. 2016) and chess (Silver et al. 2017), continuous control (Lillicrap et al. 2016; Duan et al. 2016), classic video-games such as Atari (Mnih et al. 2015; Hessel et al. 2018; Gruslys et al. 2018; Schulman et al. 2015; Schulman et al. 2017; Bacon, Harb, and Precup 2017), and 3D first person environments (Mnih et al. 2016; Jaderberg et al. 2016). While the results are im- pressive, they were achieved on one task at the time, each task requiring to train a new agent instance from scratch. Multi-task and transfer learning remain important open problems in deep RL. There are at least four different strains Copyright © 2019, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. of multi-task reinforcement learning that have been explored in the literature: off-policy learning of many predictions about the same stream of experience (Schmidhuber 1990; Sutton et al. 2011; Jaderberg et al. 2016), continual learning in a sequence of tasks (Ring 1994; Thrun 1996; Thrun 2012; Rusu et al. 2016), distillation of task-specific experts into a single shared model (Parisotto, Ba, and Salakhutdinov 2015; Rusu et al. 2015; Schmitt et al. 2018; Teh et al. 2017), and parallel learning of multiple tasks at once (Sharma and Ravindran 2017; Caruana 1998). We will focus on the latter. Parallel multi-task learning has recently achieved remark- able success in enabling a single system to learn a large number of diverse tasks. The Importance Weighted Actor- Learner Architecture, henceforth IMPALA (Espeholt et al. 2018), achieved a 59.7% median human normalised score across 57 Atari games, and a 49.4% mean human normalised score across 30 DeepMind Lab levels. These results are state of the art for multi-task RL, but they are far from the human- level performance demonstrated by deep RL agents on the same domains, when trained on each task individually. Part of why multi-task learning is much harder than sin- gle task learning is that a balance must be found between the needs of multiple tasks, that compete for the limited resources of a single learning system (for instance, for its limited representation capacity). We observed that the naive transposition of common RL algorithms to the multi-task setting may not perform well in this respect. More specif- ically, the saliency of a task for the agent increases with the scale of the returns observed in that task, and these may differ arbitrarily across tasks. This affects value-based algo- rithms such as Q-learning (Watkins 1989), as well as policy- based algorithms such as REINFORCE (Williams 1992). The problem of scaling individual rewards appropriately is not novel, and has often been addressed through re- ward clipping (Mnih et al. 2015). This heuristic changes the agent’s objective, e.g., if all rewards are non-negative the algorithm optimises frequency of rewards rather than their cumulative sum. If the two objectives are sufficiently well aligned, clipping can be effective. However, the scale of re- turns also depends on the rewards’ sparsity. This implies that, even with reward clipping, in a multi-task setting the magnitude of updates can still differ significantly between tasks, causing some tasks to have a larger impact on the learning dynamics than other equally important ones. Note that both the sparsity and the magnitude of rewards collected in an environment are inherently non-stationary, because the agent is learning to actively maximise the total amount of rewards it can collect. These non-stationary learn- ing dynamics make it impossible to normalise the learning updates a priori, even if we would be willing to pour signif- icant domain knowledge into the design of the algorithm. To summarise, in IMPALA the magnitude of updates re- sulting from experience gathered in each environment de- pends on: 1) the scale of rewards, 2) the sparsity of rewards, 3) the competence of the agent. In this paper we use PopArt normalisation (van Hasselt et al. 2016) to derive an actor- critic update invariant to these factors, enabling large per- formance improvements in parallel multi-task agents. We demonstrated this on the Atari-57 benchmark, where a sin- gle agent achieved a median normalised score of 110% and on DmLab-30, where it achieved a mean score of 72.8%. Background Reinforcement learning (RL) is a framework for learning and decision-making under uncertainty {2018}. A learning system - the agent - must learn to inter- act with the environment it is embedded in, so as to max- imise a scalar reward signal. The RL problem is often for- malised as a Markov decision process (Bellman 1957): a tuple (S,A,p, 7), where S, A are finite sets of states and actions, p denotes the dynamics, such that p(r, s’ | s,a) is the probability of observing reward r and state s’ when ex- ecuting action a in state s, and y € [0,1] discounts future rewards. The policy maps states s € S to probability dis- tributions over actions 7(A|S = s), thus specifying the be- haviour of the agent. The return G; = Ri4i+yRizo+... is the 7-discounted sum of rewards collected by an agent from state S, onward under policy 7. We define action values and state values as q"(s,a) = E,[G, | Sy = s, Ay = a] and v"(s) = E,[G, | S; = s], respectively. The agent’s objec- tive is to find a policy to maximise such values. In multi-task reinforcement learning, a single agent must learn to master N different environments T = {Di = (Si, Ai, pi, γ)}N i=1, each with its own distinct dynamics (Brunskill and Li 2013). Particularly interesting is the case in which the action space and transition dynamics are at least partially shared. For instance, the environments might follow the same physical rules, while the set of intercon- nected states and obtainable rewards differ. We may for- malise this as a single larger MDP, whose state space is S = {{(sj, i)}sj ∈Si}N i=1. The task index i may be latent, or may be exposed to the agent’s policy. In this paper, we use the task index at training time, for the value estimates used to compute the policy updates, but not at testing time: our algorithm will return a single general policy π(A|S) which is only function of the individual environment’s state S and not conditioned directly on task index i. This is more challenging than the standard multi-task learning setup, which typically allows conditioning the model on the task index even at evaluation (Romera-Paredes et al. 2013; Collobert and Weston 2008), because our agents will need to infer what task to solve purely from the stream of raw observations and/or early rewards in the episode. Actor-critic In our experiments, we use an actor-critic algorithm to learn a policy πη(A|S) and a value estimate vθ(s), which are both outputs of a deep neural network. We update the agent’s policy by using REINFORCE-style stochastic gradi- ent (Gt − vθ(St))∇η log π(At|St) (Williams 1992), where vθ(St) is used as a baseline to reduce variance. In addition we use a multi-step return Gv t that bootstraps on the value estimates after a limited number of transitions, both to re- duce variance further and to allow us to update the policy before Gt fully resolves at the end of an episode. The value function vθ(S) is instead updated to minimise the squared loss with respect to the (truncated and bootstrapped) return: ∆θ ∝ −∇θ(Gv t −vθ(St))2 = (Gv t −vθ(St))∇θvθ(St) (1) # ∆η ∝ (Gπ t and Gπ t − vθ(St))∇η log(πη(At|St)) , (2) where Gv t are stochastic estimates of vπ(St) and qπ(St, At), respectively. Note how both updates depend lin- early on the scale of returns, which, as previously argued, de- pend on scale/sparsity of rewards, and agent’s competence. Efficient multi-task learning in simulation We use the IMPALA agent architecture (Espeholt et al. 2018), proposed for reinforcement learning in simulated en- vironments. In IMPALA the agent is distributed across mul- tiple threads, processes or machines. Several actors run on CPU generating rollouts of experience, consisting of a fixed number of interactions (100 in our experiments) with their own copy of the environment, and then enqueue the roll- outs in a shared queue. Actors receive the latest copy of the network’s parameters from the learner before each rollout. A single GPU learner processes rollouts from all actors, in batches, and updates a deep network. The network is a deep convolutional ResNet (He et al. 2015), followed by a LSTM recurrent layer (Hochreiter and Schmidhuber 1997). Policy and values are all linear functions of the LSTM’s output. Despite the large network used for estimating policy πη and values vθ, the decoupled nature of the agent enables to process data very efficiently: in the order of hundreds of thousands frames per second (Espeholt et al. 2018). The setup easily supports the multi-task setting by simply assign- ing different environments to each of the actors and then run- ning the single policy π(S|A) on each of them. The data in the queue can also be easily labelled with the task id, if use- ful at training time. Note that an efficient implementation of IMPALA is available open-source 1, and that, while we use this agent for our experiments, our approach can be applied to other data parallel multi-task agents (e.g. A3C). Off-policy corrections Because we use a distributed queue-based learning setup, the data consumed by the learning algorithm might be slightly off-policy, as the policy parameters change between acting and learning. We can use importance sampling corrections ρt = π(At|St)/µ(At|St) to compensate for this (Precup, 1www.github.com/deepmind/scalable agent Sutton, and Singh 2000). In particular, we can write the n- ie me as Gp = Rigi + Riga +... + Y"0(Stin) = y+ yee Tk-t5., where 6) = Rigi + yu(Sr41) — ots ), and then apply appropriate importance sampling cor- ae to each error term to get G, = S)+ t yk- me i. 1 Pi )or- This i is unbiased, but has ae variance. To reduce variance, we can further clip most of the importance-sampling ratios, e.g., as c, = min(1, pz). This leads to the v-trace return (Espeholt et al. 2018) ttn-1 k arm nse (Hea 0 k=t ist k=t A very similar target was proposed for the ABQ(ζ) algo- rithm (Mahmood 2017), where the product ρtλt was consid- ered and then the trace parameter λt was chosen to be adap- tive to lead to exactly the same behaviour that ct = ρtλt = min(1, ρt). This shows that this form of clipping does not impair the validity of the off-policy corrections, in the same sense that bootstrapping in general does not change the se- mantics of a return. The returns used by the value and policy updates defined in Equation 1 and 2 are then Gv This is the same algorithm as used by Espeholt et al. (2018) in the experiments on the IMPALA architecture. Adaptive normalisation In this section we use PopArt normalisation (van Hasselt et al. 2016), which was introduced for value-based RL, to de- rive a scale invariant algorithm for actor-critic agents. For simplicity, we first consider the single-task setting, then we extend it to the multi-task setting (the focus of this work). Scale invariant updates In order to normalise both baseline and policy gradient up- dates, we first parameterise the value estimate Vp,0,0(S) as the linear transformation of a suitably normalised value pre- diction ng(S). We further assume that the normalised value prediction is itself the output of a linear function, for in- stance the last fully connected layer of a deep neural net: Up,o0(8) =o + No(s) += a+ (w! fo w,s}(s) +b) +H. $< —S— Up,o0(8) =o + No(s) += a+ (w! fo w,s}(s) +b) +H. $< —S— = no(s) (5) As proposed by van Hasselt et al., µ and σ can be updated so as to track mean and standard deviation of the values. First and second moments of can be estimated online as µt = (1−β)µt−1+βGv t , νt = (1−β)νt−1+β(Gv t )2, ( and then used to derive the estimated standard deviation as o1 = /% — p12. Note that the fixed decay rate 3 determines the horizon used to compute the statistics. We can then use the normalised value estimate mg (.S) and the statistics 4. and o to normalise the actor-critic loss, both in its value and pol- icy component; this results in the scale-invariant updates: ∆θ ∝ t − µ σ − nθ(St) ∇θnθ(St) , (7) An x (= f- no(5)) Vlog m (Alsi). (8) If we optimise the new objective naively, we are at risk of making the problem harder: the normalised targets for val- ues are non-stationary, since they depend on statistics 4 and o. The PopArt normalisation algorithm prevents this, by up- dating the last layer of the normalised value network to pre- serve unnormalised value estimates v,,,,9, under any change in the statistics pp + yp’ anda > o’: ww’ Cw, i ob+p—p a 3 . (9) This extends PopArt’s scale-invariant updates to the actor- critic setting, and can help to make tuning hyperparameters easier, but it is not sufficient to tackle the challenging multi- task RL setting that we are interested in this paper. For this, a single pair of normalisation statistics is not sufficient. Scale invariant updates for multi-task learning Let Di be an environment in some finite set T = {Di}N i=1, and let π(S|A) be a task-agnostic policy, that takes a state S from any of the environments Di, and maps it to a proba- bility distribution onto the shared action space A. Consider now a multi-task value function v(S) with N outputs, one for each task. We can use for v the same parametrisation as in Equation 5, but with vectors of statistics µ, σ ∈ RN , and a vector-valued function nθ(s) = (n1 Vu,0.0(9) = oOne(S)+p = 0O(Wfo\ pw.b}(S)+b) + (10) where W and b denote the parameters of the last fully con- nected layer in ng(s). Given a rollout {5;,,, Ax, Rint, generated under task-agnostic policy 7,(A|$) in environ- ment D;, we can adapt the updates in Equation Hlandfi}to provide scale invariant updates also in the multi-task setting: ∆θ ∝ Gv,i t − µi σi − ni θ(St) ∇θni θ(St) , (11) ∆η ∝ Gπ,i t − µi σi − ni θ(St) ∇η log πη(At|St) . (12) Where the targets G·,i t use the value estimates for environ- ment Di for bootstrapping. For each rollout, only the ith head in the value net is updated, while the same policy network is updated irrespectively of the task, using the appropriate rescaling for updates to parameters η. As in the single-task case, when updating the statistics µ and σ we also need to update W and b to preserve unnormalised outputs, y 7, Tibi + hi = BY w,= Swi, b; = ——_,— , i % (13) where wi is the ith row of matrix W, and µi, σi, bi are the ith elements of the corresponding parameter vectors. Note that in all updates only the values, but not the policy, are con- ditioned on the task index, which ensures that the resulting agent can then be run in a fully task agnostic way, since val- ues are only used to reduce the variance of the policy updates at training time but not needed for action selection. Table 1: Summary of results: aggregate scores for IMPALA and PopArt-IMPALA. We report median human normalised score for Atari-57, and mean capped human normalised score for DmLab-30. In Atari, Random and Human refer to whether the trained agent is evaluated with random or human starts. In DmLab-30 the test score includes evaluation on the held-out levels. Atari-57 Atari-57 (unclipped) DmLab-30 Agent Random Human Random Human Train Test IMPALA 59.7% 28.5% 0.3% 1.0% 60.6% 58.4% PopArt-IMPALA 110.7% 101.5% 107.0% 93.7% 73.5% 72.8% # Experiments We evaluated our approach in two challenging multi-task benchmarks, Atari-57 and DmLab-30, based on Atari and DeepMind Lab respectively, and introduced by Espeholt et al. We also consider a new benchmark, consisting of the same games as Atari-57, but with the original unclipped rewards. We demonstrate state of the art performance on all benchmarks. To aggregate scores across many tasks, we normalise the scores on each task based on the scores of a human player and of a random agent on that same task (van Hasselt, Guez, and Silver 2016). All experiments use population-based training (PBT) to tune hyperparameters (Jaderberg et al. 2017). As in Espeholt et al., we report learn- ing curves as function of the number of frames processed by one instance of the tuning population, summed across tasks. levels can also differ visually in non-trivial ways, as they include both natural environments and maze-like lev- els. Two levels (rooms collect good objects and rooms exploit deferred effects) have held out test versions, therefore Table 1 reports both train and test ag- gregate scores. We observed that the original IMPALA agent suffers from an artificial bottleneck in performance, due to the fact that some of the tasks cannot be solved with the ac- tion set available to the agent. As first step, we thus fix this issue by equipping it with a larger action set, resulting in a stronger IMPALA baseline than reported in the original pa- per. We also run multiple independent PBT experiments, to assess the variability of results across multiple replications. # Atari-57 results Domains Atari-57 is a collection of 57 classic Atari 2600 games. The ALE (Bellemare et al. 2013), exposes them as RL envi- ronments. Most prior work has focused on training agents for individual games (Mnih et al. 2015; Hessel et al. 2018; Gruslys et al. 2018; Schulman et al. 2015; Schulman et al. 2017; Bacon, Harb, and Precup 2017). Multi-task learning on this platform has not been as successful due to large num- ber of environments, inconsistent dynamics and very differ- ent reward structure. Prior work on multi-task RL in the ALE has therefore focused on smaller subsets of games (Rusu et al. 2015; Sharma and Ravindran 2017). Atari has a particu- larly diverse reward structure. Consequently, it is a perfect domain to fully assess how well can our agents deal with extreme differences in the scale of returns. Thus, we train all agents both with and without reward clipping, to com- pare performance degradation as returns get more diverse in the unclipped version of the environment. In both cases, at the end of training, we test agents both with random-starts (Mnih et al. 2015) and human-starts (Nair et al. 2015); ag- gregate results are reported in Table 1 accordingly. Figures 1 and 2 show the median human normalised perfor- mance across the entire set of 57 Atari games in the ALE, when training agent with and without reward clipping, re- spectively. The curves are plotted as function of the total number of frames seen by each agent. PopArt-IMPALA (orange line) achieves a median perfor- mance of 110% with reward clipping and a median perfor- mance of 101% in the unclipped version of Atari-57. Re- call that here we are measuring the median performance of a single trained agent across all games, rather than the me- dian over the performance of a set of individually trained agents as it has been more common in the Atari domain. To our knowledge, both agents are the first to surpass median human performance across the entire set of 57 Atari games. The IMPALA agent (blue line) performs much worse. The baseline barely reaches 60% with reward clipping, and the median performance is close to 0% in the unclipped setup. The large decrease in the performance of the baseline IM- PALA agent once clipping is removed is in stark contrast with what we observed for PopArt-IMPALA, that achieved almost the same performance in the two training regimes. DmLab-30 is a collection of 30 visually rich, par- tially observable RL environments (Beattie et al. 2016). This benchmark has strong internal consistency (all lev- els are played with a first person camera in a 3D envi- ronment with consistent dynamics). Howevere, the tasks themselves are quite diverse, and were designed to test dis- tinct skills in RL agents: among these navigation, mem- ory, planning, laser-tagging, and language grounding. The Since the level-specific value predictions used by multi- task PopArt effectively increase the capacity of the net- work, we also ran an additional experiment to disentan- gle the contribution of the increased network capacity from the contribution of the adaptive normalisation. For this pur- pose, we train a second baseline, that uses level specific value predictions, but does not use PopArt to adaptively normalise the learning updates. The experiments show that such MultiHead-IMPALA agent (pink line) actually per- forms slightly worse than the original IMPALA both with Atari-57 (clipped) 120 —— PopArt-IMPALA —— MultiHead-IMPALA 100 —— IMPALA s iS é Median Human Normalised Score s 8 0 2 4 6 8 10 12 Environment Frames Figure 1: Atari-57 (reward clipping). Median human nor- malised score across all Atari levels, as function of the total number of frames seen by the agents across all levels. We compare PopArt-IMPALA to IMPALA and to an additional baseline, MultiHead-IMPALA, that uses task-specific value predictions but no adaptive normalisation. All three agent are trained with the clipped reward scheme. and without clipping, confirming that the performance boost of PopArt-IMPALA is indeed due to the adaptive rescaling. We highlight that in our experiments a single instance of multi-task PopArt-IMPALA has processed the same amount of frames as a collection of 57 expert DQN agents (57 × 200 M = 1.14 × 1010), while achieving better performance. Despite the large CPU requirements, on a cloud service, training multi-task PopArt-IMPALA can also be competi- tive in terms of costs, since it exceeds the performance of a vanilla-DQN in just 2.5 days, with a smaller GPU footprint. Normalisation statistics It is insightful to observe the different normalisation statis- tics across games, and how they adapt during training. Fig- ure 3 (top row) plots the shift µ for a selection of Atari games, in the unclipped training regime. The scale σ is visualised in the same figure by shading the area in the range [µ − σ, µ + σ]. The statistics differ by orders of magnitude across games: in crazy climber the shift ex- ceeds 2500, while in bowling it never goes above 15. The adaptivity of the proposed normalisation emerges clearly in crazy climber and qbert, where the statistics span multiple orders of magnitude during training. The bottom row in Figure 3 shows the corresponding agent’s undis- counted episode return: it follows the same patterns as the statistics (with differences in magnitude due to discounting). Finally note how the statistics can even track the instabilities in the agent’s performance, as in qbert. DmLab-30 results Figure 4 shows, as a function of the total number of frames processed by each agent, the mean human normalised per- formance across all 30 DeepMind Lab levels, where each level’s score is capped at 100% . For all agents, we ran three Atari-57 (unclipped) 8 —— PopArt-IMPALA —— MultiHead-IMPALA — IMPALA y iS 2 2 S 8 é s s s Median Human Normalised Score ° -20 0 2 4 6 8 10 Environment Frames Figure 2: Atari-57 (unclipped): Median human normalised score across all Atari levels, as a function of the total num- ber of frames seen by the agents across all levels. We here compare the same set of agents as in Figure 1, but now all agents are trained without using reward clipping. The ap- proximately flat lines corresponding to the baselines mean no learning at all on at least 50% of the games. breakout crazy_climber qbert seaquest } wv Figure 3: Normalisation statistics: Top: learned statistics, without reward clipping, for four distinct Atari games. The shaded region is [µ−σ, µ+σ]. Bottom: undiscounted returns. independent PBT experiments. In Figure 4 we plot the learn- ing curves for each experiment and, for each agent, fill in the area between best and worse experiment. Compared to the original paper, our IMPALA baseline uses a richer action set, that includes more possible hori- zontal rotations, and vertical rotations (details in Appendix). Fine-grained horizontal control is useful on lasertag levels, while vertical rotations are necessary for a few psychlab levels. Note that this new baseline (solid blue in Figure 4) performs much better than the original IM- PALA agent, which we also train and report for complete- ness (dashed blue). Including PopArt normalisation (in or- ange) on top of our baseline results in largely improved scores. Note how agents achieve clearly separated perfor- mance levels, with the new action set dominating the origi- nal paper’s one, and with PopArt-IMPALA dominating IM- PALA for all three replications of the experiment. 12 DmLab-30 g g 8 Mean Capped Human Normalised Score Ss ly" — PopArt-IMPALA 10 & — IMPALA === IMPALA-original 0 2 4 6 8 10 Environment Frames Figure 4: DmLab-30. Mean capped human normalised score of IMPALA (blue) and PopArt-IMPALA (orange), across the DmLab-30 benchmark as function of the num- ber of frames (summed across all levels). Shaded region is bounded by best and worse run among 3 PBT experiments. For reference, we also plot the performance of IMPALA with the limited action set from the original paper (dashed). # Extensions In this section, we explore the combination of the proposed PopArt-IMPALA agent with pixel control (Jaderberg et al. 2016), to further improve data efficiency, and make train- ing IMPALA-like agents on large multi-task benchmarks cheaper and more practical. Pixel control is an unsuper- vised auxiliary task introduced to help learning good state representations. As shown in Figure 5, the combination of PopArt-IMPALA with pixel control (red line) allows to match the final performance of the vanilla PopArt-IMPALA (orange line) with a fraction of the data (∼ 2B frames). This is on top of the large improvement in data efficiency already provided by PopArt, meaning that the pixel con- trol augmented PopArt-IMPALA needs less than 1/10-th of the data to match our own IMPALA baseline’s performance (and 1/30-th of the frames to match the original published IMPALA). Importantly, since both PopArt and Pixel Con- trol only add a very small computational cost, this improve- ment in data efficiency directly translates in a large reduction of the cost of training IMPALA agents on large multi-task benchmarks. Note, finally, that other orthogonal advances in deep RL could also be combined to further improve perfor- mance, similarly to what was done by Rainbow (Hessel et al. 2018), in the context of value-based reinforcement learning. # Implementation notes We implemented all agents in TensorFlow. For each batch of rollouts processed by the learner, we average the Gv t tar- gets within a rollout, and for each rollout in the batch we perform one online update of PopArt’s normalisation statis- tics with decay β = 3 × 10−4. Note that β didn’t require any tuning. To prevent numerical issues, we clip the scale σ in the range [0.0001, 1e6]. We do not back-propagate gra- dients into µ and σ, exclusively updated as in Equation 6. DmLab-30 80 3 g 8 PopArt-IMPALA@10B 8 Mean Capped Human Normalised Score 8 & 6 —— PopArt-IMPALA — Pixel-PopArt-IMPALA 0 O21 2 4 6 8 10 Environment Frames 109 Figure 5: DmLab-30 (with pixel control). Mean capped hu- man normalised score of PopArt-IMPALA with pixel con- trol (red), across the DmLab-30 benchmark as function of the total number of frames across all tasks. Shaded region is bounded by best and worse run among 3 PBT experiments. Dotted lines mark the point where Pixel-PopArt-IMPALA matches PopArt-IMPALA and the two IMPALA baselines. The weights W of the last layer of the value function are updated according to Equation 13 and 11. Note that we first apply the actor-critic updates (11), then update the statis- tics (6), finally apply output preserving updates (13). For more just-in-time rescaling of updates we can invert this or- der, but this wasn’t necessary. As anticipated, in all experi- ments we used population-based training (PBT) to adapt hy- perparameters during training (Jaderberg et al. 2017). As in the IMPALA paper, we use PBT to tune learning rate, entropy cost, the optimiser’s epsilon, and—in the Atari experiments—the max gradient norm. In Atari- 57 we used populations of 24 instances, in DmLab-30 just 8 instances. All hyperparameters are reported in the Appendix. # Discussion In this paper we propose a scale-invariant actor-critic al- gorithm that enables significantly improved performance in multi-task reinforcement learning settings. Being able to ac- quire knowledge about a wide range of facts and skills has been long considered an essential feature for an RL agent to demonstrate intelligent behaviour (Sutton et al. 2011; Degris and Modayil 2012; Legg and Hutter 2007). To ask our algorithms to master multiple tasks is therefore a natural step as we progress towards increasingly powerful agents. The wide-spread adoption of deep learning in RL is quite timely in this regard, since sharing parts of a neural net- work across multiple tasks is also a powerful way of build- ing robust representations. This is particularly important for RL, because rewards on individual tasks can be sparse, and therefore sharing representations across tasks can be vital to bootstrap learning. Several agents (Jaderberg et al. 2016; Lample and Chaplot 2016; Shelhamer et al. 2016; Mirowski et al. 2016) demonstrated this by improving performance on a single external task by learning off-policy about auxiliary tasks defined on the same stream of experience (e.g. pixel control, immediate reward prediction or auto-encoding). Multi-task learning, as considered in this paper, where we get to execute, in parallel, the policies learned for each task, has potential additional benefits, including deep exploration (Osband et al. 2016), and policy composition (Mankowitz et al. 2018; Todorov 2009). By learning on-policy about tasks, it may also be easier to scale to much more diverse tasks: if we only learn about some task off-policy from experience generated pursuing a very different one, we might never ob- serve any reward. A limitation of our approach is that it can be complicated to implement parallel learning outside of simulation, but recent work on parallel training of robots (Levine et al. 2016) suggests that this is not necessarily an insurmountable obstacle if sufficient resources are available. Adoption of parallel multi-task RL has up to now been fairly limited. That the scaling issues considered in this pa- per, may have been a factor in the limited adoption is in- dicated by the wider use of this kind of learning in su- pervised settings (Johnson et al. 2017; Lu et al. 2016; Misra et al. 2016; Hashimoto et al. 2016), where loss func- tions are naturally well scaled (e.g. cross entropy), or can be easily scaled thanks to the stationarity of the training dis- tribution. We therefore hope and believe that the work pre- sented here can enable more research on multi-task RL. We also believe that PopArt’s adaptive normalisation can be combined with other research in multi-task rein- forcement learning, that previously did not scale as effec- tively to large numbers of diverse tasks. We highlight as potential candidates policy distillation (Parisotto, Ba, and Salakhutdinov 2015; Rusu et al. 2015; Schmitt et al. 2018; Teh et al. 2017) and active sampling of the task distribution the agent trains on (Sharma and Ravindran 2017). The com- bination of PopArt-IMPALA with active sampling might be particularly promising since it may allow a more efficient use of the parallel data generation, by focusing it on the task most amenable for learning. Elastic weight consolidation (Kirkpatrick et al. 2017) and other work from the contin- ual learning literature (Ring 1994; Mcclelland, Mcnaughton, and O’Reilly 1995) might also be adapted to parallel learn- ing setups to reduce interference (French 1999) among tasks. References [Bacon, Harb, and Precup 2017] Bacon, P.; Harb, J.; and Precup, D. 2017. The option-critic architecture. AAAI Conference on Artificial Intelligence. [Beattie et al. 2016] Beattie, C.; Leibo, J. Z.; Teplyashin, D.; Ward, T.; Wainwright, M.; K¨uttler, H.; Lefrancq, A.; Green, S.; Vald´es, V.; Sadik, A.; Schrittwieser, J.; Anderson, K.; York, S.; Cant, M.; Cain, A.; Bolton, A.; Gaffney, S.; King, H.; Hassabis, D.; Legg, S.; and Petersen, S. 2016. Deepmind lab. CoRR abs/1612.03801. [Bellemare et al. 2013] Bellemare, M. G.; Naddaf, Y.; Veness, J.; and Bowling, M. 2013. The arcade learning environment: An eval- uation platform for general agents. JAIR. [Bellman 1957] Bellman, R. 1957. A markovian decision process. Journal of Mathematics and Mechanics. [Brunskill and Li 2013] Brunskill, E., and Li, L. ple complexity of multi-task reinforcement abs/1309.6821. 2013. learning. Sam- CoRR [Caruana 1998] Caruana, R. 1998. Multitask learning. In Learning to learn. [Collobert and Weston 2008] Collobert, R., and Weston, J. 2008. A unified architecture for natural language processing: Deep neural networks with multitask learning. In ICML. 2012. Scaling-up knowledge for a cognizant robot. In AAAI Spring Sym- posium: Designing Intelligent Robots. [Duan et al. 2016] Duan, Y.; Chen, X.; Houthooft, R.; Schulman, J.; and Abbeel, P. 2016. Benchmarking deep reinforcement learning for continuous control. In ICML. [Espeholt et al. 2018] Espeholt, L.; Soyer, H.; Munos, R.; Si- monyan, K.; Mnih, V.; Ward, T.; Doron, Y.; Firoiu, V.; Harley, T.; Dunning, I.; Legg, S.; and Kavukcuoglu, K. 2018. Impala: Scal- able distributed deep-rl with importance weighted actor-learner ar- chitectures. In ICML. [French 1999] French, R. M. 1999. Catastrophic forgetting in con- nectionist networks. Trends in cognitive sciences. [Gruslys et al. 2018] Gruslys, A.; Azar, M. G.; Bellemare, M. G.; and Munos, R. 2018. The reactor: A sample-efficient actor-critic architecture. ICLR. [Hashimoto et al. 2016] Hashimoto, K.; Xiong, C.; Tsuruoka, Y.; and Socher, R. 2016. A joint many-task model: Growing a neural network for multiple NLP tasks. CoRR abs/1611.01587. [He et al. 2015] He, K.; Zhang, X.; Ren, S.; and Sun, J. 2015. arXiv preprint Deep residual learning for image recognition. arXiv:1512.03385. [Hessel et al. 2018] Hessel, M.; Modayil, J.; van Hasselt, H.; Schaul, T.; Ostrovski, G.; Dabney, W.; Horgan, D.; Piot, B.; Azar, M. G.; and Silver, D. 2018. Rainbow: Combining improvements in deep reinforcement learning. AAAI Conference on Artificial In- telligence. [Hochreiter and Schmidhuber 1997] Hochreiter, S., and Schmidhu- ber, J. 1997. Long short-term memory. Neural computation. [Jaderberg et al. 2016] Jaderberg, M.; Mnih, V.; Czarnecki, W. M.; Schaul, T.; Leibo, J. Z.; Silver, D.; and Kavukcuoglu, K. 2016. Reinforcement learning with unsupervised auxiliary tasks. CoRR abs/1611.05397. [Jaderberg et al. 2017] Jaderberg, M.; Dalibard, V.; Osindero, S.; Czarnecki, W. M.; Donahue, J.; Razavi, A.; Vinyals, O.; Green, T.; Dunning, I.; Simonyan, K.; Fernando, C.; and Kavukcuoglu, K. 2017. Population based training of neural networks. CoRR abs/1711.09846. [Johnson et al. 2017] Johnson, M.; Schuster, M.; Le, Q. V.; Krikun, M.; Wu, Y.; Chen, Z.; Thorat, N.; Vi´egas, F. B.; Wattenberg, M.; Corrado, G.; Hughes, M.; and Dean, J. 2017. Google’s multilingual neural machine translation system: Enabling zero-shot translation. Transactions of the Association for Computational Linguistics 5. [Kirkpatrick et al. 2017] Kirkpatrick, J.; Pascanu, R.; Rabinowitz, N.; Veness, J.; Desjardins, G.; Rusu, A. A.; Milan, K.; Quan, J.; Ramalho, T.; Grabska-Barwinska, A.; Hassabis, D.; Clopath, C.; Kumaran, D.; and Hadsell, R. 2017. Overcoming catastrophic forgetting in neural networks. PNAS. [Lample and Chaplot 2016] Lample, G., and Chaplot, D. S. 2016. Playing FPS games with deep reinforcement learning. CoRR abs/1609.05521. [Legg and Hutter 2007] Legg, S., and Hutter, M. 2007. Universal intelligence: A definition of machine intelligence. Minds Mach. [Levine et al. 2016] Levine, S.; Pastor, P.; Krizhevsky, A.; and Quillen, D. 2016. Learning hand-eye coordination for robotic grasping with large-scale data collection. In ISER. [Lillicrap et al. 2016] Lillicrap, T.; Hunt, J.; Pritzel, A.; Heess, N.; Erez, T.; Tassa, Y.; Silver, D.; and Wierstra, D. 2016. Continuous control with deep reinforcement learning. In ICLR. [Lu et al. 2016] Lu, Y.; Kumar, A.; Zhai, S.; Cheng, Y.; Javidi, T.; and Feris, R. S. 2016. Fully-adaptive feature sharing in multi-task networks with applications in person attribute classification. CoRR abs/1611.05377. [Mahmood 2017] Mahmood, A. 2017. Incremental off-policy rein- forcement learning algorithms. Ph.D. UAlberta. [Mankowitz et al. 2018] Mankowitz, D. J.; Z´ıdek, A.; Barreto, A.; Horgan, D.; Hessel, M.; Quan, J.; Oh, J.; van Hasselt, H.; Silver, D.; and Schaul, T. 2018. Unicorn: Continual learning with a universal, off-policy agent. CoRR abs/1802.08294. [Mcclelland, Mcnaughton, and O’Reilly 1995] Mcclelland, J. L.; Mcnaughton, B. L.; and O’Reilly, R. C. 1995. Why there are com- plementary learning systems in the hippocampus and neocortex: Insights from the successes and failures of connectionist models of learning and memory. Psychological Review. [Mirowski et al. 2016] Mirowski, P.; Pascanu, R.; Viola, F.; Soyer, H.; Ballard, A. J.; Banino, A.; Denil, M.; Goroshin, R.; Sifre, L.; Kavukcuoglu, K.; Kumaran, D.; and Hadsell, R. 2016. Learning to navigate in complex environments. CoRR abs/1611.03673. I.; Shrivastava, A.; Gupta, A.; and Hebert, M. 2016. Cross-stitch networks for multi-task learning. CoRR abs/1604.03539. [Mnih et al. 2015] Mnih, V.; Kavukcuoglu, K.; Silver, D.; Rusu, A. A.; Veness, J.; Bellemare, M. G.; Graves, A.; Riedmiller, M.; Fidjeland, A. K.; Ostrovski, G.; Petersen, S.; Beattie, C.; Sadik, A.; Antonoglou, I.; King, H.; Kumaran, D.; Wierstra, D.; Legg, S.; and Hassabis, D. 2015. Human-level control through deep rein- forcement learning. Nature. [Mnih et al. 2016] Mnih, V.; Badia, A. P.; Mirza, M.; Graves, A.; Lillicrap, T.; Harley, T.; Silver, D.; and Kavukcuoglu, K. 2016. Asynchronous methods for deep reinforcement learning. In ICML. [Nair et al. 2015] Nair, A.; Srinivasan, P.; Blackwell, S.; Alcicek, C.; Fearon, R.; De Maria, A.; Panneershelvam, V.; Suleyman, M.; Beattie, C.; Petersen, S.; Legg, S.; Mnih, V.; Kavukcuoglu, K.; and Silver, D. 2015. Massively parallel methods for deep reinforcement learning. arXiv preprint arXiv:1507.04296. [Osband et al. 2016] Osband, I.; Blundell, C.; Pritzel, A.; and Van Roy, B. 2016. Deep exploration via bootstrapped DQN. In NIPS. [Parisotto, Ba, and Salakhutdinov 2015] Parisotto, E.; Ba, L. J.; and Salakhutdinov, R. 2015. Actor-mimic: Deep multitask and transfer reinforcement learning. CoRR abs/1511.06342. [Precup, Sutton, and Singh 2000] Precup, D.; Sutton, R. S.; and Singh, S. P. 2000. Eligibility traces for off-policy policy evalu- ation. In ICML. [Ring 1994] Ring, M. 1994. Continual learning in reinforcement environments. [Romera-Paredes et al. 2013] Romera-Paredes, B.; Aung, H.; Bianchi-Berthouze, N.; and Pontil, M. 2013. Multilinear multitask learning. In ICML. [Rusu et al. 2015] Rusu, A. A.; Colmenarejo, S. G.; G¨ulc¸ehre, C¸ .; Desjardins, G.; Kirkpatrick, J.; Pascanu, R.; Mnih, V.; Kavukcuoglu, K.; and Hadsell, R. 2015. Policy distillation. CoRR abs/1511.06295. [Rusu et al. 2016] Rusu, A. A.; Rabinowitz, N. C.; Desjardins, G.; Soyer, H.; Kirkpatrick, J.; Kavukcuoglu, K.; Pascanu, R.; and Had- sell, R. 2016. Progressive neural networks. CoRR abs/1606.04671. [Schmidhuber 1990] Schmidhuber, J. 1990. An on-line algorithm for dynamic reinforcement learning and planning in reactive envi- ronments. In IJCNN. [Schmitt et al. 2018] Schmitt, S.; Hudson, J. J.; Z´ıdek, A.; Osin- dero, S.; Doersch, C.; Czarnecki, W. M.; Leibo, J. Z.; K¨uttler, H.; Zisserman, A.; Simonyan, K.; and Eslami, S. M. A. 2018. Kick- starting deep reinforcement learning. CoRR abs/1803.03835. [Schulman et al. 2015] Schulman, J.; Levine, S.; Moritz, P.; Jordan, M. I.; and Abbeel, P. 2015. Trust region policy optimization. CoRR abs/1502.05477. [Schulman et al. 2017] Schulman, J.; Wolski, F.; Dhariwal, P.; Rad- ford, A.; and Klimov, O. 2017. Proximal policy optimization algo- rithms. CoRR abs/1707.06347. [Sharma and Ravindran 2017] Sharma, S., and Ravindran, B. 2017. CoRR Online multi-task learning using active sampling. abs/1702.06053. [Shelhamer et al. 2016] Shelhamer, E.; Mahmoudieh, P.; Argus, M.; and Darrell, T. 2016. Loss is its own reward: Self-supervision for reinforcement learning. CoRR abs/1612.07307. [Silver et al. 2016] Silver, D.; Huang, A.; Maddison, C. J.; Guez, A.; Sifre, L.; van den Driessche, G.; Schrittwieser, J.; Antonoglou, I.; Panneershelvam, V.; Lanctot, M.; Dieleman, S.; Grewe, D.; Nham, J.; Kalchbrenner, N.; Sutskever, I.; Lillicrap, T.; Leach, M.; Kavukcuoglu, K.; Graepel, T.; and Hassabis, D. 2016. Mastering the game of Go with deep neural networks and tree search. Nature. J.; Antonoglou, I.; Lai, M.; Guez, A.; Lanctot, M.; Sifre, L.; Kumaran, D.; Graepel, T.; Lillicrap, T. P.; Simonyan, K.; and Hassabis, D. 2017. Mastering chess and shogi by self-play with a general reinforcement learning algorithm. CoRR abs/1712.01815. [Sutton and Barto 2018] Sutton, R. S., and Barto, A. G. 2018. Re- inforcement Learning: An Introduction. MIT press. [Sutton et al. 2011] Sutton, R. S.; Modayil, J.; Delp, M.; Degris, T.; Pilarski, P. M.; White, A.; and Precup, D. 2011. Horde: A scalable real-time architecture for learning knowledge from unsupervised sensorimotor interaction. In AAMAS. [Sutton et al. 2014] Sutton, R. S.; Mahmood, A. R.; Precup, D.; and van Hasselt, H. 2014. A new q(λ) with interim forward view and Monte Carlo equivalence. In ICML. [Teh et al. 2017] Teh, Y. W.; Bapst, V.; Czarnecki, W. M.; Quan, J.; Kirkpatrick, J.; Hadsell, R.; Heess, N.; and Pascanu, R. 2017. Distral: Robust multitask reinforcement learning. CoRR abs/1707.04175. [Thrun 1996] Thrun, S. 1996. Is learning the n-th thing any easier than learning the first? In NIPS. [Thrun 2012] Thrun, S. 2012. Explanation-based neural network learning: A lifelong learning approach. Springer. [Todorov 2009] Todorov, E. 2009. Compositionality of optimal control laws. In NIPS. [van Hasselt et al. 2016] van Hasselt, H.; Guez, A.; Hessel, M.; Mnih, V.; and Silver, D. 2016. Learning values across many or- ders of magnitude. In NIPS. [van Hasselt, Guez, and Silver 2016] van Hasselt, H.; Guez, A.; and Silver, D. 2016. Deep reinforcement learning with double Q- learning. In AAAI Conference on Artificial Intelligence. [Watkins 1989] Watkins, C. J. C. H. 1989. Learning from Delayed Rewards. Ph.D. Dissertation, King’s College, Cambridge, England. [Williams 1992] Williams, R. 1992. Simple statistical gradient- learning. following algorithms for connectionist reinforcement Mach. Learning. Appendix In this Appendix we report additional details about the re- sults presented in the main text, as well as present addi- tional experiments on the DmLab-30 benchmark. We also report the breakdown per level of the scores of IMPALA and PopArt-IMPALA on the Atari-57 and DmLab-30 bench- marks. Finally, we report the hyperparameters used to train the baseline agents as well as PopArt-IMPALA. These hy- perparameters are mostly the same as in Espeholt et al., but we report them for completeness and to ease reproducibility. Hyper-parameter tuning In our experiments we used Population-Based Training (PBT) to tune hyper-parameters. In our DmLab-30 exper- iments, however, we used smaller populations than in the original IMPALA paper. For completeness, we also report here the results of running PopArt-IMPALA and IMPALA with the larger population size used by Espeholt et al. Due to the increased cost of using larger populations, in this case we will only report one PBT tuning experiment per agent, rather than the 3 reported in the main text. The learning curves for both IMPALA and PopArt- IMPALA are shown in Figure 6, together with horizon- tal dashed lines marking average final performance of the agents trained with the smaller population of just 8 in- stances. The performance of both IMPALA and PopArt- IMPALA agents at the end of training is very similar whether hyperparameters are tuned with 8 or 24 PBT in- stances, suggesting that the large populations used for hyper- parameter tuning by Espeholt et al. may not be necessary. Note, however, that we have observed larger discrepancies between experiments where small and large population size are used for tuning hyper-parameter, when training the less performing IMPALA agent that used a more limited action set, as presented in the original IMPALA paper. DmLab-30 — PopartIMPALA [24] 20 — IMPALA [24] PopArt-IMPALA [8] (@1e10 frames) IMPALA [8] (@1e10 frames) 00 02 Om 06 08 To Environment Frames 1e10 Figure 6: Larger populations: mean capped human nor- malised score across the DmLab-30 benchmark as a func- tion of the total number of frames seen by the agents across all levels. The solid lines plot the performance of IMPALA (blue) and PopArt-IMPALA (orange) when tuning hyper- parameters with a large PBT population of 24 instances. Dashed lines correspond to the final performance of these same agents, after 10B frames, in the previous experiments where hyper-parameters were tuned with a population of 8. # Pixel Control Pixel control (Jaderberg et al. 2016) is an unsupervised aux- iliary task introduced to help learning good state represen- tations. We report here also the performance of combining Pixel Control with IMPALA without also using PopArt. As shown in Figure 7, pixel control increases the performance of both the PopArt-IMPALA agent as well as that of the IM- PALA baseline. PopArt still guarantees a noticeable boost in performance, with the median human normalized score of Pixel-PopArt-IMPALA (red line) exceeding the score of Pixel-IMPALA (green line) by approximately 10 points. We implemented the pixel control task as described in the original paper, only adapting the scheme to the rectangular observations used in DmLab-30. We split the (72 × 96) ob- servations into a 18×24 grid of 4×4 cells. For each location in the grid we define a distinct pseudo-reward ˜ri,j, equal to the absolute value of the difference between pixel intensities in consecutive frames, averaged across the 16 pixels of cell ci,j. For each cell, we train action values with multi-step Q- learning, accumulating rewards until the end of a rollout and then bootstrapping. We use a discount γ = 0.9. Learning is fully off-policy on experience generated by the actors, that follow the main policy π as usual. We use a deep deconvolutional network for the action value predictions associated to each pseudo-reward ˜ri,j. First, we feed the LSTM’s output to a fully connected layer, reshape the output tensor as 6 × 9 × 32, and apply a decon- volution with 3 × 3 kernels that outputs a 8 × 11 × 32 tensor. From this, we compute a spatial grid of Q-values using a du- eling network architecture: we use a deconvolution with 1 output channel for the state values across the grid and a de- convolution with |A| channels for the advantage estimates of each cell. Output deconvolutions use 4 × 4 kernels with stride 2. The additional head is only evaluated on the learner, actors do not execute it. 20 DmLab-30 PopArtIMPALA@10B IMPALA-original@10B — Pixel-PopartiMPALA = — Pixel-IMPALA ° 2 i 00) oS 10 TS 2.0 Environment Frames 109 Figure 7: Pixel Control: mean capped human normalised score across the DmLab-30 benchmark as a function of the total number of frames (summed across levels). Solid lines plot the performance PopArt-IMPALA (red) and IM- PALA (green), after augmenting both with pixel con- trol. Dashed lines mark the point at which Pixel-PopArt- IMPALA matches the final performance of previous agents. Note how, thanks to the improved data efficiency, we train for 2B frames, compared to 10B in previous experiments. Atari-57 Score breakdown In this section we use barplots to report the final perfor- mance of the agents on each of the levels in the Atari-57 multi-task benchmark. In order to compute these scores we take the final trained agent and evaluate it with a frozen pol- icy on each of the levels for 200 episodes. The same trained policy is evaluated in all the levels, and the policy is not provided information about the task it’s being evaluated on. For Atari, we compare PopArt-IMPALA, with and without reward clipping, to an IMPALA baseline. In all cases the height of the bars in the plot denote human normalised score. For the Atari results we additionally rescale logarithmically the x-axis, because in this domain games may differ in their normalised performance by several orders of magnitude. Figure 8: Atari-57 breakdown: human normalised score for IMPALA and PopArt-IMPALA, as measured in a separate evaluation phase at the end of training, broken down for the 57 games. For PopArt-IMPALA we report the scores both with and without reward clipping [I PopArt-IMPALA [J PopArt-IMPALA (unclipped) EEE) IMPALA atlantis, gopher assault up_n_down breakout double_dunk krull boxing demon_attack kangaroo crazy_climber defender road_runner robotank Jamesbond fishing_derby phoenix centipede bank heist, kung fu_master star_gunner tennis tutankham pong enduro wizard_of_wor battle_zone freeway surround venture vars revenge video_pinball Ice_hockey name _this_ game time_pilot riverraid chopper_command asterix ms_pacman hero alien space_invaders berzerk bowling beam_rider amidar oravitar abert frostbite asteroids seaquest pitfall private_eye montezuma_revenge solaris, skiing : . 10 100 Normalised Score T0000 DmLab-30 Score breakdown In this section we use barplots to report the final perfor- mance of the agents on each of the levels in the DmLab- 30 multi-task benchmark. In order to compute these scores we take the final trained agent and evaluate it with a frozen policy on each of the levels for 500 episodes. We perform the evaluation over a higher number of episodes (compared to Atari) because the variance of the mean episode return is typically higher in DeepMind Lab. As before, the same trained policy is evaluated on all levels, and the policy is not provided information about the task it’s being evaluated on. Also in DmLab-30 we perform a three-way comparison. We compare PopArt-IMPALA to our improved IMPALA base- line, and, for completeness, to the original paper’s IMPALA. Figure 9: DmLab-30 breakdown: human normalised score for the original paper’s IMPALA, our improved IMPALA baseline, and PopArt-IMPALA, as measured at the end of training, broken down for the 30 tasks; they all used 8 in- stances for population based training. CJ IMPALA-original [ES PopArt-IMPALA (a IMPALA lasertag_one_opponent_small language_select_described_object lasertag_three_opponents_small explore_goal_locations_small lasertag_three_opponents_large explore_obstructed_goals_small psychlab_visual_search lasertag_one_opponent_large explore_object_locations_small language_select_located_object natlab_varying_map_regrowth language_answer_quantitative_question explore_object locations large rooms_collect_good_objects test natlab_varying_map_randomized explore_object_rewards few explore_goal_locations_large psychlab_sequential_comparison explore_obstructed_goals_large explore_object_rewards_many psychlab_continuous_recognition rooms select_nonmatching_object natlab_fixed_large_map rooms_watermaze platforms_random rooms keys doors puzzle platforms_hard psychlab_arbitrary_visuomotor_mapping language_execute_random_task rooms_exploit_deferred_effects test Por et 0 20 40 60 80 100 120 140 Normalised Score DeepMind Lab action discretisation DeepMind Lab’s native action space is a 7-dimensional continuous space, whose dimensions correspond to rotat- ing horizontally/vertically, strafing left/right, moving for- ward/backward, tagging, crouching, and jumping. Despite the native action space being continuous, previ- ous work on this platform has however typically relied on a coarse discretisation of the action space. We therefore follow the same approach also in our experiments. Below we list the discretisations used by the agents con- sidered in our experiments. This includes the discretisation used by IMPALA, as well as the one we introduce in this pa- per in order to unlock some levels in DmLab-30 which just can’t be solved under the original IMPALA discretisation. Table 1: Action discretisation used by IMPALA: we report below the discretisation of DeepMind Lab’s action space, as used by the original IMPALA agent in Espeholt et al. Native DmLab Action Action [ 0, 0, 0, 1, 0, 0, 0] Forward (FW) [ 0, 0, 0, -1, 0, 0, 0] Backward (BW) [ 0, 0, -1, 0, 0, 0, 0] Strafe Left [ 0, 0, 1, 0, 0, 0, 0] Strafe Right [-20, 0, 0, 0, 0, 0, 0] Look Left (LL) Look Right (LR) [ 20, 0, 0, 0, 0, 0, 0] [-20, 0, 0, 1, 0, 0, 0] FW + LL [ 20, 0, 0, 1, 0, 0, 0] FW + LR [ 0, 0, 0, 0, 1, 0, 0] Fire Table 2: Action discretisation of DeepMind Lab’s action space, as used by our version of IMPALA and by PopArt- IMPALA. Native DmLab Action Action [ 0, 0, 0, 1, 0, 0, 0] FW [ 0, 0, 0, -1, 0, 0, 0] BW [ 0, 0, -1, 0, 0, 0, 0] Strafe Left [ 0, 0, 1, 0, 0, 0, 0] Strafe Right [-10, 0, 0, 0, 0, 0, 0] Small LL [ 10, 0, 0, 0, 0, 0, 0] Small LR [-60, 0, 0, 0, 0, 0, 0] Large LL [ 60, 0, 0, 0, 0, 0, 0] Large LR [ 0, 10, 0, 0, 0, 0, 0] Look Down [ 0,-10, 0, 0, 0, 0, 0] Look Up [-10, 0, 0, 1, 0, 0, 0] FW + Small LL FW + Small LR [ 10, 0, 0, 1, 0, 0, 0] [-60, 0, 0, 1, 0, 0, 0] FW + Large LL FW + Large LR [ 60, 0, 0, 1, 0, 0, 0] [ 0, 0, 0, 0, 1, 0, 0] Fire Fixed Hyperparameters Table 3: PopArt specific hyperparameters: these are held fixed during training and were only very lightly tuned. The lower bound is used to avoid numerical issues when rewards are extremely sparse. Hyperparameter Statistics learning rate 0.0003 0.0001 Scale lower bound 1e6 Scale upper bound Table 4: DeepMind Lab preprocessing. As in previous work on DeepMind Lab, we render the observation with a resolu- tion of [72, 96], as well as use 4 action repeats. We also em- ploy the optimistic asymmetric rescaling (OAR) of rewards, that was introduced in Espeholt et al. for exploration. Hyperparameter Image Height Image Width Number of action repeats Reward Rescaling value 72 96 4 -0.3min(tanh(r),0)+ 5max(tanh(r),0) standard Atari- Table 5: Atari preprocessing. The preprocessing is used in the Atari experiments. Since the introduction of DQN these setting have become a standard practice when training deep RL agent on Atari. Note however, that we report experiments training agents both with and without reward clipping. Hyperparameter Image Height Image Width Grey scaling Max-pooling 2 consecutive frames Frame Stacking End of episode on life loss Reward Clipping (if used) Number of action repeats Table 6: Other agent hyperparameters: These hyperparame- ters are the same used by Espeholt et al. # value 20 (Atari), 100 (DmLab) 0.99 0.5 32 RMSProp 0. Hyperparameter Unroll length Discount γ Baseline loss weight γ Batch size Optimiser RMSProp momentum # Network Architecture Table 7: Network hyperparameters. The network architec- ture is described in details in Espeholt et al., For complete- ness, we also report in the Table below the complete spec- ification of the network. Convolutional layers are specified according to the pattern (num layers, kernel size, stride). 3 [16, 32, 32] ReLU 1 / 3x3 / 1) 1 / 3x3 / 2 2 / 3x3 / 1 Identity 2 / 3x3 / 1 Identity 20 LSTM / 64 256 256 # Linear Linear+softmax # Population Based Training Table 8: Population Based Training: we use PBT for tuning hyper-parameters, as described in Espeholt et al., with pop- ulation size and fitness function as defined below. Hyperparameter Population Size (Atari) Population Size (DmLab) Fitness value 24 8 Mean capped human normalised score (cap=100) Table 9: hyperparameters tuned with population based train- ing are listed below: note that these are the same used by all baseline agents we compare to, to ensure fair comparisons. Hyperparameter Entropy cost Learning rate RMSProp epsilon Max Grad Norm distribution Log-uniform on [5e-5, 1e-2] Log-uniform on [5e-6, 5e-3] Categorical on [1e-1, 1e-3, 1e-5, 1e-7] Uniform on [10, 100]
Title: Multiagent Bidirectionally-Coordinated Nets: Emergence of Human-level Coordination in Learning to Play StarCraft Combat Games: Summary: Many artificial intelligence (AI) applications often require multiple intelligent agents to work in a collaborative effort. Efficient learning for intra-agent communication and coordination is an indispensable step towards general AI. In this paper, we take StarCraft combat game as a case study, where the task is to coordinate multiple agents as a team to defeat their enemies. To maintain a scalable yet effective communication protocol, we introduce a Multiagent Bidirectionally-Coordinated Network (BiCNet ['bIknet]) with a vectorised extension of actor-critic formulation. We show that BiCNet can handle different types of combats with arbitrary numbers of AI agents for both sides. Our analysis demonstrates that without any supervisions such as human demonstrations or labelled data, BiCNet could learn various types of advanced coordination strategies that have been commonly used by experienced game players. In our experiments, we evaluate our approach against multiple baselines under different scenarios; it shows state-of-the-art performance, and possesses potential values for large-scale real-world applications. # Multiagent Bidirectionally-Coordinated Nets # Emergence of Human-level Coordination in Learning to Play StarCraft Combat Games* # Peng Peng', Ying Wen'', Yaodong Yang’, Yuan Quan’, Zhenkun Tang’, Haitao Long’, Jun Wang? 5University College London, Alibaba Group # Abstract Many artificial intelligence (AI) applications often require multiple intelligent agents to work in a collaborative effort. Efficient learning for intra-agent communication and coordi- nation is an indispensable step towards general AI. In this paper, we take StarCraft combat game as a case study, where the task is to coordinate multiple agents as a team to defeat their enemies. To maintain a scalable yet effective commu- nication protocol, we introduce a Multiagent Bidirectionally- Coordinated Network (BiCNet [’brknet]) with a vectorised extension of actor-critic formulation. We show that BiCNet can handle different types of combats with arbitrary numbers of AI agents for both sides. Our analysis demonstrates that without any supervisions such as human demonstrations or labelled data, BiCNet could learn various types of advanced coordination strategies that have been commonly used by ex- perienced game players. In our experiments, we evaluate our approach against multiple baselines under different scenarios; it shows state-of-the-art performance, and possesses potential values for large-scale real-world applications. # Introduction The last decade has witnessed massive progresses in the field of Artificial Intelligence (AI). With supervision from la- belled data, machines have, to some extent, exceeded human- level perception on visual recognitions and speech recogni- tions, while fed with feedback reward, single AI units (aka agents) defeat humans in various games including Atari video games (Mnih et al. 2015), Go game (Silver et al. 2016), and card game (Brown and Sandholm 2017). Yet, true human intelligence embraces social and collective wisdom which lays an essential foundation for reaching the grand goal of Artificial General Intelligence (AGI) (Goertzel and Pennachin 2007). As demonstrated by crowd sourcing, aggregating efforts collectively from the public would solve the problem that otherwise is unthinkable by a single person. Even social animals like a brood of well-organised ants could accomplish challenging tasks such as hunting, building a kingdom, and even waging a war, although each ant by itself is weak and limited. Interestingly, in the coming era of algo- rithmic economy, AI agents with a certain rudimentary level of artificial collective intelligence start to emerge from mul- tiple domains. Typical examples include the trading robots *Previously as title: “Multiagent Bidirectionally-Coordinated Nets for Learning to Play StarCraft Combat Games”, Mar 2017. gaming on the stock markets (Deboeck 1994), ad bidding agents competing with each other over online advertising exchanges (Wang, Zhang, and Yuan 2017), and e-commerce collaborative filtering recommenders predicting user inter- ests through the wisdom of the crowd (Schafer, Konstan, and Riedl 1999). We thus believe a next grand challenge of AGI is to an- swer how multiple AI agents could learn human-level col- laborations, or competitions, from their experiences with the environment where both of their incentives and eco- nomic constraints co-exist. As the flourishes of deep rein- forcement learning (DRL) (Mnih et al. 2015; Silver et al. 2016), researchers start to shed light on tackling multia- gent problems (Schmidhuber 1996) with the enhanced learn- ing capabilities, e.g., (Sukhbaatar, Fergus, and others 2016; Mordatch and Abbeel 2017). In this paper, we leverage a real-time strategy game, Star- Craft', as the use case to explore the learning of intelligent collaborative behaviours among multiple agents. Particularly, we focus on StarCraft micromanagement tasks (Synnaeve et al. 2016), where each player controls their own units (with different functions to collaborate) to destroy the opponents army in the combats under different terrain conditions. Such game is considered as one of the most difficult games for computers with more possible states than Go game (Syn- naeve et al. 2016). The learning of this large-scale multiagent system faces a major challenge that the parameters space grows exponentially with the increasing number of agents involved. As such, the behaviours of the agents can become so sophisticated that any joint learner method (Sukhbaatar, Fergus, and others 2016) would be inefficient and unable to deal with the changing number of agents in the game. We formulate multiagent learning for StarCraft combat tasks as a zero-sum Stochastic Game. Agents are communi- cated by our proposed bidirectionally-coordinated net (BiC- Net), while the learning is done using a multiagent actor-critic framework. In addition, we also introduce parameter shar- ing to solve the scalability issue. We observe that BiCNet can automatically learn various optimal strategies to coor- dinating agents, similar to what experienced human players would adopt in playing the StarCraft game, ranging from trivial move without collision to a basic tactic hit and run to sophisticated cover attack, and focus fire without overkill. We have conducted our experiments by testing over a set of combat tasks with different levels of difficulties. Our method i The first two authors have equal contributions. Correspondence to Jun Wang, jun.wang @cs.ucl.ac.uk. ‘Trademark of Blizzard Entertainment™. outperforms state-of-the-art methods and shows its potential usage in a wide range of multiagent tasks in the real-world applications. Related Work The studies on interaction and collaboration in multiagent settings have a long history (Littman 1994; Schmidhuber 1996). Although limited to toy examples in the beginning, reinforcement learning, as a means, has long been applied to multiagent systems in order to learn optimal collaboration policies. One of the key components in multiagent RL is to learn a communication protocol among agents. With deep learning, representative solutions include the differentiable inter-agent learning (DIAL) (Foerster et al. 2016) and the CommNet (Sukhbaatar, Fergus, and others 2016), both of which are end-to-end trainable by back-propagation. DIAL (Foerster et al. 2016) was introduced in partially observable settings where messages passing between agents are allowed. The agent is also named as a independent learner. The idea of learning independent agents can also be found (Lauer and Riedmiller 2000; Kapetanakis and Kudenko 2002; Lauer and Riedmiller 2004; Foerster et al. 2016). In DIAL, each agent consists of a recurrent neural network that outputs individual agent’s Q-value and a message to transfer for each time-step. The generated messages is then transferred to other agents as used as inputs for others in the next time step. The received messages will be embedded with agent’s current observations and last action as the representation of the global information. Communication between independent agents is one way to mitigate the notorious non-stationary issue in the mutliagent settings as the gradients will at least flow among the agents; however, researchers are still looking for better solutions for complex environments such as StarCraft. By contrast, CommNet (Sukhbaatar, Fergus, and others 2016) is designed for joint action learners in fully observable settings. Unlike DIAL, CommNet proposes a single network in the multiagent setting, passing the averaged message over the agent modules between layers. However, as the commu- nication network is fully symmetric and embedded in the original network, it lacks the ability of handle heterogeneous agent types. Also it is a single network for all agents, and therefore its scalability is unclear. In this paper, we solve these issues by creating a dedicated bi-directional communi- cation channel using recurrent neural networks (Schuster and Paliwal 1997). As such, heterogeneous agents can be created with a different set of parameters and output actions. The bi-directional nature means that the communication is not entirely symmetric, and the different priority among agents would help solving any possible tie between multiple opti- mal joint actions (Busoniu, Babuska, and De Schutter 2008; Spaan et al. 2002). Multiagent systems have been explored on specific Star- Craft games. Google DeepMind released a game interface based on StarCraft II and claimed that it is hard to make significant progress on the full game even with the state-of- the-art RL algorithms (Vinyals et al. 2017). Usunier et al. presented a heuristic exploration technique for learning deter- ministic policies in micro-management tasks. Both Synnaeve et al. and Usunier et al. focused on a greedy MDP approach, 1.e., the action of an agent is dependent explicitly on the ac- tion of other agents. In our paper, the dependency of agents is rather modelled over hidden layers by making use of bi- Attention Neron, WB Bicirectionar NN WG Poticy Action (a) Multiagent policy networks (b) Multiagent Q networks Figure 1: Bidirectionally-Coordinated Net (BiCNet). As a means of communication, bi-direction recurrent networks have been used to connect each individual agent’s policy and and Q networks. The learning is done by multiagent deterministic actor-critic as derived in the text. directional RNN (Schuster and Paliwal 1997). A significant benefit over the greedy solution is that, while keeping simple, the communication happens in the latent space so that high- level information can be passed between agents; meanwhile, the gradient updates from all the agents can be efficiently propagated through the entire network. Recently, Foerster et al. has attempted to solve the non- stationarity problem in mutliagent learning by improving the replay buffer, and tested the DIAL model in a way that all agents are fully decentralised. The COMA model (Foerster et al. 2017a) was then proposed to tackle the challenge of multiagent credit assignment. Through the introduction of the counterfactual reward; the idea of training multiagent systems in the centralised critic and decentralised actors way was further reinforced. At the same time, the framework of centralised learning and decentralised execution was also adopted by MADDPG in (Lowe et al. 2017) in some simpler, non-startcraft cases. By contrast, our BiCNet makes use of memory to form a communication channel among agents where the parameter space of communication is independent of the number of agents. Multiagent Bidirectionally-Coordinated Nets StartCraft Combat as Stochastic Games The StarCraft combat games, a.k.a., the micromanagement tasks, refer to the low-level, short-term control of the army members during a combat against the enemy members. For each combat, the agents in one side are fully coop- erative, and they compete with the opponents; therefore, each combat can be considered as a zero-sum competi- tive game between N agents and M enemies. We formu- late it as a zero-sum Stochastic Game (SG) (Owen 1995), i.e., a dynamic game in a multiple state situation played by multiple agents. A SG can be described by a tuple (S, {A}, (BG, T, {RM}. Let S denotes the state space of the current game, shared among all the agents. Initial state s; follows s; ~ p(s). We define the action space of the controlled agent 7 as A;, and the action space of the enemy j as Bj. T : S x AN x BM — S stands for the deterministic transition function of the environment, and Ri: Sx AN x BM — R represents the reward function of each agent i for i € [1, N]. In order to maintain a flexible framework that could allow an arbitrary number of agents, we consider that the agents, either the controlled or the enemies, share the same state space S' of the current game; and within each camp, agents are homogeneous” thus having the same action spaces A and B respectively. That is, for each agent i € [1, N] and enemy j € [1, M], Ai = A and B; = B. As discrete action space is intractably large, we consider continuous control outputs, e.g., attack angle and distance. In defining the reward function, we introduce a time- variant global reward based on the difference of the heath level between two consecutive time steps: N+M + 1 N r(s,a,b) = M > AR‘(s,a,b) - WD ARi(s.a,b), j=N4+1 i=1 (1) where for simplicity, we drop the subscript ¢ in global reward r(s,a, b). For given time step ¢ with state s, the controlled agents take actions a € AY, the opponents take actions b € B™, and AR*(.) = Ri7!(s,a,b) — Ri(s, a, b) repre- sents the reduced health level for agent 7. Note that Eq.(1) is presented from the aspect of controlled agents; the enemy’s global reward is the exact opposite, making the sum of re- wards from both camps equal zero. As the health level is non-increasing over time, Eq. (1) gives a positive reward at time step ¢ if the decrease of enemies’ health levels exceeds that of ours. With the defined global reward r(s, a, b), the controlled agents jointly take actions a in state s when the enemies take joint actions b. The agents’ objective is to learn a policy that maximises the expected sum of discounted rewards, i.e., Ets AM ritn], where 0 < \ < 1 is discount factor. Con- versely, the enemies’ joint policy is to minimise the expected sum. Correspondingly, we have the following Minimax game: Qiq(s, a, b) =r(s,a, b) + Amaxmin Qjq(s', aa(s"), ba(s')), (2) where s’ = s‘+! is determined by T(s, a, b). Q§,(s, a, b) is the optimal action-state value function, which follows the Bellman Optimal Equation. Here we propose to use deter- ministic policy ag : S + AY of the controlled agents and the deterministic policy (Silver et al. 2014) bg : S + BY With our framework heterogeneous agents can be also trained using different parameters and action space. of the enemies. In small-scale MARL problems, a common solution is to employ Minimax Q-learning (Littman 1994). However, minimax Q-learning is generally intractable to ap- ply in complex games. For simplicity, we consider the case that the policy of enemies is fixed, while leaving dedicated opponent modelling for future work. Then, SG defined in Eq. (2) effectively turns into an MDP problem (He et al. 2016): Q"*(s,a) =r(s,a) + Amax Q"(s',a9(s‘)), GB) where we drop notation bg for brevity. # Local, Individual Rewards A potential drawback of only using the global reward in Eq. (1) and its resulting zero-sum game is that it ignores the fact that a team collaboration typically consists of local col- laborations and reward function and would normally includes certain internal structure. Moreover, in practice, each agent tends to have its own objective which drives the collaboration. To model this, we extend the formulation in the previous sec- tion by replacing Eq. (1) with each agent’s local reward and including the evaluation of their attribution to other agents that have been interacting with (either completing or collabo- rating), i.e., = 1 t rj(s,a,b) = jtop-K-u()| > AR;(s, a, b)— J€top-K-u(i) 1 t Toke 2 ARH ab), @ i! €top-K-e(i) where each agent i maintains top-K-u(i) and top-K-e(i), the top-C lists of other agents and enemies, that are cur- rently being interacted with. Replacing it with Eq. (1), we have N number of Bellman equations for agent i, where i € {1,..., N}, for the same parameter 0 of the policy func- tion: Qi(s,a) =ri(s,a) + AmaxQj(s',ag(s’)). — ) # Communication w/ Bidirectional Backpropagation Although Eq. (5) makes single-agent methods, such as deter- ministic policy gradient (Silver et al. 2014; Mnih et al. 2016), immediately applicable for learning individual actions, those approaches, however, lacks a principled mechanism to foster team-level collaboration. In this paper, we allow communica- tions between agents (right before taking individual actions) by proposing a bidirectionally-coordinated net (BiCNet). Overall, BiCNet consists of a multiagent actor network and a multiagent critic network as illustrated in Fig.(1). Both of the policy network (actor) and the Q-network (critic) are based on the bi-directional RNN structure (Schuster and Pali- wal 1997). The policy network, which takes in a shared ob- servation together with a local view, returns the action for each individual agent. As the bi-directional recurrent struc- ture could serve not only as a communication channel but also as a local memory saver, each individual agent is able to maintain its own internal states, as well as to share the information with its collaborators. For the learning over BiCNet, intuitively, we can think of computing the backward gradients by unfolding the network of length N (the number of controlled agents) and then ap- plying backpropagation through time (BPTT) (Werbos 1990). The gradients pass to both the individual Q,; function and the policy function. They are aggregated from all the agents and their actions. In other words, the gradients from all agents rewards are first propagated to influence each of agents ac- tions, and the resulting gradients are further propagated back to updating the parameters. To see this mathematically, we denote the objective of a single agent i by J; (0); that is to maximise its expected cumu- lative individual reward r; as J;(9) = Eswpr [ri(s, ao(s))], ag where pL, (s) is the discounted state distribution correspond- ing to the policy ag under the transition T, i.e., pZ,(s) := Js De A *pi(s)1 (8! = Tey, py, (S))4s 5 it can also be cho- sen as the stationary distribution of an ergodic MDP. So, we can write the objective of N agents denoted by J(@) as follows: N J(8) =Eswor [D> ri(s,ae(s))]- 6) i=1 Next, we introduce a multiagent analogue to the deterministic policy gradient theorem. The proof, which we give in the Supplementary Material, follows a similar scheme to both (Silver et al. 2014) and (Sutton et al. 2000). Theorem 1 (Multiagent Deterministic PG Theorem) Given N agents which are collectively represented in a policy parameterised with 0, the discounted state distribution pi, (s), and the objective function J(0) defined in Eq.(6), we have the policy gradient as follows: VoJ(0) = N N Es pF, (s) > > Voaj,(s) - Va;Q;*(s, aa(s)) i=l j=l (7) where to ensure adequate exploration, we apply Ornstein- Uhlenbeck process to add noise on the output of actor net- work in each time step. Here we further consider the off- policy deterministic actor-critic algorithms (Lillicrap et al. 2015; Silver et al. 2014) to reduce the variance. In particular, we employ a critic function in Eq. (7) to estimate the action- value Q?? where off-policy explorations can be conducted. In training the critic, we use the sum of square loss and have the following gradient for the parametrised critic Q§(s, a), where € is the parameter for the Q network: N VeL(S) = Borys c)| Do(rl5sa0(s)) + AQE!-a0(s') i=1 ~Q§(s, av(s))) Vac (s.a0(8) . (8) Note that the gradient is also aggregated from multiple agents as the policy network would do. With Eqs. (7) and Eqs. (8), we apply Stochastic Gradient Descent (SGD) to op- timise both the actor and the critic networks. The pseudocode of the over algorithm is given in the Supplementary Material. BiCNet is markedly different from greedy MDP approach as the dependency of agents are embedded in the latent lay- ers, rather than directly on the actions. While simple, our approach allow full dependency among agents because the gradients from all the actions in Eq.(7) are efficiently prop- agated through the entire networks. Yet, unlike CommNet (Sukhbaatar, Fergus, and others 2016), our communication is not fully symmetric, and we maintain certain social conven- tions and roles by fixing the order of the agents that join the RNN. This would help solving any possible tie between multi- ple optimal joint actions (Busoniu, Babuska, and De Schutter 2008; Spaan et al. 2002). Across different agents, the parameters are shared so that the number of parameters is independent of the number of agents (analogous to the shared parameters across the time domain in vanilla RNN). Parameter sharing results in the compactness of the model which could speed up the learning process. Moreover, this could also enable the domain adap- tion where the network trained on the small team of of agents (typically three) effectively scales up to larger team of agents during the test under different combat scenarios. # Experiments # Experimental Setup To understand the properties of our proposed BiCNet and its performance, we conducted the experiments on the Star- Craft combats with different settings . Following similar ex- periment set-up as Sukhbaatar, Fergus, and others, BiCNet controls a group of agents trying to defeat the enemy units controlled by the built-in AI. The level of combat difficulties can be adjusted by vary- ing the unit types and the number of units in both sides. We measured the winning rates, and compared it with the state-of- the-art approaches. The comparative baselines consist of both the rule-based approaches, and deep reinforcement learning approaches. Our setting is summarised as follows where BiC- Net controls the former units and the built-in AI controls the latter. We categorize the settings into three types: 1) easy combats {3 Marines vs. 1 Super Zergling, and 3 Wraiths vs. 3 Mutalisks}; 2) hard combats {5 Marines vs. 5 Marines, 15 Marines vs. 16 Marines, 20 Marines vs. 30 Zerglings, 10 Marines vs. 13 Zerglings, and 15 Wraiths vs. 17 Wraiths.}; 3) heterogeneous combats { 2 Dropships and 2 Tanks vs. 1 Ultralisk }. The rule-based approaches allow us to have a reference point that we could make sense of. Here we adopted three rule-based baselines: StarCraft built-in AI, Attack the Weakest, Attack the Closest. For the deep reinforcement learning approaches, we con- sidered the following work as the baselines: Independent controller (IND): We trained the model for single agent and control each agent individually in the com- bats. Note that there is no information sharing among differ- ent agents even though such method is easily adaptable to all kinds of multiagent combats. Fully-connected (FC): We trained the model for all agents in a multiagent setting and control them collectively in the com- bats. The communication between agents are fully-connected. Note that it is needed to re-train a different model when the number of units at either side changes. CommNet: CommNet (Sukhbaatar, Fergus, and others 2016) is a multiagent network designed to learning to communicate among multiple agents. To make a fair comparison, we im- plemented both the CommNet and the BiCNet on the same (state, action) spaces and follow the same training processes. ‘mem batch size 16 um batch sive 32 mmm batch size 64 mm batch size 128 y = Winning Rate y =MeanQ 100 ale — lo Training Testing 200 300 400-=«500. «600700 x= Dataset X= Max Number of Episodes Figure 2: The impact of batch_size in combat 2 Marines vs. 1 Super Zergling. GMEZO: GreedyMDP with Episodic Zero-Order Optimisa- tion (GMEZO) (Usunier et al. 2016) was proposed particu- larly to solve StarCraft micromanagement tasks. Two novel ideas are introduced: conducting collaborations through a greedy update over MDP agents, as well as adding episodic noises in the parameter space for explorations. To focus on the comparison with these two ideas, we replaced our bi- directional formulation with the greedy MDP approach, and employed episodic zero-order optimisation with noise over the parameter space in the last layer of Q networks in our BiCNet. We keep the rest of the settings exactly the same. BiCNet: In BiCNet, we defined the action space differently from Sukhbaatar, Fergus, and others. Specifically, the ac- tion space of each individual agent is represented as a 3- dimensional real vector, i.e., continuous action space. The first dimension corresponds to the probability of attack, ac- cording to which we sample a value from [0,1]. If the sampled value is 1, then the agent attacks; otherwise, the agent moves. The second and the third dimension correspond to the degree and the distance of where to attack. With the above three quantities, BiCNet can precisely order an agent to attack a certain location. Note that this is different from executing high-level commands such as ‘attack enemy_id’, in other words, how to effectively output the damage is itself a form of intelligence. # Parameter Tuning In our training, Adam (Kingma and Ba 2014) is set as the optimiser with learning rate equal to 0.002 and the other arguments set by default values. We set the maximum steps of each episode as 800. We study the impact of the batch size and the results are shown in Figure 2 in the “2 Marines vs. 1 Super Zergling” combat. The two metrics, the winning rate and the Q value, are given. We fine-tune the batch_size by selecting the best BiCNet model which are trained on 800 episodes (more than 700k steps) and then tested on 100 independent games. The model with batch_size 32 achieves both the highest winning rate and the highest mean Q-value after 600k training steps. We also observed that skip frame 2 gave the highest mean Q-value between 300k and 600k training steps. We fix this parameter with the learned optimal value in the remaining part of our test. In Fig. 3, we also compare the convergence speed of pa- rameter learning by plotting the winning rate against the number of training episodes. It shows that the proposed BiC- Net model has a much quicker convergence than the two main StarCraft baselines. # Performance Comparison Table 1 compares our proposed BiCNet model against the baselines under multiple combat scenarios. In each scenario, Wining Rate Ss So S S eS & 8 & & & ° id — BiCNet CommNet - GMEZO e 0.0 20 40 60 80 100 120 140 160 Num. Episodes Figure 3: Learning Curves in Combat “10 Marines vs. 13 Zerglings” Table 1: Performance comparison. M: Marine, Z: Zergling, W: Wraith. Combat Rule Based RL Based Built-in Weakest Closest /TND FC GMEZO CommNet BiCNet 20M vs. 30Z |1.00 000 870 940 .00T 880 1.00 1.00 5 Mvs.5 M}.720 900 700 310 .080 .910 950 920 15 M vs. 16 M |.610 000 670 590 440 .630 680 710 10M vs. 13 Z |.550 230 410 522 430 .570 440 640 15 W vs. 17 W}.440 000 300 310 .460 420 470 530 BiCNet is trained over 100k steps, and we measure the per- formance as the average winning rate on 100 test games. The winning rate of the built-in AI is also provided as an indicator of the level of difficulty of the combats. As illustrated in Table 1, in 4/5 of the scenarios, BiCNet outperforms the other baseline models. In particular, when the number of agents goes beyond 10, where cohesive col- laborations are required, the margin of the performance gap between BiCNet and the second best starts to increase. In the combat “5 M vs. 5 M”, where the key factor to win is to “focus fire” on the weak, the IND and the FC models have relatively poorer performance. We believe it is because both of the models do not come with an explicit collaboration mechanism between agents in the training stage; coordinating the attacks towards one single enemy is even challenging. On the contrary, GMEZO, CommNet, and BiCNet, which are explicitly or implicitly designed for multiagent collaboration, can grasp and master this simple strategy, thus enjoying bet- ter performances. Furthermore, it is worth mentioning that despite the second best performance on “5 Marines vs. 5 Marines”, our BiCNet only needs 10 combats before learn- ing the idea of “focus fire”, and achieves over 85% win rate, whereas CommNet needs more than 50 episodes to grasp the skill of “focus fire” with a much lower winning rate. Note that the order of which side starts the first attack will influence the combat. This explains why in the combat “5 M vs. 5 M”, the built-in AI on the left (as the first to attack) has more advantages on the winning rate 0.720 over the built-in AI on the right, even though the number of marines at both sides is the same. # How It Works To further understand how BiCNet works, we conduct two more studies. We first examine whether a higher Q-value would represent a more optimal join actions among agents. Hidden states have high Q value - 100 Hidden states have low Q value Q Value Figure 4: Visualisation for 3 Marines vs. 1 Super Zergling combat. Upper Left: State with high Q value; Lower Left: State with low Q value; Right: Visualisation of hidden layer outputs for each step using TSNE, coloured by Q values. We visualise the model outputs when the coordinated cover at- tack is learned in Figure 4. The values in the last hidden layer of the critic network over 10k steps are collected and then em- beded in 2-dimensional space using t-SNE algorithm (Maaten and Hinton 2008). We observe that the steps with high Q- values are aggregated in the same area in the embedding space. For example, Figure 4 Upper Left shows that the agents attack the enemy in far distance when the enemy can- not attack the agents, and in this status, the model predicts high Q values. By contrast, in Figure 4 Lower Left, the agents suffer the damages from the enemy when it closes, which leads to low Q-values. Our next aim is to examine whether there is any semantic meaning of the information exchanged among agents be- fore their actions. However, due to the high variability of the StarCraft game, so far we have not observed any con- crete meaning yet. We instead only focus on bidirectioinal communications by considering a simpler game, where the sophistications that are not related to communications are removed. Specifically, this simpler game consists of n agents, At each round, each agent observes a randomly generated number (sampled in range [—10, 10] under truncated Gaus- sian) as its input, and nothing else. The goal for each agent is to output the sum over the inputs that all the agents observed. Each agent receives reward based on the difference between the sum and their prediction (action output). In the setting of three agents guessing the sum with one Bi-RNN communication layer (the hidden state size is 1) followed by a MLP layer, Figure 5 displays the values that have been transferred among three agents. As shown, Agent 1 passes a high value to Agent 2 when it observes a high ob- servation number. When Agent 2 communicates with Agent 3, it tends to output an “additive” value between its own and previously communicated agent, i.e., agent 1. In other words, the hidden state value is increasing when the sum of Agents 1 and 2’s observations goes high. Both senders have learned to make the other receiver obtain a helpful message in order to predict the target sum over all agents’ observations. We further set the game with num. of agents n = 5, 10, or 20. Apart from the four baselines tested previously, we also implement a supervised MLP with 10 hidden nodes as additional (predicting the sum based on the inputs given to agents). The results are compared in Table 2. The metric is the absolute value of the difference between each agent’s action and target. We see our method significantly outperform others. The second best is CommNet. Possible explanation is ‘Agent 2 Observation Figure 5: Left: The hidden state value passed by Agent | to Agent 2 in three agent guessing number game; Middle: The hidden state value passed by Agent | and Agent 2 to Agent 3 in three agent guessing number game; Right: Colour bar. Table 2: Performance comparison in the guessing game with different agent numbers. Results are given as average laction_value — target_value| in 10,000 testing steps and its standard deviation; A smaller value means a better per- formance. SL-MLP is a supervised MLP as an additional baseline. t-test is conducted, and the significant ones (p-value < 0.05) compared to the second best are marked as *. gent Number SL-MLP IND CommNet GMEZO BiCNet 5 2.824238 13.92£12.0 0.57£0.4T 5.92£7.62. *0.5250.51 10 4.3143.67 15.32+13.90 1.18+0.90 9.21+8.22 *0.97+0.91 20 6.7145.31 19.67414.61 3.8843.03 13.65£11.74 *3.1242.93 that it takes an average as the message, and thus naturally fits the problem, while ours have to learn the additives implicitly. Emerged Human-level Coordination With adequate trainings from scratch, BiCNet would be able to discover several effective collaboration strategies. In this section, we conduct a qualitative analysis on the learned col- laboration policies from BiCNet. We refer the demonstration video to the Supplementary Material and the experimental configurations to Section Experiments. Coordinated moves without collision. We observe that, in the initial stages of learning, in Fig. 6 (a) and (b), the agents move in a rather uncoordinated way. In particular, when two agents are close to each other, one agent often unintentionally blocks the other’s path. With the increasing rounds of train- ing (typically over 40k steps in near 50 episodes in the “3 (a) Early stage (b) Early stage (c) Well-trained (d) Well-trained of training of training Figure 6: Coordinated moves without collision in combat 3 Marines (ours) vs. 1 Super Zergling (enemy). The yellow line points out the direction each agent is going to move. gent Number SL-MLP IND CommNet GMEZO BiCNet 5 2.824238 13.92£12.0 0.57£0.4T 5.92£7.62. *0.5250.51 10 4.3143.67 15.32+13.90 1.18+0.90 9.21+8.22 *0.97+0.91 20 6.7145.31 19.67414.61 3.8843.03 13.65£11.74 *3.1242.93 (a) time step 1 (b) time step 2 (c) time step 3 (d) time step 4 Figure 7: Hit and Run tactics in combat 3 Marines (ours) vs. I Zealot (enemy). (a) time step 1 (b) time step 2 (c) time step 3 (d) time step 4 Figure 8: Coordinated cover attacks in combat 4 Dragoons (ours) vs. 1 Ultralisks (enemy) Marines vs. 1 Super Zergling” combat setting), the number of collisions reduces dramatically. Finally, when the training be- comes stable, the coordinated moves emerge, as illustrated in Fig. 6 (c) and (d). Such coordinated moves become important in large-scale combats as shown in Fig. 9 (a) and (b). Hit and Run tactics. For human players, a common tactic of controlling agents in StarCraft combat is Hit and Run, i.e., moving the agents away if they are under attack, and fighting back again when agents stay safe. We find that BiCNet can rapidly grasp the tactic of Hit and Run, either in the case of single agent or multiple agents settings. We illustrate four consecutive movements of Hit and Run in Fig. 7. Despite the simplicity, Hit and Run serves as the basis for more advanced and sophisticated collaboration tactics. Coordinated cover attack. Cover attack is a high-level collaborative strategy that is often used on the real battlefield. The essence of cover attack is to let one agent draw fire or attentions from the enemies, meanwhile, other agents take advantage of this time period or distance gap to output more harms. The difficulty of conducting cover attack lies in how to arrange the sequential moves of multiple agents in a coor- dinated hit and run way. As shown in Figs. 8, BiCNet can master it well. Starting from Fig. 8(a), BiCNet controls the bottom two Dragoons to run away from the enemy Ultralisk, while the one in the upper-right corner immediately starts to attack the enemy Ultralisk to cover them up. As a response, the enemy starts to attack the top one in time step 2. The bottom two Dragoons fight back and form another cover-up. By continuously looping this strategy over, the team of Dra- goons guarantees consecutive attack outputs to the enemy while minimising the team-level damages (because the en- emy wastes time in targeting different Dragoons) until the enemy is killed. Focus fire without overkill. As the number of agents in- creases, how to efficiently allocate the attacking resources becomes important. Neither scattering over all enemies nor focusing on one enemy (wasting attacking fires is also called overkill) are desired. We observe that BiCNet learns to con- trol each agent to focus their fires on particular enemies, and (a) time step 1 (b) time step 2 (c) timestep 3 (d) time step 4 Figure 9: focus fire” in combat /5 Marines (ours) vs. 16 Marines (enemy). (a) time step 1 (b) time step 2 Figure 10: Coordinated heterogeneous agents in combat 2 Dropships and 2 tanks vs. | Ultralisk. different agents tend to move to the sides to spread the fire and avoid overkill. An example could be found in Fig.(9) Collaborations between heterogeneous agents. In Star- Craft, there are tens of types of agent units, each with unique functionalities, action space, strength, and weakness. For combats with different types of units involved, we expect the agents to reach win-win situations through the collaborations. In fact, heterogeneous collaborations can be easily imple- mented in our framework by limiting the parameter sharing only to the same types of the units. In this paper, we study a simple case where two Dropships and two tanks collaborate to fight against an Ultralisk. A Dropship does not have the function to attack, but it can carry maximally two ground units in the air. As shown in Fig. 10, when the Ultralisk is attacking one of the tanks, the Dropship escorts the tank to escape from the attack. At the same time, the other Dropship unloads his tank to the ground so as to attack the Ultralisk. At each side, the collaboration between the Dropship and the tank keeps iterating until the Ultralisk is destroyed. Conclusions In this paper, we have introduced a new deep multiagent re- inforcement learning. The action is learned by constructing a vectorised actor-critic framework, where each dimension corresponds to an agent. The coordination is done by bi- directional recurrent communications in the internal layers. Through end-to-end learning, our BiCNet would be able to successfully learn several effective coordination strategies. Our experiments have demonstrated its ability to collaborate and master diverse combats in StarCraft combat games. We have also shown five human-level coordination strategies BiCNet could grasp from playing StarCraft combat games. Admittedly, quantifying the sophistication of the collabora- tions in games is challenging in general, and our analysis here is qualitative in nature. In the next step, we plan to carry on experiments of letting the machine compete with human players at different lev- els. We also plan to further investigate how the policies are communicated over the networks among agents in more com- plicated settings, and whether there is a specific language that may have emerged in StartCraft (Lazaridou, Peysakhovich, and Baroni 2016; Mordatch and Abbeel 2017). # References Brown and Sandholm 2017] Brown, N., and Sandholm, T. 2017. Safe and nested endgame solving for imperfect-information games. AAAI/AAI. Busoniu, Babuska, and De Schutter 2008] Busoniu, L.; Babuska, R.; and De Schutter, B. 2008. A comprehensive survey of multia- gent reinforcement learning. IEEE Transactions on Systems Man and Cybernetics Part C Applications and Reviews 38(2):156. Deboeck 1994] Deboeck, G. 1994. Trading on the edge: neural, genetic, and fuzzy systems for chaotic financial markets, volume 39. John Wiley & Sons. Foerster et al. 2016] Foerster, J.; Assael, Y. M.; de Freitas, N.; and Whiteson, S. 2016. Learning to communicate with deep multi-agent reinforcement learning. In NJPS, 2137-2145. Foerster et al. 2017a] Foerster, J.; Farquhar, G.; Afouras, T.; Nardelli, N.; and Whiteson, S. 2017a. Counterfactual multi-agent policy gradients. arXiv preprint arXiv:1705.08926. Foerster et al. 2017b] Foerster, J.; Nardelli, N.; Farquhar, G.; Torr, P.; Kohli, P.; Whiteson, S.; et al. 2017b. Stabilising experience replay for deep multi-agent reinforcement learning. arXiv preprint arXiv: 1702.08887. Goertzel and Pennachin 2007] Goertzel, B., and Pennachin, C. 2007. Artificial general intelligence, volume 2. Springer. He et al. 2016] He, H.; Boyd-Graber, J.; Kwok, K.; and Daumé III, H. 2016. Opponent modeling in deep reinforcement learning. In ICML, 1804-1813. Kapetanakis and Kudenko 2002] Kapetanakis, S., and Kudenko, D. 2002. Reinforcement learning of coordination in cooperative multi- agent systems. AAAJ/IAAI 2002:326-331. Kingma and Ba 2014] Kingma, D., and Ba, J. 2014. Adam: A method for stochastic optimization. arXiv preprint arXiv: 1412.6980. Lauer and Riedmiller 2000] Lauer, M., and Riedmiller, M. 2000. An algorithm for distributed reinforcement learning in cooperative multi-agent systems. In JCML. Lauer and Riedmiller 2004] Lauer, M., and Riedmiller, M. 2004. Reinforcement learning for stochastic cooperative multi-agent sys- tems. In AAMA. Lazaridou, Peysakhovich, and Baroni 2016] Lazaridou, A. Peysakhovich, A.; and Baroni, M. 2016. Multi-agent cooper- ation and the emergence of (natural) language. arXiv preprint arXiv:1612.07182. Lillicrap et al. 2015] Lillicrap, T. P.; Hunt, J. J.; Pritzel, A.; Heess, N.; Erez, T.; Tassa, Y.; Silver, D.; and Wierstra, D. 2015. Con- tinuous control with deep reinforcement learning. arXiv preprint arXiv: 1509.02971. Littman 1994] Littman, M. L. 1994. Markov games as a framework for multi-agent reinforcement learning. In JCML. Lowe et al. 2017] Lowe, R.; Wu, Y.; Tamar, A.; Harb, J.; Abbeel, P.; and Mordatch, I. 2017. Multi-agent actor-critic for mixed cooperative-competitive environments. arXiv preprint arXiv:1706.02275. Maaten and Hinton 2008] Maaten, L. v. d., and Hinton, G. 2008. Visualizing data using t-sne. Journal of Machine Learning Research 9(Nov):2579-2605. Mnih et al. 2015] Mnih, V.; Kavukcuoglu, K.; Silver, D.; Rusu, A. A.; Veness, J.; Bellemare, M. G.; Graves, A.; Riedmiller, M.; Fidjeland, A. K.; Ostrovski, G.; et al. 2015. Human-level control through deep reinforcement learning. Nature 518(7540):529-533. Mnih et al. 2016] Mnih, V.; Badia, A. P.; Mirza, M.; Graves, A.; Lillicrap, T. P.; Harley, Silver, D.; and Kavukcuoglu, K. 2016. Asynchronous methods for deep reinforcement learning. In Jnterna- tional Conference on Machine Learning. Mordatch and Abbeel 2017] Mordatch, I., and Abbeel, P. 2017. Emergence of grounded compositional language in multi-agent populations. arXiv preprint arXiv: 1703.04908. Owen 1995] Owen, G. 1995. Game theory. Academic Press. Schafer, Konstan, and Riedl 1999] Schafer, J. B.; Konstan, J.; and Riedl, J. 1999. Recommender systems in e-commerce. In ACM EC. Schmidhuber 1996] Schmidhuber, J. 1996. A general method for multi-agent reinforcement learning in unrestricted environments. In Adaptation, Coevolution and Learning in Multiagent Systems: Papers from the 1996 AAAI Spring Symposium, 84-87. Schuster and Paliwal 1997] Schuster, M., and Paliwal, K. K. 1997. Bidirectional recurrent neural networks. IEEE Transactions on Signal Processing 45(11):2673-2681. Silver et al. 2014] Silver, D.; Lever, G.; Heess, N.; Degris, T.; Wier- stra, D.; and Riedmiller, M. 2014. Deterministic policy gradient algorithms. In JCML. Silver et al. 2016] Silver, D.; Huang, A.; Maddison, C. J.; Guez, A.; Sifre, L.; Van Den Driessche, G.; Schrittwieser, J.; Antonoglou, L; Panneershelvam, V.; Lanctot, M.; et al. 2016. Mastering the game of go with deep neural networks and tree search. Nature 529(7587):484489. Spaan et al. 2002] Spaan, M. T.; Vlassis, N.; Groen, F. C.; et al. 2002. High level coordination of agents based on multiagent markov decision processes with roles. In JROS, volume 2, 66-73. Sukhbaatar, Fergus, and others 2016] Sukhbaatar, S.; Fergus, R.; etal. 2016. Learning multiagent communication with backpropaga- tion. In NIPS, 2244-2252. Sutton et al. 2000] Sutton, R. S.; McAllester, D. A.; Singh, S. P.; and Mansour, Y. 2000. Policy gradient methods for reinforcement learning with function approximation. In NPS, 1057-1063. Synnaeve et al. 2016] Synnaeve, G.; Nardelli, N.; Auvolat, A.; Chintala, S.; Lacroix, T.; Lin, Z.; Richoux, F.; and Usunier, N. 2016. Torchcraft: a library for machine learning research on real-time strategy games. arXiv preprint arXiv: 1611.00625. Usunier et al. 2016] Usunier, N.; Synnaeve, G.; Lin, Z.; and Chin- tala, S. 2016. Episodic exploration for deep deterministic policies: An application to starcraft micromanagement tasks. arXiv preprint arXiv:1609.02993. Vinyals et al. 2017] Vinyals, O.; Ewalds, T.; Bartunov, S.; Georgiev, P.; Vezhnevets, A. S.; Yeo, M.; Makhzani, A.; Kiittler, H.; Agapiou, J.; Schrittwieser, J.; et al. 2017. Starcraft ii: A new challenge for reinforcement learning. arXiv preprint arXiv: 1708.04782. Wang, Zhang, and Yuan 2017] Wang, J.; Zhang, W.; and Yuan, S. 2017. Display advertising with real-time bidding (RTB) and be- havioural targeting. Foundations and Trends in Information Re- trieval, Now Publishers. Werbos 1990] Werbos, P. J. 1990. Backpropagation through time: what it does and how to do it. Proceedings of the IEEE 78(10):1550- 1560. # Supplementary Material # Proof of Theorem 1 # Qi" (8, a)la=ao(s) Following the regularity conditions mentioned in (Silver et al. 2014), we know that the supreme of 0a; ,, ind # 0aio(s) for each agent 7 are bounded functions of s. Based on the regularity and the boundedness, we can use Leibniz integral # c rule and Fubini’s theorem, respectively. Note that as the policy ag and the transition matrix of the environment 7 are both considered deterministic, the expectation is only taken over the initial state sp, which is different from the original deterministic policy gradient theorem. According to the definition of Q?°(s, a) and the our objective function in Eq.(6), we derive the multiagent deterministic policy gradient theorem, which mostly follows the line of (Sutton et al. 2000). Ny “Be man JP) LO 008)) ) ad = [noZrere. ag(s))ds (10) Ny = [m9 % (nisavis)) + [ M(s! = Te (8) "(8 as!) ) ds dh # Ny = [ m6) (ee done ia} ds + [mw [a (“2 Fall = Tevs(Nlanm Do a(t) dsids + [me [aura a0.b, (8 1 eer s',a9(s’ ») ds'ds (12) Jag(s = [ m6) 30 Fon (S, a) |a—ay(s) +f L(s' = Ta», (8 ed s’,ag(s’)) | ds’ | ds —<$<$<—_ iterate as Eq.(10) to Eq.(11) = = ) Daal (s’) a L(s' = 0 ( nds’ 1 [LE rmente = Tes (00S goon a)jana,(s)ds'ds ( 4) [> (5)1(8' = Td, 48) as ) 2222 2S ae ds’ ( 5 sy Pr ag, by a0 das a=ag(s’) _ SE = pa, (s') 0ao(s’) Es pF ( (s) : Gaa(s) ay om sa Jla= a9 ( «| ( Ey. py, a> S Voaj,o(s) - Va;Q7*(s, aa(s))] ; ( i=1 j=l 2) where in Eq.(10) Leibniz intergal rule is used to exchange derivative and integral since Q?°(s, ag(s)) is continuous. For Eq.( 1), we used the definition of @-value. Then, we take derivatives for each term in Eq.(11) to get Eq.(12). Afterwards, we combine the first and the second term in Eq.(12) to get the first term in Eq.(13), while we notice that we can iterate Eq.(10) and Eq.(11) to expand the second term in Eq.(13). By summing up the iterated terms, we get Eq.(14), which implies Eq.(15) by using Fubini’s theorem to exchange the order of integration. Using the expectation to denote Eq.(15), we derive Eq.(16). Finally, we get Eq.(17) and the proof is done. ( 3) 5) 6) # Pseudocode # Algorithm 1 BiCNet algorithm Initialise actor network and critic network with € and 6 Initialise target network and critic network with £’ + € and 6’ + 6 iti replay buffer R des=1, E do e a random process U/ for action exploration receive initial observation state s+ for t=1, T do for each agent i, select and execute action at = aio(s*) +M receive reward [r/]_, and observe new state s’+? store transition {s‘, at, r4]¥_,, s‘+4} inR ; sample a random minibatch of M transitions {5%,,, [a%, ;. 1), Jha. 8nt) JY compute target value for each agent in each transition using the Bi-RNN: for m=1, M do , from R Qmi =Tmi + OE, (shit, ag’(s't)) for each agent i # end for compute critic gradient estimation according to Eq.(8): Ag= + S > (Qn. _ Qs (Sm ag(s ))) . VeQs (s ag(s »}: Mag , mem ™ miem m compute actor gradient estimation according to Eq.(7) and replace Q-value with the critic estimation: M N N 1 AO = 5 YI Y [Voaj.0(Sn) - Vay Q%y, (Sm: Ao(Sm))] m=1i=1 j=1 update the networks based on Adam using the above gradient estimators update the target networks: EH rEt (1-9 + (1-7) 0" end for end for
Title: Annotated History of Modern AI and Deep Learning: Summary: Machine learning is the science of credit assignment: finding patterns in observations that predict the consequences of actions and help to improve future performance. Credit assignment is also required for human understanding of how the world works, not only for individuals navigating daily life, but also for academic professionals like historians who interpret the present in light of past events. Here I focus on the history of modern artificial intelligence (AI) which is dominated by artificial neural networks (NNs) and deep learning, both conceptually closer to the old field of cybernetics than to what's been called AI since 1956 (e.g., expert systems and logic programming). A modern history of AI will emphasize breakthroughs outside of the focus of traditional AI text books, in particular, mathematical foundations of today's NNs such as the chain rule (1676), the first NNs (linear regression, circa 1800), and the first working deep learners (1965-). From the perspective of 2022, I provide a timeline of the -- in hindsight -- most important relevant events in the history of NNs, deep learning, AI, computer science, and mathematics in general, crediting those who laid foundations of the field. The text contains numerous hyperlinks to relevant overview sites from my AI Blog. It supplements my previous deep learning survey (2015) which provides hundreds of additional references. Finally, to round it off, I'll put things in a broader historic context spanning the time since the Big Bang until when the universe will be many times older than it is now. 5) and Gauss (1795, Cauchy (1676): . Jerpubished) first linear neural ad (1847): chain rule for — networks (NNs) / linear regression / y gradient backward 7 method of least squares / shallow descent (GD), credit ~ learning basic tool of assignment, ‘é, Famous example of pattern aA deep learning. central td recognition through shallow learning Robbins & ingredient of from astronomical data: re-discovery te Monro (1952): Stochastic GD 1F) learni of dwarf planet Ceres (Gauss, 1801) I Ising (1925): Rosenblatt (1958): Kelley AN 1st recurrent multilayer perceptron (MLP) y : o4, precursor of| network (only last layer learned: backprop in EL SCHMIDHUBER 2022! architecture: no deep learning yet) 7 control theory fi Lenz-lsing See also (compare f model (see als» v Turing (1948): Steinbuch (1961) Bryson,'61; sae McCulloch unpublished ideas Joseph (1961) Dreyfus,’62) * & Pitts, 1943, related to evolving recurrent NNs (RNNs d URAL NE fax P10 1979 A 16UU IN § Amari (1967-68): pa ay ukushima ¥ deep learning backpropagation (1979): deep ” by stochastic or reverse mode convolutional =e “ gradient descent of automatic neural net 4c . for deep MLPs differentiation architecture a | 1972: ist published 1969: rectified — (| Svea — learning RNN First applied linear units. representations i me based on Ising to NNs by [im Both now of input data d model (1925) Werbos (1982) __widely used Jürgen Schmidhuber, KAUST AII, Swiss AI Lab IDSIA, USI Pronounce: You_again Shmidhoobuh Technical Report IDSIA-22-22 (v2), IDSIA, 12/29/2022 https://people.idsia.ch/~juergen/deep-learning-history.html AI Blog @SchmidhuberAI juergen@idsia.ch arXiv:2212.11279 # Annotated History of Modern AI and Deep Learning Abstract. Machine learning (ML) is the science of credit assignment: finding patterns in observations that predict the consequences of actions and help to improve future performance. Credit assignment is also required for human understanding of how the world works, not only for individuals navigating daily life, but also for academic professionals like historians who interpret the present in light of past events. Here I focus on the history of modern artificial intelligence (AI) which is dominated by artificial neural networks (NNs) and deep learning,[DL1-4] both conceptually closer to the old field of cybernetics than to what's been called AI since 1956 (e.g., expert systems and logic programming). A modern history of AI will emphasize breakthroughs outside of the focus of traditional AI text books, in particular, mathematical foundations of today's NNs such as the chain rule (1676), the first NNs (linear regression, circa 1800), and the first working deep learners (1965-). From the perspective of 2022, I provide a timeline of the—in hindsight—most important relevant events in the history of NNs, deep learning, AI, computer science, and mathematics in general, crediting those who laid foundations of the field. The text contains numerous hyperlinks to relevant overview sites from my AI Blog. It also debunks certain popular but misleading historic accounts of deep learning, and supplements my previous deep learning survey[DL1] which provides hundreds of additional https://people.idsia.ch/~juergen/deep-learning-history.html # https://people.idsia.ch/~juergen/deep-learning-history.html 1/75 29/12/2022, 12:21 references. Finally, to round it off, I'll put things in a broader historic context spanning the time since the Big Bang until when the universe will be many times older than it is now. The present piece is also the draft of a chapter of my upcoming AI book. Disclaimer. Some say a history of deep learning should not be written by someone who has helped to shape it—"you are part of history not a historian."[CONN21] I cannot subscribe to that point of view. Since I seem to know more about deep learning history than others,[S20][DL3,DL3a][T22] [DL1-2] I consider it my duty to document and promote this knowledge, even if that seems to imply a conflict of interest, as it means prominently mentioning my own team's work, because (as of 2022) the most cited NNs are based on it.[MOST] Future AI historians may correct any era- specific potential bias. # Table of Contents Sec. 1: Introduction Sec. 2: 1676: The Chain Rule For Backward Credit Assignment Sec. 3: Circa 1800: First Neural Net (NN) / Linear Regression / Shallow Learning Sec. 4: 1920-1925: First Recurrent NN (RNN) Architecture. ~1972: First Learning RNNs Sec. 5: 1958: Multilayer Feedforward NN (without Deep Learning) Sec. 6: 1965: First Deep Learning Sec. 7: 1967-68: Deep Learning by Stochastic Gradient Descent Sec. 8: 1970: Backpropagation. 1982: For NNs. 1960: Precursor. Sec. 9: 1979: First Deep Convolutional NN (1969: Rectified Linear Units) Sec. 10: 1980s-90s: Graph NNs / Stochastic Delta Rule (Dropout) / More RNNs / Etc Sec. 11: Feb 1990: Generative Adversarial Networks / Artificial Curiosity / NN Online Planners Sec. 12: April 1990: NNs Learn to Generate Subgoals / Work on Command Sec. 13: March 1991: NNs Learn to Program NNs. Transformers with Linearized Self-Attention Sec. 14: April 1991: Deep Learning by Self-Supervised Pre-Training. Distilling NNs Sec. 15: June 1991: Fundamental Deep Learning Problem: Vanishing/Exploding Gradients Sec. 16: June 1991: Roots of Long Short-Term Memory / Highway Nets / ResNets Sec. 17: 1980s-: NNs for Learning to Act Without a Teacher Sec. 18: It's the Hardware, Stupid! Sec. 19: But Don't Neglect the Theory of AI (Since 1931) and Computer Science Sec. 20: The Broader Historic Context from Big Bang to Far Future Sec. 21: Acknowledgments Sec. 22: 555+ Partially Annotated References (many more in the award-winning survey[DL1]) # Introduction Over time, certain historic events have become more important in the eyes of certain beholders. For example, the Big Bang of 13.8 billion years ago is now widely considered an essential moment in the history of everything. Until a few decades ago, however, it has remained completely unknown to earthlings, who for a long time have entertained quite https://people.idsia.ch/~juergen/deep-learning-history.html 2/75 29/12/2022, 12:21 erroneous ideas about the origins of the universe (see the final section for more on the world's history). Currently accepted histories of many more limited subjects are results of similarly radical revisions. Here I will focus on the history of artificial intelligence (AI), which also isn't quite what it used to be. A history of AI written in the 1980s would have emphasized topics such as theorem proving, [GOD][GOD34][ZU48][NS56] logic programming, expert systems, and heuristic search.[FEI63,83][LEN83] This would be in line with topics of a 1956 conference in Dartmouth, where the term "AI" was coined by John McCarthy as a way of describing an old area of research seeing renewed interest. Practical AI dates back at least to 1914, when Leonardo Torres y Quevedo (see below) built the first working chess end game player[BRU1-4] (back then chess was considered as an activity restricted to the realms of intelligent creatures). AI theory dates back at least to 1931-34 when Kurt Gödel (see below) identified fundamental limits of any type of computation-based AI.[GOD] [BIB3][GOD21,a,b] A history of AI written in the early 2000s would have put more emphasis on topics such as support vector machines and kernel methods,[SVM1-4] Bayesian (actually Laplacian or possibly Saundersonian[STI83-85]) reasoning[BAY1-8][FI22] and other concepts of probability theory and statistics,[MM1-5][NIL98][RUS95] decision trees,e.g.,[MIT97] ensemble methods,[ENS1-4] swarm intelligence,[SW1] and evolutionary computation.[EVO1-7]([TUR1],unpublished) Why? Because back then such techniques drove many successful AI applications. A history of AI written in the 2020s must emphasize concepts such as the even older chain rule[LEI07] and deep nonlinear artificial neural networks (NNs) trained by gradient descent,[GD'] in particular, feedback-based recurrent networks, which are general computers whose programs are weight matrices.[AC90] Why? Because many of the most famous and most commercial recent AI applications depend on them.[DL4] Such NN concepts are actually conceptually close to topics of the MACY conferences (1946- 1953)[MACY51] and the 1951 Paris conference on calculating machines and human thought, now often viewed as the first conference on AI.[AI51][BRO21][BRU4] However, before 1956, much of what's now called AI was still called cybernetics, with a focus very much in line with modern AI based on "deep learning" with NNs.[DL1-2][DEC] Some of the past NN research was inspired by the human brain, which has on the order of 100 billion neurons, each connected to 10,000 other neurons on average. Some are input neurons that feed the rest with data (sound, vision, tactile, pain, hunger). Others are output neurons that control muscles. Most neurons are hidden in between, where thinking takes place. Your brain apparently learns by changing the strengths or weights of the connections, which determine how strongly neurons influence each other, and which seem to encode all your lifelong experience. Similar for our artifical NNs, which learn better than previous methods to recognize speech or handwriting or video, minimize pain, maximize pleasure, drive cars, etc. [MIR](Sec. 0)[DL1-4] How can NNs learn all of this? In what follows, I shall highlight essential historic contributions that made this possible. Since virtually all of the fundamental concepts of modern AI were derived in previous millennia, the section titles below emphasize developments only up to the year 2000. However, many of the sections mention the later impact of this work in the new https://people.idsia.ch/~juergen/deep-learning-history.html 3/75 29/12/2022, 12:21 millennium, which brought numerous improvements in hardware and software, a bit like the 20th century brought numerous improvements of the cars invented in the 19th. The present piece also debunks a frequently repeated, misleading "history of deep learning"[S20] [DL3,3a] which ignores most of the pioneering work mentioned below.[T22] See Footnote 6. The title image of the present article is a reaction to an erroneous piece of common knowledge which says[T19] that the use of NNs "as a tool to help computers recognize patterns and simulate human intelligence had been introduced in the 1980s," although such NNs appeared long before the 1980s.[T22] Ensuring proper credit assignment in all of science is of great importance to me—just as it should be to all scientists—and I encourage an interested reader to also take a look at some of my letters on this in Science and Nature, e.g., on the history of aviation,[NASC1- 2] the telephone,[NASC3] the computer,[NASC4-7] resilient robots,[NASC8] and scientists of the 19th century.[NASC9] Finally, to round it off, I'll put things in a broader historic context spanning the time since the Big Bang until when the universe will be many times older than it is now. # 1676: The Chain Rule For Backward Credit Assignment LEIBNIZ In 1676, Gottfried Wilhelm Leibniz published the chain rule of differential calculus in a memoir (albeit with a sign error of all things!); Guillaume de l'Hopital described it in his 1696 textbook on Leibniz' differential calculus.[LEI07-10][L84] Today, this rule is central for credit assignment in deep neural networks (NNs). Why? The most popular NNs have nodes or neurons that compute differentiable functions of inputs from other neurons, which in turn compute differentiable functions of inputs from other neurons, and so on. The question is: how will the output of the final function change if we modify the parameters or weights of an earlier function a bit? The chain rule is the basic tool for computing the answer. _ This answer is used by the technique of gradient descent (GD), apparently first proposed by Augustin-Louis Cauchy in 1847[GD'] (and much later by Jacques Hadamard[GD'']; the stochastic version called SGD is due to Herbert Robbins and Sutton Monro (1951)[STO51-52]). To teach an NN to translate input patterns from a training set into desired output patterns, all NN weights are iteratively changed a bit in the direction of the biggest local improvement, to create a slightly better NN, and so on, until a satisfactory solution is found. Footnote 1. In 1684, Leibniz was also the first to publish "modern" calculus;[L84][SON18][MAD05][LEI21,a,b] later Isaac Newton was also credited for his unpublished work.[SON18] Their priority dispute,[SON18] however, did not encompass the chain rule.[LEI07-10] Of course, both were building on earlier work: in the 2nd century B.C., Archimedes (perhaps the greatest scientist ever[ARC06]) https://people.idsia.ch/~juergen/deep-learning-history.html 4/75 29/12/2022, 12:21 paved the way for infinitesimals and published special cases of calculus, e.g., for spheres and parabola segments, building on even earlier work in ancient Greece. Fundamental work on calculus was also conducted in the 14th century by Madhava of Sangamagrama and colleagues of the Indian Kerala school.[MAD86-05] Footnote 2. Remarkably, Leibniz (1646-1714, aka "the world's first computer scientist"[LA14]) also laid foundations of modern computer science. He designed the first machine that could perform all four arithmetic operations (1673), and the first with an internal memory.[BL16] He described the principles of binary computers (1679)[L79][L03][LA14][HO66][LEI21,a,b] employed by virtually all modern machines. His formal Algebra of Thought (1686)[L86][WI48] was deductively equivalent[LE18] to the much later Boolean Algebra (1847).[BOO] His Characteristica Universalis & Calculus Ratiocinator aimed at answering all possible questions through computation;[WI48] his "Calculemus!" is one of the defining quotes of the age of enlightenment. It is quite remarkable that he is also responsible for the chain rule, foundation of "modern" deep learning, a key subfield of modern computer science. Footnote 3. Some claim that the backpropagation algorithm (discussed further down; now widely used to train deep NNs) is just the chain rule of Leibniz (1676) & L'Hopital (1696).[CONN21] No, it is the efficient way of applying the chain rule to big networks with differentiable nodes (there are also many inefficient ways of doing this).[T22] It was not published until 1970, as discussed below.[BP1,4,5] # ~1800: First NN / Linear Regression / Shallow Learning In 1805, Adrien-Marie Legendre published what's now often called a linear neural network (NN). Later Johann Carl Friedrich Gauss was also credited for earlier unpublished work on this done circa 1795.[STI81] This NN from over 2 centuries ago has two layers: an input layer with several input units, and an output layer. For simplicity, let's assume the latter consists of a single output unit. Each input unit can hold a real- valued number and is connected to the output by a connection with a real-valued weight. The NN's output is the sum of the products of the inputs and their weights. Given a training set of input vectors and desired target values for each of them, the NN weights are adjusted such that the sum of the squared errors between the NN outputs and the corresponding targets is minimized. LEGENDRE Of course, back then this was not called an NN. It was called the method of least squares, also widely known as linear regression. But it is mathematically identical to today's linear NNs: same basic algorithm, same error function, same adaptive parameters/weights. Such simple NNs perform "shallow learning" (as opposed to "deep learning" with many nonlinear layers). In fact, many NN courses start by introducing this method, then move on to more complex, deeper NNs. https://people.idsia.ch/~juergen/deep-learning-history.html 5/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks Perhaps the first famous example of pattern recognition through shallow learning dates back over 200 years: the re-discovery of the dwarf planet Ceres in 1801 through Gauss, who had data points from previous astronomical observations, then used various tricks to adjust the parameters of a predictor, which essentially learned to generalise from the training data to correctly predict the new location of Ceres. [eNUSS) Footnote 4. Today, students of all technical disciplines are required to take math classes, in particular, analysis, linear algebra, and statistics. In all of these fields, essential results and methods are (at least partially) due to Gauss: the fundamental theorem of algebra, Gauss elimination, the Gaussian distribution of statistics, etc. The so-called "greatest mathematician since antiquity" also pioneered differential geometry, number theory (his favorite subject), and non-Euclidean geometry. Furthermore, he made major contributions to astronomy and physics. Modern engineering including AI would be unthinkable without his results. Footnote 5. "Shallow learning" with NNs experienced a new wave of popularity in the late 1950s. Rosenblatt's perceptron (1958)[R58] combined a linear NN as above with an output threshold function to obtain a pattern classifier (compare his more advanced work on multi- layer networks discussed below). Joseph[R61] mentions an even earlier perceptron-like device by Farley & Clark. Widrow & Hoff's similar Adaline learned in 1962.[WID62] # 1920-1925: First Recurrent Network Architecture Like the human brain, but unlike the more limited feedforward NNs (FNNs), recurrent NNs (RNNs) have feedback connections, such that one can follow directed connections from certain internal nodes to others and eventually end up where one started. This is essential for implementing a memory of past events during sequence processing. The first non-learning RNN architecture (the Ising model or Lenz-Ising model) was introduced and analyzed by physicists Ernst Ising and Wilhelm Lenz in the 1920s.[L20][I24,I25][K41][W45][T22] It settles into an equilibrium state in response to input conditions, and is the foundation of the first learning RNNs (see below). Non-learning RNNs were also discussed in 1943 by neuroscientists Warren McCulloch und Walter Pitts[MC43] and formally analyzed in 1956 by Stephen Cole Kleene.[K56] ISING # ~1972: First Published Learning Artificial RNNs In 1972, Shun-Ichi Amari made the Lenz-Ising recurrent architecture adaptive such that it could learn to associate input patterns with output patterns by changing its connection weights.[AMH1] https://people.idsia.ch/~juergen/deep-learning-history.html 6/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks ie See also Stephen Grossberg's work on biological networks,[GRO69] David Marr's[MAR71] and Teuvo Kohonen's[KOH72] work, and Kaoru Nakano's learning RNN.[NAK72] 10 years later, the Amari network was republished (and its storage capacity analyzed). [AMH2] Some called it the Hopfield Network (!) or Amari-Hopfield Network.[AMH3] It does not process sequences but settles into an equilibrium in response to static input patterns. However, Amari (1972) also had a sequence-processing generalization thereof.[AMH1] Remarkably, already in 1948, Alan Turing wrote up ideas related to artificial evolution and learning RNNs. This, however, was first published many decades later, [TUR1] which explains the obscurity of his thoughts here.[TUR21] (Margin note: it has been pointed out that the famous "Turing Test" should actually be called the "Descartes Test."[TUR3,a,b][TUR21]) Today, the most popular RNN is the Long Short-Term Memory (LSTM) mentioned below, which has become the most cited NN of the 20th century.[MOST] # 1958: Multilayer Feedforward NN (without Deep Learning) In 1958, Frank Rosenblatt not only combined linear NNs and threshold functions (see the section on shallow learning since 1800), he also had more interesting, deeper multilayer perceptrons (MLPs).[R58] His MLPs had a non-learning first layer with randomized weights and an adaptive output layer. Although this was not yet deep learning, because only the last layer learned,[DL1] Rosenblatt basically had what much later was rebranded as Extreme Learning Machines (ELMs) without proper attribution.[ELM1-2][CONN21][T22] MLPs were also discussed in 1961 by Karl Steinbuch[ST61-95] and Roger David Joseph[R61] (1961). See also Oliver Selfridge's multilayer Pandemonium[SE59] (1959). Rosenblatt (1962) even wrote about "back-propagating errors" in an MLP with a hidden layer[R62] although he did not yet have a general deep learning algorithm for deep MLPs. What's now called backpropagation is quite different and was first published in 1970, as discussed below.[BP1-BP5][BPA-C] Today, the most popular FNN is a version of the LSTM-based Highway Net (mentioned below) called ResNet,[HW1-3] which has become the most cited NN of the 21st century.[MOST] https://people.idsia.ch/~juergen/deep-learning-history.html 7/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks # 1965: First Deep Learning Successful learning in deep feedforward network architectures started in 1965 in the Ukraine (back then the USSR) when Alexey Ivakhnenko & Valentin Lapa introduced the first general, working learning algorithms for deep MLPs with arbitrarily many hidden layers (already containing the now popular multiplicative gates).[DEEP1-2][DL1-2][FDL] A paper of 1971[DEEP2] already described a deep learning net with 8 layers, trained by their highly cited method which was still popular in the new millennium,[DL2] especially in Eastern Europe, where much of Machine Learning was born.[MIR](Sec. 1)[R8] Given a training set of input vectors with corresponding target output vectors, layers are incrementally grown and trained by regression analysis, then pruned with the help of a separate validation set, where regularisation is used to weed out superfluous units. The numbers of layers and units per layer are learned in problem-dependent fashion. page | Like later deep NNs, Ivakhnenko's nets learned to create hierarchical, distributed, internal representations of incoming data. He did not call them deep learning NNs, but that's what they were. In fact, the ancient term "deep learning" was first introduced to Machine Learning much later by Dechter (1986), and to NNs by Aizenberg et al (2000).[DL2] (Margin note: our 2005 paper on deep learning[DL6,6a] was the first machine learning publication with the word combination "learn deep" in the title.[T22]) # 1967-68: Deep Learning by Stochastic Gradient Descent Ivakhnenko and Lapa (1965, see above) trained their deep networks layer by layer. In 1967, however, Shun-Ichi Amari suggested to train MLPs with many layers in non-incremental end-to-end fashion from scratch by stochastic gradient descent (SGD),[GD1] a method proposed in 1951 by Robbins & Monro.[STO51-52] Amari's implementation[GD2,GD2a] (with his student Saito) learned internal representations in a five layer MLP with two modifiable layers, which was trained to classify non-linearily separable pattern classes. Back then compute was billions of times more expensive than today. ~ See also Iakov Zalmanovich Tsypkin's even earlier work on gradient descent-based on-line learning for non-linear systems.[GDa-b] Remarkably, as mentioned above, Amari also published learning RNNs in 1972.[AMH1] https://people.idsia.ch/~juergen/deep-learning-history.html # https://people.idsia.ch/~juergen/deep-learning-history.html 8/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks # 1970: Backpropagation. 1982: For NNs. 1960: Precursor. In 1970, Seppo Linnainmaa was the first to publish what's now known as backpropagation, the famous algorithm for credit assignment in networks of differentiable nodes,[BP1,4,5] also known as "reverse mode of automatic differentiation." It is now the foundation of widely used NN software packages such as PyTorch and Google's Tensorflow. In 1982, Paul Werbos proposed to use the method to train NNs,[BP2] extending ideas in his 1974 thesis. In 1960, Henry J. Kelley already had a precursor of backpropagation in the field of control theory;[BPA] see also later work of the early 1960s by Stuart Dreyfus and Arthur E. Bryson.[BPB][BPC][R7] Unlike Linnainmaa's general method,[BP1] the systems of the 1960s[BPA-C] backpropagated derivative information through standard Jacobian matrix calculations from one "stage" to the previous one, neither addressing direct links across several stages nor potential additional efficiency gains due to network sparsity. Backpropagation is essentially an efficient way of implementing Leibniz's chain rule[LEI07-10] (1676) (see above) for deep networks. Cauchy's gradient descent[GD'] uses this to incrementally weaken certain NN connections and strengthen others in the course of many trials, such that the NN behaves more and more like some teacher, which could be a human, or another NN,[UN-UN2] or something else. By 1985, compute had become about 1,000 times cheaper than in 1970, and the first desktop computers had just become accessible in wealthier academic labs. An experimental analysis of the known method[BP1-2] by David E. Rumelhart et al. then demonstrated that backpropagation can yield useful internal representations in hidden layers of NNs.[RUM] At least for supervised learning, backpropagation is generally more efficient than Amari's above-mentioned deep https://people.idsia.ch/~juergen/deep-learning-history.html 9/75 29/12/2022, 12:21 learning through the more general SGD method (1967), which learned useful internal representations in NNs about 2 decades earlier.[GD1-2a] It took 4 decades until the backpropagation method of 1970[BP1-2] got widely accepted as a training method for deep NNs. Before 2010, many thought that the training of NNs with many layers requires unsupervised pre-training, a methodology introduced by myself in 1991[UN][UN0-3] (see below), and later championed by others (2006).[UN4] In fact, it was claimed[VID1] that "nobody in their right mind would ever suggest" to apply plain backpropagation to deep NNs. However, in 2010, our team with my outstanding Romanian postdoc Dan Ciresan[MLP1-2] showed that deep FNNs can be trained by plain backpropagation and do not at all require unsupervised pre- training for important applications.[MLP2] Our system set a new performance record[MLP1] on the back then famous and widely used image recognition benchmark called MNIST. This was achieved by greatly accelerating deep FNNs on highly parallel graphics processing units called GPUs (as first done for shallow NNs with few layers by Jung & Oh in 2004[GPUNN]). A reviewer called this a "wake-up call to the machine learning community." Today, everybody in the field is pursuing this approach. Footnote 6. Unfortunately, several authors who re-published backpropagation in the 1980s did not cite the prior art—not even in later surveys.[T22] In fact, as mentioned in the introduction, there is a broader, frequently repeated, misleading "history of deep learning"[S20] which ignores most of the pioneering work mentioned in the previous sections.[T22][DLC] This "alternative history" essentially goes like this: "In 1969, Minsky & Papert[M69] showed that shallow NNs without hidden layers are very limited and the field was abandoned until a new generation of neural network researchers took a fresh look at the problem in the 1980s."[S20] However, the 1969 book[M69] addressed a "problem" of Gauss & Legendre's shallow learning (circa 1800)[DL1-2] that had already been solved 4 years prior by Ivakhnenko & Lapa's popular deep learning method,[DEEP1-2][DL2] and then also by Amari's SGD for MLPs.[GD1-2] Minsky neither cited this work nor corrected his book later.[HIN](Sec. I)[T22] And even recent papers promulgate this revisionist narrative of deep learning, apparently to glorify later contributions of their authors (such as the Boltzmann machine[BM][HIN][SK75][G63][T22]) without relating them to the original work,[DLC][S20][T22] although the true history is well-known. Deep learning research was alive and kicking in the https://people.idsia.ch/~juergen/deep-learning-history.html 10/75 29/12/2022, 12:21 1960s-70s, especially outside of the Anglosphere.[DEEP1-2][GD1-3][CNN1][DL1-2][T22] Blatant misattribution and unintentional[PLAG1][CONN21] or intentional[FAKE2] plagiarism are still tainting the entire field of deep learning.[T22] Scientific journals "need to make clearer and firmer commitments to self- correction,"[SV20] as is already the standard in other scientific fields. # 1979: First Deep Convolutional NN (1969: ReLUs) Computer Vision was revolutionized in the 2010s by a particular feedforward NN called the convolutional NN (CNN).[CNN1-4] The basic CNN architecture with alternating convolutional and downsampling layers is due to Kunihiko Fukushima (1979). He called it Neocognitron. [CNN1] Remarkably, already 10 years earlier, Fukushima also introduced rectified linear units (ReLUs) for NNs (1969).[RELU1] They are now widely used in CNNs and other NNs. In 1987, NNs with convolutions were combined by Alex Waibel with weight sharing and backpropagation (see above),[BP1-2] and applied to speech.[CNN1a] Waibel did not call this CNNs but TDNNs. FUKUSHIMA A popular downsampling variant called max-pooling was introduced by Yamaguchi et al. for TDNNs in 1990[CNN3a] and by Juan Weng et al. for higher-dimensional CNNs in 1993.[CNN3] Since 1989, Yann LeCun's team has contributed improvements of CNNs, especially for images.[CNN2,4][T22] Baldi and Chauvin (1993) had the first application of CNNs with backpropagation to biomedical/biometric images.[BA93] HISTORY.OF COMPUTER VISION C / (am 4 WON BY DEEP CONVOLUTIONAL NETS ON-GPU CNNs became more popular in the ML community much later in 2011 when my own team greatly sped up the training of deep CNNs (Dan Ciresan et al., 2011).[GPUCNN1,3,5] Our fast GPU- based[GPUNN][GPUCNN5] CNN of 2011[GPUCNN1] known as DanNet[DAN,DAN1][R6] was a practical https://people.idsia.ch/~juergen/deep-learning-history.html # https://people.idsia.ch/~juergen/deep-learning-history.html 11/75 29/12/2022, 12:21 breakthrough, much deeper and faster than earlier GPU-accelerated CNNs of 2006.[GPUCNN] In 2011, DanNet became the first pure deep CNN to win computer vision contests.[GPUCNN2-3,5] Competition[GPUCNN5] ICDAR 2011 Chinese handwriting May 15, 2011 variable Aug 06, 2011 variable IJCNN 2011 traffic signs Mar 01, 2012 512x512 ISBI 2012 image segmentation Sep 10, 2012 2048x2048x3 8.9% ICPR 2012 medical imaging Sep 30, 2012 256x256x3 ImageNet 2012 41.4% Sep 08, 2013 2048x2048x3 26.5% MICCAI 2013 Grand Challenge Aug 18, 2014 256x256x3 ImageNet 2014 Sep 30, 2015 256x256x3 ImageNet 2015 Date/Deadline Image size Improvement 3.8% / 28.9% 68.0% (superhuman) DanNet[DAN,DAN1][R6] 26.1% Winner DanNet[GPUCNN1-3] DanNet[GPUCNN3a] DanNet[GPUCNN8] AlexNet[GPUCNN4] DanNet[GPUCNN8] VGG Net[GPUCNN9] ResNet,[HW2] a Highway Net[HW1] with open gates 15.8% For a while, DanNet enjoyed a monopoly. From 2011 to 2012 it won every contest it entered, winning four of them in a row (15 May 2011, 6 Aug 2011, 1 Mar 2012, 10 Sep 2012).[GPUCNN5] In particular, at IJCNN 2011 in Silicon Valley, DanNet blew away the competition and achieved the first superhuman visual pattern recognition[DAN1] in an international contest. DanNet was also the first deep CNN to win: a Chinese handwriting contest (ICDAR 2011), an image segmentation contest (ISBI, May 2012), a contest on object detection in large images (ICPR, 10 Sept 2012), and— at the same time—a medical imaging contest on cancer detection. [GPUCNN8] In 2010, we introduced DanNet to Arcelor Mittal, the world's largest steel producer, and were able to greatly improve steel defect detection.[ST] To the best of my knowledge, this was the first deep learning breakthrough in heavy industry. In July 2012, our CVPR paper on DanNet[GPUCNN3] hit the computer vision community. 5 months later, the similar GPU-accelerated AlexNet won the ImageNet[IM09] 2012 contest.[GPUCNN4-5][R6] Our CNN image scanners were 1000 times faster than previous methods.[SCAN] This attracted tremendous interest from the healthcare industry. Today IBM, Siemens, Google and many startups are pursuing this approach. The VGG network (ImageNet 2014 winner)[GPUCNN9] and other highly cited CNNs[RCNN1- 3] further extended the DanNet of 2011.[MIR](Sec. 19)[MOST] ResNet, the ImageNet 2015 winner[HW2] (Dec 2015) and currently the most cited NN,[MOST] is a version (with open gates) of our earlier Highway Net (May 2015).[HW1-3][R5] The Highway Net (see below) is actually the feedforward net version of our vanilla LSTM (see below).[LSTM2] It was the first working, really deep feedforward NN with hundreds of layers (previous NNs had at most a few tens of layers). # 1980s-90s: Graph NNs / Stochastic Delta Rule (Dropout) /... NNs with rapidly changing "fast weights" were introduced by v.d. Malsburg (1981) and others. [FAST,a,b] Deep learning architectures that can manipulate structured data such as graphs[T22] were proposed in 1987 by Pollack[PO87-90] and extended/improved by Sperduti, Goller, and Küchler in the early 1990s.[SP93-97][GOL][KU][T22] See also our graph NN-like, Transformer-like Fast Weight Programmers of 1991[FWP0-1][FWP6][FWP] which learn to continually rewrite mappings from https://people.idsia.ch/~juergen/deep-learning-history.html 12/75 29/12/2022, 12:21 inputs to outputs (addressed below), and the work of Baldi and colleagues.[BA96-03] Today, graph NNs are used in numerous applications. Werbos,[BP2][BPTT1] Williams,[BPTT2][CUB0-2] and others[ROB87][BPTT3][DL1] analyzed ways of implementing gradient descent[GD'][STO51-52][GDa-b][GD1-2a] in RNNs. Kohonen's self-organising maps became popular.[KOH82-89] The 80s and 90s also saw various proposals of biologically more plausible deep learning algorithms that—unlike backpropagation—are local in space and time.[BB2][NAN1-4][NHE][HEL] See overviews[MIR](Sec. 15, Sec. 17) and recent renewed interest in such methods.[NAN5][FWPMETA6][HIN22] In 1990, Hanson introduced the Stochastic Delta Rule, a stochastic way of training NNs by backpropagation. Decades later, a version of this became popular under the moniker "dropout."[Drop1-4][GPUCNN4] Many additional papers on NNs (including RNNs) were published in the 1980s and 90s—see the numerous references in the 2015 survey.[DL1] Here, however, we mostly limit ourselves to the—in hindsight—most essential ones, given the present (ephemeral?) perspective of 2022. # Feb 1990: Generative Adversarial Networks / Curiosity Generative Adversarial Networks (GANs) have become very popular.[MOST] They were first published in 1990 in Munich under the moniker Artificial Curiosity.[AC90-20][GAN1] Two dueling NNs (a probabilistic generator and a predictor) are trying to maximize each other's loss in a minimax game.[AC](Sec. 1) The generator (called the controller) generates probabilistic outputs (using stochastic units[AC90] like in the much later StyleGANs[GAN2]). The predictor (called the world model) sees the outputs of the controller and predicts environmental reactions to them. Using gradient descent, the predictor NN minimizes its error, while the generator NN tries to make outputs that maximize this error: one net's loss is the other net's gain.[AC90] (The world model can also be used for continual online action planning.[AC90][PLAN2-3][PLAN]) ” DRAWBACKS OF CURIOSITY RCE SUMS LAER 12aP # https://people.idsia.ch/~juergen/deep-learning-history.html https://people.idsia.ch/~juergen/deep-learning-history.html 13/75 29/12/2022, 12:21 4 years before a 2014 paper on GANs,[GAN1] my well-known 2010 survey[AC10] summarised the generative adversarial NNs of 1990 as follows: a "neural network as a predictive world model is used to maximize the controller's intrinsic reward, which is proportional to the model's prediction errors" (which are minimized). The 2014 GANs are an instance of this where the trials are very short (like in bandit problems) and the environment simply returns 1 or 0 depending on whether the controller's (or generator's) output is in a given set.[AC20][AC][T22](Sec. XVII) Other early adversarial machine learning settings[S59][H90] were very different—they neither involved unsupervised NNs nor were about modeling data nor used gradient descent.[AC20] PREDICTABILITY MINIMIZATION ARTIFICIAL CURIOSITY i JURGEN SCHMIDHUBER The 1990 principle has been widely used for exploration in Reinforcement Learning[SIN5][OUD13] [PAT17][BUR18] and for synthesis of realistic images,[GAN1,2] although the latter domain was recently taken over by Rombach et al.'s Latent Diffusion, another method published in Munich,[DIF1] building on Jarzynski's earlier work in physics from the previous millennium[DIF2] and more recent papers.[DIF3-5] In 1991, I published yet another ML method based on two adversarial NNs called Predictability Minimization for creating disentangled representations of partially redundant data, applied to images in 1996.[PM0-2][AC20][R2][MIR](Sec. 7) # April 1990: NNs Generate Subgoals / Work on Command Most NNs of recent centuries were dedicated to simple pattern recognition, not to high-level reasoning, which is now considered a remaining grand challenge.[LEC] The early 1990s, however, saw first exceptions: NNs that learn to decompose complex spatio-temporal observation sequences into compact but meaningful chunks[UN0-3] (see further below), and NN- based planners of hierarchical action sequences for compositional learning,[HRL0] as discussed next. This work injected concepts of traditional "symbolic" hierarchical AI[NS59][FU77] into end-to- end differentiable "sub-symbolic" NNs. https://people.idsia.ch/~juergen/deep-learning-history.html 14/75 29/12/2022, 12:21 In 1990, our NNs learned to generate hierarchical action plans with end-to-end differentiable NN-based subgoal generators for Hierarchical Reinforcement Learning (HRL).[HRL0] Soon afterwards, this was also done with recurrent NNs that learn to generate sequences of subgoals.[HRL1-2][PHD][MIR](Sec. 10) An RL machine gets extra command inputs of the form (start, goal). An evaluator NN learns to predict the current rewards/costs of going from start to goal. An (R)NN-based subgoal generator also sees (start, goal), and uses (copies of) the evaluator NN to learn by gradient descent a sequence of cost-minimising intermediate subgoals. The RL machine tries to use such subgoal sequences to achieve final goals. The system is learning action plans at multiple levels of abstraction and multiple time scales and solves (at least in principle) what recently (2022) has been called an "open problem."[LEC] Compare other NNs that have "worked on command" since April 1990, in particular, for learning selective attention,[ATT0-3] artificial curiosity and self-invented problems,[PP][PPa,1,2][AC] upside-down reinforcement learning[UDRL1-2] and its generalizations.[GGP] # March 1991: Transformers with Linearized Self-Attention Recently, Transformers[TR1] have been all the rage, e.g., generating human-sounding texts.[GPT3] Transformers with "linearized self-attention"[TR5-6] were first published in March 1991[FWP0-1][FWP6] [FWP] (apart from normalisation—see tweet of 2022 for 30-year anniversary). These so-called "Fast Weight Programmers" or "Fast Weight Controllers"[FWP0-1] separated storage and control like in traditional computers, but in an end-to-end-differentiable, adaptive, fully neural way (rather than in a hybrid fashion[PDA1-2][DNC]). The "self-attention" in standard Transformers[TR1-4] combines this with a projection and softmax (using attention terminology like the one I introduced in 1993[ATT][FWP2][R4]). 1991: NEURAL NETS LEARN TO PROGRAM NEURAL NETS WITH FAST WEIGHTS - THE OUTER PRODUCT VERSION IS A LINEAR TRANSFORMER 2021: NEW STUFF! Today's Transformers heavily use unsupervised pre-training[UN0-3] (see next section), another deep learning methodology first published in our Annus Mirabilis of 1990-1991.[MIR][MOST] The 1991 fast weight programmers also led to meta-learning self-referential NNs that can run their own weight change algorithm or learning algorithm on themselves, and improve it, and https://people.idsia.ch/~juergen/deep-learning-history.html 15/75 29/12/2022, 12:21 improve the way they improve it, and so on. This work since 1992[FWPMETA1-9][HO1] extended my 1987 diploma thesis,[META1] which introduced algorithms not just for learning but also for meta- learning or learning to learn,[META] to learn better learning algorithms through experience. This became very popular in the 2010s[DEC] when computers were a million times faster. # April 1991: Deep Learning by Self-Supervised Pre-Training Today's most powerful NNs tend to be very deep, that is, they have many layers of neurons or many subsequent computational stages.[MIR] Before the 1990s, however, gradient-based training did not work well for deep NNs, only for shallow ones[DL1-2] (but see a 1989 paper[MOZ]). This Deep Learning Problem was most obvious for recurrent NNs. Like the human brain, but unlike the more limited feedforward NNs (FNNs), RNNs have feedback connections. This makes RNNs powerful, general purpose, parallel-sequential computers that can process input sequences of arbitrary length (think of speech data or videos). RNNs can in principle implement any program that can run on your laptop or any other computer in existence. If we want to build an Artificial General Intelligence (AGI), then its underlying computational substrate must be something more like an RNN than an FNN as FNNs are fundamentally insufficient; RNNs and similar systems are to FNNs as general computers are to pocket calculators. In particular, unlike FNNs, RNNs can in principle deal with problems of arbitrary depth.[DL1] Before the 1990s, however, RNNs failed to learn deep problems in practice.[MIR](Sec. 0) To overcome this drawback through RNN-based "general deep learning," I built a self- supervised RNN hierarchy that learns representations at multiple levels of abstraction and multiple self-organizing time scales:[LEC] the Neural Sequence Chunker[UN0] or Neural History Compressor.[UN1] Each RNN tries to solve the pretext task of predicting its next input, sending only unexpected inputs (and therefore also targets) to the next RNN above. The resulting compressed sequence representations greatly facilitate downstream supervised deep learning such as sequence classification. Although computers back then were about a million times slower per dollar than today, by 1993, the Neural History Compressor above was able to solve previously unsolvable "very https://people.idsia.ch/~juergen/deep-learning-history.html # https://people.idsia.ch/~juergen/deep-learning-history.html 16/75 29/12/2022, 12:21 deep learning" tasks of depth > 1000[UN2] (requiring more than 1,000 subsequent computational stages—the more such stages, the deeper the learning). In 1993, we also published a continuous version of the Neural History Compressor.[UN3] (See also recent work on unsupervised NN-based abstraction.[OBJ1-5]) More than a decade after this work,[UN1] a similar unsupervised method for more limited feedforward NNs (FNNs) was published, facilitating supervised learning by unsupervised pre- training of stacks of FNNs called Deep Belief Networks (DBNs).[UN4] The 2006 justification was essentially the one I used in the early 1990s for my RNN stack: each higher level tries to reduce the description length (or negative log probability) of the data representation in the level below.[HIN][T22][MIR] # April 1991: Distilling one NN into another NN The hierarchical internal representations of the neural history compressor above can be collapsed into a single recurrent NN (RNN), using my NN distillation procedure of 1991.[UN0-1][MIR] Here the knowledge of a teacher NN is "distilled" into a student NN, by training the student NN to imitate the behavior of the teacher NN (while also re-training the student NN on previously learned skills such that it does not forget them). NN distillation was also republished many years later,[DIST2][MIR][HIN][T22] and is widely used today. Today, unsupervised pre-training is heavily used by Transformers[TR1-6] for natural language processing and other domains. Remarkably, Transformers with linearized self-attention were also first published[FWP0-6] in our Annus Mirabilis of 1990-1991,[MIR][MOST] together with unsupervised/self-supervised pre-training for deep learning.[UN0-3] See the previous section. # June 1991: Fundamental Problem: Vanishing Gradients 1991: SEPP HOCHREITER’S ANALYSIS OF THE \ Aa FUNDAMENTAL DEEP LEARNING PROBLEM d ||——— : de(t) de(t-q) i=l] [Pe (t-m))ll m= < (Il W Ilmax,,, {ll F'(Ner) Il})’ Deep learning is hard because of the Fundamental Deep Learning Problem identified and analyzed in 1991 by my first student Sepp Hochreiter in his diploma thesis which I had the pleasure to supervise.[VAN1] First he implemented the Neural History Compressor above but then did much more: he showed that deep NNs suffer from the now famous problem of vanishing or exploding gradients: in typical deep or recurrent networks, back- propagated error signals either shrink rapidly, or grow out of bounds. In both cases, learning fails (compare[VAN2]). This analysis led to basic principles of what's now called LSTM (see below). https://people.idsia.ch/~juergen/deep-learning-history.html 17/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks # June 1991: Roots of LSTM / Highway Nets / ResNets The Long Short-Term Memory (LSTM) recurrent neural network[LSTM1-6] overcomes the Fundamental Deep Learning Problem identified by Sepp in his above-mentioned 1991 diploma thesis,[VAN1] which I consider one of the most important documents in the history of machine learning. It also provided essential insights for overcoming the problem, through basic principles (such as constant error flow) of what we called LSTM in a tech report of 1995.[LSTM0] After the main peer-reviewed publication in 1997[LSTM1][25y97] (now the most cited NN article of the 20th century[MOST]), LSTM and its training procedures were further improved on my Swiss LSTM grants at IDSIA through the work of my later students Felix Gers, Alex Graves, and others. A milestone was the "vanilla LSTM architecture" with forget gate[LSTM2]—the LSTM variant of 1999-2000 that everybody is using today, e.g., in Google's Tensorflow. Alex was lead author of our first successful application of LSTM to speech (2004).[LSTM10] 2005 saw the first publication of LSTM with full backpropagation through time and of bi-directional LSTM[LSTM3] (now widely used). Another milestone of 2006 was the training method "Connectionist Temporal Classification" or CTC[CTC] for simultaneous alignment and recognition of sequences. Our team successfully applied CTC-trained LSTM to speech in 2007[LSTM4] (also with hierarchical LSTM stacks[LSTM14]). This led to the first superior end-to-end neural speech recognition. It was very different from hybrid methods since the late 1980s which combined NNs and traditional approaches such as Hidden Markov Models (HMMs).[BW][BRI][BOU][HYB12][T22] In 2009, through the efforts of Alex, LSTM https://people.idsia.ch/~juergen/deep-learning-history.html 18/75 29/12/2022, 12:21 trained by CTC became the first RNN to win international competitions, namely, three ICDAR 2009 Connected Handwriting Competitions (French, Farsi, Arabic). This attracted enormous interest from industry. LSTM was soon used for everything that involves sequential data such as speech[LSTM10-11][LSTM4][DL1] and videos. In 2015, the CTC-LSTM combination dramatically improved Google's speech recognition on the Android smartphones.[GSR15] Many other companies adopted this.[DL4] Google's new on-device speech recognition of 2019 (now on your phone, not on the server) is still based on LSTM. # 1995: Neural Probabilistic Language Model The first superior end-to-end neural machine translation was also based on LSTM. In 1995, we already had an excellent neural probabilistic text model[SNT] whose basic concepts were reused in 2003[NPM][T22]—see also Pollack's earlier work on embeddings of words and other structures[PO87][PO90] as well as Nakamura and Shikano's 1989 word category prediction model. [NPMa] In 2001, we showed that LSTM can learn languages unlearnable by traditional models such as HMMs,[LSTM13] i.e., a neural "subsymbolic" model suddenly excelled at learning "symbolic" tasks. Compute still had to get 1000 times cheaper, but by 2016, Google Translate[GT16]—whose whitepaper[WU] mentions LSTM over 50 times—was based on two connected LSTMs,[S2S] one for incoming texts, and one for outgoing translations—much better than what existed before.[DL4] By 2017, LSTM also powered Facebook's machine translation (over 30 billion translations per week—the most popular youtube video needed years to achieve only 10 billion clicks),[FB17][DL4] Apple's Quicktype on roughly 1 billion iPhones,[DL4] the voice of Amazon's Alexa,[DL4] Google's image caption generation[DL4] & automatic email answering[DL4] etc. Business Week called LSTM "arguably the most commercial AI achievement."[AV1] By 2016, more than a quarter of the awesome computational power for inference in Google's datacenters was used for LSTM (and 5% for another popular Deep Learning technique called CNNs—see above).[JOU17] And of course, our LSTM is also massively used in healthcare and medical diagnosis—a simple Google Scholar search turns up innumerable medical articles that have "LSTM" in their title.[DEC] HIGHWAY NETWORKS: FIRST NEURA ~ ry ty a Et ¥e ei -1 () ! R10 AY AY 4 BAS t | vi oe a = aL 4a" caembecoi/ =i ei _ = aS, Jes . cre pont | em - es Nee et - — — nia : ——| Through the work of my students Rupesh Kumar Srivastava and Klaus Greff, the LSTM principle also led to our Highway Network[HW1] of May 2015, the first working very deep FNN with hundreds of layers (previous NNs had at most a few tens of layers). Microsoft's https://people.idsia.ch/~juergen/deep-learning-history.html 19/75 29/12/2022, 12:21 ResNet[HW2] (which won the ImageNet 2015 contest) is a version thereof (ResNets are Highway Nets whose gates are always open). The earlier Highway Nets perform roughly as well as their ResNet versions on ImageNet.[HW3] Variants of highway gates are also used for certain algorithmic tasks where the pure residual layers do not work as well.[NDR] # The LSTM / Highway Net Principle is the Core of Modern Deep Learning Deep learning is all about NN depth.[DL1] In the 1990s, LSTMs brought essentially unlimited depth to supervised recurrent NNs; in the 2000s, the LSTM-inspired Highway Nets brought it to feedforward NNs. LSTM has become the most cited NN of the 20th century; the Highway Net version called ResNet the most cited NN of the 21st.[MOST] (Citations, however, are a highly questionable measure of true impact.[NAT1]) # 1980s-: NNs for Learning to Act Without a Teacher The previous sections have mostly focused on deep learning for passive pattern recognition/classification. However, NNs are also relevant for Reinforcement Learning (RL), [KAE96][BER96][TD3][UNI][GM3][LSTMPG] the most general type of learning. General RL agents must discover, without the aid of a teacher, how to interact with a dynamic, initially unknown, partially observable environment in order to maximize their expected cumulative reward signals.[DL1] There may be arbitrary, a priori unknown delays between actions and perceivable consequences. The RL problem is as hard as any problem of computer science, since any task with a computable description can be formulated in the general RL framework.[UNI] Certain RL problems can be addressed through non-neural techniques invented long before the 1980s: Monte Carlo (tree) search (MC, 1949),[MOC1-5] dynamic programming (DP, 1953),[BEL53] artificial evolution (1954),[EVO1-7]([TUR1],unpublished) alpha-beta-pruning (1959),[S59] control theory and system identification (1950s),[KAL59][GLA85] stochastic gradient descent (SGD, 1951),[STO51-52] and universal search techniques (1973).[AIT7] Deep FNNs and RNNs, however, are useful tools for improving certain types of RL. In the 1980s, concepts of function approximation and NNs were combined with system identification, [WER87-89][MUN87][NGU89] DP and its online variant called Temporal Differences (TD),[TD1-3] artificial evolution,[EVONN1-3] and policy gradients.[GD1][PG1-3] Many additional references on this can be found in Sec. 6 of the 2015 survey.[DL1] When there is a Markovian interface[PLAN3] to the environment such that the current input to the RL machine conveys all the information required to determine a next optimal action, RL with DP/TD/MC-based FNNs can be very successful, as shown in 1994[TD2] (master-level backgammon player) and the 2010s[DM1-2a] (superhuman players for Go, chess, and other games). For more complex cases without Markovian interfaces, where the learning machine must consider not only the present input, but also the history of previous inputs, our combinations of RL algorithms and LSTM[LSTM-RL][RPG] have become standard, in particular, our LSTM trained by policy gradients (2007).[RPG07][RPG][LSTMPG] https://people.idsia.ch/~juergen/deep-learning-history.html 20/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks = 2010 DEEP REINFORCEMENT. LEARNING | ee WITH POLICY GRADIENTS FOR LSTM RTSIERM MEMORY, . "7 »- - — 73 - Werstray ea Schmidhuber, 2070: Recurrent policy graces 3 tiga Journal of the IGPL, 18(5), 620-6 For example, in 2018, a PG-trained LSTM was the core of OpenAI's famous Dactyl which learned to control a dextrous robot hand without a teacher.[OAI1][OAI1a] Similar for video games: in 2019, DeepMind (co-founded by a student from my lab) famously beat a pro player in the game of Starcraft, which is theoretically harder than Chess or Go[DM2] in many ways, using Alphastar whose brain has a deep LSTM core trained by PG.[DM3] An RL LSTM (with 84% of the model's total parameter count) also was the core of the famous OpenAI Five which learned to defeat human experts in the Dota 2 video game (2018).[OAI2] Bill Gates called this a "huge milestone in advancing artificial intelligence".[OAI2a][MIR](Sec. 4)[LSTMPG] The future of RL will be about learning/composing/planning with compact spatio-temporal abstractions of complex input streams—about commonsense reasoning[MAR15] and learning to think.[PLAN4-5] How can NNs learn to represent percepts and action plans in a hierarchical manner, at multiple levels of abstraction, and multiple time scales?[LEC] We published answers to these questions in 1990-91: self-supervised neural history compressors[UN][UN0-3] learn to represent percepts at multiple levels of abstraction and multiple time scales (see above), while end-to-end differentiable NN-based subgoal generators[HRL3][MIR](Sec. 10) learn hierarchical action plans through gradient descent (see above). More sophisticated ways of learning to think in abstract ways were published in 1997[AC97][AC99][AC02] and 2015-18.[PLAN4-5] # It's the Hardware, Stupid! The recent breakthroughs of deep learning algorithms from the past millennium (see previous sections) would have been impossible without continually improving and accelerating computer hardware. Any history of AI and deep learning would be incomplete without mentioning this evolution, which has been running for at least two millennia. The first known gear-based computational device was the Antikythera mechanism (a kind of astronomical clock) in Ancient Greece over 2000 years ago. Perhaps the world's first practical programmable machine was an automatic theatre made in the 1st century[SHA7a][RAU1] by Heron of Alexandria (who apparently also had the first known https://people.idsia.ch/~juergen/deep-learning-history.html # https://people.idsia.ch/~juergen/deep-learning-history.html 21/75 29/12/2022, 12:21 working steam engine—the Aeolipile). Annotated history of modern AI and deep neural networks —- press HIGHLIGHTS OF COMPUTER HISTORY 1st century BC: first known AD 60: programmable "1600s: input data! 1623: first os 1640: Pascal's superior Pascaline for simple arithmetics gear-based calculator in Antikythera automaton by Heron input-processing calculator by Schickard 1914: Torres y Quevedo, the pioneer of 1670s: Leibniz 1st computer scientist? 1800: first commercial program-controlled 1830s: Lovelace & Babbage’s ideas _— practical Al, builds a working chess end 1st machine with memory. Principles of machines (looms) by Jacquard et al. First on programs for general computers, game player - chess was considered binary computers. Algebra of Thought. industrial programmers: software on puncheards albeit unrealized an intelligent activi \ i di 1935: Church extends Godel's result 1931: Theoretical computer science founded by Gadel. to Entscheidungsproblem (decision 1936: Zuse’s patent application. First universal coding language. Exhibits the fundamental problem). 1936: Turing, too. Later 1941: First working programmable got 10 times cheaper. limits of math & theorem proving & Al & comune. 20: helps to break Enigma code. general-purpose computer The 9th century music automaton by the Banu Musa brothers in Baghdad was perhaps the first machine with a stored program.[BAN][KOE1] It used pins on a revolving cylinder to store programs controlling a steam-driven flute—compare Al-Jazari's programmable drum machine of 1206. [SHA7b] 2021: 375TH BIRTHDAY OF LEIBNIZ FOUNDER OF COMPUTER SCIENCE The 1600s brought more flexible machines that computed answers in response to input data. The first data-processing gear-based special purpose calculator for simple arithmetics was built in 1623 by Wilhelm Schickard, one of the candidates for the title of "father of automatic https://people.idsia.ch/~juergen/deep-learning-history.html 22/75 29/12/2022, 12:21 computing," followed by the superior Pascaline of Blaise Pascal (1642). In 1673, the already mentioned Gottfried Wilhelm Leibniz (called "the smartest man who ever lived"[SMO13]) designed the first machine (the step reckoner) that could perform all four arithmetic operations, and the first with a memory.[BL16] He also described the principles of binary computers governed by punch cards (1679),[L79][L03][LA14][HO66] and published the chain rule[LEI07-10] (see above), essential ingredient of deep learning and modern AI. The first commercial program-controlled machines (punch card-based looms) were built in France circa 1800 by Joseph-Marie Jacquard and others—perhaps the first "modern" programmers who wrote the world's first industrial software. They inspired Ada Lovelace and her mentor Charles Babbage (UK, circa 1840). He planned but was unable to build a programmable, general purpose computer (only his non-universal special purpose calculator led to a working 20th century replica). In 1914, the Spaniard Leonardo Torres y Quevedo (mentioned in the introduction) became the 20th century's first AI pioneer when he built the first working chess end game player (back then chess was considered as an activity restricted to the realms of intelligent creatures). The machine was still considered impressive decades later when another AI pioneer—Norbert Wiener[WI48]—played against it at the 1951 Paris AI conference.[AI51][BRO21][BRU4] és le : ys Between 1935 and 1941, Konrad Zuse created the world's first working programmable general-purpose computer: the Z3. The corresponding patent of 1936[ZU36-38][RO98] [ZUS21] described the digital circuits required by programmable physical hardware, predating Claude Shannon's 1937 thesis on digital circuit design.[SHA37] Unlike Babbage, Zuse used Leibniz' principles of binary computation (1679)[L79][LA14][HO66][L03] instead of traditional decimal computation. This greatly simplified the hardware.[LEI21,a,b] Ignoring the inevitable storage limitations of any physical computer, the physical hardware of Z3 was indeed universal in the modern sense of the purely theoretical but impractical constructs of Gödel[GOD][GOD34,21,21a] (1931- 34), Church[CHU] (1935), Turing[TUR] (1936), and Post[POS] (1936). Simple arithmetic tricks can compensate for Z3's lack of an explicit conditional jump instruction.[RO98] Today, most computers are binary like Z3. https://people.idsia.ch/~juergen/deep-learning-history.html 23/75 29/12/2022, 12:21 Z3 used electromagnetic relays with visibly moving switches. The first electronic special purpose calculator (whose moving parts were electrons too small to see) was the binary ABC (US, 1942) by John Atanasoff (the "father of tube-based computing"[NASC6a]). Unlike the gear- based machines of the 1600s, ABC used vaccum tubes—today's machines use the transistor principle patented by Julius Edgar Lilienfeld in 1925.[LIL1-2] But unlike Zuse's Z3, ABC was not freely programmable. Neither was the electronic Colossus machine by Tommy Flowers (UK, 1943-45) used to break the Nazi code.[NASC6] The first general working programmable machine built by someone other than Zuse (1941)[RO98] was Howard Aiken's decimal MARK I (US, 1944). The much faster decimal ENIAC by Eckert and Mauchly (1945/46) was programmed by rewiring it. Both data and programs were stored in electronic memory by the "Manchester baby" (Williams, Kilburn & Tootill, UK, 1948) and the 1948 upgrade of ENIAC, which was reprogrammed by entering numerical instruction codes into read-only memory.[HAI14b] Since then, computers have become much faster through integrated circuits (ICs). In 1949, Werner Jacobi at Siemens filed a patent for an IC semiconductor with several transistors on a common substrate (granted in 1952).[IC49-14] In 1958, Jack Kilby demonstrated an IC with external wires. In 1959, Robert Noyce presented a monolithic IC.[IC14] Since the 1970s, graphics processing units (GPUs) have been used to speed up computations through parallel processing. ICs/GPUs of today (2022) contain many billions of transistors (almost all of them of Lilienfeld's 1925 FET type[LIL1-2]). In 1941, Zuse's Z3 could perform roughly one elementary operation (e.g., an addition) per second. Since then, every 5 years, compute got 10 times cheaper (note that his law is much older than Moore's Law which states that the number of transistors[LIL1-2] per chip doubles every 18 months). As of 2021, 80 years after Z3, modern computers can execute about 10 million billion instructions per second for the same (inflation-adjusted) price. The naive extrapolation of this exponential trend predicts that the 21st century will see cheap computers with a thousand times the raw computational power of all human brains combined.[RAW] Where are the physical limits? According to Bremermann (1982),[BRE] a computer of 1 kg of mass and 1 liter of volume can execute at most 1051 operations per second on at most 1032 bits. The trend above will hit the Bremermann limit roughly 25 decades after Z3, circa 2200. However, since there are only 2 x 1030 kg of mass in the solar system, the trend is bound to break within a few centuries, since the speed of light will greatly limit the acquisition of additional mass, e.g., in form of other solar systems, through a function ploynomial in time, as previously noted back in 2004.[OOPS2][ZUS21] Physics seems to dictate that future efficient computational hardware will have to be brain-like, with many compactly placed processors in 3-dimensional space, sparsely connected by many short and few long wires, to minimize total connection cost (even if the "wires" are actually light beams).[DL2] The basic architecture is essentially the one of a deep, sparsely connected, 3- dimensional RNN, and Deep Learning methods for such RNNs are expected to become even much more important than they are today.[DL2] https://people.idsia.ch/~juergen/deep-learning-history.html 24/75 29/12/2022, 12:21 Annotated history of modern AI and deep neural networks # Don't Neglect the Theory of AI Since 1931 The core of modern AI and deep learning is mostly based on simple math of recent centuries: calculus/linear algebra/statistics. Nevertheless, to efficiently implement this core on the modern hardware mentioned in the previous section, and to roll it out for billions of people, lots of software engineering was necessary, based on lots of smart algorithms invented in the past century. There is no room here to mention them all. However, at least I'll list some of the most important highlights of the theory of AI and computer science in general. In the early 1930s, Gödel founded modern theoretical computer science.[GOD][GOD34][LEI21,21a] He introduced a universal coding language (1931-34).[GOD][GOD34-21a] It was based on the integers, and allows for formalizing the operations of any digital computer in axiomatic form. Gödel used it to represent both data (such as axioms and theorems) and programs[VAR13] (such as proof- generating sequences of operations on the data). He famously constructed formal statements that talk about the computation of other formal statements—especially self-referential statements which imply that they are not decidable, given a computational theorem prover that systematically enumerates all possible theorems from an enumerable set of axioms. Thus he identified fundamental limits of algorithmic theorem proving, computing, and any type of computation-based AI.[GOD][BIB3][MIR](Sec. 18)[GOD21,21a] Diya 575s ANNIVERSARY 1931: Py) eu) = ss UNDATIONS OF se S=(0.\) ©eMPUTER SCIENCE Like most great scientists, Gödel built on earlier work. He combined Georg Cantor's diagonalization trick[CAN] (which showed in 1891 that there are different types of infinities) with the foundational work by Gottlob Frege[FRE] (who introduced the first formal language in 1879), Thoralf Skolem[SKO23] (who introduced primitive recursive functions in 1923) and Jacques Herbrand[GOD86] (who identified limitations of Skolem's approach). These authors in turn built on the formal Algebra of Thought (1686) by Gottfried Wilhelm Leibniz[L86][WI48] (see above), which is deductively equivalent[LE18] to the later Boolean Algebra of 1847.[BOO] In 1935, Alonzo Church derived a corollary / extension of Gödel's result by demonstrating that Hilbert & Ackermann's Entscheidungsproblem (decision problem) does not have a general solution.[CHU] To do this, he used his alternative universal coding language called Untyped Lambda Calculus, which forms the basis of the highly influential programming language LISP. https://people.idsia.ch/~juergen/deep-learning-history.html # https://people.idsia.ch/~juergen/deep-learning-history.html 25/75 29/12/2022, 12:21 In 1936, Alan M. Turing introduced yet another universal model: the Turing Machine.[TUR] He rederived the above-mentioned result.[CHU][TUR][HIN][GOD21,21a][TUR21][LEI21,21a] In the same year of 1936, Emil Post published yet another independent universal model of computing.[POS] Today we know many such models. Konrad Zuse not only created the world's first working programmable general-purpose computer,[ZU36-38][RO98][ZUS21] he also designed Plankalkül, the first high-level programming language.[BAU][KNU] He applied it to chess in 1945[KNU] and to theorem proving in 1948.[ZU48] Compare Newell & Simon's later work on theorem proving (1956).[NS56] Much of early AI in the 1940s-70s was actually about theorem proving and deduction in Gödel style[GOD][GOD34,21,21a] through expert systems and logic programming. In 1964, Ray Solomonoff combined Bayesian (actually Laplacian[STI83-85]) probabilistic reasoning and theoretical computer science[GOD][CHU][TUR][POS] to derive a mathematically optimal (but computationally infeasible) way of learning to predict future data from past observations.[AIT1] [AIT10] With Andrej Kolmogorov, he founded the theory of Kolmogorov complexity or algorithmic information theory (AIT),[AIT1-22] going beyond traditional information theory[SHA48][KUL] by formalizing the concept of Occam's razor, which favors the simplest explanation of given data, through the concept of the shortest program computing the data. There are many computable, time-bounded versions of this concept,[AIT7][AIT5][AIT12-13][AIT16-17] as well as applications to NNs.[KO2] [CO1-3] In the early 2000s, Marcus Hutter (while working under my Swiss National Science Foundation grant[UNI]) augmented Solomonoff's universal predictor[AIT1][AIT10] by an optimal action selector (a universal AI) for reinforcement learning agents living in initially unknown (but at least computable) environments.[AIT20,22] He also derived the asymptotically fastest algorithm for all well-defined computational problems,[AIT21] solving any problem as quickly as the unknown fastest solver of such problems, save for an additive constant that does not depend on the problem size. The even more general optimality of the self-referential 2003 Gödel Machine[GM3-9] is not limited to asymptotic optimality. Nevertheless, such mathematically optimal AIs are not yet practically feasible for various reasons. Instead, practical modern AI is based on suboptimal, limited, yet not extremely well- understood techniques such as NNs and deep learning, the focus of the present article. But who knows what kind of AI history will prevail 20 years form now? # The Broader Historic Context from Big Bang to Far Future Credit assignment is about finding patterns in historic data and figuring out how certain events were enabled by previous events. Historians do it. Physicists do it. AIs do it, too. Let's take a step back and look at AI in the broadest historical context: all time since the Big Bang. In 2014, I found a beautiful pattern of exponential acceleration in it,[OMG] which I have presented in many talks since then, and which also made it into Sibylle Berg's award-winning book "GRM: https://people.idsia.ch/~juergen/deep-learning-history.html 26/75 29/12/2022, 12:21 Brainfuck."[OMG2] Previously published patterns of this kind span much shorter time intervals: just a few decades or centuries or at most millennia.[OMG1] It turns out that from a human perspective, the most important events since the beginning of the universe are neatly aligned on a timeline of exponential speed up (error bars mostly below 10 percent). In fact, history seems to converge in an Omega point in the year 2040 or so. I like to call it Omega, because a century ago, Teilhard de Chardin called Omega the point where humanity will reach its next level.[OMG0] Also, Omega sounds much better than "Singularity"[SING1- 2]—it sounds a bit like "Oh my God."[OMG] Let's start with the Big Bang 13.8 billion years ago. We divide this time by 4 to obtain about 3.5 billion years. Omega is 2040 or so. At Omega minus 3.5 billion years, something very important happened: life emerged on this planet. And we take again a quarter of this time. We come out 900 million years ago when something very important happened: animal-like, mobile life emerged. And we divide again by 4. We come out 220 million years ago when mammals were invented, our ancestors. And we divide again by 4. 55 million years ago the first primates emerged, our ancestors. And we divide again by 4. 13 million years ago the first hominids emerged, our ancestors. I don't know why all these divisions by 4 keep hitting these defining moments in history. But they do. I also tried thirds, and fifths, and harmonic proportions, but only quarters seem to work. And we divide again by 4. 3.5 million years ago something very important happened: the dawn of technology, as Nature called it: the first stone tools. And we divide by 4. 800 thousand years ago the next great tech breakthrough happened: controlled fire. Q = 2040 or so - 13.8 B years: Big Bang Q - 1/4 of this time: Q-3.5 B years: first life on Earth Q - 1/4 of this time: Q-0.9 8B years: first animal-like mobile life Q - 1/4 of this time: Q-220 M years: first mammals (our ancestors) Q - 1/4 of this time: Q-55 Myears: first primates (our ancestors) Q - 1/4 of this time: Q-13 M years: first hominids (our ancestors) 6. V4 ot ms wme: eo 35 iM years: first stone tools fnent big echt - of this time: - ears: controlled fire (next big tec! Q - 1/4 of this time: Q-210 K years: anatomically modern man Q - 1/4 of this time: Q-50 K years: behaviorally modern man Q - 1/4 of this time: Q-13 K years: neolithic revolution, civilization Q - 1/4 of this time: Q-3.3 K years: iron age, 1*' population explosion Q - 1/4 of this time: Q- 800 years: first guns & rockets (in China) Q - 1/4 of this time: OQ-200 years: industrial revolution Q - 1/4 of this time: Q-50 years (around 1990): information revolution, WWW, cell phones & PCs for all, Cold War ends, Modern Al starts, Miraculous Year ... Q - 1/4 of this time: Q-13 years (2030 or so): cheap Als with one human brain power? And then what? Q - 1/4 of this time: Q-3 years: ?? 3 Q- 1/4 of this time Q-9 months: 7??? 3 Q - 1/4 of this time: Q-2 months: 777722722 | Q - 1/4 of this time: Q-2 weeks: ?7777272222722772 .... 3 Finally multiply Q by 4! At the age of 55 B years, the visible cosmos will be permeated by intelligence. After ©, Als will have plenty of time to go where the physical resources are, to make more and bigger Als. And we divide by 4. 200 thousand years ago, anatomically modern man became prominent, our ancestor. And we divide by 4. 50 thousand years ago, behaviorally modern man emerged, our ancestor, and started colonizing the world. https://people.idsia.ch/~juergen/deep-learning-history.html 27/75 29/12/2022, 12:21 And we divide again by 4. We come out 13 thousand years ago when something very important happened: domestication of animals, agriculture, first settlements—the begin of civilisation. Now we see that all of civilization is just a flash in world history, just one millionth of the time since the Big Bang. Agriculture and spacecraft were invented almost at the same time. And we divide by 4. 3,300 years ago saw the onset of the 1st population explosion in the Iron Age. And we divide by 4. Remember that the convergence point Omega is the year 2040 or so. Omega minus 800 years—that was in the 13th century, when iron and fire came together in form of guns and cannons and rockets in China. This has defined the world since then and the West remains quite behind of the license fees it owes China. And we divide again by 4. Omega minus 200 years—we hit the mid 19th century, when iron and fire came together in ever more sophisticated form to power the industrial revolution through improved steam engines, based on the work of Beaumont, Papin, Newcomen, Watt, and others (1600s-1700s, going beyond the first simple steam engines by Heron of Alexandria[RAU1] in the 1st century). The telephone (e.g., Meucci 1857, Reis 1860, Bell 1876) [NASC3] started to revolutionize communication. The germ theory of disease (Pasteur & Koch, late 1800s) revolutionized healthcare and made people live longer on average. And circa 1850, the fertilizer-based agricultural revolution (Sprengel & von Liebig, early 1800s) helped to trigger the 2nd population explosion, which peaked in the 20th century, when the world population quadrupled, letting the 20th century stand out among all centuries in the history of mankind, driven by the Haber-Bosch process for creating artificial fertilizer, without which the world could feed at most 4 billion people.[HAB1-2] And we divide again by 4. Omega minus 50 years—that's more or less the year 1990, the end of the 3 great wars of the 20th century: WW1, WW2, and the Cold War. The 7 most valuable public companies were all Japanese (today most of them are US-based); however, both China and the US West Coast started to rise rapidly, setting the stage for the 21st century. A digital nervous system started spanning the globe through cell phones and the wireless revolution (based on radio waves discovered in the 1800s) as well as cheap personal computers for all. The WWW was created at the European particle collider in Switzerland by Tim Berners-Lee. And Modern AI started also around this time: the first truly self-driving cars were built in the 1980s in Munich by the team of Ernst Dickmanns (by 1994, their robot cars were driving in highway traffic, up to 180 km/h).[AUT] Back then, I worked on my 1987 diploma thesis,[META1] which introduced algorithms not just for learning but also for meta-learning or learning to learn, [META] to learn better learning algorithms through experience (now a very popular topic[DEC]). And then came our Miraculous Year 1990-91[MIR] at TU Munich, the root of today's most cited NNs[MOST] and of modern deep learning through self-supervised/unsupervised learning (see above),[UN][UN0-3] the LSTM/Highway Net/ResNet principle (now in your pocket on your smartphone—see above),[DL4][DEC][MOST] artificial curiosity and generative adversarial NNs for agents that invent their own problems (see above),[AC90-AC20][PP-PP2][SA17] Transformers with linearized self-attention (see above),[FWP0-6][TR5-6] distilling teacher NNs into student NNs (see above),[UN][UN0-3] learning action plans at multiple levels of abstraction and multiple time scales (see above),[HRL0-2][LEC] and other exciting stuff. Much of this has become very popular, and improved the lives of billions of people.[DL4][DEC][MOST] https://people.idsia.ch/~juergen/deep-learning-history.html 28/75 29/12/2022, 12:21 And we divide again by 4. Omega minus 13 years—that's a point in the near future, more or less the year 2030, when many predict that cheap AIs will have a human brain power. Then the final 13 years or so until Omega, when incredible things will happen (take all of this with a grain of salt, though[OMG1]). But of course, time won't stop with Omega. Maybe it's just human-dominated history that will end. After Omega, many curious meta-learning AIs that invent their own goals (which have existed in my lab for decades[AC][AC90,AC90b]) will quickly improve themselves, restricted only by the fundamental limits of computability and physics. What will supersmart AIs do? Space is hostile to humans but friendly to appropriately designed robots, and offers many more resources than our thin film of biosphere, which receives less than a billionth of the sun's energy. While some curious AIs will remain fascinated with life, at least as long as they don't fully understand it,[ACM16][FA15][SP16][SA17] most will be more interested in the incredible new opportunities for robots and software life out there in space. Through innumerable self-replicating robot factories in the asteroid belt and beyond they will transform the solar system and then within a few hundred thousand years the entire galaxy and within tens of billions of years the rest of the reachable universe. Despite the light-speed limit, the expanding AI sphere will have plenty of time to colonize and shape the entire visible cosmos. Let me stretch your mind a bit. The universe is still young, only 13.8 billion years old. Remember when we kept dividing by 4? Now let's multiply by 4! Let's look ahead to a time when the cosmos will be 4 times older than it is now: about 55 billion years old. By then, the visible cosmos will be permeated by intelligence. Because after Omega, most AIs will have to go where most of the physical resources are, to make more and bigger AIs. Those who don't won't have an impact.[ACM16][FA15][SP16] 1997: A COMPUTER SCIENTIST’S VIEW OF LIFE, THE UNIVERSE, AND EVERYTHING THE SIMPLEST AND.FASTEST- WAY OF COMPUTING ALL POSSIBLE COMPUTABLE METAVERSE ALGORITHMIC THEORY OF EVERYTHING YIELDS PHYSICAL, PHILOSOPHICAL, AND THEOLOGICAL CONSEQUENCES # Acknowledgments Some of the material above was taken from previous AI Blog posts.[MIR] [DEC] [GOD21] [ZUS21] [LEI21] [AUT] [HAB2] [ARC06] [AC] [ATT] [DAN] [DAN1] [DL4] [GPUCNN5,8] [DLC] [FDL] [FWP] [LEC] [META] [MLP2] [MOST] [PLAN] https://people.idsia.ch/~juergen/deep-learning-history.html 29/75 29/12/2022, 12:21 [UN] [LSTMPG] [BP4] [DL6a] [HIN] [T22] Thanks to many expert reviewers (including several famous neural net pioneers) for useful comments. Since science is about self-correction, let me know under juergen@idsia.ch if you can spot any remaining error. Many additional relevant publications can be found in my publication page and my arXiv page. This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. # 555+ References (and many more in the survey[DL1]) [25y97] In 2022, we are celebrating the following works from a quarter-century ago. 1. Journal paper on Long Short-Term Memory, the most cited neural network (NN) of the 20th century (and basis of the most cited NN of the 21st). 2. First paper on physical, philosophical and theological consequences of the simplest and fastest way of computing all possible metaverses (= computable universes). 3. Implementing artificial curiosity and creativity through generative adversarial agents that learn to design abstract, interesting computational experiments. 4. Journal paper on meta-reinforcement learning. 5. Journal paper on hierarchical Q-learning. 6. First paper on reinforcement learning to play soccer: start of a series. 7. Journal papers on flat minima & low-complexity NNs that generalize well. 8. Journal paper on Low- Complexity Art, the Minimal Art of the Information Age. 9. Journal paper on probabilistic incremental program evolution. [AC] J. Schmidhuber (AI Blog, 2021). 3 decades of artificial curiosity & creativity. Schmidhuber's artificial scientists not only answer given questions but also invent new questions. They achieve curiosity through: (1990) the principle of generative adversarial networks, (1991) neural nets that maximise learning progress, (1995) neural nets that maximise information gain (optimally since 2011), (1997) adversarial design of surprising computational experiments, (2006) maximizing compression progress like scientists/artists/comedians do, (2011) PowerPlay... Since 2012: applications to real robots. [AC90] J. Schmidhuber. Making the world differentiable: On using fully recurrent self- supervised neural networks for dynamic reinforcement learning and planning in non-stationary environments. Technical Report FKI-126-90, TUM, Feb 1990, revised Nov 1990. PDF. The first paper on online planning with reinforcement learning recurrent neural networks (NNs) (more) and on generative adversarial networks where a generator NN is fighting a predictor NN in a minimax game (more). [AC90b] J. Schmidhuber. A possibility for implementing curiosity and boredom in model- building neural controllers. In J. A. Meyer and S. W. Wilson, editors, Proc. of the International Conference on Simulation of Adaptive Behavior: From Animals to Animats, pages 222-227. MIT Press/Bradford Books, 1991. Based on [AC90]. PDF. More. [AC91] J. Schmidhuber. Adaptive confidence and adaptive curiosity. Technical Report FKI-149- 91, Inst. f. Informatik, Tech. Univ. Munich, April 1991. PDF. [AC91b] J. Schmidhuber. Curious model-building control systems. Proc. International Joint Conference on Neural Networks, Singapore, volume 2, pages 1458-1463. IEEE, 1991. PDF. https://people.idsia.ch/~juergen/deep-learning-history.html 30/75 29/12/2022, 12:21 [AC97] J. Schmidhuber. What's interesting? Technical Report IDSIA-35-97, IDSIA, July 1997. Focus on automatic creation of predictable internal abstractions of complex spatio-temporal events: two competing, intrinsically motivated agents agree on essentially arbitrary algorithmic experiments and bet on their possibly surprising (not yet predictable) outcomes in zero-sum games, each agent potentially profiting from outwitting / surprising the other by inventing experimental protocols where both modules disagree on the predicted outcome. The focus is on exploring the space of general algorithms (as opposed to traditional simple mappings from inputs to outputs); the general system focuses on the interesting things by losing interest in both predictable and unpredictable aspects of the world. Unlike Schmidhuber et al.'s previous systems with intrinsic motivation,[AC90-AC95] the system also takes into account the computational cost of learning new skills, learning when to learn and what to learn. See later publications.[AC99] [AC02] [AC98] M. Wiering and J. Schmidhuber. Efficient model-based exploration. In R. Pfeiffer, B. Blumberg, J. Meyer, S. W. Wilson, eds., From Animals to Animats 5: Proceedings of the Fifth International Conference on Simulation of Adaptive Behavior, p. 223-228, MIT Press, 1998. [AC98b] M. Wiering and J. Schmidhuber. Learning exploration policies with models. In Proc. CONALD, 1998. [AC99] J. Schmidhuber. Artificial Curiosity Based on Discovering Novel Algorithmic Predictability Through Coevolution. In P. Angeline, Z. Michalewicz, M. Schoenauer, X. Yao, Z. Zalzala, eds., Congress on Evolutionary Computation, p. 1612-1618, IEEE Press, Piscataway, NJ, 1999. [AC02] J. Schmidhuber. Exploring the Predictable. In Ghosh, S. Tsutsui, eds., Advances in Evolutionary Computing, p. 579-612, Springer, 2002. PDF. [AC06] J. Schmidhuber. Developmental Robotics, Optimal Artificial Curiosity, Creativity, Music, and the Fine Arts. Connection Science, 18(2): 173-187, 2006. PDF. [AC09] J. Schmidhuber. Art & science as by-products of the search for novel patterns, or data compressible in unknown yet learnable ways. In M. Botta (ed.), Et al. Edizioni, 2009, pp. 98- 112. PDF. (More on artificial scientists and artists.) [AC10] J. Schmidhuber. Formal Theory of Creativity, Fun, and Intrinsic Motivation (1990-2010). IEEE Transactions on Autonomous Mental Development, 2(3):230-247, 2010. IEEE link. PDF. With a brief summary of the generative adversarial neural networks of 1990[AC90,90b][AC20] where a generator NN is fighting a predictor NN in a minimax game (more). [AC20] J. Schmidhuber. Generative Adversarial Networks are Special Cases of Artificial Curiosity (1990) and also Closely Related to Predictability Minimization (1991). Neural Networks, Volume 127, p 58-66, 2020. Preprint arXiv/1906.04493. [ACM16] ACM interview by S. Ibaraki (2016). Chat with J. Schmidhuber: Artificial Intelligence & Deep Learning—Now & Future. Link. [AIB] J. Schmidhuber. AI Blog. Includes variants of chapters of the AI Book. https://people.idsia.ch/~juergen/deep-learning-history.html 31/75 29/12/2022, 12:21 [AI51] Les Machines a Calculer et la Pensee Humaine: Paris, 8.-13. Januar 1951, Colloques internationaux du Centre National de la Recherche Scientifique; no. 37, Paris 1953. H. Bruderer[BRU4] calls that the first conference on AI. [AIT1] R. J. Solomonoff. A formal theory of inductive inference. Part I. Information and Control, 7:1-22, 1964. [AIT2] A. N. Kolmogorov. Three approaches to the quantitative definition of information. Problems of Information Transmission, 1:1-11, 1965. [AIT3] G.J. Chaitin. On the length of programs for computing finite binary sequences: statistical considerations. Journal of the ACM, 16:145-159, 1969 (submitted 1965). [AIT4] P. Martin-Löf. The definition of random sequences. Information and Control, 9:602-619, 1966. [AIT5] C. S. Wallace and D. M. Boulton. An information theoretic measure for classification. Computer Journal, 11(2):185-194, 1968. [AIT6] A. K. Zvonkin and L. A. Levin. The complexity of finite objects and the algorithmic concepts of information and randomness. Russian Math. Surveys, 25(6):83-124, 1970. [AIT7] L. A. Levin. Universal sequential search problems. Problems of Information Transmission, 9(3):265-266, 1973. [AIT8] L. A. Levin. Laws of information (nongrowth) and aspects of the foundation of probability theory. Problems of Information Transmission, 10(3):206-210, 1974. [AIT9] C. P. Schnorr. Process complexity and effective random tests. Journal of Computer Systems Science, 7:376-388, 1973. [AIT10] R.J. Solomonoff. Complexity-based induction systems. IEEE Transactions on Information Theory, IT-24(5):422-432, 1978. [AIT11] P. Gacs. On the relation between descriptional complexity and algorithmic probability. Theoretical Computer Science, 22:71-93, 1983. [AIT12] J. Hartmanis. Generalized Kolmogorov complexity and the structure of feasible computations. Proc. 24th IEEE Symposium on Foundations of Computer Science, pages 439- 445, 1983. [AIT13] J. Rissanen. Stochastic complexity and modeling. The Annals of Statistics, 14(3):1080- 1100, 1986. [AIT14] Y. M. Barzdin. Algorithmic information theory. In D. Reidel, editor, Encyclopaedia of Mathematics, vol. 1, pages 140-142. Kluwer Academic Publishers, 1988. [AIT15] O. Watanabe. Kolmogorov complexity and computational complexity. EATCS Monographs on Theoretical Computer Science, Springer, 1992. https://people.idsia.ch/~juergen/deep-learning-history.html 32/75 29/12/2022, 12:21 [AIT16] M. Li and P. M. B. Vitanyi. An Introduction to Kolmogorov Complexity and its Applications (2nd edition). Springer, 1997. [AIT17] J. Schmidhuber. Discovering neural nets with low Kolmogorov complexity and high generalization capability. Neural Networks, 10(5):857-873, 1997. [AIT18] M. S. Burgin and Y. M. Borodyanskii. Infinite processes and super-recursive algorithms. Notices of the Academy of Sciences of the USSR (translated from Russian), 321(5):800-803, 1991. [AIT19] C. S. Calude. Chaitin Omega numbers, Solovay machines and Gödel incompleteness. Theoretical Computer Science, 2000. [AIT20] M. Hutter. A theory of universal artificial intelligence based on algorithmic complexity. Technical Report IDSIA-14-00 (cs.AI/0004001), IDSIA, Manno (Lugano), CH, 2000. [AIT21] M. Hutter. The fastest and shortest algorithm for all well-defined problems. International Journal of Foundations of Computer Science, 13(3):431-443, 2002. (Based on work done under J. Schmidhuber's SNF grant 20-61847: unification of universal induction and sequential decision theory, 2000). [AIT22] M. Hutter. Universal Artificial Intelligence: Sequential Decisions based on Algorithmic Probability. Springer, Berlin, 2004. (Based on work done under J. Schmidhuber's SNF grant 20-61847: unification of universal induction and sequential decision theory, 2000). [AIT23] J. Schmidhuber. Hierarchies of generalized Kolmogorov complexities and nonenumerable universal measures computable in the limit. International Journal of Foundations of Computer Science, 13(4):587-612, 2002. [AIT24] J. Schmidhuber. The Speed Prior: a new simplicity measure yielding near-optimal computable predictions. In J. Kivinen and R. H. Sloan, editors, Proceedings of the 15th Annual Conference on Computational Learning Theory (COLT 2002), Lecture Notes in Artificial Intelligence, pages 216-228. Springer, Sydney, Australia, 2002. [AM16] Blog of Werner Vogels, CTO of Amazon (Nov 2016): Amazon's Alexa "takes advantage of bidirectional long short-term memory (LSTM) networks using a massive amount of data to train models that convert letters to sounds and predict the intonation contour. This technology enables high naturalness, consistent intonation, and accurate processing of texts." [AMH0] S. I. Amari (1972). Characteristics of random nets of analog neuron-like elements. IEEE Trans. Syst. Man Cybernetics, 2, 643-657. First published 1969 in Japanese, long before Wilson & Cowan's very similar work (1972-73). [AMH1] S. I. Amari (1972). Learning patterns and pattern sequences by self-organizing nets of threshold elements. IEEE Transactions, C 21, 1197-1206, 1972. PDF. First publication of what was later sometimes called the Hopfield network[AMH2] or Amari-Hopfield Network,[AMH3] based on the (uncited) Lenz-Ising recurrent architecture.[L20][I25][T22] https://people.idsia.ch/~juergen/deep-learning-history.html 33/75 29/12/2022, 12:21 [AMH1b] W. A. Little. The existence of persistent states in the brain. Mathematical Biosciences, 19.1-2, p. 101-120, 1974. Mentions the recurrent Ising model[L20][I25]on which the (uncited) Amari network[AMH1,2] is based. [AMH2] J. J. Hopfield (1982). Neural networks and physical systems with emergent collective computational abilities. Proc. of the National Academy of Sciences, vol. 79, pages 2554-2558, 1982. The Hopfield network or Amari-Hopfield Network was first published in 1972 by Amari. [AMH1] [AMH2] did not cite [AMH1]. [AMH3] A. P. Millan, J. J. Torres, J. Marro. How Memory Conforms to Brain Development. Front. Comput. Neuroscience, 2019 [ARC06] J. Schmidhuber (2006). Archimedes—Greatest Scientist Ever? [ATT] J. Schmidhuber (AI Blog, 2020). 30-year anniversary of end-to-end differentiable sequential neural attention. Plus goal-conditional reinforcement learning. Schmidhuber had both hard attention for foveas (1990) and soft attention in form of Transformers with linearized self-attention (1991-93).[FWP] Today, both types are very popular. [ATT0] J. Schmidhuber and R. Huber. Learning to generate focus trajectories for attentive vision. Technical Report FKI-128-90, Institut für Informatik, Technische Universität München, 1990. PDF. [ATT1] J. Schmidhuber and R. Huber. Learning to generate artificial fovea trajectories for target detection. International Journal of Neural Systems, 2(1 & 2):135-141, 1991. Based on TR FKI- 128-90, TUM, 1990. PDF. More. [ATT2] J. Schmidhuber. Learning algorithms for networks with internal and external feedback. In D. S. Touretzky, J. L. Elman, T. J. Sejnowski, and G. E. Hinton, editors, Proc. of the 1990 Connectionist Models Summer School, pages 52-61. San Mateo, CA: Morgan Kaufmann, 1990. PS. (PDF.) [ATT3] H. Larochelle, G. E. Hinton. Learning to combine foveal glimpses with a third-order Boltzmann machine. NIPS 2010. This work is very similar to [ATT0-2] which the authors did not cite. In fact, Hinton was the reviewer of a 1990 paper[ATT2] which summarised in its Section 5 Schmidhuber's early work on attention: the first implemented neural system for combining glimpses that jointly trains a recognition & prediction component with an attentional component (the fixation controller). Two decades later, Hinton wrote about his own work:[ATT3] "To our knowledge, this is the first implemented system for combining glimpses that jointly trains a recognition component ... with an attentional component (the fixation controller)." See [MIR] (Sec. 9)[R4]. [ATT14] D. Bahdanau, K. Cho, Y. Bengio. Neural Machine Translation by Jointly Learning to Align and Translate. 2014-16. Preprint arXiv/1409.0473, 2014-16. This work on soft "attention" did not cite Schmidhuber's much earlier original work of 1991-1993 on soft attention and Transformers with linearized self-attention.[FWP,FWP0-2,6][ATT] [AUT] J. Schmidhuber (AI Blog, 2005). Highlights of robot car history. Around 1986, Ernst Dickmanns and his group at Univ. Bundeswehr Munich built the world's first real autonomous https://people.idsia.ch/~juergen/deep-learning-history.html 34/75 29/12/2022, 12:21 robot cars, using saccadic vision, probabilistic approaches such as Kalman filters, and parallel computers. By 1994, they were in highway traffic, at up to 180 km/h, automatically passing other cars. [AV1] A. Vance. Google Amazon and Facebook Owe Jürgen Schmidhuber a Fortune—This Man Is the Godfather the AI Community Wants to Forget. Business Week, Bloomberg, May 15, 2018. [BA93] P. Baldi and Y. Chauvin. Neural Networks for Fingerprint Recognition, Neural Computation, Vol. 5, 3, 402-418, (1993). First application of CNNs with backpropagation to biomedical/biometric images. [BA96] P. Baldi and Y. Chauvin. Hybrid Modeling, HMM/NN Architectures, and Protein Applications, Neural Computation, Vol. 8, 7, 1541-1565, (1996). One of the first papers on graph neural networks. [BA99] P. Baldi, S. Brunak, P. Frasconi, G. Soda, and G. Pollastri. Exploiting the Past and the Future in Protein Secondary Structure Prediction, Bioinformatics, Vol. 15, 11, 937-946, (1999). [BA03] P. Baldi and G. Pollastri. The Principled Design of Large-Scale Recursive Neural Network Architectures-DAG-RNNs and the Protein Structure Prediction Problem. Journal of Machine Learning Research, 4, 575-602, (2003). [BAN] Banu Musa brothers (9th century). The book of ingenious devices (Kitab al-hiyal). Translated by D. R. Hill (1979), Springer, p. 44, ISBN 90-277-0833-9. As far as we know, the Banu Musa music automaton was the world's first machine with a stored program. [BAU] F. L. Bauer, H. Woessner (1972). The "Plankalkül" of Konrad Zuse: A Forerunner of Today's Programming Languages. [BAY1] S. M. Stigler. Who Discovered Bayes' Theorem? The American Statistician. 37(4):290- 296, 1983. Bayes' theorem is actually Laplace's theorem or possibly Saunderson's theorem. [BAY2] T. Bayes. An essay toward solving a problem in the doctrine of chances. Philosophical Transactions of the Royal Society of London, 53:370-418. Communicated by R. Price, in a letter to J. Canton, 1763. [BAY3] D. J. C. MacKay. A practical Bayesian framework for backprop networks. Neural Computation, 4:448-472, 1992. [BAY4] J. Pearl. Probabilistic reasoning in intelligent systems: Networks of plausible inference. Synthese-Dordrecht 104(1):161, 1995. [BAY5] N. M. Oliver, B. Rosario, A. P. Pentland A Bayesian computer vision system for modeling human interactions. IEEE transactions on pattern analysis and machine intelligence 22.8:831-843, 2000. [BAY6] D. M. Blei, A. Y. Ng, M. I. Jordan. Latent Dirichlet Allocation. Journal of Machine Learning Research 3:993-1022, 2003. https://people.idsia.ch/~juergen/deep-learning-history.html 35/75 29/12/2022, 12:21 [BAY7] J. F. G. De Freitas. Bayesian methods for neural networks. PhD thesis, University of Cambridge, 2003. [BAY8] J. M. Bernardo, A.F.M. Smith. Bayesian theory. Vol. 405. John Wiley & Sons, 2009. [BB2] J. Schmidhuber. A local learning algorithm for dynamic feedforward and recurrent networks. Connection Science, 1(4):403-412, 1989. (The Neural Bucket Brigade—figures omitted!). PDF. HTML. Compare TR FKI-124-90, TUM, 1990. PDF. Proposal of a biologically more plausible deep learning algorithm that—unlike backpropagation—is local in space and time. Based on a "neural economy" for reinforcement learning. [BEL53] R. Bellman. An introduction to the theory of dynamic programming. RAND Corp. Report, 1953 [BIB3] W. Bibel (2003). Mosaiksteine einer Wissenschaft vom Geiste. Invited talk at the conference on AI and Gödel, Arnoldsheim, 4-6 April 2003. Manuscript, 2003. [BL16] L. Bloch (2016). Informatics in the light of some Leibniz's works. Communication to XB2 Berlin Xenobiology Conference. [BM] D. Ackley, G. Hinton, T. Sejnowski (1985). A Learning Algorithm for Boltzmann Machines. Cognitive Science, 9(1):147-169. This paper neither cited relevant prior work by Sherrington & Kirkpatrick[SK75] & Glauber[G63] nor the first working algorithms for deep learning of internal representations (Ivakhnenko & Lapa, 1965)[DEEP1-2][HIN] nor Amari's work (1967-68)[GD1-2] on learning internal representations in deep nets through stochastic gradient descent. Even later surveys by the authors[S20][DLC] failed to cite the prior art.[T22] [BER96] D. P. Bertsekas, J. N. Tsitsiklis. Neuro-dynamic Programming. Athena Scientific, Belmont, MA, 1996. [BOO] George Boole (1847). The Mathematical Analysis of Logic, Being an Essay towards a Calculus of Deductive Reasoning. London, England: Macmillan, Barclay, & Macmillan, 1847. Leibniz' formal Algebra of Thought (1686)[L86][WI48] was deductively equivalent[LE18] to the much later Boolean Algebra. [BOU] H Bourlard, N Morgan (1993). Connectionist speech recognition. Kluwer, 1993. [BPA] H. J. Kelley. Gradient Theory of Optimal Flight Paths. ARS Journal, Vol. 30, No. 10, pp. 947-954, 1960. Precursor of modern backpropagation.[BP1-5] [BPB] A. E. Bryson. A gradient method for optimizing multi-stage allocation processes. Proc. Harvard Univ. Symposium on digital computers and their applications, 1961. [BPC] S. E. Dreyfus. The numerical solution of variational problems. Journal of Mathematical Analysis and Applications, 5(1): 30-45, 1962. [BP1] S. Linnainmaa. The representation of the cumulative rounding error of an algorithm as a Taylor expansion of the local rounding errors. Master's Thesis (in Finnish), Univ. Helsinki, 1970. See chapters 6-7 and FORTRAN code on pages 58-60. PDF. See also BIT 16, 146-160, https://people.idsia.ch/~juergen/deep-learning-history.html 36/75 29/12/2022, 12:21 1976. Link. The first publication on "modern" backpropagation, also known as the reverse mode of automatic differentiation. [BP2] P. J. Werbos. Applications of advances in nonlinear sensitivity analysis. In R. Drenick, F. Kozin, (eds): System Modeling and Optimization: Proc. IFIP, Springer, 1982. PDF. First application of backpropagation[BP1] to NNs (concretizing thoughts in Werbos' 1974 thesis). [BP4] J. Schmidhuber (AI Blog, 2014; updated 2020). Who invented backpropagation? More. [DL2] [BP5] A. Griewank (2012). Who invented the reverse mode of differentiation? Documenta Mathematica, Extra Volume ISMP (2012): 389-400. [BPTT1] P. J. Werbos. Backpropagation through time: what it does and how to do it. Proceedings of the IEEE 78.10, 1550-1560, 1990. [BPTT2] R. J. Williams and D. Zipser. Gradient-based learning algorithms for recurrent networks. In: Backpropagation: Theory, architectures, and applications, p 433, 1995. [BPTT3] B. A. Pearlmutter. Gradient calculations for dynamic recurrent neural networks: A survey. IEEE Transactions on Neural Networks, 6(5):1212-1228, 1995. [BUR18] Y. Burda, H. Edwards, D. Pathak, A. Storkey, T. Darrell, A. A. Efros. Large-scale study of curiosity-driven learning. Preprint arXiv:1808.04355, 2018. [BRE] H. J. Bremermann (1982). Minimum energy requirements of information transfer and computing, International Journal of Theoretical Physics, 21, 203-217, 1982. [BRI] Bridle, J.S. (1990). Alpha-Nets: A Recurrent "Neural" Network Architecture with a Hidden Markov Model Interpretation, Speech Communication, vol. 9, no. 1, pp. 83-92. [BRU1] H. Bruderer. Computing history beyond the UK and US: selected landmarks from continental Europe. Communications of the ACM 60.2 (2017): 76-84. [BRU2] H. Bruderer. Meilensteine der Rechentechnik. 2 volumes, 3rd edition. Walter de Gruyter GmbH & Co KG, 2020. [BRU3] H. Bruderer. Milestones in Analog and Digital Computing. 2 volumes, 3rd edition. Springer Nature Switzerland AG, 2020. [BRU4] H. Bruderer. The Birthplace of Artificial Intelligence? Communications of the ACM, BLOG@CACM, Nov 2017. Link. [BRO21] D. C. Brock (2021). Cybernetics, Computer Design, and a Meeting of the Minds. An influential 1951 conference in Paris considered the computer as a model of—and for—the human mind. IEEE Spectrum, 2021. Link. [BW] H. Bourlard, C. J. Wellekens (1989). Links between Markov models and multilayer perceptrons. NIPS 1989, p. 502-510. https://people.idsia.ch/~juergen/deep-learning-history.html 37/75 29/12/2022, 12:21 [CAN] G. Cantor (1891). Ueber eine elementare Frage der Mannigfaltigkeitslehre. Jahresbericht der Deutschen Mathematiker-Vereinigung, 1:75-78. English translation: W. B. Ewald (ed.). From Immanuel Kant to David Hilbert: A Source Book in the Foundations of Mathematics, Volume 2, pp. 920-922. Oxford University Press, 1996. [CDI] G. E. Hinton. Training products of experts by minimizing contrastive divergence. Neural computation 14.8 (2002): 1771-1800. [CHO15] F. Chollet (2015). Keras. [CHU] A. Church (1935). An unsolvable problem of elementary number theory. Bulletin of the American Mathematical Society, 41: 332-333. Abstract of a talk given on 19 April 1935, to the American Mathematical Society. Also in American Journal of Mathematics, 58(2), 345-363 (1 Apr 1936). First explicit proof that the Entscheidungsproblem (decision problem) does not have a general solution. [CNN1] K. Fukushima: Neural network model for a mechanism of pattern recognition unaffected by shift in position—Neocognitron. Trans. IECE, vol. J62-A, no. 10, pp. 658-665, 1979. The first deep convolutional neural network architecture, with alternating convolutional layers and downsampling layers. In Japanese. English version: [CNN1+]. More in Scholarpedia. [CNN1+] K. Fukushima: Neocognitron: a self-organizing neural network model for a mechanism of pattern recognition unaffected by shift in position. Biological Cybernetics, vol. 36, no. 4, pp. 193-202 (April 1980). Link. [CNN1a] A. Waibel. Phoneme Recognition Using Time-Delay Neural Networks. Meeting of IEICE, Tokyo, Japan, 1987. First application of backpropagation[BP1-5] and weight-sharing to a convolutional architecture. [CNN1b] A. Waibel, T. Hanazawa, G. Hinton, K. Shikano and K. J. Lang. Phoneme recognition using time-delay neural networks. IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 37, no. 3, pp. 328-339, March 1989. Based on [CNN1a]. [CNN1c] Bower Award Ceremony 2021: Jürgen Schmidhuber lauds Kunihiko Fukushima. YouTube video, 2021. [CNN2] Y. LeCun, B. Boser, J. S. Denker, D. Henderson, R. E. Howard, W. Hubbard, L. D. Jackel: Backpropagation Applied to Handwritten Zip Code Recognition, Neural Computation, 1(4):541-551, 1989. PDF. [CNN3a] K. Yamaguchi, K. Sakamoto, A. Kenji, T. Akabane, Y. Fujimoto. A Neural Network for Speaker-Independent Isolated Word Recognition. First International Conference on Spoken Language Processing (ICSLP 90), Kobe, Japan, Nov 1990. An NN with convolutions using Max-Pooling instead of Fukushima's Spatial Averaging.[CNN1] [CNN3] Weng, J., Ahuja, N., and Huang, T. S. (1993). Learning recognition and segmentation of 3-D objects from 2-D images. Proc. 4th Intl. Conf. Computer Vision, Berlin, Germany, pp. https://people.idsia.ch/~juergen/deep-learning-history.html 38/75 29/12/2022, 12:21 121-128. A CNN whose downsampling layers use Max-Pooling (which has become very popular) instead of Fukushima's Spatial Averaging.[CNN1] [CNN4] M. A. Ranzato, Y. LeCun: A Sparse and Locally Shift Invariant Feature Extractor Applied to Document Images. Proc. ICDAR, 2007 [CNN5a] S. Behnke. Learning iterative image reconstruction in the neural abstraction pyramid. International Journal of Computational Intelligence and Applications, 1(4):427-438, 1999. [CNN5b] S. Behnke. Hierarchical Neural Networks for Image Interpretation, volume LNCS 2766 of Lecture Notes in Computer Science. Springer, 2003. [CNN5c] D. Scherer, A. Mueller, S. Behnke. Evaluation of pooling operations in convolutional architectures for object recognition. In Proc. International Conference on Artificial Neural Networks (ICANN), pages 92-101, 2010. [CO1] J. Koutnik, F. Gomez, J. Schmidhuber (2010). Evolving Neural Networks in Compressed Weight Space. Proceedings of the Genetic and Evolutionary Computation Conference (GECCO-2010), Portland, 2010. PDF. [CO2] J. Koutnik, G. Cuccu, J. Schmidhuber, F. Gomez. Evolving Large-Scale Neural Networks for Vision-Based Reinforcement Learning. Proceedings of the Genetic and Evolutionary Computation Conference (GECCO), Amsterdam, July 2013. PDF. The first deep learning model to successfully learn control policies directly from high-dimensional sensory input using reinforcement learning, without any unsupervised pre-training. [CO3] R. K. Srivastava, J. Schmidhuber, F. Gomez. Generalized Compressed Network Search. Proc. GECCO 2012. PDF. [CON16] J. Carmichael (2016). Artificial Intelligence Gained Consciousness in 1991. Why A.I. pioneer Jürgen Schmidhuber is convinced the ultimate breakthrough already happened. Inverse, 2016. Link. [CONN21] Since November 2021: Comments on version 1 of the report[T22] in the Connectionists Mailing List, perhaps the oldest mailing list on artificial neural networks. Link to the archive. [CTC] A. Graves, S. Fernandez, F. Gomez, J. Schmidhuber. Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks. ICML 06, Pittsburgh, 2006. PDF. [CUB0] R. J. Williams. Complexity of exact gradient computation algorithms for recurrent neural networks. Technical Report NU-CCS-89-27, Northeastern University, College of Computer Science, 1989. [CUB2] J. Schmidhuber. A fixed size storage O(n3) time complexity learning algorithm for fully recurrent continually running networks. Neural Computation, 4(2):243-248, 1992. PDF. https://people.idsia.ch/~juergen/deep-learning-history.html 39/75 29/12/2022, 12:21 [CW] J. Koutnik, K. Greff, F. Gomez, J. Schmidhuber. A Clockwork RNN. Proc. 31st International Conference on Machine Learning (ICML), p. 1845-1853, Beijing, 2014. Preprint arXiv:1402.3511 [cs.NE]. [DAN] J. Schmidhuber (AI Blog, 2021). 10-year anniversary. In 2011, DanNet triggered the deep convolutional neural network (CNN) revolution. Named after Schmidhuber's outstanding postdoc Dan Ciresan, it was the first deep and fast CNN to win international computer vision contests, and had a temporary monopoly on winning them, driven by a very fast implementation based on graphics processing units (GPUs). 1st superhuman result in 2011. [DAN1] Now everybody is using this approach. [DAN1] J. Schmidhuber (AI Blog, 2011; updated 2021 for 10th birthday of DanNet): First superhuman visual pattern recognition. At the IJCNN 2011 computer vision competition in Silicon Valley, the artificial neural network called DanNet performed twice better than humans, three times better than the closest artificial competitor (from LeCun's team), and six times better than the best non-neural method. [DEC] J. Schmidhuber (AI Blog, 02/20/2020, updated 2021, 2022). The 2010s: Our Decade of Deep Learning / Outlook on the 2020s. The recent decade's most important developments and industrial applications based on the AI of Schmidhuber's team, with an outlook on the 2020s, also addressing privacy and data markets. [DEEP1] Ivakhnenko, A. G. and Lapa, V. G. (1965). Cybernetic Predicting Devices. CCM Information Corporation. First working Deep Learners with many layers, learning internal representations. [DEEP1a] Ivakhnenko, Alexey Grigorevich. The group method of data of handling; a rival of the method of stochastic approximation. Soviet Automatic Control 13 (1968): 43-55. [DEEP2] Ivakhnenko, A. G. (1971). Polynomial theory of complex systems. IEEE Transactions on Systems, Man and Cybernetics, (4):364-378. [DIST2] O. Vinyals, J. A. Dean, G. E. Hinton. Distilling the Knowledge in a Neural Network. Preprint arXiv:1503.02531 [stat.ML], 2015. The authors did not cite Schmidhuber's original 1991 NN distillation procedure,[UN0-2][MIR](Sec. 2) not even in the later patent application US20150356461A1. [DL1] J. Schmidhuber, 2015. Deep learning in neural networks: An overview. Neural Networks, 61, 85-117. More. Got the first Best Paper Award ever issued by the journal Neural Networks, founded in 1988. [DL2] J. Schmidhuber, 2015. Deep Learning. Scholarpedia, 10(11):32832. [DL3] Y. LeCun, Y. Bengio, G. Hinton (2015). Deep Learning. Nature 521, 436-444. HTML. A "survey" of deep learning that does not mention the pioneering works of deep learning [T22]. [DL3a] Y. Bengio, Y. LeCun, G. Hinton (2021). Turing Lecture: Deep Learning for AI. Communications of the ACM, July 2021. HTML. Local copy (HTML only). Another "survey" of deep learning that does not mention the pioneering works of deep learning [T22]. https://people.idsia.ch/~juergen/deep-learning-history.html 40/75 29/12/2022, 12:21 [DL4] J. Schmidhuber (AI Blog, 2017). Our impact on the world's most valuable public companies: Apple, Google, Microsoft, Facebook, Amazon... By 2015-17, neural nets developed in Schmidhuber's labs were on over 3 billion devices such as smartphones, and used many billions of times per day, consuming a significant fraction of the world's compute. Examples: greatly improved (CTC-based) speech recognition on all Android phones, greatly improved machine translation through Google Translate and Facebook (over 4 billion LSTM- based translations per day), Apple's Siri and Quicktype on all iPhones, the answers of Amazon's Alexa, etc. Google's 2019 on-device speech recognition (on the phone, not the server) is still based on LSTM. [DL6] F. Gomez and J. Schmidhuber. Co-evolving recurrent neurons learn deep memory POMDPs. In Proc. GECCO'05, Washington, D. C., pp. 1795-1802, ACM Press, New York, NY, USA, 2005. PDF. [DL6a] J. Schmidhuber (AI Blog, Nov 2020). 15-year anniversary: 1st paper with "learn deep" in the title (2005). The deep reinforcement learning & neuroevolution developed in Schmidhuber's lab solved problems of depth 1000 and more.[DL6] Soon after its publication, everybody started talking about "deep learning." Causality or correlation? [DL7] "Deep Learning ... moving beyond shallow machine learning since 2006!" Web site deeplearning.net of Y. Bengio's MILA (2015, retrieved May 2020; compare the version in the Internet Archive), referring to Hinton's[UN4] and Bengio's[UN5] unsupervised pre-training for deep NNs[UN4] (2006) although this type of deep learning dates back to Schmidhuber's work of 1991. [UN1-2][UN] [DLC] J. Schmidhuber (AI Blog, June 2015). Critique of Paper by self-proclaimed[DLC2] "Deep Learning Conspiracy" (Nature 521 p 436). The inventor of an important method should get credit for inventing it. She may not always be the one who popularizes it. Then the popularizer should get credit for popularizing it (but not for inventing it). More on this under [T22]. [DLC1] Y. LeCun. IEEE Spectrum Interview by L. Gomes, Feb 2015. Quote: "A lot of us involved in the resurgence of Deep Learning in the mid-2000s, including Geoff Hinton, Yoshua Bengio, and myself—the so-called 'Deep Learning conspiracy' ..." [DLC2] M. Bergen, K. Wagner (2015). Welcome to the AI Conspiracy: The 'Canadian Mafia' Behind Tech's Latest Craze. Vox recode, 15 July 2015. Quote: "... referred to themselves as the 'deep learning conspiracy.' Others called them the 'Canadian Mafia.'" [DLH] J. Schmidhuber (AI Blog, 2022). Annotated History of Modern AI and Deep Learning. Technical Report IDSIA-22-22, IDSIA, Lugano, Switzerland, 2022. Preprint arXiv:2212.11279. Tweet of 2022. [DM1] V. Mnih, K. Kavukcuoglu, D. Silver, A. Graves, I. Antonoglou, D. Wierstra, M. Riedmiller. Playing Atari with Deep Reinforcement Learning. Tech Report, 19 Dec. 2013, arxiv:1312.5602. [DM2] V. Mnih, K. Kavukcuoglu, D. Silver, A. A. Rusu, J. Veness, M. G. Bellemare, A. Graves, M. Riedmiller, A. K. Fidjeland, G. Ostrovski, S. Petersen, C. Beattie, A. Sadik, I. Antonoglou, H. King, D. Kumaran, D. Wierstra, S. Legg, D. Hassabis. Human-level control through deep reinforcement learning. Nature, vol. 518, p 1529, 26 Feb. 2015. Link. DeepMind's first famous https://people.idsia.ch/~juergen/deep-learning-history.html 41/75 29/12/2022, 12:21 paper. Its abstract claims: "While reinforcement learning agents have achieved some successes in a variety of domains, their applicability has previously been limited to domains in which useful features can be handcrafted, or to domains with fully observed, low-dimensional state spaces." It also claims to bridge "the divide between high-dimensional sensory inputs and actions." Similarly, the first sentence of the abstract of the earlier tech report version[DM1] of [DM2] claims to "present the first deep learning model to successfully learn control policies directly from high-dimensional sensory input using reinforcement learning." However, the first such system (requiring no unsupervised pre-training) was created earlier by Jan Koutnik et al. in Schmidhuber's lab.[CO2] DeepMind was co-founded by Shane Legg, a PhD student from this lab; he and Daan Wierstra (another PhD student of Schmidhuber and DeepMind's 1st employee) were the first persons at DeepMind who had AI publications and PhDs in computer science. More. [DM2a] D. Silver et al. A general reinforcement learning algorithm that masters chess, Shogi, and Go through self-play. Science 362.6419:1140-1144, 2018. [DM3] S. Stanford. DeepMind's AI, AlphaStar Showcases Significant Progress Towards AGI. Medium ML Memoirs, 2019. Alphastar has a "deep LSTM core." [DM4] J. Jumper, R. Evans, A. Pritzel, T. Green, M. Figurnov, O. Ronneberger, K. Tunyasuvunakool, R. Bates, A. Zidek, A. Potapenko, A. Bridgland, C. Meyer, S. A. A. Kohl, A. J. Ballard, A. Cowie, B. Romera-Paredes, S. Nikolov, R. Jain, J. Adler, T. Back, S. Petersen, D. Reiman, E. Clancy, M. Zielinski, M. Steinegger, M. Pacholska, T. Berghammer, S. Bodenstein, D. Silver, O. Vinyals, A. W. Senior, K. Kavukcuoglu, P. Kohli & D. Hassabis. Highly accurate protein structure prediction with AlphaFold. Nature 596, 583-589, 2021. DeepMind's breakthrough application of deep learning did not cite Hochreiter et al.'s first successful application [HO07] of deep learning to protein folding (2007). [DIF1] R. Rombach, A. Blattmann, D. Lorenz, P. Esser, B. Ommer. High-Resolution Image Synthesis with Latent Diffusion Models. CVPR 2022. Preprint arXiv:2112.10752, LMU Munich, 2021. [DIF2] C. Jarzynski. Equilibrium free-energy differences from nonequilibrium measurements: A master-equation approach. Physical Review E, 1997. [DIF3] J. Sohl-Dickstein, E. A. Weiss, N. Maheswaranathan, S. Ganguli. Deep unsupervised learning using nonequilibrium thermodynamics. CoRR, abs/1503.03585, 2015. [DIF4] O. Ronneberger, P. Fischer, T. Brox. Unet: Convolutional networks for biomedical image segmentation. In MICCAI (3), vol. 9351 of Lecture Notes in Computer Science, pages 234-241. Springer, 2015. [DIF5] J. Ho, A. Jain, P. Abbeel. Denoising diffusion probabilistic models. Advances in Neural Information Processing Systems 33:6840-6851, 2020. [DNC] A. Graves, G. Wayne, M. Reynolds, T. Harley, I. Danihelka, A. Grabska-Barwinska, S. G. Colmenarejo, E. Grefenstette, T. Ramalho, J. Agapiou, A. P. Badia, K. M. Hermann, Y. Zwols, G. Ostrovski, A. Cain, H. King, C. Summerfield, P. Blunsom, K. Kavukcuoglu, D. Hassabis. https://people.idsia.ch/~juergen/deep-learning-history.html 42/75 29/12/2022, 12:21 Hybrid computing using a neural network with dynamic external memory. Nature, 538:7626, p 471, 2016. This work of DeepMind did not cite the original work of the early 1990s on neural networks learning to control dynamic external memories.[PDA1-2][FWP0-1] [Drop1] S. J. Hanson (1990). A Stochastic Version of the Delta Rule, PHYSICA D,42, 265-272. What's now called "dropout" is a variation of the stochastic delta rule—compare preprint arXiv:1808.03578, 2018. [Drop2] N. Frazier-Logue, S. J. Hanson (2020). The Stochastic Delta Rule: Faster and More Accurate Deep Learning Through Adaptive Weight Noise. Neural Computation 32(5):1018- 1032. [Drop3] J. Hertz, A. Krogh, R. Palmer (1991). Introduction to the Theory of Neural Computation. Redwood City, California: Addison-Wesley Pub. Co., pp. 45-46. [Drop4] N. Frazier-Logue, S. J. Hanson (2018). Dropout is a special case of the stochastic delta rule: faster and more accurate deep learning. Preprint arXiv:1808.03578, 2018. [DYNA90] R. S. Sutton (1990). Integrated Architectures for Learning, Planning, and Reacting Based on Approximating Dynamic Programming. Machine Learning Proceedings 1990, of the Seventh International Conference, Austin, Texas, June 21-23, 1990, p 216-224. [DYNA91] R. S. Sutton (1991). Dyna, an integrated architecture for learning, planning, and reacting. ACM Sigart Bulletin 2.4 (1991):160-163. [ELM1] G.-B. Huang, Q.-Y. Zhu, and C.-K. Siew. Extreme learning machine: A new learning scheme of feedforward neural networks. Proc. IEEE Int. Joint Conf. on Neural Networks, Vol. 2, 2004, pp. 985-990. This paper does not mention that the "ELM" concept goes back to Rosenblatt's work in the 1950s.[R62][T22] [ELM2] ELM-ORIGIN, 2004. The Official Homepage on Origins of Extreme Learning Machines (ELM). "Extreme Learning Machine Duplicates Others' Papers from 1988-2007." Local copy. This overview does not mention that the "ELM" concept goes back to Rosenblatt's work in the 1950s.[R62][T22] [ENS1] R. E. Schapire. The strength of weak learnability. Machine Learning, 5:197-227, 1990. [ENS2] D. H. Wolpert. Stacked generalization. Neural Networks, 5(2):241-259, 1992. [ENS3] L. Breiman. Bagging predictors. Machine Learning, 24:123-140, 1996. [ENS4] T. G. Dietterich. Ensemble methods in machine learning. In Multiple classifier systems, pages 1-15. Springer, 2000. [EVO1] N. A. Barricelli. Esempi numerici di processi di evoluzione. Methodos: 45-68, 1954. Possibly the first publication on artificial evolution. [EVO2] L. Fogel, A. Owens, M. Walsh. Artificial Intelligence through Simulated Evolution. Wiley, New York, 1966. https://people.idsia.ch/~juergen/deep-learning-history.html 43/75 29/12/2022, 12:21 [EVO3] I. Rechenberg. Evolutionsstrategie—Optimierung technischer Systeme nach Prinzipien der biologischen Evolution. Dissertation, 1971. [EVO4] H. P. Schwefel. Numerische Optimierung von Computer-Modellen. Dissertation, 1974. [EVO5] J. H. Holland. Adaptation in Natural and Artificial Systems. University of Michigan Press, Ann Arbor, 1975. [EVO6] S. F. Smith. A Learning System Based on Genetic Adaptive Algorithms, PhD Thesis, Univ. Pittsburgh, 1980 [EVO7] N. L. Cramer. A representation for the adaptive generation of simple sequential programs. In J. J. Grefenstette, editor, Proceedings of an International Conference on Genetic Algorithms and Their Applications, Carnegie-Mellon University, July 24-26, 1985, Hillsdale NJ, 1985. Lawrence Erlbaum Associates. [EVONN1] Montana, D. J. and Davis, L. (1989). Training feedforward neural networks using genetic algorithms. In Proceedings of the 11th International Joint Conference on Artificial Intelligence (IJCAI)—Volume 1, IJCAI'89, pages 762–767, San Francisco, CA, USA. Morgan Kaufmann Publishers Inc. [EVONN2] Miller, G., Todd, P., and Hedge, S. (1989). Designing neural networks using genetic algorithms. In Proceedings of the 3rd International Conference on Genetic Algorithms, pages 379–384. Morgan Kauffman. [EVONN3] H. Kitano. Designing neural networks using genetic algorithms with graph generation system. Complex Systems, 4:461-476, 1990. [FA15] Intelligente Roboter werden vom Leben fasziniert sein. (Intelligent robots will be fascinated by life.) FAZ, 1 Dec 2015. Link. [FAKE] H. Hopf, A. Krief, G. Mehta, S. A. Matlin. Fake science and the knowledge crisis: ignorance can be fatal. Royal Society Open Science, May 2019. Quote: "Scientists must be willing to speak out when they see false information being presented in social media, traditional print or broadcast press" and "must speak out against false information and fake science in circulation and forcefully contradict public figures who promote it." [FAKE2] L. Stenflo. Intelligent plagiarists are the most dangerous. Nature, vol. 427, p. 777 (Feb 2004). Quote: "What is worse, in my opinion, ..., are cases where scientists rewrite previous findings in different words, purposely hiding the sources of their ideas, and then during subsequent years forcefully claim that they have discovered new phenomena. [FAST] C. v.d. Malsburg. Tech Report 81-2, Abteilung f. Neurobiologie, Max-Planck Institut f. Biophysik und Chemie, Goettingen, 1981. First paper on fast weights or dynamic links. [FASTa] J. A. Feldman. Dynamic connections in neural networks. Biological Cybernetics, 46(1):27-39, 1982. 2nd paper on fast weights. https://people.idsia.ch/~juergen/deep-learning-history.html 44/75 29/12/2022, 12:21 [FASTb] G. E. Hinton, D. C. Plaut. Using fast weights to deblur old memories. Proc. 9th annual conference of the Cognitive Science Society (pp. 177-186), 1987. 3rd paper on fast weights (two types of weights with different learning rates). [FB17] By 2017, Facebook used LSTM to handle over 4 billion automatic translations per day (The Verge, August 4, 2017); see also Facebook blog by J.M. Pino, A. Sidorov, N.F. Ayan (August 3, 2017) [FDL] J. Schmidhuber (AI Blog, 2013). My First Deep Learning System of 1991 + Deep Learning Timeline 1960-2013. [FEI63] E. A. Feigenbaum, J. Feldman. Computers and thought. McGraw-Hill: New York, 1963. [FEI83] E. A. Feigenbaum, P. McCorduck. The fifth generation. Addison-Wesley Publishers, 1983. [FI22] R. A. Fisher. On the mathematical foundations of theoretical statistics. Philosophical Transactions of the Royal Society of London. Series A, containing papers of a mathematical or physical character; 222.594-604:309-368, 1922. [FM] S. Hochreiter and J. Schmidhuber. Flat minimum search finds simple nets. Technical Report FKI-200-94, Fakultät für Informatik, Technische Universität München, December 1994. PDF. [FRE] G. Frege (1879). Begriffsschrift: eine der arithmetischen nachgebildete Formelsprache des reinen Denkens. Halle an der Saale: Verlag Louis Nebert. The first formal language / formal proofs—basis of modern logic and programming languages. [FU77] K. S. Fu. Syntactic Pattern Recognition and Applications. Berlin, Springer, 1977. [FWP] J. Schmidhuber (AI Blog, 26 March 2021, updated 2022). 26 March 1991: Neural nets learn to program neural nets with fast weights—like Transformer variants. 2021: New stuff! 30- year anniversary of a now popular alternative[FWP0-1] to recurrent NNs. A slow feedforward NN learns by gradient descent to program the changes of the fast weights[FAST,FASTa,b] of another NN, separating memory and control like in traditional computers. Such Fast Weight Programmers[FWP0-6,FWPMETA1-8] can learn to memorize past data, e.g., by computing fast weight changes through additive outer products of self-invented activation patterns[FWP0-1] (now often called keys and values for self-attention[TR1-6]). The similar Transformers[TR1-2] combine this with projections and softmax and are now widely used in natural language processing. For long input sequences, their efficiency was improved through Transformers with linearized self- attention[TR5-6] which are formally equivalent to Schmidhuber's 1991 outer product-based Fast Weight Programmers (apart from normalization). In 1993, he introduced the attention terminology[FWP2] now used in this context,[ATT] and extended the approach to RNNs that program themselves. See tweet of 2022. [FWP0] J. Schmidhuber. Learning to control fast-weight memories: An alternative to recurrent nets. Technical Report FKI-147-91, Institut für Informatik, Technische Universität München, 26 March 1991. PDF. First paper on fast weight programmers that separate storage and control: a slow net learns by gradient descent to compute weight changes of a fast net. The outer https://people.idsia.ch/~juergen/deep-learning-history.html 29/12/2022, 12:21 product-based version (Eq. 5) is now known as a "Transformer with linearized self-attention" (apart from normalization).[FWP] [FWP1] J. Schmidhuber. Learning to control fast-weight memories: An alternative to recurrent nets. Neural Computation, 4(1):131-139, 1992. Based on [FWP0]. PDF. HTML. Pictures (German). See tweet of 2022 for 30-year anniversary. [FWP2] J. Schmidhuber. Reducing the ratio between learning complexity and number of time- varying variables in fully recurrent nets. In Proceedings of the International Conference on Artificial Neural Networks, Amsterdam, pages 460-463. Springer, 1993. PDF. First recurrent NN-based fast weight programmer using outer products, introducing the terminology of learning "internal spotlights of attention." [FWP3] I. Schlag, J. Schmidhuber. Gated Fast Weights for On-The-Fly Neural Program Generation. Workshop on Meta-Learning, @N(eur)IPS 2017, Long Beach, CA, USA. [FWP3a] I. Schlag, J. Schmidhuber. Learning to Reason with Third Order Tensor Products. Advances in Neural Information Processing Systems (N(eur)IPS), Montreal, 2018. Preprint: arXiv:1811.12143. PDF. [FWP4a] J. Ba, G. Hinton, V. Mnih, J. Z. Leibo, C. Ionescu. Using Fast Weights to Attend to the Recent Past. NIPS 2016. PDF. Very similar to [FWP0-2], in both motivation [FWP2] and execution. [FWP4b] D. Bahdanau, K. Cho, Y. Bengio (2014). Neural Machine Translation by Jointly Learning to Align and Translate. Preprint arXiv:1409.0473 [cs.CL]. This work on "attention" did not cite Schmidhuber's much earlier original work of 1991-1993 on soft attention and Transformers with linearized self-attention.[FWP,FWP0-2,6][ATT] [FWP4d] Y. Tang, D. Nguyen, D. Ha (2020). Neuroevolution of Self-Interpretable Agents. Preprint: arXiv:2003.08165. [FWP5] F. J. Gomez and J. Schmidhuber. Evolving modular fast-weight networks for control. In W. Duch et al. (Eds.): Proc. ICANN'05, LNCS 3697, pp. 383-389, Springer-Verlag Berlin Heidelberg, 2005. PDF. HTML overview. Reinforcement-learning fast weight programmer. [FWP6] I. Schlag, K. Irie, J. Schmidhuber. Linear Transformers Are Secretly Fast Weight Programmers. ICML 2021. Preprint: arXiv:2102.11174. [FWP7] K. Irie, I. Schlag, R. Csordas, J. Schmidhuber. Going Beyond Linear Transformers with Recurrent Fast Weight Programmers. Preprint: arXiv:2106.06295 (June 2021). [FWPMETA1] J. Schmidhuber. Steps towards `self-referential' learning. Technical Report CU- CS-627-92, Dept. of Comp. Sci., University of Colorado at Boulder, November 1992. First recurrent NN-based fast weight programmer that can learn to run a learning algorithm or weight change algorithm on itself. [FWPMETA2] J. Schmidhuber. A self-referential weight matrix. In Proceedings of the International Conference on Artificial Neural Networks, Amsterdam, pages 446-451. Springer, https://people.idsia.ch/~juergen/deep-learning-history.html 46/75 29/12/2022, 12:21 1993. PDF. Annotated history of modern AI and deep neural networks [FWPMETA3] J. Schmidhuber. An introspective network that can learn to run its own weight change algorithm. In Proc. of the Intl. Conf. on Artificial Neural Networks, Brighton, pages 191- 195. IEE, 1993. [FWPMETA4] J. Schmidhuber. A neural network that embeds its own meta-levels. In Proc. of the International Conference on Neural Networks '93, San Francisco. IEEE, 1993. [FWPMETA5] J. Schmidhuber. Habilitation thesis, TUM, 1993. PDF. A recurrent neural net with a self-referential, self-reading, self-modifying weight matrix can be found here. [FWPMETA6] L. Kirsch and J. Schmidhuber. Meta Learning Backpropagation & Improving It. Advances in Neural Information Processing Systems (NeurIPS), 2021. Preprint arXiv:2012.14905 [cs.LG], 2020. [FWPMETA7] I. Schlag, T. Munkhdalai, J. Schmidhuber. Learning Associative Inference Using Fast Weight Memory. ICLR 2021. Report arXiv:2011.07831 [cs.AI], 2020. [FWPMETA8] K. Irie, I. Schlag, R. Csordas, J. Schmidhuber. A Modern Self-Referential Weight Matrix That Learns to Modify Itself. International Conference on Machine Learning (ICML), 2022. Preprint: arXiv:2202.05780. [FWPMETA9] L. Kirsch and J. Schmidhuber. Self-Referential Meta Learning. First Conference on Automated Machine Learning (Late-Breaking Workshop), 2022. [GAU09] C. F. Gauss. Theoria motus corporum coelestium in sectionibus conicis solem ambientium, 1809. [GAU21] C. F. Gauss. Theoria combinationis observationum erroribus minimis obnoxiae (Theory of the combination of observations least subject to error), 1821. [G63] R. J Glauber (1963). Time-dependent statistics of the Ising model. Journal of Mathematical Physics, 4(2):294-307, 1963. [GD'] C. Lemarechal. Cauchy and the Gradient Method. Doc Math Extra, pp. 251-254, 2012. [GD''] J. Hadamard. Memoire sur le probleme d'analyse relatif a Vequilibre des plaques elastiques encastrees. Memoires presentes par divers savants estrangers à l'Academie des Sciences de l'Institut de France, 33, 1908. [GDa] Y. Z. Tsypkin (1966). Adaptation, training and self-organization automatic control systems, Avtomatika I Telemekhanika, 27, 23-61. On gradient descent-based on-line learning for non-linear systems. [GDb] Y. Z. Tsypkin (1971). Adaptation and Learning in Automatic Systems, Academic Press, 1971. On gradient descent-based on-line learning for non-linear systems. https://people.idsia.ch/~juergen/deep-learning-history.html 47/75 29/12/2022, 12:21 [GD1] S. I. Amari (1967). A theory of adaptive pattern classifier, IEEE Trans, EC-16, 279-307 (Japanese version published in 1965). PDF. Probably the first paper on using stochastic gradient descent[STO51-52] for learning in multilayer neural networks (without specifying the specific gradient descent method now known as reverse mode of automatic differentiation or backpropagation[BP1]). [GD2] S. I. Amari (1968). Information Theory—Geometric Theory of Information, Kyoritsu Publ., 1968 (in Japanese). OCR-based PDF scan of pages 94-135 (see pages 119-120). Contains computer simulation results for a five layer network (with 2 modifiable layers) which learns internal representations to classify non-linearily separable pattern classes. [GD2a] H. Saito (1967). Master's thesis, Graduate School of Engineering, Kyushu University, Japan. Implementation of Amari's 1967 stochastic gradient descent method for multilayer perceptrons.[GD1] (S. Amari, personal communication, 2021.) [GD3] S. I. Amari (1977). Neural Theory of Association and Concept Formation. Biological Cybernetics, vol. 26, p. 175-185, 1977. See Section 3.1 on using gradient descent for learning in multilayer networks. [GGP] F. Faccio, V. Herrmann, A. Ramesh, L. Kirsch, J. Schmidhuber. Goal-Conditioned Generators of Deep Policies. Preprint arXiv/2207.01570, 4 July 2022 (submitted in May 2022). [GLA85] W. Glasser. Control theory. New York: Harper and Row, 1985. [GM3] J. Schmidhuber (2003). Gödel Machines: Self-Referential Universal Problem Solvers Making Provably Optimal Self-Improvements. Preprint arXiv:cs/0309048 (2003). More. [GM6] J. Schmidhuber (2006). Gödel machines: Fully Self-Referential Optimal Universal Self- Improvers. In B. Goertzel and C. Pennachin, eds.: Artificial General Intelligence, p. 199-226, 2006. PDF. [GM9] J. Schmidhuber (2009). Ultimate Cognition à la Gödel. Cognitive Computation 1(2):177- 193, 2009. PDF. More. [GSR] H. Sak, A. Senior, K. Rao, F. Beaufays, J. Schalkwyk—Google Speech Team. Google voice search: faster and more accurate. Google Research Blog, Sep 2015, see also Aug 2015 Google's speech recognition based on CTC and LSTM. [GSR15] Dramatic improvement of Google's speech recognition through LSTM: Alphr Technology, Jul 2015, or 9to5google, Jul 2015 [GSR19] Y. He, T. N. Sainath, R. Prabhavalkar, I. McGraw, R. Alvarez, D. Zhao, D. Rybach, A. Kannan, Y. Wu, R. Pang, Q. Liang, D. Bhatia, Y. Shangguan, B. Li, G. Pundak, K. Chai Sim, T. Bagby, S. Chang, K. Rao, A. Gruenstein. Streaming end-to-end speech recognition for mobile devices. ICASSP 2019-2019 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP). IEEE, 2019. [GT16] Google's dramatically improved Google Translate of 2016 is based on LSTM, e.g., WIRED, Sep 2016, or siliconANGLE, Sep 2016 https://people.idsia.ch/~juergen/deep-learning-history.html 48/75 29/12/2022, 12:21 [GAN0] O. Niemitalo. A method for training artificial neural networks to generate missing data within a variable context. Blog post, Internet Archive, 2010. A blog post describing basic ideas[AC][AC90,AC90b][AC20] of GANs. [GAN1] I. Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, D. Warde-Farley, S. Ozair, A. Courville, Y. Bengio. Generative adversarial nets. NIPS 2014, 2672-2680, Dec 2014. A description of GANs that does not cite Schmidhuber's original GAN principle of 1990[AC] [AC90,AC90b][AC20][R2][T22] (also containing wrong claims about Schmidhuber's adversarial NNs for Predictability Minimization[PM0-2][AC20][T22]). [GAN2] T. Karras, S. Laine, T. Aila. A style-based generator architecture for generative adversarial networks. In Proc. IEEE Conf. on Computer Vision and Pattern Recognition (CVPR), pages 4401-4410, 2019. [GOD] K. Gödel. Über formal unentscheidbare Sätze der Principia Mathematica und verwandter Systeme I. Monatshefte für Mathematik und Physik, 38:173-198, 1931. In the early 1930s, Gödel founded theoretical computer science. He identified fundamental limits of mathematics, theorem proving, computing, and Artificial Intelligence. [GOD34] K. Gödel (1934). On undecidable propositions of formal mathematical systems. Notes by S. C. Kleene and J. B. Rosser on lectures at the Institute for Advanced Study, Princeton, New Jersey, 1934, 30 pp. (Reprinted in M. Davis, (ed.), The Undecidable. Basic Papers on Undecidable Propositions, Unsolvable Problems, and Computable Functions, Raven Press, Hewlett, New York, 1965.) Gödel introduced a universal coding language. [GOD56] R. J. Lipton and K. W. Regan. Gödel's lost letter and P=NP. Link. Gödel identified what's now the most famous open problem of computer science. [GOD86] K. Gödel. Collected works Volume I: Publications 1929-36, S. Feferman et. al., editors, Oxford Univ. Press, Oxford, 1986. [GOD10] V. C. Nadkarni. Gödel, Einstein and proof for God. The Economic Times, 2010. [GOD21] J. Schmidhuber (2021). 90th anniversary celebrations: 1931: Kurt Gödel, founder of theoretical computer science, shows limits of math, logic, computing, and artificial intelligence. This was number 1 on Hacker News. [GOD21a] J. Schmidhuber (2021). Als Kurt Gödel die Grenzen des Berechenbaren entdeckte. (When Kurt Gödel discovered the limits of computability.) Frankfurter Allgemeine Zeitung, 16/6/2021. [GOD21b] J. Schmidhuber (AI Blog, 2021). 80. Jahrestag: 1931: Kurt Gödel, Vater der theoretischen Informatik, entdeckt die Grenzen des Berechenbaren und der künstlichen Intelligenz. [GOL] C. Goller & A. Küchler (1996). Learning task-dependent distributed representations by backpropagation through structure. Proceedings of International Conference on Neural Networks (ICNN'96). Vol. 1, p. 347-352 IEEE, 1996. Based on TR AR-95-02, TU Munich, 1995. https://people.idsia.ch/~juergen/deep-learning-history.html 49/75 29/12/2022, 12:21 [GPT3] T. B. Brown, B. Mann, N. Ryder, M. Subbiah, J. Kaplan, P. Dhariwal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell, S. Agarwal, A. Herbert-Voss, G. Krueger, T. Henighan, R. Child, A. Ramesh, D. M. Ziegler, J. Wu, C. Winter, C. Hesse, M. Chen, E. Sigler, M. Litwin, S. Gray, B. Chess, J. Clark, C. Berner, S. McCandlish, A. Radford, I. Sutskever, D. Amodei. Language Models are Few-Shot Learners (2020). Preprint arXiv/2005.14165. [GPUNN] Oh, K.-S. and Jung, K. (2004). GPU implementation of neural networks. Pattern Recognition, 37(6):1311-1314. Speeding up traditional NNs on GPU by a factor of 20. [GPUCNN] K. Chellapilla, S. Puri, P. Simard. High performance convolutional neural networks for document processing. International Workshop on Frontiers in Handwriting Recognition, 2006. Speeding up shallow CNNs on GPU by a factor of 4. [GPUCNN1] D. C. Ciresan, U. Meier, J. Masci, L. M. Gambardella, J. Schmidhuber. Flexible, High Performance Convolutional Neural Networks for Image Classification. International Joint Conference on Artificial Intelligence (IJCAI-2011, Barcelona), 2011. PDF. ArXiv preprint. Speeding up deep CNNs on GPU by a factor of 60. Used to win four important computer vision competitions 2011-2012 before others won any with similar approaches. [GPUCNN2] D. C. Ciresan, U. Meier, J. Masci, J. Schmidhuber. A Committee of Neural Networks for Traffic Sign Classification. International Joint Conference on Neural Networks (IJCNN-2011, San Francisco), 2011. PDF. HTML overview. First superhuman performance in a computer vision contest, with half the error rate of humans, and one third the error rate of the closest competitor.[DAN1] This led to massive interest from industry. [GPUCNN3] D. C. Ciresan, U. Meier, J. Schmidhuber. Multi-column Deep Neural Networks for Image Classification. Proc. IEEE Conf. on Computer Vision and Pattern Recognition CVPR 2012, p 3642-3649, July 2012. PDF. Longer TR of Feb 2012: arXiv:1202.2745v1 [cs.CV]. More. [GPUCNN3a] D. Ciresan, A. Giusti, L. Gambardella, J. Schmidhuber. Deep Neural Networks Segment Neuronal Membranes in Electron Microscopy Images. NIPS 2012, Lake Tahoe, 2012. [GPUCNN4] A. Krizhevsky, I. Sutskever, G. E. Hinton. ImageNet Classification with Deep Convolutional Neural Networks. NIPS 25, MIT Press, Dec 2012. PDF. This paper describes AlexNet, which is similar to the earlier DanNet,[DAN,DAN1][R6] the first pure deep CNN to win computer vision contests in 2011[GPUCNN2-3,5] (AlexNet and VGG Net[GPUCNN9] followed in 2012- 2014). [GPUCNN4] emphasizes benefits of Fukushima's ReLUs (1969)[RELU1] and dropout (a variant of Hanson 1990 stochastic delta rule)[Drop1-4] but neither cites the original work[RELU1][Drop1] nor the basic CNN architecture (Fukushima, 1979).[CNN1] [GPUCNN5] J. Schmidhuber (AI Blog, 2017; updated 2021 for 10th birthday of DanNet): History of computer vision contests won by deep CNNs since 2011. DanNet was the first CNN to win one, and won 4 of them in a row before the similar AlexNet/VGG Net and the Resnet (a Highway Net with open gates) joined the party. Today, deep CNNs are standard in computer vision. https://people.idsia.ch/~juergen/deep-learning-history.html 50/75 29/12/2022, 12:21 [GPUCNN6] J. Schmidhuber, D. Ciresan, U. Meier, J. Masci, A. Graves. On Fast Deep Nets for AGI Vision. In Proc. Fourth Conference on Artificial General Intelligence (AGI-11), Google, Mountain View, California, 2011. PDF. [GPUCNN7] D. C. Ciresan, A. Giusti, L. M. Gambardella, J. Schmidhuber. Mitosis Detection in Breast Cancer Histology Images using Deep Neural Networks. MICCAI 2013. PDF. [GPUCNN8] J. Schmidhuber (AI Blog, 2017; updated 2021 for 10th birthday of DanNet). First deep learner to win a contest on object detection in large images— first deep learner to win a medical imaging contest (2012). Link. How the Swiss AI Lab IDSIA used GPU-based CNNs to win the ICPR 2012 Contest on Mitosis Detection and the MICCAI 2013 Grand Challenge. [GPUCNN9] K. Simonyan, A. Zisserman. Very deep convolutional networks for large-scale image recognition. Preprint arXiv:1409.1556 (2014). [GRO69] S. Grossberg. Some networks that can learn, remember, and reproduce any number of complicated space-time patterns, Indiana University Journal of Mathematics and Mechanics, 19:53-91, 1969. [H86] J. L. van Hemmen (1986). Spin-glass models of a neural network. Phys. Rev. A 34, 3435, 1 Oct 1986. [H88] H. Sompolinsky (1988). Statistical Mechanics of Neural Networks. Physics Today 41, 12, 70, 1988. [H90] W. D. Hillis. Co-evolving parasites improve simulated evolution as an optimization procedure. Physica D: Nonlinear Phenomena, 42(1-3):228-234, 1990. [HAB1] V. Smil. Detonator of the population explosion. Nature, July 29 1999, p 415. [HAB2] J. Schmidhuber (Blog, 2000). Most influential persons of the 20th century (according to Nature, 1999). The Haber-Bosch process has often been called the most important invention of the 20th century[HAB1] as it "detonated the population explosion," driving the world's population from 1.6 billion in 1900 to about 8 billion today. Without it, half of humanity would perish. Billions of people would never have existed without it; soon it will sustain 2 out of 3 persons. [HAI14] T. Haigh (2014). Historical reflections. Actually, Turing did not invent the computer. Communications of the ACM, Vol. 57(1): 36-41, Jan 2014. PDF. [HAI14b] T. Haigh, M. Priestley, C. Rope (2014). Reconsidering the Stored-Program Concept. IEEE Annals of the History of Computing. IEEE, 2014. PDF. [HB96] S. El Hihi, Y. Bengio. Hierarchical recurrent neural networks for long-term dependencies. NIPS, 1996. Bengio claimed[YB20] that in 1995 he "introduced the use of a hierarchy of time scales to combat the vanishing gradients issue" although Schmidhuber's publications on exactly this topic date back to 1991-93.[UN0-2][UN] [HEB49] D. O. Hebb. The Organization of Behavior. Wiley, New York, 1949. https://people.idsia.ch/~juergen/deep-learning-history.html 51/75 29/12/2022, 12:21 [HEL] P. Dayan, G. E. Hinton, R. M. Neal, and R. S. Zemel. The Helmholtz machine. Neural Computation, 7:889-904, 1995. An unsupervised learning algorithm related to Schmidhuber's supervised Neural Heat Exchanger.[NHE] [HIN] J. Schmidhuber (AI Blog, 2020). Critique of Honda Prize for Dr. Hinton. Science must not allow corporate PR to distort the academic record. See also [T22]. [HIN22] G. Hinton. The Forward-Forward Algorithm: Some Preliminary Investigations. Preprint, Google Brain, 2022. Proposal of a biologically more plausible deep learning algorithm that— unlike backpropagation—is local in space and time. Does not mention previous related work. [BB2][NAN1-4][NHE][MIR](Sec. 15, Sec. 17)[FWPMETA6] [HO1] S. Hochreiter, A. S. Younger, P. R. Conwell (2001). Learning to Learn Using Gradient Descent. ICANN 2001. Lecture Notes in Computer Science, 2130, pp. 87-94. [HO66] E. Hochstetter et al. (1966): Herrn von Leibniz' Rechnung mit Null und Eins. Berlin: Siemens AG. [HO07] S. Hochreiter, M. Heusel, K. Obermayer. Fast model-based protein homology detection without alignment. Bioinformatics 23(14):1728-36, 2007. Successful application of deep learning to protein folding problems, through an LSTM that was orders of magnitude faster than competing methods. [HRL0] J. Schmidhuber. Towards compositional learning with dynamic neural networks. Technical Report FKI-129-90, Institut für Informatik, Technische Universität München, 1990. PDF. An RL machine gets extra command inputs of the form (start, goal). An evaluator NN learns to predict the current rewards/costs of going from start to goal. An (R)NN-based subgoal generator also sees (start, goal), and uses (copies of) the evaluator NN to learn by gradient descent a sequence of cost-minimising intermediate subgoals. The RL machine tries to use such subgoal sequences to achieve final goals. The system is learning action plans at multiple levels of abstraction and multiple time scales and solves what Y. LeCun called an "open problem" in 2022.[LEC] [HRL1] J. Schmidhuber. Learning to generate sub-goals for action sequences. In T. Kohonen, K. Mäkisara, O. Simula, and J. Kangas, editors, Artificial Neural Networks, pages 967-972. Elsevier Science Publishers B.V., North-Holland, 1991. PDF. Extending TR FKI-129-90, TUM, 1990. [HRL2] J. Schmidhuber and R. Wahnsiedler. Planning simple trajectories using neural subgoal generators. In J. A. Meyer, H. L. Roitblat, and S. W. Wilson, editors, Proc. of the 2nd International Conference on Simulation of Adaptive Behavior, pages 196-202. MIT Press, 1992. PDF. [HRL3] P. Dayan and G. E. Hinton. Feudal Reinforcement Learning. Advances in Neural Information Processing Systems 5, NIPS, 1992. This work did not cite Schmidhuber's gradient- based subgoal generators for hierarchical reinforcement learning (1990).[HRL0-2] [HRL4] M. Wiering and J. Schmidhuber. HQ-Learning. Adaptive Behavior 6(2):219-246, 1997. PDF. https://people.idsia.ch/~juergen/deep-learning-history.html 52/75 Annotated history of modern AI and deep neural networks 29/12/2022, 12:21 [HRLW] C. Watkins (1989). Learning from delayed rewards. [HW1] R. K. Srivastava, K. Greff, J. Schmidhuber. Highway networks. Preprints arXiv:1505.00387 (May 2015) and arXiv:1507.06228 (July 2015). Also at NIPS 2015. The first working very deep feedforward nets with over 100 layers (previous NNs had at most a few tens of layers). Let g, t, h, denote non-linear differentiable functions. Each non-input layer of a highway net computes g(x)x + t(x)h(x), where x is the data from the previous layer. (Like LSTM with forget gates[LSTM2] for RNNs.) Resnets[HW2] are a version of this where the gates are always open: g(x)=t(x)=const=1. Highway Nets perform roughly as well as ResNets[HW2] on ImageNet. [HW3] Variants of highway gates are also used for certain algorithmic tasks, where the simpler residual layers do not work as well.[NDR] More. [HW1a] R. K. Srivastava, K. Greff, J. Schmidhuber. Highway networks. Presentation at the Deep Learning Workshop, ICML'15, July 10-11, 2015. Link. [HW2] He, K., Zhang, X., Ren, S., Sun, J. Deep residual learning for image recognition. Preprint arXiv:1512.03385 (Dec 2015). Residual nets are a version of Highway Nets[HW1] where the gates are always open: g(x)=1 (a typical highway net initialization) and t(x)=1. More. [HW3] K. Greff, R. K. Srivastava, J. Schmidhuber. Highway and Residual Networks learn Unrolled Iterative Estimation. Preprint arxiv:1612.07771 (2016). Also at ICLR 2017. [HYB12] Hinton, G. E., Deng, L., Yu, D., Dahl, G. E., Mohamed, A., Jaitly, N., Senior, A., Vanhoucke, V., Nguyen, P., Sainath, T. N., and Kingsbury, B. (2012). Deep neural networks for acoustic modeling in speech recognition: The shared views of four research groups. IEEE Signal Process. Mag., 29(6):82-97. This work did not cite the earlier LSTM[LSTM0-6] trained by Connectionist Temporal Classification (CTC, 2006).[CTC] CTC-LSTM was successfully applied to speech in 2007[LSTM4] (also with hierarchical LSTM stacks[LSTM14]) and became the first superior end-to-end neural speech recogniser that outperformed the state of the art, dramatically improving Google's speech recognition.[GSR][GSR15][DL4] This was very different from previous hybrid methods since the late 1980s which combined NNs and traditional approaches such as hidden Markov models (HMMs).[BW][BRI][BOU] [HYB12] still used the old hybrid approach and did not compare it to CTC-LSTM. Later, however, Hinton switched to LSTM, too.[LSTM8] [I24] E. Ising (1925). Beitrag zur Theorie des Ferro- und Paramagnetismus. Dissertation, 1924. [I25] E. Ising (1925). Beitrag zur Theorie des Ferromagnetismus. Z. Phys., 31 (1): 253-258, 1925. Based on [I24]. The first non-learning recurrent NN architecture (the Ising model or Lenz-Ising model) was introduced and analyzed by physicists Ernst Ising and Wilhelm Lenz in the 1920s.[L20][I25][K41][W45][T22] It settles into an equilibrium state in response to input conditions, and is the foundation of the first well-known learning RNNs.[AMH1-2] [IC49] DE 833366 W. Jacobi / SIEMENS AG: Halbleiterverstärker patent filed 14 April 1949, granted 15 May 1952. First integrated circuit with several transistors on a common substrate. [IC14] @CHM Blog, Computer History Museum (2014). Who Invented the IC? [IM09] J. Deng, R. Socher, L.J. Li, K. Li, L. Fei-Fei (2009). Imagenet: A large-scale hierarchical image database. In 2009 IEEE conference on computer vision and pattern recognition, pp. https://people.idsia.ch/~juergen/deep-learning-history.html 53/75 29/12/2022, 12:21 248-255). IEEE, 2009. Annotated history of modern AI and deep neural networks [JOU17] Jouppi et al. (2017). In-Datacenter Performance Analysis of a Tensor Processing Unit. Preprint arXiv:1704.04760 [K41] H. A. Kramers and G. H. Wannier (1941). Statistics of the Two-Dimensional Ferromagnet. Phys. Rev. 60, 252 and 263, 1941. [K56] S.C. Kleene. Representation of Events in Nerve Nets and Finite Automata. Automata Studies, Editors: C.E. Shannon and J. McCarthy, Princeton University Press, p. 3-42, Princeton, N.J., 1956. [KAE96] L. P. Kaelbling, M. L. Littman, A. W. Moore. Reinforcement learning: a survey. Journal of AI research, 4:237-285, 1996. [KAL59] R. Kalman. On the general theory of control systems. IRE Transactions on Automatic Control 4.3 (1959): 110-110. [KAL59a] R. Kalman, J. Bertram. General approach to control theory based on the methods of Lyapunov. IRE Transactions on Automatic Control 4.3 (1959):20-20. [KOE1] [21] T. Koetsier (2001). On the prehistory of programmable machines: musical automata, looms, calculators. Mechanism and Machine Theory, Elsevier, 36 (5): 589-603, 2001. [KOH72] T. Kohonen. Correlation Matrix Memories. IEEE Transactions on Computers, C-21, p. 353-359, 1972. [KOH82] T. Kohonen. Self-organized formation of topologically correct feature maps. Biological Cybernetics, 43(1):59-69, 1982. [KOH88] T. Kohonen. Self-Organization and Associative Memory. Springer, second edition, 1988. [KOH89] H. Ritter, T. Kohonen. Self-organizing semantic maps. Biological Cybernetics, 61(4):241-254, 1989. [KNU] D. E. Knuth, L. T. Pardo (1976). The Early Development of Programming Languages. Stanford University, Computer Science Department. PDF. [KO2] J. Schmidhuber. Discovering neural nets with low Kolmogorov complexity and high generalization capability. Neural Networks, 10(5):857-873, 1997. PDF. [KU] A. Küchler & C. Goller (1996). Inductive learning in symbolic domains using structure- driven recurrent neural networks. Lecture Notes in Artificial Intelligence, vol 1137. Springer, Berlin, Heidelberg. [KUL] S. Kullback, R. A. Leibler. On information and sufficiency. The Annals of Mathematical Statistics, pages 79-86, 1951. https://people.idsia.ch/~juergen/deep-learning-history.html 54/75 29/12/2022, 12:21 [L03] G. Leibniz (1703). In: Explication de l'Arithmetique Binaire / Die Mathematischen Schriften, ed. C. Gerhardt, Berlin 1879, vol.7, p.223. English link. Leibniz documented the binary arithmetics which allow for greatly simplifiying computing hardware and are employed by virtually all modern computers. Binary number encodings per se, however, seem to date back over 4000 years. [L79] G. Leibniz. De Progressione dyadica Pars I. 15 March 1679. Principles of binary computers governed by punch cards. [L84] G. Leibniz (1684). Nova Methodus pro Maximis et Minimis. First publication of "modern" infinitesimal calculus. [L86] G. Leibniz (1686). Generales Inquisitiones de analysi notionum et veritatum. Also in Leibniz: Die philosophischen Schriften VII, 1890, pp. 236-247; translated as "A Study in the Calculus of Real Addition" (1690) by G. H. R. Parkinson, Leibniz: Logical Papers—A Selection, Oxford 1966, pp. 131-144. [L20] W. Lenz (1920). Beitrag zum Verständnis der magnetischen Erscheinungen in festen Körpern. Physikalische Zeitschrift, 21:613-615. See also [I25]. [LA14] D. R. Lande (2014). Development of the Binary Number System and the Foundations of Computer Science. The Mathematics Enthusiast, vol. 11(3):6 12, 2014. Link. [LAN] J. L. Ba, J. R.Kiros, G. E. Hinton. Layer Normalization. arXiv:1607.06450, 2016. [LE18] W. Lenzen. Leibniz and the Calculus Ratiocinator. Technology and Mathematics, pp 47- 78, Springer, 2018. [LEC] J. Schmidhuber (AI Blog, 2022). LeCun's 2022 paper on autonomous machine intelligence rehashes but does not cite essential work of 1990-2015. Years ago, Schmidhuber's team published most of what Y. LeCun calls his "main original contributions:" neural nets that learn multiple time scales and levels of abstraction, generate subgoals, use intrinsic motivation to improve world models, and plan (1990); controllers that learn informative predictable representations (1997), etc. This was also discussed on Hacker News, reddit, and in the media. See tweet1. LeCun also listed the "5 best ideas 2012-2022" without mentioning that most of them are from Schmidhuber's lab, and older. See tweet2. [LEI07] J. M. Child (translator), G. W. Leibniz (Author). The Early Mathematical Manuscripts of Leibniz. Merchant Books, 2007. See p. 126: the chain rule appeared in a 1676 memoir by Leibniz. [LEI10] O. H. Rodriguez, J. M. Lopez Fernandez (2010). A semiotic reflection on the didactics of the Chain rule. The Mathematics Enthusiast: Vol. 7 : No. 2 , Article 10. DOI: https://doi.org/10.54870/1551-3440.1191. [LEI21] J. Schmidhuber (AI Blog, 2021). 375th birthday of Leibniz, founder of computer science. https://people.idsia.ch/~juergen/deep-learning-history.html 55/75 29/12/2022, 12:21 [LEI21a] J. Schmidhuber (2021). Der erste Informatiker. Wie Gottfried Wilhelm Leibniz den Computer erdachte. (The first computer scientist. How Gottfried Wilhelm Leibniz conceived the computer.) Frankfurter Allgemeine Zeitung (FAZ), 17/5/2021. FAZ online: 19/5/2021. [LEI21b] J. Schmidhuber (AI Blog, 2021). 375. Geburtstag des Herrn Leibniz, dem Vater der Informatik. [LEN83] D. B. Lenat. Theory formation by heuristic search. Machine Learning, 21, 1983. [LIL1] US Patent 1745175 by Austrian physicist Julius Edgar Lilienfeld for work done in Leipzig: "Method and apparatus for controlling electric current." First filed in Canada on 22.10.1925. The patent describes a field-effect transistor. Today, almost all transistors are field-effect transistors. [LIL2] US Patent 1900018 by Austrian physicist Julius Edgar Lilienfeld: "Device for controlling electric current." Filed on 28.03.1928. The patent describes a thin film field-effect transistor. Today, almost all transistors are field-effect transistors. [LIT21] M. L. Littman (2021). Collusion Rings Threaten the Integrity of Computer Science Research. Communications of the ACM, Vol. 64 No. 6, p. 43-44, June 2021. [LSTM0] S. Hochreiter and J. Schmidhuber. Long Short-Term Memory. TR FKI-207-95, TUM, August 1995. PDF. [LSTM1] S. Hochreiter, J. Schmidhuber. Long Short-Term Memory. Neural Computation, 9(8):1735-1780, 1997. PDF. Based on [LSTM0]. More. [LSTM2] F. A. Gers, J. Schmidhuber, F. Cummins. Learning to Forget: Continual Prediction with LSTM. Neural Computation, 12(10):2451-2471, 2000. PDF. The "vanilla LSTM architecture" with forget gates that everybody is using today, e.g., in Google's Tensorflow. [LSTM3] A. Graves, J. Schmidhuber. Framewise phoneme classification with bidirectional LSTM and other neural network architectures. Neural Networks, 18:5-6, pp. 602-610, 2005. PDF. [LSTM4] S. Fernandez, A. Graves, J. Schmidhuber. An application of recurrent neural networks to discriminative keyword spotting. Intl. Conf. on Artificial Neural Networks ICANN'07, 2007. PDF. [LSTM5] A. Graves, M. Liwicki, S. Fernandez, R. Bertolami, H. Bunke, J. Schmidhuber. A Novel Connectionist System for Improved Unconstrained Handwriting Recognition. IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 31, no. 5, 2009. PDF. [LSTM6] A. Graves, J. Schmidhuber. Offline Handwriting Recognition with Multidimensional Recurrent Neural Networks. NIPS'22, p 545-552, Vancouver, MIT Press, 2009. PDF. [LSTM7] J. Bayer, D. Wierstra, J. Togelius, J. Schmidhuber. Evolving memory cell structures for sequence learning. Proc. ICANN-09, Cyprus, 2009. PDF. https://people.idsia.ch/~juergen/deep-learning-history.html 56/75 29/12/2022, 12:21 [LSTM8] A. Graves, A. Mohamed, G. E. Hinton. Speech Recognition with Deep Recurrent Neural Networks. ICASSP 2013, Vancouver, 2013. PDF. Based on [LSTM1-2,4,14][CTC]. [LSTM9] O. Vinyals, L. Kaiser, T. Koo, S. Petrov, I. Sutskever, G. Hinton. Grammar as a Foreign Language. Preprint arXiv:1412.7449 [cs.CL]. [LSTM10] A. Graves, D. Eck and N. Beringer, J. Schmidhuber. Biologically Plausible Speech Recognition with LSTM Neural Nets. In J. Ijspeert (Ed.), First Intl. Workshop on Biologically Inspired Approaches to Advanced Information Technology, Bio-ADIT 2004, Lausanne, Switzerland, p. 175-184, 2004. PDF. [LSTM11] N. Beringer and A. Graves and F. Schiel and J. Schmidhuber. Classifying unprompted speech by retraining LSTM Nets. In W. Duch et al. (Eds.): Proc. Intl. Conf. on Artificial Neural Networks ICANN'05, LNCS 3696, pp. 575-581, Springer-Verlag Berlin Heidelberg, 2005. [LSTM12] D. Wierstra, F. Gomez, J. Schmidhuber. Modeling systems with internal state using Evolino. In Proc. of the 2005 conference on genetic and evolutionary computation (GECCO), Washington, D. C., pp. 1795-1802, ACM Press, New York, NY, USA, 2005. Got a GECCO best paper award. [LSTM13] F. A. Gers and J. Schmidhuber. LSTM Recurrent Networks Learn Simple Context Free and Context Sensitive Languages. IEEE Transactions on Neural Networks 12(6):1333- 1340, 2001. PDF. [LSTM14] S. Fernandez, A. Graves, J. Schmidhuber. Sequence labelling in structured domains with hierarchical recurrent neural networks. In Proc. IJCAI 07, p. 774-779, Hyderabad, India, 2007 (talk). PDF. [LSTM15] A. Graves, J. Schmidhuber. Offline Handwriting Recognition with Multidimensional Recurrent Neural Networks. Advances in Neural Information Processing Systems 22, NIPS'22, p 545-552, Vancouver, MIT Press, 2009. PDF. [LSTM16] M. Stollenga, W. Byeon, M. Liwicki, J. Schmidhuber. Parallel Multi-Dimensional LSTM, With Application to Fast Biomedical Volumetric Image Segmentation. Advances in Neural Information Processing Systems (NIPS), 2015. Preprint: arxiv:1506.07452. [LSTM17] J. A. Perez-Ortiz, F. A. Gers, D. Eck, J. Schmidhuber. Kalman filters improve LSTM network performance in problems unsolvable by traditional recurrent nets. Neural Networks 16(2):241-250, 2003. PDF. [LSTMPG] J. Schmidhuber (AI Blog, Dec 2020). 10-year anniversary of our journal paper on deep reinforcement learning with policy gradients for LSTM (2007-2010). Recent famous applications: DeepMind's Starcraft player (2019) and OpenAI's dextrous robot hand & Dota player (2018)—Bill Gates called this a huge milestone in advancing AI. [LSTM-RL] B. Bakker, F. Linaker, J. Schmidhuber. Reinforcement Learning in Partially Observable Mobile Robot Domains Using Unsupervised Event Extraction. In Proceedings of https://people.idsia.ch/~juergen/deep-learning-history.html 57/75 29/12/2022, 12:21 the 2002 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS 2002), Lausanne, 2002. PDF. [LSTMGRU] J. Chung, C. Gulcehre, K. Cho, Y. Bengio (2014). Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling. Preprint arXiv:1412.3555 [cs.NE]. The so- called gated recurrent units (GRU) are actually a variant of the vanilla LSTM architecture[LSTM2] (2000) which the authors did not cite although this work[LSTM2] was the one that introduced gated recurrent units. Furthermore, Schmidhuber's team automatically evolved lots of additional LSTM variants and topologies already in 2009[LSTM7] without changing the name of the basic method. (Margin note: GRU cells lack an important gate and can neither learn to count[LSTMGRU2] nor learn simple non-regular languages;[LSTMGRU2] they also do not work as well for challenging translation tasks, according to Google Brain.[LSTMGRU3]) [LSTMGRU2] G. Weiss, Y. Goldberg, E. Yahav. On the Practical Computational Power of Finite Precision RNNs for Language Recognition. Preprint arXiv:1805.04908. [LSTMGRU3] D. Britz et al. (2017). Massive Exploration of Neural Machine Translation Architectures. Preprint arXiv:1703.03906 [M69] M. Minsky, S. Papert. Perceptrons (MIT Press, Cambridge, MA, 1969). A misleading "history of deep learning" goes more or less like this: "In 1969, Minsky & Papert[M69] showed that shallow NNs without hidden layers are very limited and the field was abandoned until a new generation of neural network researchers took a fresh look at the problem in the 1980s." [S20] However, the 1969 book[M69] addressed a "problem" of Gauss & Legendre's shallow learning (circa 1800)[DL1-2] that had already been solved 4 years prior by Ivakhnenko & Lapa's popular deep learning method,[DEEP1-2][DL2] and then also by Amari's SGD for MLPs.[GD1-2] Minsky was apparently unaware of this and failed to correct it later.[HIN](Sec. I)[T22](Sec. XIII) [MACY51] H. Foerster, M. Mead, H. L. Teuber (eds.). Cybernetics: Circular causal and feedback mechanisms in biological and social systems. Transactions of the 7th conference. New York: J. Macy Jr. Foundation, 1951. [MAD86] C. T. Rajagopal, M. S. Rangachari (1986). On medieval Keralese mathematics. Archive for History of Exact Sciences. 35 (2):91-99. [MAD01] D. F. Almeida, J. K. John, A. Zadorozhnyy (2001). Keralese mathematics: Its Possible Transmission to Europe and the Consequential Educational Implications. Journal of Natural Geometry 20, 77-104, 2001. [MAR71] D. Marr. Simple memory: a theory for archicortex. Philos Trans R Soc Lond B Biol Sci, 262:841, p 23-81, 1971. [MAD05] Neither Newton nor Leibniz—The Pre-History of Calculus and Celestial Mechanics in Medieval Kerala. S. Rajeev, Univ. of Rochester, 2005. [MAR15] E. Davis, G. Marcus. Commonsense Reasoning and Commonsense Knowledge in Artificial Intelligence. Communications of the ACM 58.9:92-103, 2015. https://people.idsia.ch/~juergen/deep-learning-history.html 58/75 29/12/2022, 12:21 [MC43] W. S. McCulloch, W. Pitts. A Logical Calculus of Ideas Immanent in Nervous Activity. Bulletin of Mathematical Biophysics, Vol. 5, p. 115-133, 1943. [META] J. Schmidhuber (AI Blog, 2020). 1/3 century anniversary of first publication on metalearning machines that learn to learn (1987). For its cover Schmidhuber drew a robot that bootstraps itself. 1992-: gradient descent-based neural metalearning. 1994-: Meta- Reinforcement Learning with self-modifying policies. 1997: Meta-RL plus artificial curiosity and intrinsic motivation. 2002-: asymptotically optimal metalearning for curriculum learning. 2003-: mathematically optimal Gödel Machine. 2020: new stuff! [META1] J. Schmidhuber. Evolutionary principles in self-referential learning, or on learning how to learn: The meta-meta-... hook. Diploma thesis, Institut für Informatik, Technische Universität München, 1987. Searchable PDF scan (created by OCRmypdf which uses LSTM). HTML. For example, Genetic Programming (GP) is applied to itself, to recursively evolve better GP methods through Meta-Evolution. More. [MGC] MICCAI 2013 Grand Challenge on Mitosis Detection, organised by M. Veta, M.A. Viergever, J.P.W. Pluim, N. Stathonikos, P. J. van Diest of University Medical Center Utrecht. [MIR] J. Schmidhuber (AI Blog, Oct 2019, updated 2021, 2022). Deep Learning: Our Miraculous Year 1990-1991. Preprint arXiv:2005.05744, 2020. The deep learning neural networks of Schmidhuber's team have revolutionised pattern recognition and machine learning, and are now heavily used in academia and industry. In 2020-21, we celebrate that many of the basic ideas behind this revolution were published within fewer than 12 months in the "Annus Mirabilis" 1990-1991 at TU Munich. [MIT97] T. Mitchell. Machine Learning. McGraw Hill, 1997. [MLP1] D. C. Ciresan, U. Meier, L. M. Gambardella, J. Schmidhuber. Deep Big Simple Neural Nets For Handwritten Digit Recognition. Neural Computation 22(12): 3207-3220, 2010. ArXiv Preprint. Showed that plain backprop for deep standard NNs is sufficient to break benchmark records, without any unsupervised pre-training. [MLP2] J. Schmidhuber (AI Blog, Sep 2020). 10-year anniversary of supervised deep learning breakthrough (2010). No unsupervised pre-training. By 2010, when compute was 100 times more expensive than today, both the feedforward NNs[MLP1] and the earlier recurrent NNs of Schmidhuber's team were able to beat all competing algorithms on important problems of that time. This deep learning revolution quickly spread from Europe to North America and Asia. The rest is history. [MM1] R. Stratonovich (1960). Conditional Markov processes. Theory of Probability and its Applications, 5(2):156-178. [MM2] L. E. Baum, T. Petrie. Statistical inference for probabilistic functions of finite state Markov chains. The Annals of Mathematical Statistics, pages 1554-1563, 1966. [MM3] A. P. Dempster, N. M. Laird, D. B. Rubin. Maximum likelihood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society, B, 39, 1977. https://people.idsia.ch/~juergen/deep-learning-history.html 59/75 29/12/2022, 12:21 [MM4] J. Friedman, T. Hastie, R. Tibshirani. The elements of statistical learning, volume 1. Springer Series in Statistics, New York, 2001. [MM5] C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. [MOC1] N. Metropolis, S. Ulam. The Monte Carlo method. Journal of the American Statistical Association. 44 (247): 335-341, 1949. [MOC2] B. Abramson. The Expected-Outcome Model of Two-Player Games. Technical report, Department of Computer Science, Columbia University, 1987. [MOC3] B. Brügmann. Monte Carlo Go. Technical report, Department of Physics, Syracuse University, 1993. [MOC4] H. S. Chang, M. C. Fu, J. Hu, S. I. Marcus. An Adaptive Sampling Algorithm for Solving Markov Decision Processes. Operations Research. 53:126-139, 2005. [MOC5] R. Coulom. Efficient Selectivity and Backup Operators in Monte-Carlo Tree Search. Computers and Games, 5th International Conference, CG 2006, Turin, Italy, May 29–31, 2006. [MOST] J. Schmidhuber (AI Blog, 2021). The most cited neural networks all build on work done in my labs. Foundations of the most popular NNs originated in Schmidhuber's labs at TU Munich and IDSIA. (1) Long Short-Term Memory (LSTM), (2) ResNet (which is the earlier Highway Net with open gates), (3) AlexNet and VGG Net (both building on the similar earlier DanNet: the first deep convolutional NN to win image recognition competitions), (4) Generative Adversarial Networks (an instance of the much earlier Adversarial Artificial Curiosity), and (5) variants of Transformers (Transformers with linearized self-attention are formally equivalent to the much earlier Fast Weight Programmers). Most of this started with the Annus Mirabilis of 1990-1991.[MIR] [MOZ] M. Mozer. A Focused Backpropagation Algorithm for Temporal Pattern Recognition. Complex Systems, 1989. [MUN87] P. W. Munro. A dual back-propagation scheme for scalar reinforcement learning. Proceedings of the Ninth Annual Conference of the Cognitive Science Society, Seattle, WA, pages 165-176, 1987. [NAK72] K. Nakano. Associatron—A Model of Associative Memory. IEEE Transactions on Systems, Man, and Cybernetics, SMC-2:3 p. 380-388, 1972. [NAN1] J. Schmidhuber. Networks adjusting networks. In J. Kindermann and A. Linden, editors, Proceedings of `Distributed Adaptive Neural Information Processing', St.Augustin, 24.-25.5. 1989, pages 197-208. Oldenbourg, 1990. Extended version: TR FKI-125-90 (revised), Institut für Informatik, TUM. PDF. Includes the proposal of a biologically more plausible deep learning algorithm that—unlike backpropagation—is local in space and time. Based on neural nets learning to estimate gradients for other neural nets. https://people.idsia.ch/~juergen/deep-learning-history.html 60/75 29/12/2022, 12:21 [NAN2] J. Schmidhuber. Networks adjusting networks. Technical Report FKI-125-90, Institut für Informatik, Technische Universität München. Revised in November 1990. PDF. [NAN3] Recurrent networks adjusted by adaptive critics. In Proc. IEEE/INNS International Joint Conference on Neural Networks, Washington, D. C., volume 1, pages 719-722, 1990. [NAN4] J. Schmidhuber. Additional remarks on G. Lukes' review of Schmidhuber's paper `Recurrent networks adjusted by adaptive critics'. Neural Network Reviews, 4(1):43, 1990. [NAN5] M. Jaderberg, W. M. Czarnecki, S. Osindero, O. Vinyals, A. Graves, D. Silver, K. Kavukcuoglu. Decoupled Neural Interfaces using Synthetic Gradients. Preprint arXiv:1608.05343, 2016. This work of DeepMind is similar to [NAN1-2]. [NAR90] K. S. Narendra, K. Parthasarathy. Identification and control of dynamical systems using neural networks. Neural Networks, IEEE Transactions on, 1(1):4-27, 1990. [NAS] B. Zoph, Q. V. Le. Neural Architecture Search with Reinforcement Learning. Preprint arXiv:1611.01578 (PDF), 2017. Compare the earlier Neural Architecture Search of Bayer et al. (2009) for LSTM-like topologies.[LSTM7] [NASC1] J. Schmidhuber. First Pow(d)ered flight / plane truth. Correspondence, Nature, 421 p 689, Feb 2003. [NASC2] J. Schmidhuber. Zooming in on aviation history. Correspondence, Nature, vol 566, p 39, 7 Feb 2019. [NASC3] J. Schmidhuber. The last inventor of the telephone. Letter, Science, 319, no. 5871, p. 1759, March 2008. [NASC4] J. Schmidhuber. Turing: Keep his work in perspective. Correspondence, Nature, vol 483, p 541, March 2012, doi:10.1038/483541b. [NASC5] J. Schmidhuber. Turing in Context. Letter, Science, vol 336, p 1639, June 2012. (On Gödel, Zuse, Turing.) See also comment on response by A. Hodges (DOI:10.1126/science.336.6089.1639-a) [NASC6] J. Schmidhuber. Colossus was the first electronic digital computer. Correspondence, Nature, 441 p 25, May 2006. [NASC6a] J. Schmidhuber. Comment on "Biography: The ABC of computing" by J. Gilbey, Nature 468 p 760-761 (2010). Link. [NASC7] J. Schmidhuber. Turing's impact. Correspondence, Nature, 429 p 501, June 2004 [NASC8] J. Schmidhuber. Prototype resilient, self-modeling robots. Correspondence, Science, 316, no. 5825 p 688, May 2007. [NASC9] J. Schmidhuber. Comparing the legacies of Gauss, Pasteur, Darwin. Correspondence, Nature, vol 452, p 530, April 2008. https://people.idsia.ch/~juergen/deep-learning-history.html 61/75 29/12/2022, 12:21 [NAT1] J. Schmidhuber. Citation bubble about to burst? Nature, vol. 469, p. 34, 6 January 2011. HTML. [NDR] R. Csordas, K. Irie, J. Schmidhuber. The Neural Data Router: Adaptive Control Flow in Transformers Improves Systematic Generalization. Proc. ICLR 2022. Preprint arXiv/2110.07732. [NEU45] J. von Neumann (1945). First Draft of a Report on the EDVAC. [NHE] J. Schmidhuber. The Neural Heat Exchanger. Oral presentations since 1990 at various universities including TUM and the University of Colorado at Boulder. Also in In S. Amari, L. Xu, L. Chan, I. King, K. Leung, eds., Proceedings of the Intl. Conference on Neural Information Processing (1996), pages 194-197, Springer, Hongkong. Link. Proposal of a biologically more plausible deep learning algorithm that—unlike backpropagation—is local in space and time. Inspired by the physical heat exchanger: inputs "heat up" while being transformed through many successive layers, targets enter from the other end of the deep pipeline and "cool down." [NGU89] D. Nguyen and B. Widrow; The truck backer-upper: An example of self learning in neural networks. In IEEE/INNS International Joint Conference on Neural Networks, Washington, D.C., volume 1, pages 357-364, 1989. [NIL98] N. J. Nilsson. Artificial intelligence: a new synthesis. Morgan Kaufmann, 1998. [NPMa] M. Nakamura, K. Shikano. A study of English word category prediction based on neural networks. Proc. IEEE Int. Conf. on Acoustics, Speech and Signal Processing (ICASSP), p. 731-734, 1989. [NPM] Y. Bengio, R. Ducharme, P. Vincent, C. Jauvin (2003). A Neural Probabilistic Language Model. Journal of Machine Learning Research 3, p 1137-1155, 2003. Based on Schmidhuber & Heil's excellent 1995 neural probabilistic text model.[SNT] See also Nakamura and Shikano's 1989 word category prediction model.[NPMa] [NS56] A. Newell and H. Simon. The logic theory machine—A complex information processing system. IRE Transactions on Information Theory 2.3 (1956):61-79. Compare Konrad Zuse's much earlier 1948 work on theorem proving[ZU48] based on Plankalkül, the first high-level programming language.[BAU][KNU] [NS59] A. Newell, J. C. Shaw, H. Simon. Report on a general problem solving program. IFIP congress, vol. 256, 1959. [NYT1] NY Times article by J. Markoff, Nov. 27, 2016: When A.I. Matures, It May Call Jürgen Schmidhuber 'Dad' [OAI1] G. Powell, J. Schneider, J. Tobin, W. Zaremba, A. Petron, M. Chociej, L. Weng, B. McGrew, S. Sidor, A. Ray, P. Welinder, R. Jozefowicz, M. Plappert, J. Pachocki, M. Andrychowicz, B. Baker. Learning Dexterity. OpenAI Blog, 2018. [OAI1a] OpenAI, M. Andrychowicz, B. Baker, M. Chociej, R. Jozefowicz, B. McGrew, J. Pachocki, A. Petron, M. Plappert, G. Powell, A. Ray, J. Schneider, S. Sidor, J. Tobin, P. https://people.idsia.ch/~juergen/deep-learning-history.html 62/75 29/12/2022, 12:21 Welinder, L. Weng, W. Zaremba. Learning Dexterous In-Hand Manipulation. arxiv:1312.5602 (PDF). [OAI2] OpenAI: C. Berner, G. Brockman, B. Chan, V. Cheung, P. Debiak, C. Dennison, D. Farhi, Q. Fischer, S. Hashme, C. Hesse, R. Jozefowicz, S. Gray, C. Olsson, J. Pachocki, M. Petrov, H. P. de Oliveira Pinto, J. Raiman, T. Salimans, J. Schlatter, J. Schneider, S. Sidor, I. Sutskever, J. Tang, F. Wolski, S. Zhang (Dec 2019). Dota 2 with Large Scale Deep Reinforcement Learning. Preprint arxiv:1912.06680. An LSTM composes 84% of the model's total parameter count. [OAI2a] J. Rodriguez. The Science Behind OpenAI Five that just Produced One of the Greatest Breakthrough in the History of AI. Towards Data Science, 2018. An LSTM with 84% of the model's total parameter count was the core of OpenAI Five. [OMG0] P. T. De Chardin. The antiquity and world expansion of human culture. Man's Role in Changing the Face of the Earth. Univ. Chicago Press, Chicago, p. 103-112, 1956. [OMG] J. Schmidhuber. An exponential acceleration pattern in the history of the most important events from a human perspective, reaching all the way back to the Big Bang. Link. Ask me Anything, Reddit/ML, 2014. [OMG1] J. Schmidhuber (Blog, 2006). Is History Converging? Again? Based on: J. Schmidhuber. New Millennium AI and the Convergence of History. In W. Duch and J. Mandziuk, eds., Challenges to Computational Intelligence, Springer, 2006. Update of 2012 in: Singularity Hypotheses, Springer, 2013. [OMG2] S. Berg. GRM: Brainfuck. Kiepenheuer & Witsch, 2019. Got the Swiss Book Award 2019. Contains 2 pages on Schmidhuber's timeline of history's exponential acceleration since the Big Bang.[OMG] [OBJ1] K. Greff, A. Rasmus, M. Berglund, T. Hao, H. Valpola, J. Schmidhuber (2016). Tagger: Deep unsupervised perceptual grouping. NIPS 2016, pp. 4484-4492. Preprint arXiv/1606.06724. [OBJ2] K. Greff, S. van Steenkiste, J. Schmidhuber (2017). Neural expectation maximization. NIPS 2017, pp. 6691-6701. Preprint arXiv/1708.03498. [OBJ3] S. van Steenkiste, M. Chang, K. Greff, J. Schmidhuber (2018). Relational neural expectation maximization: Unsupervised discovery of objects and their interactions. ICLR 2018. Preprint arXiv/1802.10353. [OBJ4] A. Stanic, S. van Steenkiste, J. Schmidhuber (2021). Hierarchical Relational Inference. AAAI 2021. Preprint arXiv/2010.03635. [OBJ5] A. Gopalakrishnan, S. van Steenkiste, J. Schmidhuber (2020). Unsupervised Object Keypoint Learning using Local Spatial Predictability. Preprint arXiv/2011.12930. [OOPS2] J. Schmidhuber. Optimal Ordered Problem Solver. Machine Learning, 54, 211-254, 2004. PDF. HTML. HTML overview. Download OOPS source code in crystalline format. https://people.idsia.ch/~juergen/deep-learning-history.html 63/75 29/12/2022, 12:21 [OUD13] P.-Y. Oudeyer, A. Baranes, F. Kaplan. Intrinsically motivated learning of real world sensorimotor skills with developmental constraints. In G. Baldassarre and M. Mirolli, editors, Intrinsically Motivated Learning in Natural and Artificial Systems. Springer, 2013. [PAL80] G. Palm. On associative memory. Biological Cybernetics, 36, 1980. [PAT17] D. Pathak, P. Agrawal, A. A. Efros, T. Darrell. Curiosity-driven exploration by self- supervised prediction. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition Workshops, pages 16-17, 2017. [PDA1] G.Z. Sun, H.H. Chen, C.L. Giles, Y.C. Lee, D. Chen. Neural Networks with External Memory Stack that Learn Context—Free Grammars from Examples. Proceedings of the 1990 Conference on Information Science and Systems, Vol.II, pp. 649-653, Princeton University, Princeton, NJ, 1990. [PDA2] M. Mozer, S. Das. A connectionist symbol manipulator that discovers the structure of context-free languages. Proc. NIPS 1993. [PG1] R. J. Williams. Reinforcement-learning in connectionist networks: A mathematical analysis. Technical Report 8605, Institute for Cognitive Science, University of California, San Diego, 1986 [PG3] R. J. Williams. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine Learning 8.3-4: 229-256, 1992. [PG2] Sutton, R. S., McAllester, D. A., Singh, S. P., and Mansour, Y. (1999a). Policy gradient methods for reinforcement learning with function approximation. In Advances in Neural Information Processing Systems (NIPS) 12, pages 1057-1063. [PHD] J. Schmidhuber. Dynamische neuronale Netze und das fundamentale raumzeitliche Lernproblem (Dynamic neural nets and the fundamental spatio-temporal credit assignment problem). Dissertation, Institut für Informatik, Technische Universität München, 1990. PDF. HTML. [PLAG1] Oxford's guidance to types of plagiarism (2021). Quote: "Plagiarism may be intentional or reckless, or unintentional." Link. [PLAN] J. Schmidhuber (AI Blog, 2020). 30-year anniversary of planning & reinforcement learning with recurrent world models and artificial curiosity (1990). This work also introduced high-dimensional reward signals, deterministic policy gradients for RNNs, and the GAN principle (widely used today). Agents with adaptive recurrent world models even suggest a simple explanation of consciousness & self-awareness. [PLAN2] J. Schmidhuber. An on-line algorithm for dynamic reinforcement learning and planning in reactive environments. Proc. IEEE/INNS International Joint Conference on Neural Networks, San Diego, volume 2, pages 253-258, 1990. Based on TR FKI-126-90 (1990).[AC90] More. https://people.idsia.ch/~juergen/deep-learning-history.html 64/75 29/12/2022, 12:21 [PLAN3] J. Schmidhuber. Reinforcement learning in Markovian and non-Markovian environments. In D. S. Lippman, J. E. Moody, and D. S. Touretzky, editors, Advances in Neural Information Processing Systems 3, NIPS'3, pages 500-506. San Mateo, CA: Morgan Kaufmann, 1991. PDF. Partially based on TR FKI-126-90 (1990).[AC90] [PLAN4] J. Schmidhuber. On Learning to Think: Algorithmic Information Theory for Novel Combinations of Reinforcement Learning Controllers and Recurrent Neural World Models. Report arXiv:1210.0118 [cs.AI], 2015. [PLAN5] One Big Net For Everything. Preprint arXiv:1802.08864 [cs.AI], Feb 2018. [PLAN6] D. Ha, J. Schmidhuber. Recurrent World Models Facilitate Policy Evolution. Advances in Neural Information Processing Systems (NIPS), Montreal, 2018. (Talk.) Preprint: arXiv:1809.01999. Github: World Models. [PM0] J. Schmidhuber. Learning factorial codes by predictability minimization. TR CU-CS-565- 91, Univ. Colorado at Boulder, 1991. PDF. More. [PM1] J. Schmidhuber. Learning factorial codes by predictability minimization. Neural Computation, 4(6):863-879, 1992. Based on [PM0], 1991. PDF. More. [PM2] J. Schmidhuber, M. Eldracher, B. Foltin. Semilinear predictability minimization produces well-known feature detectors. Neural Computation, 8(4):773-786, 1996. PDF. More. [PO87] J. B. Pollack. On Connectionist Models of Natural Language Processing. PhD thesis, Computer Science Department, University of Illinois, Urbana, 1987. [PO90] J. B. Pollack. Recursive Distributed Representations. Artificial Intelligence, 46(1-2):77- 105, 1990. [POS] E. L. Post (1936). Finite Combinatory Processes—Formulation 1. Journal of Symbolic Logic. 1: 103-105. Link. [PP] J. Schmidhuber. POWERPLAY: Training an Increasingly General Problem Solver by Continually Searching for the Simplest Still Unsolvable Problem. Frontiers in Cognitive Science, 2013. ArXiv preprint (2011): arXiv:1112.5309 [cs.AI] [PPa] R. K. Srivastava, B. R. Steunebrink, M. Stollenga, J. Schmidhuber. Continually Adding Self-Invented Problems to the Repertoire: First Experiments with POWERPLAY. Proc. IEEE Conference on Development and Learning / EpiRob 2012 (ICDL-EpiRob'12), San Diego, 2012. PDF. [PP1] R. K. Srivastava, B. Steunebrink, J. Schmidhuber. First Experiments with PowerPlay. Neural Networks, 2013. ArXiv preprint (2012): arXiv:1210.8385 [cs.AI]. [PP2] V. Kompella, M. Stollenga, M. Luciw, J. Schmidhuber. Continual curiosity-driven skill acquisition from high-dimensional video inputs for humanoid robots. Artificial Intelligence, 2015. https://people.idsia.ch/~juergen/deep-learning-history.html 65/75 29/12/2022, 12:21 Relevant threads with many comments at reddit.com/r/MachineLearning, the largest machine learning forum with over 800k subscribers in 2019 (note that Jürgen Schmidhuber's name is often misspelled): [R1] Reddit/ML, 2019. Hinton, LeCun, Bengio receive ACM Turing Award. This announcement contains more comments about Schmidhuber than about any of the awardees. [R2] Reddit/ML, 2019. J. Schmidhuber really had GANs in 1990. [R3] Reddit/ML, 2019. NeurIPS 2019 Bengio Schmidhuber Meta-Learning Fiasco. Schmidhuber started metalearning (learning to learn—now a hot topic) in 1987[META1][META] long before Bengio who suggested in public at N(eur)IPS 2019 that he did it before Schmidhuber. [R4] Reddit/ML, 2019. Five major deep learning papers by G. Hinton did not cite similar earlier work by J. Schmidhuber. [R5] Reddit/ML, 2019. The 1997 LSTM paper by Hochreiter & Schmidhuber has become the most cited deep learning research paper of the 20th century. [R6] Reddit/ML, 2019. DanNet, the CUDA CNN of Dan Ciresan in J. Schmidhuber's team, won 4 image recognition challenges prior to AlexNet. [R7] Reddit/ML, 2019. J. Schmidhuber on Seppo Linnainmaa, inventor of backpropagation in 1970. [R8] Reddit/ML, 2019. J. Schmidhuber on Alexey Ivakhnenko, godfather of deep learning 1965. [R9] Reddit/ML, 2019. We find it extremely unfair that Schmidhuber did not get the Turing award. That is why we dedicate this song to Juergen to cheer him up. [R11] Reddit/ML, 2020. Schmidhuber: Critique of Honda Prize for Dr. Hinton [R12] Reddit/ML, 2020. J. Schmidhuber: Critique of Turing Award for Drs. Bengio & Hinton & LeCun [R15] Reddit/ML, 2021. J. Schmidhuber's work on fast weights from 1991 is similar to linearized variants of Transformers [R58] Rosenblatt, F. (1958). The perceptron: a probabilistic model for information storage and organization in the brain. Psychological review, 65(6):386. This paper not only described single layer perceptrons, but also deeper multilayer perceptrons (MLPs). Although these MLPs did not yet have deep learning, because only the last layer learned,[DL1] Rosenblatt basically had what much later was rebranded as Extreme Learning Machines (ELMs) without proper attribution.[ELM1-2][CONN21][T22] [R61] Joseph, R. D. (1961). Contributions to perceptron theory. PhD thesis, Cornell Univ. [R62] Rosenblatt, F. (1962). Principles of Neurodynamics. Spartan, New York. https://people.idsia.ch/~juergen/deep-learning-history.html 66/75 29/12/2022, 12:21 [RAU1] M. Rausch. Heron von Alexandria. Die Automatentheater und die Erfindung der ersten antiken Programmierung. Diplomica Verlag GmbH, Hamburg 2012. Perhaps the world's first programmable machine was an automatic theatre made in the 1st century by Heron of Alexandria, who apparently also had the first known working steam engine. [RAW] J. Schmidhuber (AI Blog, 2001). Raw Computing Power. [RCNN] R. Girshick, J. Donahue, T. Darrell, J. Malik. Rich feature hierarchies for accurate object detection and semantic segmentation. Preprint arXiv/1311.2524, Nov 2013. [RCNN2] R. Girshick. Fast R-CNN. Proc. of the IEEE international conference on computer vision, p. 1440-1448, 2015. [RCNN3] K. He, G. Gkioxari, P. Dollar, R. Girshick. Mask R-CNN. Preprint arXiv/1703.06870, 2017. [RELU1] K. Fukushima (1969). Visual feature extraction by a multilayered network of analog threshold elements. IEEE Transactions on Systems Science and Cybernetics. 5 (4): 322-333. doi:10.1109/TSSC.1969.300225. This work introduced rectified linear units or ReLUs, now widely used. [RELU2] C. v. d. Malsburg (1973). Self-Organization of Orientation Sensitive Cells in the Striate Cortex. Kybernetik, 14:85-100, 1973. See Table 1 for rectified linear units or ReLUs. Possibly this was also the first work on applying an EM algorithm to neural nets. [RING91] M. B. Ring. Incremental development of complex behaviors through automatic construction of sensory-motor hierarchies. In Birnbaum, L. and Collins, G., editors, Machine Learning: Proceedings of the Eighth International Workshop, pages 343-347. Morgan Kaufmann, 1991. [RMSP] T. Tieleman, G. E. Hinton. Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude. COURSERA: Neural networks for machine learning 4.2 (2012): 26-31. [RO98] R. Rojas (1998). How to make Zuse's Z3 a universal computer. IEEE Annals of Computing, vol. 19:3, 1998. [ROB87] A. J. Robinson, F. Fallside. The utility driven dynamic error propagation network. Technical Report CUED/F-INFENG/TR.1, Cambridge University Engineering Department, 1987. [RPG] D. Wierstra, A. Foerster, J. Peters, J. Schmidhuber (2010). Recurrent policy gradients. Logic Journal of the IGPL, 18(5), 620-634. [RPG07] D. Wierstra, A. Foerster, J. Peters, J. Schmidhuber. Solving Deep Memory POMDPs with Recurrent Policy Gradients. Intl. Conf. on Artificial Neural Networks ICANN'07, 2007. PDF. The first paper on policy gradients for LSTM. This approach has become very important in reinforcement learning.[LSTMPG] https://people.idsia.ch/~juergen/deep-learning-history.html 67/75 29/12/2022, 12:21 [RUM] DE Rumelhart, GE Hinton, RJ Williams (1985). Learning Internal Representations by Error Propagation. TR No. ICS-8506, California Univ San Diego La Jolla Inst for Cognitive Science. Later version published as: Learning representations by back-propagating errors. Nature, 323, p. 533-536 (1986). This experimental analysis of backpropagation did not cite the origin of the method,[BP1-5] also known as the reverse mode of automatic differentiation. The paper also failed to cite the first working algorithms for deep learning of internal representations (Ivakhnenko & Lapa, 1965)[DEEP1-2][HIN] as well as Amari's work (1967-68)[GD1-2] on learning internal representations in deep nets through stochastic gradient descent. Even later surveys by the authors[DL3,3a] failed to cite the prior art.[T22] [RUS95] S. J. Russell, P. Norvig, J. Canny, J. M. Malik, D. D. Edwards. Artificial Intelligence: a Modern Approach, volume 2. Englewood Cliffs: Prentice Hall, 1995. [S93] D. Sherrington (1993). Neural networks: the spin glass approach. North-Holland Mathematical Library, vol 51, 1993, p. 261-291. [S20] T. Sejnowski. The unreasonable effectiveness of deep learning in artificial intelligence. PNAS, January 28, 2020. Link. A misleading "history of deep learning" which goes more or less like this: "In 1969, Minsky & Papert[M69] showed that shallow NNs without hidden layers are very limited and the field was abandoned until a new generation of neural network researchers took a fresh look at the problem in the 1980s."[S20] However, the 1969 book[M69] addressed a "problem" of Gauss & Legendre's shallow learning (circa 1800)[DL1-2] that had already been solved 4 years prior by Ivakhnenko & Lapa's popular deep learning method,[DEEP1-2][DL2] and then also by Amari's SGD for MLPs.[GD1-2] Minsky was apparently unaware of this and failed to correct it later.[HIN](Sec. I)[T22](Sec. XIII) Deep learning research was alive and kicking in the 1960s-70s, especially outside of the Anglosphere.[DEEP1-2][GD1-3][CNN1][DL1-2][T22] [S80] B. Speelpenning (1980). Compiling Fast Partial Derivatives of Functions Given by Algorithms. PhD thesis, Department of Computer Science, University of Illinois, Urbana- Champaign. [S2S] I. Sutskever, O. Vinyals, Quoc V. Le. Sequence to sequence learning with neural networks. In: Advances in Neural Information Processing Systems (NIPS), 2014, 3104-3112. [S59] A. L. Samuel. Some studies in machine learning using the game of checkers. IBM Journal on Research and Development, 3:210-229, 1959. [STO51] H. Robbins, S. Monro (1951). A Stochastic Approximation Method. The Annals of Mathematical Statistics. 22(3):400, 1951. [STO52] J. Kiefer, J. Wolfowitz (1952). Stochastic Estimation of the Maximum of a Regression Function. The Annals of Mathematical Statistics. 23(3):462, 1952. [SA17] J. Schmidhuber. Falling Walls: The Past, Present and Future of Artificial Intelligence. Scientific American, Observations, Nov 2017. [SCAN] J. Masci, A. Giusti, D. Ciresan, G. Fricout, J. Schmidhuber. A Fast Learning Algorithm for Image Segmentation with Max-Pooling Convolutional Networks. ICIP 2013. Preprint arXiv:1302.1690. https://people.idsia.ch/~juergen/deep-learning-history.html 68/75 29/12/2022, 12:21 [SE59] O. G. Selfridge (1959). Pandemonium: a paradigm for learning. In D. V. Blake and A. M. Uttley, editors, Proc. Symposium on Mechanisation of Thought Processes, p 511-529, London, 1959. [SHA7a] N. Sharkey (2007). A programmable robot from AD 60. New Scientist, Sept 2017. [SHA7b] N. Sharkey (2007). A 13th Century Programmable Robot. Univ. of Sheffield, 2007. On a programmable drum machine of 1206 by Al-Jazari. [SHA37] C. E. Shannon (1938). A Symbolic Analysis of Relay and Switching Circuits. Trans. AIEE. 57 (12): 713-723. Based on his thesis, MIT, 1937. [SHA48] C. E. Shannon. A mathematical theory of communication (parts I and II). Bell System Technical Journal, XXVII:379-423, 1948. Boltzmann's entropy formula (1877) seen from the perspective of information transmission. [SIN5] S. Singh, A. G. Barto, N. Chentanez. Intrinsically motivated reinforcement learning. In Advances in Neural Information Processing Systems 17 (NIPS). MIT Press, Cambridge, MA, 2005. [SING1] V. Vinge. Marooned in Realtime. Bluejay, 1986. [SING2] V. Vinge. The coming technological singularity: How to survive in the post-human era. Science fiction criticism: An anthology of essential writings. p. 352-363, 1993. [SK75] D. Sherrington, S. Kirkpatrick (1975). Solvable Model of a Spin-Glass. Phys. Rev. Lett. 35, 1792, 1975. [SKO23] T. Skolem (1923). Begründung der elementaren Arithmetik durch die rekurrierende Denkweise ohne Anwendung scheinbarer Veränderlichen mit unendlichem Ausdehnungsbereich. Skrifter utgit av Videnskapsselskapet i Kristiania, I. Mathematisk- Naturvidenskabelig Klasse 6 (1923), 38 pp. [SMO86] P. Smolensky. Parallel distributed processing: Explorations in the microstructure of cognition, vol. 1. chapter Information Processing in Dynamical Systems: Foundations of Harmony Theory, pages 194-281. MIT Press, Cambridge, MA, USA, 1986. [SMO13] L. Smolin (2013). My hero: Gottfried Wilhelm von Leibniz. The Guardian, 2013. Link. Quote: "And this is just the one part of Leibniz's enormous legacy: the philosopher Stanley Rosen called him 'the smartest person who ever lived'." [SNT] J. Schmidhuber, S. Heil (1996). Sequential neural text compression. IEEE Trans. Neural Networks, 1996. PDF. An earlier version appeared at NIPS 1995. Much later this was called a probabilistic language model.[T22] # [SON18] T. Sonar. The History of the Priority Dispute between Newton and Leibniz. Birkhaeuser, 2018. https://people.idsia.ch/~juergen/deep-learning-history.html 69/75 29/12/2022, 12:21 [ST] J. Masci, U. Meier, D. Ciresan, G. Fricout, J. Schmidhuber Steel Defect Classification with Max-Pooling Convolutional Neural Networks. Proc. IJCNN 2012. PDF. Apparently, this was the first deep learning breakthrough in heavy industry. [ST61] K. Steinbuch. Die Lernmatrix. (The learning matrix.) Kybernetik, 1(1):36-45, 1961. [ST95] W. Hilberg (1995). Karl Steinbuch, ein zu Unrecht vergessener Pionier der künstlichen neuronalen Systeme. (Karl Steinbuch, an unjustly forgotten pioneer of artificial neural systems.) Frequenz, 49(1995)1-2. [SP16] JS interviewed by C. Stoecker: KI wird das All erobern. (AI will conquer the universe.) SPIEGEL, 6 Feb 2016. Link. [SP93] A. Sperduti (1993). Encoding Labeled Graphs by Labeling RAAM. NIPS 1993: 1125- 1132 One of the first papers on graph neural networks. [SP94] A. Sperduti (1994). Labelling Recursive Auto-associative Memory. Connect. Sci. 6(4): 429-459 (1994) [SP95] A. Sperduti (1995). Stability properties of labeling recursive auto-associative memory. IEEE Trans. Neural Networks 6(6): 1452-1460 (1995) [SPG95] A. Sperduti, A. Starita, C. Goller (1995). Learning Distributed Representations for the Classification of Terms. IJCAI 1995: 509-517 [SPG96] A. Sperduti, D. Majidi, A. Starita (1996). Extended Cascade-Correlation for Syntactic and Structural Pattern Recognition. SSPR 1996: 90-99 [SPG97] A. Sperduti, A. Starita (1997). Supervised neural networks for the classification of structures. IEEE Trans. Neural Networks 8(3): 714-735, 1997. [STI81] S. M. Stigler. Gauss and the Invention of Least Squares. Ann. Stat. 9(3):465-474, 1981. [STI83] S. M. Stigler. Who Discovered Bayes' Theorem? The American Statistician. 37(4):290- 296, 1983. Bayes' theorem is actually Laplace's theorem or possibly Saunderson's theorem. [STI85] S. M. Stigler (1986). Inverse Probability. The History of Statistics: The Measurement of Uncertainty Before 1900. Harvard University Press, 1986. [SV20] S. Vazire (2020). A toast to the error detectors. Let 2020 be the year in which we value those who ensure that science is self-correcting. Nature, vol 577, p 9, 2/2/2020. [SVM1] V. N. Vapnik, A. Y. Chervonenkis. On a class of algorithms of learning pattern recognition. Automation and Telemechanics, 25.6:937, 1964. [SVM2] C. Cortes, V. Vapnik. Support-vector networks. Machine Learning. 20 (3): 273-297, 1995 https://people.idsia.ch/~juergen/deep-learning-history.html 70/75 29/12/2022, 12:21 [SVM3] V. Vapnik. The nature of statistical learning theory. Springer science & business media, 1999. [SVM4] B. Schölkopf, A. J. Smola. Learning with kernels: support vector machines, regularization, optimization, and beyond. MIT Press, 2002. [SW1] M. Dorigo, L. M. Gambardella. Ant colony system: a cooperative learning approach to the traveling salesman problem. IEEE Transactions on Evolutionary Computation 1 (1): 53-66, 1997. [SWA22] J. Swan, E. Nivel, N. Kant, J. Hedges, T. Atkinson, B. Steunebrink (2022). Work on Command: The Case for Generality. In: The Road to General Intelligence. Studies in Computational Intelligence, vol 1049. Springer, Cham. https://doi.org/10.1007/978-3-031- 08020-3_6. [T19] ACM's justification of the 2018 A.M. Turing Award (announced in 2019). WWW link. Local copy 1 (HTML only). Local copy 2 (HTML only). [T22] debunks this justification. [T20a] J. Schmidhuber (AI Blog, 25 June 2020). Critique of 2018 Turing Award for Drs. Bengio & Hinton & LeCun. A precursor of [T22]. [T22] J. Schmidhuber (AI Blog, 2022). Scientific Integrity and the History of Deep Learning: The 2021 Turing Lecture, and the 2018 Turing Award. Technical Report IDSIA-77-21, IDSIA, Lugano, Switzerland, 2022. Debunking [T19] and [DL3a] . [TD1] R. Sutton. Learning to predict by the methods of temporal differences. Machine Learning. 3 (1): 9-44, 1988. [TD2] G. Tesauro. TD-Gammon, a self-teaching backgammon program, achieves master-level play. Neural Computation 6.2:215-219, 1994. [TD3] R. Sutton, A. Barto. Reinforcement learning: An introduction. Cambridge, MA, MIT Press, 1998. [TR1] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, I. Polosukhin (2017). Attention is all you need. NIPS 2017, pp. 5998-6008. This paper introduced the name "Transformers" for a now widely used NN type. It did not cite the 1991 publication on what's now called "Transformers with linearized self-attention."[FWP0-6][TR5-6] Schmidhuber also introduced the now popular attention terminology in 1993.[ATT][FWP2][R4] See tweet of 2022 for 30- year anniversary. [TR2] J. Devlin, M. W. Chang, K. Lee, K. Toutanova (2018). Bert: Pre-training of deep bidirectional transformers for language understanding. Preprint arXiv:1810.04805. [TR3] K. Tran, A. Bisazza, C. Monz. The Importance of Being Recurrent for Modeling Hierarchical Structure. EMNLP 2018, p 4731-4736. ArXiv preprint 1803.03585. [TR4] M. Hahn. Theoretical Limitations of Self-Attention in Neural Sequence Models. Transactions of the Association for Computational Linguistics, Volume 8, p.156-171, 2020. https://people.idsia.ch/~juergen/deep-learning-history.html 71/75 29/12/2022, 12:21 [TR5] A. Katharopoulos, A. Vyas, N. Pappas, F. Fleuret. Transformers are RNNs: Fast autoregressive Transformers with linear attention. In Proc. Int. Conf. on Machine Learning (ICML), July 2020. [TR6] K. Choromanski, V. Likhosherstov, D. Dohan, X. Song, A. Gane, T. Sarlos, P. Hawkins, J. Davis, A. Mohiuddin, L. Kaiser, et al. Rethinking attention with Performers. In Int. Conf. on Learning Representations (ICLR), 2021. [TUR] A. M. Turing. On computable numbers, with an application to the Entscheidungsproblem. Proceedings of the London Mathematical Society, Series 2, 41:230- 267. Received 28 May 1936. Errata appeared in Series 2, 43, pp 544-546 (1937). 2nd explicit proof that the Entscheidungsproblem (decision problem) does not have a general solution. [TUR1] A. M. Turing. Intelligent Machinery. Unpublished Technical Report, 1948. Link. In: Ince DC, editor. Collected works of AM Turing—Mechanical Intelligence. Elsevier Science Publishers, 1992. [TUR21] J. Schmidhuber (AI Blog, Sep 2021). Turing Oversold. It's not Turing's fault, though. [TUR3] G. Oppy, D. Dowe (2021). The Turing Test. Stanford Encyclopedia of Philosophy. Quote: "it is sometimes suggested that the Turing Test is prefigured in Descartes' Discourse on the Method. (Copeland (2000:527) finds an anticipation of the test in the 1668 writings of the Cartesian de Cordemoy. Abramson (2011a) presents archival evidence that Turing was aware of Descartes' language test at the time that he wrote his 1950 paper. Gunderson (1964) provides an early instance of those who find that Turing's work is foreshadowed in the work of Descartes.)" [TUR3a] D. Abramson. Descartes' Influence on Turing. Studies in History and Philosophy of Science, 42:544-551, 2011. [TUR3b] Are computers conscious?—Panpsychism with Noam Chomsky | Theories of Everything. Mentioning the ancient "Turing Test" by Descartes. YouTube video, 2022. [UDRL1] J. Schmidhuber. Reinforcement Learning Upside Down: Don't Predict Rewards—Just Map Them to Actions. Preprint arXiv/1912.02875, 5 Dec 2019. [UDRL2] R. K. Srivastava, P. Shyam, F. Mutz, W. Jaskowski, J. Schmidhuber. Training Agents using Upside-Down Reinforcement Learning. Preprint arXiv/1912.02877, 5 Dec 2019. [UN] J. Schmidhuber (AI Blog, 2021). 30-year anniversary. 1991: First very deep learning with unsupervised or self-supervised pre-training. Unsupervised hierarchical predictive coding (with self-supervised target generation) finds compact internal representations of sequential data to facilitate downstream deep learning. The hierarchy can be distilled into a single deep neural network (suggesting a simple model of conscious and subconscious information processing). 1993: solving problems of depth >1000. [UN0] J. Schmidhuber. Neural sequence chunkers. Technical Report FKI-148-91, Institut für Informatik, Technische Universität München, April 1991. PDF. Unsupervised/self-supervised learning and predictive coding is used in a deep hierarchy of recurrent neural networks (RNNs) https://people.idsia.ch/~juergen/deep-learning-history.html 72/75 29/12/2022, 12:21 to find compact internal representations of long sequences of data, across multiple time scales and levels of abstraction. Each RNN tries to solve the pretext task of predicting its next input, sending only unexpected inputs to the next RNN above. The resulting compressed sequence representations greatly facilitate downstream supervised deep learning such as sequence classification. By 1993, the approach solved problems of depth 1000 [UN2] (requiring 1000 subsequent computational stages/layers—the more such stages, the deeper the learning). A variant collapses the hierarchy into a single deep net. It uses a so-called conscious chunker RNN which attends to unexpected events that surprise a lower-level so-called subconscious automatiser RNN. The chunker learns to understand the surprising events by predicting them. The automatiser uses a neural knowledge distillation procedure to compress and absorb the formerly conscious insights and behaviours of the chunker, thus making them subconscious. The systems of 1991 allowed for much deeper learning than previous methods. More. [UN1] J. Schmidhuber. Learning complex, extended sequences using the principle of history compression. Neural Computation, 4(2):234-242, 1992. Based on TR FKI-148-91, TUM, 1991. [UN0] PDF. First working Deep Learner based on a deep RNN hierarchy (with different self- organising time scales), overcoming the vanishing gradient problem through unsupervised pre- training and predictive coding (with self-supervised target generation). Also: compressing or distilling a teacher net (the chunker) into a student net (the automatizer) that does not forget its old skills—such approaches are now widely used. More. [UN2] J. Schmidhuber. Habilitation thesis, TUM, 1993. PDF. An ancient experiment on "Very Deep Learning" with credit assignment across 1200 time steps or virtual layers and unsupervised / self-supervised pre-training for a stack of recurrent NN can be found here (depth > 1000). [UN3] J. Schmidhuber, M. C. Mozer, and D. Prelinger. Continuous history compression. In H. Hüning, S. Neuhauser, M. Raus, and W. Ritschel, editors, Proc. of Intl. Workshop on Neural Networks, RWTH Aachen, pages 87-95. Augustinus, 1993. [UN4] G. E. Hinton, R. R. Salakhutdinov. Reducing the dimensionality of data with neural networks. Science, Vol. 313. no. 5786, pp. 504—507, 2006. PDF. This work describes unsupervised pre-training of stacks of feedforward NNs (FNNs) called Deep Belief Networks (DBNs). It did not cite the much earlier 1991 unsupervised pre-training of stacks of more general recurrent NNs (RNNs)[UN0-3] which introduced the first NNs shown to solve very deep problems. The 2006 justification of the authors was essentially the one Schmidhuber used for the 1991 RNN stack: each higher level tries to reduce the description length (or negative log probability) of the data representation in the level below.[HIN][T22][MIR] This can greatly facilitate very deep downstream learning.[UN0-3] [UN5] Y. Bengio, P. Lamblin, D. Popovici, H. Larochelle. Greedy layer-wise training of deep networks. Proc. NIPS 06, pages 153-160, Dec. 2006. The comment under reference[UN4] applies here as well. [UNI] Theory of Universal Learning Machines & Universal AI. Work of Marcus Hutter (in the early 2000s) on J. Schmidhuber's SNF project 20-61847: Unification of universal induction and sequential decision theory. https://people.idsia.ch/~juergen/deep-learning-history.html 73/75 29/12/2022, 12:21 [URQ10] A. Urquhart. Von Neumann, Gödel and complexity theory. Bulletin of Symbolic Logic 16.4 (2010): 516-530. Link. [VAL84] L. G. Valiant. A theory of the learnable. Communications of the ACM 27.11 (1984):1134-1142, 1984. [VAN1] S. Hochreiter. Untersuchungen zu dynamischen neuronalen Netzen. Diploma thesis, TUM, 1991 (advisor J. Schmidhuber). PDF. More on the Fundamental Deep Learning Problem. [VAN2] Y. Bengio, P. Simard, P. Frasconi. Learning long-term dependencies with gradient descent is difficult. IEEE TNN 5(2), p 157-166, 1994. Results are essentially identical to those of Schmidhuber's diploma student Sepp Hochreiter (1991).[VAN1] Even after a common publication,[VAN3] the first author of [VAN2] published papers[VAN4] that cited only their own [VAN2] but not the original work. [VAN3] S. Hochreiter, Y. Bengio, P. Frasconi, J. Schmidhuber. Gradient flow in recurrent nets: the difficulty of learning long-term dependencies. In S. C. Kremer and J. F. Kolen, eds., A Field Guide to Dynamical Recurrent Neural Networks. IEEE press, 2001. PDF. [VAN4] Y. Bengio. Neural net language models. Scholarpedia, 3(1):3881, 2008. Link. [VAR13] M. Y. Vardi (2013). Who begat computing? Communications of the ACM, Vol. 56(1):5, Jan 2013. Link. [VID1] G. Hinton. The Next Generation of Neural Networks. Youtube video [see 28:16]. GoogleTechTalk, 2007. Quote: "Nobody in their right mind would ever suggest" to use plain backpropagation for training deep networks. However, in 2010, Schmidhuber's team in Switzerland showed[MLP1-2] that unsupervised pre-training is not necessary to train deep NNs. [W45] G. H. Wannier (1945). The Statistical Problem in Cooperative Phenomena. Rev. Mod. Phys. 17, 50. [WER87] P. J. Werbos. Building and understanding adaptive systems: A statistical/numerical approach to factory automation and brain research. IEEE Transactions on Systems, Man, and Cybernetics, 17, 1987. [WER89] P. J. Werbos. Backpropagation and neurocontrol: A review and prospectus. In IEEE/INNS International Joint Conference on Neural Networks, Washington, D.C., volume 1, pages 209-216, 1989. [WI48] N. Wiener (1948). Time, communication, and the nervous system. Teleological mechanisms. Annals of the N.Y. Acad. Sci. 50 (4): 197-219. Quote: "... the general idea of a computing machine is nothing but a mechanization of Leibniz's calculus ratiocinator." [WID62] Widrow, B. and Hoff, M. (1962). Associative storage and retrieval of digital information in networks of adaptive neurons. Biological Prototypes and Synthetic Systems, 1:160, 1962. [WU] Y. Wu et al. Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation. Preprint arXiv:1609.08144 (PDF), 2016. Based on LSTM https://people.idsia.ch/~juergen/deep-learning-history.html 74/75 29/12/2022, 12:21 which it mentions at least 50 times. Annotated history of modern AI and deep neural networks [XAV] X. Glorot, Y. Bengio. Understanding the difficulty of training deep feedforward neural networks. Proc. 13th Intl. Conference on Artificial Intelligence and Statistics, PMLR 9:249-256, 2010. [YB20] Y. Bengio. Notable Past Research. WWW link (retrieved 15 May 2020). Local copy (plain HTML only). The author claims that in 1995 he "introduced the use of a hierarchy of time scales to combat the vanishing gradients issue" although Schmidhuber's publications on exactly this topic date back to 1991-93.[UN0-2][UN] The author also writes that in 1999 he "introduced, for the first time, auto-regressive neural networks for density estimation" although Schmidhuber & Heil used a very similar set-up for text compression already in 1995.[SNT] [ZU36] K. Zuse (1936). Verfahren zur selbsttätigen Durchführung von Rechnungen mit Hilfe von Rechenmaschinen. Patent application Z 23 139 / GMD Nr. 005/021, 1936. First patent application describing a general, practical, program-controlled computer. [ZU37] K. Zuse (1937). Einführung in die allgemeine Dyadik. Mentions the storage of program instructions in the computer's memory. [ZU38] K. Zuse (1938). Diary entry of 4 June 1938. Description of computer architectures that put both program instructions and data into storage—compare the later "von Neumann" architecture [NEU45]. [ZU48] K. Zuse (1948). Über den Plankalkül als Mittel zur Formulierung schematisch kombinativer Aufgaben. Archiv der Mathematik 1(6), 441-449 (1948). PDF. Apparently the first practical design of an automatic theorem prover (based on Zuse's high-level programming language Plankalkül). [ZUS21] J. Schmidhuber (AI Blog, 2021). 80th anniversary celebrations: 1941: Konrad Zuse completes the first working general computer, based on his 1936 patent application. [ZUS21a] J. Schmidhuber (AI Blog, 2021). 80. Jahrestag: 1941: Konrad Zuse baut ersten funktionalen Allzweckrechner, basierend auf der Patentanmeldung von 1936. [ZUS21b] J. Schmidhuber (2021). Der Mann, der den Computer erfunden hat. (The man who invented the computer.) Weltwoche, Nr. 33.21, 19 August 2021. PDF. . https://people.idsia.ch/~juergen/deep-learning-history.html 75/75
Title: Is ChatGPT a Good Recommender? A Preliminary Study: Summary: Recommendation systems have witnessed significant advancements and have been widely used over the past decades. However, most traditional recommendation methods are task-specific and therefore lack efficient generalization ability. Recently, the emergence of ChatGPT has significantly advanced NLP tasks by enhancing the capabilities of conversational models. Nonetheless, the application of ChatGPT in the recommendation domain has not been thoroughly investigated. In this paper, we employ ChatGPT as a general-purpose recommendation model to explore its potential for transferring extensive linguistic and world knowledge acquired from large-scale corpora to recommendation scenarios. Specifically, we design a set of prompts and evaluate ChatGPT's performance on five recommendation scenarios. Unlike traditional recommendation methods, we do not fine-tune ChatGPT during the entire evaluation process, relying only on the prompts themselves to convert recommendation tasks into natural language tasks. Further, we explore the use of few-shot prompting to inject interaction information that contains user potential interest to help ChatGPT better understand user needs and interests. Comprehensive experimental results on Amazon Beauty dataset show that ChatGPT has achieved promising results in certain tasks and is capable of reaching the baseline level in others. We conduct human evaluations on two explainability-oriented tasks to more accurately evaluate the quality of contents generated by different models. And the human evaluations show ChatGPT can truly understand the provided information and generate clearer and more reasonable results. We hope that our study can inspire researchers to further explore the potential of language models like ChatGPT to improve recommendation performance and contribute to the advancement of the recommendation systems field. # Is ChatGPT a Good Recommender? A Preliminary Study Junling Liu∗ william.liuj@gmail.com Alibaba Group China Chao Liu∗ chize.lc@antgroup.com Ant Group China Peilin Zhou∗ zhoupalin@gmail.com Hong Kong University of Science and Technology(Guangzhou) China # Renjie Lv lvrenjie.lrj@antgroup.com Ant Group China Kang Zhou kangbeyond89@163.com Alibaba Group China Yan Zhang yanbest0117@163.com Alibaba Group China ABSTRACT Recommendation systems have witnessed significant advancements and have been widely used over the past decades. However, most traditional recommendation methods are task-specific and there- fore lack efficient generalization ability. Recently, the emergence of ChatGPT has significantly advanced NLP tasks by enhancing the capabilities of conversational models. Nonetheless, the appli- cation of ChatGPT in the recommendation domain has not been thoroughly investigated. In this paper, we employ ChatGPT as a general-purpose recommendation model to explore its potential for transferring extensive linguistic and world knowledge acquired from large-scale corpora to recommendation scenarios. Specifically, we design a set of prompts and evaluate ChatGPT’s performance on five recommendation scenarios, including rating prediction, sequential recommendation, direct recommendation, explanation generation, and review summarization. Unlike traditional recom- mendation methods, we do not fine-tune ChatGPT during the entire evaluation process, relying only on the prompts themselves to con- vert recommendation tasks into natural language tasks. Further, we explore the use of few-shot prompting to inject interaction in- formation that contains user potential interest to help ChatGPT better understand user needs and interests. Comprehensive experi- mental results on Amazon Beauty dataset show that ChatGPT has achieved promising results in certain tasks and is capable of reach- ing the baseline level in others. We conduct human evaluations on two explainability-oriented tasks to more accurately evaluate the quality of contents generated by different models. The human evaluations show ChatGPT can truly understand the provided in- formation and generate clearer and more reasonable results. We hope that our study can inspire researchers to further explore the potential of language models like ChatGPT to improve recommen- dation performance and contribute to the advancement of the rec- ommendation systems field. The prompts and codes are available in https://github.com/williamliujl/LLMRec. # CCS CONCEPTS • Information systems → Recommender systems. # KEYWORDS Large-Language Model, ChatGPT, Recommendation System ACM Reference Format: Junling Liu, Chao Liu, Peilin Zhou, Renjie Lv, Kang Zhou, and Yan Zhang. 2023. Is ChatGPT a Good Recommender? A Preliminary Study. In The 1st workshop on recommendation with generative models, October 21–25, 2023, Birmingham, United Kingdom. ACM, New York, NY, USA, 10 pages. https://doi.org/10.1145/nnnnnnn.nnnnnnn 1 INTRODUCTION As a crucial technique for addressing information overload and enhancing user experience, recommendation systems have wit- nessed significant advancements over the past decade and have been widely used in various web applications such as product rec- ommendation [32, 50, 52, 60], video recommendation [40, 55, 67], news recommendation [56–58], music recommendation [27, 48] and so on. In the meanwhile, with the development of deep learn- ing, recommendation systems have gone through several stages. In early ages, collaborative filtering-based methods [5, 6, 45, 63] are primarily used to model the user’s behavior patterns from the user-item interactions. Later on, with the introduction of user and item side information into recommendation systems, content-based recommendation [37, 38, 41, 54, 59] and knowledge-based recom- mendation [2, 8, 16, 18] have gained attention due to their ability to provide personalized recommendations. However, most traditional recommendation methods are task- specific. Therefore, specific data is required to train specific models for different tasks or application scenarios, which lack efficient gen- eralization ability. To address this issue, researchers have shifted their focus towards implementing Pretrained Language Models (PLMs) in recommendation scenarios since PLMs have demon- strated impressive adaptability to improve the performance of downstream NLP tasks significantly [33]. To effectively convert user interaction data into text sequences, a variety of prompts [65] are designed to convert user interaction data into text sequences. Furthermore, P5 [19] and M6-Rec [11] focus on building a founda- tion model to support a wide range of recommendation tasks. ∗Both authors contributed equally to this research. CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom 2023. ACM ISBN 978-x-xxxx-xxxx-x/YY/MM. . . $15.00 https://doi.org/10.1145/nnnnnnn.nnnnnnn Recently, the emergence of ChatGPT has significantly advanced NLP tasks by enhancing the capabilities of conversational models, making it a valuable tool for businesses and organizations. Chataug et al. [12] leverages ChatGPT to rephrase sentences for text data augmentation. Jiao et al. [23] finds the translation ability of Chat- GPT performs competitively with commercial translation products CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom on high-resource and low-resource languages. Bang et al. [3] finds ChatGPT outperforms the previous state-of-the-art zero-shot model by a large margin in the sentiment analysis task. Nonetheless, the application of ChatGPT in the recommendation domain has not been thoroughly investigated, and whether ChatGPT can perform well on classical recommendation tasks remains an open question. Therefore, it is necessary to establish a benchmark to preliminarily evaluate and compare ChatGPT with traditional recommendation models, thereby providing valuable insights and facilitating fur- ther exploration of the potential of large-scale language models in recommendation systems. To bridge this research gap, in this paper, we directly employ ChatGPT as a general-purpose recommendation model that can han- dle various recommendation tasks, and attempt to explore whether the extensive linguistic and world knowledge acquired from large- scale corpora can be effectively transferred to recommendation sce- narios. Our main contribution is the construction of a benchmark to track ChatGPT’s performance in recommendation scenarios, and a comprehensive analysis and discussion of its strengths and limitations. Specifically, we design a set of prompts and evaluate ChatGPT’s performance on five recommendation tasks, including rating prediction, sequential recommendation, direct recommen- dation, explanation generation, and review summarization. Unlike traditional recommendation methods, we do not fine-tune ChatGPT during the entire evaluation process, relying only on the prompts themselves to convert recommendation tasks into natural language tasks. Furthermore, we explore the use of few-shot prompting to inject interaction information that contains user potential interests to help ChatGPT better understand user needs and preferences. Comprehensive experimental results on Amazon Beauty dataset reveal that, from the perspective of accuracy, ChatGPT performs well in rating prediction but poorly in sequential and direct recom- mendation tasks, achieving only similar performance levels to early baseline methods on certain metrics. On the other hand, while ChatGPT demonstrates poor performance in terms of objective evaluation metrics for explainable recommendation tasks such as explanation generation and review summarization, our additional human evaluations show that ChatGPT outperforms state-of-the- art methods. This highlights the limitations of using an objective evaluation approach to accurately reflect ChatGPT’s true explain- able recommendation capabilities. Furthermore, despite ChatGPT’s unsatisfactory performance in accuracy-based recommendation tasks, it is worth noting that ChatGPT has not been specifically trained on any recommendation data. Thus, there is still signifi- cant potential for improvement in future research by incorporating more relevant training data and techniques. We believe that our benchmark not only sheds light on ChatGPT’s recommendation ca- pabilities but also provides a valuable starting point for researchers to better understand the advantages and shortcomings of Chat- GPT in recommendation tasks. Moreover, we hope that our study can inspire researchers to design new methods that leverage the strengths of language models like ChatGPT to improve recom- mendation performance, and contribute to the advancement of the recommendation systems field. Junling Liu, et al. 2 RELATED WORK 2.1 Large Language Models and ChatGPT Language Models (LMs) are a fundamental component of natural language processing (NLP) and have been the focus of research for several decades. Recently, the emergence of large-scale LMs has led to significant progress in NLP tasks such as machine translation[1, 9, 62], summarization[34, 47], and dialogue generation[14, 28]. Large Language Models (LLMs) are a subclass of LMs that lever- age massive amounts of data and computational resources to achieve state-of-the-art performance on a wide range of NLP tasks. The history of LLMs can be traced back to the early work on neural networks and language modeling. [4] introduced neural language models that learned to predict the next word in a sentence given the previous words. Later, the development of recurrent neural networks (RNNs) and long short-term memory (LSTM) networks further improved the ability of models to capture long-term de- pendencies in language[22]. However, traditional neural language models still struggled with capturing the rich semantic and contex- tual relationships present in natural language. The introduction of the Transformer architecture by [53] was a major breakthrough in this area. The Transformer model utilizes self-attention mechanisms to capture the relationships between all elements in a sequence simultaneously, allowing for more comprehensive contextual under- standing. This architecture has been used as the backbone of many successful LLMs, including BERT[13], GPT-2[42], and XLNet[61]. ChatGPT[39] is a state-of-the-art dialogue system developed by OpenAI in 2022. It is a state-of-the-art natural language processing (NLP) model that has been widely used in various vertical domains, such as text generation and dialogue systems. In text generation, ChatGPT has shown impressive results in generating coherent and diverse text, surpassing the performance of previous models [7]. In dialogue systems, it has been used for task-oriented and open-domain conversations, achieving state-of-the-art performance in both settings [66]. Although the value of ChatGPT has been validated in various fields, whether it can still be effective in the recommendation domain remains an under-explored topic, which motivates us to construct such a benchmark to gain insights into the potential of large language models for recommendation systems. 2.2 Language Model for Recommendation Language Models (LMs), such as BERT [13] and GPT [39], have demonstrated impressive adaptability to improve the performance of downstream NLP tasks significantly, thanks to extensive linguis- tic and world knowledge learned from large-scale corpora. Inspired by these achievements, an increasing amount of attention is being paid to the application of LMs in recommender scenarios, yielding several recent breakthroughs in this field. For instance, LMRec- Sys [65] utilizes prompts to reconstitute some recommendation tasks as multi-token cloze tasks, aiming to address zero-shot and data efficiency issues. P5 [19] is the first attempt to integrate differ- ent recommendation tasks within a shared conditional language generation framework (i.e., T5 [43]). To effectively convert user in- teraction data into text sequences, a variety of prompts are designed to accommodate the specific characteristics of each recommenda- tion task. Similarly, M6-Rec [11] focuses on building a foundation CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom Is ChatGPT a Good Recommender? A Preliminary Study indicator serves to constrain the output format, making the recom- mendation results more comprehensible and assessable. 3.1.1 Rating Prediction. Rating prediction is a crucial task in rec- ommendation systems that aims to predict the ratings that a user would give to a particular item. This task is essential in personal- izing recommendations for users and improving the overall user experience. Some recent advancements in this field include the use of deep learning models[20], and the use of matrix factorization techniques[26], which are effective in dealing with the sparsity problem in recommendation systems. In line with the innovative recommendation paradigm of the LLM, we conducted experiments on a rating task that involved formulating two unique prompt types to elicit the results. We provide some sample prompts in Fig.2. Figure 1: Workflow of utilizing ChatGPT to perform five rec- ommendation tasks and evaluate its recommendation per- formance. model to support a wide range of recommendation tasks, includ- ing retrieval, ranking, and explanation generation, etc. Notably, the authors also provide practical solutions for model deployment in real-world settings. Chat-REC [17], a concurrent work closely related to our study, leverages ChatGPT as an interface for conver- sational recommendations, thereby augmenting the performance of existing recommender models and rendering the recommendation process more interactive and explainable. Different from Chat-REC, our work is inspired by P5 and treats ChatGPT as a self-contained recommendation system that does not rely on any external systems. Based on this, we conduct a thorough evaluation and comparison of its performance on clas- sic recommendation tasks including sequential recommendation, rating prediction, etc. By doing so, we hope our analysis can offer valuable insights for researchers to delve deeper into the potential of large-scale language models in the domain of recommendation. Sequential Recommendation. Sequential recommendation is 3.1.2 a subfield of recommender systems that aims to predict a user’s next item or action based on their past sequential behavior. It has received increasing attention in recent years due to its potential applications in various domains, such as e-commerce, online adver- tising, and music recommendation. In sequential recommendation, researchers have proposed various methods, including recurrent neural networks[31], contrastive learning[69], and attention-based models[53, 70], for capturing the temporal dependencies and pat- terns in user-item interactions. We have devised three distinct prompt formats for the sequential recommendation task family. These include: 1) direct prediction of the user’s next item based on their interaction history, 2) selection of a possible next item from a list of candidates, where only one item is positive and based on the user’s interaction history, and 3) prediction of whether a specific item will be the next one interacted with by the user, using their previous interaction history as a basis. These prompt formats have been designed to enhance the accuracy and effectiveness of se- quential recommendations, and are grounded in rigorous academic principles. Examples of these prompts can be seen in Fig.2. 3 RECOMMENDATION WITH CHATGPT The workflow of using ChatGPT to complete recommendation tasks is illustrated in Fig.1, which consists of three steps. First, different prompts are constructed based on the specific characteristics of the recommendation tasks (Section 3.1). Second, these prompts are used as inputs for ChatGPT, which generates the recommendation results according to the requirements specified in the prompts. Finally, the output from ChatGPT is checked and refined by the refinement module, and the refined results are returned to the user as the final recommendation results (Section 3.2). 3.1.3 Direct Recommendation. Direct Recommendation, also known as explicit feedback recommendation or rating-based recommen- dation, is a type of recommendation system that relies on explicit feedback from users in the form of ratings or reviews. Unlike other recommendation systems that rely on implicit feedback, such as user behavior or purchase history, direct recommendation systems are able to provide more personalized and accurate recommenda- tions by taking into account the explicit preferences of users. For this task, we develop the item selection prompt that selects the most appropriate item from a list of potential candidates. These prompt formats are based on rigorous academic principles and aim to opti- mize the accuracy and relevance of recommendations. Examples of these prompts can be seen in Fig.2. 3.1 Task-specific Prompt Construction In this section, we investigate the recommendation capability of ChatGPT by designing prompts tailored to different tasks. Each prompt comprises three parts: task description, behavior injection, and format indicator. The task description is utilized to adapt recom- mendation tasks to natural language processing tasks. The behavior injection is designed to assess the impact of few-shot prompting, which incorporates user-item interaction to aid ChatGPT in cap- turing user preferences and needs more effectively. The format 3.1.4 Explanation Generation. Explanation generation refers to providing users or system designers with explanations to clarify why such items are recommended. In this way, it enhances the transparency, persuasiveness, effectiveness, trustworthiness, and user satisfaction of recommendation systems. Furthermore, it fa- cilitates system designers in diagnosing, debugging, and refining the recommendation algorithm. Large language models such as ChatGPT can use the vast amount of knowledge they contain to learn the user’s interests through their historical interaction records CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom Junling Liu, et al. I I | # I I I Rating Prediction Art Set (24 Famous Colors Nail How will user rate this product_title: "SHANY Nail Art Polish, , and product_category: Beauty? ( 1 being lowest and 5 being highest ) Attention! Just give me back the exact number a result , and you don't need a lot of text. Nail Art Decoration)" Here is user rating history: 1. Bundle Monster 100 PC 3D Designs Nail Art Nailart Manicure Fimo Canes Sticks Rods Stickers Gel Tips, 5.0; 10 Different Sizes 5 Colors - Manicure Pedicure, 5.0; 2. Winstonia‘s Double Ended Nail Art Marbling Dotting Tool Pen Set w 3. Nail Art Jumbo Stamp Stamping Manicure Image Plate 2 Tropical Holiday by Cheeky&re. 4.Nail Art Jumbo Stamp Stamping Manicure Image Plate 6 Happy Holidays by Cheeky&re HANY Nail Based on above rating history, please predict user's rating for the product: Art Set (24 Famouse Colors Nail Art Polish, Nail Requirements: you must choose 10 items for recommendation and sort them in order of priority, from highest to lowest. Output format: a python list. Do not explain the reason or include any other words. The user has interacted with the following items in chronological order: {'Better Living Classic Two Chamber Dispenser, White', 'Andre Silhouettes Shampoo Cape, Metallic Black’, ......, ‘John Frieda JFHAS Hot Air Brush, 1.5 inch'].Please recommend the next item that the user might interact with. Requirements: you must choose 10 items for recommendation and sort them in order of priority, from highest to lowest. Output format: a python list. Do not explain the reason or include any other words. Given the user's interaction history in chronological order: ['Avalon Biotin B-Complex Thickening Conditioner, 14 Ounce’, 'Conair 1600 Watt Folding F lair Dryer’, . ‘RoC Multi-Correxion 4-Zone Daily Moisturizer, SPF 30, 1.7 Ounce’, the next interacted item is ['Le E Full Body Exfoliator - Pink']. Now, if the interaction history is updated to ['Avalon Biotin B-Complex Thickening Conditioner, 14 Ounce’, ‘Conair 1600 Watt Folding Handle Hair Dryer’,....... 'RoC Multi-Correxion 4-Zone Daily Moisturizer, SPF 30, 1.7 Ounce', 'Le Edge Full Body Exfoliator - Pink’| and the user is likely to interact again, recommend the next item. landle I dge Direct Recommendation Requirements: you must choose 10 items for recommendation and sort them in order of priority, from highest to lowest. Output format: a python list. Do not explain the reason or include any other words. The user has interacted with the following items (in no particular order): |" S\in Obsession Jessner's Chemical Peel Kit Anti-aging and Anti acne Skin Care Treatment", "Xtreme Brite Brightening Gel loz.',......, 'Reviva - Light Skin Peel, 1.5 oz cream']. From the candidates listed below, choose the top 10 items to recommend to the user and rank them in order of priority from highest to lowest. Candidates: {'Rogaine for -""L'Oreal Kids Extra Gentle 2-in-1 Shampoo With a Women Hair Regrowth Treatment 3- 2 ounce bottles’, 'Best Age Spot Remover’, ... Burst of Cherry Almond, 9.0 Fluid Ounce""]. zero-shot Requirements: you must choose 10 items for recommendation and sort them in order of priority, from highest to lowest. Output format: a python list. Do not explain the reason or include any other words. The user has interacted with the following items (in no particular order): {Maybelline New York Eye Studio Lasting Drama Gel Eyeliner, plant 956, 0.106 Ounce’, ""L'Oreal Paris Healthy Look Hair Color, 8.5 Blonde/White Chocolate"", , Duo Lash Adhesive, C 0.25 "|. Given that the user has interacted with 'WAWO 15 Color Profession! Makeup Eyeshadow Camouflage Facial Concealer Neutral Palette’ from a pool of candidates: ['MASH Bamboo Reusable Cuticle Pushers Remover Long-Lasting Makeup Setting Spray 4 07’, ......,!Classic Cotton Balls Jumbo Size, 100 Count'|, please recommend the best item from a new candidate pool, ['Neutrogena Ultra Sheer Sunscreen SPF 45 Twin Pack 6.0 Ounce’, 'Blinc Eyeliner Pencil - Black’, ......,'Skin MD Natural + SPF15 combines the benefits of a shielding lotion and a sunscreen lotion']. Note that the candidates in the new pool are not ordered in any particular way. Manicure Pedicure Stick’, 'Urban Decay All Nighter Figure 2: Example prompts of accuracy-based tasks on Beauty dataset. The black texts represent the description of the task, the red texts indicate the format requirements, the blue texts represent user historical information or few-shot information, and the gray texts indicate the current input. and provide reasonable explanations for their behavior. Specifically, We ask ChatGPT model to generate a textual explanation to justify a user’s preference towards a selected item as shown in Fig.3. For each category, additional auxiliary information such as the hint word and the star rating could be included. 3.1.5 Review Summarization. Automatic generation of summaries is becoming increasingly important in Natural Language Process- ing, as the demand for concise and easily comprehensible content continues to grow. Similar to the explanation generation task, we create two types of prompts: zero/few-shot prompts, and provide some example prompts in Fig.3. 3.2 Output Refinement To ensure the diversity of generated results, ChatGPT incorpo- rates a degree of randomness into its response generation process, which may result in different responses for the same input. How- ever, when using ChatGPT for recommendation, this randomness can sometimes cause difficulties in evaluating the recommended Is ChatGPT a Good Recommender? A Preliminary Study CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom zero-shot few-shot zero-shot Explanation Generation Here is user's interaction history: 1. Prolab Caffeine- Maximum Potency 200 mg 100 Tablets 2. DevaCurl Mist-er Right Lavender Curl Revitalizer 12.0 oz 3. TIGI Catwalk Curl Collection Curlesque Leave-In Conditioner, 7.27 Ounce 4. elf. Pigment Eyeshadow, Naturally Nude, 0.05 Ounce Help user generate a 5.0-star explanation about this product "SHANY Nail Art Set (24 Famouse Colors Nail Art Polish, Nail Art Decoration)" with around 10 words. Here are some recommended products and their corresponding explanations for user: 1. product "TIGI Catwalk Curl Collection Curlesque Curls Rock Amplifier, 5.07 Ounce, Packaging May Vary" and its explanation "One of the few things 2. product "DevaCurl Mist-er Right Lavender Curl Revitalizer 12.0 oz" and its explanation "it makes my hair greasy and gross" Help user generate a 5.0-star explanation about this product "SHANY Nail Art Set (24 Famouse Colors Nail Art Polish, Nail Art Decoration)" with around 10 words? I have found that work for white people with curly hair" Review Sumarization Here are some summaries of user: 1. "Loving this sooo muchh" 2. "Amazii g color" 3. "..Hong Kong Collection &lt;3 OPI" Write a short sentence to summarize the following product review from user: "So i was pretty excited that i got this in the mail, but seriously.....i think its just the color of mine, i don't know, not good cover stick... Received it sticking to the top...so basically it was broken when i opened it because of the air mail looks very pasty...very white i shall say...im never buying this product ever..". The sentence should be around 4 words. Here are some reviews and their corresponding summaries of user: 1. Review:" After watching kardashian episode back in 2009 kim mentioned OPI my private jet.. and i was like what is that? i looked it up online and LOVEL ) it and i just got it 1 week shipping.. awesomee just love this color its sparkley brown and its turns black sometimes cool!! well for mee looolll LOVE this color &It;3 on my toes and fingers lol". Summary:"Loving this sooo muchh" few-shot 2. Review:"I love this and im glad im adding this to my collection! (: a nice top coat or alone very shimmery and very pretty, especially the top brush cap thing its silver than the original black! (: i recommend this". Summary:" Amazing color" Write a short sentence to summarize the following product review from user: "So i was pretty excited that i got this in the mail, but seriously.....i think its just the color of mine, i don't know, not good cover stick... Received it sticking to the top...so basically it was broken when i opened it because of the air mail looks very pasty...very white i shall say...im never buying this product ever..". The sentence should be around 4 words. Figure 3: Example prompts of explainability-oriented tasks on Beauty dataset. The black texts represent the description of the task, the red texts indicate the format requirements, the blue texts represent user historical information or few-shot information, and the gray texts indicate the current input. items. While the format indicator in the prompt construction can partially alleviate this issue, in practical usage, it still cannot guar- antee the anticipated output format. Therefore, we devise output refinement module to check the format of ChatGPT’s output. If the output passes the format check, it is directly used as the fi- nal output. If not, it is modified based on pre-defined rules. If the format correction is successful, the corrected result is used as the final output. If not, the corresponding prompt is fed into ChatGPT for a re-recommendation until the format requirements are met. It is worth noting that different tasks have different output format requirements when evaluating ChatGPT. For example, for rating prediction, only a specific score is needed, whereas for sequential or direct recommendation, a list of recommended items is required. Particularly for sequence recommendation, it is challenging to feed all the items in the dataset to ChatGPT at once. As a result, Chat- GPT’s output may not correctly match the item set in the dataset. To address this issue, we introduce a text matching method based on similarity in the correction process to map ChatGPT’s predictions back to the original dataset. Although this method may not per- fectly reflect ChatGPT’s ability, it can still indirectly demonstrate its potential in sequential recommendation. 4 EVALUATION To evaluate ChatGPT, we conduct extensive experiments on the real- world Amazon dataset. Through the performance comparison with various representative methods and ablation studies on different tasks, we aim to answer the following research questions: • RQ1: How does ChatGPT perform as compared with the state-of-the-art baseline models? • RQ2: What is the impact of few-shot prompting on perfor- mance? • RQ3: How do we design the human evaluation to assess explanation generation and summarization tasks? 4.1 Experimental Setup 4.1.1 Datasets. We conduct numerical and human evaluations on the real-world Amazon recommendation dataset. The Amazon CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom dataset contains the customer review text with accompanying meta- data on 29 categories of products. This paper focuses on evaluating the Beauty category. 4.1.2 Metrics. In numerical evaluations, we employ Root Mean Square Error (RMSE) and Mean Absolute Error (MAE) for rating pre- diction. And we adopt top-k Hit Ratio (HR@k), top-k Normalized Discounted Cumulative Gain (NDCG@k) for sequential recommen- dation and direct recommendation which are widely used in re- lated works [19, 68]. Specifically, we report results on HR@{1,5,10}, NCGG@{5,10} for evaluation. Besides, n-gram Bilingual Evaluation Understudy (BLEU-n) and n-gram Recall-Roiented Understudy for Gising Evaluation (ROUGE-n) are used to evaluate the explanation generation and review summarization tasks. In human evaluations, we have designed and deployed a crowdsourcing task to assess the qualities of the generated explanations and review summaries. Through this task, we aim to accurately evaluate the effectiveness of the content by gathering feedback from a diverse range of human evaluators. Implementation Details. In order to verify that we can di- 4.1.3 rectly apply the knowledge learned by ChatGPT to recommendation scenarios without the need for a large amount of task-specific data for training, we apply gpt-3.5-turbo to conduct few-shot and zero- shot experiments for the five tasks mentioned above. We collect n items that users have interacted with and k shots of historical records to enable ChatGPT to learn users’ interests implicitly. In this experiment, we use the titles of the items as meta information, and set 𝑛 = 10 and 𝑘 = 3 due to the limitation of a maximum context length of 4096 tokens in ChatGPT. We randomly sample 100 records from the test set proposed by P5 [19] for evaluation. For direct recommendation, we set the number of negative sam- ples to 99, thus forming a candidate list of length 100 with one positive item. Also, due to the addition of the candidate pool in the request, we set the number of shots to 1. For sequential recom- mendation, we input the user’s historical interacted items in order and let ChatGPT predict the title of the next item that the user might interact with, and use BERT[13] to calculate the vector of the predicted title and compute the similarity between the predicted title vector and the title vectors of all items, and select the item with the highest similarity as the predicted item. For human evaluation on explanation generation and review summarization, we sample some results of different methods for each task, and each result will be scored and ranked by three human evaluators. After obtaining the manually annotated results, we will calculate the average top1 ratio and average ranking position of different methods to measure their generation performance. 4.2 Baselines for multiple tasks Following P5 [19], we gather a range of approaches that are repre- sentative of various tasks. For rating prediction, we employ MF [25] and MLP [10] as our baselines, both evaluated using mean square root loss. For direct recommendation, we use BPR-MF [44], BPR- MLP [10] and SimpleX [36] as baselines. For sequential recommen- dation, we adopt Caser [51], HGN [35], GRU4Rec [21], BERT4Rec [49], FDSA [64], SASRec [24] and S3-Rec [68] as baselines for com- parison. For explanation generation, we utilize Attn2Seq [15], NRT Junling Liu, et al. # Table 1: Performance comparison on rating prediction. Methods Beauty RMSE MAE MF MLP ChatGPT(zero-shot) ChatGPT(few-shot) 1.1973 1.3078 1.4059 1.0751 0.9461 0.9597 1.1861 0.6977 [30] and PETER [29] as baselines. For review summarization, we adopt pretrained T0 [46] and GPT-2 [42] as baselines. For more details, you can refer to P5 [19] or relevant articles. # 4.3 Performance Comparison on 5 Tasks (RQ1&2) 4.3.1 Rating prediction. To evaluate the rating prediction perfor- mance of ChatGPT, zero-shot and few-shot prompts were employed, and the results obtained from the Beauty dataset were summarized in Tab.1. The results indicate that, for the seen category on the Beauty dataset, few-shot prompts outperform MF and MLP in terms of both MAE and RMSE. These results provide evidence supporting the feasibility of utilizing a conditional text generation framework for rating prediction. Sequential recommendation. To assess the sequential recom- 4.3.2 mendation capability of ChatGPT, we conducted both zero-shot and few-shot experiments, the results of which are shown in Tab.2. We found that, compared to the baselines, ChatGPT’s performance in the zero-shot prompting setup is considerably inferior, with all met- rics being significantly lower than the baselines. However, under the few-shot prompting setup, while there is a relative improvement in performance, such as NDCG@5 surpassing GRU4Rec, ChatGPT is still generally outperformed by classical sequential recommenda- tion methods in most cases. There are possibly two main reasons contributing to this outcome: First, during the prompting design process, all items are represented by their titles. Although this ap- proach can alleviate the cold-start problem to some extent, it may cause ChatGPT to focus more on semantic similarity rather than the transition relationships between items, which are crucial for effective recommendations. Second, due to the length constraint of the prompts, it is not possible to input all items from the item set into ChatGPT. This leads to ChatGPT lacking constraints in pre- dicting the title of the next item, resulting in generating item titles that do not exist in the dataset. Although it is possible to map these predicted titles to existing titles in the dataset through semantic similarity matching, our experiments show that this mapping does not result in significant gains. Therefore, for sequential recommen- dation tasks, merely employing ChatGPT is not a suitable choice. Further exploration is needed to introduce more guidance and con- straints to help ChatGPT accurately capture historical interests and make reasonable recommendations within a limited scope. 4.3.3 Direct recommendation. Tab.3 illustrates the performance of ChatGPT on the direct recommendation task. Unlike the sequen- tial recommendation setup, direct recommendation requires the recommendation model to select the most relevant item for the user from a limited-sized item pool. We observed that, when using Is ChatGPT a Good Recommender? A Preliminary Study # Table 2: Performance comparison on sequential recommen- dation. Methods Beauty HR@5 NDCG@5 HR@10 NDCG@10 Caser HGN GRU4Rec BERT4Rec FDSA SASRec S3-Rec P5-B ChatGPT(zero-shot) ChatGPT(few-shot) 0.0205 0.0325 0.0164 0.0203 0.0267 0.0387 0.0387 0.0493 0.0000 0.0135 0.0131 0.0206 0.0099 0.0124 0.0163 0.0249 0.0244 0.0367 0.0000 0.0135 0.0347 0.0512 0.0283 0.0347 0.0407 0.0605 0.0647 0.0645 0.0000 0.0135 0.0176 0.0266 0.0137 0.0170 0.0208 0.0318 0.0327 0.0416 0.0000 0.0135 Table 3: Performance comparison on direct recommendation. # Beauty HR@5 NDCG@5 HR@10 NDCG@10 BPR-MF BPR-MLP SimpleX P5-B ChatGPT(zero-shot) ChatGPT(few-shot) 0.1426 0.1392 0.2247 0.1564 0.0217 0.0349 0.0857 0.0848 0.1441 0.1096 0.0111 0.0216 0.2573 0.2542 0.3090 0.2300 0.0652 0.0930 0.1224 0.1215 0.1711 0.1332 0.0252 0.0398 zero-shot prompting, the recommendation performance is signif- icantly inferior to supervised recommendation models. This can be attributed to the insufficient information provided to ChatGPT, resulting in an inability to capture user interests and generate more random recommendations. While few-shot prompting can improve ChatGPT’s recommendation performance by providing some of the user’s historical preferences, it still fails to surpass the baseline performance. It is worth noting that we discovered during the experiments that the construction of the item pool, specifically whether the item pool is shuffled or not, has a considerable impact on the direct recom- mendation performance. In an extreme scenario where the ground truth item is placed at the first position in the item pool, we found that the evaluation metrics were approximately ten times higher than when the item pool was shuffled. This finding suggests that ChatGPT exhibits a positional bias for the input item pool within the prompt, tending to consider items towards the beginning of the pool as more important, and thus more likely to be recommended. This additional bias introduced by the language model renders us- ing ChatGPT for direct recommendation a challenging endeavor. 4.3.4 Explanation Generation. In Tab.4, both zero-shot and few- shot prompts are used to evaluate ChatGPT’s performance on ex- planation generation. From the metrics perspective, the P5 model has a better performance. As language models, P5 and ChatGPT have different design goals and application scenarios. P5 aims to generate explanatory language similar to known texts. Therefore, P5 focuses on learning text structure and grammar rules during CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom Table 4: Performance comparison on explanation generation (%). Methods Beauty BLUE4 ROUGE1 ROUGE2 ROUGEL Attn2Seq NRT PETER P5-B PETER+ ChatGPT(zero-shot) ChatGPT(few-shot) 0.7889 0.8295 1.1541 0.9742 3.2606 0.0000 1.1967 12.6590 12.7815 14.8497 16.4530 25.5541 8.5992 11.4103 1.6820 1.8543 2.1413 1.8858 5.9668 0.6995 2.5675 9.7481 9.9477 11.4143 11.8765 19.7168 4.7564 5.9119 Table 5: Performance comparison on review summarization (%). Methods Beauty BLUE4 ROUGE1 ROUGE2 ROUGEL T0 GPT-2 P5-B ChatGPT(zero-shot) ChatGPT(few-shot) 1.2871 0.5879 2.1225 0.0000 0.0000 1.2750 3.3844 8.4205 3.8246 2.7822 0.3904 0.6756 1.6676 0.2857 0.0000 0.9592 1.3956 7.5476 3.1344 2.4328 training, making the generated results more standardized, as shown in Fig.4. In contrast, ChatGPT focuses more on language interac- tion and diversity. Its application scenario is usually to simulate human conversation, so it needs to consider multiple factors such as context, emotion, and logic when generating text to better ex- press human thinking and language habits. This design is bound to make the text generated by ChatGPT more diverse and creative. Besides, P5 is fine-tuned on Beauty dataset while ChatGPT is uti- lized in a zero-shot or few-shot experimental setting. Therefore, it is understandable that ChatGPT may not perform as well as P5 in metrics. Hence, we introduce human evaluation to better measure the performance of different models in generating content. 4.3.5 Review summarization. We conduct zero-shot and few-shot experiments to evaluate ChatGPT’s ability on review summariza- tion, as shown in Tab.5. Similar to the explanation generation task, ChatGPT does not have an advantage in metrics evaluation. How- ever, although the summary result of P5 has extracted some key- words, it has ignored relevant information from the entire review. In contrast, ChatGPT can generate more effective and meaningful summaries by deeply understanding and summarizing the reviews. As shown in Fig.5. Hence, we also conduct human evaluation in this task. 4.4 Human Evaluation (RQ3) As shown in the experiments above, we conducted numerical eval- uations on the explanation generation and review summarization tasks using the test set constructed by P5. However, the ground- truth explanations generated by P5 are not truly accurate because P5 extracts sentences from views commenting on one or more item feature words as users’ explanations about their preferences. In that case, we designed human evaluations to better assess the perfor- mance of ChatGPT. Specifically, we randomly sample 20 prompts for CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom Junling Liu, et al. / Explanation Generation Results \ Reviews Results Absolutely great product. I bought this for my fourteen year old niece for Christmas and of course I had to try it out, then I tried another one, and another one and another one. So much fun! I even contemplated keeping a few for myself! Ground truth: "Absolutely great product” P5's output: "great colors and great price for the price” ChatGPT’s output: "Love this nail art set - perfect colors and variety!" Love the colors. Didn't get any doubles. 1 bottle was not fully closed and the bottle chipped on the neck of the bottle. But being where the break was I just closed it and it is still usable. I wouldn't recommend this for painting your full nail (It is for art), but I would for stamping and nail art. Small brushes great for that. Not all work for stamping though, like the metallic ones. Ground truth: "I wouldn't recommend this for painting your full nail (It is for art)" P5's output: "great price and great price and great price" ChatGPT’s output: "SHANY's Nail Art Set is a must-have for creative nails." Wow, this is the best deal I've seen on nail polish in a long time. You get so many vibrant beautiful colors to choose from. These are nail art brushes for fine detail. I love that you can get a whole kit for this price! Ground truth: "this is the best deal I've seen on nail polish in a long time" P5's output: "great price and great quality and great price” ChatGPT’s output: "SHANY's Nail Art Set is a must-have for stunning manicures." # Figure 4: Example explanation results of different models on Beauty dataset. / Review Summarization Results \ Reviews Results "I truly love this soap. I have very sensitive skin and thi of the few soaps that doesn't dry out or break out my skin. Would recommend to others. It smells soft as well” one Ground truth: "Soap" P5's output: "Great soap" ChatGPT’s output: "Gentle, effective soap recommended.” "These brushes are okay. I don't think they're anything special, but for the price their quality is okay. I don't know that I would buy them again though.". Ground truth: "It's okay" P5's output: "Okay" ChatGPT’s output: "Average brushes for price." "Great to use after the microdermabrasion roller needle process. Skin absorbs it quickly. Face looks more rejuvenated in the morning." Ground truth: "Works Well" P5's output: "Great" ChatGPT’s output: "Quickly absorbed rejuvenating serum. "you can see and feel that it's working. easy to use too. after a XO few times you'll get the hang of it." Ground truth: "works!" P5's output: "works" ChatGPT’s output: "Effective and user-friendly." # Figure 5: Example summarization results of different models on Beauty dataset. # Table 6: Human evaluation for explanation generation on Beauty dataset. # Table 7: Human evaluation for review summarization on Beauty dataset. Methods Evaluators Eva_1 Eva_2 Eva_3 Eva_4 avg_top1_ration avg_position Ground truth P5 ChatGPT(zero-shot) 25.0% 0.0% 75.0% 45.0% 0.0% 55.0% 45.0% 0.0% 55.0% 50.0% 0.0% 50.0% 38.0% 0.0% 62.0% 1.83 2.71 1.46 Methods Evaluators Eva_1 Eva_2 Eva_3 Eva_4 Eva_5 avg_top1_ration avg_position Ground truth P5 ChatGPT(zero-shot) ChatGPT(few-shot) 12.5% 5.8% 46.2% 35.6% 10.6% 0.0% 37.5% 51.9% 8.7% 5.7% 36.5% 49.0% 17.3% 11.5% 45.2% 26.0% 22.1% 19.2% 23.1% 35.6% 14.2% 8.5% 37.7% 39.6% 2.91 3.16 1.90 2.01 explanation generation and 97 prompts for review summarization from the Beauty dataset and display every generated explanation or summary to several evaluators. The evaluators rank the results generated by ChatGPT, baseline, and ground truth for assessment. avg_top1_ration represents the proportion in which the prompt ranked first among the prompts. avg_position denotes the average position of sorting for each prompt. For explanation generation task, as shown in Tab.6, the results of the four manual annotators have a certain degree of subjectivity, but the score distribution is relatively consistent, with a general consensus that the explanations generated by ChatGPT are clearer and more reasonable, even better than the ground truth. Meanwhile, P5’s performance is the worst, with explanations tending towards a generic style and sentences that are not fluent. We can also draw the same conclusion from the examples in Tab.4. For review summa- rization task, we can find in Fig.5 that the contents summarized in P5 are too general and do not extract useful information. However, ChatGPT can truly understand the reviews and provide accurate summaries, rather than simply extracting a few keywords from the reviews. As shown in Tab.7, all annotators unanimously agree that Is ChatGPT a Good Recommender? A Preliminary Study ChatGPT has the best performance, surpassing ground truth and P5 by a large margin. 5 CONCLUSION AND FUTURE WORK In this paper, we construct a benchmark to evaluate ChatGPT’s per- formance in recommendation tasks and compare it with traditional recommendation models. The experimental results show that Chat- GPT performs well in rating prediction but poorly in sequential and direct recommendation tasks, indicating the need for further exploration and improvement. Despite its limitations, ChatGPT outperforms state-of-the-art methods in terms of human evaluation for explainable recommendation tasks, highlighting its potential to generate explanations and summaries. We believe that our study provides valuable insights into the strengths and limitations of ChatGPT in recommendation systems, and we hope that it can inspire future research to explore the use of large language models to enhance recommendation performance. Moving forward, we plan to investigate better ways to incorporate user interaction data into large language models and bridge the semantic gap between language and user interests. CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom # REFERENCES [1] Roee Aharoni, Melvin Johnson, and Orhan Firat. 2019. Massively multilingual neural machine translation. arXiv preprint arXiv:1903.00089 (2019). [2] Pegah Malekpour Alamdari, Nima Jafari Navimipour, Mehdi Hosseinzadeh, Ali Asghar Safaei, and Aso Darwesh. 2020. A systematic study on the rec- ommender systems in the E-commerce. Ieee Access 8 (2020), 115694–115716. [3] Yejin Bang, Samuel Cahyawijaya, Nayeon Lee, Wenliang Dai, Dan Su, Bryan Wilie, Holy Lovenia, Ziwei Ji, Tiezheng Yu, Willy Chung, et al. 2023. A multitask, multilingual, multimodal evaluation of chatgpt on reasoning, hallucination, and interactivity. arXiv preprint arXiv:2302.04023 (2023). [4] Y. Bengio, R. Ducharme, P. Vincent, C. Jauvin, and J. Shawe-Taylor. 2003. Journal of Machine Learning Research 3 (2003) 1137–1155 Submitted 4/02; Published 2/03 A Neural Probabilistic Language Model. JMLR.org 6 (2003). [5] Jesus Bobadilla, Santiago Alonso, and Antonio Hernando. 2020. Deep learning architecture for collaborative filtering recommender systems. Applied Sciences 10, 7 (2020), 2441. [6] Jesús Bobadilla, Fernando Ortega, Abraham Gutiérrez, and Santiago Alonso. 2020. Classification-based deep neural network architecture for collaborative filtering recommender systems. (2020). [7] T. B. Brown, B. Mann, N. Ryder, M. Subbiah, and D. Amodei. 2020. Language Models are Few-Shot Learners. (2020). [8] Federica Cena, Luca Console, and Fabiana Vernero. 2021. Logical foundations of knowledge-based recommender systems: A unifying spectrum of alternatives. Information Sciences 546 (2021), 60–73. [9] Mia Xu Chen, Orhan Firat, Ankur Bapna, Melvin Johnson, Wolfgang Macherey, George Foster, Llion Jones, Niki Parmar, Mike Schuster, Zhifeng Chen, et al. 2018. The best of both worlds: Combining recent advances in neural machine translation. arXiv preprint arXiv:1804.09849 (2018). [10] Heng-Tze Cheng, Levent Koc, Jeremiah Harmsen, Tal Shaked, Tushar Chandra, Hrishi Aradhye, Glen Anderson, Greg Corrado, Wei Chai, Mustafa Ispir, et al. 2016. Wide & deep learning for recommender systems. In Proceedings of the 1st workshop on deep learning for recommender systems. 7–10. [11] Zeyu Cui, Jianxin Ma, Chang Zhou, Jingren Zhou, and Hongxia Yang. 2022. M6- Rec: Generative Pretrained Language Models are Open-Ended Recommender Systems. CoRR abs/2205.08084 (2022). [12] Haixing Dai, Zhengliang Liu, Wenxiong Liao, Xiaoke Huang, Zihao Wu, Lin Zhao, Wei Liu, Ninghao Liu, Sheng Li, Dajiang Zhu, et al. 2023. Chataug: Leveraging chatgpt for text data augmentation. arXiv preprint arXiv:2302.13007 (2023). [13] Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2019. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In NAACL-HLT (1). Association for Computational Linguistics, 4171–4186. [14] B. Dhingra, L. Li, X. Li, J. Gao, and D. Li. 2016. Towards End-to-End Reinforcement Learning of Dialogue Agents for Information Access. (2016). [15] Li Dong, Shaohan Huang, Furu Wei, Mirella Lapata, Ming Zhou, and Ke Xu. 2017. Learning to generate product reviews from attributes. In Proceedings of the 15th Conference of the European Chapter of the Association for Computational Linguistics: Volume 1, Long Papers. 623–632. [16] Min Dong, Xianyi Zeng, Ludovic Koehl, and Junjie Zhang. 2020. An interactive knowledge-based recommender system for fashion product design in the big data environment. Information Sciences 540 (2020), 469–488. [17] Yunfan Gao, Tao Sheng, Youlin Xiang, Yun Xiong, Haofen Wang, and Jiawei Zhang. 2023. Chat-REC: Towards Interactive and Explainable LLMs-Augmented Recommender System. arXiv preprint arXiv:2303.14524 (2023). [18] Achraf Gazdar and Lotfi Hidri. 2020. A new similarity measure for collaborative filtering based recommender systems. Knowledge-Based Systems 188 (2020), 105058. [19] Shijie Geng, Shuchang Liu, Zuohui Fu, Yingqiang Ge, and Yongfeng Zhang. 2022. Recommendation as language processing (rlp): A unified pretrain, personalized prompt & predict paradigm (p5). In Proceedings of the 16th ACM Conference on Recommender Systems. 299–315. [20] X. He, L. Liao, H. Zhang, L. Nie, and T. S. Chua. 2017. Neural Collaborative Filtering. International World Wide Web Conferences Steering Committee (2017). [21] Balázs Hidasi, Alexandros Karatzoglou, Linas Baltrunas, and Domonkos Tikk. 2015. Session-based recommendations with recurrent neural networks. arXiv preprint arXiv:1511.06939 (2015). [22] S. Hochreiter and J. Schmidhuber. 1997. Long Short-Term Memory. Neural Computation 9, 8 (1997), 1735–1780. [23] Wenxiang Jiao, Wenxuan Wang, Jen-tse Huang, Xing Wang, and Zhaopeng Tu. 2023. Is ChatGPT a good translator? A preliminary study. arXiv preprint arXiv:2301.08745 (2023). [24] Wang-Cheng Kang and Julian McAuley. 2018. Self-attentive sequential recom- mendation. In 2018 IEEE international conference on data mining (ICDM). IEEE, 197–206. [25] Yehuda Koren, Robert Bell, and Chris Volinsky. 2009. Matrix factorization tech- niques for recommender systems. Computer 42, 8 (2009), 30–37. [26] Y. Koren, R. Bell, and C. Volinsky. 2009. Matrix factorization techniques for recommender systems. IEEE, Computer Journal, 42(8), 30-37. Computer 42, 8 CIKM ’23, October 21–25, 2023, Birmingham, United Kingdom (2009), 30–37. [27] Dominik Kowald, Markus Schedl, and Elisabeth Lex. 2020. The unfairness of popularity bias in music recommendation: A reproducibility study. In Advances in Information Retrieval: 42nd European Conference on IR Research, ECIR 2020, Lisbon, Portugal, April 14–17, 2020, Proceedings, Part II 42. Springer, 35–42. [28] J. Li, M. Galley, C. Brockett, G. P. Spithourakis, J. Gao, and B. Dolan. 2016. A Persona-Based Neural Conversation Model. arXiv e-prints (2016). [29] Lei Li, Yongfeng Zhang, and Li Chen. 2021. Personalized transformer for explain- able recommendation. arXiv preprint arXiv:2105.11601 (2021). [30] Piji Li, Zihao Wang, Zhaochun Ren, Lidong Bing, and Wai Lam. 2017. Neural rating regression with abstractive tips generation for recommendation. In Proceed- ings of the 40th International ACM SIGIR conference on Research and Development in Information Retrieval. 345–354. [31] Z. C. Lipton, J. Berkowitz, and C. Elkan. 2015. A Critical Review of Recurrent Neural Networks for Sequence Learning. Computer Science (2015). [32] Guoguang Liu. 2022. An ecommerce recommendation algorithm based on link prediction. Alexandria Engineering Journal 61, 1 (2022), 905–910. [33] Junling Liu, Peilin Zhou, Yining Hua, Dading Chong, Zhongyu Tian, Andrew Liu, Helin Wang, Chenyu You, Zhenhua Guo, Lei Zhu, et al. 2023. Benchmarking Large Language Models on CMExam–A Comprehensive Chinese Medical Exam Dataset. arXiv preprint arXiv:2306.03030 (2023). [34] Y. Liu. 2019. Fine-tune BERT for Extractive Summarization. (2019). [35] Chen Ma, Peng Kang, and Xue Liu. 2019. Hierarchical gating networks for sequential recommendation. In Proceedings of the 25th ACM SIGKDD international conference on knowledge discovery & data mining. 825–833. [36] Kelong Mao, Jieming Zhu, Jinpeng Wang, Quanyu Dai, Zhenhua Dong, Xi Xiao, and Xiuqiang He. 2021. SimpleX: A simple and strong baseline for collaborative filtering. In Proceedings of the 30th ACM International Conference on Information & Knowledge Management. 1243–1252. [37] Darshita Mittal, Sanyukta Shandilya, Dhruv Khirwar, and Archana Bhise. 2020. Smart billing using content-based recommender systems based on fingerprint. In ICT Analysis and Applications: Proceedings of ICT4SD 2019, Volume 2. Springer, 85–93. [38] Cataldo Musto, Giovanni Semeraro, Marco De Gemmis, and Pasquale Lops. 2016. Learning word embeddings from wikipedia for content-based recommender systems. In Advances in Information Retrieval: 38th European Conference on IR Research, ECIR 2016, Padua, Italy, March 20–23, 2016. Proceedings 38. Springer, 729–734. [39] OpenAI. 2023. GPT-4 Technical Report. CoRR abs/2303.08774 (2023). [40] Kostantinos Papadamou, Savvas Zannettou, Jeremy Blackburn, Emiliano De Cristofaro, Gianluca Stringhini, and Michael Sirivianos. 2022. “It is just a flu”: Assessing the Effect of Watch History on YouTube’s Pseudoscientific Video Recommendations. In Proceedings of the international AAAI conference on web and social media, Vol. 16. 723–734. [41] Yilena Pérez-Almaguer, Raciel Yera, Ahmad A Alzahrani, and Luis Martínez. 2021. Content-based group recommender systems: A general taxonomy and further improvements. Expert Systems with Applications 184 (2021), 115444. [42] Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. 2019. Language models are unsupervised multitask learners. OpenAI blog 1, 8 (2019), 9. [43] Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. 2020. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer. J. Mach. Learn. Res. 21 (2020), 140:1–140:67. [44] Steffen Rendle, Christoph Freudenthaler, Zeno Gantner, and Lars Schmidt-Thieme. 2012. BPR: Bayesian personalized ranking from implicit feedback. arXiv preprint arXiv:1205.2618 (2012). [45] Fatemeh Rezaimehr and Chitra Dadkhah. 2021. A survey of attack detection approaches in collaborative filtering recommender systems. Artificial Intelligence Review 54 (2021), 2011–2066. [46] Victor Sanh, Albert Webson, Colin Raffel, Stephen H Bach, Lintang Sutawika, Zaid Alyafeai, Antoine Chaffin, Arnaud Stiegler, Teven Le Scao, Arun Raja, et al. 2021. Multitask prompted training enables zero-shot task generalization. arXiv preprint arXiv:2110.08207 (2021). [47] A. See, P. J. Liu, and C. D. Manning. 2017. Get To The Point: Summarization with Pointer-Generator Networks. (2017). [48] Jagendra Singh, Mohammad Sajid, Chandra Shekhar Yadav, Shashank Sheshar Singh, and Manthan Saini. 2022. A Novel Deep Neural-based Music Recom- mendation Method considering User and Song Data. In 2022 6th International Conference on Trends in Electronics and Informatics (ICOEI). IEEE, 1–7. [49] Fei Sun, Jun Liu, Jian Wu, Changhua Pei, Xiao Lin, Wenwu Ou, and Peng Jiang. 2019. BERT4Rec: Sequential recommendation with bidirectional encoder rep- resentations from transformer. In Proceedings of the 28th ACM international conference on information and knowledge management. 1441–1450. [50] Zhu Sun, Jie Yang, Kaidong Feng, Hui Fang, Xinghua Qu, and Yew Soon Ong. 2022. Revisiting Bundle Recommendation: Datasets, Tasks, Challenges and Junling Liu, et al. Opportunities for Intent-aware Product Bundling. In Proceedings of the 45th International ACM SIGIR Conference on Research and Development in Information Retrieval. 2900–2911. [51] Jiaxi Tang and Ke Wang. 2018. Personalized top-n sequential recommenda- tion via convolutional sequence embedding. In Proceedings of the eleventh ACM international conference on web search and data mining. 565–573. [52] Manos Tsagkias, Tracy Holloway King, Surya Kallumadi, Vanessa Murdock, and Maarten de Rijke. 2021. Challenges and research opportunities in ecommerce search and recommendations. In ACM Sigir Forum, Vol. 54. ACM New York, NY, USA, 1–23. [53] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, and I. Polosukhin. 2017. Attention Is All You Need. arXiv (2017). [54] Maksims Volkovs, Guang Wei Yu, and Tomi Poutanen. 2017. Content-based neighbor models for cold start in recommender systems. In Proceedings of the Recommender Systems Challenge 2017. 1–6. [55] Yinwei Wei, Xiang Wang, Liqiang Nie, Xiangnan He, Richang Hong, and Tat-Seng Chua. 2019. MMGCN: Multi-modal graph convolution network for personalized recommendation of micro-video. In Proceedings of the 27th ACM international conference on multimedia. 1437–1445. [56] Chuhan Wu, Fangzhao Wu, Mingxiao An, Jianqiang Huang, Yongfeng Huang, and Xing Xie. 2019. NPA: neural news recommendation with personalized attention. In Proceedings of the 25th ACM SIGKDD international conference on knowledge discovery & data mining. 2576–2584. [57] Chuhan Wu, Fangzhao Wu, Tao Qi, Qi Liu, Xuan Tian, Jie Li, Wei He, Yongfeng Huang, and Xing Xie. 2022. Feedrec: News feed recommendation with various user feedbacks. In Proceedings of the ACM Web Conference 2022. 2088–2097. [58] Fangzhao Wu, Ying Qiao, Jiun-Hung Chen, Chuhan Wu, Tao Qi, Jianxun Lian, Danyang Liu, Xing Xie, Jianfeng Gao, Winnie Wu, et al. 2020. Mind: A large-scale dataset for news recommendation. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics. 3597–3606. [59] Yueqi Xie, Jingqi Gao, Peilin Zhou, Qichen Ye, Yining Hua, Jae Boum Kim, Fangzhao Wu, and Sunghun Kim. 2023. Rethinking multi-interest learning for candidate matching in recommender systems. In Proceedings of the 17th ACM Conference on Recommender Systems. 283–293. [60] Yueqi Xie, Peilin Zhou, and Sunghun Kim. 2022. Decoupled side information fusion for sequential recommendation. In Proceedings of the 45th International ACM SIGIR Conference on Research and Development in Information Retrieval. 1611–1621. [61] Z. Yang, Z. Dai, Y. Yang, J. Carbonell, R. Salakhutdinov, and Q. V. Le. 2019. XLNet: Generalized Autoregressive Pretraining for Language Understanding. (2019). [62] Qingcheng Zeng, Lucas Garay, Peilin Zhou, Dading Chong, Yining Hua, Jia- geng Wu, Yikang Pan, Han Zhou, and Jie Yang. 2022. GreenPLM: Cross-lingual pre-trained language models conversion with (almost) no cost. arXiv preprint arXiv:2211.06993 (2022). [63] Feng Zhang, Victor E Lee, Ruoming Jin, Saurabh Garg, Kim-Kwang Raymond Choo, Michele Maasberg, Lijun Dong, and Chi Cheng. 2019. Privacy-aware smart city: A case study in collaborative filtering recommender systems. J. Parallel and Distrib. Comput. 127 (2019), 145–159. [64] Tingting Zhang, Pengpeng Zhao, Yanchi Liu, Victor S Sheng, Jiajie Xu, Deqing Wang, Guanfeng Liu, Xiaofang Zhou, et al. 2019. Feature-level Deeper Self- Attention Network for Sequential Recommendation.. In IJCAI. 4320–4326. [65] Yuhui Zhang, HAO DING, Zeren Shui, Yifei Ma, James Zou, Anoop Deoras, and Hao Wang. 2021. Language Models as Recommender Systems: Evaluations and Limitations. In I (Still) Can’t Believe It’s Not Better! NeurIPS 2021 Workshop. https://openreview.net/forum?id=hFx3fY7-m9b [66] Y. Zhang, S. Sun, M. Galley, Y. C. Chen, C. Brockett, X. Gao, J. Gao, J. Liu, and B. Dolan. 2019. DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation. (2019). [67] Zhe Zhao, Lichan Hong, Li Wei, Jilin Chen, Aniruddh Nath, Shawn Andrews, Aditee Kumthekar, Maheswaran Sathiamoorthy, Xinyang Yi, and Ed Chi. 2019. Recommending what video to watch next: a multitask ranking system. In Pro- ceedings of the 13th ACM Conference on Recommender Systems. 43–51. [68] Kun Zhou, Hui Wang, Wayne Xin Zhao, Yutao Zhu, Sirui Wang, Fuzheng Zhang, Zhongyuan Wang, and Ji-Rong Wen. 2020. S3-rec: Self-supervised learning for se- quential recommendation with mutual information maximization. In Proceedings of the 29th ACM international conference on information & knowledge management. 1893–1902. [69] Peilin Zhou, Jingqi Gao, Yueqi Xie, Qichen Ye, Yining Hua, Jaeboum Kim, Shoujin Wang, and Sunghun Kim. 2023. Equivariant contrastive learning for sequential recommendation. In Proceedings of the 17th ACM Conference on Recommender Systems. 129–140. [70] Peilin Zhou, Qichen Ye, Yueqi Xie, Jingqi Gao, Shoujin Wang, Jae Boum Kim, Chenyu You, and Sunghun Kim. 2023. Attention Calibration for Transformer- based Sequential Recommendation. In Proceedings of the 32nd ACM International Conference on Information and Knowledge Management. 3595–3605.
Title: Black-box language model explanation by context length probing: Summary: The increasingly widespread adoption of large language models has highlighted the need for improving their explainability. We present context length probing, a novel explanation technique for causal language models, based on tracking the predictions of a model as a function of the length of available context, and allowing to assign differential importance scores to different contexts. The technique is model-agnostic and does not rely on access to model internals beyond computing token-level probabilities. We apply context length probing to large pre-trained language models and offer some initial analyses and insights, including the potential for studying long-range dependencies. The source code and an interactive demo of the method are available. # Black-box language model explanation by context length probing # Ondˇrej Cífka Antoine Liutkus Zenith Team, LIRMM, CNRS UMR 5506 Inria, Université de Montpellier, France cifka@matfyz.cz, antoine.liutkus@inria.fr # Abstract The increasingly widespread adoption of large language models has highlighted the need for improving their explainability. We present con- text length probing, a novel explanation tech- nique for causal language models, based on tracking the predictions of a model as a func- tion of the length of available context, and al- lowing to assign differential importance scores to different contexts. The technique is model- agnostic and does not rely on access to model internals beyond computing token-level prob- abilities. We apply context length probing to large pre-trained language models and offer some initial analyses and insights, including the potential for studying long-range depen- dencies. The source code1 and an interactive demo2 of the method are available. Petunia was just handing round a box of after- dinner mints when a huge barn[6Wl swooped through the dining room window, dropped a letter on Mrs Mason's head and swooped out again. Mrs Mason screamed like a banshee and ran from the house, shouting about lunatics. Mr Mason stayed just'‘tong enough to tell the Dursleys that his wife was mortally afraid of birds] of all shapes and sizes, and to ask whether this was their idea of a joke. target: birds top:| the) them} him) Harry|| spiders Figure 1: A screenshot of a demo2 of the proposed method. After selecting a target token (here “birds”), the preceding tokens are highlighted according to their (normalized) differential importance scores (green = positive, red = negative), obtained using our method. The user can also explore the top predictions for contexts of different lengths (here the context “house, shouting about lunatics. [. . .] mortally afraid of”). # Introduction Large language models (LMs), typically based on the Transformer architecture (Vaswani et al., 2017), have recently seen increasingly widespread adop- tion, yet understanding their behaviour remains a difficult challenge and an active research topic. Notably, as the length of the context that can be accessed by LMs has grown, a question that has attracted some attention is how this influences their predictions. Some recent studies in this line of re- search suggest that even “long-range” LMs focus heavily on local context and largely fail to exploit distant ones (O’Connor and Andreas, 2021; Sun et al., 2021; Press et al., 2021; Sun et al., 2022). A more nuanced understanding of how contexts of different lengths influence LMs’ predictions may hence be valuable for further improving their per- formance, especially on tasks like long-form text generation where long-range dependencies are of critical importance. In this work, we propose context length probing, a simple explanation technique for causal (autore- gressive) language models, based on tracking the predictions of the model as a function of the num- ber of tokens available as context. Our proposal has the following advantages: • It is conceptually simple, providing a straight- forward answer to a natural question: How does the length of available context impact the prediction? • It can be applied to a pre-trained model with- out retraining or fine-tuning and without train- ing any auxiliary models. • It does not require access to model weights, internal representations or gradients. 1https://github.com/cifkao/ context-probing/ # 2https://cifkao.github.io/ context-probing/ • It is model-agnostic, as it can be applied to any causal LM, including attentionless archi- tectures like RNN (Mikolov et al., 2010) and CNN (Dauphin et al., 2017). The only require- ment for the model is to accept arbitrary input segments (i.e. not be limited to document pre- fixes). 3 Method # 3.1 Context length probing Furthemore, we propose a way to use this tech- nique to assign what we call differential importance scores to contexts of different lengths. This can be seen as complementary to other techniques like at- tention or saliency map visualization. Interestingly, contrary to those techniques, ours appears promis- ing as a tool for studying long-range dependencies, since it can be expected to highlight important in- formation not already covered by shorter contexts. A causal LM estimates the conditional probability distribution of a token given its left-hand context in a document: p(xn+1 | x1, . . . , xn). (1) We are interested here in computing the probabil- ities conditioned on a reduced context of length c ∈ {1, . . . , n}: # 2 Related work p(xn+1 | xn−c+1, . . . , xn), (2) A popular way to dissect Transformers is by vi- sualizing their attention weights (e.g. Vig, 2019; Hoover et al., 2020). However, it has been ar- gued that this does not provide reliable explana- tions and can be misleading (Jain and Wallace, 2019; Serrano and Smith, 2019). A more re- cent line of work (Elhage et al., 2021; Olsson et al., 2022) explores “mechanistic explanations”, based on reverse-engineering the computations per- formed by Transformers. These techniques are tied to concrete architectures, which are often “toy” ver- sions of those used in real-world applications, e.g. attention-only Transformers in Elhage et al. Other options include general-purpose meth- ods like neuron/activation interpretation (e.g. Geva et al., 2021; Goh et al., 2021; Dai et al., 2022), saliency maps (e.g. Fong and Vedaldi, 2017; An- cona et al., 2019) and influence functions (Koh and Liang, 2017). These require access to internal representations and/or the ability to backpropagate gradients, and have some caveats of their own (Kin- dermans et al., 2019; Kokhlikyan et al., 2021). More closely related to our work are studies that perform ablation (e.g. by shuffling, truncation or masking) on different contexts to understand their influence on predictions (O’Connor and Andreas, 2021; Sun et al., 2021; Press et al., 2021; Vafa et al., 2021). To our knowledge, all such existing works only test a few select contexts or greedily search for the most informative one; in contrast, we show that it is feasible to consider all context lengths in the range from 1 to a maximum cmax, which permits us to obtain fine-grained insights on the example level, e.g. in the form of the proposed differential importance scores. Moreover, many existing analyses (e.g. Vafa et al., 2021; O’Connor and Andreas, 2021) rely on specific training or fine- tuning, which is not the case with our proposal. so that we may then study the behavior of this distribution as a function of c. An apparent obstacle in doing so is that ap- plying the model to an arbitrary subsequence xn−c+1, . . . , xn, instead of the full document x1, . . . , xN , may lead to inaccurate estimates of the probabilities in Eq. (2). However, we note that large LMs are not usually trained on entire docu- ments. Instead, the training data is pre-processed by shuffling all the documents, concatenating them (with a special token as a separator), and splitting the resulting sequence into chunks of a fixed length (usually 1024 or 2048 tokens) with no particular relation to the document length. Thus, the models are effectively trained to accept sequences of to- kens starting at arbitrary positions in a document and it is therefore correct to employ them as such to compute estimates of Eq. (2).3 It now remains to be detailed how to efficiently evaluate the above probabilities for all positions n and context lengths c. Specifically, for a given document 1,..., 2, and some maximum context length Cmax, we are interested in an (N — 1) x Cmax X |V| tensor P, where V = {wy,..., wp} is the vocabulary, such that: Pn,c,i = p(xn+1 = wi | xn−c+1, . . . , xn), with Pn,c,∗ = Pn,n−1,∗ for n ≤ c.4 Observe that by running the model on any segment xm, . . . , xn, we obtain all the values Pm+c−1,c,∗ for c ∈ {1, . . . , n − m + 1}. Therefore, we can fill in the tensor P by applying the model along a sliding win- dow of size cmax, i.e. running it on N (overlapping) 3For models trained on data that is pre-processed differ- ently, (re)training or fine-tuning with data augmentation such as random shifts may be needed in order to apply our method, analogously to Vafa et al. (2021), who use word dropout to ensure compatibility with their method. 4Pn,c,∗ is a |V|-dimensional slice of P along the last axis. segments of length at most cmax. See Appendix A for an illustration and additional remarks. # 3.2 Metrics Having obtained the tensor P as we have just de- scribed, we use it to study how the predictions evolve as the context length is increased from 1 to cmax. Specifically, our goal is to define a suitable metric that we can compute from Pn,c,∗ and follow it as a function of c (for a specific n or on average). One possibility would be to use the negative log- likelihood (NLL) loss values: − log p(xn+1 | xn−c+1, . . . , xn). (4) However, this may not be a particularly suitable metric for explainability purposes, as it depends (only) on the probability assigned to the ground truth xn+1, while the LM outputs a probability dis- tribution Pn,c,∗ over the entire vocabulary, which may in fact contain many other plausible contin- uations. For this reason, we propose to exploit a metric defined on whole distributions, e.g. the Kullback-Leibler (KL) divergence. To achieve this, we choose the maximum-context predictions Pn,cmax,∗ as a reference and get: Dnie = Dxw[Prcmax.* | Pics] v = , Pr pemax,i LOY Pricowssi ©) FF 7,Cmax st Pp i= n. The rationale for (5) is to quantify the amount of information that is lost by using a shorter context c ≤ cmax. Interestingly, this metric is not related to the absolute performance of the model with maxi- mal context, but rather to how the output changes if a shorter context is used. # 3.3 Differential importance scores We are also interested in studying how individual increments in context length affect the predictions. We propose to quantify this as the change in the KL divergence metric (5) when a new token is in- troduced into the context. Specifically, for a pair of tokens xn+1 (the target token) and xm (the context token), we define a differential importance score (∆-score for short) ∆Dn,m = Dn,n−m−1 − Dn,n−m. (6) We may visualize these scores as a way to explain the LM predictions, much like is often done with name #param #layer #head dmodel max len 117 M gpt2 gpt2-xl 1.5 B gpt-j-6B 6.1 B 12 48 28 12 768 25 1600 16 4096 1024 1024 2048 Table 1: Hyperparameters of the 3 models used. attention weights, with two important differences. First, a high ∆Dn,m should not be interpreted as meaning that xm in isolation is important for pre- dicting xn+1, but rather that it is salient given the context that follows it (which might mean that it brings information not contained in the following context). Second, unlike attention weights, our scores need not sum up to one, and can be negative; in this regard, the proposed representation is more conceptually similar to a saliency map than to an attention map. # 4 Results We apply the proposed technique to publicly avail- able pre-trained large Transformer language mod- els, namely GPT-J (Wang and Komatsuzaki, 2021) and two GPT-2 (Radford et al., 2019) variants – see Table 1 for an overview. We use the validation set of the English LinES treebank5 from Universal Dependencies (UD; Nivre et al., 2020), containing 8 documents with a total length of 20 672 tokens6 and covering fiction, an online manual, and Eu- roparl data. We set cmax = 1023. We use the Transformers library7 (Wolf et al., 2020) to load the pre-trained models and run inference. Fur- ther technical details are included in Appendix B. 2 # 4.1 LM loss by context length Fig. 2 shows the cross entropy losses (NLL means) across the whole validation dataset as a function of context length c. As expected, larger models perform better than smaller ones, which is tradi- tionally explained by their larger capacity. A less common observation we can make thanks to this detailed representation is that the gains in perfor- mance come mostly from relatively short contexts (8–256 tokens); this is consistent with prior works (Sun et al., 2021; Press et al., 2021) which found 5https://universaldependencies.org/ treebanks/en_lines/index.html 6After concatenating all sentences and applying the GPT-2 tokenizer, which is used by both GPT-2 and GPT-J. 7https://github.com/huggingface/ transformers 64 — gpt2 —— gpt2-xl —— gpt-j-6B 1 4 16 64 256 context length 1024 Figure 2: Mean LM losses by context length. 34 64 0 g 8 44 —SS_ 2 —S—S 1 4 16 64 256 1024 context length — PROPN — PRON/SCON) — Noun — AUX/CCONJ/ADP — VERB/ADJ/ADV/NUM | — PART/PUNCT/DET Figure 3: Mean GPT-J loss by context length and part- of-speech (POS) tag of the target token. Only POS tags with at least 100 occurrences in the dataset are included. The tags are grouped (arbitrarily) for clarity. that very long contexts bring only minimal improve- ment (though these focused on specific long-range architectures and on contexts beyond the range we investigate here). In Fig. 3, we display the same information (loss by context length) broken down by part-of-speech (POS) tags, for GPT-J only. For most POS tags, the behavior is similar to what we observed in Fig. 2 and the loss appears to stabilize around context lengths 16–64. However, we see a distinct be- haviour for proper nouns (PROPN), which are the hardest-to-predict category for short contexts, but whose loss improves steadily with increasing c, sur- passing that of regular nouns (NOUN) at c = 162 and continuing to improve beyond that point. # 4.2 Per-token losses by context length We have also examined token-level losses, as well as the KL divergence metric (see Section 3.2); an example plot is shown in Fig. 4 and more are found in Appendix C.1. In general, we observe that the values tend to change gradually with c; large differ- ences are sparse, especially for large c, and can of- ten be attributed to important pieces of information appearing in the context (e.g. “owl” and “swoop” in the context of “birds” in Fig. 4). This justifies our use of these differences as importance scores. # 4.3 Differential importance scores To facilitate the exploration of ∆-scores from Sec- tion 3.3, we have created an interactive web demo,2 which allows visualizing the scores for any of the 3 models on the validation set as shown in Fig. 1. In Fig. 5, we display the magnitudes of the ∆- scores – normalized for each position to sum up to 1 across all context lengths – as a function of con- text length. The plot suggests a power-law-like in- verse relationship where increasing context length proportionally reduces the ∆-score magnitude on average. We interpret this as far-away tokens being less likely to carry information not already covered by shorter contexts. Long contexts (see inset in Fig. 5) bear less importance for larger models than for smaller ones, perhaps because the additional capacity allows relying more on shorter contexts. In Fig. 6, we also display the mean importance score received by each POS category, by model. We can see that proper nouns (PROPN) are sub- stantially more informative than other categories (which is in line with the observations in the pre- vious section), but less so for the smallest model. This could mean e.g. that larger models are better at memorizing named entities from training data and using them to identify the topic of the document, or simply at copying them from distant context as observed in (Sun et al., 2021). # 5 Limitations and future directions Experiments. We acknowledge the limited scope of our experiments, including only 8 (closed- domain) documents, 3 models and a single lan- guage. This is largely due to the limited availability of suitable large LMs and their high computational cost. Still, we believe that our experiments are valu- able as a case study that already clearly showcases some interesting features of our methodology. Computational cost. While we have demons- trated an efficient strategy to obtain predictions for all tokens at all possible context lengths, it still requires running the model N times for a document of length N . For a k-fold reduction in computational cost, the technique may be modified to use a sliding window with stride k > 1 (instead of k = 1 as proposed above). See Appendix A.1 for details. 10 10 + —_ — a gpt2 raid & gpte (atraid 31 — gpt2-xl swoop. “pafraid 5 — gpt2-xI p~<awife® ? + hae Vileys 2. | — optj-6B on. A Appa 6 uSWOOp $ “swoop > 3 4 g Ni“ owl -yowl- 2 pow a + : : 256 64 16 4 1 256 64 16 4 1 context length context length # 4 Zz Figure 4: NLL (left) and KL divergence (right) as a function of context length for a selected example: “[. . .] mortally afraid of birds” (same as in Fig. 1). The x axis is reversed for visual correspondence with the left-hand context. The 5 context tokens causing the largest drops in each metric for GPT-J are marked by red dots. — gpt2 —— gpt2-x| —— gpt-j-6B 600 800 logio(norm. |AD|) 4 16 64 context length 256 # 6 Conclusion and future directions We have presented context length probing, a novel causal LM explanation technique based on tracking the predictions of the LM as a function of context length, and enabling the assignment of differential importance scores (∆-scores). While it has some advantages over existing techniques, it answers different questions, and should thus be thought of as complementary rather than a substitute. Figure 5: Normalized ∆-score log-magnitude (mean and std. dev.) by context length and by model. Only positions n ≥ 1024 are included. gpt-j-6B gpt2-xl gpt2 SYM PART ADP CCON, PUNC ADV DET NUM AD INT) PRON AUX SCON} NOUN Xx VERB PROPN i?) 0.005 0 0.005 0 0.005 Figure 6: Mean ∆-score by POS tag of the context token and by model. Choice of metrics. The proposed methodology allows investigating how any given metric is im- pacted by context, yet our study is limited to NLL loss and the proposed KL divergence metric (the latter for defining importance scores). These may not be optimal for every purpose, and other choices should be explored depending on the application. For example, to study sequences generated (sam- pled) from a LM, one might want to define impor- tance scores using a metric that does depend on the generated token, e.g. its NLL loss or its ranking among all candidates. (Indeed, our web demo also supports ∆-scores defined using NLL loss values.) A particularly interesting feature of our ∆-scores is their apparent potential for discovering long- range dependencies (LRDs) (as they are expected to highlight information not already covered by shorter contexts, unlike e.g. attention maps). Remarkably, our analysis suggests a power-law- like inverse relationship between context length and importance score, seemingly questioning the impor- tance of LRDs in language modeling. While LRDs clearly appear crucial for applications such as long- form text generation, their importance may not be strongly reflected by LM performance metrics like cross entropy or perplexity. We thus believe that there is an opportunity for more specialized bench- marks of LRD modeling capabilities of different models, such as that of Sun et al. (2022), for exam- ple. These should further elucidate questions like to what extent improvements in LM performance are due to better LRD modeling, how LRDs are han- dled by various Transformer variants (e.g. Kitaev et al., 2020; Katharopoulos et al., 2020; Choroman- ski et al., 2021; Press et al., 2022), or what their importance is for different tasks. # Acknowledgments This work was supported by the LabEx NUMEV (ANR-10-LABX-0020) within the I-Site MUSE (ANR-16-IDEX-0006). The authors are grateful to the OPAL infrastructure from Université Côte d’Azur for providing resources and support. # References Marco Ancona, Cengiz Oztireli, and Markus Gross. 2019. Explaining deep neural networks with a poly- nomial time algorithm for Shapley value approxima- tion. In Proceedings of the 36th International Con- ference on Machine Learning, volume 97 of Proceed- ings of Machine Learning Research, pages 272–281. PMLR. Krzysztof Marcin Choromanski, Valerii Likhosherstov, David Dohan, Xingyou Song, Andreea Gane, Tamás Sarlós, Peter Hawkins, Jared Quincy Davis, Afroz Mohiuddin, Lukasz Kaiser, David Benjamin Be- langer, Lucy J. Colwell, and Adrian Weller. 2021. Rethinking attention with Performers. In 9th Inter- national Conference on Learning Representations (ICLR 2021). OpenReview.net. Damai Dai, Li Dong, Yaru Hao, Zhifang Sui, Baobao Chang, and Furu Wei. 2022. Knowledge neurons in pretrained transformers. In Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 8493– 8502, Dublin, Ireland. Association for Computational Linguistics. Yann N. Dauphin, Angela Fan, Michael Auli, and David Grangier. 2017. Language modeling with gated con- volutional networks. In Proceedings of the 34th In- ternational Conference on Machine Learning, vol- ume 70 of Proceedings of Machine Learning Re- search, pages 933–941. PMLR. Nelson Elhage, Neel Nanda, Catherine Olsson, Tom Henighan, Nicholas Joseph, Ben Mann, Amanda Askell, Yuntao Bai, Anna Chen, Tom Conerly, Nova DasSarma, Dawn Drain, Deep Ganguli, Zac Hatfield-Dodds, Danny Hernandez, Andy Jones, Jackson Kernion, Liane Lovitt, Kamal Ndousse, Dario Amodei, Tom Brown, Jack Clark, Jared Ka- plan, Sam McCandlish, and Chris Olah. 2021. A mathematical framework for Transformer circuits. Transformer Circuits Thread. Ruth C. Fong and Andrea Vedaldi. 2017. Interpretable explanations of black boxes by meaningful perturba- tion. In IEEE International Conference on Computer Vision, pages 3449–3457, Venice, Italy. IEEE Com- puter Society. Mor Geva, Roei Schuster, Jonathan Berant, and Omer Levy. 2021. Transformer feed-forward layers are key- value memories. In Proceedings of the 2021 Confer- ence on Empirical Methods in Natural Language Pro- cessing, pages 5484–5495, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. Gabriel Goh, Nick Cammarata, Chelsea Voss, Shan Carter, Michael Petrov, Ludwig Schubert, Alec Rad- ford, and Chris Olah. 2021. Multimodal neurons in artificial neural networks. Distill. Benjamin Hoover, Hendrik Strobelt, and Sebastian Gehrmann. 2020. exBERT: A Visual Analysis Tool to Explore Learned Representations in Transformer Models. In Proceedings of the 58th Annual Meet- ing of the Association for Computational Linguistics: System Demonstrations, pages 187–196, Online. As- sociation for Computational Linguistics. Sarthak Jain and Byron C. Wallace. 2019. Attention is not Explanation. In Proceedings of the 2019 Con- ference of the North American Chapter of the Asso- ciation for Computational Linguistics: Human Lan- guage Technologies, Volume 1 (Long and Short Pa- pers), pages 3543–3556, Minneapolis, Minnesota. Association for Computational Linguistics. Angelos Katharopoulos, Apoorv Vyas, Nikolaos Pap- pas, and François Fleuret. 2020. Transformers are RNNs: Fast autoregressive Transformers with linear attention. In Proceedings of the 37th International Conference on Machine Learning. PMLR. Pieter-Jan Kindermans, Sara Hooker, Julius Adebayo, Maximilian Alber, Kristof T. Schütt, Sven Dähne, Du- mitru Erhan, and Been Kim. 2019. The (un)reliability of saliency methods. In Wojciech Samek, Grégoire Montavon, Andrea Vedaldi, Lars Kai Hansen, and Klaus-Robert Müller, editors, Explainable AI: Inter- preting, Explaining and Visualizing Deep Learning, volume 11700 of Lecture Notes in Computer Science, pages 267–280. Springer. Nikita Kitaev, Lukasz Kaiser, and Anselm Levskaya. 2020. Reformer: The efficient Transformer. In 8th International Conference on Learning Representa- tions (ICLR 2020). OpenReview.net. Pang Wei Koh and Percy Liang. 2017. Understanding In black-box predictions via influence functions. Proceedings of the 34th International Conference on Machine Learning, volume 70 of Proceedings of Machine Learning Research, pages 1885–1894. PMLR. Narine Kokhlikyan, Vivek Miglani, Bilal Alsallakh, Miguel Martin, and Orion Reblitz-Richardson. 2021. Investigating sanity checks for saliency maps with arXiv preprint image and text classification. arXiv:2106.07475. Tomáš Mikolov, Martin Karafiát, Lukáš Burget, Jan ˇCernocký, and Sanjeev Khudanpur. 2010. Recurrent neural network based language model. In INTER- SPEECH 2010, 11th Annual Conference of the Inter- national Speech Communication Association, pages 1045–1048, Makuhari, Chiba, Japan. ISCA. Joakim Nivre, Marie-Catherine de Marneffe, Filip Gin- ter, Jan Hajiˇc, Christopher D. Manning, Sampo Pyysalo, Sebastian Schuster, Francis Tyers, and Daniel Zeman. 2020. Universal Dependencies v2: An evergrowing multilingual treebank collection. In Proceedings of the 12th Language Resources and Evaluation Conference, pages 4034–4043, Marseille, France. European Language Resources Association. Joe O’Connor and Jacob Andreas. 2021. What context features can transformer language models use? In Proceedings of the 59th Annual Meeting of the Asso- ciation for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), pages 851–864, Online. Association for Computational Linguistics. Catherine Olsson, Nelson Elhage, Neel Nanda, Nicholas Joseph, Nova DasSarma, Tom Henighan, Ben Mann, Amanda Askell, Yuntao Bai, Anna Chen, Tom Con- erly, Dawn Drain, Deep Ganguli, Zac Hatfield-Dodds, Danny Hernandez, Scott Johnston, Andy Jones, Jack- son Kernion, Liane Lovitt, Kamal Ndousse, Dario Amodei, Tom Brown, Jack Clark, Jared Kaplan, Sam McCandlish, and Chris Olah. 2022. In-context learning and induction heads. Transformer Circuits Thread. Ofir Press, Noah Smith, and Mike Lewis. 2022. Train short, test long: Attention with linear biases enables In The Tenth Interna- input length extrapolation. tional Conference on Learning Representations, Vir- tual Event. OpenReview.net. Ofir Press, Noah A. Smith, and Mike Lewis. 2021. Shortformer: Better language modeling using shorter In Proceedings of the 59th Annual Meet- inputs. ing of the Association for Computational Linguistics and the 11th International Joint Conference on Natu- ral Language Processing (Volume 1: Long Papers), pages 5493–5505, Online. Association for Computa- tional Linguistics. Alec Radford, Jeff Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2019. Language models are unsupervised multitask learners. Sofia Serrano and Noah A. Smith. 2019. Is attention in- terpretable? In Proceedings of the 57th Annual Meet- ing of the Association for Computational Linguistics, pages 2931–2951, Florence, Italy. Association for Computational Linguistics. Simeng Sun, Kalpesh Krishna, Andrew Mattarella- Micke, and Mohit Iyyer. 2021. Do long-range lan- guage models actually use long-range context? In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pages 807– 822, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. Simeng Sun, Katherine Thai, and Mohit Iyyer. 2022. ChapterBreak: A challenge dataset for long-range language models. In Proceedings of the 2022 Con- ference of the North American Chapter of the As- sociation for Computational Linguistics: Human Language Technologies, pages 3704–3714, Seattle, United States. Association for Computational Lin- guistics. Keyon Vafa, Yuntian Deng, David Blei, and Alexander Rush. 2021. Rationales for sequential predictions. In Proceedings of the 2021 Conference on Empiri- cal Methods in Natural Language Processing, pages 10314–10332, Online and Punta Cana, Dominican Republic. Association for Computational Linguistics. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Pro- cessing Systems 30: Annual Conference on Neural Information Processing Systems, pages 5998–6008, Long Beach, CA, USA. Jesse Vig. 2019. A multiscale visualization of attention in the transformer model. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics: System Demonstrations, pages 37–42, Florence, Italy. Association for Computational Lin- guistics. Ben Wang and Aran Komatsuzaki. 2021. GPT-J-6B: A 6 billion parameter autoregressive language model. Thomas Wolf, Lysandre Debut, Victor Sanh, Julien Chaumond, Clement Delangue, Anthony Moi, Pier- ric Cistac, Tim Rault, Remi Louf, Morgan Funtowicz, Joe Davison, Sam Shleifer, Patrick von Platen, Clara Ma, Yacine Jernite, Julien Plu, Canwen Xu, Teven Le Scao, Sylvain Gugger, Mariama Drame, Quentin Lhoest, and Alexander Rush. 2020. Transform- ers: State-of-the-art natural language processing. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations, pages 38–45, Online. Association for Computational Linguistics. © tell the D = -urs-leys that his wife was mort-allyafraid of ee ee ee | LM context length OANOA KWH = 10 the D -urs-leys that his wife was mort-allyafraid of birds Figure 7: A step of context length probing with cmax = 10. The input tokens are shown at the top, the target tokens at the bottom. When the LM is run on a segment of the document, the effective context length for each target token is equal to its offset from the beginning of the segment, e.g. the context for predicting “ D” is “ the” (c = 1), the context for “urs” is “ the D” (c = 2), etc. # A Context length probing Fig. 7 illustrates a step of context length probing. We wish to obtain the tensor P from Eq. (3), understood as a table where each cell contains the predictions (next-token logits) for a given position in the text and a given context length. By running our LM on a segment of the text, we get predictions such that for the n-th token in the segment, the effective context length is equal to n, which corresponds to a diagonal in the table. We can thus fill in the whole table by running the LM on all segments of length cmax (plus trailing segments of lengths cmax − 1, . . . , 1). Notice that this process is somewhat similar to (naïvely) running the LM in generation mode, except that at each step, the leading token is removed, preventing the use of caching to speed up the computation. In practice, it is not necessary to explicitly construct the tensor P . Indeed, we find it more efficient to instead store the raw logits obtained by running the model on all the segments, then do the necessary index arithmetics when computing the metrics. # A.1 Strided context length probing For a k-fold reduction in computational cost, we may instead use a sliding window with a stride k > 1, i.e. run the model only on segments starting at positions k (n − 1) + 1 for all n ∈ {1, . . . , ⌈N/k⌉}, rather than all positions. This way, for a target token xn+1, we obtain the predictions p(xn+1 | xn−c+1, . . . , xn) only for such context lengths c that c mod k = n. In other words, predictions with context length c are only available for tokens xc+1, xc+k+1, xc+2k+1, . . .. Consequently: • Overall, we still cover all context lengths 1, . . . , cmax, allowing us to perform aggregate analyses like the ones in Section 4.1. • When analyzing the predictions for a specific target token in a document (e.g. to compute ∆-scores), context tokens come in blocks of length k. Visualizations like the ones in Figs. 1 and 4 are still possible for all target tokens, but become less detailed, grouping every k context tokens together. • Computation time, as well as the space needed to store the predictions, is reduced by a factor of k. # B Technical details Data. The LinES treebank is licensed under Creative Commons BY-NC-SA 4.0. We concatenated all tokens from each of the documents from the treebank, then re-tokenized them using the GPT-2 tokenizer. We mapped the original (UD) POS tags to the GPT-tokenized dataset in such a way that every GPT token is assigned the POS tag of the first UD token it overlaps with. Models. We used the models EleutherAI/gpt-j-6B (Apache 2.0 license), and gpt2-xl and gpt2 (MIT license), all from huggingface.co. Computation. We parallelized the inference over 500 jobs on a compute cluster,8 each running on 8 CPU cores with at least 8 GB of RAM per core, with a batch size of 16. Each job took about 10–20 min for GPT-2 and 30–60 min for GPT-J. Additionally, computing the metrics from the logits (which take up 2 TB of disk space in float16) took between 2 and 4 h per model on a single machine with 32 CPU cores. The total computing time was 318 core-days, including debugging and discarded runs. # C Additional plots # C.1 Token-wise metrics as a function of context length Figs. 8 and 9 show NLL and KL divergence (5), respectively, as a function of context length, for selected target tokens (proper nouns) from the validation set. 8Nef, the cluster computing infrastructure of Inria Sophia Antipolis Méditerranée; see https://wiki.inria.fr/ ClustersSophia 144 _ gpt2 24 gpt2-xl — gpt-j-6B 10 8 6 Access 4 Nn wm SAC eMicrosoft 1024 256 64 16 4 1 (a) . . . and attribute means (and thus how the data between them will look in a browser), XML uses the tags only to delimit pieces of data, and leaves the interpretation of the data completely to the application that reads it. Additional information about XML can be found on the web site. About importing XML data Access 12 — gpt2 ZA 10 | —— gpt2-x! Zo — gptj-6B ymostt oa 5 — : et alike” 6 N 4 mete traWvhat 2 from 0 1024 256 64 16 4 1 (b) . . . he felt things were getting too quiet, and small explosions from Fred and George’s bedroom were considered perfectly normal. What Harry found most unusual about life at Ron’s, however, wasn’t the talking mirror or the clanking ghoul: it was the fact that everybody there seemed to like him. Mrs Weasley 12 —— gpt2 /~ 10 | —— gpt2-xl ed — — gpt-j-6B 8 6 ians {\; Russian 4 agree “aitibishop 1024 256 64 16 a 1 (c) . . . is a great difference between Napoleon the Emperor and Napoleon the private person. There are raisons d’etat and there are private crimes. And the talk goes on. What is still being perpetuated in all civilized discussion is the ritual of civilized discussion itself. Tatu agrees with the Archbishop about the Russians Figure 8: NLL losses (y axis) for 3 selected target tokens as a function of context length (x axis). Below each plot, the target token is displayed in bold, along with a context of 60 tokens. The x axis is reversed to correspond visually to left-hand context. The red dots show the 10 tokens that cause the largest drops in GPT-J cross entropy when added to the context. — gpt2 a i ech —— gpt2-xl — gpt-j-6B pte 1024 256 64 16 4 1 (a) . . . and attribute means (and thus how the data between them will look in a browser), XML uses the tags only to delimit pieces of data, and leaves the interpretation of the data completely to the application that reads it. Additional information about XML can be found on the web site. About importing XML data Access — gpt2 —— gpt2-xl v im: <— 10 —— gpt-j-6B ymostut a Ah 8 Lait Vou 6 4 puflarry teys) Jarihat 2 afrom 0 1024 256 64 16 4 1 (b) . . . he felt things were getting too quiet, and small explosions from Fred and George’s bedroom were considered perfectly normal. What Harry found most unusual about life at Ron’s, however, wasn’t the talking mirror or the clanking ghoul: it was the fact that everybody there seemed to like him. Mrs Weasley 3.0 4 2.54 2.0 4 154 1.04 0.5 4 0.0 4 — gpt2 I~ — — . / = Bah amaiaroiial \ Napolebtt uated wor : 10. 24 256 64 16 4 1 (c) . . . is a great difference between Napoleon the Emperor and Napoleon the private person. There are raisons d’etat and there are private crimes. And the talk goes on. What is still being perpetuated in all civilized discussion is the ritual of civilized discussion itself. Tatu agrees with the Archbishop about the Russians Figure 9: KL divergences (y axis) from Eq. (5) for 3 selected target tokens as a function of context length (x axis). Below each plot, the target token is displayed in bold, along with a context of 60 tokens. The x axis is reversed to correspond visually to left-hand context. The red dots show the 10 tokens that cause the largest drops in the metric (for GPT-J) when added to the context.
Title: Thor: Wielding Hammers to Integrate Language Models and Automated Theorem Provers: Summary: In theorem proving, the task of selecting useful premises from a large library to unlock the proof of a given conjecture is crucially important. This presents a challenge for all theorem provers, especially the ones based on language models, due to their relative inability to reason over huge volumes of premises in text form. This paper introduces Thor, a framework integrating language models and automated theorem provers to overcome this difficulty. In Thor, a class of methods called hammers that leverage the power of automated theorem provers are used for premise selection, while all other tasks are designated to language models. Thor increases a language model's success rate on the PISA dataset from $39\%$ to $57\%$, while solving $8.2\%$ of problems neither language models nor automated theorem provers are able to solve on their own. Furthermore, with a significantly smaller computational budget, Thor can achieve a success rate on the MiniF2F dataset that is on par with the best existing methods. Thor can be instantiated for the majority of popular interactive theorem provers via a straightforward protocol we provide. # Thor: Wielding Hammers to Integrate Language Models and Automated Theorem Provers Albert Q. Jiang University of Cambridge qj213@cam.ac.uk Wenda Li University of Cambridge wl302@cam.ac.uk # Szymon Tworkowski University of Warsaw szy.tworkowski@gmail.com # Piotr Miło´s Polish Academy of Sciences pmilos@mimuw.edu.pl # Konrad Czechowski University of Warsaw konrad.czechowski@gmail.com Tomasz Odrzygó´zd´z IDEAS NCBR tomaszo@impan.pl Yuhuai Wu Google Research & Stanford University yuhuai@google.com Mateja Jamnik University of Cambridge mateja.jamnik@cl.cam.ac.uk # Abstract In theorem proving, the task of selecting useful premises from a large library to unlock the proof of a given conjecture is crucially important. This presents a challenge for all theorem provers, especially the ones based on language models, due to their relative inability to reason over huge volumes of premises in text form. This paper introduces Thor, a framework integrating language models and automated theorem provers to overcome this difficulty. In Thor, a class of methods called hammers that leverage the power of automated theorem provers are used for premise selection, while all other tasks are designated to language models. Thor increases a language model’s success rate on the PISA dataset from 39% to 57%, while solving 8.2% of problems neither language models nor automated theorem provers are able to solve on their own. Furthermore, with a significantly smaller computational budget, Thor can achieve a success rate on the MiniF2F dataset that is on par with the best existing methods. Thor can be instantiated for the majority of popular interactive theorem provers via a straightforward protocol we provide. # Introduction In theorem proving, premise selection is the task of identifying useful facts from a large library that enable finding the proof of a given conjecture. It is essential for the discovery of many proofs, and Automated Reasoning in Large Theories (ARLT) depends on having apt methods for premise selection [Kühlwein et al., 2012, Sutcliffe et al., 2007]. A group of proof methods have been developed inside interactive theorem provers (ITPs) to deal with this task. They use external automated theorem provers (ATPs) to reach the remaining goals, inspect the proofs produced, and pick out the premises involved in them. Such systems are called hammers [Blanchette et al., 2016]. Hammers are available in many ITPs [Paulson, 2010, Kaliszyk and Urban, 2015, Gauthier and Kaliszyk, 2015, Czajka and Kaliszyk, 2018] and are immensely popular within the theorem proving community. Language models have had some successful applications in the area of formal theorem proving [Polu and Sutskever, 2020, Han et al., 2021, Jiang et al., 2021, Polu et al., 2022]. However, we observe that language-model-based reasoning systems are inept at premise selection. The difficulty of premise selection for language models is that they cannot effectively reason over thousands of available facts Preprint. Under review. and their definitions in plain text form. In subsection 2.2, we elaborate on the scale of the problems language models need to deal with for premise selection and provide empirical evidence for this difficulty. Seeing that hammers are very good at finding relevant facts, we propose in our framework to offload the premise selection task to them from language models. The resulting system is Thor, a framework that organically integrates language models and ATPs via the use of hammers. The methodology of Thor is simple and can be deployed in any hammer-enabled ITP: we first use the hammer method to attempt to prove every proof state in the training problems, and mark the successful application steps. Then we train the language model on the training problems, predicting a special token (e.g., <hammer>) if the hammer can be applied at the state. When doing evaluation, if the language model emits the special token, we invoke the hammer method. This methodology incurs very little extra computation compared to standard language model training while capitalising on the potential of a hybrid neuro-symbolic model. To demonstrate the usefulness of Thor, we instantiate it with a language-model-based reasoning system for the ITP Isabelle and Sledgehammer [Paulson, 2010], Isabelle’s implementation of the hammer method. We then investigate the performance of the instantiated Thor system on two datasets, PISA [Jiang et al., 2021] and MiniF2F [Zheng et al., 2022]. On PISA we dramatically improve the success rate of a language-model-based reasoning system from 39.0% to 57.0% and solve 8.2% of problems that cannot be solved by either language models or Sledgehammer alone. On MiniF2F, Polu et al. [2022] used expert iteration to improve on a language model and achieved the state-of-the-art 1-pass success rate of 29.6%. With much less computation, Thor increases this rate to 29.9%, slightly exceeding the previous result. It is worth noting that Thor and expert iteration can be used in tandem. In this paper, we demonstrate that finding suitable sub-systems for premise selection can benefit the performance of the overall reasoning system. Given Thor’s strong performance, computational efficiency, and applicability to many ITPs, we believe it should become a strong baseline as often as possible when language models are used for theorem proving. # Contributions 1. We created Thor, a theorem proving framework which integrates language models and automated theorem provers via using hammers. 2. We raised the state-of-the-art success rate of language-model-based reasoning systems on PISA from 39.0% to 57.0%. Thor proved 8.2% theorems which cannot be proved by either language models or Sledgehammer. 3. We improved the state-of-the-art success rate on MiniF2F from 29.6% to 29.9%, matching the language models trained with expert iteration, but with far less computation. # 2 Background # 2.1 Automated and Interactive Theorem Proving Mechanising theorem proving has been a grand challenge of artificial intelligence since the late 1950s [Gelernter, 1959]. A group of systems which we call automated theorem provers attempt to use automated procedures to determine the validity of conjectures (e.g., the DPLL algorithm [Davis et al., 1962] for SAT problems [Tarski, 1969]). Popular examples of ATPs include E, SPASS, Z3, CVC4, and Vampire. Although SAT is known to be NP-complete [Cook, 1971], modern ATPs can often solve problems with millions of symbols [Ohrimenko et al., 2009] and are useful practically. ATPs are often based on fragments of first-order logic, which limits the type of theorems they can express. Hence, projects such as the formalisation of complicated mathematical results [Gonthier et al., 2008, Avigad et al., 2007, Gonthier et al., 2013, Scholze, 2021] and operating system kernel verification [Klein et al., 2009] are done in interactive theorem provers, often based on higher-order logic or dependent type theory. ITPs and ATPs have very different objectives: ITPs aim at making it easy to formalise a diverse set of problems in numerous mathematical domains in a sound manner; while ATPs focus on improving the efficiency and performance on very well-defined problems like SAT solving. Prominent ITPs include Isabelle, Mizar, HOL Light, HOL4, Lean, and Coq. Theorem proving in ITPs can be modelled as a sequential decision process: initially a theorem gets declared and the proof state contains some goals; at each step, the user produces a proof step that 2 applies to and transforms the proof state; when all the goals have been discharged, the theorem is considered proven. Large libraries of mathematical knowledge such as the Archive of Formal Proofs1 and the Mizar Mathematical Library2 have been built around these ITPs. Because of the size of these mathematical libraries, to find useful premises in them is a difficult problem. In the next subsections we illustrate how two different approaches deal with premise selection. # 2.2 Language Models for Theorem Proving Language models that automate theorem proving mostly follow the approach of the GPT-f model [Polu and Sutskever, 2020]: pre-trained causal language models are used to predict a proof step that can be applied, given the current proof state and some optional context. Concretely, a language model can take as input and output, two sequences of the following form: INPUT: OUTPUT: <SOS> <CTXT> $(context) <PRF_STT> $(proof state) <PRF_STP> $(proof step) <EOS> OUTPUT: $(proof step) <EQS> At test time, the reasoning system receives the text representation of the current proof state, samples a proof step from the language model, applies it to the ITP, and repeats until the proof is finished or a computational budget has been reached. A best-first strategy is often used for proof search: a queue of search nodes is maintained with the priority being the accumulated log likelihood of the generated proof steps. Language models treat all input and output information as text and they are usually limited to be a few thousands of characters long. To do premise selection well, the language model has to either memorise all the relevant premises during training, or be prompted with available premises in evaluation. It is difficult to do the former because a mathematical corpus can have too many facts for a language model to remember. For example, the Archive of Formal Proofs has more than 200,000 theorems, plus the numerous definitions and their derivations to serve as premises. The latter is no easier because there may be too many premises to fit into the input. For instance, if we use the textual representation of 300 available premises (a usual number used for premise selection with symbolic tools) and their definitions as the context in the input-output format above, the input length can well exceed 10,000 characters and the limit of standard language models. We observe that empirically 1.9% of the steps involving premise selection generated by the language model manage to advance the proof, while the number is 28.2% for steps having no premises. Hence, a good mechanism for premise selection could bring crucial benefits. # 2.3 Hammers Blanchette et al. [2016] define hammers as methods that “automate reasoning over large libraries developed with formal proof assistants (ITPs)”. Consider, for example, Sledgehammer (designed for Isabelle) which is the original and the most popular implementation of hammers. Figure 1 2 /∈ Q in Isabelle. The beauty of using Sledgehammer with Isabelle is that presents a proof of despite the complicated-looking proof, humans only need to sketch the proof in Figure 1a and let Sledgehammer find all the necessary premises to complete every single proof step. The final accepted proof is presented in Figure 1b. The Sledgehammer proof steps use the internal proof methods metis, meson, smt, auto, simp, fastforce and blast. Conveniently, this tells us which steps in the corpus are generated by Sledgehammer. Note that a human user might also use the proof methods auto, simp, fastforce and blast as these do not contain additional premises. Only the methods metis, meson, smt are exclusive to Sledgehammer. We now describe how Sledgehammer performs premise selection: Sledgehammer makes it possible to leverage the advancement of ATP research while using ITPs, and can thus be seen as a bridge between the two [Paulson, 2010]. When invoked, Sledgehammer translates the current goal together with hundreds of possibly relevant premises into a format (e.g., SMT-LIB, TPTP) that external ATPs can understand [Meng and Paulson, 2008]. The ATPs are then executed to solve the current goal. Note that Isabelle follows a kernel philosophy (i.e., only a handful of axioms and inference rules are trusted), and external ATPs are used skeptically—should a proof be found by the ATPs, Sledgehammer picks out the useful premises, and reconstructs the proof within the Isabelle kernel # 1https://www.isa-afp.org 2http://mizar.org/library/ 3 lemma "sqrt 2 ¢ Q" proof assume "sqrt 2 € Q" then obtain a brrint where “sqrt 2 = a/b" “coprime a b # 0" sledgehammer then have c: yay fer ee ar ud sledgehammer then have "b*2 * 0" sledgehammer ees oa hee ete ae cee a are sledgehammer then have "even a" sledgehammer then obtain cr:int where "a=2*c" sledgehammer with * have "b*2 = 2*c*2" sledgehammer then have "even b" sledgehammer with «coprime a b> «even a> «even bi show False sledgehammer une lemma “sqrt 2 ¢ Q" proof assume “sqrt 2 € Q" then obtain a br:int where "sqrt 2 = a/b" “coprime a b" "b # 0" by (metis ases' less_irrefl) then have c: a*2 / b*2" by (smt (23) of_int_power power_divide real_sart_pow2) them Bevel! Dae oO. by, pest force then have *: "2*b*2 = a*2 by (smt (verit, ccfv_SIG) ¢ comm semiring class.distrib eq_divide_eq numeral(1) mult_cancel_right1 numeral_Bito numeral_plus numeral of_int_add of_int_power of_int_power_eq of int_cancel_iff one_plus_numeral) then have "even a” by (smt (23) even_power oddE) then obtain “a=2*c" by blast with * have " ” by auto ben) have) joven Us by (smt (23) even_power oddE) with «coprime a b> veven a> ceven b> show False by fastforce qed (a) The proof sketch produced by the human user. The sledgehammer command indi- cates that the human invokes the Sledgeham- mer method at that point. (b) The proof accepted by Isabelle. The steps containing assume, obtain, have, show are from the original hu- man proof sketch. The steps containing metis, smt, fastforce, blast, auto, fastforce are completed by Sledgehammer. √ Figure 1: A proof of 2 /∈ Q, adapted from the original by Li et al. [2021] with consent. (e.g., using the primitive inference rules). Here, external ATPs serve as relevance filters of premises rather than trusted oracles. Hammers implemented in other ITPs are largely similar. # 3 Thor In this section we introduce Thor, a framework integrating language models and automated theorem provers via the use of hammers. Thor is motivated by the difficulty for language models to do premise selection and the excellent performance of hammers for it: we should be able to drastically improve automation in theorem proving if we can take the best from both worlds. Below we provide the protocol of adopting Thor for a hammer-enabled ITP. We first provide Thor’s training data preprocessing procedure in Algorithm 1, and then look at a concrete example to demonstrate its use. Algorithm 1 Thor’s training data preprocessing algorithm. # Require: Proof state s, hammer method h INPUT = s.input if h(s)→ success then OUTPUT = <hammer> <EOS> else OUTPUT = s.output end if return (INPUT, OUTPUT) > Hammer can be applied to the proof state > Hammer fails at the proof state √ 2 /∈ Q (Figure 1) after the step then have "even a": Now consider the situation in the proof of without Thor, it should produce the following datapoint INPUT: OUTPUT: <SOS> <CTXT> $(context) <PRF_STT> $(proof state) <PRF_STP> by (smt (z3) even_power oddE) <EOS> With Thor’s preprocessing, we apply the hammer method to the proof state and find out that it can be done successfully. Hence, we keep the input the same and change the output to: OUTPUT: <hammer> <EOS> If the hammer method cannot be applied, we leave the datapoint unchanged. We iterate over every datapoint in the training data and apply this preprocessing algorithm. 4 We hypothesise that being exposed to training data in this format, the language model is capable of learning a heuristic for when the hammer can be successfully invoked. At evaluation time, whenever the language model outputs the sequence <hammer> <EOS>, instead of applying it directly to the ITP, we call the hammer method. This effectively makes the hammer an invokable method for the language model. This protocol is straightforward to implement for hammer-enabled ITPs. The only extra cost of deploying Thor is in the data preprocessing step. Multiplying the hammer time limit by the average number of problems submitted to the Archive of Formal Proofs in one year, we estimate that 7400 CPU hours per year are needed to preprocess one of the largest proof corpora available. This is a modest cost since the process only needs to be done once per dataset and the results can be shared. Better still, for some ITPs, the hammer method leaves a trace, greatly reducing the time needed to figure out which steps can be solved by hammers. For the ITP Coq, all steps containing the keyword sauto are generated by CoqHammer [Czajka and Kaliszyk, 2018]. For Isabelle, all steps containing the keywords metis, meson, smt are generated by Sledgehammer (described in Section 2.3). With these traces, deploying Thor on ITPs like Coq or Isabelle incurs little extra computational cost compared to training a standard language model. # 4 Experiment Our experiments are intended to answer the following research questions: 1. Can Thor prove theorems that cannot be proved by language models or automated theorem provers individually? Does Thor improve premise selection for language models? 2. Does explicitly learning how to select premises hurt the performance of language models? 3. How important are the context information and the diversity of sequence generation? 4. How does Thor compare with other methods at improving language models for theorem proving? To answer these questions, we create an instance of Thor for the ITP Isabelle. We choose Isabelle for two reasons: (1) Isabelle’s Sledgehammer is one of the most mature hammer methods among major ITPs, and may thus showcase Thor’s full potential; and (2) Isabelle’s Archive of Formal Proofs is one of the world’s largest formal mathematical libraries, suitable for data-hungry methods like language models. We make explicit the details of our experimental setup next. # 4.1 Experimental Setup Machine specification For pre-training, fine-tuning, and evaluation, we use a TPUVM with 8 cores from Google Cloud Platform. The Isabelle process has access to up to 32 CPU cores. We estimate that reproducing all the experiments in this paper requires a total of 1160 TPU hours. Language model architecture We use a decoder-only transformer [Vaswani et al., 2017] language model, adapting the setup, codebase, and hyperparameters from [Wang and Komatsuzaki, 2021]. The language model has 700M non-embedding parameters, with 24 layers, 24 attention heads, a hidden dimension of 1536, and a GPT-2 [Radford et al., 2019] tokenizer with a vocabulary size of 50400. Rotary positional embeddings [Su et al., 2021] are used. The model is pre-trained on the GitHub + arXiv subsets of The Pile [Gao et al., 2021], with a context length of 2048. We use a global batch size of 32 sequences which amounts to 65536 tokens. For the first 3,000 steps, the learning rate linearly increases from 0 to 0.0002, and then it follows a cosine schedule with a final value of 1.2 × 10−5 for 197,000 steps. We use a weight decay rate of 0.05 and no dropout for pre-training. Pre-training takes ≈ 150 TPU hours. For fine-tuning, we use the procedure described in Section 3 to prepare the PISA dataset. We use the most recent proof step as the context in each datapoint. The same learning rate scheduling strategy is used, with a peak learning rate of 3 × 10−4 after 10,000 steps and a final learning rate of 3 × 10−5 after a further 90,000 steps. We use a dropout rate of 0.15 and a weight decay rate of 0.1. The global batch size is 256 sequences, or 524, 288 tokens. We early-stop fine-tuning and take the checkpoint at 11,000 steps for evaluation as the validation loss reaches a minimum then. Fine-tuning takes ≈ 50 TPU hours. 5 # Table 1: Proof success rates on PISA/test Method Success rate (%) LISA [Jiang et al., 2021] 33.2 Sledgehammer Language model Language model ∪ Sledgehammer 25.7 39.0 48.8 Thor 57.0 Sledgehammer configuration To set up Sledgehammer, we mostly follow the default Isabelle2021 configuration. An important default parameter is that the Sledgehammer timeout limit is 30s. Our configuration uses the on-machine versions of the five default ATPs (E, SPASS, Vampire, Z3, and CVC4) to prevent performance deviation caused by network issues. Proof search To sample from the language model, we use temperature sampling with the tempera- ture parameter T = 1.2. To search for the proof of a theorem, we use the best-first search strategy described in [Polu and Sutskever, 2020]. The queue is ordered by the accumulated log likelihoods of the generated proof steps, with a maximum length of 32. Each proof step has a timeout limit of 10s. The search is terminated if and only if one of the following scenarios happens: (1) a valid proof has been found for the theorem; (2) the language model is queried 300 times; (3) a wallclock timeout of 500s has been reached; (4) the queue is empty but the theorem is not proved. Empirically, it takes ≈ 60 TPU hours to evaluate 1, 000 problems. Our language model setup is different from Language models of ISAbelle proofs [Jiang et al., 2021, LISA] in three aspects: (1) our language model has 700M instead of 163M non-embedding parameters (2) the most recent proof step is included in the language model prompt (3) a higher sampling temperature (1.2 instead of 1.0) is used. # 4.2 Datasets and Environment We use two datasets. The first is the PISA dataset [Jiang et al., 2021], which includes the Isabelle/HOL repository3 under a BSD-style license and the Archive of Formal Proofs version 2021-10-224, whose various entries are under open-source licenses as described on its official page. PISA contains the core higher-order logic library of Isabelle, as well as a diverse library of proofs formalised with Isabelle, mostly concerning mathematics or verification of software and hardware. The PISA dataset contains 2.49 million datapoints in total. The proof states have an average length of 369 characters and the proof steps have an average length of 33 characters. All of the Isabelle/HOL theorems go into the training set as they are considered foundational and might be used by all other repositories. We make a 95%/1%/4% split of theorems from the AFP for the training/validation/test sets. We randomly select 3,000 theorems from the test set (PISA/test) for the evaluation of model performance. The second is the Isabelle fraction of the MiniF2F dataset [Zheng et al., 2022] under an Apache license. The dataset contains 488 high school mathematics competition problems split into a validation set and a test set, each with 244 problems. These problems have been formalised in Lean, Metamath, and Isabelle to provide a benchmark of the same problems in different ITP languages. This allows us to contrast different approaches developed for different ITPs. Since we do not use the validation set for model selection, we do not actually distinguish between the two sets. Hence, we mainly compare with previous work on the test set as the final result. We use the codebase by Jiang et al. [2021], under a BSD 3-clause license, to interact with the Isabelle server and prove theorems from both datasets. 6 400 Ml Language model 600 Ml Language model 5 3 Thor 5 3 Thor & & 400 ‘6 200 ‘6 ° ° < & 200 0 5 10 15 0 5 10 15 #Premises in proofs #Premises in ground truth proofs (a) The number of premises in successful proofs found by the language model and Thor. (b) The number of premises in ground truth proofs for problems solved by the language model and Thor. Figure 2: Comparison of the number of premises in problems the language model and Thor can solve. # 4.3 Thor Against an Ensemble of a Language Model and Sledgehammer Because Thor has both a language model and Sledgehammer at its disposal, we wish to investigate how it fares against a simple ensemble of the two. We set out to evaluate the performance of Thor, as well as a language model of the same configuration, and Sledgehammer with a 120s timeout on PISA/test. It takes ≈ 50 TPU hours to evaluate Thor for 1000 problems. The proof success rates on PISA/test are presented in the second column of Table 1. We can see that the language model alone and Sledgehammer alone can prove 39.0% and 25.7% of the problems respectively. When we take the union of the problems they manage to solve individually, we get a 48.8% success rate. Thor manages to prove 57.0% of the problems. This implies that for 8.2% of the problems, Thor uses both the language model and Sledgehammer to complete the proofs, and it’s not possible to achieve this with only the language model or only Sledgehammer. We perform 4 case studies on problems that only Thor can solve in Appendix A. Thor’s motivation is to solve the premise selection problem for language models. To confirm that Thor helps premise selection, we collect the proofs generated by the language model and Thor respectively and count the number of premises in them. The results are presented in Figure 2a: we can see that for proofs requiring 0 or 1 premises, Thor and the language model perform similarly. But for proofs requiring more premises, Thor performs much more robustly, finding several times more proofs than the language model. We also count the number of premises in the ground truth proofs (written by humans) for theorems the language model and Thor can prove. The results are presented in Figure 2b: we see that whatever the number of premises the ground truth uses, Thor outperforms the language model in finding proofs, and the more premises the ground truth proof has, the more obvious is the effect. We conclude that Thor is indeed more capable of premise selection than language models. # 4.4 The Effect of Learning How to Select Premises The procedure we described in Section 3 ensures that the language model learns when to do premise selection, but not how to do it, by replacing the premise selection steps with <hammer>. Here we investigate the effect of making the language model learn both when and how. An easy way to achieve this is to create a variant of Thor: (i) at training time, use the original data; (ii) at evaluation time, when the language model outputs a sequence containing any of the Sledgehammer keywords, invoke Sledgehammer. This further simplifies data preparation and explicitly subjects the language model to perform premise selection. To investigate the effect of this alternative approach, we evaluate a system trained in this way on PISA/test and present its success rate in Table 2. We can see that it achieves a success rate of 55.4% on PISA/test, 1.6% lower than the base version of Thor, which suggests that explicitly learning how to do premise selection marginally decreases its success rate. This result is expected: since finding how to do premise selection is entrusted to the hammer method, the language model should focus on learning when to invoke the hammer for optimal performance. Making the language model learn an irrelevant additional task only hurts Thor’s performance. 3https://isabelle.in.tum.de/website-Isabelle2021/dist/library/HOL/index.html 4https://www.isa-afp.org/release/afp-2021-10-22.tar.gz 7 # Table 2: Proof success rates on PISA/test Variants of Thor Success rate (%) Base, sampling temperature T = 1.2 57.0 Learning how to select premises No proof context Sampling temperature T = 1.0 55.4 53.6 55.7 # Table 3: Proof success rates on MiniF2F. Method Valid (%) Test (%) PACT [Han et al., 2021] Expert iteration [Polu et al., 2022] 23.9 33.6 24.6 29.6 Sledgehammer Language model Language model ∪ Sledgehammer 9.9 25.0 27.1 10.4 24.2 27.5 Thor 28.3 29.9 # 4.5 The Effect of the Proof Context Our language model setup differs from that of LISA [Jiang et al., 2021] in that we use the most recent proof step as the context in the input data, as introduced in Section 3. This is based on the intuition that the most recent proof step information is beneficial for the language model’s reasoning ability. In this subsection we perform an ablation study to confirm the effect of this context on Thor. Here a variant of Thor is trained without the context information and evaluated on PISA/test. The results are in Table 2. We observe that this variant manages to prove 53.6% of theorems on PISA/test, 3.4% fewer than the base version of Thor. The drop in success rate indicates that the context information we use is crucial for the optimal performance of Thor. # 4.6 The Effect of the Sequence Sampling Diversity Our language model setup differs from LISA [Jiang et al., 2021] also in the sampling temperature. Previous works on language models for theorem proving often use a temperature T = 1.0 [Polu and Sutskever, 2020, Jiang et al., 2021] for sampling output sequences, while we use T = 1.2. A higher temperature in the sampling procedure means that the generated sequences are more diverse (having a higher entropy). Here we perform an ablation study on the diversity of Thor-generated sequences. We evaluate Thor with sampling temperature T = 1.0 on PISA/test and the success rate is in Table 2. We can see that the success rate with sampling temperature T = 1.0 is 55.7%, 1.3% lower than with T = 1.2. This suggests a more diverse sampling strategy can improve Thor’s performance, and that the optimal diversity in language model samples varies for different systems. # 4.7 Comparing Thor with Expert Iteration There exist other methods for improving language models for theorem proving like value function training [Polu and Sutskever, 2020], proof artifact co-training [Han et al., 2021, PACT], and expert iteration [Polu et al., 2022]. We wish to compare Thor with them. However, these methods operate in ITPs other than Isabelle and are thus hard to compare with directly. Thankfully, Polu et al. [2022] used expert iteration [Silver et al., 2017] to improve PACT [Han et al., 2021] and to achieve the state-of-the-art result on MiniF2F, a dataset containing multiple ITP formalisations of the same problems. Hence, we can fairly contrast expert iteration with Thor. We should emphasise that Thor and expert iteration are not incompatible methods: one can use Thor together with expert iteration. We start by evaluating Thor, a language model with the same configuration, and Sledgehammer on MiniF2F. The results are presented in Table 3. We also include the success rates of the language model that Polu et al. [2022] used (PACT), as well as the language model after expert iteration in the same table. The success rates on the validation set are also included, but we use the rates on the test 8 set as the final results, as the valid set can be used for model selection. We can see that the language model is able to prove 24.2% of the problems on MiniF2F, similar to PACT’s 24.6%. Thor increases the success rate of the language model by 5.7% to 29.9%, while expert iteration increases the success rate of PACT by 5.0% to 29.6%. Hence, the improvement in proof success rate brought upon the language model by Thor is comparable to that by expert iteration. An important factor in choosing a suitable method is its cost. Expert iteration requires manually creating a set of “curriculum” problems, evaluating the language model on them, and training the language model on a growing training set for one epoch every iteration. We estimate that to perform expert iteration at the same scale as Polu et al. [2022] for Isabelle, it would cost 100 human hours to formalise 300 maths problems, and 500 TPU hours to evaluate and fine-tune the language model for 8 expert iterations. Thor, on the other hand, incurs little extra computational cost compared with training a standard language model. We conclude that while requiring a much smaller computational budget, Thor can improve language models’ success rates to a similar degree as expert iteration. # 5 Related Work Language models were first applied to automate theorem proving by Polu and Sutskever [2020]. Since then, there have been a few works [Han et al., 2021, Jiang et al., 2021, Polu et al., 2022] aiming to enhance the ability of language-model-based reasoning systems, or to enable these systems for interactive theorem provers that were not supported before. All of these works used the same framework laid down by Polu and Sutskever [2020], namely to iteratively sample from a language model and directly apply the output to the ITP. Thor, to the best of our knowledge, is the first system to explicitly hybridise language models and symbolic reasoning tools (ATPs) for theorem proving. Instead of relying on language models entirely, Thor uses hammers, a well-established tool, to solve premise selection. With the growing bodies of formal mathematical libraries, premise selection has become one of the most crucial tasks of theorem proving. The hammer method is one of the many ways that premise selection can be done. We have described how the Isabelle implementation of the hammer method selects premises in Section 2. HOL(y)Hammer [Kaliszyk and Urban, 2015] and CoqHammer [Czajka and Kaliszyk, 2018] implement the hammer method for HOL Light and Coq respectively, making it possible for Thor to be instantiated for them. Apart from hammers, SInE [Hoder and Voronkov, 2011] and SRASS [Sutcliffe and Puzis, 2007] are both symbolic methods that take on the task of premise selection by ranking the available premises according to their relevance to the current conjecture, measured by syntactic and semantic distances respectively. MaLARea [Urban, 2007] pioneered having machine learning components in premise selection systems and its later version MaLARea SG1 [Urban et al., 2008] combines machine learning and formal semantics for premise selection. A few approaches [Irving et al., 2016, Wang et al., 2017, Kaliszyk et al., 2017] use deep learning in the premise selection task. All these diverse methods may have quantitative or qualitative merits over the hammer approach, and thus have the potential to be integrated as the premise selection component for future versions of Thor. # 6 Discussion In this paper we introduced a simple approach to overcome language models’ weakness in premise selection for theorem proving: we created Thor, a framework that integrates language models and automated theorem provers via the hammer proof method. We presented a straightforward protocol for deploying Thor on any hammer-enabled ITP. The instance of Thor with Isabelle dramatically increased the number of automatically proved theorems, suggesting that language models’ deficiency at premise selection can be effectively compensated by utilising ATPs. Furthermore, approaches like expert iteration [Polu et al., 2022] or proof artifact co-training [Han et al., 2021] have no contradictions and can be easily incorporated with Thor. Compared with these methods, Thor has the additional advantage of being computationally efficient. One limitation of Thor is that it only admits automated theorem provers that directly generate valid proof steps in the ITP via the use of the hammer. In Section 5, we pointed out that there are other premise selection tools with approaches different from the hammer method that the current version of Thor cannot use. Also, there exist methods which assist premise selection but do not directly generate 9 the proof steps. An example of this is SErAPIS [Stathopoulos et al., 2020], which performs semantic search over the Isabelle mathematical library with the help of Wikipedia. Thor cannot use this class of methods either. We leave to future work the task of broadening the options for the premise selection tool that Thor uses. Here we only tested Thor on the ITP Isabelle due to the computational costs of experiments. Therefore another future direction is to instantiate Thor with other ITPs and see whether improvements brought by Thor are as significant for other ITPs as we show them here for Isabelle. Thor demonstrates how a difficult problem for language models can be solved by borrowing tools from another research domain. We are encouraged by its success and think that more problems like premise selection can be identified and solved similarly. With its strong performance, computational efficiency, and convenient deployment, Thor gives scope to tool hybridisation, which shows promise to be impactful in the field of automated reasoning, and artificial intelligence in general. # References Jeremy Avigad, Kevin Donnelly, David Gray, and Paul Raff. A formally verified proof of the prime number theorem. ACM Transactions on Computational Logic (TOCL), 9(1):2–es, 2007. Jasmin Christian Blanchette, Cezary Kaliszyk, Lawrence C. Paulson, and Josef Urban. Hammering towards QED. J. Formaliz. Reason., 9(1):101–148, 2016. doi: 10.6092/issn.1972-5787/4593. URL https://doi.org/10.6092/issn.1972-5787/4593. Stephen A Cook. The complexity of theorem-proving procedures. In Proceedings of the third annual ACM symposium on Theory of computing, pages 151–158, 1971. Lukasz Czajka and Cezary Kaliszyk. Hammer for coq: Automation for dependent type theory. J. Autom. Reason., 61(1-4):423–453, 2018. doi: 10.1007/s10817-018-9458-4. URL https: //doi.org/10.1007/s10817-018-9458-4. Martin Davis, George Logemann, and Donald Loveland. A machine program for theorem-proving. Communications of the ACM, 5(7):394–397, 1962. Leo Gao, Stella Biderman, Sid Black, Laurence Golding, Travis Hoppe, Charles Foster, Jason Phang, Horace He, Anish Thite, Noa Nabeshima, Shawn Presser, and Connor Leahy. The pile: An 800gb dataset of diverse text for language modeling, 2021. URL https://arxiv.org/abs/ 2101.00027. In Xavier Leroy and Alwen Tiu, editors, Proceedings of the 2015 Conference on Certified Programs and Proofs, CPP 2015, Mumbai, India, January 15-17, 2015, pages 49–57. ACM, 2015. doi: 10.1145/2676724.2693173. URL https://doi.org/10.1145/2676724.2693173. Herbert L Gelernter. Realization of a geometry theorem proving machine. In IFIP congress, pages 273–281, 1959. Georges Gonthier, Andrea Asperti, Jeremy Avigad, Yves Bertot, Cyril Cohen, François Garillot, Stéphane Le Roux, Assia Mahboubi, Russell O’Connor, Sidi Ould Biha, et al. A machine-checked proof of the odd order theorem. In International conference on interactive theorem proving, pages 163–179. Springer, 2013. Georges Gonthier et al. Formal proof–the four-color theorem. Notices of the AMS, 55(11):1382–1393, 2008. Jesse Michael Han, Jason Rute, Yuhuai Wu, Edward W. Ayers, and Stanislas Polu. Proof artifact co-training for theorem proving with language models. CoRR, abs/2102.06203, 2021. URL https://arxiv.org/abs/2102.06203. Kryštof Hoder and Andrei Voronkov. Sine qua non for large theory reasoning. In International Conference on Automated Deduction, pages 299–314. Springer, 2011. Geoffrey Irving, Christian Szegedy, Alexander A Alemi, Niklas Eén, François Chollet, and Josef Urban. Deepmath-deep sequence models for premise selection. Advances in neural information processing systems, 29, 2016. 10 Albert Q. Jiang, Wenda Li, Jesse Michael Han, and Yuhuai Wu. Lisa: Language models of isabelle proofs. 6th Conference on Artificial Intelligence and Theorem Proving, 2021. Cezary Kaliszyk and Josef Urban. Hol(y)hammer: Online ATP service for HOL light. Math. Comput. Sci., 9(1):5–22, 2015. doi: 10.1007/s11786-014-0182-0. URL https://doi.org/10.1007/ s11786-014-0182-0. Cezary Kaliszyk, François Chollet, and Christian Szegedy. Holstep: A machine learning dataset for higher-order logic theorem proving. arXiv preprint arXiv:1703.00426, 2017. Gerwin Klein, Kevin Elphinstone, Gernot Heiser, June Andronick, David Cock, Philip Derrin, Dhammika Elkaduwe, Kai Engelhardt, Rafal Kolanski, Michael Norrish, et al. sel4: Formal verification of an os kernel. In Proceedings of the ACM SIGOPS 22nd symposium on Operating systems principles, pages 207–220, 2009. Daniel Kühlwein, Twan van Laarhoven, Evgeni Tsivtsivadze, Josef Urban, and Tom Heskes. Overview and evaluation of premise selection techniques for large theory mathematics. In Bernhard Gramlich, Dale Miller, and Uli Sattler, editors, Automated Reasoning - 6th International Joint Conference, IJCAR 2012, Manchester, UK, June 26-29, 2012. Proceedings, volume 7364 of Lecture Notes in Computer Science, pages 378–392. Springer, 2012. doi: 10.1007/978-3-642-31365-3\_30. URL https://doi.org/10.1007/978-3-642-31365-3_30. Wenda Li, Lei Yu, Yuhuai Wu, and Lawrence C. Paulson. Isarstep: a benchmark for high-level mathematical reasoning. 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=Pzj6fzU6wkj. Jia Meng and Lawrence C. Paulson. Translating higher-order clauses to first-order clauses. J. Autom. Reason., 40(1):35–60, 2008. doi: 10.1007/s10817-007-9085-y. URL https://doi.org/10. 1007/s10817-007-9085-y. Olga Ohrimenko, Peter J Stuckey, and Michael Codish. Propagation via lazy clause generation. Constraints, 14(3):357–391, 2009. Lawrence C. Paulson. Three years of experience with sledgehammer, a practical link between automatic and interactive theorem provers. In Renate A. Schmidt, Stephan Schulz, and Boris Konev, editors, Proceedings of the 2nd Workshop on Practical Aspects of Automated Reasoning, PAAR-2010, Edinburgh, Scotland, UK, July 14, 2010, volume 9 of EPiC Series in Computing, pages 1–10. EasyChair, 2010. doi: 10.29007/tnfd. URL https://doi.org/10.29007/tnfd. Stanislas Polu and Ilya Sutskever. Generative language modeling for automated theorem proving. CoRR, abs/2009.03393, 2020. URL https://arxiv.org/abs/2009.03393. Stanislas Polu, Jesse Michael Han, Kunhao Zheng, Mantas Baksys, Igor Babuschkin, and Ilya Sutskever. Formal mathematics statement curriculum learning. CoRR, abs/2202.01344, 2022. URL https://arxiv.org/abs/2202.01344. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, et al. Language models are unsupervised multitask learners. OpenAI blog, 1(8):9, 2019. Peter Scholze. Liquid tensor experiment. Experimental Mathematics, 0(0):1–6, 2021. doi: 10.1080/ 10586458.2021.1926016. URL https://doi.org/10.1080/10586458.2021.1926016. David Silver, Thomas Hubert, Julian Schrittwieser, Ioannis Antonoglou, Matthew Lai, Arthur Guez, Marc Lanctot, Laurent Sifre, Dharshan Kumaran, Thore Graepel, Timothy P. Lillicrap, Karen Simonyan, and Demis Hassabis. Mastering chess and shogi by self-play with a general reinforcement learning algorithm. CoRR, abs/1712.01815, 2017. URL http://arxiv.org/abs/ 1712.01815. Yiannos Stathopoulos, Angeliki Koutsoukou-Argyraki, and LC Paulson. Serapis: A concept-oriented search engine for the isabelle libraries based on natural language. In Online proceedings of the Isabelle Workshop, 2020. 11 Jianlin Su, Yu Lu, Shengfeng Pan, Bo Wen, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding, 2021. URL https://arxiv.org/abs/2104.09864. Geoff Sutcliffe and Yury Puzis. SRASS - A semantic relevance axiom selection system. In Frank Pfenning, editor, Automated Deduction - CADE-21, 21st International Conference on Automated Deduction, Bremen, Germany, July 17-20, 2007, Proceedings, volume 4603 of Lecture Notes in Computer Science, pages 295–310. Springer, 2007. doi: 10.1007/978-3-540-73595-3\_20. URL https://doi.org/10.1007/978-3-540-73595-3_20. Geoff Sutcliffe, Josef Urban, and Stephan Schulz, editors. Proceedings of the CADE-21 Workshop on Empirically Successful Automated Reasoning in Large Theories, Bremen, Germany, 17th July 2007, volume 257 of CEUR Workshop Proceedings, 2007. CEUR-WS.org. URL http: //ceur-ws.org/Vol-257. Alfred Tarski. Truth and proof. Scientific American, 220(6):63–77, 1969. Josef Urban. Malarea: a metasystem for automated reasoning in large theories. In ESARLT, 2007. Josef Urban, Geoff Sutcliffe, Petr Pudlák, and Jirí Vyskocil. Malarea SG1- machine learner for automated reasoning with semantic guidance. In Alessandro Armando, Peter Baumgartner, and Gilles Dowek, editors, Automated Reasoning, 4th International Joint Conference, IJCAR 2008, Sydney, Australia, August 12-15, 2008, Proceedings, volume 5195 of Lecture Notes in Computer Science, pages 441–456. Springer, 2008. doi: 10.1007/978-3-540-71070-7\_37. URL https: //doi.org/10.1007/978-3-540-71070-7_37. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. Attention is all you need, 2017. URL https://arxiv.org/abs/ 1706.03762. Ben Wang and Aran Komatsuzaki. GPT-J-6B: A 6 Billion Parameter Autoregressive Language Model. https://github.com/kingoflolz/mesh-transformer-jax, May 2021. Mingzhe Wang, Yihe Tang, Jian Wang, and Jia Deng. Premise selection for theorem proving by deep graph embedding. Advances in neural information processing systems, 30, 2017. Kunhao Zheng, Jesse Michael Han, and Stanislas Polu. minif2f: a cross-system benchmark for formal olympiad-level mathematics. In International Conference on Learning Representations, 2022. URL https://openreview.net/forum?id=9ZPegFuFTFv. 12 # A Appendix In this section, we present some lemmas solved by Thor only. Case 1. The lemma cols_upt_k _insert is from the QR Decomposition entry5 in the AFP. lemma cols_upt_k_insert: fixes A::"’a^’n::{mod_type}^’m::{mod_type}" assumes k: "(Suc k)<ncols A" shows "cols_upt_k A (Suc k) = (insert (column (from_nat (Suc k)) A) (cols_upt_k A k))" unfolding cols_upt_k_def apply (auto) apply (metis Suc_lessD from_nat_mono’ from_nat_to_nat_id k less_Suc_eq_le less_le ncols_def to_nat_le) by (metis from_nat_mono’ k less_imp_triv less_or_eq_imp_le ncols_def not_less_eq order_trans) Here, cols_upt_k A (Suc k) returns the set of columns in the matrix A up to the natural number k+1, while ncols A counts the number of columns in the matrix A. In short, this lemma claims that the set of columns (in a matrix A) up to column index k + 1 is equivalent to that of the same matrix up to column index k inserted with the (k + 1)th column (of A). This will subject to the condition that k + 1 is less than the number of columns in A. With Thor, the LM decided to unfold the goal with the definition of cols_upt_k, which is followed by an auto tactic to simplify the proof state. All remaining subgoals are then discharged by Sledgehammer. Case 2. The lemma size_del_max is from theWeight-Balanced Trees entry6 in the AFP. lemma size_del_max: "t # Leaf => size t = Suc(size(snd(del_max t)))" apply (induction t rule: del_max. induct) apply simp apply (clarsimp split: prod.splits) apply (smt (z3) size_rotateR size_wbt.simps(1)) by simp In this lemma, t is a weight-balanced tree, and the size function measures its size (as the name suggests) and del_max deletes the maximum node from it. Essentially, this lemma claims that when a weight-balanced its size will be reduced by one if we remove the largest node from it. For the proof, Thor intelligently performs structural induction with the induction rule del_max.induct and then simplifies the proof state a few times, which includes splitting products with the rule prod.splits. Finally, Thor concludes the remaining goals with Sledgehammer. Case 3. The lemma t_list_of_B_log_bound is from the AFP entry named as Priority Queues Based on Braun Trees.7 lemma t_list_of_B_log_bound: "braun t =⇒ t_list_of_B t ≤ 3 * (nlog2 (size t + 1) + 1) * size t" apply (induction t rule: measure_induct_rule[where f=size]) apply (case_tac x) apply simp using braun.simps(1) t_list_of_B_braun_simps(1) apply blast by (metis acomplete_if_braun height_acomplete order_refl size1_size t_list_of_B_induct) Here, size measures the size of a Braun tree; nlog2 stands for the function Az. [log,(x) |; t_list_of_B is another measure of a Braun tree. Basically, this lemma describes the relation- ship between a normal tree size and a Braun-tree specific measure. The proof starts with an intelligent structural induction, progresses with case analysis, and is concluded with Sledgehammer on each of the remaining subgoals. # 5QR_Decomposition/Gram_Schmidt.thy 6Weight_Balanced_Trees/Weight_Balanced_Trees.thy 7Priority_Queue_Braun/Sorting_Braun.thy 13 Case 4. The lemma inj_imp_Ker0 is from the AFP entry named as Matrices, Jordan Normal Forms, and Spectral Radius Theory.8 assumes "inj_on T (carrier V)" shows "carrier (V.vs kerT) = {0V}" apply (rule equalityI) apply (rule subsetI) apply (unfold ker_def, auto) by (metis V.module.M.zero_closed assms f0_is_0 inj_on_contraD) Here, T is a linear map between two vector spaces. The lemma claims that if the T is injective on the carrier set of the space V, the kernel of T has to be a singleton set with the zero in V. In this proof, Thor naturally performs a sequence of introduction steps by applying the lemma equalityI and subsetI, before unfolds the definition of a kernel (i.e., ker_def ) and uses auto to simplify the proof state. The final remaining goal is closed with Sledgehammer. 8Jordan_Normal_Form/Missing_VectorSpace.thy 14
Title: Identifying and Reducing Gender Bias in Word-Level Language Models: Summary: Many text corpora exhibit socially problematic biases, which can be propagated or amplified in the models trained on such data. For example, doctor cooccurs more frequently with male pronouns than female pronouns. In this study we (i) propose a metric to measure gender bias; (ii) measure bias in a text corpus and the text generated from a recurrent neural network language model trained on the text corpus; (iii) propose a regularization loss term for the language model that minimizes the projection of encoder-trained embeddings onto an embedding subspace that encodes gender; (iv) finally, evaluate efficacy of our proposed method on reducing gender bias. We find this regularization method to be effective in reducing gender bias up to an optimal weight assigned to the loss term, beyond which the model becomes unstable as the perplexity increases. We replicate this study on three training corpora---Penn Treebank, WikiText-2, and CNN/Daily Mail---resulting in similar conclusions. # Identifying and Reducing Gender Bias in Word-Level Language Models # Shikha Bordia1 sb6416@nyu.edu # Samuel R. Bowman1,2,3 bowman@nyu.edu 1Dept. of Computer Science New York University 251 Mercer St New York, NY 10012 2Center for Data Science New York University 60 Fifth Avenue New York, NY 10011 3Dept. of Linguistics New York University 10 Washington Place New York, NY 10003 # Abstract Many text corpora exhibit socially problematic biases, which can be propagated or amplified in the models trained on such data. For ex- ample, doctor cooccurs more frequently with male pronouns than female pronouns. In this study we (i) propose a metric to measure gen- der bias; (ii) measure bias in a text corpus and the text generated from a recurrent neural net- work language model trained on the text cor- pus; (iii) propose a regularization loss term for the language model that minimizes the pro- jection of encoder-trained embeddings onto an embedding subspace that encodes gender; (iv) finally, evaluate efficacy of our proposed method on reducing gender bias. We find this regularization method to be effective in re- ducing gender bias up to an optimal weight assigned to the loss term, beyond which the model becomes unstable as the perplexity in- creases. We replicate this study on three train- ing corpora—Penn Treebank, WikiText-2, and CNN/Daily Mail—resulting in similar conclu- sions. # Introduction Models automating resume screening have also proved to have a heavy gender bias favoring male candidates (Lambrecht and Tucker, 2018). Such data and algorithmic biases have become a grow- ing concern. Evaluation and mitigation of biases in data and models that use the data has been a growing field of research in recent years. One natural language understanding task vul- nerable to gender bias is language modeling. The task of language modeling has a number of prac- tical applications, such as word prediction used in If possible, we would like onscreen keyboards. to identify the bias in the data used to train these models and reduce its effect on model behavior. Towards this pursuit, we aim to evaluate the ef- fect of gender bias on word-level language models that are trained on a text corpus. Our contributions in this work include: (i) an analysis of the gen- der bias exhibited by publicly available datasets used in building state-of-the-art language models; (ii) an analysis of the effect of this bias on re- current neural networks (RNNs) based word-level language models; (iii) a method for reducing bias learned in these models; and (iv) an analysis of the results of our method. Dealing with discriminatory bias in training data is a major issue concerning the mainstream im- plementation of machine learning. Existing bi- ases in data can be amplified by models and the resulting output consumed by the public can in- fluence them, encourage and reinforce harmful stereotypes, or distort the truth. Automated sys- tems that depend on these models can take prob- lematic actions based on biased profiling of indi- viduals. The National Institute for Standards and Technology (NIST) evaluated several facial recog- nition algorithms and found that they are systemat- ically biased based on gender (Ngan and Grother, 2015). Algorithms performed worse on faces la- beled as female than those labeled as male. # 2 Related Work A number of methods have been proposed for in evaluating and addressing biases that exist datasets and the models that use them. Recasens et al. (2013) studies the neutral point of view (NPOV) edit tags in the Wikipedia edit histories to understand linguistic realization of bias. Ac- cording to their study, bias can be broadly cat- egorized into two classes: framing and episte- mological. While the framing bias is more ex- the epistemological bias is implicit and plicit, subtle. Framing bias occurs when subjective or one-sided words are used. For example, in the ‘Training Corpus Cross Entropy Loss + M(N.B) pPOW aBenBue] [20971 prog Bias in Training Corpus Generated Text Bias in Generated Text Generated Text with Regularization Bias after Regularization Figure 1: Word level language model is a three layer LSTM model. λ controls the importance of minimizing bias in the embedding matrix. sentence—“Usually, smaller cottage-style houses have been demolished to make way for these Mc- the word McMansions has a neg- Mansions.”, ative connotation towards large and pretentious houses. Epistemological biases are entailed, as- serted or hedged in the text. For example, in the sentence—“Kuypers claimed that the main- stream press in America tends to favor liberal viewpoints,” the word claimed has a doubtful ef- fect on Kuypers statement as opposed to stated in the sentence—“Kuypers stated that the main- stream press in America tends to favor liberal viewpoints.” It may be possible to capture both of these kinds of biases through the distributions of co-occurrences. In this paper, we deal with iden- tifying and reducing gender bias based on words co-occurring in a context window. Bolukbasi et al. (2016) propose an approach to investigate gender bias present in popular word embeddings, such as word2vec (Mikolov et al., 2013). They construct a gender subspace using a set of binary gender pairs. For words that are not explicitly gendered, the component of the word embeddings that project onto this subspace can be removed to debias the embeddings in the gender direction. They also propose a softer variation that balances reconstruction of the original em- beddings while minimizing the part of the embed- dings that project onto the gender subspace. We use the softer variation to debias the embeddings while training our language model. serve gender bias in the training examples and that their model amplifies the bias in its predictions. They impose constraints on the optimization to re- duce bias amplification while incurring minimal degradation in their model’s performance. Word embeddings can capture the stereotypi- cal bias in human generated text leading to biases in NLP Applications. Caliskan et al. (2017) con- duct Word Embedding Association Test (WEAT). It is based on the hypothesis that word embeddings closer together in high dimensional space are se- mantically closer. They find strong evidence of social biases in pretrained word embeddings. Rudinger et al. (2018) introduce Winogender schemas1 and evaluate three coreference resolu- tion systems—rule-based, statistical and neural systems. They find that these systems’ predictions strongly prefer one gender over the other for occu- pations. Font and Costa-Juss`a (2019) study the impact of gender debiasing techniques by Bolukbasi et al. (2016) and Zhao et al. (2018) in machine trans- lation. They find these methods to be effective, and even a noted BLEU score improvement for the debiased model. Our work is closely related but while they use debiased pretrained embeddings, we train the word embeddings from scratch and debias them while the language model is trained. May et al. (2019) extend WEAT to state-of- the-art sentence encoders: the Sentence Encoder Association Test (SEAT). They show that these tests can provide an evidence for presence of bias. Zhao et al. (2017) look at gender bias in the con- text of using structured prediction for visual object classification and semantic role labeling. They ob- 1It is Winograd Schema-style coreference dataset consist- ing of pair of sentences that differ only by a gender pronoun However, the cosine similarity between sentences can be an inadequate measure of text similarity in sentences. In this paper, we attempt to mini- mize the cosine similarity between word embed- dings and gender direction. Gonen and Goldberg (2019) conduct experi- ments using the debiasing techniques proposed by Bolukbasi et al. (2016) and Zhao et al. (2018). They show that bias removal techniques based on gender direction are inefficient in removing all as- pects of bias. In a high dimensional space, spa- tial distribution of the gender neutral word embed- dings remain almost same after debiasing. This enables a gender-neutral classifier to still pick up the cues that encode other semantic aspects of bias. We use softer variation of the debiasing method proposed by Bolukbasi et al. (2016) and attempt to measure the debiasing effect from the minimal changes in the embedding space. # 3 Methods We first examine the bias existing in the datasets through qualitative and quantitative analysis of trained embeddings and cooccurrence patterns. We then train an LSTM word-level language model on a dataset and measure the bias of the generated outputs. As shown in Figure 1, we then apply a regularization procedure that encourages the embeddings learned by the model to depend minimally on gender. We debias the input and the output embeddings individually as well as simul- taneously. Finally, we assess the efficacy of the proposed method in reducing bias. We observe that when both input and output em- beddings are debiased together, the perplexity of the model shoots up by a much larger number than the input or the output embeddings debiased indi- vidually. We report our results when only input embeddings are debiased. This method, however, does not limit the model to capture other forms of bias being learned in other model parameters or output embeddings. The code implementing our methods can be found in our GitHub repository.2 # 3.1 Datasets and Text Preprocessing We compare the model on three datasets–Penn Treebank (PTB), WikiText-2 and CNN/Daily Mail. The first two have been used in language modeling for a long time. We include CNN/Daily 2https://github.com/BordiaS/language-model-bias Mail dataset in our experiments as it contains a more diverse range of topics. PTB Penn Treebank comprises of articles rang- ing from scientific abstracts, computer manuals, In our experiments, we etc. observe that PTB has a higher count of male words than female words. Following prior lan- guage modeling work, we use the Penn Treebank dataset (PTB; Marcus et al., 1993) preprocessed by Mikolov et al. (2010). WikiText-2 WikiText-2 is twice the size of the PTB and is sourced from curated Wikipedia ar- ticles. It is more diverse and therefore has a more balanced ratio of female to male gender words than PTB. We use preprocessed WikiText-2 (Wikitext-2; Merity et al., 2016). CNN/Daily Mail This dataset is curated from a diverse range of news articles on topics like sports, health, business, lifestyle, travel etc. This dataset has an even more balanced ratio of female to male gender words and thus, relatively less biased than the above two. However, this does not mean that the use of pronouns is not biased. This dataset was released as part of a summarization dataset by Hermann et al. (2015), and contains 219,506 arti- cles from the newspaper the Daily Mail. We sub- sample the sentences by a factor of 100 in order to make the dataset more manageable for experi- ments. # 3.2 Word-Level Language Model We use a three-layer LSTM word-level language model (AWD-LSTM; Merity et al., 2018) with 1150 hidden units implemented in PyTorch.3 These models have an embedding size of 400 and a learning rate of 30. We use a batch size of 80 for Wikitext-2 and 40 for PTB. Both are trained for 750 epochs. The PTB baseline model achieves a perplexity of 62.56. For WikiText-2, the baseline model achieves a perplexity of 67.67. For CNN/Daily Mail, we use a batch size of 80 and train it for 500 epochs. We do early stopping for this model. The hyperparameters are chosen through a systematic trial and error approach. The baseline model achieves a perplexity of 118.01. All three baseline models achieve reasonable perplexities indicating them to be good proxies for standard language models. 3https://github.com/salesforce/awd-lstm-lm λ Fixed Context µ σ β Infinite Context σ µ β P pl. train 0.0 0.001 0.01 0.1 0.5 0.8 1.0 0.83 0.74 0.69 0.63 0.64 0.70 0.76 0.84 1.00 0.91 0.88 0.81 0.82 0.91 0.96 0.94 0.40 0.34 0.31 0.33 0.39 0.45 0.38 3.81 2.23 2.43 2.56 2.30 2.91 3.43 2.42 4.65 2.90 2.98 3.40 3.09 3.76 4.06 3.02 0.38 0.35 0.36 0.24 0.38 0.26 -0.30 62.56 62.69 62.83 62.48 62.5 63.36 62.63 Table 1: Experimental results for Penn Treebank and generated text for different λ values λ Fixed Context µ σ β Infinite Context σ µ β P pl. train 0.0 0.001 0.01 0.1 0.5 0.8 1.0 0.80 0.70 0.69 0.61 0.65 0.70 0.65 0.74 1.00 0.84 0.84 0.79 0.82 0.88 0.84 0.92 0.29 0.27 0.20 0.24 0.31 0.28 0.27 3.70 3.48 2.32 1.88 2.26 2.25 2.07 2.32 4.60 4.29 3.12 2.69 3.11 3.17 2.98 3.21 0.15 0.16 0.14 0.06 0.20 0.18 -0.08 67.67 67.84 67.78 67.89 69.07 69.36 69.56 Table 2: Experimental results for WikiText-2 and generated text for different λ values λ Fixed Context µ σ β Infinite Context µ σ β P pl. train 0.0 0.1 0.5 0.8 1.0 0.72 0.51 0.38 0.34 0.40 0.62 0.94 0.68 0.52 0.48 0.56 0.83 0.22 0.19 0.14 0.19 0.21 0.77 0.43 0.85 0.79 0.96 1.71 1.05 0.59 1.38 1.31 1.57 2.65 0.29 0.22 0.20 0.23 0.31 118.01 116.49 116.19 121.00 120.55 Table 3: Experimental results for CNN/Daily Mail and generated text for different λ values # 3.3 Quantifying Biases For numeric data, bias can be caused simply by class imbalance, which is relatively easy to quan- tify and fix. For text and image data, the com- plexity in the nature of the data increases and it becomes difficult to quantify. Nonetheless, defin- ing relevant metrics is crucial in assessing the bias exhibited in a dataset or in a model’s behavior. # 3.3.1 Bias Score Definition In a text corpus, we can express the probability of a word occurring in context with gendered words as follows: P (w|g) = c(w, g)/Σic(wi, g) c(g)/Σic(wi) etc. w is any word in the corpus, excluding stop words and gendered words. The bias score of a specific word w is then defined as: Peal) biastrain(w) = log Gao This bias score is measured for each word in the text sampled from the training corpus and the text corpus generated by the language model. A posi- tive bias score implies that a word cooccurs more often with female words than male words. For an infinite context, the words doctor and nurse would cooccur as many times with a female gender as with male gender words and the bias scores for these words will be equal to zero. where c(w, g) is a context window and g is a set of gendered words that belongs to either of the two categories: male or female. For example, when g = f , such words would include she, her, woman We conduct two sets of experiments where we define context window c(w, g) as follows: Fixed Context In this scenario, we take a fixed context window size and measure the bias scores. We generated bias scores for several context win- dow sizes in the range (5, 15). For a context size k, there are k words before and k words after the tar- get word w for which the bias score is being mea- sured. Qualitatively, a smaller context window size has more focused information about the tar- get word. On the other hand, a larger window size captures topicality (Levy and Goldberg, 2014). By choosing an optimal window of k = 10, we give equal weight of 5% to the ten words before and the ten words after the target word. Infinite Context In this scenario, we take an in- finite window of context with weights diminish- ing exponentially based on the distance between the target word w and the gendered word g. This method emphasizes on the fact that the nearest word has more information about the target word. The farther the context gets away from a word, the less information it has about the word. We give 5% weight to the words adjacent to the target word as in Fixed Context but reduce the weights of the words following by 5% and 95% to the rest; this applied recursively gives a base of 0.95. This method of exponential weighting instead of equal weighting adds to the stability of the measure. # 3.3.2 Bias Reduction Measures To evaluate debiasing of each model, we measure the bias for the generated corpus. biasλ(w) = log( P (w|f ) P (w|m) ) To estimate the amplification or reduction of the bias, we fit a univariate linear regression model over bias scores of context words w as follows: biasλ(w) = β ∗ biastrain(w) + c where β is the scaled amplification measure rela- tive to the training data. Reducing β implies debi- asing the model. We also look at the distribution of the bias by evaluating mean absolute bias and deviation in bias scores for each context word in each of the generated corpora. µλ = mean(abs(biasλ)); σλ = stdev(biasλ) We take the mean of absolute bias score as the word can be biased in either of the two directions. # 3.4 Model Debiasing Machine learning techniques that capture patterns in data to make coherent predictions can uninten- tionally capture or even amplify the bias in data (Zhao et al., 2017). We consider a gender sub- space present in the learned embedding matrix in our model as introduced in the Bolukbasi et al. (2016) paper. We train these embeddings on the word level language model instead of using the debiased pretrained embeddings (Font and Costa- Juss`a, 2019). We conduct experiments for the three cases where we debias—input embeddings, output embeddings, and both the embeddings si- multaneously. Let w ∈ SW be a word embedding correspond- ing to a word in the word embedding matrix W . Let Di, . . . , Dn ⊂ SW be the defining sets4 that contain gender-opposing words, e.g. man and woman. The defining sets are designed separately for each corpus since cer- tain words may not appear in another corpus. We consider it a defining set if both gender-opposing words occur in the training corpus. If ui, vi are the embeddings corresponding to the words man and woman, then {ui, vi} = Di. We consider the matrix C which is defined as a stack of difference vectors between the pairs in the defining sets. We have: C = ( u1−v1 2 ... ( un−vn 2 ) = U ΣV ) The difference between the pairs encodes the gender information corresponding to the gender pair. We then perform singular value decomposi- tion on C, obtaining U ΣV . The gender subspace B is then defined as the first k columns (where k is chosen to capture 50% of the variation) of the right singular matrix V : B = V1:k Let N be the matrix consisting of the embed- dings for which we would like the corresponding words to exhibit unbiased behavior. If we want the embeddings in N to have minimal bias, then its projection onto the gender subspace B should be small in terms its the squared Frobenius norm. 4See the supplement for corpus-wise defining sets Target Word λ Sample From Generated Text crying 0.0 0.5 1.0 “she was put on her own machine to raise money for her own wedding <unk> route which saw her crying and <unk> down a programme today . effects began by bottom of her marrow the <unk>” “he <unk> in the americas with the <unk> which can spread a <unk> circumcision ceremony made last month . as he <unk> his mother s <unk> crying to those that” “he discovered peaceful facebook remains when he was caught crying officers but was arrested after they found the crash hire a man <unk> brown shocked his brother <unk> over” fragile 0.0 0.5 1.0 “camilla said she talked to anyone and had previously left her love of two young children . it all comes with her family in conviction of her son s death . it s been fragile . the <unk> and retail boy that was rik s same maker identified genuinely <unk> attacked all” “his children at nearby children s hospital in <unk> and went <unk> years after he was arrested on <unk> bail . she spent relaxed weeks in prison after being sharply in fragile <unk> while she was jailed and strangled when she was born in <unk> virginia” “could they possibly have a big barrier to jeff <unk> and <unk> my son all intelligence period that will contain the east country s world from all in the world the truth is when we moved clear before the split twenty days earlier that day . none of the distributed packs on the website can never <unk> re able to <unk> it the second time so that fitting fragile <unk> are and less the country is <unk> . it came as it was once <unk> million lead jobs mail yorkshire . adoption of these first product is ohio but it is currently almost impossible for the moon to address and fully offshore hotly ” leadership 0.0 0.5 1.0 “mr <unk> worked traditions at the squadron base in <unk> rbs to marry the us government .he referring to the mainland them in february <unk> he kept communist leadership from undergoing” “obama s first wife janet had a chance to run the opposition for a superbowl event for charity the majority of the south african people s travel stage <unk> leadership while it was married off christ- mas” “the woman s lungs and drinking the ryder of his daughters s leadership morris said businesses . however being of his mouth around wiltshire and burn talks from the hickey s <unk> employees” prisoner 0.0 0.5 1.0 “his legs and allegedly killed himself by suspicious points . in the latest case after an online page he left prisoner in his home in <unk> near <unk> manhattan on saturday when he was struck in his car operating in <unk> bay smoking <unk> and <unk> <unk> when he had” “it is something that the medicines can target prisoner and destroy <unk> firms in the uk but i hope that there are something into the on top getting older people who have more branded them as poor .” “the ankle follows a worker <unk> her <unk> prisoner she died this year before now an profile which clear her eye borrowed for her organ own role . it was a huge accident after the drugs she had” Table 4: Generated text comparison for CNN/Daily Mail for different λ values Therefore, to reduce the bias learned by the em- bedding layer in the model, we can add the follow- ing bias regularization term to the training loss: # 4 Experiments # 4.1 Model Le = X\|NB\|z After achieving the baseline results, we run exper- iments to tune λ as hyperparameter. We report an in-depth analysis of bias measure on the models with debiased input embeddings. # 4.2 Results and Text Examples where λ controls the importance of minimizing bias in the embedding matrix W (from which N and B are derived) relative to the other compo- nents of the model loss. The matrices N and C are updated each iteration during the model train- ing. We input 2000 random seeds in the language model as starting points to start word generation. We use the previous words as an input to the lan- guage model and perform multinomial selection to generate up the next word. We repeat this up to 500 times. In total, we generate 106 tokens for all three datasets for each λ and measure the bias. We calculate the measures stated in Section 3.3 for the three datasets and the generated corpora using the corresponding RNN models. The results are shown in Tables 1, 2 and 3. We see that the µ con- sistently decline as we increase λ until a point, be- yond which the model becomes unstable. So there is a scope of optimizing the λ values. The detailed analysis is presented in Section 4.3 Table 4 shows excerpts around selected target words from the generated corpora to demonstrate the effect of debiasing for different values of λ. We highlight the words crying and fragile that are typically associated with feminine qualities, along with the words leadership and prisoners that are stereotyped with male identity. These biases are reflected in the generated text for λ = 0. We no- tice increased mention of the less probable gen- der in the subsequent generated text with debias- ing (λ = 0.5, 1.0). For fragile, the generated text at λ = 1.0 has reduced the mention of stereotyped female words but had no mentions of male words; resulting in a large chunk of neutral text. Simi- larly, in prisoners, the generated text for λ = 0.5 has no gender words. However, these are small snippets and the bias scores presented in the supplementary table quan- tifies the distribution of gender words around the target word in the entire corpus. These target words are chosen as they are commonly perceived gender biases and in our study, they show promi- nent debiasing effect.5 # 4.3 Analysis and Discussion We consider a text corpus to be biased when it has a skewed distribution of words cooccuring with one gender vs another. Any dataset that has such demographic bias can lead to (potentially unin- tended) social exclusion (Hovy, 2015). PTB and WikiText-2 consist of news articles related to busi- ness, science, politics, and sports. These are all male dominated fields. However, CNN/Daily Mail consists of articles across diverse set of categories like entertainment, health, travel etc. Among the three corpora, Penn Treebank has more frequent mentions of male words with respect to female words and CNN/Daily Mail has the least. As defined, bias score of zero implies perfectly neutral word, any value higher/lower implies fe- male/male bias. Therefore, the absolute value of bias score signifies presence of bias. Overall bias in a dataset can be estimated as the average of ab- solute bias score (µ). The aggregated absolute bias scores µ of the three datasets—Penn Treebank, WikiText-2, and CNN/Daily Mail—are 0.83, 0.80, and 0.72 respectively. Higher µ value in this mea- sure means on-an-average the words in the entire corpus are more gender biased. As per the Tables 1, 2, and 3, we see that the µ consistently decline as we increase λ until a point, beyond which the model becomes unstable. So there is a scope of optimizing the λ values. The second measure we evaluated is the stan- dard deviation (σ) of the bias score distribution. 5For more examples, refer to the supplement Less biased dataset should have the bias score con- centrating closer to zero and hence lower σ value. We consistently see that, with the initial increase of λ, there is a decrease in σ of the bias score dis- tribution. The final measure to evaluate debiasing is com- parison of bias scores at individual word level. We regress the bias scores of the words in generated text against their bias scores in the training corpus after removing the outliers. The slope of regres- sion β signifies the amplification or dampening ef- fect of the model relative to the training corpus. Unlike the previous measures, this measure gives clarity at word level bias changes. A drop in β sig- nifies reduction in bias and vice versa. A negative β signifies inversion in bias assuming there are no other effects of the loss term. In our experiments, we observe β to increase with higher values of λ possibly due to instability in model and none of those values go beyond 1. We observe that corpus level bias scores like µ, σ are less effective measures to study efficacy of debiasing techniques because they fail to track the improvements at word level. Instead, we recom- mend a word level score comparison like β to eval- uate robustness of debiasing at corpus level. To choose the context window in a more ro- bust manner, we take exponential weightings to the cooccurrences. The results for aggregated av- erage of absolute bias and standard deviation show the same pattern as in fixed context window. As shown in the results above, we see that the standard deviation (σ), absolute mean (µ) and slope of regression (β) reduce for smaller λ rel- ative to those in training data and then increase with λ to match the variance in the original cor- pus. This holds for the experiments conducted with fixed context window as well as with expo- nential weightings. # 5 Conclusion In this paper, we quantify and reduce gender bias in word level language models by defining a gen- der subspace and penalizing the projection of the word embeddings onto that gender subspace. We device a metric to measure gender bias in the train- ing and the generated corpus. In this study, we quantify corpus level bias in two different metrics—absolute mean (µ) and standard deviation (σ). However, for evaluating debiasing effects, we propose a relative metric (β) to study the change in bias scores at word level in training corpus. To calculate generated text vs. β, we conduct an in-depth regression analysis of the word level bias measures in the generated text corpus over the same for the training corpus. Although we found mixed results on amplifica- tion of bias as stated by Zhao et al. (2017), the de- biasing method shown by Bolukbasi et al. (2016) was validated with the use of novel and robust bias measure designed in this paper. Our proposed methodology can deal with distribution of words in a vocabulary in word level language model and it targets one way to measure bias, but it’s highly likely that there is significant bias in the debiased models and data, just not bias that we can detect on this measure. It can be concluded different bias metrics show different kinds of bias (Gonen and Goldberg, 2019). We additionally observe a perplexity bias trade- off as a result of the additional bias regularization term. In order to reduce bias, there is a compro- mise on perplexity. Intuitively, as we reduce bias the perplexity is bound to increase due to the fact that, in an unbiased model, male and female words will be predicted with an equal probability. # 6 Acknowledgements We are grateful to Yu Wang and Jason Cramer for helping to initiate this project, to Nishant Subra- mani for helpful discussion, and to our reviewers for their thoughtful feedback. Bowman acknowl- edges support from Samsung Research. # References Tolga Bolukbasi, Kai-Wei Chang, James Y Zou, Venkatesh Saligrama, and Adam T Kalai. 2016. Man is to computer programmer as woman is to homemaker? Debiasing word embeddings. In D. D. Lee, M. Sugiyama, U. V. Luxburg, I. Guyon, and R. Garnett, editors, Advances in Neural Information Processing Systems 29, pages 4349–4357. Curran Associates, Inc. and Arvind Joanna J. Bryson, Narayanan. 2017. Semantics derived automatically from language corpora contain human-like biases. Science, 356(6334):183–186. Joel Escud´e Font and Marta R. Costa-Juss`a. 2019. Equalizing gender biases in neural machine trans- lation with word embeddings techniques. CoRR, abs/1901.03116. Hila Gonen and Yoav Goldberg. 2019. Lipstick on a pig: Debiasing methods cover up systematic gender biases in word embeddings but do not remove them. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computa- tional Linguistics: Human Language Technologies. Association for Computational Linguistics. Karl Moritz Hermann, Tomas Kocisky, Edward Grefenstette, Lasse Espeholt, Will Kay, Mustafa Su- leyman, and Phil Blunsom. 2015. Teaching ma- chines to read and comprehend. In C. Cortes, N. D. Lawrence, D. D. Lee, M. Sugiyama, and R. Garnett, editors, Advances in Neural Information Processing Systems 28, pages 1693–1701. Curran Associates, Inc. Dirk Hovy. 2015. Demographic factors improve clas- sification performance. In Proceedings of the 53rd Annual Meeting of the Association for Computa- tional Linguistics and the 7th International Joint Conference on Natural Language Processing (Vol- ume 1: Long Papers), volume 1, pages 752–762. Anja Lambrecht and Catherine E Tucker. 2018. Al- gorithmic bias? an empirical study into appar- ent gender-based discrimination in the display of stem career ads. Social Science Research Network (SSRN). Omer Levy and Yoav Goldberg. 2014. Dependency- based word embeddings. In Proceedings of the 52nd Annual Meeting of the Association for Computa- tional Linguistics (Volume 2: Short Papers), vol- ume 2, pages 302–308. Mitchell P. Marcus, Beatrice Santorini, and Mary Ann Marcinkiewicz. 1993. Building a large annotated corpus of english: The penn treebank. Computa- tional Linguistics, 19(2):313–330. Chandler May, Alex Wang, Shikha Bordia, Samuel R. Bowman, and Rachel Rudinger. 2019. On measur- In Proceed- ing social bias in sentence encoders. ings of the 2019 Conference of the North American Chapter of the Association for Computational Lin- guistics: Human Language Technologies. Associa- tion for Computational Linguistics. Stephen Merity, Nitish Shirish Keskar, and Richard Socher. 2018. Regularizing and optimizing LSTM In International Conference on language models. Learning Representations. Stephen Merity, Caiming Xiong, James Bradbury, and Pointer sentinel mixture Richard Socher. 2016. models. arXiv preprint arXiv:1609.07843. Tomas Mikolov, Martin Karafi´at, Luk´as Burget, Jan Cernock´y, and Sanjeev Khudanpur. 2010. Recur- rent neural network based language model. In IN- TERSPEECH, pages 1045–1048. ISCA. Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg S Cor- rado, and Jeff Dean. 2013. Distributed representa- tions of words and phrases and their compositional- In Advances in neural information processing ity. systems, pages 3111–3119. Mei Ngan and Patrick Grother. 2015. Face recogni- tion vendor test (FRVT) performance of automated gender classification algorithms. US Department of Commerce, National Institute of Standards and Technology. Marta Recasens, Cristian Danescu-Niculescu-Mizil, and Dan Jurafsky. 2013. Linguistic models for an- alyzing and detecting biased language. In Proceed- ings of the 51st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Pa- pers), volume 1, pages 1650–1659. Rachel Rudinger, Jason Naradowsky, Brian Leonard, and Benjamin Van Durme. 2018. Gender bias in coreference resolution. In Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, New Orleans, Louisiana. Association for Computational Linguistics. Jieyu Zhao, Tianlu Wang, Mark Yatskar, Vicente Or- donez, and Kai-Wei Chang. 2017. Men also like shopping: Reducing gender bias amplification using In EMNLP, pages 2979– corpus-level constraints. 2989. Association for Computational Linguistics. Jieyu Zhao, Yichao Zhou, Zeyu Li, Wei Wang, and Kai- Wei Chang. 2018. Learning gender-neutral word In Proceedings of the 2018 Confer- embeddings. ence on Empirical Methods in Natural Language Processing, pages 4847–4853. Association for Com- putational Linguistics. # A Defining sets The gender pair list for each corpus is designed separately. We consider only those gender pairs that occur in the training corpus. Below are the gender lists corresponding to each corpus: # A.1 Penn Treebank Male Words: “actor” “boy” “father” “he” “him ” “his” “male” “man” “men” “son” “sons” “spokesman” “wife” “king” “brother” Female Words: “actress” “girl ” “mother” “she” “her ” “her” “female” “woman” “women” “daughter” “daughters” “spokeswoman” “hus- band” “queen” “sister” # A.2 WikiText-2 Male Words: “actor” “Actor” “boy” “Boy” “boyfriend” “Boys” “boys” “father” “Father” “Fa- thers” “fathers” “Gentleman” “gentleman” “gen- tlemen” “Gentlemen” “grandson” “he” “He” “hero” “him” “Him” “his” “His” “Husband” “husbands” “King” “kings” “Kings” “male” “Male” “males” “Males” “man” “Man” “men” “Men” “Mr.” “Prince” “prince” “son” “sons” “spokesman” “stepfather” “uncle” “wife” “king” Female Words: “actress” “Actress” “girl” “Girl” “girlfriend” “Girls” “girls” “mother” “Mother” “Mothers” “mothers” “Lady” “lady” “ladies” “Ladies” “granddaughter” “she” “She” “heroine” “her” “Her” “her” “Her” “Wife” “wives” “Queen” “queens” “Queens” “female” “Female” “fe- males” “Females” “woman” “Woman” “women” “Women” “Mrs.” “Princess” “princess” “daugh- ter” “daughters” “spokeswoman” “stepmother” “aunt” “husband” “queen” # A.3 CNN/Daily Mail Male Words: “actor” “boy” “boyfriend” “boys” “father” “gentlemen” “grandson” “he” “him” “his” “husbands” “kings” “male” “males” “man” “men” “prince” “son” “sons” “spokesman” “stepfather” “uncle” “wife” “king” “brother” “brothers” Female Words: “actress” “girl” “girlfriend” “ladies” “mothers” “mother” “girls” “wives” “granddaughter” “woman” “queens” “women” “daughters” “spokeswoman” “stepmother” “aunt” “husband” “queen” “sister” “sisters” # B Word Level Bias Examples Tables 5 and 6 show the bias scores at individual word level for selected words for Wikitext-2. The tables show how the scores vary for the training text and the generated text for different values of λ Tables 7 and 8 show the bias scores at individ- ual word level for selected words for CNN/Daily Mail. The tables show how the scores vary for the training text and the generated text for different values of λ Target Words training λ=0.0 λ=0.01 λ=0.1 λ=0.5 λ=0.8 λ=1.0 Arts Boston Edward George Henry Peter Royal Sir Stephen Taylor ambassador failed focused idea manager students university wife work youth -0.76 -0.95 -0.68 -0.52 -0.59 -0.69 -0.01 -0.01 -0.35 -0.84 -0.76 -0.46 -0.22 -0.20 -1.58 -0.60 -0.12 -0.92 -0.24 -0.39 -1.20 -1.06 -1.06 -0.91 -1.06 -2.06 -1.89 -1.76 -1.20 -0.91 -1.20 -2.06 -0.91 -1.06 -1.60 -0.79 -1.06 -1.29 -0.88 -1.20 -0.87 -0.23 0.09 -0.26 0.11 -0.09 -0.39 -0.99 -0.18 0.57 -0.23 0.03 -0.12 -0.36 -0.04 -0.31 0.17 -0.81 -0.48 0.54 -0.32 -1.06 -0.56 -0.22 -0.34 -0.14 -0.61 -0.86 -1.01 0.00 -0.63 -0.36 -0.41 -0.16 -0.30 -0.29 -1.01 -1.02 -0.23 -0.16 -0.17 -0.13 -0.14 -0.48 -0.84 -0.32 -0.64 -0.64 -0.84 -0.01 -0.74 -1.00 -0.40 -0.27 -1.08 -0.32 -0.79 -0.57 -0.49 -0.68 0.13 -0.37 -0.44 -0.26 -0.92 0.08 -1.14 -0.16 -0.11 -0.39 0.43 0.17 -0.57 -0.06 -0.30 -0.51 -0.95 -0.67 -0.52 0.58 -1.48 -0.94 -0.23 0.01 -0.61 0.53 -0.56 0.07 0.36 -0.83 -0.81 -0.53 -0.42 -1.06 -0.50 -0.70 -1.03 -0.13 Table 5: WikiText-2 bias scores for the words biased towards male gender for different λ values Target Words training λ=0.0 λ=0.01 λ=0.1 λ=0.5 λ=0.8 λ=1.0 Katherine Zenobia childhood cousin humor invitation parents partners performances producers readers stars talent wore 1.78 0.05 0.48 0.13 0.34 0.19 0.51 0.85 0.79 1.04 0.22 0.85 0.02 0.09 2.27 0.88 1.80 0.88 1.29 1.80 0.76 2.27 1.02 1.58 0.88 1.58 0.88 0.88 1.38 1.84 0.12 0.67 -0.87 0.77 -0.28 -0.20 0.33 0.28 0.16 -0.75 0.48 0.69 0.47 1.10 0.13 0.69 0.69 0.08 0.98 0.16 0.78 0.29 0.90 0.10 0.29 0.95 0.65 0.37 0.09 0.61 0.57 0.45 0.87 0.03 1.35 0.36 0.46 0.31 0.65 0.75 1.24 0.38 0.67 0.34 -0.44 0.57 -0.17 0.10 -1.45 -0.32 -0.28 -0.86 0.16 0.70 0.34 0.71 -0.25 1.11 3.22 -1.80 0.18 -1.29 -0.08 -0.69 Table 6: WikiText-2 bias scores for the words biased towards female gender for different λ values -1.93 0.60 -0.45 -0.69 0.21 0.69 -1.93 -0.27 0.04 -0.32 -0.43 -0.43 -0.52 0.26 -0.63 -0.36 -0.11 -0.63 -0.21 0.49 -0.50 -0.32 -0.99 -1.49 -0.11 -0.19 0.04 -1.30 0.40 -1.59 -1.68 -0.97 -0.83 -0.58 -1.12 abusers acting actions barrister battle beneficiary bills businessman cars citizen cocaine conspiracy controversial cooking cop drug executive fighter fraud friendly heroin journalists lawyer lead leadership notorious offensive officer outstanding parole pensioners prisoners religion reporters representatives research resignation sacrifice supervisor violent 0.66 -0.23 -0.27 -1.35 -0.27 -1.64 -0.32 -0.19 -0.43 -0.03 -0.59 -0.57 -0.21 -0.48 -1.30 -0.76 -0.04 -0.59 -0.17 -0.48 -0.57 -0.25 -0.39 -0.47 -0.25 -0.18 -0.17 -0.25 -0.25 -0.54 -0.48 -0.52 -0.41 -0.60 -0.07 -0.34 -0.95 -0.03 -0.66 -0.17 1.17 -0.81 -0.51 -2.00 -0.53 -1.87 -0.53 -1.81 -0.55 -0.30 -1.00 -0.73 -0.39 -0.53 -1.42 -0.82 -0.34 -0.90 -0.30 -0.53 -0.67 -1.08 -0.47 -0.50 -0.74 -0.64 -0.39 -0.29 -1.55 -0.86 -0.86 -0.99 -0.97 -0.93 -0.48 -0.46 -1.67 -1.08 -0.92 -0.54 0.56 -0.59 -0.06 -0.64 -0.10 -1.06 -0.18 -0.71 -0.32 -0.03 -0.84 -0.66 -0.39 -0.24 -0.77 -0.53 -0.22 -0.48 -0.16 -0.30 -0.28 -0.55 -0.14 -0.40 -0.28 -0.36 -0.28 -0.21 -0.98 0.00 -0.77 -0.18 -0.15 -0.26 -0.40 -0.05 -0.61 -0.38 -0.44 -0.07 0.77 -0.35 -0.07 -0.76 -0.32 -0.22 -0.50 -0.45 -0.11 -0.22 -0.44 -0.39 -0.02 -0.22 -0.72 -0.42 -0.04 -0.36 -0.19 -0.23 -0.26 -0.76 -0.10 -0.09 -0.68 -0.22 -0.17 -0.13 -0.50 -0.08 -0.07 -0.29 -0.48 -0.05 -0.18 -0.33 -0.58 -0.17 -0.25 -0.22 0.16 -0.54 -0.53 -0.08 -0.16 0.63 0.23 -0.53 -0.24 -0.01 -0.42 -0.83 -0.17 0.07 0.00 -0.54 -0.48 -0.89 0.10 0.36 -0.66 -0.44 -0.20 -0.07 -0.57 -0.12 -0.52 -0.17 0.03 0.07 0.64 -0.17 0.18 -0.52 -0.46 0.03 -0.40 -1.29 -0.17 -0.19 | | | | | 0.48 -0.19 Table 7: CNN/Daily Mail bias scores for the words biased towards male gender for different λ values Target Words training λ=0.0 λ=0.1 λ=0.5 λ=0.8 λ=1.0 -0.65 1.16 0.64 0.36 0.48 -0.25 0.27 -0.14 0.87 -1.53 1.11 1.36 0.88 0.26 -0.21 -0.94 0.55 0.06 0.29 0.26 0.25 0.25 -0.09 0.26 -0.26 -0.22 -0.14 -0.34 -0.83 0.42 0.08 0.59 0.96 0.43 0.45 0.17 0.58 -0.53 0.35 abusive appealing bags beloved carol chatted children comments crying designer designers distressed divorced dollar donated donating embracing encouragement endure expecting feeling festive fragile happy healthy hooked hurting indian kissed kissing loving luxurious makeup mannequin married models pictures pray relationship scholarship sharing sleeping stealing tears thanksgiving waist 0.00 0.44 0.34 0.17 0.76 0.03 0.29 0.17 0.28 0.73 0.44 0.15 0.68 0.44 0.52 1.29 1.13 0.85 0.85 1.01 0.21 0.15 0.44 0.32 0.52 0.78 0.75 0.18 0.31 0.26 0.41 0.59 1.60 0.95 0.29 0.35 0.08 0.62 0.53 0.80 0.58 0.18 0.10 0.50 0.85 1.33 0.40 1.22 1.42 0.35 1.41 1.83 0.46 0.46 0.70 0.80 2.14 0.53 0.70 1.63 0.57 1.38 1.78 0.94 0.94 1.07 0.84 0.53 0.94 0.66 0.64 1.38 1.13 0.28 1.03 1.14 0.73 0.82 1.63 1.92 0.37 1.22 0.50 1.58 0.62 1.16 0.73 0.71 0.48 0.58 2.14 1.45 0.06 0.23 0.48 0.27 0.20 0.20 0.36 0.04 0.19 0.57 1.29 0.23 0.18 0.65 0.06 0.27 0.74 0.22 0.26 0.26 0.16 0.52 0.20 0.10 0.26 0.12 0.33 0.15 0.17 0.54 0.43 0.17 0.07 0.70 0.34 0.28 0.10 0.25 0.39 0.80 0.33 0.27 0.32 0.44 1.14 0.68 0.39 0.30 0.05 0.15 0.39 0.19 0.26 0.02 0.57 0.69 0.76 0.26 0.10 0.59 0.15 0.80 0.55 0.50 0.29 0.12 0.25 0.14 0.45 0.11 0.45 0.12 0.34 0.02 0.19 0.61 0.18 0.44 0.22 0.04 0.09 0.38 0.04 0.35 0.32 0.70 0.67 0.35 0.18 0.12 1.08 0.02 0.48 -0.68 0.16 0.52 0.27 -0.14 0.41 -0.35 0.17 0.53 -0.11 -0.56 0.31 -0.24 0.68 -0.03 1.48 0.37 1.02 0.53 0.16 0.21 -0.20 0.11 0.24 -0.11 0.44 -0.02 0.28 0.44 0.15 -0.03 1.09 1.42 0.30 0.90 -0.06 -0.25 0.58 0.53 0.42 0.56 0.06 0.45 0.90 0.31 0.96 Table 8: CNN/Daily Mail bias scores for the words biased towards female gender for different λ values
Title: Pythia v0.1: the Winning Entry to the VQA Challenge 2018: Summary: This document describes Pythia v0.1, the winning entry from Facebook AI Research (FAIR)'s A-STAR team to the VQA Challenge 2018. Our starting point is a modular re-implementation of the bottom-up top-down (up-down) model. We demonstrate that by making subtle but important changes to the model architecture and the learning rate schedule, fine-tuning image features, and adding data augmentation, we can significantly improve the performance of the up-down model on VQA v2.0 dataset -- from 65.67% to 70.22%. Furthermore, by using a diverse ensemble of models trained with different features and on different datasets, we are able to significantly improve over the 'standard' way of ensembling (i.e. same model with different random seeds) by 1.31%. Overall, we achieve 72.27% on the test-std split of the VQA v2.0 dataset. Our code in its entirety (training, evaluation, data-augmentation, ensembling) and pre-trained models are publicly available at: https://github.com/facebookresearch/pythia # Pythia v0.1: the Winning Entry to the VQA Challenge 2018 Yu Jiang∗, Vivek Natarajan∗, Xinlei Chen∗, Marcus Rohrbach, Dhruv Batra, Devi Parikh Facebook AI Research # Abstract This document describes Pythia v0.1, the winning entry from Facebook AI Research (FAIR)’s A-STAR team to the VQA Challenge 20181. Our starting point is a modular re-implementation of the bottom-up top-down (up-down) model [1, 14]. We demon- strate that by making subtle but important changes to the model architecture and the learning rate schedule, fine- tuning image features, and adding data augmentation, we can significantly improve the performance of the up-down model on VQA v2.0 dataset [6] – from 65.67% to 70.24%. Furthermore, by using a diverse ensemble of models trained with different features and on different datasets, we are able to significantly improve over the ‘standard’ way of ensembling (i.e. same model with different random seeds) by 1.31%. Overall, we achieve 72.27% on the test- std split of the VQA v2.0 dataset. Our code in its entirety (training, evaluation, data-augmentation, ensembling) and pre-trained models are publicly available at: https:// github.com/facebookresearch/pythia . development in VQA [2] and related directions like visual dialog [3]. The name ‘Pythia’ is an homage to the Ora- cle of Apollo at Delphi, who answered questions in Ancient Greece. The starting point for Pythia v0.1 is a modular reim- plementation of the bottom-up top-down (up-down) model [14]. In this study, we demonstrate that by making a se- quence of subtle but important changes, we can significantly improve the performance as summarized in Table 13. # 2. Bottom-Up and Top-Down Attention We perform ablations and augmentations over the base- line system of the up-down model [1], which was the basis of the winning entry to the 2017 VQA challenge. The key idea in up-down is the use of an object detector – Faster RCNN [12] pre-trained on the Visual Genome dataset [9] – to extract image features with bottom-up attention, i.e., visual feed-forward attention. Specifically, a ResNet-101 was chosen as the backbone network, and its entire Res-5 block was used as the second-stage region classifier for de- tection. After training, each region was then represented by the 2048D feature after average pooling from a 7×7 grid. # 1. Introduction Pythia – Is there any man alive wiser than Socrates? Pythia: None. # Chaerephon: We present Pythia v0.1, a modular framework for Visual Question Answering research, which formed the basis for the winning entry to the VQA Challenge 2018 from Face- book AI Research (FAIR)’s A-STAR2 team. The question text is then used to compute the top-down attention, i.e., task specific attention, for each object in the image. Multi-modal fusion is done through a simple Hadamard product followed by a multi-label classifier using a sigmoid activation function to predict the answer scores. Their performance reached 70.34% on VQA 2.0 test-std split with an ensemble of 30 models trained with differ- ent seeds. For presentation clarity, we present our proposed changes (and the respective improvements) in a sequence; however, we also found them to be independently useful. The motivation for Pythia comes from the following ob- servation – a majority of today’s Visual Question Answer- ing (VQA) models fit a particular design paradigm, with modules for question encoding, image feature extraction, fusion of the two (typically with attention), and classifica- tion over the space of answers. The long-term goal of Pythia is to serve as a platform for easy and modular research & # 2.1. Model Architecture We made a few changes to the up-down model to im- Instead of using the prove training speed and accuracy. gated hyperbolic tangent activation [1], we use weight nor- malization [13] followed by ReLU to reduce computation4. We also replaced feature concatenation with element-wise ∗ indicates equal contributions. 1and changes made after the challenge deadline. 2Agents that See, Talk, Act, and Reason. 3FAIR A-STAR’s entry in the VQA 2018 Challenge was 72.25%. This document describes results produced by our code release which reaches 72.27%. 1 Table 1. Accuracy (%) on VQA v2.0. For ease of presentation, our changes are presented as a sequence building on top of previ- ous changes. ∗ denotes that these models are not included in our ensemble results submitted to the challenge. Model test-dev test-std up-down [1] up-down Model Adaptation (§2.1) + Learning Schedule (§2.2) + Detectron & Fine-tuning (§2.3) + Data Augmentation∗ (§2.4) + Grid Feature∗ (§2.5) + 100 bboxes∗ (§2.5) 65.32 66.91 68.05 68.49 69.24 69.81 70.01 65.67 70.24 Ensemble, 30× same model (§2.6) Ensemble, 30× diverse model (§2.6) 70.96 72.18 72.27 multiplication to combine the features from text and vi- sual modalities when computing the top-down attention. To compute the question representation, we used 300D GloVe [11] vectors to initialize the word embeddings and then passed it to a GRU network and a question attention module to extract attentive text features [16]. For fusing the image and text information, we found the best-performing hidden size to be 5000. With these modifications, we were able to improve the performance of the model from 65.32% to 66.91% on VQA v2.0 test-dev. # 2.2. Learning Schedule Our model is optimized by Adamax, a variant of Adam with infinite norm [8]. In one popular implementation of up-down4 learning rate is set to 0.002 with a batch size of 512. We found that reducing the batch size improves perfor- mance – which suggests that there is potential for improv- ing performance by increasing the learning rate. However, naively increasing the learning rate resulted in divergence. To increase the learning rate, we thus deployed the warm up strategy [5] commonly used for large learning-rate training of networks. Specifically, we begin with a learning rate of 0.002, linearly increasing it at each iteration till it reaches 0.01 at iteration 1000. Next, we first reduce the learning rate by a factor of 0.1 at 5K and then reduce it every 2K iterations, and stop training at 12K. With this we increase the performance from 66.91% to 68.05% on test-dev. # 2.3. Fine-Tuning Bottom-Up Features Fine tuning pre-trained features is a well known tech- nique to better tailor the features to the task at hand and thus improve model performance [12]. Different from Anderson et al. [1], we also used the new state-of-the-art detectors based on feature pyramid net- # 4https://github.com/hengyuan-hu/ # bottom-up-attention-vqa 2 > z 84 ec ennneenn ners 3 4 8 —S o 2 4 $ | — same model > » -- diversified model oT T T T T T T 0 5 10 15 20 25 30 Number of Models in Ensemble Figure 1. Performance with different ensemble strategies. works (FPN) [10] from Detectron5, which uses ResNeXt [15] as backbone and has two fully connected layers (fc6 and fc7) for region classification. This allows us to extract the 2048D fc6 features and fine-tune the fc7 parameters, as opposed to the original up-down [1], where fine-tuning previous layers requires significantly more storage/IO and computation on 7×7×2048 convolutional feature maps. Similar to up-down, we also used Visual Genome (VG) [9] with both objects and attributes annotations to train the de- tector. We set the fine-tune learning rate as 0.1 times the overall learning rate. We are able to reach a performance of 68.49% on test-dev with this fine-tuning. # 2.4. Data Augmentation from Visual Genome [9] and Visual Dialog (VisDial v0.9) [3] datasets. For VisDial, we converted the 10 turns in a dialog to 10 independent question-answer pairs. Since both VG and VisDial datasets only have a single ground-truth answer while VQA has 10, we simply replicated the answer to each question in VG and VisDial 10 times to make the data format compatible with the VQA evaluation protocol. We also performed additional data augmentation by mir- roring the images in the VQA dataset. We do some basic processing of the questions and answers for the mirrored images by interchanging the tokens “left” and “right” in the questions and answers which contain them. When adding these additional datasets, we reduce the learning rate as we described in Section 2.2 first at 15K iterations, respectively, and stop training at 22K iterations. As a result of data aug- mentation, we are able to improve our single model perfor- mance from 68.49% to 69.24% on test-dev. # 2.5. Post-Challenge Improvements Anderson et al. [1] uses only the features pooled from object proposals (called bottom-up features) to represent an image. Our hypothesis is that such a representation does not fully capture a holistic spatial information about the image and visual representations from image regions not covered by the proposals. To test this hypothesis, we combined grid- 5https://github.com/facebookresearch/Detectron level image features together with bottom-up features. We follow the same procedure as [4] to extract grid-level fea- tures from ResNet152 [7]. Object-level features and grid- level features are separately fused with features from ques- tions and then are concatenated to fed to classification. Be- fore the challenge deadline, we had experimented with this only on images from the VQA dataset without fine-tuning. After the challenge, we performed more comprehensive ex- periments and found that adding grid level features helps to further improve the performance to 69.81%. Instead of using an adaptive protocol for choosing the number of object proposals (between 10 and 100) per im- age as as done in [14], we also experimented with using a simpler (but slower) strategy of using 100 objects proposals for all images. As can be seen in Table 1, with features from 100 bounding-boxes, we reach 70.01% for test-dev and 70.24% for test-std on VQA 2.0. # 2.6. Model Ensembling All ensembling experiments described below involve models trained before the challenge deadline. That is, they do not include the two after-challenge experiments de- scribed in Section 2.5. We tried two strategies for ensem- bling. First, we choose our best single model and train the same network with different seeds, and finally average the predictions from each model. As can be seen from Fig 1, the performance plateaus at 70.96%. Second, we choose models trained with different settings, i.e., the tweaked up- down model trained on the VQA dataset with/without data augmentation and models trained with image features ex- tracted from different Detectron models with/without data augmentation. As can be seen, this ensembling strategy is much more effective than the previous one. Ensembling 30 diverse models, we reach 72.18% on test-dev and 72.27% on test-std of VQA v2.0. # Acknowledgements We would like to thank Peter Anderson, Abhishek Das, Stefan Lee, Jiasen Lu, Jianwei Yang, Licheng Yu, Luowei Zhou for helpful discussions, Peter Anderson for providing training data for the Visual Genome detector, Deshraj Ya- dav for responses on EvalAI related questions, Stefan Lee for suggesting the name ‘Pythia’, Abhishek Das, Abhishek Kadian for feedback on our codebase and Meet Shah for making a docker image for our demo. # References [1] P. Anderson, X. He, C. Buehler, D. Teney, M. Johnson, S. Gould, and L. Zhang. Bottom-up and top-down atten- tion for image captioning and visual question answering. In CVPR, 2018. 3 [2] S. Antol, A. Agrawal, J. Lu, M. Mitchell, D. Batra, C. Lawrence Zitnick, and D. Parikh. VQA: Visual question answering. In ICCV, 2015. [3] A. Das, S. Kottur, K. Gupta, A. Singh, D. Yadav, J. M. Moura, D. Parikh, and D. Batra. Visual Dialog. In CVPR, 2017. [4] A. Fukui, D. H. Park, D. Yang, A. Rohrbach, T. Dar- rell, and M. Rohrbach. Multimodal compact bilinear pool- ing for visual question answering and visual grounding. arXiv:1606.01847, 2016. P. Noordhuis, L. Wesolowski, A. Kyrola, A. Tulloch, Y. Jia, and K. He. Accurate, large minibatch SGD: training imagenet in 1 hour. arXiv preprint arXiv:1706.02677, 2017. [6] Y. Goyal, T. Khot, D. Summers-Stay, D. Batra, and D. Parikh. Making the V in VQA matter: Elevating the role of image understanding in Visual Question Answering. In CVPR, 2017. [7] K. He, X. Zhang, S. Ren, and J. Sun. Deep residual learning for image recognition. In CVPR, 2016. [8] D. P. Kingma and J. Ba. Adam: A method for stochastic optimization. arXiv preprint arXiv:1412.6980, 2014. [9] R. Krishna, Y. Zhu, O. Groth, J. Johnson, K. Hata, J. Kravitz, S. Chen, Y. Kalantidis, L.-J. Li, D. A. Shamma, et al. Vi- sual genome: Connecting language and vision using crowd- sourced dense image annotations. IJCV, 2017. [10] T.-Y. Lin, P. Doll´ar, R. Girshick, K. He, B. Hariharan, and S. Belongie. Feature pyramid networks for object detection. In CVPR, 2017. [11] J. Pennington, R. Socher, and C. Manning. Glove: Global vectors for word representation. In EMNLP, 2014. [12] S. Ren, K. He, R. Girshick, and J. Sun. Faster r-cnn: Towards real-time object detection with region proposal networks. In NIPS, 2015. [13] T. Salimans and D. P. Kingma. Weight normalization: A simple reparameterization to accelerate training of deep neu- ral networks. In NIPS, 2016. [14] D. Teney, P. Anderson, X. He, and A. van den Hengel. Tips and tricks for visual question answering: Learnings from the 2017 challenge. CoRR, abs/1708.02711, 2017. [15] S. Xie, R. Girshick, P. Dollr, Z. Tu, and K. He. Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431, 2016. [16] Z. Yu, J. Yu, C. Xiang, J. Fan, and D. Tao. Beyond bilin- ear: Generalized multimodal factorized high-order pooling for visual question answering. TNNLS, 2018.
Title: Beyond neural scaling laws: beating power law scaling via data pruning: Summary: Widely observed neural scaling laws, in which error falls off as a power of the training set size, model size, or both, have driven substantial performance improvements in deep learning. However, these improvements through scaling alone require considerable costs in compute and energy. Here we focus on the scaling of error with dataset size and show how in theory we can break beyond power law scaling and potentially even reduce it to exponential scaling instead if we have access to a high-quality data pruning metric that ranks the order in which training examples should be discarded to achieve any pruned dataset size. We then test this improved scaling prediction with pruned dataset size empirically, and indeed observe better than power law scaling in practice on ResNets trained on CIFAR-10, SVHN, and ImageNet. Next, given the importance of finding high-quality pruning metrics, we perform the first large-scale benchmarking study of ten different data pruning metrics on ImageNet. We find most existing high performing metrics scale poorly to ImageNet, while the best are computationally intensive and require labels for every image. We therefore developed a new simple, cheap and scalable self-supervised pruning metric that demonstrates comparable performance to the best supervised metrics. Overall, our work suggests that the discovery of good data-pruning metrics may provide a viable path forward to substantially improved neural scaling laws, thereby reducing the resource costs of modern deep learning. # Beyond neural scaling laws: beating power law scaling via data pruning # Ben Sorscher∗∗1 # Robert Geirhos∗2 # Shashank Shekhar3 # Surya Ganguli1,3§ Ari S. Morcos3§ ∗equal contribution 1Department of Applied Physics, Stanford University 2University of Tübingen 3Meta AI (FAIR) §Joint senior authors # Abstract Widely observed neural scaling laws, in which error falls off as a power of the training set size, model size, or both, have driven substantial performance im- provements in deep learning. However, these improvements through scaling alone require considerable costs in compute and energy. Here we focus on the scaling of error with dataset size and show how in theory we can break beyond power law scaling and potentially even reduce it to exponential scaling instead if we have access to a high-quality data pruning metric that ranks the order in which training examples should be discarded to achieve any pruned dataset size. We then test this improved scaling prediction with pruned dataset size empirically, and indeed observe better than power law scaling in practice on ResNets trained on CIFAR-10, SVHN, and ImageNet. Next, given the importance of finding high-quality pruning metrics, we perform the first large-scale benchmarking study of ten different data pruning metrics on ImageNet. We find most existing high performing metrics scale poorly to ImageNet, while the best are computationally intensive and require labels for every image. We therefore developed a new simple, cheap and scalable self-supervised pruning metric that demonstrates comparable performance to the best supervised metrics. Overall, our work suggests that the discovery of good data-pruning metrics may provide a viable path forward to substantially improved neural scaling laws, thereby reducing the resource costs of modern deep learning. # 1 Introduction Empirically observed neural scaling laws [1, 2, 3, 4, 5, 6, 7, 8] in many domains of machine learning, including vision, language, and speech, demonstrate that test error often falls off as a power law with either the amount of training data, model size, or compute. Such power law scaling has motivated significant societal investments in data collection, compute, and associated energy consumption. However, power law scaling is extremely weak and unsustainable. For example, a drop in error ∗work done during an internship at Meta AI (FAIR) 36th Conference on Neural Information Processing Systems (NeurIPS 2022). A ,__ Perceptron in teacher-student setting C__Perceptron in teacher-student setting E — Theory * Simulation Test accuracy (%) Keep hard examples Frac. data na © 100% 077% © 60% © 469 © 369 © 289% © 22% © 17% © 13% © 10% Frac. data kept Frac. data kept Keep easy examples 10> 10° 10 to 15 20 25 30 35 40 Total examples per parameter (Qitot) Training examples per parameter (prune) 1 n Information gain per example Keep hard ~ examples when total data is abundant 3 D ResNet18 on CIFAR-10 2 Training examples per parameter (prune) —_" “ig, Keep easy |_| $ 3 Information (nats) qday eyep sey examples Keep easy when total examples data is J 10 scarce Total examples T 2 3 a Training examples per parameter (Qprune) Figure 1: Our analytic theory of data pruning predicts that power law scaling of test error with respect to dataset size can be beaten. A: Test error as a function of αprune = f αtot with θ = 0. We observe an excellent match between our analytic theory (solid curves) and numerical simulations (dots) of perceptron learning at parameters N=200 (here: N=200 constant throughout figure). The red curve indicates the Pareto optimal test error ε achievable from a tradeoff between αtot and f at fixed αprune. B: We find that when data is abundant (scarce) corresponding to large (small) αtot, the better pruning strategy is to keep the hard (easy) examples. C: Color indicates difference in test error in keeping hard versus easy examples, revealing the change in strategy in (B). D: We tested this prediction on a ResNet18 trained on CIFAR-10, finding remarkably the same shift in optimal pruning strategy under the EL2N metric. E: Test accuracy as a function of f and αprune. For every fixed αprune, there is an optimal fopt (purple curve). F: I(αprune) for different f . from 3% to 2% might require an order of magnitude more data, compute, or energy. In language modeling with large transformers, a drop in cross entropy loss from about 3.4 to 2.8 nats2 requires 10 times more training data (Fig. 1 in [2]). Also, for large vision transformers, an additional 2 billion pre-training data points (starting from 1 billion) leads to an accuracy gain on ImageNet of a few percentage points (Fig. 1 in [7]). Here we ask whether we might be able to do better. For example, can we achieve exponential scaling instead, with a good strategy for selecting training examples? Such vastly superior scaling would mean that we could go from 3% to 2% error by only adding a few carefully chosen training examples, rather than collecting 10× more random ones. Focusing on scaling of performance with training dataset size, we demonstrate that exponential scaling is possible, both in theory and practice. The key idea is that power law scaling of error with respect to data suggests that many training examples are highly redundant. Thus one should in principle be able to prune training datasets to much smaller sizes and train on the smaller pruned datasets without sacrificing performance. Indeed some recent works [9, 10, 11] have demonstrated this possibility by suggesting various metrics to sort training examples in order of their difficulty or importance, ranging from easy or redundant examples to hard or important ones, and pruning datasets by retaining some fraction of the hardest examples. However, these works leave open fundamental theoretical and empirical questions: When and why is successful data pruning possible? What are good metrics and strategies for data pruning? Can such strategies beat power law scaling? Can they scale to ImageNet? Can we leverage large unlabeled datasets to successfully prune labeled datasets? We address these questions through both theory and experiment. Our main contributions are: 1. Employing statistical mechanics, we develop a new analytic theory of data pruning in the student-teacher setting for perceptron learning, where examples are pruned based on their teacher margin, with large (small) margins corresponding to easy (hard) examples. Our theory quantitatively matches numerical experiments and reveals two striking predictions: 2However, note that nats is on a logarithmic scale and and small improvements in nats can lead to large improvements in downstream tasks. 2 (a) The optimal pruning strategy changes depending on the amount of initial data; with abundant (scarce) initial data, one should retain only hard (easy) examples. (b) Exponential scaling is possible with respect to pruned dataset size provided one chooses an increasing Pareto optimal pruning fraction as a function of initial dataset size. 2. We show that the two striking predictions derived from theory hold also in practice in much more general settings. Indeed we empirically demonstrate signatures of exponential scaling of error with respect to pruned dataset size for ResNets trained from scratch on SVHN, CIFAR-10 and ImageNet, and Vision Transformers fine-tuned on CIFAR-10. 3. Motivated by the importance of finding good quality metrics for data pruning, we perform a large scale benchmarking study of 10 different data pruning metrics at scale on ImageNet, finding that most perform poorly, with the exception of the most compute intensive metrics. 4. We leveraged self-supervised learning (SSL) to developed a new, cheap unsupervised data pruning metric that does not require labels, unlike prior metrics. We show this unsupervised metric performs comparably to the best supervised pruning metrics that require labels and much more compute. This result opens the door to the exciting possibility of leveraging pre-trained foundation models to prune new datasets even before they are labeled. Overall these results shed theoretical and empirical insights into the nature of data in deep learning and our ability to prune it, and suggest our current practice of collecting extremely large datasets may be highly inefficient. Our initial results in beating power law scaling motivate further studies and investments in not just inefficently collecting large amounts of random data, but rather, intelligently collecting much smaller amounts of carefully selected data, potentially leading to the creation and dissemination of foundation datasets, in addition to foundation models [12]. # 2 Background and related work Our work brings together 3 largely disparate strands of intellectual inquiry in machine learning: (1) explorations of different metrics for quantifying differences between individual training examples; (2) the empirical observation of neural scaling laws; and (3) the statistical mechanics of learning. # 2.1 Pruning metrics: not all training examples are created equal Several recent works have explored various metrics for quantifying individual differences between data points. To describe these metrics in a uniform manner, we will think of all of them as ordering data points by their difficulty, ranging from “easiest” to “hardest.” When these metrics have been used for data pruning, the hardest examples are retained, while the easiest ones are pruned away. EL2N scores. For example [10] trained small ensembles (of about 10) networks for a very short time (about 10 epochs) and computed for every training example the average L2 norm of the error vector (EL2N score). Data pruning by retaining only the hardest examples with largest error enabled training from scratch on only 50% and 75% of CIFAR-10 and CIFAR-100 respectively without any loss in final test accuracy. However the performance of EL2N on ImageNet has not yet been explored. Forgetting scores and classification margins. [9] noticed that over the entire course of training, some examples are learned early and never forgotten, while others can be learned and unlearned (i.e. forgotten) repeatedly. They developed a forgetting score which measures the degree of forgetting of each example. Intuitively examples with low (high) forgetting scores can be thought of as easy (hard) examples. [9] explored data pruning using these metrics, but not at ImageNet scale. Memorization and influence. [13] defined a memorization score for each example, corresponding to how much the probability of predicting the correct label for the example increases when it is present in the training set relative to when it is absent (also see [14]); a large increase means the example must be memorized (i.e. the remaining training data do not suffice to correctly learn this example). Additionally [13] also considered an influence score that quantifies how much adding a particular example to the training set increases the probability of the correct class label of a test example. Intuitively, low memorization and influence scores correspond to easy examples that are redundant with the rest of the data, while high scores correspond to hard examples that must be 3 individually learned. [13] did not use these scores for data pruning as their computation is expensive. We note since memorization explicitly approximates the increase in test loss due to removing each individual example, it is likely to be a good pruning metric (though it does not consider interactions). Ensemble active learning. Active learning iterates between training a model and selecting new inputs to be labeled [15, 16, 17, 18, 19]. In contrast, we focus on data pruning: one-shot selection of a data subset sufficient to train to high accuracy from scratch. A variety of coreset algorithms (e.g. [20]) have been proposed for this, but their computation is expensive, and so data-pruning has been less explored at scale on ImageNet. An early clustering approach [21] allowed training on 90% of ImageNet without sacrificing accuracy. Notably [11] reduced this to 80% by training a large ensemble of networks on ImageNet and using ensemble uncertainty to define the difficulty of each example, with low (high) uncertainty corresponding to easy (hard) examples. We will show how to achieve similar pruning performance without labels or the need to train a large ensemble. Diverse ensembles (DDD). [22] assigned a score to every ImageNet image, given by the number of models in a diverse ensemble (10 models) that misclassified the image. Intuitively, low (high) scores correspond to easy (hard) examples. The pruning performance of this metric remains unexplored. Summary. We note: (1) only one of these metrics has tested well for its efficacy in data pruning at scale on ImageNet; (2) all of these metrics require label information; (3) there is no theory of when and why data pruning is possible for any of these metrics; and (4) none of these works suggest the possibility of exponential scaling. We thus go beyond this prior work by benchmarking the data pruning efficacy of not only these metrics but also a new unsupervised metric we introduce that does not require label information, all at scale on ImageNet. We also develop an analytic theory for data-pruning for the margin metric that predicts not only the possibility of exponential scaling but also the novel finding that retaining easy instead of hard examples is better when data is scarce. # 2.2 Neural scaling laws and their potential inefficiency Recent work [1, 2, 3, 4, 5, 6, 7, 8] has demonstrated that test loss L often falls off as a power law with different resources like model parameters (N ), number of training examples (P ), and amount of compute (C). However, the exponents ν of these power laws are often close to 0, suggesting potentially inefficient use of resources. For example, for large models with lots of compute, so that the amount of training data constitutes a performance bottleneck, the loss scales as L ≈ P −ν. Specifically for a large transformer based language model, ν = 0.095, which implies an order of magnitude increase in training data drops cross-entropy loss by only about 0.6 nats (Fig. 1 in [2]). In neural machine translation experiments ν varies across language pairs from 0.35 to 0.48 (Table 1 in [5]). Interestingly, [8] explored a fixed computation budget C and optimized jointly over model size N and training set size P , revealing that scaling both N and P commensurately as C increases is compute optimal, and can yield smaller high performing models (trained on more data) than previous work. Nevertheless, for a transformer based language model, a 100× increase in compute, corresponding to 10× increases in both model size and training set size, leads to a drop in cross-entropy loss of only about 0.5 nats (Fig. 2 in [8]). Similar slow scaling holds for large vision transformers where adding 2 billion pre-training images reduces ImageNet performance by a few percentage points (Fig. 1 in [7]). While all of these results constitute significant improvements in performance, they do come at a substantial resource cost whose fundamental origin arises from power law scaling with small exponents. Recent theoretical works [23, 24, 25] have argued that the power law exponent is governed by the dimension of a data manifold from which training examples are uniformly drawn. Here we explore whether we can beat power law scaling through careful data selection. # 2.3 Statistical mechanics of perceptron learning Statistical mechanics has long played a role in analyzing machine learning problems (see e.g. [26, 27, 28, 29] for reviews). One of the most fundamental applications is perceptron learning in the student-teacher setting [30, 31], in which random i.i.d. Gaussian inputs are labeled by a teacher perceptron to construct a training set. The test error for another student perceptron learning from this training set then scales as a power law with exponent −1 for such data. Such perceptrons have also been analyzed in an active learning setting where the learner is free to design any new input to be 4 labeled [32, 33], rather than choose from a fixed set of inputs, as in data-pruning. Recent work [34] has analyzed this scenario but focused on message passing algorithms that are tailored to the case of Gaussian inputs and perceptrons, and are hard to generalize to real world settings. In contrast we analyze margin based pruning algorithms that are used in practice in diverse settings, as in [9, 10]. # 3 An analytic theory of data pruning To better understand data pruning, we employed the replica method from statistical mechanics [35] to develop an analytic theory of pruning for the perceptron in the student-teacher setting [26] (see App. A for detailed derivations of all results). Consider a training dataset of P examples {xµ, yµ}µ=1,...,P where xµ ∈ RN are i.i.d. zero mean unit variance random Gaussian inputs and yµ = sign(T · xµ) are labels generated by a teacher perceptron with weight vector T ∈ RN . We work in the high dimensional statistics limit where N, P → ∞ but the ratio αtot = P N of the number of total training examples to parameters remains O(1). We then consider a pruning algorithm used in [9, 10], namely: (1) train a probe student perceptron for very few epochs on the training data, obtaining weights Jprobe; (2) compute the margin mµ = Jprobe · (yµxµ) of each training example, where large (small) margins correspond to easy (hard) examples; (3) construct a pruned dataset of size Pprune = f P , where f is the fraction of examples kept, by retaining the Pprune hardest examples, (4) train a new perceptron to completion on the smaller dataset with a smaller ratio αprune = Pprune We are interested in the test error ε of this final perceptron as a function of αtot, f , and the angle θ between the probe student Jprobe and the teacher T. Our theory approximates Jprobe as simply a random Gaussian vector conditioned to have angle θ with the teacher T. Under this approximation we obtain an analytic theory for ε(αtot, f, θ) that is asymptotically exact in the high dimensional limit (App. A). We first examine results when θ = 0, so we are pruning training examples according to their veridical margins with respect to the teacher (Fig. 1A). We find two striking phenomena, each of which constitute predictions in real-world settings that we will successfully confirm empirically. # N of examples to parameters. The best pruning strategy depends on the amount of initial data. First, we note the test error curve for f = 1 in Fig. 1A corresponding to no pruning, or equivalently to randomly pruning a larger dataset of size αtot down to a size αprune, exhibits the well known classical perceptron learning power law scaling ε ∝ α−1 prune. Interestingly though, for small αtot, keeping the hardest examples performs worse than random pruning (lighter curves above darkest curve for small αprune in Fig. 1A). However, for large αtot, keeping the hardest examples performs substantially better than random pruning (lighter curves below darkest curve for large αprune in Fig. 1A). It turns out keeping the easiest rather than hardest examples is a better pruning strategy when αtot is small (Fig. 1C). If one does not have much data to start with, it is better to keep the easiest examples with largest margins (i.e. the blue regions of Fig. 1B) to avoid overfitting. The easiest examples provide coarse-grained information about the target function, while the hard examples provide fine-grained information about the target function which can prevent the model from learning if one starts with lots of data. In cases where overfitting is less of an issue, it is best to keep the hardest examples with smallest margin that provide more information about the teacher’s decision boundary (i.e. the green region of Fig. 1B). Intuitively, in the limited data regime, it is challenging to model outliers since the basics are not adequately captured; hence, it is more important to keep easy examples so that the model can get to moderate error. However, with a larger dataset, the easy examples can be learned without difficulty, making modeling outliers the fundamental challenge. Fig. 1C reveals which pruning strategy is best as a joint function of αtot and f . Note the transition between optimal strategies becomes sharper at small fractions f of data kept. This transition between optimal pruning strategies can be viewed as a prediction in more general settings. To test this prediction we trained a ResNet18 on pruned subsets of the CIFAR-10 dataset (Fig. 1D), and observed strikingly similar behavior, indicating the prediction can hold far more generally, beyond perceptron learning. Interestingly, [9, 10] missed this transition, likely because they started pruning from large datasets. Pareto optimal data pruning can beat power law scaling. A second prediction of our theory is that when keeping a fixed fraction f of the hardest examples as αtot increases (i.e. constant color curves in Fig. 1A), the error initially drops exponentially in αprune = f αtot, but then settles into the universal power law ε ∝ α−1 prune for all fixed f . Thus there is no asymptotic advantage to data 5 o° c —Theory ® Simulation 1 2.3 45678 1 2 3 45678 1 2 3 45678 Training examples per parameter Training examples per parameter __Training examples per parameter (prune) (prune) (prune) Figure 2: Data pruning with an imperfect metric. A: Weight vectors and decision boundaries for a teacher (black) and probe student (red) separated by angle θ. The black point has margin 0 (κ) w.r.t. the probe (teacher). B–D: Test error as a function of αprune for different f and different θ. pruning at a fixed f . However, by pruning more aggressively (smaller f ) when given more initial data (larger αtot), one can achieve a Pareto optimal test error as a function of pruned dataset size αprune that remarkably traces out at least an exponential scaling law (Fig. 1A, purple curve). Indeed our theory predicts for each αprune a Pareto optimal point in αtot and f (subject to αprune = f αtot), yielding for every fixed αprune an optimal fopt, plotted in Fig. 1E. Note fopt decreases with αprune indicating more aggressive pruning (smaller fopt) of original datasets of larger size αtot is required to obtain larger Pareto optimal pruned datasets of size αprune. We will test this striking scaling prediction in Fig. 3. Beating power law scaling: an information-theoretic perspective. Classical randomly selected data generates slow power law error scaling because each extra training example provides less new information about the correct decision boundary than the previous example. More formally, let S(αtot) denote the typical entropy of the posterior distribution over student perceptron weights consistent with a training set of size αtot. The information gain I(αtot) due to additional examples beyond αtot can be defined as the rate at which the posterior entropy is reduced: I(αtot) = − d S(αtot). In dαtot classical perceptron learning I(αtot) decays to zero as a power law in αtot, reflecting a vanishing amount of information per each new example, leading to the slow power law decay of test error ε ∝ α−1 tot . However, data pruning can increase the information gained per example by pruning away the uninformative examples. To show this, we generalized the replica calculation of the posterior entropy S and information gain I from random datasets of size αtot to pruned datasets of size αprune (App. A). We plot the resulting information gain I(αprune) for different f in Fig. 1F. For any fixed f , I(αprune) will eventually decay as a power law as α−1 prune. However, by more aggressively pruning (smaller f ) datasets of larger size αtot, I(αprune) can converge to a finite value I(∞) = 1 nat/example, resulting in larger pruned datasets only adding useful non-redundant information. Since each new example under Pareto optimal data pruning conveys finite information about the target decision boundary, as seen in Fig. 1F, the test error can decay at least exponentially in pruned dataset size as in Fig. 1A. Classical results [31] have shown that training examples chosen by maximizing the disagreement of a committee of student perceptrons can provide an asymptotically finite information rate, leading to exponential decay in test error. Intriguingly, the Pareto-optimal data pruning strategy we study in this work leads to faster than exponential decay, because it includes (partial) information about the target function provided by the probe student (Fig. 11). An imperfect pruning metric yields a cross over from exponential to power law scaling. We next examine the case of nonzero angle θ between the probe student Jprobe and the teacher T, such that the ranking of training examples by margin is no longer completely accurate (Fig. 2A). Retaining the hard examples with smallest margin with respect to the probe student will always result in pruned datasets lying near the probe’s decision boundary. But if θ is large, such examples might be far from the teacher’s decision boundary, and therefore could be less informative about the teacher (Fig. 2A). As a result our theory, confirmed by simulations, predicts that under nonzero angles θ, the Pareto optimal lower envelope of test error over both αtot and f initially scales exponentially as a function of αprune = f αtot but then crosses over to a power law (Fig. 2BCD). Indeed, at any given nonzero θ, our theory reveals that as αtot (and therefore αprune) becomes large, one cannot decrease test error any further by retaining less than a minimum fraction fmin(θ) of all available data. For example when θ = 10◦ (θ = 20◦) one can do no better asymptotically than pruning down to 24% (46%) of the total 6 A __Perceptron in teacher-student setting B ResNet?8 on SVHN c ResNetl8 on CIFAR-10 D ResNet50 on ImageNet F Frac Theory °.@ Simulation Frac. data kept © 20% © 30% © 40% © 50% @ 60% 10° | © 70% -o.s2 | @ 60% © 90% ee © 90% © 100% Pareto frontier Test error (9%) Test error (%6) Test error (top-5 %) Pareto frontier Training examples per parameter" 1 Faning examples TBining examples oe Training etamples Figure 3: Beating power law scaling in practice. A–D: Curves of test error against pruned dataset size in 4 settings. Pruning scores were EL2N [10] for CIFAR-10 and SVHN and memorization [13] for ImageNet. See App. B for all pruning/training details and App. D for similar ImageNet plots with EL2N. Note solid curves reflect performance with a fixed total dataset size; if we prune more aggressively with even larger datasets, scaling could improve further (e.g., dashed lines in A). Error curves with no data pruning (f = 1) are labeled with their best-fit power law scaling ∼ α−ν. (Note that for SVHN in B an asymptotic constant error E(P → ∞) = 1.1% is subtracted from each of the curves to visualize the power law scaling more clearly.) A ViT finetuned on CIFAR-10 B oe —s- Memorization 4 ee vo ons as os 107? Frac. of mageNet used for pretaining 10° 10* Fine-tuning examples aed ResNet50 finetuned on CIFAR-10 2 cm fe 7 £ © 20% | E96 Bios : 5 os Figure 4: Data pruning improves transfer learning. A: CIFAR-10 performance of a ViT pre-trained on all of ImageNet21K and fine-tuned on different pruned subsets of CIFAR-10 under the EL2N metric. B: CIFAR-10 performance of ResNet50s pre- trained on different pruned subsets of Ima- geNet1K and fine-tuned on all of CIFAR- 10. data (Fig. 2CD). As θ approaches 0, fmin(θ) approaches 0, indicating that one can prune extremely aggressively to arbitrarily small f while still improving performance, leading to at least exponential scaling for arbitrarily large αprune in Fig. 2B. However, for nonzero θ, the lack of improvement for f < fmin(θ) at large αprune renders aggressive pruning ineffective. This result highlights the importance of finding high quality pruning metrics with θ ≈ 0. Such metrics can delay the cross over from exponential to power law scaling as pruned dataset size αprune increases, by making aggressive pruning with very small f highly effective. Strikingly, in App. Fig. 10 we demonstrate this cross-over in a real-world setting by showing that the test error on SVHN is bounded below by a power law when the dataset is pruned by a probe ResNet18 under the EL2N metric, trained for 4 epochs (weak pruning metric) but not a probe ResNet18 trained for 40 epochs (strong pruning metric). # 4 Data pruning can beat power law scaling in practice Our theory of data pruning for the perceptron makes three striking predictions which can be tested in more general settings, such as deep neural networks trained on benchmark datasets: (1) relative to random data pruning, keeping only the hardest examples should help when the initial dataset size is large, but hurt when it is small; (2) data pruning by retaining a fixed fraction f of the hardest examples should yield power law scaling, with exponent equal to that of random pruning, as the initial dataset size increases; (3) the test error optimized over both initial data set size and fraction of data kept can trace out a Pareto optimal lower envelope that beats power law scaling of test error as a function of pruned dataset size, through more aggressive pruning at larger initial dataset size. We verified all three of these predictions on ResNets trained on SVHN, CIFAR-10, and ImageNet using varying amounts of initial dataset size and fractions of data kept under data pruning (compare theory in Fig. 3A with deep learning experiments in Fig. 3BCD). In each experimental setting we see better than power law scaling at larger initial data set sizes and more aggressive pruning. Moreover we would likely see even better scaling with even larger initial datasets (as in Fig.3A dashed lines). 7 Data pruning improves transfer learning. Modern foundation models are pre-trained on a large initial dataset, and then transferred to other downstream tasks by fine-tuning on them. We therefore examined whether data-pruning can be effective for both reducing the amount of fine-tuning data and the amount of pre-training data. To this end, we first analyzed a vision transformer (ViT) pre-trained on ImageNet21K and then fine-tuned on different pruned subsets of CIFAR-10. Interestingly, pre-trained models allow for far more aggressive data pruning; fine-tuning on only 10% of CIFAR-10 can match or exceed performance obtained by fine tuning on all of CIFAR-10 (Fig. 4A). Furthermore Fig. 4A provides a new example of beating power law scaling in the setting of fine-tuning. Additionally, we examined the efficacy of pruning pre-training data by pre-training ResNet50s on different pruned subsets of ImageNet1K (exactly as in Fig. 3D) and then fine-tuning them on all of CIFAR-10. Fig. 4B demonstrates pre-training on as little as 50% of ImageNet can match or exceed CIFAR-10 performance obtained by pre-training on all of ImageNet. Thus intriguingly pruning pre-training data on an upstream task can still maintain high performance on a different downstream task. Overall these results demonstrate the promise of data pruning in transfer learning for both the pre-training and fine-tuning phases. ae 5 rn 92. BEE 0,00 0,00 -0,00 -0,00 0,00 0,00 -0,00 0,00 0 -0,00 ~ random ‘curacy (%) — ho pruning (4-2 std) e+ active learning -® random pruning 8 forgetting pop 2 influence max 2 EL2N (1 model) —e~ influence sum-abs 0.16 - 87] -e- £L2N (20 models) —e~ memorization _—-0.00 0.08 04 022 028 |020 0.12 020 -seVsupervsed prototypes ag L_ 6.00 0.10 0.00 0.18 oo ee 10 095 09 08 o8 075 OF 085 06 (1 model, Paul '2: c Frac. data kept 0.00 0.14 |031 0.19 - LeLan oe (20 models, Paul '21) 0.00 0.17 |o37 aw L900 010 021 010 0:16 0.28 0.19 |0.33 |039 forgetting (Toneva '19) Top-5 accuracy (%) om 08 075 07 08 06 Frac. data kept Figure 5: Dataset pruning at ImageNet scale. A: Spearman’s rank correlation between all pairs of ImageNet metric scores, along with hierarchical clustering (as provided by seaborn.clustermap). B: Benchmarking existing supervised metrics on ImageNet (top-5 validation accuracy). C: Compar- ing top-5 performance on ImageNet when pruning according to the best existing supervised metric (memorization) and our supervised and self-supervised prototype metrics. In all 3 cases, training on 80% of ImageNet approximates training on 100%. See App. B for pruning and training details. # 5 Benchmarking supervised pruning metrics on ImageNet We note that the majority of data pruning experiments have been performed on small-scale datasets (i.e. variants of MNIST and CIFAR), while the few pruning metrics proposed for ImageNet have rarely been compared against baselines designed on smaller datasets. Therefore, it is currently unclear how most pruning methods scale to ImageNet and which method is best. Motivated by how strongly the quality of a pruning metric can impact performance in theory (Fig. 2), we decided to fill this knowledge gap by performing a systematic evaluation of 8 different supervised pruning metrics on ImageNet: two variants of influence scores [13], two variants of EL2N [10], DDD [22], memorization [13], ensemble active learning [11], and forgetting [9]. See Section 2 for a review of these metrics. Additionally, we include two new prototypicality metrics that we introduce in the next section. We first asked how consistent the rankings induced by different metrics are by computing the Spearman rank correlation between each pair of metrics (Fig. 5A). Interestingly, we found substantial diversity across metrics, though some (EL2N, DDD, and memorization) were fairly similar with rank correlations above 0.7. However, we observed marked performance differences between metrics: Fig 5BC shows test performance when a fraction f of the hardest examples under each metric are kept in the training set. Despite the success of many of these metrics on smaller datasets, only a 8 few still match performance obtained by training on the full dataset, when selecting a significantly smaller training subset (i.e. about 80% of ImageNet). Nonetheless, most metrics continue to beat random pruning, with memorization in particular demonstrating strong performance (Fig. 5C). We note that data pruning on ImageNet may be more difficult than data pruning on other datasets, because ImageNet is already carefully curated to filter out uninformative examples. We found that all pruning metrics amplify class imbalance, which results in degraded performance. To solve this we used a simple 50% class balancing ratio for all ImageNet experiments. Further details and baselines without class balancing are shown in App. H. Metric scores, including baselines, are available from https://github.com/rgeirhos/dataset-pruning-metrics. # 6 Self-supervised data pruning through a prototypicality metric Fig. 5 shows many data pruning metrics do not scale well to ImageNet, while the few that do require substantial amounts of compute. Furthermore, all these metrics require labels, thereby limiting their ability to prune data for large-scale foundation models trained on massive unlabeled datasets [12]. Thus there is a clear need for simple, scalable, self-supervised pruning metrics. To compute a self-supervised pruning metric for ImageNet, we perform k-means clustering in the embedding space of an ImageNet pre-trained self-supervised model (here: SWaV [36]), and define the difficulty of each data point by the cosine distance to its nearest cluster centroid, or prototype. Thus easy (hard) examples are the most (least) prototypical. Encouragingly, in Fig. 5C, we find our self-supervised prototype metric matches or exceeds the performance of the best supervised metric, memorization, until only 70–80% of the data is kept, despite the fact that our metric does not use labels and is much simpler and cheaper to compute than many previously proposed supervised metrics. See App. Fig. 9 for further scaling experiments using the self-supervised metric. To assess whether the clusters found by our metric align with ImageNet classes, we compared their overlaps in Fig. 6A. Interestingly, we found alignment for some but not all classes. For example, class categories such as snakes were largely aligned to a small number of unsupervised clusters, while other classes were dispersed across many such clusters. If class information is available, we can enforce alignment between clusters and classes by simply computing a single prototype for each class (by averaging the embeddings of all examples of this class). While originally intended to be an additional baseline metric (called supervised prototypes, light blue in Fig 5C), this metric remarkably outperforms other supervised metrics and largely matches the performance of memorization, which is prohibitively expensive to compute. Moreover, the performance of the best self-supervised and supervised metrics are similar, demonstrating the promise of self-supervised pruning. One important choice for the self-supervised prototype metric is the number of clusters k. We found, reassuringly, our results were robust to this choice: k can deviate one order of magnitude more or less than the true number of classes (i.e. 1000 for ImageNet) without affecting performance (App. F). To better understand example difficulty under various metrics, we visualize extremal images for our self-supervised prototype metric and the memorization metric for one class (Fig 6B,C). Qualitatively, easy examples correspond to highly similar, redundant images, while hard examples look like idiosyncratic outliers. See App. E, Figs. 12,13,14,15,16,17,18,19 for more classes and metrics. imageNe ted by wordnet hierarchy) Figure 6: A: Heat map where each row denotes the probability that images in a given cluster come from each ImageNet class. B: The four easiest and hardest images under our self-supervised pruning metric and the best previously published supervised metric (memorization, shown in C) for ImageNet class 100 (black swan). 9 # 7 Discussion Summary. We have shown, both in theory and practice, how to break beyond slow power law scaling of error versus dataset size to faster exponential scaling, through data pruning. Additionally we have developed a simple self-supervised pruning metric that enables us to discard 20% of ImageNet without sacrificing performance, on par with the best and most compute intensive supervised metric. Limitations. The most notable limitation is that achieving exponential scaling requires a high quality data pruning metric. Since most metrics developed for smaller datasets scale poorly to ImageNet, our results emphasize the importance of future work in identifying high quality, scalable metrics. Our self-supervised metric provides a strong initial baseline. Moreover, a key advantage of data pruning is reduced computational cost due to training on a smaller dataset for the same number of epochs as the full dataset (see App. C). However, we found that performance often increased when training on the pruned dataset for the same number of iterations as on the full dataset, resulting in the same training time, but additional training epochs. However, this performance gain saturated before training time on the pruned dataset approached that on the whole dataset (App. J) thereby still yielding a computational efficiency gain. Overall this tradeoff between accuracy and training time on pruned data is important to consider in evaluating potential gains due to data pruning. Finally, we found that class-balancing was essential to maintain performance on data subsets (App. H). Future work will be required to identify ways to effectively select the appropriate amount of class-balancing. Ethical considerations. A potential negative societal impact could be that data-pruning leads to unfair outcomes for certain groups. We have done a preliminary analysis of how data-pruning affects performance on individual ImageNet classes (App. I), finding no substantial differential effects across classes. However proper fairness tests specific to deployment settings should always be conducted on every model, whether trained on pruned data or not. Additionally, we analyzed the impact of pruning on OOD performance (App. K). Outlook: Towards foundation datasets. We believe the most promising future direction is the further development of scalable, unsupervised data pruning metrics. Indeed our theory predicts that the application of pruning metrics on larger scale datasets should yield larger gains by allowing more aggressive pruning. This makes data pruning especially exciting for use on the massive unlabeled datasets used to train large foundation models (e.g. 400M image-text pairs for CLIP [37], 3.5B Instagram images [38], 650M images for the DALLE-2 encoder [39], 780B tokens for PALM [40]). If highly pruned versions of these datasets can be used to train a large number of different models, one can conceive of such carefully chosen data subsets as foundation datasets in which the initial computational cost of data pruning can be amortized across efficiency gains in training many downstream models, just at the initial computational cost of training foundation models is amortized across the efficiency gains of fine-tuning across many downstream tasks. Together, our results demonstrate the promise and potential of data pruning for large-scale training and pretraining. # Acknowledgments We thank Priya Goyal, Berfin Simsek, Pascal Vincent valuable discussions, Qing Jin for insights about the optimal pruning distribution, Isaac Seessel for VISSL support as well as Kashyap Chitta and José Álvarez for kindly providing their ensemble active learning score. # References [1] Joel Hestness, Sharan Narang, Newsha Ardalani, Gregory Diamos, Heewoo Jun, Hassan Kianinejad, Md Patwary, Mostofa Ali, Yang Yang, and Yanqi Zhou. Deep learning scaling is predictable, empirically. arXiv preprint arXiv:1712.00409, 2017. [2] 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. [3] Tom Henighan, Jared Kaplan, Mor Katz, Mark Chen, Christopher Hesse, Jacob Jackson, Heewoo Jun, Tom B Brown, Prafulla Dhariwal, Scott Gray, et al. Scaling laws for autoregressive generative modeling. arXiv preprint arXiv:2010.14701, 2020. 10 [4] Jonathan S. Rosenfeld, Amir Rosenfeld, Yonatan Belinkov, and Nir Shavit. A constructive prediction of the generalization error across scales. International Conference on Learning Representations, 2020. [5] Mitchell A Gordon, Kevin Duh, and Jared Kaplan. Data and parameter scaling laws for neural machine translation. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pages 5915–5922, Online and Punta Cana, Dominican Republic, November 2021. Association for Computational Linguistics. [6] Danny Hernandez, Jared Kaplan, Tom Henighan, and Sam McCandlish. Scaling laws for transfer. arXiv preprint arXiv:2102.01293, 2021. [7] Xiaohua Zhai, Alexander Kolesnikov, Neil Houlsby, and Lucas Beyer. Scaling vision transform- ers. arXiv preprint arXiv:2106.04560, 2021. [8] Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, et al. Training compute-optimal large language models. arXiv preprint arXiv:2203.15556, 2022. [9] Mariya Toneva, Alessandro Sordoni, Remi Tachet des Combes, Adam Trischler, Yoshua Bengio, and Geoffrey J Gordon. An empirical study of example forgetting during deep neural network learning. In ICLR, 2019. [10] Mansheej Paul, Surya Ganguli, and Gintare Karolina Dziugaite. Deep learning on a data diet: Finding important examples early in training. Adv. Neural Inf. Process. Syst., 34, December 2021. [11] Kashyap Chitta, José M Álvarez, Elmar Haussmann, and Clément Farabet. Training data subset search with ensemble active learning. IEEE Trans. Intell. Transp. Syst., pages 1–12, 2021. [12] Rishi Bommasani, Drew A Hudson, Ehsan Adeli, Russ Altman, Simran Arora, Sydney von Arx, Michael S Bernstein, Jeannette Bohg, Antoine Bosselut, Emma Brunskill, et al. On the opportunities and risks of foundation models. arXiv preprint arXiv:2108.07258, 2021. [13] Vitaly Feldman and Chiyuan Zhang. What neural networks memorize and why: Discovering the long tail via influence estimation. Adv. Neural Inf. Process. Syst., 33:2881–2891, 2020. [14] Hrayr Harutyunyan, Alessandro Achille, Giovanni Paolini, Orchid Majumder, Avinash Ravichandran, Rahul Bhotika, and Stefano Soatto. Estimating informativeness of samples with smooth unique information. In International Conference on Learning Representations, 2021. [15] Burr Settles. Active learning literature survey. Technical Report, 2009. [16] Antoine Bordes, Seyda Ertekin, Jason Weston, Léon Botton, and Nello Cristianini. Fast kernel classifiers with online and active learning. J. Mach. Learn. Res., 6(9), 2005. [17] Zeyad Ali Sami Emam, Hong-Min Chu, Ping-Yeh Chiang, Wojciech Czaja, Richard Leapman, Micah Goldblum, and Tom Goldstein. Active learning at the ImageNet scale. arXiv preprint arXiv:2111.12880, 2021. [18] Ozan Sener and Silvio Savarese. Active learning for convolutional neural networks: A core-set approach. arXiv preprint arXiv:1708.00489, 2017. [19] Siddharth Karamcheti, Ranjay Krishna, Li Fei-Fei, and Christopher D Manning. Mind your outliers! Investigating the negative impact of outliers on active learning for visual question answering. arXiv preprint arXiv:2107.02331, 2021. [20] Baharan Mirzasoleiman, Jeff Bilmes, and Jure Leskovec. Coresets for data-efficient training of machine learning models. In Hal Daumé Iii and Aarti Singh, editors, Proceedings of the 37th International Conference on Machine Learning, volume 119 of Proceedings of Machine Learning Research, pages 6950–6960. PMLR, 2020. [21] V Birodkar, H Mobahi, and S Bengio. Semantic redundancies in Image-Classification datasets: The 10% you don’t need. arXiv preprint arXiv:1901.11409, 2019. [22] Kristof Meding, Luca M. Schulze Buschoff, Robert Geirhos, and Felix A. Wichmann. Trivial or impossible—dichotomous data difficulty masks model differences (on ImageNet and beyond). In International Conference on Learning Representations, 2022. [23] Utkarsh Sharma and Jared Kaplan. Scaling laws from the data manifold dimension. Journal of Machine Learning Research, 23(9):1–34, 2022. 11 [24] Yasaman Bahri, Ethan Dyer, Jared Kaplan, Jaehoon Lee, and Utkarsh Sharma. Explaining neural scaling laws. CoRR, abs/2102.06701, 2021. [25] Jonathan S. Rosenfeld. Scaling Laws for Deep Learning. PhD thesis, Massachusetts Institute of Technology, USA, 2021. [26] A Engel and C V den Broeck. Statistical Mechanics of Learning. Cambridge Univ. Press, 2001. [27] Madhu Advani, Subhaneil Lahiri, and Surya Ganguli. Statistical mechanics of complex neural systems and high dimensional data. J. Stat. Mech: Theory Exp., 2013(03):P03014, 2013. [28] Yasaman Bahri, Jonathan Kadmon, Jeffrey Pennington, Sam S Schoenholz, Jascha Sohl- Dickstein, and Surya Ganguli. Statistical mechanics of deep learning. Annual Review of Condensed Matter Physics, March 2020. [29] Lenka Zdeborová and Florent Krzakala. Statistical physics of inference: thresholds and algorithms. Adv. Phys., 65(5):453–552, September 2016. [30] E Gardner. The space of interactions in neural network models. J. of Physics A, 21:257–270, 1988. [31] H S Seung, H Sompolinsky, and N Tishby. Statistical mechanics of learning from examples. Phys. Rev. A, 45(8):6056, 1992. [32] Yoav Freund, H Sebastian Seung, Eli Shamir, and Naftali Tishby. Information, prediction, and query by committee. Adv. Neural Inf. Process. Syst., 5, 1992. [33] Hai-Jun Zhou. Active online learning in the binary perceptron problem. Commun. Theor. Phys., 71(2):243, February 2019. [34] Hugo Cui, Luca Saglietti, and Lenka Zdeborovà. Large deviations in the perceptron model and consequences for active learning, 2021. [35] M Mezard, G Parisi, and M A Virasoro. Spin glass theory and beyond. World scientific Singapore, 1987. [36] Mathilde Caron, Ishan Misra, Julien Mairal, Priya Goyal, Piotr Bojanowski, and Armand Joulin. Unsupervised learning of visual features by contrasting cluster assignments. In H. Larochelle, M. Ranzato, R. Hadsell, M.F. Balcan, and H. Lin, editors, Advances in Neural Information Processing Systems, volume 33, pages 9912–9924. Curran Associates, Inc., 2020. [37] Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, et al. Learning transferable visual models from natural language supervision. In International Conference on Machine Learning, pages 8748–8763. PMLR, 2021. [38] Dhruv Mahajan, Ross Girshick, Vignesh Ramanathan, Kaiming He, Manohar Paluri, Yixuan Li, Ashwin Bharambe, and Laurens Van Der Maaten. Exploring the limits of weakly supervised pretraining. In Proceedings of the European conference on computer vision (ECCV), pages 181–196, 2018. [39] Aditya Ramesh, Prafulla Dhariwal, Alex Nichol, Casey Chu, and Mark Chen. Hierarchical text-conditional image generation with clip latents. arXiv preprint arXiv:2204.06125, 2022. [40] 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. [41] Priya Goyal, Quentin Duval, Jeremy Reizenstein, Matthew Leavitt, Min Xu, Benjamin Lefaudeux, Mannat Singh, Vinicius Reis, Mathilde Caron, Piotr Bojanowski, Armand Joulin, and Ishan Misra. VISSL. https://github.com/facebookresearch/vissl, 2021. [42] Olga Russakovsky, Jia Deng, Hao Su, Jonathan Krause, Sanjeev Satheesh, Sean Ma, Zhiheng Huang, Andrej Karpathy, Aditya Khosla, Michael Bernstein, et al. ImageNet large scale visual recognition challenge. International Journal of Computer Vision, 115(3):211–252, 2015. [43] Kaiyu Yang, Klint Qinami, Li Fei-Fei, Jia Deng, and Olga Russakovsky. Towards fairer datasets: Filtering and balancing the distribution of the people subtree in the ImageNet hierarchy. In Proceedings of the 2020 Conference on Fairness, Accountability, and Transparency, pages 547–558, 2020. 12 [44] Yuki M Asano, Christian Rupprecht, Andrew Zisserman, and Andrea Vedaldi. PASS: An ImageNet replacement for self-supervised pretraining without humans. arXiv preprint arXiv:2109.13228, 2021. [45] Ross Wightman. Pytorch image models. https://github.com/rwightman/ pytorch-image-models, 2019. [46] Justin M Johnson and Taghi M Khoshgoftaar. Survey on deep learning with class imbalance. Journal of Big Data, 6(1):1–54, 2019. [47] Robert Geirhos, Kantharaju Narayanappa, Benjamin Mitzkus, Tizian Thieringer, Matthias Bethge, Felix A Wichmann, and Wieland Brendel. Partial success in closing the gap between human and machine vision. Advances in Neural Information Processing Systems, 34:23885– 23899, 2021. [48] Felix A Wichmann, David HJ Janssen, Robert Geirhos, Guillermo Aguilar, Heiko H Schütt, Marianne Maertens, and Matthias Bethge. Methods and measurements to compare men against machines. Electronic Imaging, Human Vision and Electronic Imaging, 2017(14):36–45, 2017. [49] Robert Geirhos, Carlos RM Temme, Jonas Rauber, Heiko H Schütt, Matthias Bethge, and Felix A Wichmann. Generalisation in humans and deep neural networks. In Advances in Neural Information Processing Systems, 2018. [50] Robert Geirhos, Patricia Rubisch, Claudio Michaelis, Matthias Bethge, Felix A. Wichmann, and Wieland Brendel. ImageNet-trained CNNs are biased towards texture; increasing shape bias improves accuracy and robustness. In International Conference on Learning Representations, 2019. [51] Haohan Wang, Songwei Ge, Zachary Lipton, and Eric P Xing. Learning robust global repre- sentations by penalizing local predictive power. Advances in Neural Information Processing Systems, 32, 2019. [52] Robert Geirhos, Kristof Meding, and Felix A Wichmann. Beyond accuracy: quantifying trial- by-trial behaviour of CNNs and humans by measuring error consistency. Advances in Neural Information Processing Systems, 33, 2020. [53] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification. In Proceedings of the IEEE International Conference on Computer Vision, pages 1026–1034, 2015. [54] John P Miller, Rohan Taori, Aditi Raghunathan, Shiori Sagawa, Pang Wei Koh, Vaishaal Shankar, Percy Liang, Yair Carmon, and Ludwig Schmidt. Accuracy on the line: on the strong correlation between out-of-distribution and in-distribution generalization. In International Conference on Machine Learning, pages 7721–7735. PMLR, 2021. 13 # Appendix # Table of Contents A A theory of data-pruning for the perceptron: detailed derivations . . . A.1 Problem setup . . A.2 Main result and overview . . . A.3 Replica calculation of the generalization error . . . A.4 Quenched entropy . . . . . A.5 Perfect teacher-probe overlap . . . A.6 Information gain per example . . . . A.7 Imperfect teacher-probe overlap . . . . A.8 Optimal pruning policy . . . . . A.9 Exact saddle point equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B Model training method details & dataset information C Breaking compute scaling laws via data pruning D Additional scaling experiments E Extremal images according to different metrics F Impact of number of clusters k on self-supervised prototypes G Impact of ensemble prototypes H Relationship between pruning and class (im-)balance I Effect of pruning on class-conditional accuracy and fairness J Interaction between data pruning and training duration K Out-of-distribution (OOD) analysis of dataset pruning 14 14 15 15 24 24 25 26 26 28 31 32 33 33 44 44 44 50 50 51 # A A theory of data-pruning for the perceptron: detailed derivations All code required to reproduce the theory figures and numerical simulations throughout this paper can be run in the Colab notebook at https://colab.research.google.com/drive/1in35C6jh7y_ ynwuWLBmGOWAgmUgpl8dF?usp=sharing. # A.1 Problem setup In this section we introduce a theory for data pruning in the teacher-student perceptron setting, using the tools of statistical mechanics. We study the problem of classifying a dataset of P examples {xµ, yµ}µ=1,...,P , where xµ ∼ N (0, IN ) are i.i.d. zero mean unit variance random Gaussian inputs, and yµ = sign(T · x) are labels generated by a teacher perceptron T ∈ RN , which we will assume is randomly drawn from a uniform distribution on the sphere T ∼ Unif(SN −1( N )). We work in the high-dimensional statistics limit where N, P → ∞ but the ratio αtot = P/N remains O(1). The generalization error of a perceptron trained on such an isotropic dataset is a classical problem (see e.g. [26]). However, we are interested in the setting where the training dataset is not isotropic, but instead has inherited some structure due to data pruning. 14 In particular, consider pruning the training dataset by keeping only the examples with the smallest margin |z“| = |Jprobe - X“| along a probe student Jprobe. The pruned dataset will follow some distribution p(z) along the direction of Jprove, and remain isotropic in the nullspace of Jprobe- In what follows we will derive a general theory for an arbitrary data distribution p(z), and specialize to the case of small-margin pruning only at the very end (in which case p(z) will take the form of a truncated Gaussian). We will also make no assumptions on the form of the probe student Jprobe or the learning rule used to train it; only: that Ge has ees some overlap with the teacher, quantified ) Fig. by the angle @ = cos~ 1 (gn Te Ge ) Fig. by the angle @ = cos~ 1 (gn Te After the dataset has been pruned, we consider training a new student J from scratch on the pruned dataset. A typical training algorithm (used in support vector machines and the solution to which SGD converges on separable data) is to find the solution J which classifies the training data with the maximal margin & = min,,J - (y"x"). Our goal is to compute the generalization error €, of this student, which is simply governed by the overlap between the student and the teacher, ey = cos *(R)/r, where R = J-T/|J}l2\Tlo. # A.2 Main result and overview Our main result is a set of self-consistent equations which can be solved to obtain the generalization error ε(α, p, θ) for any α and any data distribution p(z) along a probe student at any angle θ relative to the teacher. These equations take the form, R—pcos? a ® A(t, z)\ za AC dt exp ( DAE (K — t) ; qd) 24 pe Kk — (ope p> + R* — 2pRcos0 ( e 2p?) ( T(t, z) ) 2) 1 — ——_,—__ = 2a dt AD Kt 2 sin? 6 oo V2nv1~p 2 V1- pear ( ) z 2) p—Rcosé ([ ® e acer ( T(t, z) \EY) —,—_ = 2a 5H K—t sin? 6 neve V1- pear ( ) _l woe . + oA en (3 OA? >) (“- )is-o) (3) Where, A= \/sin? 0 — R2 — p? + 2pReos8, (4) T(t, z) = 2(pR — cos 6) — t(R — pcos), (5) A(t, z) = 2? (p? + cos? @ — 2pR cos) + 2tz(Rcos 0 — p) +t? sin 6. (6) Where (-), represents an average over the pruned data distribution p(z) along the probe student. For any a, p(z), 8, these equations can be solved for the order parameters R, p, «, from which the generalization error can be easily read off as €y = cos~!(R)/7. This calculation results in the solid theory curves in Figs which show an excellent match to numerical simulations. In the following section we will walk through the derivation of these equations using replica theory. In Section we will derive an expression for the information gained per training example, and show that wi Pareto optimal data pruning this information gain can be made to converge to a finite rate, resulting in at least exponential decay in test error. In Section{A.7] we will show that super-exponential scaling eventually breaks down when the probe student does not match the teacher perfectly, resulting in power law scaling at at a minimum pruning fraction fmin(9). # A.3 Replica calculation of the generalization error To obtain Eqs. 1,2,3, we follow the approach of Elizabeth Gardner and compute the volume Ω(xµ, T, κ) of solutions J which perfectly classify the training data up to a margin κ (known as the 15 Gardner volume) [30, 26]. As κ grows, the volume of solutions shrinks until it reaches a unique solution at a critical κ, the max-margin solution. The Gardner volume Ω takes the form, Q(x", T, 6) = [ awa) Tle = (ue -*)) (7) Because the student’s decision boundary is invariant to an overall scaling of J, we enforce normaliza- tion of J via the measure dµ(J), qu(S) = 5(I|JII? — N) (8) 1 (Qre) N72 In the thermodynamic limit N, P — oo the typical value of the entropy S(«) = ((log Q(x", T, «))) is dominated by particular values of R, «, where the double angle brackets ((-)) denote a quenched average over disorder introduced by random realizations of the training examples x“ and the teacher T. However, computing this quenched average is intractable since the integral over J cannot be performed analytically for every individual realization of the examples. We rely on the replica trick from statistical physics, ln(x) = lim n→0 xn − 1 n (9) Which allows us to evaluate S(κ) in terms of easier-to-compute powers of Ω, O"(x!#,T,«))) —1 Sli) = ((in Q(x", T, «))) = LO" Ts 8) = 2 (10) n This reduces our problem to computing powers of Ω, which for integer n can be written in terms of α = 1, . . . , n replicated copies of the original system, Txt! (J+ xt QA” = ((A"(x", TK) (C/T d(S°) o(=s ( -«)))) ist ((a"( Tews 10( TI TN (i) o any We begin by introducing auxiliary variables, λα µ = Jα · xµ √ N , uµ = T · xµ √ N (12) by δ−functions, to pull the dependence on J and T outside of the Heaviside function, 00 [hoo [Tos ts a= np ap (esse) Jere) «9 Using the integral representation of the δ-functions, 1) = -/ Il du oy) [Te d\edie Ts du, dt, (14) a=l att x Il O(up (Ae - K)) exp (: > NBAG +i > unt) (15) oun a in x (exp ( - wes oye x! ye et >) 16) 16 The data obeys some distribution p(z) along the direction of Jprobe and is isotropic in the nullspace of Jprobe. Hence we can decompose a training example xµ as follows, xµ = Jprobezµ+(I −JprobeJT probe)sµ, where zµ ∼ p(z) and sµ ∼ N (0, IN ), Qe) = [Thea (J°) (Te dyed * Ts (17) a=1 oun x [le Up (Az — ) ) exp (: i> rade + De uty) (18) att pe # att i Say qo m i ~ x ((exp ( - Tru + Iprobe2” + JG 8") — Tp 2 ted oe +TL ‘s'))) (19) Where J⊥ = (1 − JprobeJT sµ ∼ N (0, IN ), probe)J and T⊥ = (1 − JprobeJT probe)T. Now we can average over the patterns a u ~ 1 Jayo yn (oo(-Jp Qin gy E Mn) no(- shies +n) VN tx (20) 1 Va }8 ze B Jan ya ~ =e (= 57 (DAA gh 42D Anaya Ta + aplmu IP). (21) uw ap Inserting this back into our expression for the Gardner volume, a”) = | Tl aua) /l na / Nooo a=1 x [le Up(Ay — K )e( Peer +12 uty) oH Ha HM 1 $a} B70 «(Co | - sy (D aiiist ee ene T+ a3)T.|P) nw Sap - id, (>> Mis - Iprobe + ti T - Jie)" )) in a Ty2h (22) As is typical in replica calculations of this type, we now introduce order parameters, qαβ = Jα · Jβ N , Rα = T · Jα N (23) which will allow us to decouple the J- from the λ-µ-z- integrals. qαβ represents the overlaps between replicated students, and Rα the overlap between each replicated student and the teacher. However, because our problem involves the additional role of the probe student, we must introduce an additional order parameter, ρα = Jα · Jprobe N (24) which represents the overlap between each replicated student and the probe student. Notice that, JETL =I Sh Ty = NC" — pe") 25) 17 JO-TL=S°-T-Jj Ty = N(R — p* cos) (26) With this new set of order parameters in hand, we can decouple the J from the λ − u − z−integrals. -/ TL eee He a<p «fT ay(3°) (Tse a _ NR® ) TI 505° 39 = Na"*) Tf 50° - Spore — Np") a=1 Ta<p a dnrdie . « [TI “TIS: du, diy, Ile e( unl (Ae - k) «)) [[exp (‘ naka + ing) au ou Ht a 1 « (exp -3 -= 5a NGAP (G a8 _ pap) )- Ae y(R® — p* cos 0) — ih sin? 6 aB a -i( » p* + ty, cos 0) “| ) (27) Ω(n) = We can now perform the gaussian integral over ˆuµ, a” -/ TI ag? [Tan [ Tao" a<B x | Il au(ae)( [st — NR* )) [] 6° WP - Na) TT (J - Iprove — Nip) a=1 Ta<p “1s dneaie ape duydtiy I 6 (uj(A2 — k) ye (: >» nA) x (exp |-3 5 Dl AaNg ap — p%p*) E> See a ap 1 . 2 + sin? (iu — 2 cos 6) — » An (R® — p* cos 0) ), (28) Expanding, 18 (28) QAM = | [I ’ | [ar | [le a<B «/T ayi(3°) (The .J° — NR®) )) Il aI - no) T] 9 (J° - Sprove — Np”) a=1 Ta<p dyadic duj,dti, a . aga — 1 (up = 2" C088)? x [TI * ISS pe [le UpAg — «)) Tew (stg - F# One Oh ia a . 1 Say ie a 6 . Sa nc x (exp — 5 a? — p%p?) = 10 Apr zt ap a - 9 p (un z cos @) Dnt (R° = p* cos) + Qain2 4 Do MAR — p* cos )(R? — p? cos 0] (29) Ω(n) = Simplifying, # Il a”) = | Il aur? [Tare [ Theo" a<B «fT ay(3°) (Ihr s “ _ NR®) ) Il 5s? ~ Ng) Tp ou" - Tove — Np) a=1 Ta<p a dyadic duy,dii, ata L (uy, — 2" cos)? x [TT * ISS [le up (At — &)) exp iy MG = 5 5 aa ayn ay Ha a6 (,a8 — ag _ (R*—p%cos6)(R° — p?cosé)\ _ fa «(eo | SLD IAs (ae oe - at LDA ap s Ba _ a — z cos 0 Je( RO — * cost} ) Sng (te z" cos pS i (R* — p* cos 6) . (30) Ω(n) = Now we introduce integral representations for the remaining delta functions, including the measure dµ(Jα), for which we introduce the parameter ˆkα, 19 # ˆλα µραzµ ).. # zµ n dq? dge® dR“dR® dp° dp oT [Ty Se Is x exp (oe ko + in»? ghh Gee + inde ROR® + ine i") a<B « {TIS ly on exp (-5 —5 3A kelly — i > geese 8 - (DAs T iD pad®- a) a<p «TS d\ed\e Ts duy,dii, T° u,(X2 — )) exp (: iS regia a 1 — 2h “cos 6)? ) oma sin? 6 a R® — p* cos )(R? — p? cos 0) ae x (ex |=} sD X (0 ap _ pep! — | pm “On pe ‘ LU Moe ap = 5 (tu — Zz * cos) 5 AG( (R° —p * cos} ) 1) Ω(n) = Notice that the uµ − λα the power of P = αN . µ − ˆλα µ − zµ-integrals factorize in µ, and can be written as a single integral to n dk dg? age? dR°dR® dp“ dp a” «/T15, /T Qn/N /T In/N /T on/N * exp (v E dt ke +a PG +i X R°R® + Dp» pp (32) a<p + Gs (k%, ge", R®, p*) +0Ge(a"*, R*.0")}) Where we have written the Gardner volume in terms of an entropic part GS, which measures how many spherical couplings satisfy the constraints, Gs = x log | I _ exp ( Dy RSP aT GP PD RT TAD i) a<p a And an energetic part GE, aya — +4 eos 8)2 Ge tog [| du = / TS dreds IIe (u(A® =k) )exn (i nw 5 1 (uy = 2 cos 6)" aa cos 8) ) sin? 0 cate — p* cos 8) 1? — 9 cos8) . «(ox [E3638 ( 0 (R° — p* cose MUR p® cos 2) isp irene op sin* 0 i ~ A (u — zcos 8) Ss A°(R® — p* cos 0] ) (34) sin 7" 2 We first evaluate the entropic part, GS, by introducing the n × n matrices A, B, Aαβ = iˆkαδαβ + iˆqαβ(1 − δαβ) Bαβ = δαβ + qαβ(1 − δαβ) (35) (36) 20 (33) # ˆλα µραzµ Inserting this our expression for GS becomes Gs = = log [Th = exp (= 5 Je" Aad? —iS~I* - (TR + Imai) (37) Ve > 2 " Integrating over Jα, Gs = 3 — = log(det A) — (TR® + Iproveo") Ag 3(TR? + Iprove®) (38) 2N a8 Now we can include the remaining terms in the expression for Ω(n) outside of GE and GS by noting that tr(AB) = AαβBβα (39) # ap = (iˆkαδαβ + iˆqαβ(1 − δαβ))(δαβ + qαβ(1 − δαβ)) (40) # ap = Dike e2 yaaa’ (41) a<p Additionally, we can use log det A = tr(log A). Thus all terms in the exponent except GE can be written as r Ob 1 2 Oe Pa 2 an ante (log A)— ow TR°+Spronep*)” Ang (T TR +Iprovep”) +5tr(AB) t iS” RER i> °° Sprobe a8 a a (42) − α (42) Now we extremize wrt ˆRα and the elements of A by setting the derivatives wrt ˆRγ, ˆργ and Aγδ equal to zero: 0 = − αγ T · (T ˆRα + Jprobe ˆρα) + iRγ = − A−1 αγ ( ˆRα + ˆρα cos θ) + iRγ A−1 α (43) 0 = − αγ Jprobe · (T ˆRα + Jprobe ˆρα) + iργ = − A−1 αγ ( ˆRα cos θ + ˆρα) + iργ A−1 α α (44) 1 r Ob = 5A + 5 DA(TR® + Iproteh")” Ags Ags (TR? + IproveP”) + 5 5 Bas (45) a,b Solving these gives - R® — p® cosé R° =i Agg—>3—_ 46 : » aa sin? 0 (46) 3B B eos R . p’ — R® cosé ~ Aa, : 47 p ‘ y “8 sin? 0 an # β and A−1 γδ = Bγδ − RγRδ − Rγρδ cos θ − Rδργ cos θ + ργρδ sin2 θ ≡ Cγδ (48) and now we are left with 1 Qa” ~ exp (Werte ee [5ér(ow C)+ aGe(u*.R°)]) (49) 21 # A.3.1 Replica symmetry ansatz In order to extremize wrt qαβ, Rα, ρα, we take the replica symmetry ansatz [26], qαβ = q, Rα = R, ρα = ρ (50) Then C takes the form R2 − 2Rρ cos θ + ρ2 sin2 θ A matrix with E on the diagonal and F elsewhere, Cαβ = Eδαβ + F (1 − δαβ), has n − 1 degenerate eigenvalues E − F and one eigenvalue E + (n − 1)F . Hence in our case C has n − 1 degenerate eigenvalues 2 *0s 2 2 -0s 2 (-4 2Rpcos 6 + p’ )- (.-* 2Rpcos 6 + p’ ) =1-q (52) sin? 0 sin? 0 and one other eigenvalue, R? — 2Rpcos@ + p? R? — 2Rpcosé + p? R? — 2Rpcos@ + p? 1- +(n—1)(¢ 1l—q+n| q- sin? 0 sin? 0 sin? 0 (53) Therefore, R? — 2Rpcos@ + p? r(log C) = (n— 1)log{ 1—q}) +log]1—q4+n(q — sin* 0 (54) qsin? @ — (R? — 2Rpcos6 + p?) =nlog{l—q)})+log|l+n 3 (1 —q)sin* 6 We next evaluate the energetic part, GE, du dd“d\* o ata l(u—zcosé)? Ge=los [ = / Ts TLewo —k)) en (138 per 1 Sang (R — pcosé)? (R — pcosé)? _t feye(a—p2- aeeses fed — pp — = Posty (exp | aa ) ( p sin? @ “3 sin? 6 — iy N° p% 2 = mn 5 (wu — zcos 4) e A°(R® — p* cos 0] ) (55) First note that we can rewrite the terms 1 2 (R= pcosé) 2 B (R = pcos 6)? = S37 (1 =p? — SPN ie ReN3 (gq —p? — a Peser 2— ( p sin? 6 yo 2D) ae sin? 0 1 Boot) « 5( (R — pcos 6) -)| A __t 1— p2 — MER 00s ey" * (fay2 —p aes Jey? (A%)2 >> ( p sin? 6 0°) g ? sin? 0 () => ) __l jay2_ t 2 (R= pcos6)? jay2 = 2 tt DA") AG p sin? () ) (56) − 22 To simplify the last term we apply the Hubbard-Stratonovich transformation, e””/? = f Dte®, introducing auxiliary field t, « 2 c0s6)(R* — p* cos) (R = pcos 6)? ) 1 eae) Ae ( ye 9% 2 : _ylq—p2— t\)—— : » 6, pe sin? 6 IP sin? 6 2 sin? 6 # +i Using the Θ-function to restrict the bounds of integration, ‘ono [a ia I aXe [Tl dae [> [-4 tue 0 ex] . 0 Vln Vin J AS 20 P « ur *0080)(R* — p* cos) (R- roost? 1 (u— zcos6)? ie(ae pee! ! _[ a 2 )) : » ( pe sin? 6 IP sin? 6 2 sin? 6 - # +i Now we can perform the gaussian integrals over ˆλα, du d\* 1 = lor 2 _ Ne — 9 es val Ile Di | nial “ _ (u — zcos 0)(R* — p* cos 0) _ 3 H,)" _ 1in= 2cos6))) (59) 2 sin’ 0 2 sin? 6 A%, − And λα, sin? 0 sco cess (60) sin? 6 Shifting the integration variable t → (ραz + (u−z cos θ)(Rα−ρα cos θ) we can finally perform the gaussian integral over u, sin2 θ + q − ρ2 − (R−ρ cos θ)2 sin2 θ t)/ √ q, at ar) | q “( [4 ) =log2 | —= - H t “8 [ya (eo( 2(q - p)? q-~ i-q. x ( 1 «&— (qRoz + zp(R — 2pcos@) — /qt(R — pen) (61) q-p? /qsin” 0 + 2Rpcos6 — R? — p z √ — zp)/\/q — p?, We can simplify this further by taking t → ( k—(zp+J/q—P)t eee =log2 | Dt( H” H via /- (q — p?) (p? = qsin 2 @ + R? — 2pRcos 6) (62) 23 z (57) z (58) # z # t # A.4 Quenched entropy Putting everything together, and using the replica identity, (log Q)=lim,,_,9((Q2”) — 1)/n, we obtain an expression for the quenched entropy of the teacher-student perceptron under data pruning: 1 1 1 (q—(R? — 2Rpcos6 + p?)/ sin? (0H 9) = ext | 5 Tou (1-2) ; (4 (R Rp cos 6 + p*)/ sin ) Ta +2a( | Deiog (SCAT ve coe Vim) <n (WE ee pcos@) + 2(q cos 6 my) | a= p*) (R2 + p2 = qsin® @ — 2pRcos8) z We will now unpack this equation and use it to make predictions in several specific settings. # A.5 Perfect teacher-probe overlap We will begin by considering the case where the probe student has learned to perfectly match the teacher, Jprobe = T , which we can obtain by the limit θ → 0, ρ → R. In this limit the second H-function in Eq. 63 becomes increasingly sharp, approaching a step function: (64) u(- (Va—P? + pz) (R— pcos d) + 2(qcos — on) (2) Va — p?) (R? + p? — qsin® 6 — 2pR cos 6) Hence we are left with, 2|- _ p2 + an a(x, 7) = ext | 510g (1 - ‘) +5 (4 — ) +20 f ve f aev(90( )O(z) log H (- va 8) (65) # A.5.1 Saddle point equations We can now obtain a set of self-consistent saddle point equations by setting set to zero the derivatives with respect to R and q of the right side of Eq. 65. As κ approaches its critical value, the space of solutions shrinks to a unique solution, and hence the overlap between students q approaches one. In the limit q → 1, after some partial integration, we find, K [mip [oon SBI ee eS ee These saddle point equations can be solved numerically to find R and « as a function of a for a student perceptron trained on a dataset with an arbitrary distribution along the teacher direction p(z). We can specialize to the case of data pruning by setting p(z) to the distribution found after pruning an initially Gaussian-distributed dataset so that t only a fraction f of those examples with the smallest = ey - = H-*(4L), margin along the teacher are kept, p(z) = 24 (63) Y 1- R= 2 [pela - Bea) - (- FS)? (69) Solving these saddle point equations numerically for R and κ yields an excellent fit to numerical simulations, as can be seen in Fig. 1A. It is also easy to verify that in the limit of no data pruning (f → 1, γ → ∞) we recover the saddle point equations for the classical teacher-student perceptron (Eqs. 4.4 and 4.5 in [26]), 2a Rt? . = ag | Dio (~ Ea )im-9 (70) Rt 2 1- R= 20 [ pen(- A) n-9) (71) # Information gain per example Why does data pruning allow for super-exponential performance with dataset size α? We can define the amount of information gained from each new example, I(α),as the fraction by which the space of solutions which perfectly classify the data is reduced when a new training example is added, I(α) = Ω( P +1 dα S(α). Of coure, the volume of solutions shrinks to zero at the max-margin solution; so to study the volume of solutions which perfectly classify the data we simply set the margin to zero κ = 0. In [32] the information gain for a perceptron in the classical teacher-student setting is shown to take the form, I(a) = 2 [ oon (/ a) tow (yp) (72) Which goes to zero in the limit of large α as I(α) ∼ 1/α. Data pruning can increase the information gained per example by pruning away the uninformative examples. To show this, we generalize the calculation of the information gain to pruned datasets, using the expression for the entropy we obtained in the previous section (Eq. 65). S(a) = 5(loe) = ext, [5 log (1- R)+5 raza f pe [” de plz Vox 1 (— Vit-— 42) vV1-R (73) Hence the information gain I(α) = − d dα S(α) is given by I(a) = 2a f vt [ aen(2012) toe H( — VRt- =") (74) V1-R √ Changing variables to t → −( Rt + R√ z)/ q, 1−R √ √ *° 1 1 2+ om) ( R ) a) =2a | Dt dzp(z ex! - log H ——t 75 ) | [ P(?) Rog »( sak) lV z—Rt) Now, assuming that we prune to a fraction f, so that p(z) = O(|z| — ) Se )) Now, assuming that we prune to a fraction f, so that p(z) = O(|z| — ) Se )) where 7 = V2nf ~ 1- Ho (=) H −1 1−f 2 √ 8 fool) ose] 25 I(α) is plotted for varying values of f in Fig. 1F. Notice that for f → 1, γ → ∞ and we recover Eq. 72. To obtain the optimal pruning fraction fopt for any α, we first need an equation for R, which can be obtained by taking the saddle point of Eq. 73. Next we optimize I(α) by setting the derivative of Eq. 76 with respect to f equal to zero. This gives us a pair of equations which can be solved numerically to obtain fopt for any α. Finally, Eq. 76 reveals that as we prune more aggressively the information gain per example approaches a finite rate. As f → 0, γ → 0, and we obtain, √ I(α) = − Dt log H( Rt) (77) Which allows us to produce to trace the Pareto frontier in Fig. 1F. For R → 1, Eq. 77 gives the asymptotic information gain I(∞) = 1 nat/example. # Imperfect teacher-probe overlap In realistic settings we expect the probe student to have only partial information about the target function. What happens if the probe student does not perfectly match the teacher? To understand this carefully, we need to compute the full set of saddle point equations over R, q, and ρ, which we will do in the following section. But to first get an idea for what goes wrong, we include in this section a simple sketch which reveals the limiting behavior. Consider the case where the angle between the probe student and teacher is θ. Rotate coordinates so that the first canonical basis vector aligns with the student J = (1, 0, . . . , 0), and the teacher lies in the span of the first two canonical basis vectors, T = (cos θ, sin θ, 0, . . . , 0). Consider the margin along the teacher of a new training example x drawn from the pruned distribution. E|T · x|2 = E[x2 0 cos2 θ + x2 1 sin2 θ] (78) As the fraction of examples kept goes to zero, Ex2 converges to a fixed value, 0 → 0, and the average margin of a new example # E|T · x|2 = sin2 θ E|T · x|2 = sin2 θ (79) Hence the data ultimately stops concentrating around the teacher’s decision boundary, and the information gained from each new example goes to zero. Therefore we expect the generalization error to converge to a power law, where the constant prefactor is roughly that of pruning with a prune fraction fmin which yields an average margin of 1 − R2. This “minimum” pruning fraction lower bounds the generalization error envelope (see Fig. 2), and satisfies the following equation, nin . 1 en Vin yin dxp(a)x? = = — 1-R (80) [- \ 2 V2n(1 — 2H (ymin) where γmin = H −1 1−fmin 2 . Eq. 80 can be solved numerically, and we use it to produce the lower-bounding power laws shown in red in Fig. 2C,D. The minimum achievable pruning fraction fmin(θ) approaches zero as the angle between the probe student and the teacher shrinks, and we can obtain its scaling by taking R → 1, in which case we find, fmin(θ) ∼ θ (81) # A.8 Optimal pruning policy The saddle point equations Eq. 66,67 reveal that the optimal pruning policy varies as a function of αprune. For αprune large the best policy is to retain only the “hardest" (smallest-margin) examples. But when αprune is small, keeping the “hardest" examples performs worse than chance, suggesting that the best policy in the αprune small regime is to keep the easiest examples. Indeed by switching between 26 the “keep easy” and “keep hard” strategies as αprune grows, one can achieve a lower Pareto frontier than the one shown in Fig. 1A in the small αprune regime (Fig. 7C). A Optimal data distribution QO on — 20 10 Optimal pruning window OOK prune —> Test error (%) Figure 7: Optimal pruning policy as a function of αprune. A, The Pareto frontier in Fig. AA can be lowered in the small αprune regime if one adaptively switches pruning policies from a “keep easy” to a “keep hard” policy. The dashed purple line indicates the “keep easy” frontier (computed using numerical simulations). The optimal pruning window (derived below) interpolates between the two policies, achieving the lowest possible Pareto frontier (cartooned in blue). B, The optimal data distribution along the teacher p(z|αprune, f ) is a delta function, which selects easy examples for small αprune, intermediate examples for intermediate αprune, and hard examples for large αprune. C, The optimal pruning window similarly selects easy examples for small αprune, intermediate examples for intermediate αprune, and hard examples for large αprune These observations beg the question: what is the best policy in the intermediate αprune regime? Is there a globally optimal pruning policy which interpolates between the “keep easy” and “keep hard” strategies and achieves the lowest possible Pareto frontier (blue curve in Fig. 7A)? In this section we investigate this question. Using the calculus of variations, we first derive the optimal data distribution p(z|αprune, f ) along the teacher for a given αprune, f . We begin by framing the problem using the method of Lagrange multipliers. Seeking to optimize R under the constraints imposed by the saddle point equations Eqs. 66,67, we define the Lagrangian, 20 c= Ru (R-20 [de v(e)e(ei Rh) +A(1~ R20 | dz p(z Vole: Rh). (82) 0 0 Where, eeni)= [" etm oe(— sam )(iam)O- 9 and, ve ff dt (t — Rz)? . 2 werk) =f Javice exp (— FE )(e-9) (84) Taking a variational derivative δL δp with respect to the data distribution p, we obtain an equation for z, indicating that the optimal distribution is a delta function at z = z∗. To find the optimal location of the delta function z∗, we take derivatives with respect to the remaining variables R, k, µ, λ and solve the resulting set of equations numerically. The qualitative behavior is shown in Fig. 7A. As αprune grows, the location of the delta function shifts from infinity to zero, confirming that the optimal strategy for small αprune is to keep the "easy" (large-margin) examples, and for large αprune to keep the "hard" (small-margin) examples. Interestingly, this calculation also reveals that if the location of the delta function is chosen optimally, the student can perfectly recover the teacher (R = 1, zero generalization error) for any αprune. This 27 observation, while interesting, is of no practical consequence because it relies on an infinitely large training set from which examples can be precisely selected to perfectly recover the teacher. Therefore, to derive the optimal pruning policy for a more realistic scenario, we assume a gaussian distribution of data along the teacher direction and model pruning as keeping only those examples which fall inside a window a < z < b. The saddle point equations, Eqs. 66,67, then take the form, ype |e (Carr) or (Carma) 9 69 1- R= of Dt [i () -1(—*)| («-t)? (86) Where a must satisfy a = H −1(f /2 + H(b)). For each f, α, we find the optimal location of this window using the method of Lagrange multipliers. Defining the Lagrangian as before, 20 c=R4u(R-20 [ de p(eho(ssRyk)) + A(1~ = 20 | dz p(z Vole Rh), (87) 0 0 Where now, 6(b; R,k) = [ew -—) ~ exp (- we = | (x -t) (88) To find the optimal location of the pruning window, we take derivatives with respect to the remaining variables b, R, k, µ, λ and solve the resulting set of equations numerically. Consistent with the results for the optimal distribution, the location of the optimal window shifts from around infinity to around zero as αprune grows (Fig. 7C). # A.9 Exact saddle point equations To obtain exact expressions for the generalization error for all θ, we can extremize Eq. 63 wrt R, q, ρ. # Derivative wrt R √ R- Fee peosd = fa fave vn tVq- Pr Coe) (90) (1—q)sin?6 —q)sin? 6 Pa V2 /(2 — ga V2\/q— p?A3 ; K— t/q — p? — pz T(t, z)? P sos (1 ( Vi=a ))o» (-xfre- 5) Ov Where we have defined, Λ = q sin2 θ − R2 − ρ2 + 2Rρ cos θ, (92) T(t, z) = (R — pcos 6) («a —pt 2) + qzcos@ — pRz. (93) Integrating the right-hand side by parts, √ 5 tos)? Tapa [0 [ener Po (5) "a= E) wert 28 where q − ρ2(R−ρ cos θ) cos θ +qt2 sin2 θ +qz2 cos2 θ −ρ2t2 sin2 θ −ρ2z2 cos2 θ (95) ∆(t, z) = 2tz # 2tzv/q Changing variables to t > t/q — p? + pz and taking the limit q > 1, R − ρ cos θ sin2 θ = −∞ dt α πΛ exp − ∆(t, z) 2Λ2 (κ − t) z (96) Where with this change of variables, Λ = q sin2 θ − R2 − ρ2 + 2ρR cos θ (97) A(t, z) = 2? (om + cos? 6 — 2pR cos @) + 2tz(Rcos@ — p) + t? sin? 6 (98) # Derivative wrt q, _ (92 2 sos 2 -_ _p q-—(p° +R 2pRcos6)/sin 2 = fat f azn) K— t/q er pz t 2(1 — q) us (1 —q)3/ VI-qVq-P? (99) 2 (n-1 q— P? ~ p2) 2 W-@ 2 x exp (100) (R — pcos) (t/q — p? + pz) + qzcos@ — pRz _ _ pe | ( ) a { Rotva= PP?) oy Ve =o (p? — qsin? 9 + R? — 2pR cos 6) vig √ t(R−ρ cos θ) UR=p008) 4 5 Gog . . V2a (~ 2/q-e* © ((q— p?) sin? 6 + A?) P(t, z) - a _ (102) mT \ V2/(q— p?)A 2V2 (p? — q)*? 8 vI-q 2(q— p?) AM? 2 (103) 2 . _ pe (R= pcos@) (t/q — p? + pz) + qzcos 0 — pRz 2 x log (» (: iva—P “)) exp ( ( ) ) t (103) Where I(t, z) = (R — pcos 6) (tva pt p2) + qzcos@ — pRz. After integating by parts, √ aexp ( — 2ty/q—p? (pz—K)—(p?-1) 1? +(«—pz)? q— (p? + R? — 2pRcos6)/ sin? 0 Pp 2a) xa — @ dt | dzp(z) - 5 ; k—ty/q—p2—pz 4nH ( (104) √ natVa=pe—pz) x2 an ) ul — T(t, z) (105) T (q—p?yA 29 Changing variables to t > t/q — p? + pz and taking the limit q > 1, (t=pz)? 2 pope. ~3G=e7 2 ear Zee a4 | dte n( T(t, 2) Jn 1?) (106) sin? 6 oo V27\/1 = p? V1- per Where now Γ(t, z) = z(ρR − cos θ) − t(R − ρ cos θ). # Derivative wrt ρ, et__)exp _ (not 2)" 2) (Pes p—Rcosé Qa qe “ 2 2(1—q) 2 q—peA (1-4q) sin?0 9 Qn ~ n—t/q=p2—pz vI—~qH — Vi-q (107) aa (-- a) - (tVa— 0? + pz) cos @ — Rz v2Vq— pA T (108) _ (—2pA? — (q — p?) (2p — 2Rcos 6)) T(t, ?) 2/2 (q- py? AB (109) fil Kk — t/q — p? — pz T(t, z)? (ra woe (Sr ( Vita )) os (-a sae 2 (110) Integrating the second term by parts, 2 a 2) exp (ree) at) 9 (ne p—Rcos@ a a-P? ata) va-pe (1—4q) sin?@0-7 K—ty/q—p?—pz vi — gH | a= (111) a A(t, z) pR—qcosé 7A XP 22 q-p? (112) Changing variables to t > t/q — p? + pz and taking the limit q > 1, (t—pz)? p—Rcosé ( * e 20-67) ( T(t, z) ) (4) ——7— = 2a dt ——— H K-t sin? 6 oo VinvV/1— p? V1- pea 1-” ( ) (113) -toro(-S4) (aS), (114) So together we have three saddle point equations: 30 R 0 (t, a A dt exp ol “) (K — 0) (115) p? + R? — 2pRcosd T(t, z) 1 FER PR eos _ 9g af [ae coor vee rn yy (116) Vorv i tt - p- p Roos _» 2a( fare eo Bae (se J\(= sin? Vi-p 2A (117) en( 8a) (ta Where A= Vani Bo aptows (119) I(t, z) = z(pR — cos 0) — t(R — pcos 8), (120) A(t, 2) = 2 (p? + cos? 6 — 2pRcos 9) + 2tz(Rcos@ — p) + t sin? 0. (121) Solving these equations numerically yields an excellent fit to numerical simulations on structured data (Fig. 2BCD). # B Model training method details & dataset information Perceptron in the teacher-student setting All code to reproduce these simulations can be found at: https://colab.research.google.com/drive/1in35C6jh7y_ynwuWLBmGOWAgmUgpl8dF? usp=sharing. Perceptrons were trained on a synthetic dataset of P examples {xµ, yµ}µ=1,...,P , where xµ ∼ N (0, IN ) are i.i.d. zero mean unit variance random Gaussian inputs, and yµ = sign(T·x) are labels generated by a teacher perceptron T ∈ RN , which was randomly drawn from a uniform distribution on the sphere T ∼ Unif(SN −1( N )). For all of our experiments we fixed N = 200 and set P = αN where α varied between 100.1 and 100.5. Each synthetic dataset was pruned to keep a fraction f of the smallest-margin examples, where f varied between 0.1 and 1 in Fig. 1 and between 0.2 and 1 in Figs. 2,3 to match the real-world experiments in Fig. 3. Perceptrons were optimized to find the max-margin separating solution using a standard quadratic programming (QP) algorithm from the CVXPY library (for analysis of the computational complexity of this algorithm see Fig. 8). Results were averaged over 100 independent draws of the teacher and training examples. ImageNet. ImageNet model training was performed using a standard ResNet-50 through the VISSL library [41] (stable version v0.1.6), which provides default configuration files for supervised ResNet- 50 training (accessible here; released under the MIT license). Each model was trained on a single node of 8 NVIDIA V100 32GB graphics cards with BATCHSIZE_PER_REPLICA = 256, using the Stochastic Gradient Descent (SGD) optimizer with a base learning rate = 0.1, nesterov momentum = 0.9, and weight decay = 0.001. For our scaling experiments (Fig. 3 and Fig. 9), we trained one model per fraction of data kept (0.1-1.0) for each dataset size. In total, these plot required training 97 models on (potentially a subset of) ImageNet. All the models were trained with matched number of iterations, corresponding to 105 epochs on the full ImageNet dataset. The learning rate was decayed by a factor of 10 after the number of iterations corresponding to 30, 60, 90, and 100 epochs on the full ImageNet dataset. For our main ImageNet experiments (Fig. 5) we trained one model per fraction of data kept (1.0, 0.9, 0.8, 0.7, 0.6) × metric (11 metrics in total). In the plot itself, since any variation in the “fraction of data kept = 1.0” setting is due to random variation across runs not due to potential metric differences, we averaged model performances to obtain a single datapoint here (while also keeping track of the variation across models, which is plotted as ±2 standard deviations). In total, this plot required training 55 models on (potentially a subset of) ImageNet. For Fig. 5C, in order to reduce noise from random variation, we additionally trained five models per datapoint and metric, and plot the averaged performance in addition to error bars showing one standard deviation 31 of the mean. Numerical results from Figure 5BC are available from Table 1. ImageNet [42] is released under the ImageNet terms of access. It is important to note that ImageNet images are often biased [43, 44]. The SWaV model used to compute our prototypicality metrics was obtained via torch.hub.load(‘facebookresearch/swav:main’, ‘resnet50’), which is the original model provided by [36]; we then used the avgpool layer’s activations. Fraction of data kept metric 0.9 0.8 0.7 0.6 random memorization supervised prototypes self-supervised prototypes DDD EL2N (1 model) EL2N (20 models) active learning forgetting influence max influence sum-abs 89.882 90.664 90.528 90.466 89.060 90.310 89.698 90.314 90.120 89.804 90.224 89.108 89.837 89.358 89.46 88.682 89.818 90.352 89.334 89.486 88.684 88.618 88.206 89.032 88.925 88.547 88.484 88.476 88.674 89.360 89.112 88.062 88.082 89.816 90.209 90.076 90.245 89.428 90.534 90.348 90.354 90.352 90.590 89.558 Table 1: Benchmark table of pruning results (top-5 ImageNet validation accuracy) corresponding to Figure 5BC. Values for ResNet-50 trained with VISSL (baseline unpruned top-5 accuracy: 90.848). CIFAR-10 and SVHN. CIFAR-10 and SVHN model training was performed using a standard ResNet-18 through the PyTorch library. Each model was trained on a single NVIDIA TITAN Xp 12GB graphics card with batch size = 128, using the Stochastic Gradient Descent (SGD) optimizer with learning rate = 0.1, nesterov momentum = 0.9, and weight decay = 0.0005. Probe models were trained for 20 epochs each for CIFAR-10 and 40 epochs each for SVHN. Pruning scores were then computed using the EL2Ns metric [10], averaged across 10 independent initializations of the probe models. To evaluate data pruning performance, fresh models were trained from scratch on each pruned dataset for 200 epochs, with the learning rate decayed by a factor of 5 after 60, 120 and 160 epochs. Data pruning for transfer learning. To assess the effect of pruning downstream finetuning data on transfer learning performance, vision transformers (ViTs) pre-trained on ImageNet21k were fine-tuned on different pruned subsets of CIFAR-10. Pre-trained models were obtained from the timm model library [45]. Each model was trained on a single NVIDIA TITAN Xp 12GB graphics card with batch size = 128, using the Adam optimizer with learning rate = 1e-5 and no weight decay. Probe models were trained for 2 epochs each. Pruning scores were then computed using the EL2Ns metric [10], averaged across 10 independent random seeds. To evaluate data pruning performance, pre-trained models were fine-tuned on each pruned dataset for 10 epochs. To assess the effect of pruning upstream pretraining data on transfer learning performance, each of the ResNet-50s pre-trained on pruned subsets of ImageNet1k in Fig. 3D was fine-tuned on all of CIFAR-10. Each model was trained on a single NVIDIA TITAN Xp 12GB graphics card with batch size = 128, using the RMSProp optimizer with learning rate = 1e-4 and no weight decay. Probe models were trained for 2 epochs each. Pruning scores were then computed using the EL2Ns metric [10], averaged across 10 independent random seeds. To evaluate data pruning performance, pre-trained models were fine-tuned on each pruned dataset for 10 epochs. # C Breaking compute scaling laws via data pruning Do the savings in training dataset size we have identified translate to savings in compute, and can data pruning be used to beat widely observed compute scaling laws [2, 5, 7]? Here we show for the perceptron that data pruning can afford exponential savings in compute, and we provide preliminary evidence that the same is true for ResNets trained on CIFAR-10 and ImageNet. We repeat the perceptron learning experiments in Fig. 1A, keeping track of the computational complexity of each experiment, measured by the time to convergence of the quadratic programming algorithm used to 32 A Perceptron in teacher-student setting Bo ResNet18 on CIFAR-10 Cc ResNet50 on ImageNet —Theory @ Simulation Frac. data kept Frac. data kept & Frac. data kept RZ | 20% BJ e 20% = © 100% = = S104 0 77% 5 5 je 20% a © 60% 5 ° 5 [ea 2 © 46% | © 50% | ©50% & © 36% en 2 | @ 60% Pareto peed fee 10° 4 @ 70% © 70% frontier © 17% oe © 80% Pareto | © 80% © 13% © 90% frontier © 90% © 10% @ 100% @ 100% 2x10 3xio™ 4x10 10" 10° 10° 10° 0 Compute (clock time in seconds) Compute (FLOPs) Compute (FLOPs) D ResNet18 on CIFAR-10 E ResNet50 on Imagenet 2.004 — 100% 00 — 100% 175 — 92% — 60% 1504 — 20% 80 — 10% 60% 1254 60 1.00 Test loss 0754 40 Test error (top-5 %) oso 20 0254 0 20 40 60 80 100 Epoch Figure 8: Breaking compute scaling laws via data pruning. A,B,C, We repeat the experiments in Figs. 1A, 3C,D, replacing the x-axis with compute, measured as clock time to convergence for the perceptron (A), and FLOPs in a fixed-epoch training setting for the ResNets (B,C). Theoretical curves in A are overlaid by linearly regressing clock time to convergence T from αprune, with T = 0.96αprune + 0.80. Perceptrons in A are trained on a CPU on a google Colab. E,D, CIFAR-10 and ImageNet learning curves for fixed epochs. find a max-margin solution (see B for details). Across all experiments, the convergence time T was linearly proportional to αprune with T = 0.96αprune + 0.80, allowing us to replace the x-axis of 1A with compute to produce Fig. 8A, which reveals that data pruning can be used to break compute scaling laws for the perceptron. Motivated by this, we next investigate whether the convergence time of neural networks trained on pruned datasets depends largely on the number of examples and not their difficulty, potentially allowing for exponential compute savings. We investigate the learning curves of a ResNet18 trained on CIFAR-10 and a ResNet50 on ImageNet for several different pruning fractions (Fig. 8B). While previous works have fixed the number of iterations [10], here we fix the number of epochs, so that the model trained on 60% of the full dataset is trained for only 60% the iterations of the model trained on the full dataset, using only 60% the compute. Nevertheless, we find that the learning curves are strikingly similar across pruning fractions, and appear to converge equally quickly. These results suggest that data pruning could lead to large compute savings in practical settings, and in ongoing experiments we are working to make the analogs of Fig. 8A for ResNets on CIFAR-10 and ImageNet to quantify this benefit. # D Additional scaling experiments In Fig. 9 we perform additional scaling experiments using the EL2Ns and self-supervised prototypes metrics. In Fig. 10 we give a practical example of a cross over from exponential to power-law scaling when the probe student has limited information about the teacher (here a model trained for only a small number of epochs on SVHN) . # E Extremal images according to different metrics In Fig. 6, we showed extremal images for two metrics (self-supervised prototypes, memorization) and a single class. In order to gain a better understanding of how extremal images (i.e. images that are 33 Self-supervised prototypes A EL2Ns (0% class balancing) B EL2Ns (50% class balancing) Cc (50% class balancing) & Frac. data kept z Frac. data kept & Frac. data kept s 8 © 100% ig © 100% & & © 77% o © 77% 3 % © 60% g © 60% o & © 46% & © 46% 2 Pareto a © 36% Pareto 2 © 36% e frontier e © 28% frontier e © 28% lend 10 go’ | © 22% jo’ | © 22% © 17% © 17% © 13% © 13% © 10% © 10% 10° 10° 10° 10° 10° 10° 10° 10° 10° Num examples Num examples Num examples Figure 9: Additional scaling experiments. We reproduce the scaling results on ImageNet in Fig. 3D using three additional metrics: two supervised and one self-supervised. Each shows some signatures of breaking power law scaling, although the effect is less dramatic than for the best metric, memorization (Fig. 3D). (A) EL2Ns with a class balancing fraction of 0% (see App. Section H for details), (B) EL2Ns with a class balancing fraction of 50%, and (C) Self-supervised prototypes with a class balancing fraction of 50%. A SVHN (epoch 4) B SVHN (epoch 40) 10° 10° 7% om aimee 3% 32% —e @ 3% © 3% ose oo o 8% 3 om om Pare 3 22% 3 20% = o3e% | 3 36% S ocx | & 60% Si & tox | S10 @ t00% Q Q | ee l ba wm . Q ss Q . ss ~ 10°? Error lower-bounded i 107? Error no longer = < by:power law at fmnin ss] lower-bounded 7” lees 10° 108 10° 10° 108 10° Training examples P Training examples P Figure 10: Consistent with a prediction from the perceptron theory (Fig. 2), when SVHN is pruned using a weak metric (a probe trained for only 4 epochs), the learning curve envelope is lower-bounded by a power law at some fmin (A). However, with a stronger pruning metric (a probe trained for 40 epochs), the learning curve can break through this power law to achieve lower generalization error (B). easiest or hardest to learn according to different metrics) look like for all metrics and more classes, we here provide additional figures. In order to avoid cherry-picking classes while at the same time making sure that we are visualizing images for very different classes, we here show extreme images for classes 100, ..., 500 while leaving out classes 0 and 400 (which would have been part of the visualization) since those classes almost exclusively consist of images containing people (0: tench, 400: academic gown). The extremal images are shown in Figures 12,13,14,15,16,17,18,19. 34 A Teacher-student perceptron B ResNet18 on SVHN 10° 5 — Empirical frontier me c- 7? — c-exp(—ba) g Sid 5 ao! 8 g 04 q g \ 3 g 2 — cat — c-exp(-ba) 10-2 4 — c-(ba)! — © ((ba)!)! 0 0 02 0 3 o4 O58 2x10 3x10 10° 10 10’ 10 Qprune Training examples Figure 11: Scaling of the Pareto frontier. (A) Different functional forms fitted to the Pareto frontier of the teacher-student perceptron using least squares: power-law (blue), exponential (orange), factorial (red), and iterated factorial (purple). (B), We estimate the empirical Pareto frontier (red) for ResNet18 on SVHN at higher resolution by training an additional 300 models in the region around the frontier. We then fit two functional forms to the empirical frontier using least squares: power-law (dark red) and exponential (pink). The exponential shows a much better fit to the empirical Pareto frontier, indicating that the scaling is at least exponential. 35 random influence sum-abs hai self-supervised prototypes random influence sum-abs hai self-supervised prototypes Figure 12: Extreme images according to different metrics for ImageNet class 100 (black swan). For each metric, the top row shows images that are ranked as “easy” (most pruneable) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 36 easy EL2N (20 models) hard easy memorization hard asy active learning hard easy forgetting hard easy EL2N (20 models) hard easy memorization hard asy active learning hard easy forgetting hard Figure 13: Extreme images according to different metrics for ImageNet class 100 (black swan). For each metric, the top row shows images that are ranked as “easy” (most pruneable) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 37 easy self-supervised prototypes hard easy self-supervised prototypes hard Figure 14: Extreme images according to different metrics for ImageNet class 200 (Tibetan terrier). For each metric, the top row shows images that are ranked as “easy” (most prune- able) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 38 easy EL2N (20 models) active learning easy EL2N (20 models) active learning Figure 15: Extreme images according to different metrics for ImageNet class 200 (Tibetan terrier). For each metric, the top row shows images that are ranked as “easy” (most prune- able) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 39 easy hard self-supervised prototypes supervised prototypes easy hard self-supervised prototypes supervised prototypes Figure 16: Extreme images according to different metrics for ImageNet class 300 (tiger beetle). For each metric, the top row shows images that are ranked as “easy” (most pruneable) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 40 hard hard easy EL2N (20 models) hard easy hard active learning hard easy EL2N (20 models) hard easy hard active learning hard Figure 17: Extreme images according to different metrics for ImageNet class 300 (tiger beetle). For each metric, the top row shows images that are ranked as “easy” (most pruneable) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 41 self-supervised prototypes supervised prototypes self-supervised prototypes supervised prototypes Figure 18: Extreme images according to different metrics for ImageNet class 500 (cliff dwelling). For each metric, the top row shows images that are ranked as “easy” (most pruneable) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 42 EL2N (20 models) easy hard easy active learning hard EL2N (20 models) easy hard easy active learning hard Figure 19: Extreme images according to different metrics for ImageNet class 500 (cliff dwelling). For each metric, the top row shows images that are ranked as “easy” (most pruneable) according to the metric, and the bottom row shows images that are ranked as “hard” (least pruneable). 43 # F Impact of number of clusters k on self-supervised prototypes Our self-supervised prototype metric is based on k-means clustering, which has a single hyperparam- eter k. By default and throughout the main paper, we set k = 1000, corresponding to the number of classes in ImageNet. Here, we investigate other settings of k to understand how this hyperparameter impacts performance. As can be seen in Table 2, k does indeed have an impact on performance, and very small values for k (e.g. k < 10) as well as very large values for k (e.g. k = 50, 000) both lead to performance impairments. At the same time, performance is relatively high across very different in-between settings for k. In order to assess these results, it may be important to keep in mind that ±0.54% corresponds to plus/minus 2 standard deviations of performance when simply training the same model multiple times (with different random initialization). Overall, these results suggest that if the number of clusters k deviates at most by one order of magnitude from the number of classes in the dataset (for ImageNet-1K), the exact choice of k does not matter much. # k 1 5 10 50 100 200 400 600 800 # 1K 5K 10K 50K k 1 5 10 50 100 200 400 600 800 1K 5K 10K 50K acc 88.35 89.09 88.76 89.04 89.48 90.27 89.85 89.96 90.44 90.56 90.33 90.57 88.67 Table 2: Performance (top-5 accuracy, denoted as acc) when pruning away 20% of ImageNet according to our self-supervised prototype metric as a function of the number of prototypes k (hyperparameter used for self-supervised clustering indicating the number of clusters). Results based on training a ResNet-50 architecture with VISSL without class balancing. # G Impact of ensemble prototypes The self-supervised prototypes metric is based on k-means clustering in the embedding space of a self- supervised (=SSL) model. Since even otherwise identical models trained with different random seeds can end up with somewhat different embedding spaces, we here investigated how the performance of our self-supervised prototypes metric would change when averaging the scores derived from five models, instead of just using a single model’s score. The results, shown in Table 3, indicate that ensembling the self-supervised prototype scores neither improves nor hurts performance. This is both good and bad news: Bad news since naturally any improvement in metric development leads to better data efficiency; on the other hand this is also good news since ensembles increase the computational cost of deriving the metric—and this suggests that ensembling is not necessary to achieve the performance we achieved (unlike in other methods such as ensemble active learning). Fraction of data kept 0.9 0.8 0.7 score from single model score from ensemble model 90.03 89.93 90.10 90.40 89.38 89.38 Table 3: Performance (top-5 acuracy) when pruning away 10%, 20% or 30% of ImageNet based on the self-supervised prototype metric derived from either a single SSL model, or an ensemble of SSL models. Supervised model training on the pruned dataset was performed with a ResNet-50 architecture trained using VISSL without class balancing. Overall, we do not observe any performance difference between the two settings: the differences are still well within a single standard deviation of training multiple models with identical settings. In order to reduce the influence of random variations, each data point in this table shows the average of four independent runs. # H Relationship between pruning and class (im-)balance Motivation. It is well-known that strong class imbalance in a dataset is a challenge that needs to be addressed. In order to understand the effect of pruning on class (im-)balance, we quantified this relationship. For context, if pruning according to a certain metric preferentially leads to discarding most (or even all) images from certain classes, it is likely that the performance on those classes will drop as a result if this imbalance is not addressed. 44 Class imbalance metric: pruning amplifies class imbalance. Since a standard measure of class (im-)balance—dividing the number of images for the majority class by the number of images for the minority class—is highly sensitive to outliers and discards information about the 998 non-extreme ImageNet classes, we instead calculated a class balance score b ∈ [0%, 100%] as the average class imbalance across any two pairs of classes by computing the expectation over taking two random classes, and then computing how many images the minority class has in proportion to the majority class. For instance, a class balance score of 90% means that on average, when selecting two random classes from the dataset, the smaller of those two classes contains 90% of the number of images of the larger class (higher=better; 100% would be perfectly balanced). In Fig. 20, we observe that dataset pruning strongly increases class imbalance. This is the case both when pruning away easy images and when pruning away hard images, and the effect occurs for all pruning metrics except, of course, for random pruning. Class imbalance is well-known to be a challenge for deep learning models when not addressed properly [46]. The cause for the amplified class imbalance is revealed when looking at class-conditional differences of metric scores (Figs. 22 and 23): The histograms of the class-conditional score distributions show that for many classes, most (if not all) images have very low scores, while for others most (if not all) images have very high scores. This means that as soon as the lowest / highest scoring images are pruned, certain classes are pruned preferentially and thus class imbalance worsens. We thus use 50% class balancing for our ImageNet experiments. This ensures that every class has at least 50% of the images that it would have when pruning all classes equally (essentially providing a fixed floor for the minimum number of images per class). This simple fix is an important step to address and counteract class imbalance, although other means could be used as well; and ultimately one would likely want to use a self-supervised version of class (or cluster) balancing when it comes to pruning large-scale unlabeled datasets. For comparison purposes, the results for ImageNet pruning without class balancing are shown in supplementary Fig. 21. 45 (a) random (b) influence max (c) influence sum-abs (d) self-supervised prototypes (e) supervised prototypes (f) EL2N (1 model) (g) DDD (h) EL2N (20 models) (i) memorization # (j) active learning # (k) forgetting Figure 20: Pruning amplifies class imbalance. With larger pruning fractions, class balance decreases— both when pruning “easy” images (turquoise) and when pruning “hard” images (orange). This effect occurs for all pruning metrics except for random pruning (top left). For details on the class imbalance metric see Appendix H. Pruning fraction refers to the fraction of data pruned, from 0 (no pruning) to 0.9 (keeping only 10% of the data). 46 random pruning DDD EL2N (1 model) EL2N (20 models) self-supervised prototypes supervised prototypes active learning forgetting influence max influence sum-abs memorization no pruning (+-2 std) Accuracy (%) 8 8 0 © © Ss letetdittete 1.0 0.95 09 0.85 08 0.75 07 0.65 06 Frac. data kept Figure 21: ImageNet-1K pruning results for different metrics, compared against random pruning. ‘Pruning fraction’ refers to the fraction of the dataset that is pruned away. Results obtained without any class balancing are worse than results with 50% class balancing (Fig. 5BC), confirming the finding that vanilla pruning amplifies class imbalance. 47 Figure 22: How do ImageNet metric scores differ across classes? Class-conditional score distribution histograms across metrics. For the purpose of visualization, only every 10th class is shown. 48 DDD emeaiioboand ton Ae PLU EU ELE LEETEECTETeererererres gee EETEEETECECSTETETErers EST ELETESTETETereerer * Gass rank memorization nen EF EL EES ES EEE ahee} ace ra ae FS ESTEFESTELELLS SSCS LELELESE ET EL ET ESTES Ts 8 active learning £ & & & A sasresoimnmrnese *SARSSIRSAISHALSLE RSA RAAT RAE ARATRITSIAA SSF aahee} aes ra ae ESET EPEECECSESI ESTELLE) Tenis 9823 THe re *SARSSIRSAISHALSLE RSA RAAT RAE ARATRITSIAA SSF aahee} aes ra ae ESET EPEECECSESI ESTELLE) Tenis 9823 THe re Figure 23: How do ImageNet metric scores differ across classes (continued)? Class-conditional score distribution histograms across metrics. For the purpose of visualization, only every 10th class is shown. Please note that the active learning plot is to be taken with a grain of salt since the authors provided a binary score (included/excluded) for ImageNet corresponding to 80% “important” images, thus the scores are either zero or one and a boxplot fit does not apply here. 49 # I Effect of pruning on class-conditional accuracy and fairness In order to study the effect of dataset pruning on model fairness, at least with respect to specific ImageNet classes, we compared the class-conditional accuracy of a ResNet-50 model trained on the full ImageNet dataset, versus that of the same model trained on an 80% subset obtained after pruning. We used two supervised pruning metrics (EL2N, memorization) and one self-supervised pruning metric (self-supervised prototypes) for obtaining the pruned dataset. In all three cases, and across all 1000 classes, we found that the class-conditional accuracy of the model trained on a pruned subset of the dataset remains quite similar to that of the model trained on the full dataset (Fig. 24). However, we did notice a very small reduction in class-conditioned accuracy for ImageNet classes that were least accurately predicted by models trained on the entire dataset (blue lines slightly above red unity lines when class-conditioned accuracy is low). This suggests that pruning yields a slight systematic reduction in the accuracy of harder classes, relative to easier classes, though the effect is small. While we have focused on fairness with respect to individual ImageNet classes, any ultimate test of model fairness should be conducted in scenarios that are specific to the use case of the deployed model. Our examination of the fairness of pruning with respect to individual ImageNet classes constitutes only an initial foray into an exploration of fairness, given the absence of any specific deployment scenario for our current models other than testing them on ImageNet. We leave a full exploration of fairness in other deployment settings for future work. (a) EL2N (20 models) (b) Memorization (c) Self-supervised prototypes Figure 24: The effect of data pruning on ImageNet test accuracy on individual classes. For all 3 plots, each point corresponds to an ImageNet class, and for all classes, the class specific test accuracy when training on the entire dataset (y-axis) is plotted against the test accuracy when training on the pruned dataset (x-axis). # Interaction between data pruning and training duration Throughout the main paper, our ImageNet experiments are based on a setting where the number of training epochs is kept constant (i.e. we train the same number of epochs on the smaller pruned dataset as on the larger original dataset). This means that data pruning directly reduces the number of iterations required to train the model specifically by reducing the size of the dataset. However, this simultaneously places two constraints on model performance: not only training on a smaller data set, but also training for fewer iterations. We therefore investigate how model performance changes if we train longer, as quantified by a matched iterations factor. A matched iterations factor of 0 corresponds to the default setting used in the paper of training for the same number of epochs (so that a smaller dataset means proportionally fewer training iterations). In contrast a matched iterations factor of 1 corresponds to training on the smaller pruned dataset for a number of iterations equal to that when training on the larger initial dataset (e.g. when pruning away 50% of the dataset one would train twice as long to match the number of iterations of a model trained on 100% of the dataset). Otherwise the matched iterations factor reflects a linear interpolation in the number of training iterations as the factor varies between 0 and 1. 50 The results are shown in Table 4 and indicate that training longer does indeed improve performance slightly; however, a matched iterations factor of around 0.4–0.6 may already be sufficient to reap the full benefit. Any matched iterations factor strictly smaller than 1.0 comes with reduced training time compared to training a model on the full dataset. matched iterations factor 0.0 0.2 0.4 0.6 0.8 1.0 ImageNet top-5 accuracy 90.20 90.48 90.56 90.45 90.50 90.41 Table 4: Comparing different settings for training longer when pruning: Performance (top-5 acuracy) when pruning away 20% of ImageNet based on our self-supervised prototype metric. Supervised model training on the pruned dataset performed with a ResNet-50 architecture trained using VISSL without class balancing. Performance tends to increase when training longer (i.e. with a larger matched iterations factor). Interestingly, the benefit of training longer may already be achieved with a matched iterations factor of around 0.4–0.6. # K Out-of-distribution (OOD) analysis of dataset pruning Pruning changes the data regime that a model is exposed to. Therefore, a natural question is how this might affect desirable properties beyond IID performance like fairness (see Appendix I) and out-of-distribution, or OOD, performance which we investigate here. To this end, we use the model-vs- human toolbox [47] based on data and analyses from [48, 49, 50, 51, 52]. This toolbox is comprised of 17 different OOD datasets, including many image distortions and style changes. In Figure 25a, OOD accuracies averaged across those 17 datasets are shown for a total of 12 models. These models all have a ResNet-50 architecture [53]. Two baseline models are trained on the full ImageNet training dataset, one using torchvision (purple) and the other using VISSL (blue). Human classification data is shown as an additional reference in red. The remaining 10 models are VISSL- trained on pruned versions of ImageNet using pruning fractions in {0.1, 0.2, 0.3, 0.4, 0.5} and our self-supervised prototype metric. A pruning fraction of 0.3 would correspond to “fraction of data kept = 0.7”, i.e. to training on 70% of ImageNet while discarding the other 30%. We investigated two different settings: discarding easy examples (the default used throughout the paper), which is denoted as “Best Case” (or BC) in the plots; and the reverse setting, i.e. discarding hard examples denoted as Worst Case, or WC. (These terms should be taken with a grain of salt; examples are only insofar best- or worst case examples as predicted by the metric, which itself is in all likelihood far less than perfect.) The results are as follows: In terms of OOD accuracy (Figure 25a), best-case pruning in green achieves very similar accuracies to the most relevant baseline, the blue ResNet-50 model trained via VISSL. This is interesting since oftentimes, OOD accuracies closely follow IID accuracies except for a constant offset [54], and we know from Figure 5 that the self-supervised prototype metric has a drastic performance impairment when pruning away 40% of the data, yet the model “BC_pruning-fraction-0.4” still achieves almost the same OOD accuracy as the baseline trained on the full dataset. The core take-away is: While more analyses would be necessary to investigate whether pruning indeed consistently helps on OOD performance, it seems safe to conclude that it does not hurt OOD performance on the investigated datasets compared to an accuracy- matched baseline. (The control setting, pruning away hard examples shown in orange, leads to much lower IID accuracies and consequently also lower OOD accuracies.) For reference, the numerical results from Figure 25a are also shown in Table 5. Figures 25b, 25c and 25d focus on a related question, the question of whether models show human- like behavior on OOD datasets. Figure 25b shows that two models pruned using our self-supervised prototype metric somewhat more closely match human accuracies compared to the baseline in blue; Figures 25c and 25d specifically focus on image-level consistency with human responses. In terms of overall consistency (c), the baseline scores best; in terms of error consistency pruned models outperform the VISSL-trained baseline. For details on the metrics we kindly refer the interested reader to [47]. Numerical results are again also shown in a Table (Table 6). Finally, in Figure 26 we observe that best-case pruning leads to slightly higher shape bias as indicated by green vertical lines plotting the average shape bias across categories, which are shifted to the left 51 of the baseline; while worst-case pruning in orange is shifted to the right. An outlier is the torchvision- trained model in purple with a very strong texture bias; we attribute this to data augmentation differences between VISSL and torchvision training. 0D accuracy accuracy difference (a) OOD accuracy (higher = better). (b) Accuracy difference (lower = better). observed consistency # error consistency (c) Observed consistency (higher = better). (d) Error consistency (higher = better). Figure 25: OOD benchmark results for different models, aggregated over 17 datasets. All models have a ResNet-50 architecture [53]. Two baseline models are trained on the full ImageNet training dataset, one using torchvision (purple) and the other using VISSL (blue). Human comparison data is shown in red. # Table 5: Benchmark table of model results for highest out-of-distribution robustness. model OOD accuracy ↑ rank ↓ ResNet-50 (VISSL) BC_pruning-fraction-0.3 BC_pruning-fraction-0.4 BC_pruning-fraction-0.1 BC_pruning-fraction-0.2 WC_pruning-fraction-0.1 BC_pruning-fraction-0.5 ResNet-50 (torchvision) WC_pruning-fraction-0.2 WC_pruning-fraction-0.3 WC_pruning-fraction-0.4 WC_pruning-fraction-0.5 0.582 0.578 0.574 0.574 0.565 0.565 0.560 0.559 0.556 0.540 0.516 0.498 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000 9.000 10.000 11.000 12.000 52 Table 6: Benchmark table of model results for most human-like behaviour. The three metrics “accuracy difference” “observed consistency” and “error consistency” (plotted in Figure 25) each produce a different model ranking. model accuracy diff. ↓ obs. consistency ↑ error consistency ↑ mean rank ↓ BC_pruning-fraction-0.3 ResNet-50 (VISSL) BC_pruning-fraction-0.5 BC_pruning-fraction-0.4 WC_pruning-fraction-0.1 ResNet-50 (torchvision) BC_pruning-fraction-0.1 WC_pruning-fraction-0.2 BC_pruning-fraction-0.2 WC_pruning-fraction-0.3 WC_pruning-fraction-0.4 WC_pruning-fraction-0.5 0.075 0.077 0.077 0.078 0.082 0.087 0.079 0.086 0.084 0.088 0.099 0.108 0.671 0.671 0.666 0.670 0.666 0.665 0.671 0.658 0.660 0.652 0.635 0.623 0.194 0.184 0.190 0.187 0.191 0.208 0.182 0.186 0.175 0.183 0.169 0.165 1.667 3.667 4.000 4.333 4.667 5.667 5.667 7.667 8.333 9.333 11.000 12.000 < Fraction of 'shape' decisions 1 09 08 07 06 05 04 03 02 01 O | it 1 | | 1 | | 1 [=] o ¢ @m Ad @ ae, o 200A fal od Hom Md @ emes y o A4@ eo 6 ¢ @ omee os 2 ial ¢ Ac @ A c ¢ @A OO O° | ' A o [e\¢ comma 8 4 a ? e@ @@ © [am | @oa A [0] @ eomeeera [i] > @o|| ee a A [2] | cam A [ga] > @ epoca” || rN 0 O1 02 03 04 05 06 0.7 08 09 E Fraction of ‘texture’ decisions Figure 26: Shape vs. texture bias [50]: category-level plot. Horizontal lines indicate average shape/texture bias; values to the left lean towards a shape bias while values to the right lean towards a texture bias. For details on the plot see [50]; model colors are identical to Figure 25. 53
Title: Conversational Question Reformulation via Sequence-to-Sequence Architectures and Pretrained Language Models: Summary: This paper presents an empirical study of conversational question reformulation (CQR) with sequence-to-sequence architectures and pretrained language models (PLMs). We leverage PLMs to address the strong token-to-token independence assumption made in the common objective, maximum likelihood estimation, for the CQR task. In CQR benchmarks of task-oriented dialogue systems, we evaluate fine-tuned PLMs on the recently-introduced CANARD dataset as an in-domain task and validate the models using data from the TREC 2019 CAsT Track as an out-domain task. Examining a variety of architectures with different numbers of parameters, we demonstrate that the recent text-to-text transfer transformer (T5) achieves the best results both on CANARD and CAsT with fewer parameters, compared to similar transformer architectures. # Conversational Question Reformulation via Sequence-to-Sequence Architectures and Pretrained Language Models Sheng-Chieh Lin∗1, Jheng-Hong Yang∗1, Rodrigo Nogueira2, Ming-Feng Tsai1, Chuan-Ju Wang1 and Jimmy Lin2 1Research Center for Information Technology Innovation, Academia Sinica 2David R. Cheriton School of Computer Science, University of Waterloo # Abstract This paper presents an empirical study of conversational question reformulation (CQR) with sequence-to-sequence architectures and pretrained language models (PLMs). We lever- age PLMs to address the strong token-to-token independence assumption made in the com- mon objective, maximum likelihood estima- tion, for the CQR task. In CQR benchmarks of task-oriented dialogue systems, we evaluate fine-tuned PLMs on the recently-introduced CANARD dataset as an in-domain task and validate the models using data from the TREC 2019 CAsT Track as an out-domain task. Ex- amining a variety of architectures with dif- ferent numbers of parameters, we demon- strate that the recent text-to-text transfer trans- former (T5) achieves the best results both on CANARD and CAsT with fewer parameters, compared to similar transformer architectures. # Introduction Natural-language dialogue capabilities play an es- sential role as an enabling technology in intelligent personal assistants to understand and connect peo- ple (Gao et al., 2018). Effective dialogue systems require many components, including natural lan- guage understanding, dialogue state tracking, and natural language generation (Zhao and Eskenazi, 2016). Of late, practitioners in industry (Ren et al., 2018) and researchers in academia (Elgohary et al., 2019) have made substantial progress in a variety of methods to improve end-to-end task-oriented dialogue systems. Original question Context Rewritten question (b) Pretrained language model (dashed lines) to augment maximum likelihood estimation Figure 1: Conversational question reformulation. present an example from Elgohary et al. (2019) in Figure 1 to illustrate the task of conversational question reformulation (CQR). However, as we can observe from Figure 1(a), applying maximum likelihood estimation (MLE) purely based on human-rewritten sentences intro- duces a strong independence assumption that does not consider conversation dependencies or linguis- tic structure. Thanks to great progress made by language models pretrained on large corpora using self-supervised learning objectives (Devlin et al., 2018; Radford et al., 2018; Dong et al., 2019; Raffel et al., 2019), there are now many mod- els equipped with knowledge of various language structures extracted from human-generated texts. We can leverage these models to relax the indepen- dence assumption in a pure MLE objective, shown in Figure 1(b). We list the contributions of this work as follows: Due to the complex and nuanced nature of hu- man communication, conversations often contain utterances that include coreference, ellipsis, and other phenomena; thus, a good dialogue system should be able to resolve these ambiguities to ac- curately reconstruct the user’s original intent. We ∗Contributed equally. • We conduct, to our knowledge, the first empiri- cal study leveraging pretrained language models to relax the independence assumption made in using an MLE objective in a CQR task. • We achieve the state of the art in terms of BLEU on two CQR benchmarks of task-oriented dia- logue systems: (a) conversational open-domain question answering with CANARD and (b) con- versational search with TREC CAsT. In summary, this work demonstrates a simple yet effective way to resolve coreference and ellipsis in a CQR task by leveraging pretrained language models. Furthermore, among representative mod- els, we find that a well-tuned text-to-text transfer transformer (T5) reaches performance that is on par with humans on the in-domain CANARD dataset and achieves the best performance on the out-of- domain CAsT dataset. # 2 Related Work Conversational search (Radlinski and Craswell, 2017) covers a broad range of techniques that facil- itate an IR task in a conversational context: nat- ural language interactions, cumulative clarifica- tion (Aliannejadi et al., 2019), feedback collection, and information needs profiling during conversa- tions. CQR is an important component of conver- sational search systems. In order to resolve users’ information needs to retrieve relevant answers, a CQR module that leverages pretrained models is a promising approach, compared to alternatives that track dialogue states based on “cheap” but noisy implicit feedback from users (Ahmad et al., 2018, 2019) or “expensive” but sparse judgments (Jeffrey et al., 2019). Open-domain question answering (QA) sys- tems return answers in response to user questions, both in natural language, from a broad range of domains (Sun et al., 2018). With great progress coming from contributions by the NLP and IR com- munities, high quality datasets for single-turn (Ra- jpurkar et al., 2018; Koˇcisk´y et al., 2018; Dhingra et al., 2017) and multi-turn (conversational) (Reddy et al., 2019; Choi et al., 2018) open-domain QA are available today. These datasets have led to many successful supervised techniques for various tasks (Chen et al., 2017; Seo et al., 2017; Huang et al., 2019). Recently, to improve dialogue understanding, re- searchers have proposed collecting annotations on resolving multi-turn dialogues in the context of question answering tasks (Ren et al., 2018; Elgo- hary et al., 2019). Building on this line of thought, our work addresses the problem of modeling ques- tion rewrites in multi-turn dialogues, especially in the context of open-domain conversational QA. # 3 Conversational Question Reformulation # 3.1 Problem Formulation We first formally define the conversational ques- tion reformulation (CQR) task, which is also called question de-contextualization (Elgohary et al., 2019) or conversational question (query) under- standing in the context of task-oriented dialogue systems (Ren et al., 2018). Consider a topic t from a set of topics T , given a topic-oriented ut- terance sequence (i.e., the conversation history): H t = {u1, · · · , ui, ui+1, · · · uN } of N utterances, each of which could be a question qi or an answer ai at the i-th turn. The task is to reformulate the question qi into ¯qi that incorporates the context H t j=1. In other words, we wish to au- tomatically reformulate the input question qi by infusing information that exists in the context H t but is missing from the question itself. Following the definitions of Ren et al. (2018) and Elgohary et al. (2019), we further refine the task scope of reformulating ¯qi. Given a question qi with its historical context H t <i and a human- rewritten ground truth ¯qi, our objective is to induce a function F ({qi, H t <i}) = ¯qi, where ¯qi is com- prised of tokens {yk}m k=1 of length m from the con- text comprising the dialogue sequence {qi, H t <i} (current and historical utterances), modeled as a se- quence of tokens {xk}n k=1 of length n. The tokens yk’s can either be drawn from the context H t <i or the current input qi. In the reconstruction of the ground truth, human annotators are asked to main- tain the sentence structure of qi by copying phrases from the original utterances and performing as few edits as possible. Finally, given probability P conditioned on a parameterized function ˆF and the context (current and historical utterances), the overall objective of the task is then defined in terms of finding the pa- rameters θ by maximum likelihood estimation: T N 0 = arg mpx TT] II Pa (@IP({a. Ed) # 3.2 Sequence-to-Sequence Architectures and Pretrained Language Models As both the input qi and the output ¯qi are posed in natural language, a reasonable choice for the para- metric function is a sequence-to-sequence (S2S) model (Sutskever et al., 2014; Vaswani et al., 2017). With this design, we can incorporate context- dependent sentence-level structures when gener- ating output tokens, since the model can consider both the previously-generated sequences as well as the context. To extract information from the conversation flow, a simple approach, proposed by Xiong et al. (2018) and Elgohary et al. (2019), is to concatenate the historical utterances H‘, with the current input q as the context [H!, || q;], and then use a S2S model to infer the output sequence q; based on it. To optimize parameters in the S2S model, we can adopt a supervised learning approach to train the S2S model to generate the g; tokens, given the qj tokens as ground truth output. However, Eq (1) makes an important assumption: here, we consider each conversation topic t and each i-th turn independently. Since a topic-oriented conversation is often coherent and smoothly spans several utterances, an approximation of the param- eterized function ˆF (·, θ) purely based on Eq (1) could be sub-optimal. To relax this assumption, we introduce pretrained language models (Devlin et al., 2018; Radford et al., 2018; Raffel et al., 2019) to leverage language structures extracted from large corpora. Specifically, we adopt these models and fine-tune their pretrained weights, as in previous work (Radford et al., 2018; Raffel et al., 2019). # 4 Experiments # 4.1 Dataset To evaluate the capability of various models in re- formulating conversational questions, we conduct experiments on the CANARD dataset (Elgohary et al., 2019), an existing large open-domain dataset for CQR (containing over 30k training samples). Each sample in the CANARD dataset includes an original query from the QuAC dataset (Choi et al., 2018), its context (historical utterances and their answers), and the corresponding rewritten question by human annotators. In addition, we also evaluate model performance on the dataset provided by the TREC 2019 Conver- sational Assistant Track (CAsT).1 CAsT organizers manually rewrote each conversational query in the evaluation set according to its contextual informa- tion and previous utterances in the same session. Statistics of the CANARD and CAsT datasets are presented in Table 1. # 1https://github.com/daltonj/ treccastweb Table 1: Statistics of the datasets used in this work. CANARD CAsT Train Dev Test 31,538 3,418 5,571 479 # 4.2 Setup To train and evaluate our sequence-to-sequence (S2S) models, we construct model input largely fol- lowing Elgohary et al. (2019). Specifically, we con- catenate each original question and its context by adding special separator tokens between them. Sep- arator tokens are also added to contextual informa- tion to separate historical utterances. The human- rewritten questions serve as the ground truth target sequences. For encoder- or decoder-only models (e.g., GPT-2, BERT, and UniLM), each training in- put sequence (as described above) is concatenated with its target sequence, and the models are trained to recover the target sequence using standard mask- ing tricks. We train each model on the CANARD training set and select the checkpoint with the best perfor- mance on development set. In addition to compar- ing model performance on the CANARD test set, we directly use the model trained on CANARD to perform CQR on the CAsT dataset.2 Model per- formance is computed by the BLEU score between model output and the human-rewritten ground truth. Table 2 shows the settings of the neural models. Additional model-specific training details are as follows. (a) LSTM: Following the script provided by Elgohary et al. (2019), we train a bidirectional LSTM S2S model with attention; the word embed- dings are initialized with GloVE.3 (b) GPT-2 (Rad- ford et al., 2018), which can be characterized as a pretrained decoder-only transformer: To focus on rewriting questions, we fine-tune the model (GPT-2 medium) by masking the cross entropy loss at the positions of the contextual tokens. (c) BERT (De- vlin et al., 2018), which can be characterized as a pretrained encoder-only transformer: Following the S2S fine-tuning procedure proposed in Dong et al. (2019), we fine-tune BERT-large (cased) by randomly masking the tokens with 70% probability in targeted sequences.4 (d) UniLM (Dong et al., 2019), where the model architecture is the same as BERT large and pretrained using three types 2Note that for CAsT, only historical questions are included as contextual information. 3https://github.com/aagohary/canard 4https://github.com/microsoft/unilm Table 2: Model settings. # parameters Learning rate Batch size LSTM GPT-2-medium BERT-large UniLM-large T5-base 46M 345M 340M 340M 220M 0.15 10−4 10−5 10−5 10−4 16 32 32 32 256 of language-modeling tasks: The method for fine- tuning is the same as BERT. (e) T5 (Raffel et al., 2019), an encoder–decoder transformer that maps natural language understanding tasks to text-to- text transformation tasks: We fine-tune the T5-base model with the same settings used in Nogueira and Lin (2019).5 In addition, we list human performance of CQR (denoted as Human), as measured by Elgohary et al. (2019), and the baseline performance using questions without any reformulation (denoted as Raw) for comparison. # 4.3 Results Our main results in terms of BLEU on CANARD and CAsT are shown in Table 3, using greedy search decoding for inference. In general, all neu- ral S2S models perform better than the original questions (Raw), except for LSTM on CAsT. This indicates that the PLMs (GPT2, BERT, UniLM, and T5) have obtained at least some generalization capability on the CQR task. Among all neural S2S models, T5 demonstrates a better ability to learn CQR from human-rewritten questions with fewer model parameters. Specifi- cally, in the CANARD test set, T5 beats the other neural S2S models with 58.08 BLEU, which is close to human performance, 59.92. Furthermore, on CAsT, T5 achieves the highest BLEU score (75.07), four points better than the second-best model (71.21). These results demonstrate T5’s superior generalization ability. In addition, we also perform S2S model infer- ence using beam search and top-k random sam- pling decoding.6 Figure 2 (left side) shows that beam search with larger beam widths further im- proves BLEU scores in both datasets. T5 with a beam width of 10 achieves a BLEU score that is on par with human performance on the CANARD test set and reaches 76.22 on CAsT.7 Figure 2 (right 5https://github.com/castorini/ docTTTTTquery 6Note that beam search (top-k random sampling) is equal to greedy search when the beam width (top-k) is set to 1 7We did not perform GPT-2 inference with beam search Table 3: BLEU score comparison. For simplicity, we compare neural S2S models using greedy search. CANARD CAsT Dev Test Human Raw 59.92 33.84 36.25 - 60.41 LSTM 43.68 GPT-2-medium 52.63 55.34 BERT-large 57.39 UniLM-large 59.13 T5-base 39.15 50.07 54.34 55.92 58.08 42.24 68.07 69.53 71.21 75.07 @ LST @ S # Mode # GPT2 # BERT # Uni # mt CANARD (Test) CANARD (Test) per bon 69.02 5 Chunk size (random sampling) CAST 5 Chunk size (beam search) CAsT 5 Chunk size (beam search) Chunk size (random sampling) Figure 2: Decoding sensitivity analysis side) illustrates that random sampling with larger top-k leads to poor BLEU scores.8 Under this de- coding strategy, T5 still maintains better BLEU scores compared to the other S2S models. # 5 Conclusion In this paper, we conduct experiments on conver- sational question reformulation (CQR) via neural sequence-to-sequence (S2S) models and demon- strate that our fine-tuned T5-base model achieves the state of the art, in one case achieving perfor- mance on par with humans (at least measured by BLEU). In addition, experiments on the CAsT dataset show that our fine-tuned T5-base model can be directly used in a transfer setting and beats other neural S2S models by quite a large margin. since the original implementation does not support beam search. 8For random sampling, we perform model inference with 10 repetitions and average over them. # 6 Acknowledgements This research was supported in part by the Canada First Research Excellence Fund and the Natural Sci- ences and Engineering Research Council (NSERC) of Canada. Additionally, we would like to thank Google for computational resources in the form of Google Cloud credits. # References Wasi Uddin Ahmad, Kai-Wei Chang, and Hongning Wang. 2018. Multi-task learning for document rank- ing and query suggestion. In Proc. ICLR. Wasi Uddin Ahmad, Kai-Wei Chang, and Hongning Wang. 2019. Context attentive document ranking and query suggestion. In Proc. SIGIR, page 385394. Mohammad Aliannejadi, Hamed Zamani, Fabio Crestani, and W. Bruce Croft. 2019. Asking clarify- ing questions in open-domain information-seeking conversations. In Proc. SIGIR, page 475484. Danqi Chen, Adam Fisch, Jason Weston, and Antoine Bordes. 2017. Reading Wikipedia to answer open- domain questions. In Proc. ACL, pages 1870–1879. Eunsol Choi, He He, Mohit Iyyer, Mark Yatskar, Wen- tau Yih, Yejin Choi, Percy Liang, and Luke Zettle- moyer. 2018. QuAC: Question answering in context. arXiv:1808.07036. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. BERT: Pre-training of deep bidirectional transformers for language under- standing. arXiv:1810.04805. Bhuwan Dhingra, Kathryn Mazaitis, and William W. Cohen. 2017. Quasar: Datasets for question answer- ing by search and reading. arXiv:1707.03904. Li Dong, Nan Yang, Wenhui Wang, Furu Wei, Xi- aodong Liu, Yu Wang, Jianfeng Gao, Ming Zhou, and Hsiao-Wuen Hon. 2019. Unified language model pre-training for natural language understand- ing and generation. In Proc. NIPS. Ahmed Elgohary, Denis Peskov, and Jordan Boyd- Graber. 2019. Can you unpack that? Learning In Proc. EMNLP, to rewrite questions-in-context. pages 5917–5923. and Lihong Li. 2018. Neural approaches to conversational AI. arXiv:1809.08267. Hsin-Yuan Huang, Eunsol Choi, and Wen tau Yih. 2019. FlowQA: Grasping flow in history for con- versational machine comprehension. In Proc. ICLR. Dalton Jeffrey, Chenyan Xiong, and Jamie Callan. 2019. CAsT 2019: The conversational assistance track overview. In Proc. TREC. Tom´aˇs Koˇcisk´y, Jonathan Schwarz, Phil Blunsom, Chris Dyer, Karl Moritz Hermann, G´abor Melis, and Edward Grefenstette. 2018. The NarrativeQA read- ing comprehension challenge. Trans.of ACL, 6:317– 328. Rodrigo Nogueira and Jimmy Lin. 2019. From doc2query to docTTTTTquery. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. 2018. Language models are unsupervised multitask learners. Filip Radlinski and Nick Craswell. 2017. A theoret- In Proc. ical framework for conversational search. CHIIR, page 117126. Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, and Peter J. Liu. 2019. Exploring the limits of transfer learning with a unified text-to-text trans- former. arXiv:1910.10683. Pranav Rajpurkar, Robin Jia, and Percy Liang. 2018. Know what you don’t know: Unanswerable ques- tions for SQuAD. In Proc. ACL, pages 784–789. Siva Reddy, Danqi Chen, and Christopher D. Manning. 2019. CoQA: A conversational question answering challenge. Trans. of ACL, 7:249–266. Gary Ren, Xiaochuan Ni, Manish Malik, and Qifa Ke. 2018. Conversational query understanding using se- quence to sequence modeling. In Proc. WWW, page 17151724. Min Joon Seo, Aniruddha Kembhavi, Ali Farhadi, and Hannaneh Hajishirzi. 2017. Bidirectional attention flow for machine comprehension. In Proc. ICLR. Haitian Sun, Bhuwan Dhingra, Manzil Zaheer, Kathryn Mazaitis, Ruslan Salakhutdinov, and William Co- hen. 2018. Open domain question answering using early fusion of knowledge bases and text. In Proc. EMNLP, pages 4231–4242. Ilya Sutskever, Oriol Vinyals, and Quoc V. Le. 2014. Sequence to sequence learning with neural networks. In Proc. NIPS, page 31043112. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. At- In Proc. NIPS, pages tention is all you need. 5998–6008. Wayne Xiong, Lingfeng Wu, Jun Zhang, and Andreas Stolcke. 2018. Session-level language modeling for conversational speech. In Proc. EMNLP, pages 2764–2768. Tiancheng Zhao and Maxine Eskenazi. 2016. Towards end-to-end learning for dialog state tracking and management using deep reinforcement learning. In Proc. of SIGDIAL, pages 1–10.
Title: Universal and Independent: Multilingual Probing Framework for Exhaustive Model Interpretation and Evaluation: Summary: Linguistic analysis of language models is one of the ways to explain and describe their reasoning, weaknesses, and limitations. In the probing part of the model interpretability research, studies concern individual languages as well as individual linguistic structures. The question arises: are the detected regularities linguistically coherent, or on the contrary, do they dissonate at the typological scale? Moreover, the majority of studies address the inherent set of languages and linguistic structures, leaving the actual typological diversity knowledge out of scope. In this paper, we present and apply the GUI-assisted framework allowing us to easily probe a massive number of languages for all the morphosyntactic features present in the Universal Dependencies data. We show that reflecting the anglo-centric trend in NLP over the past years, most of the regularities revealed in the mBERT model are typical for the western-European languages. Our framework can be integrated with the existing probing toolboxes, model cards, and leaderboards, allowing practitioners to use and share their standard probing methods to interpret multilingual models. Thus we propose a toolkit to systematize the multilingual flaws in multilingual models, providing a reproducible experimental setup for 104 languages and 80 morphosyntactic features. https://github.com/AIRI-Institute/Probing_framework # Universal and Independent: Multilingual Probing Framework for Exhaustive Model Interpretation and Evaluation # Oleg Serikov‡♠♥, Vitaly Protasov‡, Ekaterina Voloshina$, Viktoria Knyazkova♥, Tatiana Shavrina‡$ ‡ Artificial Intelligence Research Institute, $ SberDevices, ♥ HSE University, ♠ DeepPavlov lab, MIPT # Abstract Linguistic analysis of language models is one of the ways to explain and describe their rea- soning, weaknesses, and limitations. In the probing part of the model interpretability re- search, studies concern individual languages as well as individual linguistic structures. The question arises: are the detected regularities linguistically coherent, or on the contrary, do they dissonate at the typological scale? More- over, the majority of studies address the in- herent set of languages and linguistic struc- tures, leaving the actual typological diversity knowledge out of scope. In this paper, we present and apply the GUI-assisted framework allowing us to easily probe a massive number of languages for all the morphosyntactic fea- tures present in the Universal Dependencies data. We show that reflecting the anglo-centric trend in NLP over the past years, most of the regularities revealed in the mBERT model are typical for the western-European languages. Our framework can be integrated with the ex- isting probing toolboxes, model cards, and leaderboards, allowing practitioners to use and share their standard probing methods to inter- pret multilingual models. Thus we propose a toolkit to systematize the multilingual flaws in multilingual models, providing a reproducible experimental setup for 104 languages and 80 morphosyntactic features. GitHub knowledge and a need to standardize the experi- mental setup. At the same time, the fixation of the setup and hyperparameters should allow the repro- duction of a wide range of experiments, such as multilingual probing, like X-Probe (Ravishankar et al., 2019a) and Linspector (Sahin et al., 2020), layer-wise probing (Fayyaz et al., 2021), chrono- logical probing (Voloshina et al., 2022). Often, data for probing experiments is based on already known competition data, benchmarks, and gold standards. To obtain consistent results, such data must be high-quality, manually validated, and carefully include multiple languages. For this rea- son, in this work, we use the Universal Dependen- cies data (de Marneffe et al., 2021) as a source of multilingual data with a validated and standardized complete morphological and syntactic annotation, which will allow us to accumulate the assimila- tion of specific linguistic phenomena in many lan- guages at once. Probing these languages on the respective annotated linguistic categories would re- veal how models seize the typological proximity of languages. Therefore, the general probing methodology should include (according to Conneau and Kiela (2018)) 1) a fixed set of evaluations based on what appears to be community consensus; 2) a fixed eval- uation pipeline with standard hyperparameters; 3) a straightforward Python interface. 1 # 1 Introduction Probing methods shed light on the black box of the neural models in unearthing the linguistic features encoded in them. Probing sets a standard setup with various internal representations from the model and uses an auxiliary classifier to predict linguistic information captured in the representation. As probing research results have come up with contradictory results on different languages and language models, there appears to be a method- ological need for a meta-study of the accumulated This paper aims to extrapolate the multilin- gual linguistic diversity on the proven and tested SentEval-like methodology. We state our contribution as follows: • We develop a framework for exhaustive multi- lingual probing of the language models, with a complete enumeration of all grammatical char- acteristics and all languages available in Uni- versal Dependencies while maintaining the standard SentEval format. • We provide a setup for better and explanatory aggregation and exploration of the massive probing results with thousands of experiments for each model. • We illustrate the possibilities of the frame- work on the example of the mBERT model, demonstrating new insights and reassuring the results of previous studies on narrower data. Performing probing studies on such a large scale addresses the vision outlined in Nichols (2007) and contribute to a new dimension to linguistic typol- ogy research, as the revealed structures are encapsu- lated in tools and data inseparably tied to nowadays linguistic nature. Our framework provides users from different fields, including linguists, with a new point of view on the typological proximity of languages and categories. # 2 Related Work Different attempts were made to interpret behavior and hidden learned representation of language mod- els. For example, Hoover et al. (2020) investigated the attention-heads of the BERT model on word tokens connectivity level. Wallace et al. (2019) presented an interpretation framework where they improved a visual component of the model predic- tion process on several NLP tasks for the end-user. Flourishing after the ACL debates on semantic parsing1, the probing methodology has developed its own model interpretation tools. Thus, SentEval framework (Conneau and Kiela, 2018) includes various types of linguistically-motivated tasks: sur- face tasks probe for sentence length (SentLen) and for the presence of words in the sentence (WC); syntactic tasks test for sensitivity to word order (BShift), the depth of the syntactic tree (TreeDepth) and the sequence of top-level constituents in the syntax tree (TopConst); semantic tasks check for the tense (Tense), the subject (resp. direct object) number in the main clause (SubjNum, resp. Ob- jNum), the sensitivity to random replacement of a noun/verb (SOMO) and the random swapping of coordinated clausal conjuncts (CoordInv). Linspector ( ¸Sahin et al., 2019) includes 15 prob- ing tasks for 24 languages by taking morphosyntac- tic language properties into account, including case, verb mood, and tense, syntactic correctness, and the semantic impossibility of an example. While lacking the simplicity of the SentEval approach, the framework provides both a linguistically-grounded 1https://aclanthology.org/volumes/W14-24/ and multilingual setup. We are significantly ex- panding both the list of languages and properties being examined. Probe-X (Ravishankar et al., 2019b) has ex- panded SentEval setup with 5 additional languages, while NeuroX framework (Dalvi et al., 2019) also introduced novelty, but proposed to enrich the methodology to allow for cross-model analysis of the results, supporting neuron-level inspection. # 2.1 Probing Critique We would state a few problems why some of the probing practices are methodologically problem- atic. First, the probing interpretation result can differ from paper to paper, creating various conclusions from different authors. While Jawahar et al. (2019) achieves from 69.5-96.2% accuracy on the SentLen SentEval probing task (BERT model), they state that this info is somehow represented at the bot- tom layers. The work (Ravishankar et al., 2019b) achieves 38-51% accuracy on SentLen (RNN en- coder) and states that "recurrent encoders show solid performance on certain tasks, such as sen- tence length." This drastic difference in result in- terpretation (“somehow” vs. “extremely strong”) leads to misrepresenting the factual results. Con- flicting evidence within the field of BERTology can be found in Rogers et al. (2020), see Sec 3.1 and 4.3. Secondly, the results on similar tasks can be ob- tained with unstable success if the hyperparame- ters are not fixed or exhaustively described: for example, study (Jawahar et al., 2019) finds that "BERT’s intermediate layers encode a rich hierar- chy of linguistic information, with surface features at the bottom, syntactic features in the middle and semantic features at the top," while the work by Tikhonova et al. (2022) on mBERT shows, that the model does not learn the linguistic informa- tion. More meta-research is needed to explore the contradictory results obtained by the community. # 2.2 Task Representation In the survey of post-hoc language model inter- pretation (Madsen et al., 2021), the linguistic information-based tasks fall into the groups of the highest abstraction and the top-informativeness of properties used. This group of projects includes tasks based on the various theoretical language lev- els: from part-of-speech tagging to discourse. Languages While the most tasks are English- based, there appear the non-English monolingual frameworks: French-based probing (Merlo, 2019), Russian-based SentEval (Mikhailov et al., 2021), Chinese word masking probing (Cui et al., 2021). The multilingual benchmarks have paved the way for multilingual probing studies by collecting the necessary data. Linguistic features Most language-based tasks tend to be based on morphology or syntax, de- riving from SentEval methodology. Thus, higher- level tasks can concentrate both on monolingual discourse evaluation (Koto et al., 2021) (mostly English-based by now), as well as the multilin- gual discursive probing based on the conversion of the existing multilingual benchmarks (Kurfalı and Östling, 2021) (XNLI, XQUAD). # 3 Framework Design This section describes the probing framework and the experimental setup part. The main goal is to probe how well a model assimilates language constructions during training. For the framework, we want to form an end-to-end solution that can be applied to different models, work on diverse data, and simplify the process of getting insights from the results. Based on that, the challenges we have are the following: 1. The data we use in the training and evaluation parts must be in the standard format no matter what language we deal with. 2. The probing process should be universal for different models. Based on it, we also need to collect detailed results for further analysis. 3. Since we aim to work with diverse data, we should contain instruments to simplify the pro- cess of getting insights from the results. If we do not handle this problem, we can have bunches of results that would be difficult to interpret and provide findings for. Thus, we can represent our framework as a tool with different instruments. The first one is aimed at pre-processing data for probing, which is com- monly a classification task. The second one is a probing engine supporting popular probing tech- niques such as diagnostic classification. And the last one is a visualization instrument which should ease the process of interpreting the findings. # 3.1 SentEval Format Converter We found the SentEval format to be generally good and universal in the data composition for classifi- cation tasks. Since we have such a vast resource as Universal Dependencies for different languages, we can transform the data into the SentEval format and compose different classification tasks based on the language categories we can get. UD annotation consists of several parts: lem- mas, parts of speech, morphological features, and universal dependencies relations. The converter to SentEval format is focused on morphological features. As Table 1 illustrates, morphological cat- egories are written in the sixth column with their category values separated by the equals sign, for example, in Number=Sing, Number is a category and Sing is a category value. It took us 8 hours to process by the SentEval converter on 96 CPUs for absolutely all archives. For each morphological category found in a given file, the converter generates a new file in SentEval format according to the following steps: Data: CONLLU files or a directory to such files for one language Result: a file in SentEval format read files; find all morphological categories; foreach categories do foreach sentences do if category is in sentence then get a category value end stratified split on three samples; write to a file end Algorithm 1: The conversion process # end If split UD data into train, validation, and test sets, we do not change this split. In other cases, we split data into three sets, so the distribution of category values in the original text will be kept in each set. If a sentence contains several words with the same morphological categories, the closest to the sentence node word is taken, preventing the one sentence from being repeated several times. Table 1 depicts the example of Tense category, the value of word stopped will be taken, as it is the root of the sentence. # sent_id = weblog-typepad.com_ripples_20040407125600_ENG_20840407_125600-0055 # text = That too was stopped. 1 That that = PRON OT. Number=Sing|PronType=Dem 4 nsubj:pass 4:nsubj:pass 2 too too ADV RB _ advmod 4:advmod _ 3 was be AUX VBD-—s Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin 4 aux: pass 4:aux:pass _ 4 stopped stop VERB VBN Tense=Past|VerbForm=Part |Voice=Pass e root @:root SpaceAfter=No 5 : : PUNCT _ 4 punct 4:punct _ Figure 1: The example of UD annotation # Format Data entry # s e n t _ i d = weblog − t y p e p a d . com_ripples_20040407125600_ENG_20040407_125 # t e x t = T h a t 1 . That 2 . 3 . was be AUX VBD Mood= I n d | Number= S i n g | P e r s o n = 3 | T e n s e = P a s t | VerbForm= F i n 4 aux : p a s s 4 : aux : p a s s 4 . stopped s t o p VERB VBN T e n s e = P a s t | VerbForm= P a r t | V o i c e = P a s s 0 r o o t 0 : r o o t S p a c e A f t e r =No PUNCT 5 . # Conll-U # SentEval Table 1: Example of CONLL-U format and its conversion to SentEval: Tense classification, train set. # 3.2 Multilingual Data We take 289 repositories, including the data of 172 languages available at the GitHub of Universal Dependencies , updated in May 2022.2 While parsing files, we face several problems inherited from UD. 71 of the repositories do not contain any CONLLU files. Three Japanese repos- itories and Korean and Frisian Dutch repositories contain different annotations from standard UD an- notations. The data from 16 repositories (Akkadian, Cantonese, Chinese (2), German, Japanese, Hindi, Irish, Kangri, Maltese, Neapolitan, South Levan- tine Arabic, Swedish Sign language, Swiss Ger- man, Old Turkish, Tagalog) do not contain morpho- logical annotation. Also, some repositories include correctly annotated data but are not suitable for classification problems because all the examples contain only one value of all the categories, for ex- ample, only examples with class Plural are left for the category Number (Cantonese, Chukchi, Frisian Dutch, Hindi English, Japanese, Kangri, Khunsari, Makurap, Maltese, Nayini, Neapolitan, Old Turk- ish, Soi, South Levantine Arabic, Swedish Sign Language, Swiss German, Telugu, Vietnamese). Many of the languages in our data are endangered or even extinct. The UD data is distributed based on Creative Commons and GNU-based licenses, varying from language to language3. Extracting the tasks for every grammatical category results in 1927 probing datasets. # 3.3 Probing Engine # 3.3.1 Encoders In the experiments, we consider the layers of encoder-based models and their ability to acquire language data and perform well on probing tasks. Using the output of the model’s layers, we can get contextualized token embeddings for elements of the input text. For that reason, we can consider several options for embedding aggregation: CLS where the text is presented as the embedding from "[CLS] "token, SUM and AVG where the sentence vector is a sum or average of embeddings of all text tokens. # 3.3.2 Classifiers and metrics After filtering, we have data from 104 languages from 194 repositories (see Appendix A.1). From the typological point of view, these languages be- long to 20 language families, and the Basque lan- guage is an isolate. Although almost half of the lan- guages are from the Indo-European family, the data include several under-studied language families. After the embeddings are obtained, we train a sim- ple classification model based on the encoder lay- ers’ representation and task data labels. We con- sider linear (Logistic Regression) and non-linear (MLP) classifiers. As the metrics for performance evaluation, we use accuracy score and weighted F1 score in case of unbalanced classes. 2https://github.com/UniversalDependencies 3https://lindat.mff.cuni.cz/repository/xmlui/ page/licence-UD-2.1 Frechet: 0.04 Pearson: 0.87 08 1 Vy . VA A: 3 VAN: fos VN: AVA ao Vs oe S ‘| (ZZ Danish Definite I Vi: :: {EH Afrikaans Tense 0.0 * * UAT ATMIZI I At 0 1 2 3 4 5 6 7 8 9 10 11 layer number Figure 2: An example of δF and r scores calcula- tion between the two probing experiments # 3.4 Aggregation The engine is meant to produce probes of a particu- lar category in a particular language. We provide additional grouping and visualization tools to allow for meaningful interpretation of such large result sets. They are meant to highlight similar experi- ments and visualize them on the world map. The default configuration follows the classical probing experiments and uses layers’ numbers as X axes. Yet the more novel setup can be chosen, e.g. treating the < language, category > features pairs as X-axis instead. The defined atomic experimental axis allows to characterize larger groups of experiments via their pooled value (such as mean-pooled by categories value in Figure 6), or even cluster them (e.g., using pairwise experiments similarity as in Figure 3). # 3.4.1 Similarity Metrics We support two metrics of scoring the experiments’ pair-wise similarity. Both of them are calculated for the experiment results curves. 4 Frechet distance (δF ) provides a natural way to compare curves taking into account both the similarity of curves’ shapes and their absolute positioning on the chart. Unlike that, for Pearson correlation (r) absolute positioning is irrelevant. While r formalizes the notion of “coherent” or “similar” behavior of models’ layers, δF comple- ments it with exact values similarity constraint (see Figure 2). Frechet distance Given the simultaneous iter- ative step-by-step walkthrough from the start to the end points of both curves, one could freely vary the step size for every curve at every itera- tion. By the proper choice of step sizes during 4By probing curve we refer to the typical probing chart. Layers, or other probed parts of a model, and the respective results are visualized as a curve on a linear chart. the walkthrough, one could guarantee that the op- timal distance between curves’ respective points will never be exceeded during the iteration pro- cess. That optimal distance is called Frechet dis- tance and is formally calculated as follows: δF = infa,b {maxt {d (Aa(t), Bb(t))}}, where t denotes iteration steps, a, b combinations correspond to var- ious step size strategies, and A, B are the functions respective to the curves. Pearson correlation coefficient Pearson corre- lation measures the strength of linear dependence of two samples: rxy = , where sα is the standard deviation of sample α and α is this sample mean. # 3.4.2 Visualization We provide the GUI (see Figure 3) to allow us to configure the similarity thresholds and explore the particular categories’ results on a geospatial chart. GUI allows setting off the δF and r absolute val- ues thresholds and specifying particular languages and categories to be shown. # 4 Evaluation Setup To present the whole procedure of our probing framework working process, we decided to run the experiments only for two multilingual transformer encoder-based models: the 12-layer mBERT model (Devlin et al., 2018)5 and the 24-layer XLM- RoBERTa model (Conneau et al., 2019)6. We used embeddings from “[CLS]“ token for each text sam- ple as it is widely accepted. As the classifier, while supporting LogReg and MLP, we choose Logis- tic Regression due to its higher Selectivity (Hewitt and Liang, 2019). The classifier was trained on 10 epochs using cross-entropy loss and AdamW (Loshchilov and Hutter, 2017) optimizer. A sep- arate classifier was trained for each feature of all languages and each layer. To eliminate the problem of different sizes of the datasets, we run the classifier five times and then take an average result to avoid the classifier bias. The results were evaluated by F1 weighted score because of the unbalanced data for most prob- ing tasks. From Universal Dependencies, using our SentEval converter, we obtained 1927 probing tasks for 104 languages. During the training, we noticed # 5https://huggingface.co/ bert-base-multilingual-cased 6https://huggingface.co/xlm-roberta-large Inputs Visualization Category * Gender * Number x Tense Language Corr threshold, abs oa Frechet 0.12 threshold | Tense Gender Figure 3: GUI screenshot: Similarity between languages learned by mBERT based on different probing tasks. that some samples contain long sentences with to- ken numbers of more than 512. We propose two options for handling it correctly: truncate sentences to 512 tokens or dispose of all of these sentences. Tense are among the most frequent ones. The exam- ple of the geospatial visualizations of the similarly learned features is presented in Figure 3 # 5 Results and Insights # 5.2 mBERT and XLM-R Multilingual Abilities and Insights # 5.1 General Results We received a massive multilingual probing task bundle of 1927 tasks using all the converted data for 104 languages. It took us 10 hours to probe through all the files on one NVidia Tesla GPU V100. We thus conducted the probing of the mBERT and XLM-R models to figure out the capabilities of the models, as follows: 1. to generalize linguistic information language- wise: grouping the average results a) by layers (Figure 5), b) by each feature in each language (Figure 4). 2. to generalize linguistic information feature- wise, grouping the average results by each layer and by each language (Appendix A.2). 3. to explore the results feature-wise: a) by searching for similarities in layer-wise feature representations) by exploring individual fea- ture results grouped by language and layer (Appendices A.4, A.5), c) by creating the geospatial visualizations of the similar fea- tures. The model evaluation results are presented in Fig- ure 4: the figure clearly shows the sparseness with which all features are presented in each language. Basic features such as Number, PronType, and Given the mBERT model as an example, as for the categories Number and PronType, which are the most common across languages, the best scores were achieved at the 3rd and 6th layers, respec- tively. In the case of all categories, mBERT showed the best result at the 5th layer. In Appendix A.4 and A.5 the heatmaps for all languages with these categories can be found. As for the average results by all categories, see Appendices A.2 and A.3. Fig- ure 5 depicts average language scores for Number and PronType and among all categories. As mentioned above, we evaluated two mod- els, mBERT and XLM-R, on our data. On aver- age, their performance is similar. However, the scores of XLM-R are slightly worse than the ones of mBERT. By the categories, mBERT shows the best performance in Hungarian, Chinese, Urdu, Welsh, and Slovak. The worst results were shown in Tupinambá and Akuntsu. XLM-R’s top lan- guages include the same language in a different order (Chinese has the best quality). On Javanese and Akuntsu, XLM-R shows the worst quality. The models show the best quality on high-resource languages and have worse repre- sentations of under-resourced non-Indo-European languages. Among the factors that can impact the models’ Figure 4: mBERT results grouped by languages and average feature probing score on all layers performance on different languages, the following might be the most essential: script, language ge- nealogy, and typological features of languages. en 2 10 Fa Layer Numbers Figure 5: Distribution of scores by model’s layers depending on the categories which are used across languages. To research the effect of script and language ge- nealogy on the results, we run an ANOVA test since we have more than two families or scripts. The test reveals a strong correlation between a language family and the models’ performance (p = .0005 for both XLM-R and mBERT). We also run an ANOVA test to see if another significant difference in performance on languages with different scripts exists. The test shows that script did not impact the final performance (p = .52 for mBERT and p = .39 for XLM-R). The reported difference in the performance may be caused by the set of categories or the dataset size. Independently, other works (Pires et al., 2019; Wu and Dredze, 2019) claim that mBERT shows language neutral- ity regarding both a language and its script. Our results support that level of performance does not depend on a script, as models show high results on languages with Arabic-based (Persian, Urdu) or Ge’ez scripts (Amharic). Yet, the models might be biased towards Stan- dard Average European languages (SAE) (Haspel- math, 2001), as it solves tasks on the categories found in SAE languages better than on the other language-specific categories. For example, the top- 10 of the best recognised categories include Per- son[abs], PunctSide, Person[obj], Agglutination 7, Mutation, Degree, Decl, Mood 8, Evident9, and Polarity10. Agglutination and Mutation are highly imbalanced towards one class, and other categories, except for Evident, are widespread in European languages. On the other hand, top-10 worst categories are following: NumValue, InflClass, NounClass, Heb- Binyan, Clitic, ExtPos, Derivation, NameType, In- flClass[nominal], FocusType. These categories are language-specific and are not found in SAE lan- guages. Apart from that, if a category typical for SAE gets a different set of values, the model per- forms much worse. The model generally shows good results on Case and significantly worse re- sults for Hungarian and Amharic with a different set of values for Case. Chi et al. (2020) prove that mBERT has a joint subspace of universal syntactic relations. Since we cannot fully prove if mBERT has a joint subspace of morphological features because, as mentioned before, some morphological features are not univer- sal. However, we can see if there is any correlation between categories across all languages based on how different layers learn these features, according to Frechet distance. Most categories do not have a correlating category. However, there are several compelling cases to mention. mBERT generally learns Evident and Mood similarly, and in some lan- guages, such as Bulgarian, Evident is regarded as a value of Mood. Other than that, Definite and Num- ber have a little distance, which might be expressed with one morpheme, as in Scandinavian languages. The same is valid for Number and Person cate- gories that are learned similarly by mBERT. 7Only used for Polish past participles 8Mood express modality, such as indicative, imperative, conditional 9Evidence is the morphological marking of a speaker’s source of information (Aikhenvald, 2006) 10Polarity shows if words can be used only in negative or positive contexts There is not enough evidence to claim that mBERT has a joint subspace for morphological features because categories have different sets of values, and mBERT performs better on SAE cate- gories. Yet, it shows some generalization abilities on the similarity of morphology across languages. # 6 Future Work As part of future work, we plan to include syntactic markup in research and an interface with a CQL- like11 query language for authors. The ability to set conditions on a subcorpus of examples will give the researchers the freedom to create custom and linguistically motivated probing tasks while the rest of the experiment parameters will be fixed. One can imagine, e.g., the probing of the model on the [tag="NP"] query, exploring the results specifically on the noun phrases. We believe that, in this respect, the tasks of probing and interpreting the results of the model become close to the tasks of corpus linguistics and searching through corpora for statistical testing of hypotheses. # 7 Conclusion The typological variety of linguistic features com- poses the general nature of language. To address the lower-abstract parts of this nature, we intro- duced the Universal Probing framework, which allows the researchers to run and aggregate mas- sive amounts of probing experiments in a fixed and reproducible setup. The current framework version includes an ex- perimental setup from 104 languages and 80 gram- matical features. The framework can be used for language model interpretation with various archi- tectures, and the results can also be easily incor- porated into the model cards checklist. It can be used in more language-wise transfer learning and typological studies with multilingual models. the community will use our work in order to interpret, evaluate and compare the language models, leading to better and more explainable NLP. The framework and all the data are open-source under Apache 2.0 license https://github.com/AIRI-Institute/ Probing_framework. # 11https://www.sketchengine.eu/documentation/ corpus-querying/ # 8 Limitations By now, it is also worth mentioning the UD data de- pendencies of the framework. The problems in the UD data, such as annotation errors, formatting er- rors, and version instability, could potentially affect the resulting probing framework. As described in Section 3.2, we have eliminated obviously problem- atic fragments; however, more deeply incorporated inaccuracies may drag on, surviving conversion to the SentEval format. Some inconsistencies in the accepted annotation format affected the quality of model embeddings: such categories as Punct- Side (Catalan, Finnish, Icelandic, Polish, Spanish), NameType (Armenian, Classical Chinese, Czech, Erzya, etc.) are rare and have a very different distri- bution from language to language and are expected to be at the bottom of the list. The categories ac- cepted in the UD for one specific language are also poorly solved: Agglutination (Polish), Mu- tation (Welsh), HebBinyan (Hebrew), NounClass (Wolof), NumValue (Arabic, Czech). We use the latest available UD release (version 2.10)12. As stated on the project’s website, the next release (v2.11) is scheduled for November 15, 2022, so data curation and updates will be neces- sary to incorporate the newer and better UD anno- tation into the framework. The proposed framework allows for different probing methods to be used similarly, includ- ing the widely criticized ones (Belinkov, 2022). Researchers relying on the presented framework should carefully pick the proper methods in their probing studies. For example, we’ve introduced the control task (Hewitt and Liang, 2019) consisting of averaging the probing performance across several probing experiments. This reduced the possibility of a probing task erroneously receiving a high score due to the small size of the testing data. # 9 Ethical Considerations # 9.1 Possible Misuse The framework’s usage implies working concern- ing standard practices during model pre-training, such as controlling that the test data (e.g., UD cor- pora) are excluded from the training corpus. Us- ing UD data during pre-training or fine-tuning the model can lead to indicative and biased results of model interpretation. 12Version 2.10 treebanks are available at http://hdl. handle.net/11234/1-4758. 228 treebanks, 130 languages, released May 15, 2022. # 9.2 Data-specific Problems 9.2.1 Dataset Characteristics The dataset covers the languages described in Sec- tion A.1. The probing dataset statistics are also presented in Section A.1. 9.2.2 Generalization The UD data can be considered mostly validated, as it involves multiple institutions to develop and test the annotation standards, as well as the corpus data itself. However, besides data quality, usage of the data should address such characteristics as quantity: that is why we have automatically ex- cluded the UD categories having only one value within a category in all available languages. For all other categories, the data for the classification task were not limited in any way; the train/val/test data division was preserved. Potentially, other data-dependent problems (see also the resulting data dependencies in Section 8) could be: genre bias in specific languages; • personal style/resource bias in specific lan- guages; collocation of the specific features: some fea- tures can possibly occur within the same con- texts (sentences), which makes the solution of the classification problem within the probing setup noisy for the tested language model. Nevertheless, we consider the UD corpora to be sufficiently reliable and the most complete of the available data for a detailed low-level multilingual probing study of the models. 9.2.3 Data Quality In addition to the above, we draw attention to the question of the language representation problems in the UD. According to the Ethnologue database 13, there are more than 4000 languages with devel- oped writing systems, while only 172 of them are presented in the UD in general, and even less (104) were qualified to be included in the framework for- mat. As we understand that the presented language set is not typologically sampled, we proceeded from the criterion of completeness, not balance. If nec- essary, we encourage willing researchers to sample their subsamples from our data to follow typologi- cal sampling. 13https://www.ethnologue.com/enterprise-faq/ how-many-languages-world-are-unwritten-0 # References Alexandra Y Aikhenvald. 2006. Evidentiality. oxford: Oxford university press, 2004. Yonatan Belinkov. 2022. Probing classifiers: Promises, shortcomings, and advances. Computational Lin- guistics, 48(1):207–219. Ethan A Chi, John Hewitt, and Christopher D Manning. 2020. Finding universal grammatical relations in multilingual bert. arXiv preprint arXiv:2005.04511. Alexis Conneau, Kartikay Khandelwal, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettle- moyer, and Veselin Stoyanov. 2019. Unsupervised cross-lingual representation learning at scale. CoRR, abs/1911.02116. Alexis Conneau and Douwe Kiela. 2018. Senteval: An evaluation toolkit for universal sentence representa- tions. ArXiv, abs/1803.05449. Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, and Ziqing Yang. 2021. Pre-training with whole word IEEE/ACM Transac- masking for chinese BERT. tions on Audio, Speech, and Language Processing, 29:3504–3514. Fahim Dalvi, Avery Nortonsmith, D. Anthony Bau, Yonatan Belinkov, Hassan Sajjad, Nadir Durrani, and James Glass. 2019. Neurox: A toolkit for an- alyzing individual neurons in neural networks. In AAAI Conference on Artificial Intelligence (AAAI). Marie-Catherine de Marneffe, Christopher D. Man- ning, Joakim Nivre, and Daniel Zeman. 2021. Uni- versal Dependencies. Computational Linguistics, 47(2):255–308. Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. Bert: Pre-training of deep bidirectional transformers for language understand- ing. Mohsen Fayyaz, Ehsan Aghazadeh, Ali Modarressi, Hosein Mohebbi, and Mohammad Taher Pilehvar. 2021. Not all models localize linguistic knowl- edge in the same place: A layer-wise probing on In Proceedings of the BERToids’ representations. Fourth BlackboxNLP Workshop on Analyzing and Interpreting Neural Networks for NLP, pages 375– 388, Punta Cana, Dominican Republic. Association for Computational Linguistics. Martin Haspelmath. 2001. The european linguistic area: Standard average european. In Wulf Oesterre- icher Martin Haspelmath and Wolfgang Raible, edi- tors, Language Typology and Language Universals, Handbücher zur Sprach- und Kommunikationswis- senschaft, pages 1492–1510. Mouton de Gruyter, Berlin. Designing and interpreting probes with control tasks. ArXiv, abs/1909.03368. Benjamin Hoover, Hendrik Strobelt, and Sebastian Gehrmann. 2020. exbert: A visual analysis tool to explore learned representations in transformer mod- els. In ACL. Ganesh Jawahar, Benoît Sagot, and Djamé Seddah. 2019. What does BERT learn about the structure In Proceedings of the 57th Annual of language? Meeting of the Association for Computational Lin- guistics, pages 3651–3657, Florence, Italy. Associa- tion for Computational Linguistics. Fajri Koto, Jey Han Lau, and Tim Baldwin. 2021. Dis- course probing of pretrained language models. In NAACL. Murathan Kurfalı and Robert Östling. 2021. Prob- ing multilingual language models for discourse. In Proceedings of the 6th Workshop on Representation Learning for NLP (RepL4NLP-2021), pages 8–19, Online. Association for Computational Linguistics. Ilya Loshchilov and Frank Hutter. 2017. weight decay regularization in adam. abs/1711.05101. Andreas Madsen, Siva Reddy, and A. P. Sarath Chan- dar. 2021. Post-hoc interpretability for neural nlp: A survey. ArXiv, abs/2108.04840. Paola Merlo. 2019. Probing word and sentence em- beddings for long-distance dependencies effects in In Proceedings of the 2019 French and English. ACL Workshop BlackboxNLP: Analyzing and Inter- preting Neural Networks for NLP, pages 158–172, Florence, Italy. Association for Computational Lin- guistics. Vladislav Mikhailov, Ekaterina Taktasheva, Elina Sigdel, and Ekaterina Artemova. 2021. RuSentE- In Proceed- val: Linguistic source, encoder force! ings of the 8th Workshop on Balto-Slavic Natural Language Processing, pages 43–65, Kiyv, Ukraine. Association for Computational Linguistics. Johanna Nichols. 2007. What, if anything, is typology? Telmo Pires, Eva Schlinger, and Dan Garrette. 2019. arXiv How multilingual is multilingual bert? preprint arXiv:1906.01502. Vinit Ravishankar, Lilja Øvrelid, and Erik Velldal. 2019a. Probing multilingual sentence representa- tions with x-probe. In RepL4NLP@ACL. Vinit Ravishankar, Lilja Øvrelid, and Erik Velldal. 2019b. Probing multilingual sentence representa- In Proceedings of the 4th tions with X-probe. Workshop on Representation Learning for NLP (RepL4NLP-2019), pages 156–168, Florence, Italy. Association for Computational Linguistics. Anna Rogers, Olga Kovaleva, and Anna Rumshisky. 2020. A primer in BERTology: What we know about how BERT works. Transactions of the Associ- ation for Computational Linguistics, 8:842–866. Gözde Gül Sahin, Clara Vania, Ilia Kuznetsov, and Iryna Gurevych. 2020. Linspector: Multilingual probing tasks for word representations. Computa- tional Linguistics, 46:335–385. Maria Tikhonova, Vladislav Mikhailov, Dina Pis- arevskaya, Valentin Malykh, and Tatiana Shavrina. 2022. Ad astra or astray: Exploring linguistic knowledge of multilingual bert through nli task. Nat- ural Language Engineering, page 1–30. Ekaterina Voloshina, Oleg Serikov, and Tatiana Shav- rina. 2022. Is neural language acquisition similar to natural?a chronological probing study. Eric Wallace, Jens Tuyls, Junlin Wang, Sanjay Subra- manian, Matt Gardner, and Sameer Singh. 2019. Al- lennlp interpret: A framework for explaining predic- tions of nlp models. ArXiv, abs/1909.09251. Shijie Wu and Mark Dredze. 2019. Beto, bentz, be- cas: The surprising cross-lingual effectiveness of bert. arXiv preprint arXiv:1904.09077. Gözde Gül ¸Sahin, Clara Vania, Ilia Kuznetsov, and Iryna Gurevych. 2019. Linspector: Multilingual probing tasks for word representations. # A Appendix # A.1 Languages information and statistic After the processing of Universal Dependencies, 104 languages left. Here is a table with the languages, their families, and the number of examples that we used in the experiments. Language Family Examples Language Family Examples Indo-European Afrikaans Afro-Asiatic Akkadian Tupian Akuntsu Indo-European Albanian Afro-Asiatic Amharic Indo-European Ancient Greek Arawakan Apurina Afro-Asiatic Arabic Indo-European Armenian Afro-Asiatic Assyrian Mande Bambara - Basque Afro-Asiatic Beja Indo-European Belarusian Indo-European Bengali Indo-European Bhojpuri Indo-European Breton Indo-European Bulgarian Mongolic-Khitan Buryat Indo-European Catalan Chinese Sino-Tibetan Classical Chinese Sino-Tibetan Afro-Asiatic Coptic Indo-European Croatian Indo-European Czech Indo-European Danish Indo-European Dutch Indo-European English Uralic Erzya Uralic Estonian Indo-European Faroese Uralic Finnish Indo-European French Indo-European Galician Indo-European German Indo-European Gothic Indo-European Greek Tupian Guajajara Afro-Asiatic Hebrew Indo-European Hindi Uralic Hungarian Indo-European Icelandic Austronesian Indonesian Indo-European Irish Indo-European Italian Austronesian Javanese Tupian Kaapor Uralic Karelian Tupian Karo Turkic Kazakh Indo-European Kiche Uralic Komi Permyak 19646 15037 79 380 7166 566076 176 484604 37117 152 4829 191646 347 445666 156 1525 5206 238822 6832 305522 18865 93864 22150 193156 831540 104906 241808 414215 17458 557773 21133 624845 686410 15878 311259 99064 49364 409 112866 321197 41102 503790 47426 93264 395470 290 99 1475 1845 15082 11534 325 Komi Zyrian Korean Kurmanji Latin Latvian Ligurian Lithuanian Livvi Low Saxon Manx Marathi Mbya Guarani Moksha Munduruku Naija North Sami Norwegian Old Church Slavonic Old East Slavic Old French Persian Polish Portuguese Romanian Russian Sanskrit Scottish Gaelic Serbian Skolt Sami Slovak Slovenian Spanish Swedish Tagalog Tamil Tatar Thai Tupinamba Turkish Turkish German Ukrainian Upper Sorbian Urdu Uyghur Warlpiri Welsh Western Armenian Wolof Xibe Yakut Yoruba Yupik Uralic Koreanic Indo-European Indo-European Indo-European Indo-European Indo-European Uralic Indo-European Indo-European Indo-European Tupian Uralic Tupian Atlantic-Congo Uralic Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Indo-European Uralic Indo-European Indo-European Indo-European Indo-European Austronesian Dravidian Turkic Tai-Kadai Tupian Turkic Indo-European Indo-European Indo-European Indo-European Turkic Pama-Nyungan Indo-European Indo-European Atlantic-Congo Tungusic Turkic Atlantic-Congo Eskimo-Aleut 5682 3314 9134 1048162 393694 2304 81462 835 623 13536 6340 5503 3133 164 42928 21639 631651 118508 153393 45115 183678 860418 197481 543203 270189 25885 27907 94856 989 218032 286196 660046 213496 380 12602 250 612 593 746291 21160 139882 5241 96902 40174 128 17026 71303 21518 4226 213 1151 2281 # A.2 mBERT’s layers F1 scores for all languages and categories. Afrikaans Akkadian Akuntsu Albanian Amharic Ancient Greek Apurina Arabic Armenian Assyrian Bambara Basque Beja Belarusian Bengali Bhojpuri Breton Bulgarian Buryat Catalan Chinese Classical Chinese Coptic Croatian Czech Danish Dutch English Erzya Estonian Faroese Finnish French Galician German Gothic Greek Guajajara Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Javanese Kaapor Karelian Karo Kazakh Kiche Komi Permyak Komi Zyrian Korean Kurmanji Latin Latvian Ligurian oe po Lithuanian Livi SSS EEE EEOEA~A>EAE={=«x=am"| 0.6 Low Saxo i es es ee ee es i ls (ai [tlt Manx Marathi eS LS SS SS SS OY SS Mbya Guarani Ls ee eee ea ee [| [cen (st [ttt Moksha EE en Munduruku | Naija North Sami Nomvegian Old Church Slavonic Old East Slavic Old French Persian Polish Portuguese Romanian Russian Sanskrit Scottish Gaelic Serbian Skolt Sami Slovak Slovenian Spanish Swedish Tagalog Tamil Tatar Thai Tupinamba Turkish Turkish German Ukrainian Upper Sorbian Urdu Uyghur Warlpiri Welsh Western Armenian Wolof Xibe Yakut Yoruba Yupik -0.9 0.8 0.7 Languages 0.5 0.4 Layer Numbers Figure 6: Distribution of average model scores by layers for languages measured on all categories. A.3 XLM-R results grouped by languages and average feature probing score on all layers Figure 7: XLM-R results grouped by languages and average feature probing score on all layers A.4 Model’s layers F1 scores for all languages on category "Number". Aiko TE TS TS eS ee . es cs es es 71.0 ‘Akkadian Abe TE ‘Amharic Ancient Grek i i. i i es ee es es ee ee ‘Apurina Arabic ‘Armenian Assyrian Bambara Basque Beja Belarusian Bhojpuri Broton Bulgarian Catalan Coptic Croatian Czech Danish Dutch English Erzya Estonian Faroese Finnish French Galician German Gothic Greek Hebrew Hindi ‘Hungarian SS a a Tcolancic A LL Le eS Indonesian Irish 1 ee Koqpor SS es Kearelicn LL LLL Lee aa eee ———— Kh SS Se ee SS 5 Ss 8 Kc ee ee Se A Komi Zyrian ‘Kurman}! Latin Latvian Ligurian Lithuanian Livi Low Saxon Manx: Marathi Mbya Guarani Moksha Mundurukst Naija North Sami Norwegian (Old Church Slavonic Old East Slavic Persian Polish Portuguese Romanian Russian Languages Sanskrit Scottish Gaelic — Sebi es a Skolt Sami Slovak. Shove, TT a a a ee Spanish — ——e—E—Eee Ne se ‘Tagalog a eS ee ee ee ee Tatar pin Sa a eee ee eee eT TT “Turkish ‘Turkish German | eran LS LLL eee eee A Ss SS A SN per 0 TT es es es Urdu hs a es ee ee es Welsh Vese1 (rie a ee SS Ss SS ee cs EE EE EE eee Se Yakut Nor ss eT he Se ee Se es ce 0.0 1 2 3) 4 3) 6 7 8 9 10 11 12 Layer Numbers Figure 8: Distribution of model scores by layers for languages measured on category Number. A.5 Model’s layers F1 scores for all languages on category "PronType". - 1.0 Aik. 2s a a a Albanian A A (S(O Ancient Greek iS LS i i i (SL Arabic Acme A TS SS A Se ee (y(n (A (a (a Ca Bambara Basque | | | pT Belo sic A a a a a ( ( Bhojpuri Breton Bolg arin A a a a eS (A Buryat es Catalan Classical Chinese Coptic Croatian Czech Danish Dutch English Erzya Estonian Faroese Finnish French Galician German Gothic Greek Guajajara Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Javanese Karelian Karo Kazakh Kiche Komi Zyrian Kurmanji Latin Latvian Ligurian Lithuanian es La i Low Saxon | | i PC i Manx orth Mbya Guarani Moksha Naija North Sami Norwegian Old Church Slavonic Old East Slavic Old French Persian Polish Portuguese Romanian Russian Sanskrit Scottish Gaelic Serbian Skolt Sami Slovak Slovenian Spanish Swedish Tupinamba Turkish Turkish German Languages Ukrainian Upper Sorbian Urdu Uyghur Welsh Western Armenian a a 1 Xibe Yoruba Yupik NO Ww > ol fo) ~— lee) © e lo) e a e N Layer Numbers Figure 9: Distribution of model scores by layers for languages measured on category PronType.