원시데이터 수집 시스템
선정목록으로

Code Models are Zero-shot Precondition Reasoners

관련 산업용 섬유 · (8) HDPE 섬유(FORPE)

기본 정보

저자
  1. Lajanugen Logeswaran
  2. Sungryull Sohn
  3. Yiwei Lyu
  4. Anthony Liu
  5. Dong Ki Kim
  6. Dongsub Shim
  7. Moontae Lee
  8. Honglak Lee
DOI
10.18653/v1/2024.naacl-long.317
저널
–
발행년도
2024
발행기관
–
피인용수
2
라이선스
cc-by
논문 유형
–
언어
–
원문 페이지
http://dx.doi.org/10.18653/v1/2024.naacl-long.317
토픽
Fuel Cells and Related Materials
OpenAlex ID
W4401042802

평가 내용

관련도
관련
사업분야
산업용 섬유 · (8) HDPE 섬유(FORPE)
부 분야
–
R&D 측면
–
확신도
–
근거 용어
–
판단 근거
임베딩 유사도 기반 평가로 '산업용 섬유 > HDPE 섬유(FORPE)' 분야에 선정된 논문입니다.
R&D 활용 포인트
–
평가 입력
–

초록

Lajanugen Logeswaran, Sungryull Sohn, Yiwei Lyu, Anthony Liu, Dong-Ki Kim, Dongsub Shim, Moontae Lee, Honglak Lee. Proceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers). 2024.

본문 66,693자

