Code Prompting Enhances LLM Reasoning
Code Prompting Enhances LLM Reasoning
in Text+Code LLMs
Haritz Puerto1 , Martin Tutek2 * , Somak Aditya3 , Xiaodan Zhu1,4 , Iryna Gurevych1
1
Ubiquitous Knowledge Processing Lab (UKP Lab),
TU Darmstadt and Hessian Center for AI ([Link])
2
Technion – IIT, 3 IIT Kharagpur, 4 Queen’s University
[Link]
Abstract
Reasoning is a fundamental component of lan-
guage understanding. Recent prompting tech-
arXiv:2401.10065v3 [[Link]] 28 Sep 2024
investigate how to best use an external symbolic in- To the best of our knowledge, only the work of
terpreter to aid an LLM in solving reasoning tasks, Hussain et al. (2023) investigates the conditional
i.e., they run code and therefore have a program reasoning abilities of LLMs. However, they only
state with variables and its values. However, we analyze the abilities of text LLMs after training
do not employ any external symbolic reasoner, and them on ConditionalQA (Sun et al., 2022).
we do not run code. We investigate the reasoning
abilities of LLMs under different input representa- 3 Code Prompting
tions (i.e., text and code). Our code prompts are We posit that each LLM encodes a set of capabili-
not executed; they are simply read by the LLM and ties, such as mathematical, logical, or conditional
used to generate a natural language answer. reasoning. However, not all of them are used for
every input instance, even if they would be use-
Some works suggest that code LLMs may pos-
ful. We hypothesize that the input representation
sess superior reasoning abilities than text LLMs.
plays a pivotal role in eliciting such capabilities.
Madaan et al. (2022) investigate whether code
Prior works show that LLMs trained on a combi-
LLMs are superior at structured reasoning than
nation of text and code exhibit superior reasoning
text LLMs. They observe that code LLMs can gen-
abilities (Kojima et al., 2022; OpenAI, 2023; Jiang
erate graphs that link commonsense concepts better
et al., 2024, 2023). Therefore, we conjecture that
than text LLMs. Liu et al. (2023b) investigate code
a code representation of a natural language (NL)
prompts in abductive and counterfactual reasoning
problem may trigger some of these reasoning abil-
tasks and report superior results than text prompts
ities encoded in text+code LLMs. More formally,
on code-davinci (Ouyang et al., 2022), a code
we wonder whether exists some space S 2 with an
LLM. However, code prompts exhibit mixed re-
associated function f that transforms a natural lan-
sults on text-davinci-002 (Ouyang et al., 2022),
guage problem p ∈ N into that space, such that,
a text LLM. We attribute this to the fact that while
when prompting an LLM with the representation
this model includes some code in its pretraining cor-
of p in such space yields better results according to
pus, it is not explicitly trained for code generation
some evaluation function σ.
and, in general, performs poorly on code generation
tasks (Chen et al., 2021a). Therefore, the effect of ∃S, f : N → S, σ(LLM (f (p)) ≥ σ(LLM (p))
the input representation on the reasoning abilities of
text+code LLMs remains unclear. Furthermore, the We fix S to the programming language space and
reasons behind the superior performance of code define code prompts f (p) as prompts that model
prompts in code LLMs also remain unclear. In our a natural language problem with code. We also
work, we aim to answer whether code prompts can 2
Since the input of LLMs must be strings, S must be a set
elicit conditional reasoning abilities in text+code of all possible sentences constructed using some alphabet and
LLMs and the reasons behind this. grammar.
define f as a prompt that transforms the NL text we focus on the main partition, which includes
into code. f (p) code follows the original NL text three subsets BGQA-1, BGQA-2, and BGQA-3, where
as much as possible. We use a simple structured the number indicates the reasoning hops needed to
code that contains the logical structure needed to answer. Lastly, while ShARC encompasses dialogue
solve the problem, along with the original NL text generation, we aim to evaluate specific capabilities
as code comments. In particular, it creates vari- unrelated to conversational flow. Therefore, we
ables for key entities in the question and documents isolated the QA pairs from the provided dialogues,
and if blocks for each conditional statement in the resulting in a dataset where the model has to answer
documents. Figure 2 exemplifies this transforma- yes, no, or not enough information.3 We include
tion and Appendix D provides more details of the more details about the datasets in Appendix B, a
code features. Lastly, we define code prompting formal definition of the prompts in Appendix C,
as LLM (f (p)), a chain of prompts that i) trans- and examples in Appendix Q.
form the NL text into code, and ii) use this code to
prompt the LLM to generate the answer in natural 4.3 Models
language. Figure 1 illustrates this pipeline.
It is important to note that the code is not ex- We perform our study using text+code LLMs be-
ecuted per se and therefore, there is no program cause of their ability to process text and code inter-
state. We simply prompt the LLM with the code changeably. We do not employ code-only LLMs
and ask the LLM to generate a natural language because their intended use does not include solving
answer based on the content of such code. This natural language tasks (Roziere et al., 2023), as
setup allows us to investigate the effect of the input required in our case. Similarly, we do not employ
representation on text+code LLMs. text-only LLMs because they cannot generate code.
Furthermore, using text+code LLMs also allow us
4 Experimental Setup to eliminate the confouding effect of fine-tuning
between model variants specialized for only text or
4.1 Task Setup code. We corroborate the shortcomings of text-only
We evaluate the conditional reasoning abilities of and code-only LLMs with additional experiments
the LLMs under different prompting methods us- on CodeLLaMA (Roziere et al., 2023) and LLaMA
ing the traditional question-answering task. The 2 (Touvron et al., 2023b) in Appendix G and H.
input is a question and a document, and the model We employ OpenAI’s gpt-35-turbo, Mixtral
needs to produce the answer, which can be a span 8x7B (Jiang et al., 2024), and Mistral 7B (Jiang
of the input document, yes or no. Given that chain- et al., 2023). The use of these models allows us to
of-thought prompting (CoT, Wei et al. 2022) has investigate whether our hypothesis holds across all
been shown to improve the reasoning abilities of available sizes of text+code LLMs. We execute our
LLMs, we instruct the model to generate a CoT prompts with in-context learning and provide one
before the final answer in all prompting methods. demonstration per class. More details on the LLM
Since we force code prompting to generate a natu- setup are provided in Appendix E.
ral language answer, we also force it to generate a
natural language CoT. 4.4 Evaluation
Table 1: Comparison (F1 score) of text prompt and code prompts. All results use one demonstration per class.
∆CP = Code Prompt - Text Prompt, i.e., the average performance gain from code prompts across all datasets.
LLMs. Now, we aim to investigate which aspects on CondQA and BGQA-1. This can be interpreted as
of code are pivotal. In particular, we evaluate the the model being able to identify the irrelevance of
impact of retaining the natural language text of the the code to the text. Hence, the model disregards
original instance within the code comments and the the code to solely focus on the code comments (i.e.,
importance of the code semantics. To analyze the the natural language text). This could be possible
former, we have (1) removed the code comments thanks to the provided demonstrations, which show
that include the original natural language text from answers that only refer to the natural language text.
the input and evaluated the performance of the new
prompts. To analyze the latter, we (2) perturbed These results confirm that code alone does not
the code to anonymize the variables and functions, trigger reasoning abilities, and instead, the combi-
as well as (3) added random code whose seman- nation of code that represents the original natural
tics are completely irrelevant to the original natural language instance and the NL text is able to unlock
language text. In the latter two cases, the code com- the potential of LLMs. We observe similar patterns
ments remain unmodified (examples illustrating on Mistral and Mixtral in Appendix J.
them are provided in Table 17 from Appendix P).
Since CondQA includes span answers and removing
5.4 Code Prompts are More Sample-Efficient
the NL text would make it impossible for the model
at Eliciting Reasoning Abilities
to generate the span, we only report performance
on the yes-no answers partition (CondQA-YN).
Given our observations that code prompts trig-
Table 3 shows that removing the NL text in the
ger conditional reasoning abilities better than text
code comments yields a performance drop of 14.02
prompts, it is natural to ask the follow-up question:
points on CondQA and a performance drop between
are code prompts also more sample-efficient than
16.7 and 5.2 on BGQA. This significant and consis-
text prompts? To answer this, we evaluate how the
tent decrease in all datasets confirms that retaining
overall performance of GPT 3.5 changes with re-
NL text in comments is vital for the LLM to under-
spect to the number of demonstrations for the two
stand the input problem.
prompting methods.
Effect of Code Perturbations. Code perturba- Figure 3 shows that when we only provide
tions (anonymous code and random code) confirm one demonstration per class (i.e., answer type in
the importance of code semantics in eliciting rea- our datasets), the performance gap is the largest
soning abilities. When we use anonymized code, across all datasets. As expected, this gap de-
we observe a performance reduction of almost 2 creases when we provide more demonstrations.
points on CondQA and a decrease between 6.6 and 4 Moreover, we also observe that code prompts with
in BGQA. The decrease is even larger when the code only one demonstration per class even outperform
is randomized, with drops of more than 3 points text prompts with three demonstrations per class,
on CondQA and between 7.4 and 9.8 on BGQA. This which further shows the sample efficiency of code
more pronounced drop is expected since the seman- prompts. These results indicate that code prompts
tics and logic of the code mismatch the NL text, trigger conditional reasoning more efficiently than
whereas anonymous code maintains the same logic text prompts on GPT 3.5, and this is one of the
on both NL and code. Furthermore, we also ob- reasons for its superior performance. We conduct
serve that the performance drop of random code additional analysis on Mistral and Mixtral in Ap-
prompts is similar to that of text prompts (Table 1) pendix K.
Correct Ans. Incorrect Ans.
Dataset Text Code Text Code
CondQA 71.08 4.39 60.79 11.39
BGQA-1 39.33 8.84 51.65 22.12
BGQA-2 44.79 15.04 52.54 24.75
BGQA-3 54.01 14.21 52.13 16.98
Lastly, we conduct our experiments on data in Elana Cabria and Bernardo Magnini. 2014. Decom-
English. Analyzing whether our findings hold true posing semantic inference. Linguistic Issues in Lan-
guage Technology, 9.
in other languages would be interesting. However,
the lack of conditional reasoning datasets in other Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan,
languages would make this study difficult. Henrique Ponde de Oliveira Pinto, Jared Kaplan,
Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Urvashi Khandelwal, He He, Peng Qi, and Dan Jurafsky.
Brockman, et al. 2021a. Evaluating large lan- 2018. Sharp nearby, fuzzy far away: How neural lan-
guage models trained on code. arXiv preprint guage models use context. In Proceedings of the 56th
arXiv:2107.03374. Annual Meeting of the Association for Computational
Linguistics (Volume 1: Long Papers), pages 284–294,
Wenhu Chen, Xueguang Ma, Xinyi Wang, and Melbourne, Australia. Association for Computational
William W. Cohen. 2023. Program of thoughts Linguistics.
prompting: Disentangling computation from reason-
ing for numerical reasoning tasks. Transactions on Takeshi Kojima, Shixiang (Shane) Gu, Machel Reid, Yu-
Machine Learning Research. taka Matsuo, and Yusuke Iwasawa. 2022. Large lan-
guage models are zero-shot reasoners. In Advances in
Zhiyu Chen, Wenhu Chen, Charese Smiley, Sameena
Neural Information Processing Systems, volume 35,
Shah, Iana Borova, Dylan Langdon, Reema Moussa,
pages 22199–22213. Curran Associates, Inc.
Matt Beane, Ting-Hao Huang, Bryan Routledge, and
William Yang Wang. 2021b. FinQA: A dataset of nu- Tamera Lanham, Anna Chen, Ansh Radhakrishnan,
merical reasoning over financial data. In Proceedings Benoit Steiner, Carson Denison, Danny Hernan-
of the 2021 Conference on Empirical Methods in Nat- dez, Dustin Li, Esin Durmus, Evan Hubinger, Jack-
ural Language Processing, pages 3697–3711, Online son Kernion, et al. 2023. Measuring faithful-
and Punta Cana, Dominican Republic. Association ness in chain-of-thought reasoning. arXiv preprint
for Computational Linguistics. arXiv:2307.13702.
Karl Cobbe, Vineet Kosaraju, Mohammad Bavarian,
Mark Chen, Heewoo Jun, Lukasz Kaiser, Matthias Chengshu Li, Jacky Liang, Andy Zeng, Xinyun Chen,
Plappert, Jerry Tworek, Jacob Hilton, Reiichiro Karol Hausman, Dorsa Sadigh, Sergey Levine, Li Fei-
Nakano, et al. 2021. Training verifiers to solve math Fei, Fei Xia, and Brian Ichter. 2023a. Chain of code:
word problems. arXiv preprint arXiv:2110.14168. Reasoning with a language model-augmented code
emulator. arXiv preprint arXiv:2312.04474.
Luyu Gao, Aman Madaan, Shuyan Zhou, Uri Alon,
Pengfei Liu, Yiming Yang, Jamie Callan, and Raymond Li, Loubna Ben allal, Yangtian Zi, Niklas
Graham Neubig. 2023. Pal: program-aided lan- Muennighoff, Denis Kocetkov, Chenghao Mou, Marc
guage models. In Proceedings of the 40th Interna- Marone, Christopher Akiki, Jia LI, Jenny Chim,
tional Conference on Machine Learning, ICML’23. Qian Liu, Evgenii Zheltonozhskii, Terry Yue Zhuo,
[Link]. Thomas Wang, Olivier Dehaene, Joel Lamy-Poirier,
Joao Monteiro, Nicolas Gontier, Ming-Ho Yee, Lo-
Suriya Gunasekar, Yi Zhang, Jyoti Aneja, Caio gesh Kumar Umapathi, Jian Zhu, Ben Lipkin, Muh-
César Teodoro Mendes, Allie Del Giorno, Sivakanth tasham Oblokulov, Zhiruo Wang, Rudra Murthy, Ja-
Gopi, Mojan Javaheripi, Piero Kauffmann, Gustavo son T Stillerman, Siva Sankalp Patel, Dmitry Ab-
de Rosa, Olli Saarikivi, et al. 2023. Textbooks are all ulkhanov, Marco Zocca, Manan Dey, Zhihan Zhang,
you need. arXiv preprint arXiv:2306.11644. Urvashi Bhattacharyya, Wenhao Yu, Sasha Luccioni,
Paulo Villegas, Fedor Zhdanov, Tony Lee, Nadav
Syed-Amad Hussain, Parag Pravin Dakle, SaiKrishna Timor, Jennifer Ding, Claire S Schlesinger, Hailey
Rallabandi, and Preethi Raghavan. 2023. Towards Schoelkopf, Jan Ebert, Tri Dao, Mayank Mishra,
leveraging llms for conditional qa. arXiv preprint Alex Gu, Carolyn Jane Anderson, Brendan Dolan-
arXiv:2312.01143. Gavitt, Danish Contractor, Siva Reddy, Daniel Fried,
Albert Q. Jiang, Alexandre Sablayrolles, Arthur Men- Dzmitry Bahdanau, Yacine Jernite, Carlos Muñoz
sch, Chris Bamford, Devendra Singh Chaplot, Diego Ferrandis, Sean Hughes, Thomas Wolf, Arjun Guha,
de las Casas, Florian Bressand, Gianna Lengyel, Guil- Leandro Von Werra, and Harm de Vries. 2023b. Star-
laume Lample, Lucile Saulnier, Lélio Renard Lavaud, coder: may the source be with you! Transactions on
Marie-Anne Lachaux, Pierre Stock, Teven Le Scao, Machine Learning Research. Reproducibility Certifi-
Thibaut Lavril, Thomas Wang, Timothée Lacroix, cation.
and William El Sayed. 2023. Mistral 7b. arXiv
preprint arXiv:2310.06825. Tianle Li, Ge Zhang, Quy Duc Do, Xiang Yue,
and Wenhu Chen. 2024. Long-context llms strug-
Albert Q Jiang, Alexandre Sablayrolles, Antoine gle with long in-context learning. arXiv preprint
Roux, Arthur Mensch, Blanche Savary, Chris Bam- arXiv:2404.02060.
ford, Devendra Singh Chaplot, Diego de las Casas,
Emma Bou Hanna, Florian Bressand, et al. 2024. Hanmeng Liu, Jian Liu, Leyang Cui, Zhiyang Teng, Nan
Mixtral of experts. arXiv preprint arXiv:2401.04088. Duan, Ming Zhou, and Yue Zhang. 2023a. Logiqa
2.0—an improved dataset for logical reasoning in
Mehran Kazemi, Quan Yuan, Deepti Bhatia, Najoung natural language understanding. IEEE/ACM Trans-
Kim, Xin Xu, Vaiva Imbrasaite, and Deepak Ra- actions on Audio, Speech, and Language Processing,
machandran. 2023. BoardgameQA: A dataset for 31:2947–2962.
natural language reasoning with contradictory infor-
mation. In Thirty-seventh Conference on Neural In- Jiacheng Liu, Skyler Hallinan, Ximing Lu, Pengfei He,
formation Processing Systems Datasets and Bench- Sean Welleck, Hannaneh Hajishirzi, and Yejin Choi.
marks Track, pages 1–23. 2022a. Rainier: Reinforced knowledge introspector
for commonsense question answering. In Proceed- Liangming Pan, Xiaobao Wu, Xinyuan Lu, Anh Tuan
ings of the 2022 Conference on Empirical Methods Luu, William Yang Wang, Min-Yen Kan, and Preslav
in Natural Language Processing, pages 8938–8958, Nakov. 2023. Fact-checking complex claims with
Abu Dhabi, United Arab Emirates. Association for program-guided reasoning. In Proceedings of the
Computational Linguistics. 61st Annual Meeting of the Association for Compu-
tational Linguistics (Volume 1: Long Papers), pages
Jiacheng Liu, Alisa Liu, Ximing Lu, Sean Welleck, Pe- 6981–7004, Toronto, Canada. Association for Com-
ter West, Ronan Le Bras, Yejin Choi, and Hannaneh putational Linguistics.
Hajishirzi. 2022b. Generated knowledge prompting
for commonsense reasoning. In Proceedings of the Arkil Patel, Satwik Bhattamishra, and Navin Goyal.
60th Annual Meeting of the Association for Compu- 2021. Are NLP models really able to solve simple
tational Linguistics (Volume 1: Long Papers), pages math word problems? In Proceedings of the 2021
3154–3169, Dublin, Ireland. Association for Compu- Conference of the North American Chapter of the
tational Linguistics. Association for Computational Linguistics: Human
Jian Liu, Leyang Cui, Hanmeng Liu, Dandan Huang, Language Technologies, pages 2080–2094, Online.
Yile Wang, and Yue Zhang. 2020. Logiqa: A chal- Association for Computational Linguistics.
lenge dataset for machine reading comprehension
with logical reasoning. In Proceedings of the Twenty- Baptiste Roziere, Jonas Gehring, Fabian Gloeckle, Sten
Ninth International Joint Conference on Artificial Sootla, Itai Gat, Xiaoqing Ellen Tan, Yossi Adi,
Intelligence, IJCAI-20, pages 3622–3628. Interna- Jingyu Liu, Tal Remez, Jérémy Rapin, et al. 2023.
tional Joint Conferences on Artificial Intelligence Code llama: Open foundation models for code. arXiv
Organization. Main track. preprint arXiv:2308.12950.
Xiao Liu, Da Yin, Chen Zhang, Yansong Feng, and Marzieh Saeidi, Max Bartolo, Patrick Lewis, Sameer
Dongyan Zhao. 2023b. The magic of IF: Investi- Singh, Tim Rocktäschel, Mike Sheldon, Guillaume
gating causal reasoning abilities in large language Bouchard, and Sebastian Riedel. 2018. Interpretation
models of code. In Findings of the Association for of natural language rules in conversational machine
Computational Linguistics: ACL 2023, pages 9009– reading. In Proceedings of the 2018 Conference on
9022, Toronto, Canada. Association for Computa- Empirical Methods in Natural Language Processing,
tional Linguistics. pages 2087–2097, Brussels, Belgium. Association
for Computational Linguistics.
Qing Lyu, Shreya Havaldar, Adam Stein, Li Zhang,
Delip Rao, Eric Wong, Marianna Apidianaki, and Koustuv Sinha, Shagun Sodhani, Jin Dong, Joelle
Chris Callison-Burch. 2023. Faithful chain-of- Pineau, and William L. Hamilton. 2019. CLUTRR:
thought reasoning. arXiv preprint arXiv:2301.13379. A diagnostic benchmark for inductive reasoning from
Aman Madaan, Shuyan Zhou, Uri Alon, Yiming Yang, text. In Proceedings of the 2019 Conference on
and Graham Neubig. 2022. Language models of code Empirical Methods in Natural Language Processing
are few-shot commonsense learners. In Proceedings and the 9th International Joint Conference on Natu-
of the 2022 Conference on Empirical Methods in Nat- ral Language Processing (EMNLP-IJCNLP), pages
ural Language Processing, pages 1384–1403, Abu 4506–4515, Hong Kong, China. Association for Com-
Dhabi, United Arab Emirates. Association for Com- putational Linguistics.
putational Linguistics.
Haitian Sun, William Cohen, and Ruslan Salakhutdinov.
Sewon Min, Kalpesh Krishna, Xinxi Lyu, Mike Lewis, 2022. ConditionalQA: A complex reading compre-
Wen-tau Yih, Pang Koh, Mohit Iyyer, Luke Zettle- hension dataset with conditional answers. In Pro-
moyer, and Hannaneh Hajishirzi. 2023. FActScore: ceedings of the 60th Annual Meeting of the Associa-
Fine-grained atomic evaluation of factual precision tion for Computational Linguistics (Volume 1: Long
in long form text generation. In Proceedings of the Papers), pages 3627–3637, Dublin, Ireland. Associa-
2023 Conference on Empirical Methods in Natural tion for Computational Linguistics.
Language Processing, pages 12076–12100, Singa-
pore. Association for Computational Linguistics. Simeng Sun, Kalpesh Krishna, Andrew Mattarella-
Micke, and Mohit Iyyer. 2021. Do long-range lan-
John Eric Nolt, Dennis Rohatyn, and Achille Varzi. guage models actually use long-range context? In
1988. Schaum’s outline of logic. McGraw Hill Pro- Proceedings of the 2021 Conference on Empirical
fessional. Methods in Natural Language Processing, pages 807–
OpenAI. 2023. Gpt-4 technical report. arXiv preprint 822, Online and Punta Cana, Dominican Republic.
arXiv:2303.08774. Association for Computational Linguistics.
Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Mirac Suzgun, Nathan Scales, Nathanael Schärli, Se-
Carroll Wainwright, Pamela Mishkin, Chong Zhang, bastian Gehrmann, Yi Tay, Hyung Won Chung,
Sandhini Agarwal, Katarina Slama, Alex Ray, et al. Aakanksha Chowdhery, Quoc V. Le, Ed H. Chi,
2022. Training language models to follow instruc- Denny Zhou, and Jason Wei. 2022. Challenging
tions with human feedback. Advances in Neural big-bench tasks and whether chain-of-thought can
Information Processing Systems, 35:27730–27744. solve them. arXiv preprint arXiv:2210.09261.
Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier (Appendix D, E, and F). Subsequently, we perform
Martinet, Marie-Anne Lachaux, Timothée Lacroix, experiments on code-only and text-only LLMs to
Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
show that code prompting should only be used on
Azhar, et al. 2023a. Llama: Open and effi-
cient foundation language models. arXiv preprint text+code LLMs (Appendix G and H). Then, we
arXiv:2302.13971. show experiments on small LLMs (Appendix I),
ablations on local LLMs (Appendix J, K, L, and M.
Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
bert, Amjad Almahairi, Yasmine Babaei, Nikolay We conclude with the confusion matrices for the
Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti main experiments Appendix N, prompt examples
Bhosale, Dan Bikel, Lukas Blecher, Cristian Canton O, P, and Q.
Ferrer, Moya Chen, Guillem Cucurull, David Esiobu,
Jude Fernandes, Jeremy Fu, Wenyin Fu, Brian Fuller, B Datasets
Cynthia Gao, Vedanuj Goswami, Naman Goyal, An-
thony Hartshorn, Saghar Hosseini, Rui Hou, Hakan ConditionalQA is a QA dataset where the an-
Inan, Marcin Kardas, Viktor Kerkez, Madian Khabsa,
swers are applicable under specific scenarios (i.e.,
Isabel Kloumann, Artem Korenev, Punit Singh Koura,
Marie-Anne Lachaux, Thibaut Lavril, Jenya Lee, Di- conditional answers). Therefore, along with each
ana Liskovich, Yinghai Lu, Yuning Mao, Xavier Mar- question, the dataset provides a scenario that de-
tinet, Todor Mihaylov, Pushkar Mishra, Igor Moly- scribes the background of the person posing such
bog, Yixin Nie, Andrew Poulton, Jeremy Reizen- a question. Questions require multi-hop, composi-
stein, Rashi Rungta, Kalyan Saladi, Alan Schelten,
Ruan Silva, Eric Michael Smith, Ranjan Subrama- tional, and conditional logic over documents about
nian, Xiaoqing Ellen Tan, Binh Tang, Ross Tay- public policies (e.g., the eligibility for a subsidy).
lor, Adina Williams, Jian Xiang Kuan, Puxin Xu, Answers can be a span of the document, yes, and
Zheng Yan, Iliyan Zarov, Yuchen Zhang, Angela Fan, no. We use an oracle retriever to select the relevant
Melanie Kambadur, Sharan Narang, Aurelien Ro-
driguez, Robert Stojnic, Sergey Edunov, and Thomas passages to the question so that we can isolate the
Scialom. 2023b. Llama 2: Open foundation and fine- analysis of conditional reasoning abilities in LLMs
tuned chat models. arXiv preprint arXiv:2307.09288. from the retrieval component. The expected out-
put is a chain of thought (CoT; Wei et al. 2022)
Wenya Wang, Vivek Srikumar, Hannaneh Hajishirzi,
and Noah A. Smith. 2023. Elaboration-generating followed by the final answer. To create the CoT,
commonsense question answering at scale. In Pro- we use the annotated evidence sentences. We use
ceedings of the 61st Annual Meeting of the Associa- an oracle retriever to retrieve the relevant passages
tion for Computational Linguistics (Volume 1: Long to the question. This retriever is based on the sen-
Papers), pages 1619–1635, Toronto, Canada. Associ-
ation for Computational Linguistics. tences annotated as evidence for the answer (i.e.,
rationales). We concatenate all sections that in-
Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten clude one rationale and use the resulting passage
Bosma, brian ichter, Fei Xia, Ed Chi, Quoc V Le,
and Denny Zhou. 2022. Chain-of-thought prompt-
as input document.
ing elicits reasoning in large language models. In
Advances in Neural Information Processing Systems,
BoardgameQA is a dataset that evaluates the abil-
volume 35, pages 24824–24837. Curran Associates, ity to reason with contradictory information guided
Inc. by preferences. For example, given a question
about traveling abroad, information found online
Xi Ye, Qiaochu Chen, Isil Dillig, and Greg Durrett. 2023.
Satlm: Satisfiability-aided language models using about regulations can be contradictory because
declarative prompting. In Proceedings of NeurIPS, rules may change over time. Answering questions
pages 1–33. in this dataset requires complex multi-hop reason-
ing with conditional, deductive, and compositional
Susan Zhang, Stephen Roller, Naman Goyal, Mikel
Artetxe, Moya Chen, Shuohui Chen, Christopher De- abilities. The domain of the problems is board
wan, Mona Diab, Xian Li, Xi Victoria Lin, et al. 2022. games, which allows us to analyze the conditional
Opt: Open pre-trained transformer language models. reasoning abilities in a completely different domain
arXiv preprint arXiv:2205.01068. from CondQA. BGQA is divided into multiple parti-
tions focusing on different characteristics, such as
A List of Appendices
the depth of the reasoning tree, the need for exter-
We start the appendices with details on the datasets nal information, etc. We focus on the main par-
and prompts (Appendix B and C). Then, we pro- tition and its subpartitions (i.e., BGQA-1, BGQA-2,
vide additional details on the features of the gener- BGQA-3), where the number refers to the number
ated code, the setup of the LLMs, and their costs of reasoning hops required to answer the ques-
tion. This dataset also includes annotated chain-of- As far as we know, these datasets do not contain
thoughts (CoT); therefore, we use their annotated any personal information or offensive content. Al-
input (“example”) as the input prompt and their though we did not explicitly analyze this, the au-
annotated CoT (“proof ”) as the expected output. thors of these datasets did not mention including
such content, and we did not observe such content
ShARC is a conversational QA dataset with nat- during our use of the datasets. All these datasets
ural language rules where most questions are un- are in English.
derspecified. Therefore, the model may need to
ask a follow-up question to know more about the Dataset Training Dev Test License
background of the interlocutor to return an answer.
CondQA 2338 285 804 BSD 2
The documents are of legal domain retrieved from BGQA-1 1000 500 1000 CC BY
the web pages of different governments and state BGQA-2 1000 500 1000 CC BY
agencies. Since this is a conversational QA and we BGQA-3 1000 500 1000 CC BY
are not interested in evaluating the conversational ShARC 21890 2270 8276 CC-BY-SA-3.0
abilities of LLMs, we transform the task into regu-
lar QA, instead of conversational QA. To do this, Table 5: Sizes of the datasets.
the model must answer yes, no, or not enough infor-
mation for each question. In the original task, not C Prompt Formulation
enough information, would lead to the generation
of a follow-up question. CONDQA. Firstly, we define the different compo-
nents of a data point: scenario (S), question (Q),
Complexity of the datasets. We analyze the document (D), rationales (R), and answer (A).
complexity of the datasets by counting the percent- Then, the text prompt tp is defined as follows:
age of reasoning operations (i.e., if statements) in
the code prompt generated by GPT 3.5. This analy- tp = "Question:" + S + Q + "Document:" + D
sis shows that the most difficult dataset is BGQA-3 +"Let’s think step by step"
with 21.58% of reasoning operations, followed (1)
by BGQA-2 (16.99%), CondQA (14.66%), BGQA-1
(10.55%), and lastly, ShARC (8.32%). where + represents the string concatenation op-
We also analyze the length of the documents of erator. Then, the output format, to is:
each dataset and find that BGQA-3 has the longest to = R + "Answer:" + A (2)
documents with an average of 39 lines of code, fol-
lowed by CondQA (38), BGQA-2 (25), ShARC (22), For code prompts, we first define a function
and lastly BGQA-1 (15). It is worth noting that C : NL → C that maps a natural language text into
the documents from CondQA are the short docu- code as shown in Figure 2. Then, we define code
ments extracted with the oracle retriever described prompt cp as follows:
above, instead of the full documents, which are
cp = "#Question:" + C(S) + C(Q)+
much longer (up to 9k tokens).
These two analyses suggest that BGQA-3 and "#Document:" + C(D) (3)
BGQA-2 are the most reasoning-intensive datasets +"#Let’s think step by step"
due to the high proportion of reasoning operations.
Similarly, we define the output format, co, as:
In contrast, CondQA is the dataset where the lin-
guistic dimension plays the biggest role because
co = R + "#Answer:" + A (4)
their documents are among the longest ones while
it contains much less proportion of reasoning opera- BGQA. Firstly, we define the components of a data
tions than the other datasets with similar document point in this dataset: facts (F ), rules (R), and ques-
lengths. tions (Q). Therefore, our text prompt is defined as
follows6 :
Dataset sizes, licenses, and safety. The sizes
and licenses of all the datasets used in this work tp = F + R + Q (5)
are provided in Table 5. Our use of these datasets 6
BGQA provides a field example with all the variables of
is consistent with their intended use, i.e., academic the dataset concatenated with descriptions. We use this field
research to evaluate question-answering systems. as text prompt.
This dataset also provides the CoT that leads to the E LLM Setup
answer. Therefore, we use that CoT as the expected
output. The exact models we used are the following: gpt-
For code prompts, we follow the same approach 3.5-16k-0613 for CondQA and BGQA. For ShARC,
as with the previous dataset. We define code since the documents are shorter, we used GPT-3.5-
prompts, cp, as follows: 0301 due to the lower costs. In both cases, we
run the models through the Azure AI service. We
also use Mixtral 8x7B with 4-bit quantization for
tp = C(F ) + C(R) + C(Q) (6)
all the datasets using one Nvidia A100 in our own
with the output format (co) being: server. Lastly, we use Mistral 7B v0.1 for CondQA
and BGQA. However, this model yields very poor
co = C(cot) (7) results on ShARC, so we use the instruct-v0.2 vari-
ant to be able to make a fair comparison between
ShARC. Firstly, we define the components of a text and code prompts on this dataset using Mistral
data point in this dataset: question (Q), scenario 7B. We use fp16 quantization for the Mistral 7B
(S), document (D), and conversation history (H). experiments and run them on our own server with
Then, the text prompt tp is defined as follows: one Nvidia A100.
All of our prompting methods are implemented
tp = "Question:" + S + Q + "Document:" + D using the Langchain library.7 We set the decoding
temperature to zero and use greedy sampling to
+"Conversation history:" + H
make the outputs deterministic. For each experi-
+"What is the answer to the question:" + Q ment, we use a random sample from the training
(8) set as demonstrations. The LLM generating the
code for code prompts is the same one as the one
the output format is the answer label directly, which running the code to generate the final answer. We
can be yes, no, or not enough information. evaluate each model and prompt in the dev set of
Similarly to the other datasets, we defined code each dataset with two random seeds. Since the
prompts cp as follows: demonstrations are selected randomly, the seed de-
termines them. The seed that yields the best per-
tp = "#Question:" + C(S) + C(Q)+ formance on the dev set is then used for the final
+"#Document:" + C(D) evaluation on the test set.
+"#Conversation history:" + C(H) The number of demonstrations used to translate
+"#What is the answer to the question:" + C(Q) the documents into code is specified in Table 6.
(9) Note that this number differs from the number of
demonstrations used to generate the answer, which
Lastly, the output format is the answer label di- is always three.
rectly, which in this case are True, False, or None. We use chain of thoughts (CoT) based on the pro-
vided annotations of the datasets. We do not use
D Coding Features advanced CoT methods for text prompts because
our aim is to quantify how much improvement we
To generate code as close as possible to the NL text, can get by transforming the natural language CoT
we use a programming language based on a simpli- into code syntax, and therefore, the natural lan-
fication of Python. We only use boolean variables guage text and code must be as close as possible.
or variables that contain lists of strings. Variables The use of advanced CoT methods would also be
follow the snake case naming convention. We also reflected in the code syntax, making the experi-
employ if statements to model conditional reason- mental setup more complicated without providing
ing, but we do not use loops, functions, or classes. better insights.
We create a code comment with the original NL The best random seeds found (and consequently
text for each input sentence, and right after the code used for the test set evaluation) are described in
comment, we generate the code that represents the Table 7 and Table 8.
semantics of that sentence. However, we do not
7
enforce the generated code to be a runnable script. [Link]
Dataset GPT Mixtral Mistral Dataset GPT Mixtral Mistral
CondQA 4 4 4 CondQA 0 1 0
ShARC 5 4 4 ShARC 0 0 0
BGQA-1 4 3 3 BGQA-1 1 0 1
BGQA-2 4 3 4 BGQA-2 0 1 1
BGQA-3 4 3 4 BGQA-3 0 1 0
Table 6: Number of demonstrations for code transla- Table 8: Best seeds for text prompts
tions. Note this is not the number of demonstrations to
generate the answer.
Furthermore, CondQA requires generating a natu-
Dataset GPT Mixtral Mistral ral language answer that is a span of the document.
The use of code to generate a natural language span
CondQA 0 0 0
of a document is also far from the fine-tuning tasks
ShARC 0 1 1
of this model. This would explain why the code
BGQA-1 1 0 1
representation is worse than the text representation.
BGQA-2 1 0 0
It is particularly interesting to see the results on
BGQA-3 0 1 0
ShARC. After manually inspecting the outputs, we
observe that Code Llama can successfully generate
Table 7: Best seeds for code prompts
the code corresponding to the natural language in-
put. However, when it is prompted with such code
F Costs and the question variable, the model does not gen-
erate the value of the variable (i.e., true, false,
Running a data instance from ConditionalQA with
or none). Instead, it generates \n. The reasons
gpt-3.5-16k-0613 using code prompts costs $0.04
behind this remain unclear and would require fur-
while with text prompts $0.01. On BoardgameQA-
ther investigation, which is out of the scope of this
depth 3 (i.e., the partition with the most expensive
paper.
prompts), with the same model, the costs per ques-
However, we observe a different behavior on
tion are $0.02 and $0.03 for text and code prompts,
BGQA. In this dataset, code prompts outperform
respectively. Lastly, on ShaRC, using gpt-3.5-0301,
text prompts. We attribute this to the high align-
the costs per question are $0.0006 and $0.005 for
ment with the first-order logic of this dataset, which
text and code prompts, respectively.
makes it closer to the intended use of the model.
G Code-only LLMs Nevertheless, it is important to note that these re-
sults are not intended to be comprehensive enough
Although our work focuses on text+code LLMs to conclude that code LLMs or Code Llama can
because they are the only type of LLMs whose or cannot solve natural language tasks, which is
intended use includes natural language and cod- out of the scope of this work. Instead, they sim-
ing tasks, we conduct a small experiment on Code ply seem to confirm the warnings of the authors
Llama (Roziere et al., 2023), a code-only LLM. It of Code Llama, i.e., this model is not intended for
is important to note that their authors advise against natural language tasks.
using this model on natural language tasks because
their intended use is in code generation tasks only.
Table 9 shows the results of Code Llama on our Model Text Prompt Code Prompt
datasets. Firstly, we can observe that code prompts CondQA 31.58 26.34
perform significantly worse than text prompts on ShARC 58.33 18.62
CondQA and ShARC despite being a code LLM. We BGQA1 44.38 44.78
can attribute this to the nature of these datasets and BGQA2 44.59 49.41
the intended use of the model. These datasets re- BGQA3 40.88 46.44
quire a strong comprehension of natural language
documents and dialogues and answering natural Table 9: Text and code prompts results in Code Llama
language questions about them. This is far from the 7B - Instruct with one demonstration.
intended use of the model (i.e., generating code).
H Text-only LLMs Prompt BGQA-1
As briefly mentioned in Section 4.3, text-only Text 33.20 ± 1.42
LLMs are not expected to perform well with code Code 48.32 ± 1.65
prompting and should not be used for this as they
are not explicitly trained on code. For example, Table 11: Comparison of text prompt and code prompts
on the MBPP coding benchmark (Austin et al., with Phi-2 on the validation set. Metric: F1 score. One
2021), LLaMA 2 scores 26.1% , while Mistral 7B demonstration per class is provided.
(a text+code LLM) achieves 47.5% and code-llama
2 7B, achieves 52.5% (Jiang et al., 2023). Table 10 Prompt BG1 BG2 BG3
further proves our claim. LLaMA 2 7B-Chat (Tou-
Atomic St. -4.29 -8.09 -2.19
vron et al., 2023b) with code prompting never out-
NLCode -2.7 -4.36 -5.97
performs text prompting due to its lack of code
Anonym. Code -0.45 -7.17 -4.52
understanding.
Rnd Code -4.27 -11.16 -13.93
- Comments -0.79 -9.88 -29.21
Prompt CQA ShARC BG1 BG2
Text 29.79 46.16 51.85 39.23 Table 12: Performance drop w.r.t. Code Prompting on
Code 21.32 24.74 45.16 37.66 Mistral.
N Confusion Matrices
Figure 4 shows the confusion matrices of all our
models using text and code prompts for all the
datasets except CondQA. We cannot include this
one because it is a span-extraction task, not a clas-
sification task.
O Atomic Statements
Original sentence: <p>Applying for the legal right
to deal with someone’s property, money and posses-
sions (their estate) when they die is called applying
for probate.</p> Atomic statements: Applying for
the legal right is a process. The process is called
’applying for probate’. The legal right is to deal
with someone’s property, money, and possessions.
The someone is a person who has died. The prop-
erty, money, and possessions are collectively called
the ’estate’.
Table 16: Example of a back-translation NL → C in ConditionalQA and BGQA-3. Text in bold represents the main
modification.
Type Text
Original # <p>To be eligible you must have left your country and be unable to go back because
Code you fear persecution.</p>
if left_country_and_fear_persecution:
eligible_for_asylum = True
Anonymous # <p>To be eligible you must have left your country and be unable to go back because
Code you fear persecution.</p>
if var_1
var_2 = True
Random # <p>To be eligible you must have left your country and be unable to go back because
Code you fear persecution.</p>
if value_of_property_gone_down_by_more_than_50:
eligible_to_claim = True
getting_housing_benefit = True
Table 18: Variable Tracking Example. Underlined text represents the variable to probe. Partial CoT is not the
complete answer. The generation was stopped, and only the first step was used in this probe.
System: You are a helpful assistant that answers questions given a document. Answers must be a short
span of the document. You have to extract the span from the document. Do not write anything else. I will
give you some examples first.
ICL Demonstrations...
Human: Question: My brother and his wife are in prison for carrying out a large fraud scheme. Their
7 and 8 year old children have been living with me for the last 4 years. I want to become their Special
Guardian to look after them permanently. How long will it be before I hear back from the court?
Document: <h1>What is a special guardian</h1>
<p>You can apply to be a child’s special guardian when they cannot live with their birth parents and
adoption is not right for them.</p>
<p>You’ll be responsible for looking after the child until they’re 18 (unless the court takes your responsi-
bility away earlier).</p>
<p>You’ll make all day to day decisions about the child, for example schooling and medical treatment.
You do not have to discuss these decisions with the birth parents.</p>
<p>You’ll need to get the consent of everyone who has parental responsibility for the child before you
make some important decisions, for example:</p>
<li>changing the child’s surname</li>
<li>putting the child up for adoption</li>
<li>taking the child abroad for more than 3 months</li>
<li>the child having surgery for reasons other than improving health, such as circumcision, sterilisation or
cosmetic surgery</li>
<p>If you cannot get consent, you can ask the court to decide. Use the form ‘Make an application in
existing court proceedings related to children’ (form C2).</p>
<h1>After you apply</h1>
<p>Within 10 days of receiving your application the court will send you a case number and a date for a
meeting to set out:</p>
<li>a timetable for your case</li>
<li>how it will be dealt with</li>
<p>This meeting is called a ‘first directions hearing’.</p>
<p>You must go to all hearings you’re told to unless the court excuses you. If you’re not able to go,
contact the court office.</p> Answers must be a short span of the document. You have to extract the span
from the document. Do not write anything else. Let’s think step by step:
System: You are a large language model of code that can interpret code. You are given a pseudo-code
that resembles to first-order logic that models some scenario. You will be given a question and you
have to answer it step by step. You can use a rule if and only if you know the antecedent of the rule.
ICL Demonstrations
Human: # A few players are playing a boardgame
# The rules of the game are as follows
# Rule1: If the amberjack has difficulty to find food, then the amberjack removes from the board one
of the pieces of the carp.
rule1() = difficulty_finding_food(amberjack) => remove_piece(amberjack, carp)
# The current state of the game is as follows
# The amberjack struggles to find food.
difficulty_finding_food(amberjack) = True
# Based on the game state and the rules and preferences, does the amberjack remove from the board
one of the pieces of the carp?
question = remove_piece(amberjack, carp)
AI:
System: You are a question answering system that answers questions given a document and a conversation
history. The conversation history gives information about the background of the person posing the question.
You must answer ‘yes‘, ‘no‘, or ‘not enough information‘ to the question and nothing else.
ICL Demonstrations...
Human: Question: The item is not equipment for audio books or newspapers, and I’m not selling lifeboats
or anything related to that. It’s for medicine and medicinal ingredients. Can I apply zero VAT to this item?
Document:
## Items that qualify for the zero rate
You may be able to apply zero VAT when you sell the following to an eligible charity:
* equipment for making ‘talking’ books and newspapers
* lifeboats and associated equipment, including fuel
* medicine or ingredients for medicine
* resuscitation training models
Conversation history:
Q: Is it equipment for making ‘talking’ books and newspapers?
A: No
Q: Are you selling lifeboats and associated equipment, including fuel?
A: No
Q: Are you selling medicine or ingredients for medicine?
A: Yes
What is the answer to the question: Can I apply zero VAT to this item? You must answer ‘yes‘, ‘no‘, or
‘not enough information‘ to the question and nothing else.
AI:
Code prompts enhance models' ability to manage long-range context by frequently referring back to previous functions and variables, which can be far apart compared to typical language tasks. This capability improves the model's performance in multi-hop reasoning by enabling it to trace entities over long contexts, leading to better handling of complex natural language tasks that require understanding of distant information .
The evaluation used a traditional question-answering task where LLMs were given a question and a document to generate answers. The model was instructed to produce chain-of-thought (CoT) processes before final answers. This helped examine the effects of different prompting methods, specifically focusing on how code prompts impact LLMs' ability to handle conditional reasoning .
Using text+code LLMs eliminates the confounding effect of fine-tuning by allowing for interchangeable processing of text and code. This integration ensures that the model can handle both natural language and code-based tasks without bias towards either domain, maintaining consistency across tasks that traditionally demand specialization .
The experiment involved transforming natural language text into code and using it to prompt LLMs to generate answers in natural language. The primary goal was to evaluate the conditional reasoning abilities of LLMs under different prompting methods and to explore how input representation affects LLM performance .
The datasets used, such as ConditionalQA and BoardgameQA, are designed to require advanced conditional and compositional reasoning capabilities. These datasets, with structured reasoning tasks and multiple reasoning hops, allow for evaluating LLMs' ability to process and respond to complex scenarios, challenging the models' multi-hop reasoning skills needed for code and natural language task integration .
In chain-of-thought prompting, transforming natural language text into code plays a role in structuring logical reasoning. It helps the model follow logical sequences and conditions explicitly, facilitating a sequence of logical deductions that mirror a structured thought process. Code acts as a scaffold, improving the model's capability to simulate reasoning steps that lead to natural language solutions .
The findings highlight the potential of code prompts in enhancing reasoning abilities and efficiency in NLP models, influencing future research to explore more integrated approaches for contextual reasoning and sophisticated dataset design to challenge LLMs. This may lead to a broader acceptance of code as a tool for advancing language understanding and reasoning capabilities, guiding future NLP model development .
The performance of GPT 3.5 using code prompts was significantly better with a smaller number of demonstrations. With only one demonstration per class, code prompts outperform text prompts that have three demonstrations per class. This indicates that code prompts are more efficient in eliciting reasoning capabilities, requiring fewer examples to achieve superior performance .
The improved ability to identify and track the states of key variables or concepts contributes to code prompting's superior performance. Code often requires reference to previously defined functions and variables, mirroring multi-hop reasoning where the model traces entities across distantly separated lines. This training on code is beneficial for multi-hop reasoning, a necessary skill in solving complex datasets .
Code prompts are more sample-efficient than text prompts in eliciting reasoning abilities from GPT 3.5. When providing only one demonstration per class, code prompts outperform text prompts, even when text prompts have three demonstrations per class. This indicates that code prompts trigger conditional reasoning more efficiently, contributing to superior performance .