Chain-of-Thought Prompting
local graph
Chapter 19 — Chain-of-Thought Prompting
Section titled “Chapter 19 — Chain-of-Thought Prompting”Chain-of-thought (CoT) prompting originated from a research paper titled Chain-of-Thought Prompting Elicits Reasoning in Large Language Models, published by Google researchers Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Brian Ichter, Fei Xia, Ed Chi, Quoc Le, and Denny Zhou in 2022.
The key innovation of CoT prompting was encouraging language models to break down complex reasoning problems into intermediate steps before arriving at a final answer. This was done by including demonstrations where the model is shown examples of step-by-step reasoning.
The researchers demonstrated that by prompting LLMs with a few examples of reasoning chains (such as “Let’s think step by step”), the models could significantly improve their performance on complex tasks requiring multi-step reasoning, such as arithmetic, commonsense, and symbolic reasoning problems.
Before CoT, most prompting techniques focused on getting direct answers. CoT showed that explicitly encouraging models to demonstrate their reasoning process led to more accurate results, especially for problems requiring several logical steps. CoT is beneficial in promoting transparency and ensuring accuracy by guiding the model through logical steps, whereas direct answering, while quicker, can miss intermediate steps that could clarify or validate the reasoning behind the answer.
This research was particularly significant because it showed that reasoning abilities could emerge primarily through scale and prompting rather than requiring architectural changes to the models.
In this chapter, you’ll learn to leverage CoT prompting to improve your LLM’s performance on complex reasoning tasks.
In this chapter, we’ll be covering the following topics:
- Designing effective CoT prompts
- Using CoT prompting for problem solving
- Combining CoT prompting with other techniques
- Evaluating CoT prompting outputs
- Limitations of CoT prompting
- Future directions
Designing effective CoT prompts
Section titled “Designing effective CoT prompts”The process of creating effective CoT prompts helps in fostering clarity, logical progression, and structured reasoning, which in turn ensures more accurate and coherent outputs. By providing a well-defined problem statement, breaking the task into smaller steps, using explicit markers to guide the reasoning, and including a sample CoT response, the model is better equipped to follow a systematic approach that aligns with human problem-solving methods, leading to clear and rational conclusions:
- Provide a clear problem statement: A precise problem statement directs the reasoning toward a specific goal, eliminating ambiguity and ensuring that the model understands exactly what is being asked. This helps prevent misinterpretations and guides the entire reasoning process in the right direction.
- Break down the problem into logical steps: Dividing a complex task into smaller, manageable steps helps in organizing the reasoning and makes the overall problem easier to tackle. This breakdown aids in focusing on one aspect at a time, promoting clarity and reducing the risk of missing important details.
- Use explicit reasoning markers: Markers such as “First,” “Next,” and “Finally” act as signposts for the logical flow of the reasoning process. They help structure the thought process in a clear sequence, ensuring that each part of the problem is addressed in the right order, which increases the overall coherence of the response.
- Include a sample CoT response in the prompt: Providing an example helps establish a standard for the reasoning format and sets clear expectations for the process. It also serves as a reference point, guiding the model in how to structure its response and making it easier to generate consistent and logically sound outputs.
Here’s an example of implementing a CoT prompt:
def cot_prompt(question): return f"""Solve the following problem step by step:Problem: {question}Let's approach this step by step:1) First, we need to...2) Next, we should...3) Then, we can...4) Finally, we...Therefore, the answer is...Now, solve this new problem using the same step-by-step approach:Problem: If a train travels 120 km in 2 hours, what is its average speed in km/h?Let's solve this step by step:"""# Example usageproblem = "If a train travels 120 km in 2 hours, what is its average speed in km/h?"prompt = cot_prompt(problem)print(prompt)This function generates a CoT prompt for a given problem (If a train travels 120 km in 2 hours, what is its average speed in km/h?), providing a structure for step-by-step reasoning. Here are the sample steps using CoT:
Solve the following problem step by step:Problem: If a train travels 120 km in 2 hours, what is its average speed in km/h?Let's approach this step by step:1) First, we need to recall the formula for average speed, which is: Average Speed = Total Distance / Total Time.2) Next, we should identify the total distance traveled, which is 120 km.3) Then, we can identify the total time taken, which is 2 hours.4) Now, we will apply the formula: Average Speed = 120 km / 2 hours.5) Finally, we calculate the result: Average Speed = 60 km/h.Therefore, the answer is 60 km/h.
CoT prompting can be applied to various problem-solving scenarios. Let’s see one such scenario next.
Using CoT prompting for problem solving
Section titled “Using CoT prompting for problem solving”Let’s implement a function that uses CoT for mathematical word problems:
from transformers import AutoModelForCausalLM, AutoTokenizerdef solve_math_problem(model, tokenizer, problem): prompt = cot_prompt(problem) inputs = tokenizer(prompt, return_tensors="pt") outputs = model.generate( inputs, max_length=500, num_return_sequences=1 ) solution = tokenizer.decode( outputs[0], skip_special_tokens=True ) return solution# Example usagemodel_name = "gpt2-large" # Replace with your preferred modelmodel = AutoModelForCausalLM.from_pretrained(model_name)tokenizer = AutoTokenizer.from_pretrained(model_name)problem = "If a recipe calls for 2 cups of flour for 8 servings, how many cups of flour are needed for 12 servings?"solution = solve_math_problem(model, tokenizer, problem)print(solution)This function applies CoT prompting to solve a mathematical word problem (for example, If a recipe calls for 2 cups of flour for 8 servings, how many cups of flour are needed for 12 servings?), guiding the LLM through a step-by-step reasoning process.
In addition to using CoT prompting for problem solving, we can also combine it with other techniques to improve LLM performance.
Combining CoT prompting with other techniques
Section titled “Combining CoT prompting with other techniques”CoT can be combined with other prompting techniques to further enhance LLM performance. Let’s implement a function that combines CoT with few-shot learning (FSL):
def few_shot_cot_prompt(question, examples): prompt = "Solve the following problems step by step:\n\n" for example in examples: prompt += f"Problem: {example['question']}\n\n" prompt += f"Solution: {example['solution']}\n\n" prompt += f"Problem: {question}\n\nSolution:" return promptdef solve_with_few_shot_cot(model, tokenizer, problem, examples): prompt = few_shot_cot_prompt(problem, examples) inputs = tokenizer(prompt, return_tensors="pt") outputs = model.generate(inputs, max_length=500, num_return_sequences=1) solution = tokenizer.decode(outputs[0], skip_special_tokens=True) return solution# Example usageexamples = [ { "question": "If a car travels 60 miles in 2 hours, what is its average speed?", "solution": "1) First, we identify the given information:\n - Distance traveled = 60 miles\n - Time taken = 2 hours\n\n2) We know that average speed is calculated by dividing distance by time:\n Average Speed = Distance / Time\n\n3) Let's plug in the values:\n Average Speed = 60 miles / 2 hours\n\n4) Perform the division:\n Average Speed = 30 miles per hour\n\nTherefore, the car's average speed is 30 miles per hour." }]problem = "If a train travels 180 km in 3 hours, what is its average speed in km/h?"solution = solve_with_few_shot_cot(model, tokenizer, problem, examples)print(solution)This function combines FSL with CoT prompting, providing examples of step-by-step solutions to guide the LLM in solving a new problem (see the code example for If a train travels 180 km in 3 hours, what is its average speed in km/h?). Combining methods such as CoT + FSL has been shown to improve performance in recent benchmarks (https://aclanthology.org/2023.emnlp-main.782.pdf).
Next, let’s see how we can evaluate the quality of CoT prompts.
Evaluating CoT prompting outputs
Section titled “Evaluating CoT prompting outputs”Evaluating the outputs of CoT prompts involves assessing both the final answer and the reasoning process. Let’s implement a simple evaluation function:
def evaluate_cot_output(output, correct_answer): # Extract the final answer from the CoT output final_answer = extract_final_answer(output) # Check if the final answer is correct answer_correct = final_answer == correct_answer # Evaluate the reasoning steps reasoning_score = evaluate_reasoning_steps(output) return { "answer_correct": answer_correct, "reasoning_score": reasoning_score }def extract_final_answer(output): # Implement logic to extract the final answer from the CoT output # This could involve parsing the last line or looking for specific phrases passdef evaluate_reasoning_steps(output): # Implement logic to evaluate the quality of the reasoning steps # This could involve checking for logical consistency, completeness, etc. pass# Example usageproblem = "If a train travels 180 km in 3 hours, what is its average speed in km/h?"correct_answer = 60cot_output = solve_math_problem(model, tokenizer, problem)evaluation = evaluate_cot_output(cot_output, correct_answer)print(evaluation)This evaluation function assesses both the correctness of the final answer and the quality of the reasoning steps in the CoT output.
Limitations of CoT prompting
Section titled “Limitations of CoT prompting”While CoT prompting is powerful, it has some limitations:
- High token usage and computation time
- Potential for error propagation in multi-step reasoning
- Dependence on the quality of the initial prompt
- May not be suitable for all types of problems
To address some of these limitations, consider implementing a dynamic CoT approach:
def dynamic_cot(model, tokenizer, problem, max_steps=5): prompt = f"Problem: {problem}\n\nLet's solve this step by step:" for step in range(1, max_steps + 1): prompt += f"\n\nStep {step}:" inputs = tokenizer(prompt, return_tensors="pt") outputs = model.generate( inputs, max_length=len(prompt) + 100, num_return_sequences=1 ) new_step = tokenizer.decode( outputs[0][len(inputs['input_ids'][0]):], skip_special_tokens=True ) prompt += new_step if "Therefore, the final answer is" in new_step: break return prompt# Example usageproblem = "If a recipe calls for 2 cups of flour for 8 servings, how many cups of flour are needed for 12 servings?"solution = dynamic_cot(model, tokenizer, problem)print(solution)The dynamic_cot function implements a dynamic CoT approach to break down and solve a problem step by step using a language model. It starts by creating an initial prompt that introduces the problem and instructs the model to solve it incrementally. The function then enters a loop, iterating up to max_steps times (default is 5), where in each iteration, it feeds the model a growing prompt that includes all the steps generated so far. The model processes this prompt, generates the next step in the reasoning process, and appends it to the prompt. The new step is decoded from tokenized outputs and added to the prompt string. The function checks for the phrase Therefore, the final answer is in the generated step, signaling that the model has reached a conclusion and should stop. If this phrase is found, the loop breaks early; otherwise, it continues until the maximum steps are reached. Finally, the function returns the complete prompt, which includes all the reasoning steps leading to the solution. However, in real-world use, token limitations of the model may impact long multi-step prompts. As the prompt grows with each new step, it might exceed the model’s maximum token limit, which could result in truncated inputs, loss of earlier context, or failure to generate accurate steps, especially in complex or lengthy problems. This is a significant consideration when dealing with problems requiring many steps or substantial context.
Future directions
Section titled “Future directions”As CoT prompting continues to evolve, several promising directions emerge:
- Adaptive CoT: Dynamically adjusting the reasoning process based on problem complexity
- Multi-modal CoT: Incorporating visual or auditory information in the reasoning process (https://arxiv.org/abs/2302.00923)
- Collaborative CoT: Combining insights from multiple LLMs or human-AI collaboration (https://arxiv.org/html/2409.07355v1)
- Meta-learning for CoT: Meta-learning and CoT approaches have emerged as powerful techniques for addressing the challenges of few-shot relation extraction (https://arxiv.org/abs/2311.05922)
Here’s a conceptual implementation of adaptive CoT:
def adaptive_cot( model, tokenizer, problem, complexity_threshold=0.7): # Assess problem complexity complexity = assess_problem_complexity(problem) if complexity > complexity_threshold: # Use detailed CoT for complex problems return detailed_cot(model, tokenizer, problem) else: # Use simple direct approach for simpler problems return simple_solve(model, tokenizer, problem)def assess_problem_complexity(problem): # Implement logic to assess problem complexity # This could involve keyword analysis, sentence structure, etc. passdef detailed_cot(model, tokenizer, problem): # Implement detailed Chain-of-Thought approach passdef simple_solve(model, tokenizer, problem): # Implement simple direct solving approach pass# Example usageproblem = "What is the result of 25 divided by 5?"solution = adaptive_cot(model, tokenizer, problem)print(solution)This adaptive CoT approach assesses problem complexity and chooses an appropriate solving strategy, balancing efficiency and reasoning depth.
The adaptive_cot function adapts the CoT approach based on the complexity of the problem. It first assesses the problem’s complexity by calling the assess_problem_complexity function, which could involve analyzing keywords, sentence structure, or other features to determine how complex the problem is (though the logic for this is yet to be implemented). If the complexity score exceeds a predefined threshold (complexity_threshold), the function uses a detailed CoT approach via the detailed_cot function, which would generate a more elaborate, step-by-step solution. For simpler problems, it uses a straightforward solving method via the simple_solve function, which provides a direct answer without breaking down the problem into multiple steps. The result is returned based on which approach is deemed appropriate for the given problem. This dynamic approach allows the model to choose the most efficient method of solving a problem based on its complexity.
Summary
Section titled “Summary”In this chapter, you learned how to design effective CoT prompts that guide LLMs through step-by-step reasoning processes. We covered applications of this technique in various problem-solving scenarios and discussed how to combine it with other prompting strategies. You also learned how to evaluate the quality of CoT outputs and understood the limitations of this approach.
By implementing the strategies and considerations discussed in this chapter, you can significantly improve your LLM’s performance on complex problem-solving tasks, while also gaining insights into the model’s reasoning process.
In the next chapter, we will investigate tree-of-thoughts (ToT) prompting, an advanced technique that extends the concepts of CoT to create even more sophisticated reasoning structures.