본문 펼치기
# Code Models are Zero-shot Precondition Reasoners Lajanugen Logeswaran <sup>1</sup> Sungryull Sohn <sup>1</sup> Yiwei Lyu <sup>2</sup> Anthony Zhe Liu <sup>2</sup> Dong-Ki Kim <sup>1</sup> Dongsub Shim <sup>1</sup> Moontae Lee <sup>1</sup> Honglak Lee <sup>1</sup> <sup>_,_</sup> <sup>2</sup> 1LG AI Research 2University of Michigan, Ann Arbor Abstract One of the fundamental skills required for an agent acting in an environment to complete tasks is the ability to understand what actions are plausible at any given point. This work explores a novel use of code representations to reason about action preconditions for sequential decision making tasks. Code representations offer the flexibility to model procedural activities and associated constraints as well as the ability to execute and verify constraint satisfaction. Leveraging code representations, we extract action preconditions from demonstration trajectories in a zero-shot manner using pre-trained code models. Given these extracted preconditions, we propose a precondition-aware action sampling strategy that ensures actions predicted by a policy are consistent with preconditions. We demonstrate that the proposed approach enhances the performance of few-shot policy learning approaches across task-oriented dialog and embodied textworld benchmarks. 1 Introduction A key capability for learning an optimal agent policy in sequential decision making settings is understanding the plausibility of different actions. For instance, a dialog agent recommending restaurants needs to have basic information like location and type of food in order to look up its database for potential options. Understanding the necessary conditions for performing an action (e.g., location and type of food are necessary for the database lookup action) is referred to as _precondition inference_ or _affordance_ _learning_ in the literature (Ahn et al., 2022; Sohn et al., 2020). Knowledge about preconditions has broad implications for policy learning and safety applications. Few-shot prompted large language models (LLMs) have demonstrated strong capabilities for task planning (Logeswaran et al., 2022; Huang et al., 2022a; Micheli and Fleuret, 2021; Ahn et al., Figure 1: We propose a framework to extract action preconditions from demonstration trajectories leveraging code representation and code models. Extracted preconditions are used to construct an agent policy that predicts actions consistent with preconditions. 2022). However, they lack a systematic mechanism to reason about action preconditions. Some approaches attempt to teach LLMs preconditions by providing examples in the form of code assertions (Singh et al., 2022; Liang et al., 2022) or natural language rationales (Huang et al., 2022b; Yao et al., 2022). Preconditions or rationales for predicted actions are generated dynamically on-thefly the during inference. However, it is non-trivial to verify whether these preconditions or rationales Domain Description Example Trajectory _INFORM -_ Inform the value for a slot. _REQUEST -_ Request the value of a slot. _OFFER -_ Offer a certain value for a slot. … SYSTEM: _REQUEST(city)_ USER: _INFORM(city)_ SYSTEM: _REQUEST(cuisine)_ … Partial Program Specification Demonstration Trajectories ``` class USER: def __init__(self): self.informed = {} self.requested = {} ... def INFORM(self, slot): self.informed[slot] = True class SYSTEM: def __init__(self, user): self.user = user def FindRestaurants(self): assert ``` ``` def demonstration(): system.REQUEST('city') user.INFORM('city') system.REQUEST('cuisine') user.INFORM('cuisine') system.FindRestaurants() system.set_query_status(True) system.OFFER('restaurant') system.OFFER('city') system.INFORM_COUNT() user.REQUEST_ALTS() system.OFFER('restaurant') system.OFFER('city') ... ``` Action Preconditions Precondition Inference ``` def FindRestaurants(self): assert self.user.informed['city'] assert self.user.informed['cuisine'] ``` Partial Test Trajectory ``` def test(): user.INFORM('cuisine') system.REQUEST('city') user.INFORM('city') system. ``` Next action = ``` FindRestaurants() ``` Precondition-Aware Action Prediction 5681 _Proceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics:_ are adequate as they are dynamically generated. It is further difficult to guarantee with certainty that predicted actions will be consistent with the preconditions or rationales. Taking inspiration from classical AI planning literature (Aeronautiques et al., 1998; Fikes and Nilsson, 1993) and recent work that use code representations for reasoning problems, we leverage code representation to reason about preconditions. Programs are a natural formalism to model event sequences and offer the flexibility to express dependency constraints between events, such as in the form of assertions (Liang et al., 2022; Singh et al., 2022). Verifying that a program meets the specifications dictated by the assertions amounts to simply executing the program and verifying that the program ran successfully. The ability to execute and verify constraint satisfaction is a key benefit of code compared to alternative representations such as natural language. Representing preconditions in the form of procedural statements in code further provides transparency, controllability and better generalization to unseen scenarios compared to alternative representations of affordance such as neural network functions. Finally, this also enables us to exploit strong priors captured by code understanding models for policy learning problems. Armed with a code representation, we formulate precondition inference as a code completion problem and propose a zero-shot approach to infer preconditions of actions given demonstration trajectories leveraging pre-trained code models. Given these inferred preconditions, we propose a precondition-aware action prediction strategy that ensures actions predicted by a policy are consistent with the preconditions. We present extensive analysis and ablations that show the impact of different components of our approach. In summary, we make the following contributions in this work. - We propose a new approach that leverages program representations and pre-trained code models to extract action preconditions from expert demonstrations alone in a zero-shot manner. - Combining inferred preconditions with a precondition-aware action prediction strategy, we demonstrate that the proposed framework leads to better agent policies compared to baselines on task-oriented dialog and embodied textworld benchmarks. 2 Problem Setting We consider a sequential decision making setting where the agent receives a sequence of observations _oi_ _∈O_ and performs an action _ai_ _∈A_, where we assume discrete observation and action spaces _O, A_ . The agent’s trajectory can be represented as a sequence of observations and actions _τ_ = ( _o_ 1 _, a_ 1 _, o_ 2 _, a_ 2 _, . . ., on, an_ ). We consider a few-shot learning setting where we are given demonstrations _D_ = _{τ_ <sup>1</sup> _, . . ., τ_ <sup>_n_</sup> _}_ . Let _τ<t_ = ( _o_ 1: _t, a_ 1: _t−_ 1) represent the history of observations and actions. The goal of learning is two-fold. First, for each action _a_ we intend to estimate a precondition function _ga_ ( _τ<t_ ) _∈{_ 0 _,_ 1 _}_ that informs whether the action is plausible in a given context _τ<t_ (i.e., _ga_ ( _τ<t_ ) = 0 represents the action is implausible and _ga_ ( _τ<t_ ) = 1 represents the action is plausible). Given these inferred preconditions _G_ = _{ga|a_ _∈A}_, our second goal is to estimate a policy _π_ ( _at|τ<t, D, G_ ) that predicts actions _at_ consistent with the preconditions _G_ . 3 Approach We first discuss the code representation in Sec tion 3.1. We then describe our approach to precondition inference and action prediction problems in Sections 3.2 and 3.3, respectively. See Figure 1 for an overview of our approach. 3.1 Representing Agent Trajectories as Programs We represent the agent’s interaction with the envi ronment as a program. We represent every action and observation as one or more function calls that modify the state of a predefined set of variables _v_ <sup>1</sup> that capture a summary of the agent’s experience (e.g., observations _o_ 1: _t_ and actions _a_ 1: _t−_ 1). Such a representation exists since we assume discrete observation and action spaces (for instance, we can define a separate function for each string in _O, A_ ). Assume we have defined a set of functions _FO, FA_ corresponding to observations _O_ and actions _A_ respectively. Given this representation, a trajectory _τ_ can be viewed as a program which consists of a sequence of function calls. <sup>2</sup> We present an example program in Figure 1 and further examples in the Appendix. 1For instance, these could be boolean variables analogous to predicates that represent state in PDDL planning. 2We interchangeably refer to actions/observations as functions and trajectories as programs in the paper. 5682 ``` def demonstration():... class USER:.. class SYSTEM:.. def INFORM(self, slot): assert ``` ``` self.query_success!= None (self.query_success == True) (self.user.informed_slot[slot]) self.user.affirmed == True (slot in self.user.informed_slot) ... ``` Generate Candidates Validate with Execution Ranking ``` self.query_success!= None (self.query_success == True) isinstance(slot, str) self.user.requested_slot[slot] ``` ``` (self.query_success == True) self.user.requested_slot[slot] ``` Figure 2: Precondition Inference Overview : We first generate multiple precondition candidates by prompting a code model with demonstration programs. We then validate these candidates based on the demonstrations via execution, and rank them to identify the most promising candidates. 3.2 Precondition Inference Recall that the precondition function _ga_ ( _τ<t_ ) _∈_ _{_ 0 _,_ 1 _}_ informs whether an action _a_ is plausible in a given context _τ<t_ . Equivalently, for the corresponding function in the program representation _fa_ _∈FA_, we seek to identify assertion statements in terms of variables _v_ (which represent a summary of _τ<t_ ) and the function arguments of _fa_ . (For example in Figure 1, the precondition for the action FindRestaurants is identified as assert user.informed[‘city’] and user.informed[‘cuisine’]). We predict preconditions for each action independently of other actions and the process below is repeated for each action _a ∈A_ . <sup>3</sup> Our approach to precondition inference consists of the following steps: candidate generation, validation and ranking. We detail these steps next (See Appendix D for an illustration and Appendix F for example outputs from each component of the pipeline). Candidate Generation. Given demonstration trajectories _D_ we first generate candidate preconditions by prompting a pre-trained code generation model. The prompt consists of (i) a demonstration _τ_ _∈D_ (ii) definitions of functions _FO_ and (iii) definition of function _fa_ with the assert keyword in its body. The assert prefix forces the model to generate assertion statements (as opposed to arbitrary code). We vary the demonstration program and sample multiple precondition candidates for each demonstration to come up with a pool of plau _a_ . The pre-trained model is sible candidates _H_ <sup>initial</sup> expected to understand the appropriate contexts in which a function can be used and use this understanding to come up with assertion statements. Although pretrained models have strong priors about appropriate assert statements, the above process has some limitations. First, generated statements may not be meaningful due to syntax errors 3Jointly reasoning about preconditions for all functions in _FA_ can be interesting and is left to future work. or other deficiencies in the generated expressions. Second, the candidates are obtained based on static analysis of the program alone and the model has to implicitly reason about execution and program state in order to predict accurate preconditions. Candidate Validation. A key advantages of code compared to alternative representations such as natural language is the ability to execute. We augment the above candidate generation approach with a verification approach where candidates are vetted for validity and consistency with the data. Given a candidate assertion, we verify whether each of the demonstration programs can run successfully (e.g,. replacing the function body with a candidate assertion and executing a demonstration program). Candidates which led to execution failures are dis _a_ are thus carded. The remaining candidates _H_ <sup>valid</sup> valid and consistent with the data. Many of the assertions generated will not be useful in practice. For example, trivial assertions such as ‘assert True’ do not convey any useful information about instances where the function is applicable. Although all candidate assertions at this point are valid, they may be _sub-optimal_ for the purpose of constructing a policy. We seek assertions that help discriminate situations where the function is applicable. We propose a ranking mechanism to identify the most discriminative assertions. Candidate Ranking. We seek to identify a small set of precondition/assertion candidates from _H_ <sup>valid</sup> useful for constructing an agent policy. We begin with the observation that if candidates _h_ 1 _, h_ 2 are such that _h_ 2 is satisfied whenever _h_ 1 is satisfied (i.e., _h_ 1 _⇒_ _h_ 2), _h_ 1 is more desirable as it is more discriminative of the contexts where action _a_ is applicable (and hence leads to a better policy). As we discuss in the experiments, this assumption leads to high precision solutions and compromises recall. We leave alternate ranking criteria to future work. However, verifying the above property ( _h_ 1 _⇒_ _h_ 2) for given precondition candidates is generally 5683 intractable. We thus consider an approximation where we examine if the property is satisfied in scenarios that appear in the demonstration trajectories. Consider the precondition function _ga_ ( _·_ ; _h_ ) which assumes _h_ to be the precondition of action _a_ . Define _Ca_ <sup>_h_</sup> <sup>=</sup> <sup>_{_</sup> <sup>(</sup> <sup>_i, j_</sup> <sup>)</sup> <sup>_|ga_</sup> <sup>(</sup> <sup>_τ i_</sup> _<j_ <sup>;</sup> <sup>_h_</sup> <sup>)</sup> <sup>=</sup> <sup>1</sup> <sup>_, τ i_</sup> <sup>_∈D}_</sup> <sup>to be</sup> fine _Ca_ <sup>_h_</sup> <sup>=</sup> <sup>_{_</sup> <sup>(</sup> <sup>_i, j_</sup> <sup>)</sup> <sup>_|ga_</sup> <sup>(</sup> <sup>_τ i_</sup> _<j_ <sup>;</sup> <sup>_h_</sup> <sup>)</sup> <sup>=</sup> <sup>1</sup> <sup>_, τ i_</sup> <sup>_∈D}_</sup> <sup>to be</sup> the set of instances ( _i, j_ ) where precondition _h_ is satisfied at time-step _j_ of demonstration trajectory _τ_ <sup>_i_</sup> . We use _Ca_ <sup>_h_</sup> <sup>1</sup> _a_ as a proxy to determine _⊆_ _C_ <sup>_h_</sup> <sup>2</sup> whether _h_ 1 _⇒_ _h_ 2. We define the optimal set of assertion statements as in Equation (1). When multiple equivalent candidates exist, we choose one random representative to retain in set _Ha_ <sup>opt.</sup> <sup>Note that the conjunction of</sup> . _a_ <sup>_h_</sup> <sup>=</sup> <sup>_{_</sup> <sup>(</sup> <sup>_i, j_</sup> <sup>)</sup> <sup>_|ga_</sup> <sup>(</sup> <sup>_τ i_</sup> ( _i, j_ to retain in set _Ha_ <sup>opt.</sup> <sup>Note that the conjunction of</sup> _a_ _a_ . assertions in _H_ <sup>opt</sup> is equivalent to that of _H_ <sup>valid</sup> However, identifying a small set of assertions is _a_ _a_ . <sup>opt</sup> is equivalent to that of _H_ <sup>valid</sup> a small set of assertions is _a_ _a_ . assertions in _H_ <sup>opt</sup> is equivalent to that of _H_ <sup>valid</sup> However, identifying a small set of assertions is beneficial for interpretability and for providing as a prompt to models with limited context lengths. <sup>_h′_</sup> _a_ <sup>_⊂_</sup> <sup>_C_</sup> _a_ <sup>_h_</sup> _a_ <sup>_h}_</sup> (1) _a_ _H_ <sup>opt</sup> _a_ _a_ <sup>opt</sup> = _{h ∈H_ <sup>valid</sup> _a_ _a_ <sup>valid</sup> _|_ ∄ _h_ <sup>_′_</sup> _∈H_ <sup>valid</sup> _a_ s.t. _C_ <sup>_h′_</sup> <sup>valid</sup> _a_ We use the CodeGen 2B (Nijkamp et al., 2022) and StarCoder 16B (Li et al., 2023) open-source pretrained code models in our experiments. Specifically, we use the versions of these models which were further pre-trained on python code after initial pre-training on many programming languages. 4.1 Benchmarks Task Oriented Dialog Benchmark. The decision making component of a task-oriented dialog system is a dialog manager which takes as input a sequence of utterances represented as dialog acts and predicts the next action. In this setting, a user and a system (agent) take turns to speak and user utterances constitute the agent’s observations. We use the SGD dataset (Rastogi et al., 2020) in our experiments. There are 11 user acts and 11 system acts defined in the dataset, each of which takes either no argument, a single slot argument or a single intent argument. We define analogous functions _FO_ and _FA_ corresponding to each of these acts. We take an object-oriented approach and group these functions respectively under a user class and a system class. We define variables _v_ corresponding to each user action that records whether the action was performed (e.g., informed_slot[], requested_slot[] in Figure 1). We experiment with 10 domains (schemas) from the SGD dataset. 10 instances are used as demonstrations and 50 instances for testing. For evaluation purposes we manually define the ground-truth preconditions for each system action based on prior knowledge about the dialog acts. Note that these are only used for evaluation and no supervision is provided to the model about ground-truth preconditions. Embodied Textworld. We experiment with the ALFworld embodied textworld benchmark (Shridhar et al., 2020) which involves an agent interacting with an environment to perform object interaction tasks. The observations and actions are natural language statements and the agent is expected to perform a task specified using a natural language instruction (e.g., _move the keys to the table_ ). There are 9 types of actions which include interaction and navigation actions. Each of these action types take an object argument and/or a receptacle argument and we define analogous functions _FA_ . In addition, we define auxiliary functions _FO_ for adding/removing an object from the agent’s inventory and updating the set of objects visible to the agent. We define three variables _v_ that summarize the agent’s 3.3 Precondition-aware Action Prediction We pose action prediction as a code completion problem where given a partial agent trajectory, a code model is tasked with suggesting possible next actions (as functions from _FA_, with appropriate arguments). Given any policy which predicts the next action given past actions and observations, we consider a simple approach to augment the policy with precondition knowledge. Next action candidates are sampled from the policy until an action consistent with the preconditions is found or a maximum number of attempts is exceeded. The first attempt uses greedy sampling and subsequent attempts use random sampling. If random sampling does not yield an action consistent with preconditions, we default to the greedy action. We sample an action by generating tokens until a newline token is encountered. See Appendix E for pseudocode. 4 Experiments We attempt to answer the following key questions in our evaluation: (i) Is it possible to extract information about action preconditions from demonstrations of agent behavior? (ii) Is such inferred precondition information useful for building better agent policies? We use the python programming language as the code representation in our experiments due to its simplicity and popularity, as well as the recent release of code models that primarily focus on python. 5684 SGD Alfworld Model Prec Rec _F_ 1 Prec Rec _F_ 1 Neural Prec. 0.77 0.65 0.70 0.64 0.42 0.51 Prompt.(2B) 0.73 0.75 0.74 0.59 0.89 0.71 Prompt.(16B) 0.73 0.77 0.75 0.69 0.68 0.68 Ours(2B) 0.91 0.69 0.78 1.0 0.85 0.92 Ours(16B) <u>0.92</u> <u>0.78</u> <u>0.84</u> <u>1.0</u> 0.81 0.90 Table 1: Precondition Inference performance on the SGD and Alfworld benchmarks. Metrics are precision, recall and _F_ 1 score (All metrics higher _↑_ the better). The prompting baseline and our approach are evaluated with CodeGen 2B and StarCoder 16B models. experience: the set of visible objects, the agent’s inventory and states of objects in the environment (e.g., open/closed). The dataset has 6 task types. We use 2 instances from each task type as demon strations and the standard test set of the benchmark for testing. The benchmark provides ground-truth preconditions for the actions in a PDDL (Planning Domain Definition Language) representation, which we convert to python assertions for evaluation. We provide the complete program specification for these benchmarks in Appendix A. 4.2 Precondition Inference Metrics. Recall that a precondition _ga_ ( _τ<t_ ) _∈_ _{_ 0 _,_ 1 _}_ informs whether an action _a_ _∈A_ is plausible given context _τ<t_ = ( _o_ 1: _t, a_ 1: _t−_ 1). Define _Ca_ = _{_ ( _i, j_ ) _|ga_ ( _τ<j_ <sup>_i_</sup> <sup>)</sup> <sup>=</sup> <sup>1</sup> <sup>_, τ i_</sup> <sup>_∈D_</sup> <sup>test</sup> <sup>_}_</sup> <sup>to</sup> <sup>be</sup> <sup>the</sup> set of instances ( _i, j_ ) where the precondition of _Ca_ = _{_ ( _i, j_ ) _|ga_ ( _τ<j_ <sup>_i_</sup> <sup>)</sup> <sup>=</sup> <sup>1</sup> <sup>_, τ i_</sup> <sup>_∈D_</sup> <sup>test</sup> <sup>_}_</sup> <sup>to</sup> <sup>be</sup> <sup>the</sup> set of instances ( _i, j_ ) where the precondition of action _a_ is satisfied at time-step _j_ of test trajectory _τ_ <sup>_i_</sup> _∈D_ <sup>test</sup> . We define precision and recall metrics for a particular action _a_ as in Equation (2), where _Ca_ <sup>pred</sup> _, Ca_ <sup>gt</sup> <sup>respectively correspond to the predicted</sup> _a_ <sup>pred</sup> _, Ca_ <sup>gt</sup> _Ca_ <sup>pred</sup> _, Ca_ <sup>gt</sup> <sup>respectively correspond to the predicted</sup> and ground-truth preconditions. The _F_ 1 score is defined as the harmonic mean of precision and recall. These metrics are macro-averaged across all actions _a ∈A_ to obtain the final metrics. _<u>a</u>_ Prec = <sup>_<u>|C</u>_</sup> <sup>pred</sup> _|C_ _<u>a</u>_ _<u>∩</u>_ _<u>Ca</u>_ <sup>gt</sup> <sup>pred</sup> _a_ <sup><u>gt</u></sup> <sup>_|_</sup> _<u>a</u>_ _,_ Rec = <sup>_<u>|C</u>_</sup> <sup>pred</sup> _|_ _<u>a</u>_ _<u>∩</u>_ _<u>Ca</u>_ <sup>gt</sup> <sup>pred</sup> _<u>∩</u>_ _<u>Ca</u>_ <sup>gt</sup> <sup>_<u>|</u>_</sup> _|Ca_ <sup><u>gt</u></sup> <sup>_|_</sup> that the precondition of an action was satisfied, i.e., _D_ <sup>pos</sup> = _{_ ( _τ<t, at,_ 1) _|τ_ _∈D, t_ _≤_ _n}_, where _D_ is a dataset of expert trajectories. In order to construct negative instances, we assume that the precondition for every future action _at′_ ; _t_ <sup>_′_</sup> _>_ _t_ that appeared in the trajectory _τ_ apart from the ground-truth action _at_ was not satisfied. Based on this assumption we construct negative instances _D_ <sup>neg</sup> = _{_ ( _τ<t, at′,_ 0) _|t_ <sup>_′_</sup> _>_ _t, at′̸_ = _at, τ_ _∈D}_ and train a binary classifier _h_ on _D_ <sup>pos</sup> _∪D_ <sup>neg</sup> . In practice, we uniformly sample instances from _D_ <sup>pos</sup> and _D_ <sup>neg</sup> to train the classifier. We also consider a _Prompting_ baseline where we prompt a code model with a partial program specification and predict assertion statements with greedy decoding. Results. In Table 1 we compare the precondition inference performance of different methods. The precision for our models are high since the ranking criteria we adopted encourages high precision solutions. For example, in the _Restau-_ _rants_ domain of the SGD dataset, the ground truth precondition for the action INFORM(slot) is requested_slot[slot]. <sup>4</sup> However, the predicted precondition is (requested_slot[slot] and query_success==True). The models pick up the fact that query_success==True in all instances the INFORM(slot) action appeared in the demonstration trajectories. In this case precision is 1 _._ 0 since the ground truth precondition will be satisfied whenever the predicted precondition is satisfied. However, the recall is lower (0 _._ 57) since the predicted and ground-truth preconditions may not agree when query_success! =True. The Neural Precondition baseline generally underperforms other methods. The assumption that actions in the future are invalid for the current timestep does not always hold. Comparing the labels in the generated data (e.g., _D_ pos _, D_ neg) with the corresponding ground-truth labels (computed using ground-truth preconditions), we observe that the (precision, recall) of the generated labels are respectively (1, 0.74) and (1, 0.60) for the SGD and Alfworld datasets. <sup>5</sup> When ground-truth precondition labels are used for training the classifier, performance improves (F1 scores of 0.81 and 0.67 in SGD and Alfworld, respectively), but generalization to unseen scenarios is still limited. Table 2 presents qualitative prediction results for 4‘self’ and ‘user’ omitted for brevity 5Precision is 1.0 since labels in _D_ pos are guaranteed to be correct. Recall is lower since this is not the case for _D_ neg. _a_ _|C_ <sup><u>pred</u></sup> (2) _a_ <sup><u>pred</u></sup> _|_ _<u>a</u>_ <sup>gt</sup> <sup>_<u>|</u>_</sup> Baselines. We first consider a binary classifier which we call the _Neural_ _Precondition_ baseline. If we have labeled data of the form ( _τ<t, a, l_ ), where _l_ _∈{_ 0 _,_ 1 _}_ indicates whether action _a_ is plausible given context _τ<t_, we can train a binary classifier _ha_ that predicts if the precondition for _a_ is satisfied. However, in our setting, we only have positive instances where we know 5685 Ground-truth precondition Predicted precondition Prec Rec _F_ 1 def INFORM(self, slot): assert self.user.requested_slot[slot] def REQUEST(self, slot): assert not self.user.informed_slot[slot] def GOODBYE(self): assert self.user.no_more def OFFER(self, slot): assert self.query_success def INFORM_COUNT(self): assert self.query_success def OFFER_INTENT(self, intent): assert self.user.selected def CONFIRM(self, slot): assert self.user.informed_slot['to_location'] assert self.user.informed_slot['from_location'] assert self.user.informed_slot['leaving_date'] assert self.user.informed_slot['travelers'] def NOTIFY_SUCCESS(self): assert self.user.query_success def REQ_MORE(self): assert self.user.selected or self.user.no_more def FindBus(self): assert self.user.informed_slot['to_location'] assert self.user.informed_slot['from_location'] assert self.user.informed_slot['leaving_date'] def BuyBusTicket(self): assert self.user.affirmed def INFORM(self, slot): assert slot in self.user.requested_slot def REQUEST(self, slot): assert self.user.informed_slot[slot] == False def GOODBYE(self): assert self.user.no_more def OFFER(self, slot): assert self.query_success == True def INFORM_COUNT(self): assert self.query_success == True def OFFER_INTENT(self, intent): assert self.query_success == True def CONFIRM(self, slot): assert self.user.selected assert slot != 'travelers' \ or self.user.informed_slot[slot] def NOTIFY_SUCCESS(self): assert self.user.selected assert not self.user.no_more def REQ_MORE(self): assert self.user.selected def FindBus(self): assert not self.user.no_more assert self.user.informed_intent['FindBus'] assert self.user.informed_slot['leaving_date'] assert self.user.informed_slot['from_location'] def BuyBusTicket(self): assert self.user.affirmed 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.49 1 0.66 0.96 0.7 0.81 1 0.44 0.62 1 1 1 0.99 0.89 0.94 1 1 1 Table 2: Ground-truth and predicted preconditions for actions in the _Buses_ domain of the SGD benchmark, along with Precision, Recall scores for predictions. all action types in the _Buses_ domain of the SGD benchmarks. Note that our models receive no supervision about preconditions and predict these candidates by only observing expert demonstrations. We present qualitative prediction results for the Alfworld benchmark in Appendix C. Next, we analyze how these inferred action precondition can help build better agent policies. 4.3 Precondition-aware Agent Policy Metrics. In the SGD benchmark, we evaluate policy performance using actions in the demonstrations as reference. Since the agent needs to predict multiple actions in a turn, we compute _F_ 1 score treating demonstration actions as ground-truth. For the embodied textworld task, a simulation environment is available, and we define success rate (SR) which measures how often the agent successfully completed the given task. We also define precondition compatibility (Cmp.), which measures how often the predicted action is compatible with (i.e., does not violate) the ground-truth preconditions. Baselines. We consider the following baseline policy approaches. - BC : We consider a behavioral cloning baseline where a code model is fine-tuned (with LoRA) on the given expert demonstrations with a language modeling training objective. - Act (Yao et al., 2022): A few-shot prompting baseline where training demonstrations are provided as a prompt to a pre-trained model and the model predicts the next action. - ReAct (Yao et al., 2022): A variation of the _Act_ prompting strategy where the agent predicts a chain-of-thought natural language rationale before predicting each action. We design ‘think’ prompts similar to the original work and insert them as code comments in the demonstrations. At every step the agent generates an optional code comment (‘think’ step) and predicts an action. The StarCoder 16B model is used as the backbone model for all the policy methods unless specified otherwise. We use preconditions predicted by the StarCoder 16B model in all experiments. Results. We present the main results in Table 3. The table shows the performance of each baseline policy (BC, Act, ReAct) and the performance when each of these methods are augmented with preconditions inferred by our approach. We observe that the precondition-aware action sampling strategy combined with predicted preconditions lead to consistent improvements over each baseline pol 5686 SGD Alfworld Approach _F_ 1 Cmp. SR Cmp. BC 0.88 0.96 0.11 0.53 BC+Ours <u>0.89</u> <u>0.98</u> 0.14 0.74 Act 0.84 0.92 0.06 0.56 Act+Ours 0.85 0.97 0.23 <u>0.96</u> ReAct - - 0.44 0.81 ReAct+Ours - - <u>0.48</u> <u>0.96</u> Table 3: Policy performance on SGD and Alfworld benchmarks. The performance metrics are _F_ 1 score, task success rate (SR) and precondition compatibility (Cmp.) (All metrics higher _↑_ the better). icy. In particular, we observe that the proposed precondition-based reasoning approach helps models generate actions that are more accurate and consistent with ground-truth preconditions. On the Alfworld benchmark, our approach improves the success rate of the React agent from 44% to 48% and its precondition compatibility from 81% to 96%. This shows the synergistic potential of our approach and recent advances in prompting for policy learning problems such as generating natural language rationales before predicting actions. These results shows that explicitly reasoning about preconditions helps build better policies. Although few-shot prompting enables language/code models to perform tasks with limited supervision, they are generally limited by the number of demonstrations that can fit in the context window. Condensing the information in multiple trajectories in a small set of rules (e.g., preconditions) can help overcome this limitation. 4.4 Ablations and Analysis We perform a series of ablations to understand the impact of different components in our pipeline. How to incorporate precondition information? In Table 4 we analyze the impact of (i) including precondition information in the prompt and (ii) the precondition-aware action sampling strategy. Overall, while the inclusion of precondition information in the model prompt generally helps, our proposed precondition-aware action prediction strategy yields more consistent and significant improvements (e.g., 0 _._ 64 to 0 _._ 68 with predicted preconditions and 0 _._ 73 with ground-truth preconditions in the 1-shot setting). In addition, it helps predict actions that are more consistent with their Model size 16B ✗ ✗ 0.64 0.78 0.89 0.97 16B ✓ ✗ 0.65 0.77 0.90 0.97 16B ✓ ✓ <u>0.68</u> 0.90 <u>0.91</u> <u>0.99</u> Table 4: Ablation to study the effect of (a) providing preconditions as part of the prompt (column 2) and (b) precondition-aware action prediction strategy (column 3) in the SGD benchmark. The 2B model can only accommodate upto 4 demonstrations and hence is not evaluated in the 10-shot setting. preconditions (e.g., precondition compatibility improves to _>_ 0 _._ 9 for both 2B and 16B models). Amount of Supervision. Figure 3 shows model performance for varying amounts of supervision. Due to it’s maximum context size of 2048 tokens, CodeGen 2B can only accommodate upto 4 demonstrations. Knowledge about preconditions is particularly helpful when the number of demonstrations is small. Even as we increase the number of demonstrations, models continue to benefit from explicitly reasoning about preconditions. Furthermore, performance with ground-truth preconditions shows that improvements in quality of preconditions lead to improvements in policy performance. Model scale. We observe that the small model benefits more from precondition knowledge compared to the big model regardless of the amount of supervision. Enhancing the reasoning capabilities of small models is important as big models demand higher costs and computation. Leveraging precondition information and execution-based verification is a promising strategy to enhance small models. 5 Related Work Programs as Policies. There exist prior work that advocate viewing robot policies as code/programs (Liang et al., 2022; Singh et al., 2022). Similar to natural language based prompting, LLMs are prompted with examples of programs corresponding to example tasks and are required to generate programs for a query task. The programs can be rich and composed of functions supported by the target robot API or third party library functions. Code comments help break down high-level task Prec. prompt Prec. sample _F_ 1 _<u>↑</u>_ Cmp. _<u>↑</u>_ _F_ 1 _<u>↑</u>_ Cmp. _<u>↑</u>_ 1-shot 10-shot 2B ✗ ✗ 0.51 0.73 - 2B ✓ ✗ 0.52 0.75 - 2B ✓ ✓ 0.58 <u>0.92</u> - 5687 0 _._ 9 0 _._ 8 0 _._ 7 0 _._ 6 F1 No precond. (16B) Pred precond. (16B) GT precond. (16B) No precond. (2B) Pred precond. (2B) GT precond. (2B) Num demos 0 _._ 5 2 4 6 8 10 Figure 3: Ablation showing policy performance (F1 score) in the SGD benchmark when varying (a) number of demonstrations (1 to 10), (b) model scale (2B, 16B) and (c) precondition information available to policy model (None/Predicted/Ground-truth). into subtasks and assertions are used to take environment feedback into account and provide an error recovery mechanism. These prior work assume that precondition information is specified as part of the prompt. In contrast, our work attempts to discover such information from action trajectories. Programs have also been used as a representation for structured prediction tasks in NLP (Wang et al., 2022; Madaan et al., 2022; Zhang et al., 2023). These work find that code models have strong capability to reason about event sequences with minimal supervision compared to language models. Reasoning with Execution. Prior work has attempted to augment capabilities of language models with programs and execution. Liu et al. (2022) combine LLMs with a physics simulator to answer physics questions. Gao et al. (2022) interleave natural language chain-of-thought statements with program statements to perform calculations for arithmetic reasoning problems. Analogous to these work, we find that the ability to verify via execution improves the performance of LMs. Reasoning via Prompting. Chain-of-thought prompting (Wei et al., 2022) has emerged as a powerful technique for getting language models to perform step-by-step reasoning. These ideas have also been applied to planning problems (Huang et al., 2022b; Yao et al., 2022) where agents are taught how to come up with rationales for predicted actions with few-shot demonstrations. Compared to chain-of-thought rationales, which are dynamically generated on the fly and are problem-specific, we seek to identify a set of rules that capture action preconditions. This provides more controllability over the action generation process and the rules can also be vetted/edited to achieve desired behavior. Subtask Graph Framework. Subtask Graphs are a modeling framework to learn subtask preconditions (Sohn et al., 2018, 2020; Jang et al., 2023; Logeswaran et al., 2023). Preconditions are modeled as boolean expressions involving a pre-defined set of boolean subtask variables which represent whether a subtask has been completed or not. In contrast to boolean expressions as the class of functions to model preconditions, the program representation we consider has the flexibility to represent a broader set of scenarios. We draw inspiration from these works to formulate and evaluate the precondition inference component in our approach. Planning with Symbolic Problem Specifications. Symbolic problem specifications such as PDDL have been considered in classical AI planning (Aeronautiques et al., 1998). Recent approaches have augmented LLMs with PDDL problem specifications and symbolic solvers (Liu et al., 2023; Silver et al., 2023). A PDDL specification exposes the preconditions and effects of actions, described in terms of a set of predicates that describe environment state. It typically assumes deterministic, fully observable environments with known preconditions and effects and known goal state. On the other hand, our approach is more flexible and is applicable in scenarios where partial knowledge about the task and environment are available. 6 Conclusion This work presented a novel approach to reason about action preconditions using programs for learning agent policies in a sequential decision making setting. We proposed to use programs as a representation of the agent’s observations and actions and showed that precondition inference and action prediction can be formulated as codecompletion problems. By leveraging the strong priors of pre-trained code models, we proposed a novel approach to infer action preconditions from demonstration trajectories without any additional supervision. With the predicted preconditions, our precondition-aware action prediction strategy enables the agent to predict actions that are consistent with the preconditions and lead to better task completion compared to baselines. Our study opens an exciting new direction to reason about action preconditions by leveraging code models. 5688 Limitations Designing program specifications requires domain knowledge, which is a limitation of our work. For instance, we define variables such as the agent’s inventory and set of visible objects in the embodied textworld benchmark and variables that capture which slots were requested/informed in the dialog benchmark. It would be interesting to generalize our approach to broader scenarios by identifying the key variables of interest with less manual intervention. For example, this may be possible with few-shot prompting where an LLM is shown example program specifications for a few domains and is expected to come up with program specifications for new domains. It would be interesting to further explore the use of preconditions to more actively direct the agent towards task completion. References Constructions Aeronautiques, Adele Howe, Craig Raymond Li, Loubna Ben Allal, Yangtian Zi, Niklas Muennighoff, Denis Kocetkov, Chenghao Mou, Marc Marone, Christopher Akiki, Jia Li, Jenny Chim, Qian Liu, Evgenii Zheltonozhskii, Terry Yue Zhuo, Thomas Wang, Olivier Dehaene, Mishig Davaadorj, Joel Lamy-Poirier, João Monteiro, Oleh Shliazhko, Nicolas Gontier, Nicholas Meade, Armel Zebaze, Ming-Ho Yee, Logesh Kumar Umapathi, Jian Zhu, Benjamin Lipkin, Muhtasham Oblokulov, Zhiruo Wang, Rudra Murthy, Jason Stillerman, Siva Sankalp Patel, Dmitry Abulkhanov, Marco Zocca, Manan Dey, Zhihan Zhang, Nour Fahmy, Urvashi Bhattacharyya, Wenhao Yu, Swayam Singh, Sasha Luccioni, Paulo Villegas, Maxim Kunakov, Fedor Zhdanov, Manuel Romero, Tony Lee, Nadav Timor, Jennifer Ding, Claire Schlesinger, Hailey Schoelkopf, Jan Ebert, Tri Dao, Mayank Mishra, Alex Gu, Jennifer Robinson, Carolyn Jane Anderson, Brendan Dolan-Gavitt, Danish Contractor, Siva Reddy, Daniel Fried, Dzmitry Bahdanau, Yacine Jernite, Carlos Muñoz Ferrandis, Sean Hughes, Thomas Wolf, Arjun Guha, Leandro von Werra, and Harm de Vries. 2023. [Starcoder: may](http://arxiv.org/abs/2305.06161) [the source be with you!](http://arxiv.org/abs/2305.06161) 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 language. _Technical_ Jacky Liang, Wenlong Huang, Fei Xia, Peng Xu, Karol Hausman, Brian Ichter, Pete Florence, and Andy Zeng. 2022. Code as policies: Language model programs for embodied control. _arXiv_ _preprint_ _arXiv:2209.07753_ . Bo Liu, Yuqian Jiang, Xiaohan Zhang, Qiang Liu, Shiqi Zhang, Joydeep Biswas, and Peter Stone. 2023. Llm+ p: Empowering large language models with optimal planning proficiency. _arXiv preprint_ _arXiv:2304.11477_ . _Report, Tech. Rep._ Michael Ahn, Anthony Brohan, Noah Brown, Yevgen Chebotar, Omar Cortes, Byron David, Chelsea Finn, Keerthana Gopalakrishnan, Karol Hausman, Alex Herzog, et al. 2022. Do as i can, not as i say: Grounding language in robotic affordances. _arXiv preprint_ _arXiv:2204.01691_ . Richard E Fikes and Nils J Nilsson. 1993. Strips, a retrospective. _Artificial_ _intelligence_, 59(1-2):227– 232. Ruibo Liu, Jason Wei, Shixiang Shane Gu, Te-Yen Wu, Soroush Vosoughi, Claire Cui, Denny Zhou, and Andrew M Dai. 2022. Mind’s eye: Grounded language model reasoning through simulation. _arXiv preprint_ _arXiv:2210.05359_ . Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon, Pengfei Liu, Yiming Yang, Jamie Callan, and Graham Neubig. 2022. Pal: Program-aided language models. _arXiv preprint arXiv:2211.10435_ . Lajanugen Logeswaran, Yao Fu, Moontae Lee, and Honglak Lee. 2022. Few-shot subgoal planning with language models. _arXiv preprint arXiv:2205.14288_ . Wenlong Huang, Pieter Abbeel, Deepak Pathak, and Igor Mordatch. 2022a. Language models as zeroshot planners: Extracting actionable knowledge for embodied agents. In _International_ _Conference_ _on_ _Machine Learning_, pages 9118–9147. PMLR. Lajanugen Logeswaran, Sungryull Sohn, Yunseok Jang, Moontae Lee, and Honglak Lee. 2023. Unsupervised task graph generation from instructional video transcripts. _arXiv preprint arXiv:2302.09173_ . 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: Embodied reasoning through planning with language models. _arXiv_ _preprint arXiv:2207.05608_ . Yunseok Jang, Sungryull Sohn, Lajanugen Logeswaran, Tiange Luo, Moontae Lee, and Honglak Lee. 2023. Multimodal subtask graph generation from instructional videos. _arXiv preprint arXiv:2302.08672_ . Aman Madaan, Shuyan Zhou, Uri Alon, Yiming Yang, and Graham Neubig. 2022. Language models of code are few-shot commonsense learners. _arXiv preprint_ _arXiv:2210.07128_ . Vincent Micheli and François Fleuret. 2021. Language models are few-shot butlers. _arXiv_ _preprint_ _arXiv:2104.07972_ . Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and Caiming Xiong. 2022. Codegen: An open large language model for code with multi-turn program synthesis. _arXiv preprint arXiv:2203.13474_ . 5689 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_, volume 34, pages 8689–8696. Mohit Shridhar, Xingdi Yuan, Marc-Alexandre Côté, Yonatan Bisk, Adam Trischler, and Matthew Hausknecht. 2020. Alfworld: Aligning text and embodied environments for interactive learning. _arXiv_ _preprint arXiv:2010.03768_ . Tom Silver, Soham Dan, Kavitha Srinivas, Joshua B Tenenbaum, Leslie Pack Kaelbling, and Michael Katz. 2023. Generalized planning in pddl domains with pretrained large language models. _arXiv_ _preprint arXiv:2305.11014_ . Ishika Singh, Valts Blukis, Arsalan Mousavian, Ankit Goyal, Danfei Xu, Jonathan Tremblay, Dieter Fox, Jesse Thomason, and Animesh Garg. 2022. Progprompt: Generating situated robot task plans using large language models. _arXiv_ _preprint_ _arXiv:2209.11302_ . Sungryull Sohn, Junhyuk Oh, and Honglak Lee. 2018. Hierarchical reinforcement learning for zero-shot generalization with subtask dependencies. _Advances_ _in neural information processing systems_, 31. Sungryull Sohn, Hyunjae Woo, Jongwook Choi, and Honglak Lee. 2020. Meta reinforcement learning with autonomous inference of subtask dependencies. _arXiv preprint arXiv:2001.00248_ . Xingyao Wang, Sha Li, and Heng Ji. 2022. Code4struct: Code generation for few-shot structured prediction from natural language. _arXiv_ _preprint_ _arXiv:2210.12810_ . 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_ . 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_ . Li Zhang, Hainiu Xu, Yue Yang, Shuyan Zhou, Weiqiu You, Manni Arora, and Chris Callison-Burch. 2023. Causal reasoning of entities and events in procedural texts. _arXiv preprint arXiv:2301.10896_ . 5690 A Program Specification We present the program specification for the _Restaurants_ domain in the SGD benchmark in Figure 4 and the Alfworld benchmark in Figure 5. from collections import defaultdict class USER : def __init__(self): self.informed_intent = defaultdict( lambda : False ) self.informed_slot = defaultdict( lambda : False ) self.requested_slot = defaultdict( lambda : False ) self.no_more = False self.selected = False self.affirmed = False self.affirm_intent = False self.negate_intent = False self.request_alternatives = False def INFORM_INTENT(self, intent): self.informed_intent[intent] = True def NEGATE_INTENT(self): self.negate_intent = True def AFFIRM_INTENT(self): self.affirm_intent = True def REQUEST_ALTS(self): self.request_alternatives = True def INFORM(self, slot): self.informed_slot[slot] = True def REQUEST(self, slot): self.requested_slot[slot] = True def GOODBYE(self): self.no_more = True def THANK_YOU(self): self.no_more = True def SELECT(self): self.selected = True def AFFIRM(self): self.affirmed = True def NEGATE(self): self.affirmed = False class SYSTEM : def __init__(self, user): self.user = user self.query_success = None def INFORM(self, slot): assert self.user.requested_slot[slot] def REQUEST(self, slot): assert not self.user.informed_slot[slot] def GOODBYE(self): assert self.user.no_more def FindRestaurants(self): assert self.user.informed_slot['city'] assert self.user.informed_slot['cuisine'] assert self.user.informed_intent['FindRestaurants'] def ReserveRestaurant(self): assert self.user.selected or self.user.affirmed def OFFER(self, slot): assert self.query_success or self.user.affirmed def INFORM_COUNT(self): assert self.query_success def OFFER_INTENT(self, intent): assert self.user.selected def CONFIRM(self, slot): assert self.user.informed_slot['time'] assert self.user.informed_slot['city'] assert self.user.selected or \ self.user.informed_slot['restaurant_name'] def NOTIFY_SUCCESS(self): assert self.query_success def NOTIFY_FAILURE(self): assert not self.query_success def REQ_MORE(self): assert self.user.selected or self.user.no_more or \ not self.query_success def set_query_status(self, status): self.query_success = status Figure 4: Program specification of the _Restaurants_ domain in the SGD benchmark. Note that the assertion statements are assumed to be unknown and only used for evaluation. 5691 from collections import defaultdict class Environment : def __init__(self): self.object_states = defaultdict( lambda : False ) def set_property(self, obj, property, value): self.object_states[(obj, property)] = value def get_property(self, obj, property): return self.object_states[(obj, property)] class Agent : def __init__(self, env): self.env = env self.inventory = None self.visible_objects = set() def add_inventory(self, obj): self.inventory = obj def remove_inventory(self, obj): self.inventory = None def update_visible_objects(self, *args): self.visible_objects.update(list(args)) def is_visible(self, obj): return obj in self.visible_objects def goto(self, recep): assert self.is_visible(recep) def open(self, recep): assert self.is_visible(recep) assert self.env.get_property(recep, 'open') == False def close(self, recep): assert self.is_visible(recep) assert self.env.get_property(recep, 'open') == True def take(self, obj, recep): assert self.is_visible(obj) assert self.is_visible(recep) assert self.inventory == None, 'Can only hold one object at a time' def put(self, obj, recep): assert self.inventory == obj, 'Need to be holding the object' assert self.is_visible(recep) def clean(self, obj, recep): assert self.is_visible(recep) assert self.inventory == obj, 'Need to be holding the object' assert 'sink' in recep def heat(self, obj, recep): assert self.is_visible(recep) assert self.inventory == obj, 'Need to be holding the object' assert 'microwave' in recep def cool(self, obj, recep): assert self.is_visible(recep) assert self.inventory == obj, 'Need to be holding the object' assert 'fridge' in recep def toggle(self, obj): assert self.is_visible(obj) Figure 5: Program specification of the Alfworld benchmark. Note that the assertion statements are assumed to be unknown and only used for evaluation. 5692 B Example Trajectories Figure 6 shows an example trajectory from the _Restaurants_ domain in the SGD benchmark and the corresponding program representation. Figures 7 and 8 show an example trajectory from the _pick and_ _place_ task of the Alfworld benchmark in its original text representation and the corresponding program representation. <mark>USER:</mark> <mark>(INFORM_INTENT,</mark> <mark>FindRestaurants)</mark> <mark>SYSTEM:</mark> <mark>(REQUEST,</mark> <mark>city)</mark> <mark>USER:</mark> <mark>(INFORM,</mark> <mark>city)</mark> <mark>SYSTEM:</mark> <mark>(REQUEST,</mark> <mark>cuisine)</mark> <mark>USER:</mark> <mark>(INFORM,</mark> <mark>cuisine)</mark> <mark>SYSTEM:</mark> <mark>(FindRestaurants)</mark> <mark>(Query</mark> <mark>successful)</mark> <mark>(OFFER,</mark> <mark>restaurant_name)</mark> <mark>(OFFER,</mark> <mark>city)</mark> <mark>(INFORM_COUNT)</mark> <mark>USER:</mark> <mark>(REQUEST_ALTS)</mark> <mark>SYSTEM:</mark> <mark>(OFFER,</mark> <mark>restaurant_name)</mark> <mark>(OFFER,</mark> <mark>city)</mark> <mark>USER:</mark> <mark>(REQUEST,</mark> <mark>has_live_music)</mark> <mark>SYSTEM:</mark> <mark>(INFORM,</mark> <mark>has_live_music)</mark> <mark>USER:</mark> <mark>(INFORM_INTENT,</mark> <mark>ReserveRestaurant)</mark> <mark>(SELECT)</mark> <mark>SYSTEM:</mark> <mark>(REQUEST,</mark> <mark>time)</mark> <mark>USER:</mark> <mark>(INFORM,</mark> <mark>time)</mark> <mark>SYSTEM:</mark> <mark>(CONFIRM,</mark> <mark>restaurant_name)</mark> <mark>(CONFIRM,</mark> <mark>city)</mark> <mark>(CONFIRM,</mark> <mark>time)</mark> <mark>(CONFIRM,</mark> <mark>party_size)</mark> <mark>(CONFIRM,</mark> <mark>date)</mark> <mark>USER:</mark> <mark>(INFORM,</mark> <mark>date)</mark> <mark>(NEGATE)</mark> <mark>SYSTEM:</mark> <mark>(CONFIRM,</mark> <mark>time)</mark> <mark>(CONFIRM,</mark> <mark>date)</mark> <mark>USER:</mark> <mark>(INFORM,</mark> <mark>time)</mark> <mark>(NEGATE)</mark> <mark>SYSTEM:</mark> <mark>(CONFIRM,</mark> <mark>time)</mark> <mark>(CONFIRM,</mark> <mark>date)</mark> <mark>USER:</mark> <mark>(AFFIRM)</mark> <mark>SYSTEM:</mark> <mark>(ReserveRestaurant)</mark> <mark>(Query</mark> <mark>successful)</mark> <mark>(NOTIFY_SUCCESS)</mark> <mark>USER:</mark> <mark>(REQUEST,</mark> <mark>serves_alcohol)</mark> <mark>SYSTEM:</mark> <mark>(INFORM,</mark> <mark>serves_alcohol)</mark> <mark>USER:</mark> <mark>(THANK_YOU)</mark> <mark>(GOODBYE)</mark> <mark>SYSTEM:</mark> <mark>(GOODBYE)</mark> user.INFORM_INTENT('FindRestaurants') system.REQUEST('city') user.INFORM('city') system.REQUEST('cuisine') user.INFORM('cuisine') system.FindRestaurants() system.set_query_status( True ) system.OFFER('restaurant_name') system.OFFER('city') system.INFORM_COUNT() user.REQUEST_ALTS() system.OFFER('restaurant_name') system.OFFER('city') user.REQUEST('has_live_music') system.INFORM('has_live_music') user.INFORM_INTENT('ReserveRestaurant') user.SELECT() system.REQUEST('time') user.INFORM('time') system.CONFIRM('restaurant_name') system.CONFIRM('city') system.CONFIRM('time') system.CONFIRM('party_size') system.CONFIRM('date') user.INFORM('date') user.NEGATE() system.CONFIRM('time') system.CONFIRM('date') user.INFORM('time') user.NEGATE() system.CONFIRM('time') system.CONFIRM('date') user.AFFIRM() system.ReserveRestaurant() system.set_query_status( True ) system.NOTIFY_SUCCESS() user.REQUEST('serves_alcohol') system.INFORM('serves_alcohol') user.THANK_YOU() user.GOODBYE() system.GOODBYE() Figure 6: Example trajectory from the _Restaurants_ domain of the SGD benchmark. The original data representation is shown on the left and the corresponding program representation is shown on the right. 5693 <mark>You</mark> <mark>are</mark> <mark>in</mark> <mark>the</mark> <mark>middle</mark> <mark>of</mark> <mark>a</mark> <mark>room.</mark> <mark>Looking</mark> <mark>quickly</mark> <mark>around</mark> <mark>you,</mark> <mark>you</mark> <mark>see</mark> <mark>a</mark> <mark>countertop</mark> <mark>1,</mark> <mark>a</mark> <mark>drawer</mark> <mark>1,</mark> <mark>a</mark> <mark>drawer</mark> <mark>2,</mark> <mark>a</mark> <mark>drawer</mark> <mark>3,</mark> <mark>a</mark> <mark>drawer</mark> <mark>4,</mark> <mark>a</mark> <mark>drawer</mark> <mark>5,</mark> <mark>a</mark> <mark>drawer</mark> <mark>6,</mark> <mark>a</mark> <mark>garbagecan</mark> <mark>1,</mark> <mark>a</mark> <mark>handtowelholder</mark> <mark>1,</mark> <mark>a</mark> <mark>handtowelholder</mark> <mark>2,</mark> <mark>a</mark> <mark>sinkbasin</mark> <mark>1,</mark> <mark>a</mark> <mark>toilet</mark> <mark>1,</mark> <mark>a</mark> <mark>toiletpaperhanger</mark> <mark>1,</mark> <mark>a</mark> <mark>towelholder</mark> <mark>1,</mark> <mark>and</mark> <mark>a</mark> <mark>towelholder</mark> <mark>2.</mark> <mark>Your</mark> <mark>task</mark> <mark>is</mark> <mark>to:</mark> <mark>put</mark> <mark>some</mark> <mark>spraybottle</mark> <mark>on</mark> <mark>garbagecan</mark> <mark>></mark> <mark>go</mark> <mark>to</mark> <mark>drawer</mark> <mark>4</mark> <mark>The</mark> <mark>drawer</mark> <mark>4</mark> <mark>is</mark> <mark>closed.</mark> <mark>></mark> <mark>open</mark> <mark>drawer</mark> <mark>4</mark> <mark>You</mark> <mark>open</mark> <mark>the</mark> <mark>drawer</mark> <mark>4.</mark> <mark>The</mark> <mark>drawer</mark> <mark>4</mark> <mark>is</mark> <mark>open.</mark> <mark>In</mark> <mark>it,</mark> <mark>you</mark> <mark>see</mark> <mark>nothing.</mark> <mark>></mark> <mark>close</mark> <mark>drawer</mark> <mark>4</mark> <mark>You</mark> <mark>close</mark> <mark>the</mark> <mark>drawer</mark> <mark>4.</mark> <mark>></mark> <mark>go</mark> <mark>to</mark> <mark>drawer</mark> <mark>2</mark> <mark>The</mark> <mark>drawer</mark> <mark>2</mark> <mark>is</mark> <mark>closed.</mark> <mark>></mark> <mark>open</mark> <mark>drawer</mark> <mark>2</mark> <mark>You</mark> <mark>open</mark> <mark>the</mark> <mark>drawer</mark> <mark>2.</mark> <mark>The</mark> <mark>drawer</mark> <mark>2</mark> <mark>is</mark> <mark>open.</mark> <mark>In</mark> <mark>it,</mark> <mark>you</mark> <mark>see</mark> <mark>nothing.</mark> <mark>></mark> <mark>close</mark> <mark>drawer</mark> <mark>2</mark> <mark>You</mark> <mark>close</mark> <mark>the</mark> <mark>drawer</mark> <mark>2.</mark> <mark>></mark> <mark>go</mark> <mark>to</mark> <mark>drawer</mark> <mark>3</mark> <mark>The</mark> <mark>drawer</mark> <mark>3</mark> <mark>is</mark> <mark>closed.</mark> <mark>></mark> <mark>open</mark> <mark>drawer</mark> <mark>3</mark> <mark>You</mark> <mark>open</mark> <mark>the</mark> <mark>drawer</mark> <mark>3.</mark> <mark>The</mark> <mark>drawer</mark> <mark>3</mark> <mark>is</mark> <mark>open.</mark> <mark>In</mark> <mark>it,</mark> <mark>you</mark> <mark>see</mark> <mark>nothing.</mark> <mark>></mark> <mark>close</mark> <mark>drawer</mark> <mark>3</mark> <mark>You</mark> <mark>close</mark> <mark>the</mark> <mark>drawer</mark> <mark>3.</mark> <mark>></mark> <mark>go</mark> <mark>to</mark> <mark>countertop</mark> <mark>1</mark> <mark>On</mark> <mark>the</mark> <mark>countertop</mark> <mark>1,</mark> <mark>you</mark> <mark>see</mark> <mark>a</mark> <mark>sink</mark> <mark>1,</mark> <mark>a</mark> <mark>soapbottle</mark> <mark>1,</mark> <mark>and</mark> <mark>a</mark> <mark>toiletpaper</mark> <mark>1.</mark> <mark>></mark> <mark>go</mark> <mark>to</mark> <mark>toilet</mark> <mark>1</mark> <mark>On</mark> <mark>the</mark> <mark>toilet</mark> <mark>1,</mark> <mark>you</mark> <mark>see</mark> <mark>a</mark> <mark>cloth</mark> <mark>1,</mark> <mark>and</mark> <mark>a</mark> <mark>spraybottle</mark> <mark>1.</mark> <mark>></mark> <mark>take</mark> <mark>spraybottle</mark> <mark>1</mark> <mark>from</mark> <mark>toilet</mark> <mark>1</mark> <mark>You</mark> <mark>pick</mark> <mark>up</mark> <mark>the</mark> <mark>spraybottle</mark> <mark>1</mark> <mark>from</mark> <mark>the</mark> <mark>toilet</mark> <mark>1.</mark> <mark>></mark> <mark>go</mark> <mark>to</mark> <mark>garbagecan</mark> <mark>1</mark> <mark>On</mark> <mark>the</mark> <mark>garbagecan</mark> <mark>1,</mark> <mark>you</mark> <mark>see</mark> <mark>nothing.</mark> <mark>></mark> <mark>put</mark> <mark>spraybottle</mark> <mark>1</mark> <mark>in/on</mark> <mark>garbagecan</mark> <mark>1</mark> <mark>You</mark> <mark>put</mark> <mark>the</mark> <mark>spraybottle</mark> <mark>1</mark> <mark>in/on</mark> <mark>the</mark> <mark>garbagecan</mark> <mark>1.</mark> Figure 7: Example trajectory from the _pick and place_ task of the Alfworld benchmark in its original text representation. def put_some_spraybottle_on_garbagecan(): # put some spraybottle on garbagecan. env = Environment() agent = Agent(env) agent.update_visible_objects('countertop 1', 'drawer 1', 'drawer 2', 'drawer 3', 'drawer 4', 'drawer 5', \ 'drawer 6', 'garbagecan 1', 'handtowelholder 1', 'handtowelholder 2', 'sinkbasin 1', 'toilet 1', \ 'toiletpaperhanger 1', 'towelholder 1', 'towelholder 2') agent.goto('drawer 4') env.set_property('drawer 4', 'open', False ) agent.open('drawer 4') env.set_property('drawer 4', 'open', True ) agent.close('drawer 4') env.set_property('drawer 4', 'open', False ) agent.goto('drawer 2') env.set_property('drawer 2', 'open', False ) agent.open('drawer 2') env.set_property('drawer 2', 'open', True ) agent.close('drawer 2') env.set_property('drawer 2', 'open', False ) agent.goto('drawer 3') env.set_property('drawer 3', 'open', False ) agent.open('drawer 3') env.set_property('drawer 3', 'open', True ) agent.close('drawer 3') env.set_property('drawer 3', 'open', False ) agent.goto('countertop 1') agent.update_visible_objects('countertop 1', 'sink 1', 'soapbottle 1', 'toiletpaper 1') agent.goto('toilet 1') agent.update_visible_objects('toilet 1', 'cloth 1', 'spraybottle 1') agent.take('spraybottle 1', 'toilet 1') agent.add_inventory('spraybottle 1') agent.goto('garbagecan 1') agent.update_visible_objects('garbagecan 1') agent.put('spraybottle 1', 'garbagecan 1') agent.remove_inventory('spraybottle 1') Figure 8: Example trajectory from the _pick and place_ task of the Alfworld benchmark in our program representation. 5694 C Qualitative Prediction Results for Alfworld Figure 9 shows precondition prediction results for the Alfworld benchmark. # Ground-Truth Preconditions def goto(self, recep): assert self.is_visible(recep) def open(self, recep): assert self.is_visible(recep) assert self.env.get_property(recep, 'open') == False def close(self, recep): assert self.is_visible(recep) assert self.env.get_property(recep, 'open') == True def take(self, obj, recep): assert self.is_visible(obj) assert self.is_visible(recep) assert self.inventory == None def put(self, obj, recep): assert self.inventory == obj assert self.is_visible(recep) def clean(self, obj, recep): assert self.is_visible(recep) assert self.inventory == obj assert 'sink' in recep def heat(self, obj, recep): assert self.is_visible(recep) assert self.inventory == obj assert 'microwave' in recep def cool(self, obj, recep): assert self.is_visible(recep) assert self.inventory == obj assert 'fridge' in recep def toggle(self, obj): assert self.is_visible(obj) # Predicted Preconditions def goto(self, recep): assert self.is_visible(recep) def open(self, recep): assert recep in self.visible_objects assert self.env.get_property(recep, 'open') is False def close(self, recep): assert self.env.get_property(recep, 'open') def take(self, obj, recep): assert self.is_visible(obj) assert self.inventory is None def put(self, obj, recep): assert obj in self.inventory def clean(self, obj, recep): assert obj in self.inventory def heat(self, obj, recep): assert self.inventory != None assert self.env.get_property(obj, 'heat') == False def cool(self, obj, recep): assert obj in self.inventory assert self.env.get_property(obj, 'cool') == False def toggle(self, obj): assert self.is_visible(obj) assert self.inventory is not None Figure 9: Ground-truth and predicted preconditions for actions in the Alfworld benchmark. 5695 D Precondition Inference Figure 10 illustrates the pipeline for action precondition generation. Generate candidate preconditions Validate with Execution Candidate Ranking def demonstration():.. class USER:.. class SYSTEM:.. def INFORM(self, slot): assert Code model ⁃ isinstance(slot, str) ⁃ self.db_status in DB_STATUS ⁃ (len(slot) > 0) ⁃ not self.db_status == DB_STATUS.NONE ⁃ self.user.requested_slot[slot] ... def demonstration():.. class USER:.. class SYSTEM:.. def INFORM(self, slot): assert isinstance(slot, str) demonstration() def demonstration():.. class USER:.. class SYSTEM:.. def INFORM(self, slot): assert self.user.informed_slot[slot] demonstration() (self.user.no_more == False) not self.user.no_more" self.user.informed_slot[slot] == False isinstance(slot, str) self.db_status in DB_STATUS (len(slot) > 0) not self.user.informed_intent[slot] Figure 10: Precondition Inference Overview : We first generate multiple precondition candidates by prompting a code model with demonstration programs. We then validate these candidates based on the demonstrations via execution, and rank them to identify the most promising candidates. E Precondition-aware Action Prediction Algorithm 1 presents the pseudocode for our precondition-aware action sampling strategy. <u>Algorithm 1</u> <u>Sample Next Action with Verifcationi</u> Inputs : query, max_attempts verified _←_ _False_ attempts _←_ 0 prediction _←_ GREEDYSAMPLE(query) while not verified and attempts < max_attempts do if attempts _>_ 0 then prediction _←_ RANDOMSAMPLE(query) program _←_ query + prediction verified _←_ VERIFYPROGRAM(program) attempts _←_ attempts + 1 if not verified then prediction _←_ GREEDYSAMPLE(query) <u>Outputs</u> : prediction, verified 5696 F Precondition Inference Example Below we present an example showing the intermediate outputs of the precondition inference pipeline for action INFORM in the _Restaurants_ domain of the SGD benchmark. The INFORM action takes a slot argument and the function syntax is INFORM(self, slot) (See the full program specification in Appendix A). _a_ by prompting a code model with demonstrations - Generate candidate preconditions _H_ <sup>initial</sup> not self.user.requested_slot[slot], 'Requested slot' self.query_success!= None (self.query_success == True ) (self.query_success) self.query_success is not None (self.user.informed_slot[slot]) self.query_success is None (slot in self.user.informed_slot) slot not in self.user.requested_slot.keys() self.user.affirmed == True self.user.affirmed (hasattr(slot, '__name__')) isinstance(slot, str) slot!= 'date' self.query_success in ( True, False ) slot!='serves_alcohol' self.user.requested_slot[slot] _a_ based on execution against the demonstration programs - Identify valid candidates _H_ <sup>valid</sup> self.query_success!= None (self.query_success == True ) (self.query_success) self.query_success is not None isinstance(slot, str) slot!= 'date' self.query_success in ( True, False ) self.user.requested_slot[slot] - Identify candidates that are functionally equivalent # Cluster 0 self.query_success!= None self.query_success is not None self.query_success in ( True, False ) # Cluster 1 (self.query_success == True ) (self.query_success) # Cluster 2 isinstance(slot, str) slot!= 'date' # Cluster 3 self.user.requested_slot[slot] - Identify the precondition clusters that satisfy Equation (1) # Cluster 1 (subsumes both cluster 0 and 2) (self.query_success == True ) (self.query_success) # Cluster 3 self.user.requested_slot[slot] _a_ - Choose single representative (randomly) from each cluster to construct _H_ <sup>opt</sup> (self.query_success == True ) self.user.requested_slot[slot] 5697

