Recent advances in reasoning Large Language Models (LLMs) have primarily relied on upfront thinking, where reasoning occurs before final answer. However, this approach suffers from critical limitations in code generation, where upfront thinking is often insufficient as problems' full complexity only reveals itself during code implementation. Moreover, it cannot adaptively allocate reasoning effort throughout the code generation process where difficulty varies significantly. In this paper, we propose Think-Anywhere, a novel reasoning mechanism that enables LLMs to invoke thinking on-demand at any token position during code generation. We achieve Think-Anywhere by first teaching LLMs to imitate the reasoning patterns through cold-start training, then leveraging outcome-based RL rewards to drive the model's autonomous exploration of when and where to invoke reasoning. Extensive experiments on four mainstream code generation benchmarks (i.e., LeetCode, LiveCodeBench, HumanEval, and MBPP) show that Think-Anywhere achieves state-of-the-art performance over both existing reasoning methods and recent post-training approaches, while demonstrating consistent generalization across diverse LLMs. Our analysis further reveals that Think-Anywhere enables the model to adaptively invoke reasoning at high-entropy positions, providing enhanced interpretability.
Figures & tables
Figure 1: Illustration of Think-Anywhere . Reasoning can be invoked at any token position during code generation. The ellipsis (“…”) within <think> or <thinkanywhere> represents truncated thinking content for brevity.
You are a coding assistant that generates both code and inline self-guidance signals. First output <think>... </think> with brief reasoning, then output the final code.
MUST FOLLOW Rules for <thinkanywhere>...</thinkanywhere> tags:
1. You MUST use <thinkanywhere>...</thinkanywhere> tags for self-guidance or intermediate reasoning.
2. <thinkanywhere>...</thinkanywhere> MUST be embedded within an existing program statement token sequence.
3. The code must remain valid and executable after removing all <thinkanywhere>...</thinkanywhere> segments.
Table 1: Template for Think-Anywhere . Prompt will be replaced with the specific coding requirement.
Method
LeetCode
LiveCodeBench
HumanEval
MBPP
Average
Base Model
50.6
34.3
88.4
70.7
61.0
Post-Training Methods
OlympicCoder
45.3
30.9
75.6
67.2
54.8
OCR-Qwen-7B
53.3
33.0
86.8
58.9
58.0
CodePRM
52.8
34.8
88.4
73.9
62.5
CodeBoost
53.3
34.6
87.2
65.7
60.2
Table 2: Performance of Think-Anywhere compared to post-training methods and reasoning-enhanced methods. Best results are in bold . Think-Anywhere* denotes the special token variant with semantic-aware initialization (see Section 3.2).
Method
AIME 2024
AIME 2025
HMMT 2025
pass@1
pass@5
pass@10
pass@1
pass@5
pass@10
pass@1
pass@5
pass@10
Base Model
5.3
14.6
20.0
4.0
13.4
16.7
0.0
0.0
0.0
GRPO
6.0
16.8
23.3
4.7
17.2
26.7
0.3
1.7
3.3
Think-Anywhere
17.3
32.9
40.2
17.7
28.0
33.2
14.4
18.5
19.6
Table 3: Cross-domain generalization of Think-Anywhere to mathematical reasoning benchmarks. The model is trained solely on code generation tasks.
Model
Average
Δ vs. Base
Qwen2.5-Coder-7B-Instruct
Base Model
61.0
–
+ GRPO
68.4
+7.4
+ Think-Anywhere
70.3
+9.3
Qwen2.5-Coder-1.5B-Instruct
Base Model
40.6
–
Table 4: Generalizability of Think-Anywhere across different model families and scales.
Method
Pass@1
Δ
Think-Anywhere
69.4
–
Only Cold Start
47.9
-21.5
Only RLVR
63.4
-6.0
Line-level Thinking
67.2
-2.2
No Upfront Thinking
66.6
-2.8
Padding Thinking
67.6
-1.8
Table 5: The results of ablation study.
Figure 2: Results of Thinking Position Analysis.
Figure 3: Token cost of different methods.
Figure 4: Pass@k comparison between GRPO and Think-Anywhere across four benchmarks.
Appendix figures & tables2 assets
Supplementary material from the paper’s appendix.
Appendix
Method
HumanEval
MBPP
LeetCode
GRPO
309.4
325.2
440.7
CoT
348.8
372.0
577.0
Think-Anywhere
215.6 + 22.5
183.2 + 23.2
283.0 + 22.9
Appendix
Table 6: Breakdown of reasoning token costs. For Think-Anywhere , the two numbers denote upfront thinking length + <thinkanywhere> block length.
Dataset
Model
Avg.Freq
Avg.Len
HumanEval
Base Model
0
0
Think-Anywhere (Prompting)
0.24
113.5
Think-Anywhere (SFT)
6.69
31.9
Think-Anywhere (Ours)
6.15
22.5
MBPP
Base Model
0
0
Think-Anywhere (Prompting)
0.53
66.4
Appendix
Table 7: Average frequency and length of <thinkanywhere> blocks across training stages.
Code reasoning refers to the task of predicting the output of a program given its source code and specific inputs. It can measure the reasoning capability of large language models (LLMs) and also benefit downstream tasks such as code generation and mathematical reasoning. Existing work has verified the effectiveness of reinforcement learning on the task. However, these methods design rewards solely based on final outputs or coarse-grained signals, and neglect the inherent consistency of the stepwise reasoning process in the task. Therefore, these methods often result in sparse reward or reward hacking, which limits the full play of enhanced learning capabilities. To alleviate these issues, we propose CodeThinker, a consistency-driven reinforcement learning framework for code reasoning. Specifically, CodeThinker has three key components: (1) a stepwise reasoning-aware model training module, which utilizes a consistency tracing paradigm as a template to synthesize training data that captures the stepwise reasoning process; (2) a dynamic beam sampling strategy, which aims to improve the quality of sampled outputs under a fixed sampling budget; and (3) a consistency reward mechanism that can effectively alleviate reward hacking. Experiments on three popular benchmarks show that CodeThinker achieves state-of-the-art performance across multiple LLMs. For instance, it outperforms the strongest baseline by 4.3% in accuracy when deployed on Qwen2.5-Coder-7B-Instruct. We also validate the effectiveness of CodeThinker on downstream tasks. Results show that, without additional training, CodeThinker obtains average accuracy gains of 5.33 and 3.11 percentage points on mathematical reasoning and code reasoning tasks covering 17 programming languages, respectively.
Zhanyue Qin, Jia Feng, Yibo Lyu +4
Harbin Institute of Technology · The Chinese University of Hong Kong
LLMs are widely used for code generation and mathematical reasoning tasks where they are required to generate structured output. They either need to reason about code, generate code for a given specification, or reason using programs of thought. The typical approach to code generation is to prompt the model and generate samples until an appropriate program is obtained. Within this process, sampling n programs from the language model requires n GPU compute-intensive generations which becomes prohibitively expensive for larger values of n. In this work, we address this limitation by exposing the LLM's distribution within the generated programs themselves. We propose a novel test-time framework we dub probabilistic programs of thought to obtain more samples from the model with fewer LLM generations. Given a program generated by a model and the associated next-token probabilities, we build a probabilistic program that compactly represents exponentially many deterministic programs. Since performing probabilistic reasoning in this probabilistic program is much cheaper, our approach allows sampling new programs without any additional GPU compute and little CPU overhead. We instantiate our approach on benchmarks for code generation, code understanding and mathematical reasoning and report improvements in performance with fewer generations from the LLM.
Poorva Garg, Renato Lui Geh, Daniel Israel +3
University of California Los Angeles · Allen Institute for AI
Reinforcement learning with verifiable rewards (RLVR) has driven substantial progress in large language model reasoning, but relies on ground-truth supervision that is costly or infeasible, especially in coding tasks. Recent work addresses this by deriving rewards from a model's own signals, such as majority voting or confidence-based scores, achieving notable success on mathematical reasoning benchmarks. However, code generation poses distinct challenges: programs are structurally complex, semantically equivalent solutions may differ syntactically, and verification typically requires execution. Whether these intrinsic reward methods transfer effectively to code remains unexplored. In this work, we present a systematic empirical study of intrinsic reward methods for code generation. We conduct extensive experiments on LiveCodeBench, systematically evaluating representative certainty-based Reinforcement Learning from Internal Feedback (RLIF) approaches under different training scenarios and hyperparameter settings. Our experiments reveal that certainty-based methods yield early gains but inevitably collapse: models progressively shorten outputs and lose reasoning capability, with collapse speed sensitive to sample size and temperature. When used to initialize RLVR training, RLIF pre-training offers no significant improvement over training from scratch. We also provide actionable recommendations for using intrinsic rewards for training code reasoning models. Our study shows both the promise and limitations of intrinsic reward methods for code, informing future work on code models and agents.
Xiaolong Jin, Xuandong Zhao, Wenbo Guo +2
Purdue University · UC Berkeley · UC Santa Barbara