|
| 1 | +import argparse |
| 2 | +import asyncio |
| 3 | +import itertools |
| 4 | +import os |
| 5 | +import re |
| 6 | +from typing import Iterator, TypedDict, cast |
| 7 | + |
| 8 | +import polars as pl |
| 9 | + |
| 10 | +import art |
| 11 | +from art.local import LocalBackend |
| 12 | + |
| 13 | + |
| 14 | +class DecodedImage(TypedDict): |
| 15 | + bytes: bytes |
| 16 | + |
| 17 | + |
| 18 | +class Scenario(TypedDict): |
| 19 | + pid: int |
| 20 | + question: str |
| 21 | + answer: str |
| 22 | + image: str |
| 23 | + decoded_image: DecodedImage |
| 24 | + |
| 25 | + |
| 26 | +async def main(model_name: str, steps: int) -> None: |
| 27 | + # Load and shuffle the dataset |
| 28 | + df = pl.read_parquet( |
| 29 | + "hf://datasets/AI4Math/MathVista/data/testmini-00000-of-00001-725687bf7a18d64b.parquet" |
| 30 | + ).sample(fraction=1.0, shuffle=True, seed=42) |
| 31 | + |
| 32 | + val_scenarios = cast(list[Scenario], df.head(64).to_dicts()) |
| 33 | + train_scenarios_iter = cast(Iterator[Scenario], df.tail(-64).iter_rows(named=True)) |
| 34 | + |
| 35 | + # Initialize trainable model and backend |
| 36 | + model = art.TrainableModel( |
| 37 | + name=model_name, |
| 38 | + project="math-vista", |
| 39 | + base_model="Qwen/Qwen2.5-VL-7B-Instruct", |
| 40 | + ) |
| 41 | + |
| 42 | + async def rollout(scenario: Scenario) -> art.Trajectory: |
| 43 | + image_path = f"/tmp/{scenario['image']}" |
| 44 | + os.makedirs(os.path.dirname(image_path), exist_ok=True) |
| 45 | + with open(image_path, "wb") as f: |
| 46 | + f.write(scenario["decoded_image"]["bytes"]) |
| 47 | + |
| 48 | + trajectory = art.Trajectory(messages_and_choices=[], reward=0.0) |
| 49 | + trajectory.messages_and_choices = [ |
| 50 | + { |
| 51 | + "role": "user", |
| 52 | + "content": [ |
| 53 | + { |
| 54 | + "type": "text", |
| 55 | + "text": scenario["question"] |
| 56 | + + "\n\nNote: Provide your answer in a LaTeX box.", |
| 57 | + }, |
| 58 | + {"type": "image_url", "image_url": {"url": f"file://{image_path}"}}, |
| 59 | + ], |
| 60 | + } |
| 61 | + ] |
| 62 | + |
| 63 | + chat_completion = await client.chat.completions.create( |
| 64 | + model=model.name, messages=trajectory.messages() |
| 65 | + ) |
| 66 | + choice = chat_completion.choices[0] |
| 67 | + trajectory.messages_and_choices.append(choice) |
| 68 | + content = choice.message.content |
| 69 | + assert content is not None |
| 70 | + |
| 71 | + if matches := list(re.finditer(r"\\boxed\{(.*?)\}", content, re.DOTALL)): |
| 72 | + match = matches[-1] |
| 73 | + answer = match.group(1) |
| 74 | + if answer.lower() == scenario["answer"].lower(): |
| 75 | + trajectory.reward = 1.0 |
| 76 | + return trajectory |
| 77 | + |
| 78 | + SCENARIOS_PER_STEP = 8 |
| 79 | + TRAJECTORY_GROUP_SIZE = 8 |
| 80 | + |
| 81 | + with LocalBackend() as backend: |
| 82 | + await model.register(backend) |
| 83 | + client = model.openai_client() |
| 84 | + |
| 85 | + start = await model.get_step() |
| 86 | + train_scenarios_iter = itertools.cycle(train_scenarios_iter) |
| 87 | + for _ in range(start * SCENARIOS_PER_STEP): |
| 88 | + next(train_scenarios_iter) |
| 89 | + |
| 90 | + # Training loop |
| 91 | + for _ in range(start, steps): |
| 92 | + train_scenarios = [ |
| 93 | + next(train_scenarios_iter) for _ in range(SCENARIOS_PER_STEP) |
| 94 | + ] |
| 95 | + val_trajectories, train_trajectory_groups = await asyncio.gather( |
| 96 | + art.gather_trajectories( |
| 97 | + (rollout(scenario) for scenario in val_scenarios), |
| 98 | + pbar_desc="gather(val)", |
| 99 | + max_exceptions=32, |
| 100 | + ), |
| 101 | + art.gather_trajectory_groups( |
| 102 | + ( |
| 103 | + art.TrajectoryGroup( |
| 104 | + rollout(scenario) for _ in range(TRAJECTORY_GROUP_SIZE) |
| 105 | + ) |
| 106 | + for scenario in train_scenarios |
| 107 | + ), |
| 108 | + pbar_desc="gather(train)", |
| 109 | + max_exceptions=32, |
| 110 | + ), |
| 111 | + ) |
| 112 | + await model.log(val_trajectories) |
| 113 | + await model.train(train_trajectory_groups) |
| 114 | + |
| 115 | + |
| 116 | +def parse_args() -> argparse.Namespace: |
| 117 | + parser = argparse.ArgumentParser(description="Minimal MathVista trainer script") |
| 118 | + parser.add_argument( |
| 119 | + "-n", |
| 120 | + "--name", |
| 121 | + required=True, |
| 122 | + help="Run/model name to use for the TrainableModel", |
| 123 | + ) |
| 124 | + parser.add_argument( |
| 125 | + "-s", |
| 126 | + "--steps", |
| 127 | + type=int, |
| 128 | + default=1000, |
| 129 | + help="Number of training steps to run", |
| 130 | + ) |
| 131 | + return parser.parse_args() |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + args = parse_args() |
| 136 | + asyncio.run(main(args.name, args.steps)) |
0 commit comments