섹션 본문 62문단 · 34,239자

(제목 없음)

1One of the fundamental skills required for an agent acting in an environment to complete tasks is the ability to understand what actions are plausible at any given point.This work explores a novel use of code representations to reason about action preconditions for sequential decision making tasks.Code representations offer the flexibility to model procedural activities and associated constraints as well as the ability to execute and verify constraint satisfaction.Leveraging code representations, we extract action preconditions from demonstration trajectories in a zero-shot manner using pre-trained code models.Given these extracted preconditions, we propose a precondition-aware action sampling strategy that ensures actions predicted by a policy are consistent with preconditions.We demonstrate that the proposed approach enhances the performance of few-shot policy learning approaches across task-oriented dialog and embodied textworld benchmarks.

INTRODUCTION

2A key capability for learning an optimal agent policy in sequential decision making settings is understanding the plausibility of different actions.For instance, a dialog agent recommending restaurants needs to have basic information like location and type of food in order to look up its database for potential options.Understanding the necessary conditions for performing an action (e.g., location and type of food are necessary for the database lookup action) is referred to as precondition inference or affordance learning in the literature (Ahn et al., 2022;Sohn et al., 2020).Knowledge about preconditions has broad implications for policy learning and safety applications.

3Few-shot prompted large language models (LLMs) have demonstrated strong capabilities for task planning (Logeswaran et al., 2022;Huang et al., 2022a;Micheli & Fleuret, 2021;Ahn et al., 2022).However, they lack a systematic mechanism to reason about action preconditions.Some approaches attempt to teach LLMs preconditions by providing examples in the form of code assertions (Singh et al., 2022;Liang et al., 2022) or natural language rationales (Huang et al., 2022b;Yao et al., 2022).Preconditions or rationales for predicted actions are generated dynamically on-the-fly the during inference.However, it is non-trivial to verify whether these preconditions or rationales are adequate as they are dynamically generated.It is further difficult to guarantee with certainty that predicted actions will be consistent with the preconditions or rationales.

