|
| 1 | +"""Chain-of-thought warm-up for GRPO training. |
| 2 | +
|
| 3 | +Provides utilities to annotate successful demonstration episodes with |
| 4 | +chain-of-thought reasoning, then convert them to SFT training format. |
| 5 | +This CoT SFT warm-up initializes the policy before GRPO online RL, |
| 6 | +giving the model a better starting point for action generation. |
| 7 | +
|
| 8 | +The two-step process: |
| 9 | + 1. generate_cot_annotations(): Use a capable model to add reasoning |
| 10 | + to each step of successful demonstrations. |
| 11 | + 2. build_cot_sft_samples(): Convert annotated episodes to the |
| 12 | + TRL SFT format used by trl_trainer.py. |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def generate_cot_annotations( |
| 24 | + episodes: list[Any], |
| 25 | + annotator_model: str = "gpt-4o", |
| 26 | +) -> list[Any]: |
| 27 | + """Add chain-of-thought reasoning to successful demonstrations. |
| 28 | +
|
| 29 | + For each step in a successful episode, uses the specified model to |
| 30 | + generate reasoning that explains the action choice given the |
| 31 | + screenshot context. This produces <think>...</think> blocks that |
| 32 | + teach the model to reason before acting. |
| 33 | +
|
| 34 | + Args: |
| 35 | + episodes: List of Episode objects from openadapt_ml.schema. |
| 36 | + Only successful episodes (episode.success == True) are |
| 37 | + annotated; others are returned unchanged. |
| 38 | + annotator_model: Model identifier for generating CoT annotations. |
| 39 | + Must support vision (image inputs). |
| 40 | +
|
| 41 | + Returns: |
| 42 | + List of episodes with reasoning fields populated on each step. |
| 43 | + Episodes that were already annotated or unsuccessful are |
| 44 | + returned unchanged. |
| 45 | + """ |
| 46 | + # Deferred import for optional dependency |
| 47 | + try: |
| 48 | + from openadapt_ml.models.api_adapter import get_api_adapter |
| 49 | + except ImportError: |
| 50 | + logger.error( |
| 51 | + "openadapt_ml.models.api_adapter not available. " |
| 52 | + "Cannot generate CoT annotations." |
| 53 | + ) |
| 54 | + return episodes |
| 55 | + |
| 56 | + annotated = [] |
| 57 | + |
| 58 | + for episode in episodes: |
| 59 | + if not getattr(episode, "success", False): |
| 60 | + annotated.append(episode) |
| 61 | + continue |
| 62 | + |
| 63 | + instruction = getattr(episode, "instruction", "") |
| 64 | + steps = getattr(episode, "steps", []) |
| 65 | + |
| 66 | + for step_idx, step in enumerate(steps): |
| 67 | + # Skip if already annotated |
| 68 | + if getattr(step, "reasoning", None): |
| 69 | + continue |
| 70 | + |
| 71 | + screenshot_path = getattr( |
| 72 | + getattr(step, "observation", None), |
| 73 | + "screenshot_path", |
| 74 | + None, |
| 75 | + ) |
| 76 | + action = getattr(step, "action", None) |
| 77 | + |
| 78 | + if not screenshot_path or not action: |
| 79 | + continue |
| 80 | + |
| 81 | + prompt = ( |
| 82 | + f"You are analyzing step {step_idx + 1} of {len(steps)} " |
| 83 | + f"in a GUI automation task.\n\n" |
| 84 | + f"Task instruction: {instruction}\n\n" |
| 85 | + f"The action taken at this step was: {action}\n\n" |
| 86 | + "Explain in 1-2 sentences WHY this action was taken. " |
| 87 | + "Focus on what the agent sees on screen and how the " |
| 88 | + "action moves toward completing the task. " |
| 89 | + "Be concise and specific." |
| 90 | + ) |
| 91 | + |
| 92 | + try: |
| 93 | + adapter = get_api_adapter(annotator_model) |
| 94 | + reasoning = adapter.generate( |
| 95 | + { |
| 96 | + "images": [screenshot_path], |
| 97 | + "messages": [ |
| 98 | + {"role": "user", "content": prompt}, |
| 99 | + ], |
| 100 | + }, |
| 101 | + max_new_tokens=150, |
| 102 | + ) |
| 103 | + step.reasoning = reasoning.strip() |
| 104 | + logger.debug( |
| 105 | + "Annotated step %d: %s", |
| 106 | + step_idx, |
| 107 | + step.reasoning[:80], |
| 108 | + ) |
| 109 | + except Exception as e: |
| 110 | + logger.warning( |
| 111 | + "Failed to annotate step %d: %s", step_idx, e |
| 112 | + ) |
| 113 | + |
| 114 | + annotated.append(episode) |
| 115 | + |
| 116 | + logger.info( |
| 117 | + "CoT annotation complete: %d episodes processed", len(annotated) |
| 118 | + ) |
| 119 | + return annotated |
| 120 | + |
| 121 | + |
| 122 | +def build_cot_sft_samples(annotated_episodes: list[Any]) -> list[dict]: |
| 123 | + """Convert CoT-annotated episodes to TRL SFT format. |
| 124 | +
|
| 125 | + Produces training samples where the assistant response includes a |
| 126 | + <think> block before the action, teaching the model to reason |
| 127 | + step-by-step during inference. |
| 128 | +
|
| 129 | + Format: |
| 130 | + User: <image> |
| 131 | + Instruction: Open Notepad and type Hello |
| 132 | + Previous actions: CLICK(x=0.05, y=0.95) |
| 133 | +
|
| 134 | + Assistant: <think>I see the Start menu is open. The task requires |
| 135 | + opening Notepad, so I need to search for it.</think> |
| 136 | + TYPE(text="notepad") |
| 137 | +
|
| 138 | + Args: |
| 139 | + annotated_episodes: Episodes with reasoning fields on steps, |
| 140 | + typically from generate_cot_annotations(). |
| 141 | +
|
| 142 | + Returns: |
| 143 | + List of SFT sample dicts compatible with trl_trainer.py: |
| 144 | + { |
| 145 | + "images": [path], |
| 146 | + "messages": [system, user, assistant], |
| 147 | + } |
| 148 | + """ |
| 149 | + from openadapt_ml.datasets.next_action import ( |
| 150 | + SYSTEM_PROMPT, |
| 151 | + format_action, |
| 152 | + ) |
| 153 | + |
| 154 | + samples: list[dict] = [] |
| 155 | + |
| 156 | + for episode in annotated_episodes: |
| 157 | + if not getattr(episode, "success", False): |
| 158 | + continue |
| 159 | + |
| 160 | + instruction = getattr(episode, "instruction", "") |
| 161 | + steps = getattr(episode, "steps", []) |
| 162 | + |
| 163 | + for step in steps: |
| 164 | + screenshot_path = getattr( |
| 165 | + getattr(step, "observation", None), |
| 166 | + "screenshot_path", |
| 167 | + None, |
| 168 | + ) |
| 169 | + action = getattr(step, "action", None) |
| 170 | + reasoning = getattr(step, "reasoning", None) |
| 171 | + |
| 172 | + if not screenshot_path or not action: |
| 173 | + continue |
| 174 | + |
| 175 | + # Build action history |
| 176 | + step_index = getattr(step, "step_index", 0) |
| 177 | + prev_actions = [] |
| 178 | + for prev_step in steps: |
| 179 | + prev_idx = getattr(prev_step, "step_index", 0) |
| 180 | + if prev_idx < step_index: |
| 181 | + prev_actions.append( |
| 182 | + format_action(prev_step.action) |
| 183 | + ) |
| 184 | + |
| 185 | + # Build user content |
| 186 | + parts = [f"Instruction: {instruction}"] |
| 187 | + if prev_actions: |
| 188 | + parts.append( |
| 189 | + "Previous actions: " |
| 190 | + + " -> ".join(prev_actions) |
| 191 | + ) |
| 192 | + user_content = "\n".join(parts) |
| 193 | + |
| 194 | + # Build assistant content with CoT |
| 195 | + action_text = format_action(action) |
| 196 | + if reasoning: |
| 197 | + assistant_content = f"<think>{reasoning}</think>\n{action_text}" |
| 198 | + else: |
| 199 | + assistant_content = action_text |
| 200 | + |
| 201 | + sample = { |
| 202 | + "images": [screenshot_path], |
| 203 | + "messages": [ |
| 204 | + {"role": "system", "content": SYSTEM_PROMPT}, |
| 205 | + {"role": "user", "content": user_content}, |
| 206 | + {"role": "assistant", "content": assistant_content}, |
| 207 | + ], |
| 208 | + } |
| 209 | + samples.append(sample) |
| 210 | + |
| 211 | + logger.info("Built %d CoT SFT samples", len(samples)) |
| 212 | + return samples |
0 commit comments