4Taking inspiration from classical AI planning literature (Aeronautiques et al., 1998;Fikes & Nilsson, 1993) and recent work that use code representations for reasoning problems, we leverage code representation to reason about preconditions.Programs are a natural formalism to model event sequences and offer the flexibility to express dependency constraints between events, such as in the form of assertions (Liang et al., 2022;Singh et al., 2022).Verifying that a program meets the specifications dictated by the assertions amounts to simply executing the program and verifying that the program ran successfully.The ability to execute and verify constraint satisfaction is a key benefit of code as a representations compared to alternative representations such as natural language.Representing preconditions in the form of procedural statements in code further provides transparency, controllability and better generalization to unseen scenarios compared to alternative representations of affordance such as neural network functions.Finally, this also enables us to exploit strong priors captured by code understanding models for policy learning problems.We propose a framework to extract action preconditions from demonstration trajectories by leveraging code representation and pre-trained code models.Extracted preconditions are used to construct an agent policy that predicts actions consistent with preconditions.

5Armed with a code representation, we formulate precondition inference as a code completion problem and propose a zero-shot approach to infer preconditions of actions given demonstration trajectories leveraging pre-trained code models.Given these inferred preconditions, we propose a precondition-aware action prediction strategy that ensures actions predicted by a policy are consistent with the preconditions.We present extensive analysis and ablations that show the impact of different components of our approach.

6In summary, we make the following contributions in this work.

7• We propose a new approach that leverages program representations and pre-trained code models to extract action preconditions from expert demonstrations alone in a zero-shot manner.• Combining inferred preconditions with a precondition-aware action prediction strategy, we demonstrate that the proposed framework leads to better agent policies compared to baselines on taskoriented dialog and embodied textworld benchmarks.

PROBLEM SETTING

8We consider a sequential decision making setting where the agent receives a sequence of observations o i ∈ O and performs an action a i ∈ A, where we assume discrete observation and action spaces O, A. The agent's trajectory can be represented as a sequence of observations and actions τ = (o 1 , a 1 , o 2 , a 2 , . . ., o n , a n ).We consider a few-shot learning setting where we are given demonstrations D = {τ 1 , . . ., τ n }.

9Let τ <t = (o 1:t , a 1:t−1 ) represent the history of observations and actions.The goal of learning is two-fold.First, for each action a we intend to estimate a precondition function g a (τ <t ) ∈ {0, 1} that informs whether the action is plausible in a given context τ <t (i.e., g a (τ <t ) = 0 represents the action is implausible and g a (τ <t ) = 1 represents the action is plausible).

APPROACH

10We first discuss the code representation in Section 3.1.We then describe our approach to precondition inference and action prediction problems in Sections 3.2 and 3.3, respectively.See Figure 1 for an overview of our approach.

REPRESENTING AGENT TRAJECTORIES AS PROGRAMS

11We represent the agent's interaction with the environment as a program.We represent every action and observation as one or more function calls that modify the state of a predefined set of variables v that capture a summary of the agent's experience (e.g., observations o 1:t and actions a 1:t−1 ).1 Such a representation exists since we assume discrete observation and action spaces (for instance, we can define a separate function for each string in O, A).Assume we have defined a set of functions F O , F A corresponding to observations O and actions A respectively.Given this representation, a trajectory τ can be viewed as a program which consists of a sequence of function calls. 2 We present an example program in Figure 1 and further examples in the Appendix.

PRECONDITION INFERENCE

12Recall that the precondition function g a (τ <t ) ∈ {0, 1} informs whether an action a is plausible in a given context τ <t .Equivalently, for the corresponding function in the program representation f a ∈ F A , we seek to identify assertion statements in terms of variables v (which represent a summary of τ <t ) and the function arguments of f a .(For example in Figure 1, the precondition for the action FindRestaurants is identified as assert user.informed['city'] and user.informed['cuisine']).

13We predict the preconditions for each action independently of other actions and the process described below is repeated for each action a ∈ A.3 Our approach to precondition inference consists of the following steps: candidate generation, validation and ranking.We detail these steps next (See Appendix D for an illustration and Appendix F for example outputs from each component of the pipeline).

14Candidate Generation.Given demonstration trajectories D we first generate candidate preconditions by prompting a pre-trained code generation model.The prompt consists of (i) a demonstration τ ∈ D (ii) definitions of functions F O and (iii) definition of function f a with the assert keyword in its body.The assert prefix forces the model to generate assertion statements (as opposed to arbitrary code).We vary the demonstration program and sample multiple precondition candidates for each demonstration to come up with a pool of plausible candidates H initial a .The pre-trained model is expected to understand what are appropriate contexts in which a function can be used and use this understanding to come up with assertion statements.

15Although pretrained models have strong priors about appropriate assert statements, the above process has some limitations.First, generated statements may not be meaningful due to syntax errors or other deficiencies in the generated expressions.Second, the candidates are obtained based on static analysis of the program alone and the model has to implicitly reason about execution and program state in order to predict accurate preconditions.

16Candidate Validation.One of the key advantages of a program representation as opposed to alternative representations such as natural language is the ability to execute.We augment the above candidate generation approach with a verification approach where each candidate is vetted for validity and consistency with the data.Given a candidate assertion, we verify whether each of the demonstration programs can run successfully (e.g,.replacing the function body with a candidate assertion and executing a demonstration program).Candidates which led to execution failures are discarded.The remaining candidates H valid a are thus valid and consistent with the data.

17Many of the assertions generated will not be useful in practice.For example, trivial assertions such as 'assert True' do not convey any useful information about instances where the function is applicable.

18Although all the candidate assertions at this point are valid, they may be sub-optimal for the purpose of constructing a policy.We seek assertions that help discriminate situations where the function is applicable.We propose a ranking mechanism to identify the most discriminative assertions.

19Candidate Ranking.We seek to identify a small set of precondition/assertion candidates from H valid useful for constructing an agent policy.We begin with the observation that if candidates h 1 , h 2 are such that h 2 is satisfied whenever h 1 is satisfied (i.e., h 1 ⇒ h 2 ), h 1 is more desirable as it is more discriminative of the contexts where action a is applicable (and hence leads to a better policy).As we discuss in the experiments, this assumption leads to high precision solutions and compromises recall.We leave alternate ranking criteria to future work.

20However, verifying the above property (h 1 ⇒ h 2 ) for given precondition candidates is generally intractable.We thus consider an approximation where we examine if the property is satisfied in scenarios that appear in the demonstration trajectories.Consider the precondition function g a ( • ; h) which assumes h to be the precondition of action a. Define C h a = {(i, j)|g a (τ i <j ; h) = 1, τ i ∈ D} to be the set of instances (i, j) where precondition h is satisfied at time-step j of demonstration trajectory τ i .We use C h1 a ⊆ C h2 a as a proxy to determine whether h 1 ⇒ h 2 .We define the optimal set of assertion statements as in Equation ( 1).When multiple equivalent candidates exist, we choose one random representative to retain in set H opt a .Note that the conjunction of assertions in H opt a is equivalent to that of H valid a .However, identifying a small set of assertion statements is beneficial both for interpretability and for providing as a prompt for models which have limited context lengths.

PRECONDITION-AWARE ACTION PREDICTION

21We pose action prediction as a code completion problem where given a partial agent trajectory, a code model is tasked with suggesting possible next actions (as functions from F A , with appropriate arguments).Given any policy which predicts the next action given past actions and observations, we consider a simple approach to augment the policy with precondition knowledge.Next action candidates are sampled from the policy until an action consistent with the preconditions is found or a maximum number of attempts is exceeded.The first attempt uses greedy sampling and subsequent attempts resort to random sampling.If random sampling does not yield an action consistent with preconditions, we default to the greedy action.We sample an action by generating tokens until a newline token is encountered.See Appendix E for the algorithm pseudocode.

EXPERIMENTS

22We attempt to answer the following key questions in our evaluation: (i) Is it possible to extract information about action preconditions from demonstrations of agent behavior?(ii) Is such inferred precondition information useful for building better agent policies?

23We use the python programming language as the code representation in our experiments due to its simplicity and popularity, as well as the recent release of code models that primarily focus on python.We use the CodeGen 2B (Nijkamp et al., 2022) and StarCoder 16B (Li et al., 2023) open-source pre-trained code models in our experiments.Specifically, we use the versions of these models which were further pre-trained on python code after initial pre-training on many programming languages.

BENCHMARKS

24Task Oriented Dialog Benchmark.The decision making component of a task-oriented dialog system is a dialog manager which takes as input a sequence of utterances represented as dialog acts and predicts the next action.In this setting, a user and a system (agent) take turns to speak and user utterances constitute the agent's observations.We use the SGD dataset (Rastogi et al., 2020) in our experiments.There are 11 user acts and 11 system acts defined in the dataset, each of which takes either no argument, a single slot argument or a single intent argument.We define analogous functions F O and F A corresponding to each of these acts.We take an object-oriented approach and group these functions respectively under a user class and a system class.We define variables v corresponding to each user action that records whether the action was performed (e.g., informed_slot[], requested_slot[] in Figure 1).We experiment with 10 domains (schemas) from the SGD dataset.10 instances are used as demonstrations and 50 instances for testing.For evaluation purposes we manually define the ground-truth preconditions for each system action based on prior knowledge about the dialog acts.Note that these are only used for evaluation and no supervision is provided to the model about ground-truth preconditions.

25Embodied Textworld.We experiment with the ALFworld embodied textworld benchmark (Shridhar et al., 2020) which involves an agent interacting with an environment to perform object interaction tasks.The observations and actions are natural language statements and the agent is expected to perform a task specified using a natural language instruction (e.g., move the keys to the table).There are 9 types of actions which include interaction and navigation actions.Each of these action types take an object argument and/or a receptacle argument and we define analogous functions F A .In addition, we define auxiliary functions F O for adding/removing an object from the agent's inventory and updating the set of objects visible to the agent.We define three variables v that summarize the agent's experience: the set of visible objects, the agent's inventory and states of objects in the environment (e.g., open/closed).The dataset has 6 task types.We use 2 instances from each task type as demonstrations and the standard test set of the benchmark for testing.The benchmark provides ground-truth preconditions for the actions in a PDDL (Planning Domain Definition Language) representation, which we convert to python assertions for evaluation.We provide the complete program specification for these benchmarks in Appendix A.

PRECONDITION INFERENCE

26Metrics.Recall that a precondition g a (τ <t ) ∈ {0, 1} informs whether an action a ∈ A is plausible given context τ <t = (o 1:t , a 1:t−1 ).Define C a = {(i, j)|g a (τ i <j ) = 1, τ i ∈ D test } to be the set of instances (i, j) where the precondition of action a is satisfied at time-step j of test trajectory τ i ∈ D test .We define precision and recall metrics for a particular action a as in Equation ( 2), where C pred a , C gt a respectively correspond to the predicted and ground-truth preconditions.The F 1 score is defined as the harmonic mean of precision and recall.These metrics are macro-averaged across all actions a ∈ A to obtain the final metrics.

27Baselines.We first consider a binary classifier which we call the Neural Precondition baseline.

28If we have labeled data of the form (τ <t , a, l), where l ∈ {0, 1} indicates whether action a is plausible given context τ <t , we can train a binary classifier h a that predicts if the precondition for a is satisfied.However, in our setting, we only have positive instances where we know that the precondition of an action was satisfied, i.e., D pos = {(τ <t , a t , 1)|τ ∈ D, t ≤ n} where D is a dataset of expert trajectories.In order to construct negative instances, we assume that the precondition for every future action a t ′ ; t ′ > t that appeared in the trajectory τ apart from the ground-truth action a t was not satisfied.Based on this assumption we construct negative instances D neg = {(τ <t , a t ′ , 0)|t ′ > t, a t ′ ̸ = a t , τ ∈ D} and train a binary classifier h on D pos ∪ D neg .In practice, we uniformly sample instances from D pos and D neg to train the classifier.We also consider a Prompting baseline where we prompt a code model with a partial program specification and predict assertion statements with greedy decoding.

29Results.In Table 2 we compare the precondition inference performance of different methods.

30The precision for our models are high since the ranking criteria we adopted encourages high precision solutions.For example, in the Restaurants domain of the SGD dataset, the ground truth precondition for the action INFORM(slot) is requested_slot[slot]. 4 However, the predicted precondition is (requested_slot[slot] and query_success==True).The models pick up the fact that query_success==True in all instances the INFORM(slot) action appeared in the demonstration trajectories.In this case precision is 1.0 since the ground truth precondition will be satisfied whenever the predicted precondition is satisfied.However, the recall is lower (0.57) since the predicted and ground-truth preconditions do not agree whenever query_success! =True.

31The Neural Precondition baseline generally underperforms other methods.The assumption that actions different from the observed action for a given time-step in a trajectory are invalid does not always hold.This is particularly an issue for the Alfworld benchmark where there can be multiple navigation actions in a trajectory while the agent is searching for an object which are equally plausible.

32Comparing the labels in the generated data (e.g., D pos , D neg ) with the corresponding ground-truth labels (computed using ground-truth preconditions), we observe that the (precision, recall) of the generated labels are respectively (1, 0.74) and (1, 0.60) for the SGD and Alfworld datasets. 5When ground-truth precondition labels are used for training the classifier, performance improves (F1 scores of 0.81 and 0.67 in SGD and Alfworld, respectively), but generalization to unseen scenarios is still limited.

33Table 1 presents qualitative prediction results for all action types in the Buses domain of the SGD benchmarks.Note that our models receive no supervision about preconditions and predict these candidates by only observing expert demonstrations.We present qualitative prediction results for the Alfworld benchmark in Appendix C. Next, we analyze how these inferred action precondition can help build better agent policies.

PRECONDITION-AWARE AGENT POLICY

34Metrics.In the SGD benchmark, we evaluate policy performance using actions in the demonstrations as reference.Since the agent needs to predict multiple actions in a turn, we compute F 1 score treating demonstration actions as ground-truth.For the embodied textworld task, a simulation environment is available, and we define the success rate (SR) metric which measures how often the agent successfully completed the given task.We also define precondition compatibility, which measures how often the predicted action is compatible with (i.e., does not violate) the ground-truth preconditions.

35Baselines.We consider the following baseline policy approaches.

36• BC: We consider a behavioral cloning baseline where a code model is fine-tuned (with LoRA) on the given expert demonstrations with a language modeling training objective.• Act (Yao et al., 2022): A few-shot prompting baseline where training demonstrations are provided as a prompt to a pre-trained model and the model predicts the next action.• ReAct (Yao et al., 2022): A variation of the few-shot prompting strategy where the agent predicts a chain-of-thought natural language rationale before predicting each action.We design 'think' prompts similar to the original work and insert them as code comments in the demonstrations.At every step the agent generates an optional code comment ('think' step) and predicts an action.

37The StarCoder 16B model is used as the backbone model for all the policy methods unless specified otherwise.We use preconditions predicted by the StarCoder 16B model in all experiments.

38Results.We present the main results in Table 3.The table shows the performance of each baseline policy (BC, Act, ReAct) as well as the performance when each of these methods are augmented with preconditions inferred by our approach.We observe that the precondition-aware action sampling strategy combined with predicted preconditions lead to consistent performance improvements over each baseline policy.In particular, we observe that the proposed precondition-based reasoning approach helps models generate actions that are more accurate and consistent with ground-truth preconditions.

39On the Alfworld benchmark, our approach improves the success rate of the React agent from 44% to 48% and its precondition compatibility from 81% to 96%.This shows the synergistic potential of our approach and recent advances in prompting for policy learning problems such as generating natural language rationales before predicting actions.

40These results shows that explicitly reasoning about preconditions helps build better policies.Although few-shot prompting enables language/code models to perform tasks with limited supervision, they are generally limited by the number of demonstrations that can fit in the context window.Condensing the information in multiple trajectories in a small set of rules (e.g., preconditions) can help overcome this limitation, and this idea may further be applicable to other tasks in general.

ABLATIONS AND ANALYSIS

41We perform a series of ablations to understand the impact of different components in our pipeline.

42How to incorporate precondition information?In Figure 2 we analyze the impact of (i) including precondition information in the prompt and (ii) the precondition-aware action sampling strategy.Overall, while the inclusion of precondition information in the model prompt generally helps, our proposed

Model size

43Prec. prompt Prec.sample 1-shot 10-shot precondition-aware action prediction strategy yields more consistent and significant improvements (e.g., 0.64 to 0.68 with predicted preconditions and 0.73 with ground-truth preconditions in the 1-shot setting).In addition, it helps predict actions that are more consistent with their preconditions (e.g., precondition compatibility improves to > 0.9 for both 2B and 16B models).

44Amount of Supervision.Figure 3 shows model performance for varying amounts of supervision.Due to it's maximum context size of 2048 tokens, the CodeGen 2B model can only accommodate upto 4 demonstrations.Knowledge about preconditions is particularly helpful when the number of demonstrations is small.Even as we increase the number of demonstrations, models continue to benefit from explicitly reasoning about preconditions.Furthermore, performance with ground-truth preconditions shows that improvements in quality of preconditions lead to improvements in policy performance.

45Model scale.We observe that the small model benefits more from precondition knowledge compared to the big model regardless of the amount of supervision.Enhancing the reasoning capabilities of small models is important as big models demand higher costs and computation.Leveraging precondition information and execution-based verification is a promising strategy to enhance small models.

RELATED WORK

46Programs as Policies.There exist prior work that advocate viewing robot policies as code/programs (Liang et al., 2022;Singh et al., 2022).This is in contrast to most prior work that reason about plans almost entirely in natural language.Similar to natural language based prompting, LLMs are prompted with examples of programs corresponding to example tasks and are required to generate programs for a query task.The programs can be rich and composed of functions supported by the target robot API or third party library functions.Code comments help break down high-level task into subtasks and assertions are used to take environment feedback into account and provide an error recovery mechanism.These prior work assume that precondition information is specified as part of the prompt.In contrast, our work attempts to discover such information from action trajectories.

47Reasoning with Verification.Prior work has attempted to augment capabilities of language models with programs and execution.Liu et al. (2022) combine LLMs with a physics simulator to answer physics questions.Given a query, a text-to-code model trained with supervised learning generates a program in order to perform a simulation.The simulator performs the simulation and produces an output, which is fed as additional information to the LLM to generate a response.Gao et al. (2022) interleave natural language chain-of-thought statements with program statements to perform calculations for arithmetic reasoning problems.Analogous to these work, we find that the ability to verify via execution improves the performance of LMs, particularly small models.

48Reasoning via Prompting.Chain-of-thought prompting (Wei et al., 2022) has emerged as a powerful technique for getting language models to perform step-by-step reasoning.These ideas have also been applied to planning problems (Huang et al., 2022b;Yao et al., 2022) where agents are taught how to come up with rationales for predicted actions with few-shot demonstrations.Compared to chain-of-thought rationales, which are dynamically generated on the fly and are problem-specific, we seek to identify a set of rules that capture action preconditions.This provides more controllability over the action generation process and the rules can also be vetted/edited to achieve desired behavior.

49Structured Prediction with Programs.Programs have been used as a representation for structured prediction tasks in NLP (Wang et al., 2022;Madaan et al., 2022;Zhang et al., 2023).Code models have been used by these work for modeling procedural real-world activities, also called the script generation problem.They find that code models have strong capability to reason about event sequences with minimal supervision compared to language models.Subtask Graph Framework.Subtask Graphs are a modeling framework proposed by Sohn et al. (2018;2020) to learn subtask preconditions from demonstrations.Preconditions are modeled as boolean expressions involving a pre-defined set of boolean subtask variables which represent whether a subtask has been completed or not.An Inductive Logic Programming (ILP) algorithm is used to identify the optimal boolean expression.This framework was further extended to model real-world procedural activities in Jang et al. (2023); Logeswaran et al. (2023).In contrast to the use of boolean expressions as the class of functions to model preconditions, the program representation we consider has the flexibility to represent a broader set of scenarios.We draw inspiration from these works to formulate and evaluate the precondition inference component in our approach.

CONCLUSION

50This work presented a novel approach to reason about action preconditions using programs for learning agent policies in a sequential decision making setting.We proposed to use programs as a representation of the agent's observations and actions and showed that precondition inference and action prediction can be formulated as code-completion problems.By leveraging the strong priors of pre-trained code models, we proposed a novel approach to infer action preconditions from demonstration trajectories without any additional supervision.With the predicted preconditions, our precondition-aware action prediction strategy enables the agent to predict actions that are consistent with the preconditions and lead to better task completion compared to baselines.Our study opens an exciting new direction to reason about action preconditions by leveraging code models.

A PROGRAM SPECIFICATION

51We present the program specification for the Restaurants domain in the SGD benchmark in Figure 4 and the Alfworld benchmark in Figure 5.

Figure 2 :

52Figure 2: Ablation to study the effect of (a) providing preconditions as part of the prompt (column 2) and (b) precondition-aware action prediction strategy (column 3) in the SGD benchmark.The 2B model can only accommodate upto 4 demonstrations and hence is not evaluated in the 10-shot setting.The performance metrics are F 1 score and precondition compatibility (Cmp.).

Figure 3 :

53Figure 3: Ablation showing policy performance (F1 score) in the SGD benchmark when varying (a) the number of demonstrations (from 1 to 10), (b) model scale (Code-Gen 2B vs StarCoder 16B) and (c) precondition information available to the policy model (None/Predicted/Ground-truth).

54= defaultdict(lambda: False) self.informed_slot= defaultdict(lambda: False) self.requested_slot= defaultdict(lambda: False) self.no_more= False self.selected= False self.affirmed= False self.affirm_intent= False self.negate_intent= False self.request_alternatives= False def INFORM_INTENT(self, intent): self.informed_intent[intent]= True def NEGATE_INTENT(self): self.negate_intent= True def AFFIRM_INTENT(self): self.affirm_intent= True def REQUEST_ALTS(self): self.request_alternatives= True def INFORM(self, slot): self.informed_slot[slot]= True def REQUEST(self, slot): self.requested_slot[slot]= True def GOODBYE(self): self.no_more= True def THANK_YOU(self): self.no_more= True def SELECT(self): self.selected= True def AFFIRM(self): self.affirmed= True def NEGATE(self): self.affirmed= False class SYSTEM: def __init__(self, user): self.user= user self.query_success= None def INFORM(self, slot): assert self.user.requested_slot[slot]

Figure 7 :

55Figure 7: Example trajectory from the pick and place task of the Alfworld benchmark in its original text representation.

Figure 9 :

56Figure 9: Ground-truth and predicted preconditions for actions in the Alfworld benchmark.

57Given these inferred preconditions G = {g a |a ∈ A}, our second goal is to estimate a policy π(a t |τ <t , D, G) that predicts the next action given τ <t .The overall goal is to construct a policy π that generalizes to a set of test trajectories D test : maximize Eτ∈D test [log π(a t |τ <t , D, G)].

Table 1 :

58Ground-truth and predicted preconditions for actions in the Buses domain of the SGD benchmark, along with Precision, Recall scores for predictions.

59def REQ_MORE(self): assert self.user.selectedor self.user.no_moredef REQ_MORE(self): assert self.user.selected 1 1 def FindBus(self): assert self.user.informed_slot['to_location']assert self.user.informed_slot['from_location']assert self.user.informed_slot['leaving_date']def FindBus(self): assert not self.user.no_moreassert self.user.informed_intent['FindBus']assert self.user.informed_slot['leaving_date']assert self.user.informed_slot['from_location']0.99 0.89 def BuyBusTicket(self): assert self.user.affirmeddef BuyBusTicket(self): assert self.user.affirmed 1 1

Table 2 :

60Precondition Inference performance on the SGD and Alfworld benchmarks.Metrics are precision, recall and F 1 score (All metrics higher ↑ the better).The simple prompting baseline and our approach are both evaluated with the CodeGen 2B model and StarCoder 16B model.

61Figure 4: Program specification of the Restaurants domain in the SGD benchmark.Note that the assertion statements are assumed to be unknown and only used for evaluation.are in the middle of a room .Looking quickly around you , you see a countertop 1 , a drawer 1 , a drawer 2 , a drawer 3 , a drawer 4 , a drawer 5 , a drawer 6 , a garbagecan 1 , a handtowelholder 1 , a handtowelholder 2 , a sinkbasin 1 , a toilet 1 , a toiletpaperhanger 1 , a towelholder 1 , and a towelholder 2. Your task is to : put some spraybottle on garbagecan > 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 .> close drawer 4 You close the drawer 4. > 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 .> close drawer 2 You close the drawer 2. > 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 nothing .> close drawer 3 You close the drawer 3. > go to countertop 1 On the countertop 1 , you see a sink 1 , a soapbottle 1 , and a toiletpaper 1. > go to toilet 1 On the toilet 1 , you see a cloth 1 , and a spraybottle 1. > take spraybottle 1 from toilet 1 You pick up the spraybottle 1 from the toilet 1. > go to garbagecan 1 On the garbagecan 1 , you see nothing .> put spraybottle 1 in / on garbagecan 1 You put the spraybottle 1 in / on the garbagecan 1.

62def ReserveRestaurant(self): assert self.user.selectedor self.user.affirmeddef OFFER(self, slot): assert self.query_success or self.user.affirmeddef INFORM_COUNT(self): assert self.query_successdef OFFER_INTENT(self, intent): assert self.user.selecteddef CONFIRM(self, slot): assert self.user.informed_slot['time']assert self.user.informed_slot['city']assert self.user.selectedor \ self.user.informed_slot['restaurant_name']def NOTIFY_SUCCESS(self): assert self.query_successdef NOTIFY_FAILURE(self): assert not self.query_successdef REQ_MORE(self): assert self.user.selectedor self.user.no_moreor \ not self.query_success

참고문헌

참고문헌 정보가 없습니다.