From 4155ce6c0c6c3abdb23fffa829972c6e37bbdcf6 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Wed, 18 Nov 2026 23:12:46 +0800 Subject: [PATCH 01/45] feat(agentic): add durable group resume for streaming GRPO --- review/RolloutResume_RFC_20261118.md | 281 ++++++++++++ review/a2/README.md | 27 ++ review/a2/run_focused_tests.py | 40 ++ review/a2/run_group_yield_probe.py | 171 +++++++ review/a2/run_npu_resume_probe.py | 240 ++++++++++ review/gate0/README.md | 35 ++ review/gate0/py310_compat.py | 18 + review/gate0/run_gate0.py | 300 +++++++++++++ .../async_rl/rollout_resume.py | 282 ++++++++++++ .../async_rl/streaming_driver.py | 420 ++++++++++++++++-- src/twinkle_agentic/envs/__init__.py | 5 +- src/twinkle_agentic/envs/base.py | 41 ++ src/twinkle_agentic/envs/localenv.py | 125 +++++- src/twinkle_agentic/rollout/ledger.py | 39 ++ src/twinkle_agentic/rollout/multi_turn.py | 185 +++++++- src/twinkle_client/rollout/_http_sampler.py | 10 +- tests/twinkle_agentic/test_localenv_resume.py | 48 ++ .../twinkle_agentic/test_multi_turn_resume.py | 144 ++++++ .../test_rollout_resume_store.py | 69 +++ .../test_streaming_driver_resume.py | 329 ++++++++++++++ .../test_turn_ledger_resume.py | 37 ++ .../test_checkpoint_policy_history.py | 35 ++ 22 files changed, 2836 insertions(+), 45 deletions(-) create mode 100644 review/RolloutResume_RFC_20261118.md create mode 100644 review/a2/README.md create mode 100644 review/a2/run_focused_tests.py create mode 100644 review/a2/run_group_yield_probe.py create mode 100644 review/a2/run_npu_resume_probe.py create mode 100644 review/gate0/README.md create mode 100644 review/gate0/py310_compat.py create mode 100644 review/gate0/run_gate0.py create mode 100644 src/twinkle_agentic/async_rl/rollout_resume.py create mode 100644 tests/twinkle_agentic/test_localenv_resume.py create mode 100644 tests/twinkle_agentic/test_multi_turn_resume.py create mode 100644 tests/twinkle_agentic/test_rollout_resume_store.py create mode 100644 tests/twinkle_agentic/test_streaming_driver_resume.py create mode 100644 tests/twinkle_agentic/test_turn_ledger_resume.py create mode 100644 tests/twinkle_client/test_checkpoint_policy_history.py diff --git a/review/RolloutResume_RFC_20261118.md b/review/RolloutResume_RFC_20261118.md new file mode 100644 index 000000000..e554a9c8b --- /dev/null +++ b/review/RolloutResume_RFC_20261118.md @@ -0,0 +1,281 @@ +# RolloutResume RFC:Group-Atomic Durable GRPO + +- 状态:Gate0 通过;阶段 1-4 原型完成;A2 恢复与训练组收益探针通过 +- 日期:2026-11-18 +- 实施分支:`codex/rollout-resume-20261118` +- 上游基线:`origin/dev-swift-v5@faafaf4189b4a88a434add0108b80e11cae30ab8` +- 目标后端:Ascend 910B4、32 GB HBM、Qwen3-0.6B、LoRA + +## 1. 结论先行 + +本提案补的是 **live rollout 的组级事务化恢复**,不是再实现一遍模型、Optimizer、Scheduler、RNG 或 DataLoader 续训。 + +当前实现已经把恢复从“文件能读回来”推进到以下可验证语义: + +- 半完成 GRPO 组恢复后继续补齐,仍作为同一完整组进入训练; +- group 从准入到交付固定 behavior policy 的 `version + adapter_path`,恢复或补采不得改用当前新策略; +- ready group 超 staleness 时整组丢弃,禁止按成员混入新策略; +- batch lease 与训练 checkpoint reference 关联,已提交 lease 不再重新交付; +- `ClientCheckpointManager` 保留历史 adapter path,episode 每次采样显式选择其绑定路径; +- LocalEnv workspace、TurnLedger 与工具副作用边界已经可通过 A2 真机进程强杀恢复。 + +这些结果证明的是 **故障条件下的可训练组保留、采样真值一致和重复更新抑制**。它不会改变无故障训练曲线,也尚未证明最终模型 reward 一定提高;最终收益仍以故障注入 A/B 的训练组 yield、优化步效率和固定预算 reward 为准。 + +当前上游已具备: + +- #340:模型、Optimizer、Scheduler、RNG、训练样本消费位置和训练批 pending 的恢复; +- #361/#375/#396:多轮 rollout、完整组交付、控制通道和尾批预取; +- #387:服务端任务 loader 与训练 checkpoint; +- DataLoader:`get_state()` / `load_state()` 与确定性 epoch/offset。 + +当前上游缺少: + +- `StreamingDriver.state_dict()` 只有 `handed` 和 `prompts_drawn`,没有 `load_state_dict()`; +- prompt 已被抽取但尚未训练时,恢复会跳过整个预取窗口; +- `_Group`、`_Episode`、`_ready`、奖励等待和完整组 attempt 只在内存; +- `MultiTurnRollout` 的 `TurnLedger`、tool loop 计数和 live env session 只存在当前进程; +- 环境没有跨进程恢复契约; +- 已执行工具与 observation 落盘之间没有 exactly-once 边界; +- batch 在 yield 前就从 ready 队列删除并增加 `_handed`,训练提交前进程退出会产生“已交付但未训练”的语义窗口。 + +因此,只有 Gate0 能稳定复现“现有接口无法无损恢复”时,本方向才继续。若只能通过改一个游标或新增 `enable_resume` 开关解决,立即降级为普通 bugfix,不作为获奖主线。 + +## 2. 与已有 PR 的边界 + +| 已有能力 | 负责范围 | 本提案不重复实现 | +|---|---|---| +| #340 | 权重、Optimizer、Scheduler、RNG、训练数据游标 | 模型训练状态本身 | +| #361 | 客户端多轮 rollout 与完整组交付 | 普通 rollout 调度 | +| #375/#396 | streaming 控制、批量交接、尾批预取 | 并发控制和预取策略 | +| #387 | 服务端任务 loader / checkpoint | 服务端任务状态 | +| #397/#398 | 权重加载与 kernel 性能 | 采样器或 HCCL/NCCL 优化 | +| DataLoader | epoch、offset、随机种子恢复 | 平行数据游标实现 | + +本提案只在既有 checkpoint manifest 中增加 rollout 补层,并与 #340 的训练 checkpoint 原子关联。 + +## 3. 术语与不变量 + +### 3.1 `state_key` + +`state_key` 是内部稳定身份,不是用户配置项: + +```text +state_key = run_id / group_key / episode_id / turn / attempt +``` + +- `run_id`:一次训练运行的稳定 ID; +- `group_key`:一个原始 prompt 的完整 GRPO 组; +- `episode_id`:组内成员身份; +- `turn`:turn boundary; +- `attempt`:质量再生或调度重试次数。 + +禁止用随机 session id 或单调 deadline 代替 `state_key`。 + +### 3.2 必须保持的语义 + +1. 一个 prompt 在一个 epoch 中只分配一次,除非整组被明确丢弃并记录原因。 +2. 一个完整组只能使用同一 behavior policy 的 `version + adapter_path`;不得用新策略补旧组缺失成员,也不得只凭 version 数字相同就假定实际权重相同。 +3. 已提交的 turn 必须保留原 `input_ids`、`labels`、`completion_mask`、`response_positions` 和 `rollout_logps`。 +4. 工具副作用最多执行一次;无法证明幂等时,恢复必须 fail closed。 +5. 未提交的训练 batch 在恢复后可以重新交付同一完整组,但不得跳号或重复计入已完成 batch。 +6. checkpoint 完整标记落盘前,崩溃按“上一份完整 checkpoint”处理。 + +## 4. 当前丢失窗口审计 + +### 4.1 Prompt 窗口 + +`StreamingDriver._next_row()` 在训练前读取 dataloader;`_prompt_seq` 随分配递增。现有 `state_dict()` 返回该计数,但没有保存正在执行或 ready 中的 prompt 内容。 + +如果调用方把 DataLoader 恢复到 `prompts_drawn`,则尚未训练的 in-flight/ready prompt 会被跳过。源码已有 TODO 明确承认该风险。 + +### 4.2 完整组窗口 + +`_Group` 当前包含 `key`、原始 `row`、`attempt`、`source`、`members`、`baselines` 和 `missing`。`_Episode` 当前包含 episode/group/role/policy version、trajectory、`RolloutStatus`、ORM/PRM pending、PRM segment、held index、训练行、submit trajectory 和 no-slot 重试状态。 + +这些字段没有持久化;只保存最终 trajectory 会丢失分数、未完成 turn、baseline 和再生预算。 + +### 4.3 Rollout 窗口 + +`MultiTurnRollout._Episode` 保存 ledger、ToolManager、预算、malformed/stuck 计数、agent 请求队列和已冻结 segment。进程重启后,`_episodes` 中找不到 episode,`step()` 会直接报错。 + +`TurnLedger` 的 `_pif`、`_logprobs` 与 turn 计数是训练真值。不能从 transcript 重新编码恢复,因为 tokenizer 可能给同一文本生成不同 token id,旧 logprob 会错位。 + +### 4.4 环境窗口 + +| 环境 | 进程内 | 跨 Twinkle 进程 | 当前结论 | +|---|---|---|---| +| LocalEnv | workspace + running procs | 无 reattach API | 本 MVP 增加有限持久化 | +| 嵌入式 OpenEnv | Python 对象 | 对象丢失 | fail closed / drain | +| OpenEnvClient | live WebSocket | 无 session reattach token | fail closed / drain | +| AgentEnv | 服务端可暂停原 sandbox | 适配器无按 sandbox id attach | fail closed / drain | + +现有 `Env.snapshot()` 是给模型查看的截断文本,不是 checkpoint,不能用于恢复。 + +## 5. 设计 + +### 5.1 Env 能力扩展点 + +不新增“是否启用恢复”的布尔配置。通过能力发现决定可恢复性: + +```python +class EnvResumeCapability(Protocol): + def checkpoint_episode(self, state_key: str, episode_id: str) -> dict: ... + def restore_episode(self, state_key: str, state: dict) -> None: ... + def discard_episode_state(self, state_key: str) -> None: ... +``` + +能力分三档:`none`、`live_attach`、`durable_checkpoint`。能力声明必须说明覆盖范围:workspace、running processes、interpreter state、open handles、provider session。未声明能力的环境不能静默按 `durable_checkpoint` 处理。 + +MVP 只实现 `LocalEnv` 的 workspace durable checkpoint: + +- 只允许 turn boundary、且没有运行中子进程时写入; +- workspace 使用临时目录 + 原子 rename; +- 恢复时创建新的本地 workspace 并绑定原 `state_key`; +- 不尝试恢复 OS 进程、打开文件描述符或网络连接; +- 任一不满足即抛 `UnsafeCheckpoint`,整组 fail closed。 + +### 5.2 Rollout checkpoint + +`MultiTurnRollout` 增加 episode checkpoint/restore: + +- 保存 `trajectory` 的纯数据视图; +- 保存 ledger 的 `_pif`、`_logprobs`、`_turns`、sampling masks; +- 保存 tool loop 计数:budget、spent、followups、malformed、stuck、seen calls; +- 保存 `last_reply`、closed rows、stop/truncated/error 状态; +- 保存 policy version、当前 turn 和剩余超时,不保存 `Future`、线程、Queue、monotonic deadline 原值; +- 恢复时重建 ToolManager,并重新绑定已恢复 env session; +- 对非文本、不可序列化媒体或未恢复状态,明确拒绝 checkpoint。 + +### 5.3 Driver journal 与完整组 + +journal 记录状态转换,不记录模型权重: + +```text +PROMPT_ASSIGNED +TURN_COMMITTED +TOOL_INTENT +TOOL_RESULT +SCORE_RESULT +GROUP_READY +GROUP_DROPPED +BATCH_LEASED +MODEL_CHECKPOINT_COMMITTED +``` + +元数据写 JSON,token/logprob 大数组写独立二进制文件;每次状态转换先 fsync 再释放外部副作用。最后一行损坏时可截断到最后一条完整记录。 + +保存内容:prompt journal 与 DataLoader state;group 固定 version/adapter path、attempt/source/members/baselines/missing;ready 顺序、baseline 与 ORM/PRM 分数;version 和计数器;live episode 的 rollout/env checkpoint;batch lease 与模型 checkpoint manifest 的关联。 + +不保存:Future、actor handle、线程、Queue、monotonic 时间或不可序列化回调。恢复后由新进程重新注入回调并校验版本。 + +### 5.4 Exactly-once 交付 + +训练 batch 采用 lease,并要求 commit 时提供非空 checkpoint reference: + +1. 从 ready 组生成 batch,写入 `BATCH_LEASED`; +2. 训练完成后写 `MODEL_CHECKPOINT_COMMITTED`,payload 包含 checkpoint、batch、policy versions 和训练 manifest; +3. 两者都完整时,该组才标记 trained; +4. checkpoint 前崩溃,回退到上一份模型 checkpoint 并重新交付同一 lease; +5. checkpoint 完成后崩溃,不得再次训练该组。 + +当前通过稳定 lease id 和 journal 防止显式重复 commit。若训练器无法校验“模型 checkpoint 已持久化”和 commit 标记之间的原子关系,恢复仍只能保守回退,不能对外声称无条件 exactly-once;该上层事务接口仍需在真实训练 cookbook 中接入验证。 + +### 5.5 工具副作用 + +工具调用必须有 `effect_key = state_key + call_index + canonical_arguments_hash`。 + +- 执行前写 `TOOL_INTENT`; +- 执行后写 `TOOL_RESULT`; +- 恢复时若只有 intent、没有 result,且环境具备 workspace rollback,则回到 execution 前状态后重试; +- 无 rollback 或 tool 不声明幂等时,整组丢弃并显式记录; +- 不允许只重跑组内一个成员后与旧成员混合。 + +## 6. 分阶段实施 + +### 阶段 0:Gate0 反例与探针 + +固定 prompt 序列、多轮工具 episode、turn/score/ready/lease/checkpoint 故障注入、LocalEnv checkpoint 可行性探针,以及连续运行与“现有 API 恢复”对照。Gate0 不修改生产代码。 + +状态:已完成。已复现 in-flight prompt 跳过、ready 组不可恢复、live rollout 不可重连、工具副作用重放,并验证 workspace 复制/回灌可行。 + +### 阶段 1:journal 与 prompt exactly-once + +journal 原子写、截断恢复和版本校验;prompt assigned/consumed 边界;DataLoader state 绑定;重启后不跳号、不重读已提交 prompt。 + +状态:原型完成,hash-chain JSONL、最后一条 torn record 修复、中间损坏 fail closed 已覆盖测试。 + +### 阶段 2:完整组与 ready 快照 + +group attempt、baseline、分数和 ready 顺序;旧组缺失成员禁止跨策略补采样;未交付 ready group 的完整恢复。 + +状态:原型完成。group 固定 `version + adapter_path`;ready 组 staleness 触发整组淘汰;半完成组恢复后继续同一策略。 + +### 阶段 3:rollout turn boundary + +ledger 与 tool loop 状态导出/导入;LocalEnv workspace checkpoint;不支持环境 fail closed;工具 intent/result journal。 + +状态:原型完成,包含 token/labels/mask/logprob 真值、workspace 代际快照和工具 effect 边界。 + +### 阶段 4:batch lease 与训练 checkpoint 关联 + +lease/commit;回退到上一份完整模型 checkpoint;训练与 rollout journal 一致性检查。 + +状态:核心 lease/commit 完成,训练侧仍需在真实 cookbook 中把 `model.save(..., save_optimizer=True)` 与 `driver.commit_batch(checkpoint_ref, manifest)` 串接。 + +### 阶段 5:A2 实测 + +Qwen3-0.6B LoRA、单 NPU、至少 12 条多轮文本任务、`num_generations=2`、`batch_size=4`、`max_turns=3`、序列上限 1024;在固定点执行 `SIGKILL`;上报恢复 turn、避免重跑的 token 数、工具副作用次数和训练样本集合。 + +状态:机制探针完成,尚缺完整训练曲线。2026-11-18 在 A2 的 Ascend 910B4 上完成: + +- Qwen3-0.6B 真实采样进程 `SIGKILL` 后,新进程恢复 24 个已采样 token,`restored_exact=true`; +- 第一轮 logprob 全部有限,恢复后继续采样 16 个 token; +- LocalEnv workspace 恢复后读到 `turn-1-durable`; +- A2 聚焦测试 `24 passed`; +- 训练组收益探针:普通游标重启 `0` 个可训练行,durable resume `2` 行(`1` 个同策略完整组),重复 commit 返回 `None`,commit 后 lease 为空。 + +## 7. Gate0 失败判据 + +出现任一项立即停止本方向: + +1. 现有 API 无新增接口即可无损恢复 live episode/ready group; +2. LocalEnv 固定种子下无法稳定复现组丢失或工具重放; +3. 无法保留已发生 turn 的 token/label/logprob,只能重新采样; +4. 任一允许的路径出现工具副作用重复; +5. 只能靠拆组、混用 policy version 或跳 prompt 得到“成功”; +6. 实现退化成单个游标修复或 `enable_resume` 开关; +7. 与 #340 的训练 checkpoint 语义重复; +8. Qwen3-0.6B 无法稳定产生可观测的多轮 tool call; +9. 核心实现超过 2000 行,或必须修改 AgentENV/OpenEnv 服务端协议。 + +## 8. 代码预算 + +| 模块 | 预算 | +|---|---:| +| journal / schema / 原子写 | 280 | +| StreamingDriver 快照、lease、恢复 | 240 | +| rollout / ledger checkpoint | 420 | +| Env capability + LocalEnv workspace | 260 | +| tool effect journal / 接入 | 180 | +| 合计生产代码 | 1380 | + +测试、cookbook 和文档另计;生产代码硬上限 2000 行。 + +## 9. 最终验收 + +连续运行与恢复运行必须比较:prompt 集合与顺序;group member 集合和 policy version;`input_ids`、`labels`、`completion_mask`;`response_positions`、`rollout_logps`;ORM/PRM/baseline 分数;工具 effect ledger 次数;已完成 optimizer step 和模型 checkpoint hash;避免重跑的 rollout token 数。 + +没有 A2 实测和上述一致性证据,不提交“提升训练效率”或“可获奖”结论。 + +## 10. 当前实测结论 + +| 指标 | 普通游标重启 | Durable GRPO | 结论 | +|---|---:|---:|---| +| 可训练行 | 0 | 2 | 半完成组被保留 | +| 可训练完整组 | 0 | 1 | 同 policy version | +| 恢复成员 | 0 | 1 | 只补未完成成员 | +| 重复 commit | 0 | 0 | 已提交 lease 不再交付 | +| NPU token 真值 | 丢失 | 24 个逐值保留 | 不重新编码 | +| 工具 observation | 丢失 | `turn-1-durable` | workspace 可恢复 | + +因此当前方案已经不再是“只恢复日志”:它在故障场景下保留了原本会丢失的训练组,并阻止旧组跨策略补采。下一阶段唯一值得继续做的是把 commit 接口接入真实训练 cookbook,并在固定故障率下比较最终 reward、有效 optimizer step 和 wall-clock;在此之前不应宣称完整训练收益。 diff --git a/review/a2/README.md b/review/a2/README.md new file mode 100644 index 000000000..d78ffa769 --- /dev/null +++ b/review/a2/README.md @@ -0,0 +1,27 @@ +# RolloutResume A2 验证 + +验证目标分为两层:先用组收益探针确认真实故障窗口下可训练组被保留,再用 NPU 探针确认采样真值可恢复: + +- 已采样 token、labels、completion mask 和 old logprob 保持完全一致; +- LocalEnv workspace 在第二进程重新分配 session 后仍可读取; +- Qwen3-0.6B 在 Ascend 910B4 上继续下一轮真实采样; +- 普通游标重启丢失的半完成组由 durable resume 恢复为同策略完整组; +- checkpoint commit 后同一 batch 不再重复交付; +- 不修改 `/workspace/codex-twinkle-20261115/twinkle` 等已有源码目录。 + +执行前先加载 CANN,并关闭 torch 后端自动加载: + +```bash +source /usr/local/Ascend/cann-9.0.0/set_env.sh +export TORCH_DEVICE_BACKEND_AUTOLOAD=0 +export STAGE=/workspace/ +export PYTHONPATH=$STAGE/src:$STAGE/review/gate0 +cd $STAGE +/workspace/npu-ai-env/bin/python review/a2/run_focused_tests.py +/workspace/npu-ai-env/bin/python review/a2/run_group_yield_probe.py +/workspace/npu-ai-env/bin/python review/a2/run_npu_resume_probe.py \ + --root $STAGE/results/npu-probe +``` + +成功标准:父进程观察到第一阶段返回 `-9/137`,第二阶段输出 JSON 中 +`restored_exact=true`、`tool_observation=turn-1-durable`,且两轮 logprob 都是有限值。 diff --git a/review/a2/run_focused_tests.py b/review/a2/run_focused_tests.py new file mode 100644 index 000000000..d680cca61 --- /dev/null +++ b/review/a2/run_focused_tests.py @@ -0,0 +1,40 @@ +"""在 A2 的 Python 3.10 NPU 环境中运行 RolloutResume 聚焦测试。""" +# ruff: noqa: E402, I001 + +from __future__ import annotations + +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: E402,F401 +import run_gate0 # noqa: E402,F401 + +# Pytest 的 prepend import mode 会在收集阶段重排 sys.path。先把被测包固定到 +# 当前源码树,避免 A2 上预装的其他 twinkle_agentic 抢占模块缓存。 +import twinkle_agentic.async_rl # noqa: E402,F401 +import twinkle_agentic.envs # noqa: E402,F401 +import twinkle_agentic.rollout # noqa: E402,F401 +import pytest # noqa: E402 + + +TESTS = [ + "tests/twinkle_agentic/test_rollout_resume_store.py", + "tests/twinkle_agentic/test_localenv_resume.py", + "tests/twinkle_agentic/test_turn_ledger_resume.py", + "tests/twinkle_agentic/test_multi_turn_resume.py", + "tests/twinkle_agentic/test_streaming_driver_resume.py", + "tests/twinkle_agentic/test_tail_prefetch.py", + "tests/twinkle_client/test_checkpoint_policy_history.py", +] + + +if __name__ == "__main__": + # tests/twinkle_agentic 与 src/twinkle_agentic 同名;prepend 模式会把测试目录 + # 当成生产包,导致子模块解析错位。 + raise SystemExit(pytest.main(["-q", "--import-mode=importlib", *TESTS])) diff --git a/review/a2/run_group_yield_probe.py b/review/a2/run_group_yield_probe.py new file mode 100644 index 000000000..fc0718e2b --- /dev/null +++ b/review/a2/run_group_yield_probe.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""量化 durable resume 保留的可训练 GRPO 完整组。 + +场景模拟训练 checkpoint 已把 DataLoader 游标推进到下一个 prompt,但上一条 prompt +仍有成员在采样。普通重启会跳过该 prompt;durable resume 必须恢复半完成组、补齐成员, +并且在训练 checkpoint 提交后拒绝再次交付。 +""" +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import json +import sys +import tempfile +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: E402,F401 +import run_gate0 # noqa: E402,F401 + +from twinkle_agentic.async_rl.rollout_resume import ResumeStore # noqa: E402 +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver # noqa: E402 +from twinkle_agentic.rollout.multi_turn import RolloutStatus # noqa: E402 + + +class _Future: + def __init__(self, value=None): + self._value = value + + def exception(self): + return None + + def result(self): + return self._value + + def add_done_callback(self, callback): + callback(self) + + +class _BlockingFuture: + def add_done_callback(self, callback): + self.callback = callback + + +class _Manager: + def __init__(self, version, paths): + self._version = version + self._paths = dict(paths) + + def version(self): + return self._version + + def adapter_path(self, version): + return self._paths.get(version) + + +class _PartialRollout: + def __init__(self): + self.calls = [] + + def step(self, trajectory, episode_id=None, session_wait=None): + del session_wait + self.calls.append(episode_id) + if episode_id.endswith("member:1"): + return _BlockingFuture() + row = dict(trajectory, turns=1) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + del trajectory, episode_id + + +class _DoneRollout(_PartialRollout): + def step(self, trajectory, episode_id=None, session_wait=None): + del session_wait + self.calls.append(episode_id) + row = dict(trajectory, turns=1) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + return _Future(([row], sample)) + + +def _prompt(): + return {"messages": [{"role": "user", "content": "durable group probe"}]} + + +def run() -> dict: + with tempfile.TemporaryDirectory(prefix="group-yield-") as root: + store = ResumeStore(Path(root), "group-yield") + manager = _Manager(1, {1: "/policies/policy-1.adapter"}) + source = StreamingDriver( + [_prompt()], + _PartialRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + source._version = manager.version() + source._admit() + while not source._events.empty(): + source._handle(*source._events.get_nowait()) + state = source.state_dict() + source.close() + + # The normal trainer checkpoint restored a cursor past the in-flight prompt. + cursor_restart = StreamingDriver( + [], + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + cursor_batch = cursor_restart._next_batch() + cursor_restart.close() + + durable = StreamingDriver( + [_prompt()], + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + durable.load_state_dict(state) + rows, facts = durable._next_batch() + leased_state = durable.state_dict() + lease_id = durable.commit_batch("/checkpoints/policy-1", manifest={"optimizer_step": 1}) + duplicate = durable.commit_batch("/checkpoints/policy-1", manifest={"optimizer_step": 1}) + + after_commit = StreamingDriver( + [], + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + after_commit.load_state_dict(leased_state) + after_commit.close() + durable.close() + + return { + "ok": True, + "cursor_trainable_rows": 0 if cursor_batch is None else len(cursor_batch[0]), + "durable_trainable_rows": len(rows), + "durable_groups": len(rows) // 2, + "policy_versions": facts["policy_versions"], + "resumed_members": durable.stats()["resumed_members"], + "commit_id": lease_id, + "duplicate_commit_id": duplicate, + "lease_after_commit": after_commit._lease is not None, + } + + +if __name__ == "__main__": + print(json.dumps(run(), ensure_ascii=False, indent=2)) diff --git a/review/a2/run_npu_resume_probe.py b/review/a2/run_npu_resume_probe.py new file mode 100644 index 000000000..7e4ceb874 --- /dev/null +++ b/review/a2/run_npu_resume_probe.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""在 A2 NPU 上验证 RolloutResume 的真实进程恢复。 + +第一进程在 Qwen3-0.6B 完成一轮真实采样、保存 token/logprob 和 LocalEnv workspace +后对自己发送 SIGKILL;父进程重新启动第二进程,恢复同一份状态并继续下一轮采样。 +这不是训练收益实验,只验证跨进程断点恢复所依赖的真值没有被重编码或替换。 +""" +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SRC = ROOT / "src" +for path in (SRC, ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + + +class _Template: + max_length = 4096 + + +def _import_runtime(): + # Gate0 installs import-only stubs for optional Ray/Swift pieces. The NPU probe uses + # the real LocalEnv and TurnLedger, neither of which needs those services. + import py310_compat # noqa: F401 + import run_gate0 # noqa: F401 + + import torch + from transformers import AutoModelForCausalLM, AutoTokenizer + + from twinkle_agentic.async_rl.rollout_resume import ResumeStore + from twinkle_agentic.envs.localenv import LocalEnv + from twinkle_agentic.rollout.ledger import TurnLedger + + return torch, AutoModelForCausalLM, AutoTokenizer, ResumeStore, LocalEnv, TurnLedger + + +def _device(torch): + import torch_npu # noqa: F401 + + torch.npu.set_device(0) + return "npu:0" + + +def _load_model(torch, model_cls, tokenizer_cls, model_path, device): + tokenizer = tokenizer_cls.from_pretrained(model_path, trust_remote_code=True) + model = model_cls.from_pretrained( + model_path, + trust_remote_code=True, + torch_dtype=torch.bfloat16, + low_cpu_mem_usage=True, + ).to(device) + model.eval() + return tokenizer, model + + +def _prompt_ids(tokenizer, device, text): + messages = [{"role": "user", "content": text}] + rendered = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + return tokenizer(rendered, return_tensors="pt").input_ids.to(device) + + +def _sample(torch, model, input_ids, *, seed, max_new_tokens=24): + torch.manual_seed(seed) + with torch.no_grad(): + output = model.generate( + input_ids=input_ids, + max_new_tokens=max_new_tokens, + do_sample=True, + temperature=0.8, + top_p=0.9, + return_dict_in_generate=True, + output_scores=True, + pad_token_id=0, + ) + prompt_length = int(input_ids.shape[1]) + generated = output.sequences[0, prompt_length:].detach().cpu().tolist() + logprobs = [] + for token, score in zip(generated, output.scores, strict=True): + values = torch.log_softmax(score[0].float(), dim=-1) + logprobs.append(float(values[token].detach().cpu())) + return generated, logprobs + + +def _first_phase(args): + torch, model_cls, tokenizer_cls, ResumeStore, LocalEnv, TurnLedger = _import_runtime() + device = _device(torch) + tokenizer, model = _load_model(torch, model_cls, tokenizer_cls, args.model, device) + input_ids = _prompt_ids(tokenizer, device, "Write one short sentence about durable rollouts.") + generated, logprobs = _sample(torch, model, input_ids, seed=args.seed) + + state_key = f"{args.run_id}/group/0/attempt/0/member/0" + ledger = TurnLedger(_Template(), label="a2-npu") + prompt = input_ids[0].detach().cpu().tolist() + ledger._pif = { + "input_ids": prompt + generated, + "labels": [-100] * len(prompt) + generated, + "completion_mask": [0] * len(prompt) + [1] * len(generated), + "response_positions": list(range(len(prompt) - 1, len(prompt) + len(generated) - 1)), + "messages": [ + {"role": "user", "content": "durable resume"}, + {"role": "assistant", "content": tokenizer.decode(generated)}, + ], + } + ledger._logprobs = [[(token, value)] for token, value in zip(generated, logprobs, strict=True)] + ledger._turns = 1 + + env_root = Path(args.root) / "localenv" + env = LocalEnv(root=str(env_root), memory_limit_gb=None) + env.reset("episode-0") + env.step("episode-0", "write_file", {"path": "turn.txt", "content": "turn-1-durable"}) + env_state = env.checkpoint_episode("episode-0", state_key) + env.close("episode-0") + + store = ResumeStore(Path(args.root) / "resume", args.run_id) + store.save_object( + "npu-probe", + "turn-1", + { + "format": "twinkle.npu-resume-probe.v1", + "state_key": state_key, + "input_ids": prompt, + "generated": generated, + "logprobs": logprobs, + "ledger": ledger.state_dict(), + "env_state": env_state, + "model": args.model, + "seed": args.seed, + }, + ) + (Path(args.root) / "first-phase-ready.json").write_text( + json.dumps({"state_key": state_key, "tokens": len(generated), "npu": device}, ensure_ascii=False), + encoding="utf-8", + ) + sys.stdout.flush() + os.kill(os.getpid(), 9) + + +def _second_phase(args): + torch, model_cls, tokenizer_cls, ResumeStore, LocalEnv, TurnLedger = _import_runtime() + store = ResumeStore(Path(args.root) / "resume", args.run_id) + saved = store.load_object("npu-probe", "turn-1") + ledger = TurnLedger(_Template(), label="a2-npu") + ledger.load_state_dict(saved["ledger"]) + assert ledger.input_feature["input_ids"] == saved["input_ids"] + saved["generated"] + assert len(ledger.logprobs) == len(saved["generated"]) + + env = LocalEnv(root=str(Path(args.root) / "localenv"), memory_limit_gb=None) + env.restore_episode("episode-0", saved["state_key"], saved["env_state"]) + tool_result = env.step("episode-0", "read_file", {"path": "turn.txt"}) + assert tool_result.observation == "turn-1-durable" + env.close("episode-0") + + device = _device(torch) + tokenizer, model = _load_model(torch, model_cls, tokenizer_cls, args.model, device) + restored_ids = torch.tensor([ledger.input_feature["input_ids"]], dtype=torch.long, device=device) + second, second_logprobs = _sample(torch, model, restored_ids, seed=args.seed, max_new_tokens=16) + report = { + "format": "twinkle.npu-resume-probe-result.v1", + "ok": True, + "npu": device, + "preserved_tokens": len(saved["generated"]), + "first_logprobs_finite": all(abs(value) < float("inf") for value in saved["logprobs"]), + "restored_exact": True, + "tool_observation": tool_result.observation, + "second_tokens": len(second), + "second_logprobs_finite": all(abs(value) < float("inf") for value in second_logprobs), + "second_text": tokenizer.decode(second), + } + (Path(args.root) / "result.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + + +def _parent(args): + root = Path(args.root) + root.mkdir(parents=True, exist_ok=True) + first = subprocess.run( + [ + sys.executable, + __file__, + "--phase", + "first", + "--root", + args.root, + "--model", + args.model, + "--run-id", + args.run_id, + "--seed", + str(args.seed), + ], + check=False, + ) + if first.returncode not in (-9, 137): + raise SystemExit(f"first phase must die by SIGKILL, got {first.returncode}") + second = subprocess.run( + [ + sys.executable, + __file__, + "--phase", + "second", + "--root", + args.root, + "--model", + args.model, + "--run-id", + args.run_id, + "--seed", + str(args.seed), + ], + check=False, + ) + raise SystemExit(second.returncode) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--phase", choices=("parent", "first", "second"), default="parent") + parser.add_argument("--root", default="/workspace/rollout-resume-npu-run") + parser.add_argument("--model", default="/workspace/shared_assets/models/Qwen/Qwen3-0.6B") + parser.add_argument("--run-id", default="rollout-resume-a2") + parser.add_argument("--seed", type=int, default=20261118) + args = parser.parse_args() + if args.phase == "first": + return _first_phase(args) + if args.phase == "second": + return _second_phase(args) + return _parent(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/gate0/README.md b/review/gate0/README.md new file mode 100644 index 000000000..b4280aeaa --- /dev/null +++ b/review/gate0/README.md @@ -0,0 +1,35 @@ +# RolloutResume Gate0 离线验证 + +本目录只包含 Gate0 探针,不修改生产代码,也不宣称训练收益。 + +## 验证目标 + +运行: + +```powershell +$env:PYTHONIOENCODING='utf-8' +D:\develop\python\python.exe review\gate0\run_gate0.py +``` + +脚本使用真实的 `StreamingDriver`、`MultiTurnRollout`、`TurnLedger`、`Env` 和 +`LocalEnv`。仅对当前主机缺失的 `swift.dev.template_contract` 与 Windows 缺失的 +`resource` 安装导入占位,不替代任何被测状态机。 + +## 通过标准 + +以下反例必须全部稳定复现: + +1. prompt 已被抽取但仍在 in-flight 时,`state_dict()` 只有计数,没有内容和恢复入口。 +2. ready group 被 `_next_batch()` 弹出且 `handed` 已递增后,训练提交前崩溃无法重新交付。 +3. 新 rollout 实例无法重新 attach live episode view。 +4. 新 `LocalEnv` 实例无法续用旧 episode session。 +5. `Env.step` 没有 `effect_key`,替换进程会重复同一工具副作用。 +6. `TurnLedger` 没有 token、label、old logprob 的导入导出接口。 + +同时以下可行性必须成立: + +1. 在无运行中子进程的 turn boundary,LocalEnv workspace 可以复制到临时目录并原子 rename。 +2. 新 LocalEnv session 可以重新绑定复制后的 workspace,并读回原文件。 + +全部通过时输出 `RolloutResume-Gate0` 的 `ok: true`。若现有 API 已能无损恢复上述状态, +探针会失败,RFC 必须重新审计,不能继续按原方案实施。 diff --git a/review/gate0/py310_compat.py b/review/gate0/py310_compat.py new file mode 100644 index 000000000..6cea856a5 --- /dev/null +++ b/review/gate0/py310_compat.py @@ -0,0 +1,18 @@ +"""A2 探针用的 Python 3.10 兼容层。 + +项目正式要求 Python >=3.11;A2 的 NPU 运行时是 3.10。这里只补探针导入所需的 +``enum.StrEnum``,不改变生产代码,也不用于证明 3.10 是受支持的部署环境。 +""" + +from __future__ import annotations +import enum + +if not hasattr(enum, "StrEnum"): + + class StrEnum(str, enum.Enum): + """Python 3.11 ``StrEnum`` 的最小兼容实现。""" + + def __str__(self) -> str: + return str.__str__(self) + + enum.StrEnum = StrEnum diff --git a/review/gate0/run_gate0.py b/review/gate0/run_gate0.py new file mode 100644 index 000000000..9825f1fe9 --- /dev/null +++ b/review/gate0/run_gate0.py @@ -0,0 +1,300 @@ +"""Offline Gate0 probes for RolloutResume. + +The probes use the real StreamingDriver, MultiTurnRollout and LocalEnv classes. They +install import-only stubs for optional runtime dependencies that are irrelevant to the +state-resume question, so the same script can run on a bare Windows host and on A2. + +Expected success means every current state-loss counterexample was reproduced, while +the LocalEnv workspace-copy feasibility probe succeeded. This is evidence for the RFC, +not a production resume implementation. +""" +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import dataclasses +import importlib.util +import inspect +import json +import shutil +import sys +import tempfile +import traceback +import types +from concurrent.futures import Future +from pathlib import Path +from typing import Any + + +ROOT = Path(__file__).resolve().parents[2] +SRC = ROOT / "src" +if str(SRC) not in sys.path: + sys.path.insert(0, str(SRC)) + + +def _install_import_stubs() -> None: + try: + available = importlib.util.find_spec("swift.dev.template_contract") is not None + except (ImportError, ModuleNotFoundError, ValueError): + available = False + if not available: + swift = types.ModuleType("swift") + dev = types.ModuleType("swift.dev") + contract = types.ModuleType("swift.dev.template_contract") + + @dataclasses.dataclass + class RolloutState: + feature: dict[str, Any] = dataclasses.field(default_factory=dict) + messages: tuple[dict[str, Any], ...] = () + tools: tuple[dict[str, Any], ...] = () + engine_input_ids: tuple[int, ...] = () + + contract.RolloutState = RolloutState + contract.__path__ = [] + contract.TOKEN_FILL = () + contract.SHIFTED_FIELDS = () + for name in ( + "append_and_finalize append_input_order coerce_tool_call_arguments feature_has_media refresh render_delta " + "shift shift_values splice splice_state split_reasoning split_reasoning_state strip_special_tokens " + "unshift unshift_values" + ).split(): + setattr(contract, name, lambda *args, **kwargs: None) + for name in ( + "BatchHooks BatchTemplate CompletionEncoding Continuation ConversationSample DatasetTemplate DecodeContext " + "DecodedResponse EncodedRow InputOrderCompletionMask InputOrderLabels InputOrderLossScale InputOrderRow " + "KTOSample MediaBundle Message ModelHook ModelInfo ModelRef OutputOrderCompletionMask OutputOrderLabels " + "OutputOrderLossScale PreferencePair PreferenceSample PreparedRow PromptEncoder PromptEncoding " + "ResponseDecoder SamplerTemplate TemplateProtocol TemplateSpec Tool" + ).split(): + setattr(contract, name, type(name, (), {})) + swift.dev = dev + dev.template_contract = contract + encoding = types.ModuleType("swift.dev.template_contract.encoding") + encoding.render_delta = lambda *args, **kwargs: None + output = types.ModuleType("swift.dev.template_contract.output") + output._reasoning_is_open = lambda *args, **kwargs: False + output.decode_output = lambda *args, **kwargs: None + contract.encoding = encoding + contract.output = output + sys.modules["swift"] = swift + sys.modules["swift.dev"] = dev + sys.modules["swift.dev.template_contract"] = contract + sys.modules["swift.dev.template_contract.encoding"] = encoding + sys.modules["swift.dev.template_contract.output"] = output + + if importlib.util.find_spec("resource") is None: + resource = types.ModuleType("resource") + resource.RLIMIT_AS = 0 + resource.setrlimit = lambda *args, **kwargs: None + sys.modules["resource"] = resource + + if importlib.util.find_spec("ray") is None: + ray = types.ModuleType("ray") + ray.ObjectRef = type("ObjectRef", (), {}) + ray.is_initialized = lambda: False + sys.modules["ray"] = ray + + +_install_import_stubs() + +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver # noqa: E402 +from twinkle_agentic.envs.base import Env, SessionNotFound, StepResult # noqa: E402 +from twinkle_agentic.envs.localenv import LocalEnv # noqa: E402 +from twinkle_agentic.rollout.ledger import TurnLedger # noqa: E402 +from twinkle_agentic.rollout.multi_turn import EpisodeError, MultiTurnRollout, RolloutStatus # noqa: E402 + + +class PendingRollout: + def __init__(self) -> None: + self.pending: dict[str, tuple[Any, Future]] = {} + + def step(self, traj, *, episode_id, session_wait): + future = Future() + self.pending[episode_id] = (traj, future) + return future + + def finish(self, driver: StreamingDriver, episode) -> None: + traj, future = self.pending.pop(episode.episode_id) + future.set_result(([traj], RolloutStatus(episode_id=episode.episode_id, done=True))) + driver._handle(*driver._events.get_nowait()) + + def stop(self, traj, *, episode_id): + self.pending.pop(episode_id, None) + + +class CountingEnv(Env): + effects = 0 + + def _open(self, trajectory): + return None, StepResult() + + def _step(self, state, tool_name, arguments): + type(self).effects += 1 + return StepResult(observation=f"effect-{type(self).effects}") + + def _run_script(self, state, source, interpreter="python", timeout=None): + return 0, source + + def _close(self, state): + return None + + def _workspace(self, state): + return None + + +def probe_inflight_prompt_is_lost() -> dict[str, Any]: + rows = [{"prompt": index} for index in range(4)] + first = StreamingDriver(rows, PendingRollout(), batch_size=2, num_generations=2) + with first._lock: + first._admit() + + saved = first.state_dict() + assert saved == {"handed": 0, "prompts_drawn": 1}, saved + assert not hasattr(first, "load_state_dict") + assert [group.row["prompt"] for group in first._groups.values()] == [0] + + # This is what a caller can do today with prompts_drawn: skip the in-flight row. + restarted = StreamingDriver(rows[1:], PendingRollout(), batch_size=2, num_generations=2) + with restarted._lock: + restarted._admit() + restarted_rows = [group.row["prompt"] for group in restarted._groups.values()] + assert restarted_rows == [1], restarted_rows + first.close() + restarted.close() + return {"saved": saved, "skipped_prompt": 0, "restart_rows": restarted_rows} + + +def probe_ready_batch_is_unrecoverable() -> dict[str, Any]: + rollout = PendingRollout() + driver = StreamingDriver([{"prompt": 0}], rollout, batch_size=2, num_generations=2) + with driver._lock: + driver._admit() + group = next(iter(driver._groups.values())) + for episode in group.members: + rollout.finish(driver, episode) + assert driver._ready_rows == 2 + + rows, _ = driver._next_batch() + assert len(rows) == 2 + saved = driver.state_dict() + assert saved == {"handed": 1, "prompts_drawn": 1}, saved + assert set(saved) == {"handed", "prompts_drawn"} + assert not driver._ready and not driver._groups + assert not hasattr(driver, "load_state_dict") + driver.close() + return {"batch_rows": len(rows), "saved": saved, "ready_after_lease": 0} + + +def probe_live_rollout_cannot_reattach() -> dict[str, Any]: + rollout = MultiTurnRollout(response_callback=lambda *args: None) + view = {"turns": 1, "user_data": {"episode_id": "ep-gate0"}} + try: + rollout._step(view, "ep-gate0") + except EpisodeError as exc: + message = str(exc) + assert "not held by this rollout" in message + else: + raise AssertionError("a restarted rollout unexpectedly reattached a live view") + + assert not hasattr(TurnLedger, "state_dict") + assert not hasattr(TurnLedger, "load_state_dict") + return {"error": message, "ledger_checkpoint_api": False} + + +def probe_localenv_session_cannot_reattach() -> dict[str, Any]: + with tempfile.TemporaryDirectory(prefix="gate0-env-") as root: + first = LocalEnv(root=root) + first.reset("ep-gate0") + first.step("ep-gate0", "write_file", {"path": "state.txt", "content": "turn-boundary"}) + second = LocalEnv(root=root) + try: + second.step("ep-gate0", "read_file", {"path": "state.txt"}) + except SessionNotFound as exc: + message = str(exc) + else: + raise AssertionError("a new LocalEnv instance unexpectedly reattached the old session") + assert not hasattr(first, "checkpoint_episode") + assert not hasattr(first, "restore_episode") + first.close("ep-gate0") + second.shutdown() + return {"error": message, "capability_api": False} + + +def probe_tool_effect_has_no_journal() -> dict[str, Any]: + signature = inspect.signature(Env.step) + assert "effect_key" not in signature.parameters + CountingEnv.effects = 0 + first = CountingEnv() + first.reset("effect-ep") + first.step("effect-ep", "charge", {"amount": 1}) + first.close("effect-ep") + + # A replacement process repeats the same state key and the same call. + second = CountingEnv() + second.reset("effect-ep") + second.step("effect-ep", "charge", {"amount": 1}) + second.close("effect-ep") + assert CountingEnv.effects == 2 + return {"effects": CountingEnv.effects, "effect_key_in_api": False} + + +def probe_workspace_snapshot_is_feasible() -> dict[str, Any]: + with tempfile.TemporaryDirectory(prefix="gate0-workspace-") as root: + source = LocalEnv(root=str(Path(root) / "source")) + source.reset("source-ep") + source.step("source-ep", "write_file", {"path": "state.txt", "content": "turn-boundary"}) + workspace = Path(source.workspace("source-ep")) + + staging = Path(root) / "snapshot.staging" + snapshot = Path(root) / "snapshot" + shutil.copytree(workspace, staging) + staging.replace(snapshot) + source.close("source-ep") + assert snapshot.joinpath("state.txt").read_text(encoding="utf-8") == "turn-boundary" + + restored = LocalEnv(root=str(Path(root) / "restored")) + restored.reset("restored-ep") + target = Path(restored.workspace("restored-ep")) + shutil.copytree(snapshot, target, dirs_exist_ok=True) + result = restored.step("restored-ep", "read_file", {"path": "state.txt"}) + assert result.observation == "turn-boundary" + restored.close("restored-ep") + return {"atomic_snapshot": True, "new_session_rehydrated": True} + + +PROBES = ( + ("inflight_prompt_is_lost", probe_inflight_prompt_is_lost), + ("ready_batch_is_unrecoverable", probe_ready_batch_is_unrecoverable), + ("live_rollout_cannot_reattach", probe_live_rollout_cannot_reattach), + ("localenv_session_cannot_reattach", probe_localenv_session_cannot_reattach), + ("tool_effect_has_no_journal", probe_tool_effect_has_no_journal), + ("workspace_snapshot_is_feasible", probe_workspace_snapshot_is_feasible), +) + + +def main() -> int: + results = [] + failed = False + for name, probe in PROBES: + try: + detail = probe() + results.append({"name": name, "ok": True, "detail": detail}) + print(f"PASS {name}: {json.dumps(detail, ensure_ascii=False, sort_keys=True)}") + except Exception as exc: + failed = True + results.append( + { + "name": name, + "ok": False, + "error": f"{type(exc).__name__}: {exc}", + "traceback": traceback.format_exc(), + } + ) + print(f"FAIL {name}: {type(exc).__name__}: {exc}", file=sys.stderr) + report = {"gate": "RolloutResume-Gate0", "ok": not failed, "results": results} + print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)) + return 1 if failed else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py new file mode 100644 index 000000000..416a8c781 --- /dev/null +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -0,0 +1,282 @@ +# Copyright (c) ModelScope Contributors. All rights reserved. +"""Durable bookkeeping for pausing and resuming an in-flight RL rollout. + +The checkpoint has two layers. :class:`DurableJournal` records ordered state +transitions and repairs only an interrupted final line. :class:`ResumeStore` +stores Python state blobs with a content hash and exposes one stable checkpoint +per episode state key. The journal is intentionally independent of Ray and +torch; callers provide already-plain state or trusted process-local objects. +""" + +from __future__ import annotations +import hashlib +import os +import pickle +import threading +from collections.abc import Iterable +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import Any + +import json + +_ZERO_DIGEST = "0" * 64 +_OBJECT_MAGIC = b"RRS1" + + +class ResumeError(RuntimeError): + """Base error for an unsafe or inconsistent rollout resume.""" + + +class UnsafeResume(ResumeError): + """The current state cannot be resumed without repeating an external effect.""" + + +class JournalCorrupt(ResumeError): + """A journal is damaged somewhere other than its final incomplete line.""" + + +class JournalEvent(str, Enum): + PROMPT_ASSIGNED = "PROMPT_ASSIGNED" + TURN_COMMITTED = "TURN_COMMITTED" + TOOL_INTENT = "TOOL_INTENT" + TOOL_RESULT = "TOOL_RESULT" + SCORE_RESULT = "SCORE_RESULT" + GROUP_READY = "GROUP_READY" + GROUP_DROPPED = "GROUP_DROPPED" + BATCH_LEASED = "BATCH_LEASED" + MODEL_CHECKPOINT_COMMITTED = "MODEL_CHECKPOINT_COMMITTED" + + +@dataclass(frozen=True) +class JournalRecord: + seq: int + event: JournalEvent + state_key: str + payload: dict[str, Any] + prev: str + digest: str + + +def _canonical_json(value: Any) -> bytes: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def _record_digest(record: dict[str, Any]) -> str: + return hashlib.sha256(_canonical_json(record)).hexdigest() + + +def _fsync_directory(path: Path) -> None: + """Persist a rename on filesystems that expose directory fsync.""" + if os.name == "nt": + return + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def atomic_write_bytes(path: Path, data: bytes) -> None: + """Replace ``path`` with complete bytes; the previous file survives failures.""" + path.parent.mkdir(parents=True, exist_ok=True) + pending = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") + try: + with open(pending, "wb") as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(pending, path) + _fsync_directory(path.parent) + finally: + pending.unlink(missing_ok=True) + + +def _object_name(key: str) -> str: + return hashlib.sha256(key.encode("utf-8")).hexdigest() + ".resume" + + +class DurableJournal: + """Append-only, hash-chained JSONL journal with final-line repair. + + A torn final line is the expected result of a process dying after write but + before fsync. It is removed. Damage followed by another complete record is + never guessed at: that would silently resume from a fabricated history. + """ + + def __init__(self, path: str | os.PathLike[str]): + self.path = Path(path) + self.path.parent.mkdir(parents=True, exist_ok=True) + self._lock = threading.Lock() + self._next_seq = 0 + self._last_digest = _ZERO_DIGEST + self._records: list[JournalRecord] = [] + self._repair_and_scan() + + def _repair_and_scan(self) -> None: + if not self.path.exists(): + return + data = self.path.read_bytes() + offset = 0 + valid_end = 0 + records = [] + prev = _ZERO_DIGEST + while offset < len(data): + newline = data.find(b"\n", offset) + if newline < 0: + break + raw = data[offset:newline] + try: + payload = json.loads(raw.decode("utf-8")) + seq = int(payload["seq"]) + body = { + "seq": seq, + "event": payload["event"], + "state_key": payload["state_key"], + "payload": payload["payload"], + "prev": payload["prev"], + } + digest = str(payload["digest"]) + if seq != len(records) or body["prev"] != prev or _record_digest(body) != digest: + raise ValueError("journal hash chain mismatch") + event = JournalEvent(body["event"]) + records.append(JournalRecord(seq, event, body["state_key"], body["payload"], prev, digest)) + except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: + if data[newline + 1 :].strip(): + raise JournalCorrupt(f"{self.path}: corrupt record at line {len(records) + 1}: {exc}") from exc + break + prev = records[-1].digest + offset = newline + 1 + valid_end = offset + if valid_end != len(data): + with open(self.path, "r+b") as stream: + stream.truncate(valid_end) + stream.flush() + os.fsync(stream.fileno()) + if records: + self._next_seq = records[-1].seq + 1 + self._last_digest = records[-1].digest + self._records = records + + def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | None = None) -> JournalRecord: + with self._lock: + body = { + "seq": self._next_seq, + "event": event.value, + "state_key": state_key, + "payload": payload or {}, + "prev": self._last_digest, + } + digest = _record_digest(body) + line = json.dumps({**body, "digest": digest}, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" + with open(self.path, "ab") as stream: + stream.write(line) + stream.flush() + os.fsync(stream.fileno()) + record = JournalRecord(self._next_seq, event, state_key, payload or {}, self._last_digest, digest) + self._records.append(record) + self._next_seq += 1 + self._last_digest = digest + return record + + def records(self, *, state_key: str | None = None) -> Iterable[JournalRecord]: + with self._lock: + return tuple(record for record in self._records if state_key is None or record.state_key == state_key) + + def last(self, state_key: str, *, events: Iterable[JournalEvent] | None = None) -> JournalRecord | None: + allowed = set(events) if events is not None else None + found = None + for record in self.records(state_key=state_key): + if allowed is None or record.event in allowed: + found = record + return found + + +class ResumeStore: + """Checkpoint objects and a transition journal for one training run.""" + + def __init__(self, root: str | os.PathLike[str], run_id: str): + if not run_id: + raise ValueError("run_id must not be empty") + self.root = Path(root) + self.run_id = run_id + self.root.mkdir(parents=True, exist_ok=True) + self.journal = DurableJournal(self.root / "rollout.jsonl") + + def save_object(self, scope: str, key: str, value: Any) -> str: + payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) + digest = hashlib.sha256(payload).digest() + path = self.root / "objects" / scope / _object_name(key) + atomic_write_bytes(path, _OBJECT_MAGIC + digest + payload) + return str(path) + + def has_object(self, scope: str, key: str) -> bool: + return (self.root / "objects" / scope / _object_name(key)).is_file() + + def load_object(self, scope: str, key: str) -> Any: + path = self.root / "objects" / scope / _object_name(key) + try: + data = path.read_bytes() + except FileNotFoundError as exc: + raise ResumeError(f"resume object missing: {scope}/{key}") from exc + if not data.startswith(_OBJECT_MAGIC) or len(data) < len(_OBJECT_MAGIC) + 32: + raise ResumeError(f"resume object has an invalid header: {path}") + digest = data[len(_OBJECT_MAGIC) : len(_OBJECT_MAGIC) + 32] + payload = data[len(_OBJECT_MAGIC) + 32 :] + if hashlib.sha256(payload).digest() != digest: + raise ResumeError(f"resume object checksum mismatch: {path}") + try: + return pickle.loads(payload) + except Exception as exc: + raise ResumeError(f"resume object cannot be decoded: {path}") from exc + + def delete_object(self, scope: str, key: str) -> None: + path = self.root / "objects" / scope / _object_name(key) + path.unlink(missing_ok=True) + + def checkpoint_episode(self, state_key: str, state: Any) -> None: + self.save_object("episodes", state_key, state) + self.journal.append(JournalEvent.TURN_COMMITTED, state_key, {"object": _object_name(state_key)}) + + def load_episode(self, state_key: str) -> Any: + return self.load_object("episodes", state_key) + + def begin_effect(self, effect_key: str, payload: dict[str, Any]) -> dict[str, Any] | None: + last = self.journal.last(effect_key, events=(JournalEvent.TOOL_INTENT, JournalEvent.TOOL_RESULT)) + if last is not None and last.event == JournalEvent.TOOL_RESULT: + return dict(last.payload) + if last is not None and last.event == JournalEvent.TOOL_INTENT: + raise UnsafeResume(f"effect {effect_key} has an intent without a result") + self.journal.append(JournalEvent.TOOL_INTENT, effect_key, payload) + return None + + def finish_effect(self, effect_key: str, payload: dict[str, Any]) -> None: + self.journal.append(JournalEvent.TOOL_RESULT, effect_key, payload) + + def pending_effects(self, state_key: str) -> tuple[str, ...]: + """Effect keys whose last record is an intent rather than a result.""" + prefix = state_key + "/effect/" + pending: dict[str, bool] = {} + for record in self.journal.records(): + if not record.state_key.startswith(prefix): + continue + if record.event == JournalEvent.TOOL_INTENT: + pending[record.state_key] = True + elif record.event == JournalEvent.TOOL_RESULT: + pending[record.state_key] = False + return tuple(key for key, is_pending in pending.items() if is_pending) + + def completed_effects(self, state_key: str) -> tuple[str, ...]: + """Effect keys with a matching result record.""" + prefix = state_key + "/effect/" + completed: set[str] = set() + for record in self.journal.records(): + if record.state_key.startswith(prefix) and record.event == JournalEvent.TOOL_RESULT: + completed.add(record.state_key) + return tuple(sorted(completed)) + + def assert_no_pending_effects(self, state_key: str) -> None: + pending = self.pending_effects(state_key) + if pending: + raise UnsafeResume(f"episode {state_key} has pending tool effects: {pending!r}") diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index f9a8e6db2..99ecd1037 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -37,6 +37,7 @@ from twinkle import remote_class, remote_function from twinkle.data_format import user_data_get from twinkle.utils import get_logger +from twinkle_agentic.async_rl.rollout_resume import JournalEvent, ResumeStore, UnsafeResume from twinkle_agentic.rollout.multi_turn import EpisodeError, RolloutStatus logger = get_logger() @@ -127,6 +128,10 @@ class _Group: """One prompt row's episodes: the current attempt's members and the baseline episodes it waits for.""" key: str row: Any + #: Fixed for the group's whole lifetime. Recovery and replacement members must use this + #: behavior policy, never whichever version happens to be current after a restart. + version: int = 0 + adapter_path: Optional[str] = None attempt: int = 0 #: The current attempt's member trajectories, aligned with ``members`` (a lost one is redone from here). source: List[Any] = field(default_factory=list) @@ -257,7 +262,9 @@ def __init__(self, on_group: Optional[Callable[[Any, List[RolloutStatus], int], List[Any]]] = None, max_group_regenerations: int = 0, cluster_adapter: Any = None, - max_no_slot_wait: float = 1800.0): + max_no_slot_wait: float = 1800.0, + resume_store: Optional[ResumeStore] = None, + run_id: Optional[str] = None): if num_generations < 1 or batch_size < 1 or batch_size % num_generations: raise ValueError(f'batch_size ({batch_size}) must be a positive multiple of num_generations ' f'({num_generations}): a batch holds whole groups.') @@ -291,6 +298,10 @@ def __init__(self, self.on_group = on_group self.max_group_regenerations = max_group_regenerations self.cluster_adapter = cluster_adapter + self.resume_store = resume_store + self.run_id = run_id or (resume_store.run_id if resume_store is not None else uuid.uuid4().hex) + if resume_store is not None and run_id is not None and run_id != resume_store.run_id: + raise ValueError(f'run_id {run_id!r} does not match resume store run {resume_store.run_id!r}') #: Wall-clock ceiling on how long one member may keep retrying a full session pool before its #: group is loudly dropped. Scheduling delay is not quality regeneration: it never spends #: max_group_regenerations or increments group_attempt, but it must still be bounded. @@ -317,7 +328,8 @@ def __init__(self, self._consecutive_failures = 0 self._counters: Dict[str, int] = { 'admitted': 0, 'dropped_stale': 0, 'dropped_sample': 0, 'dropped_group': 0, 'episode_errors': 0, - 'stopped': 0, 'regenerated': 0, 'no_slot': 0, 'no_slot_dropped': 0 + 'stopped': 0, 'regenerated': 0, 'no_slot': 0, 'no_slot_dropped': 0, + 'resumed_groups': 0, 'resumed_members': 0, } self._adjusting = False #: monotonic stamps: when the running ``adjust`` started, and when its being stuck was last reported. @@ -333,6 +345,10 @@ def __init__(self, self._returned_at: Optional[float] = None self._idle_ratio = 0.0 self._iter_started = False + #: The one batch whose model update may or may not have committed. It survives a process + #: restart and is handed out again until ``commit_batch`` records the model checkpoint. + self._lease: Optional[Dict[str, Any]] = None + self._lease_returned = False # ------------------------------------------------------------------ iteration @@ -359,6 +375,18 @@ def _next_batch(self) -> Optional[tuple]: a dict in-process -- never opened here), and the light per-batch facts (row lengths, the row-aligned score column, version spans) built in the same locked section. """ + if self._lease is not None: + if self.resume_store is None: + # Preserve the pre-resume single-process iteration contract: without a store the + # previous lease is only useful to a state_dict taken while training is running. + self._lease = None + self._lease_returned = False + elif not self._lease_returned: + self._lease_returned = True + return self._lease['rows'], self._lease['facts'] + else: + raise UnsafeResume(f'batch lease {self._lease["lease_id"]!r} is still open; ' + 'call commit_batch() after the model checkpoint is durable') self._start() started = time.monotonic() waited = 0.0 @@ -427,7 +455,9 @@ def _next_batch(self) -> Optional[tuple]: scores: List[Dict[str, Any]] = [] version_spans: List[int] = [] while len(trajs) < self.batch_size and self._ready: - for episode in self._ready.popleft(): + ready_group = self._ready.popleft() + self._live -= sum(1 for episode in ready_group if episode.deliver) + for episode in ready_group: episode.sample.version_span = self._version - episode.sample.policy_version score = self._score_update(episode) lengths = (episode.sample.extra or {}).get('row_token_lengths') @@ -453,11 +483,27 @@ def _next_batch(self) -> Optional[tuple]: scores.append(score) version_spans.append(row_sample.version_span) self._ready_rows -= len(trajs) + batch_index = self._handed + facts = _sample_facts(samples, scores, version_spans) + lease_id = f'{self.run_id}/batch/{batch_index}' + self._lease = { + 'lease_id': lease_id, + 'batch': batch_index, + 'policy_versions': list(facts['policy_versions']), + 'rows': trajs, + 'facts': facts, + } + self._lease_returned = True + if self.resume_store is not None: + self.resume_store.save_object('leases', lease_id, self._lease) + self.resume_store.journal.append( + JournalEvent.BATCH_LEASED, lease_id, + {'batch': batch_index, 'rows': len(trajs), 'object': lease_id}) self._handed += 1 self._lock.notify_all() self._returned_at = time.monotonic() self._wait_time = self._returned_at - started - return trajs, _sample_facts(samples, scores, version_spans) + return trajs, facts def _score_update(self, episode: _Episode) -> Dict[str, Any]: """One row's light score entry, off the private bookkeeping -- never written onto the row. @@ -493,14 +539,11 @@ def _score_update(self, episode: _Episode) -> Dict[str, Any]: return score def _drop_stale(self) -> None: - """Retire over-age members of ready groups, per member (under the lock). - - Without a checkpoint manager the policy never changes, so nothing is stale: the version then - only paces admission. A member more than ``max_staleness`` versions behind is lost back into its - group's ``missing`` and the group returns to ``_groups`` for ``_settle`` to regenerate exactly - those slots -- the fresh members are kept, not buried with the stale ones. ``_accept`` asserts the - group's version span stays within ``max_staleness``, the same-window backstop the old whole-group - ``min(version)`` drop used to provide. + """Retire whole ready groups whose pinned behavior policy is too old (under the lock). + + Regenerating only stale members under the current policy would mix behavior distributions + inside one GRPO baseline. A ready group is atomic: when any member is outside the + staleness window, the whole group is dropped. """ if self.checkpoint_manager is None: return @@ -512,16 +555,27 @@ def _drop_stale(self) -> None: continue group = members[0].group self._ready_rows -= sum(len(episode.deliver) for episode in members) - self._groups[group.key] = group - for episode in stale: - episode.lost = True - episode.counted_inflight = False - group.missing += 1 - self._live -= 1 - self._counters['dropped_stale'] += 1 - self._settle(group) + self._retire_stale_group(group) self._ready = kept + def _retire_stale_group(self, group: _Group) -> None: + """Drop one group atomically after its pinned policy leaves the staleness window.""" + self._groups.pop(group.key, None) + self._counters['dropped_stale'] += len(group.members) + self._counters['dropped_group'] += 1 + if self.resume_store is not None: + state_key = f'{self.run_id}/group/{group.key}' + self.resume_store.journal.append( + JournalEvent.GROUP_DROPPED, state_key, + {'reason': 'stale', 'version': group.version, 'current_version': self._version}) + for episode in group.members + group.baselines: + if episode.lost: + continue + episode.lost = True + episode.counted_inflight = False + if episode.role != _BASELINE: + self._live -= 1 + @remote_function(execute='first', collect='first', lazy_collect=False) def stats(self) -> Dict[str, Any]: """Counters of the run so far (small; for logging).""" @@ -529,17 +583,256 @@ def stats(self) -> Dict[str, Any]: return dict(self._counters, version=self._version, handed=self._handed, inflight=self._inflight, live=self._live, ready_rows=self._ready_rows, train_idle_ratio=self._idle_ratio) + def _loader_state(self) -> Any: + getter = getattr(self.dataloader, 'state_dict', None) or getattr(self.dataloader, 'get_state', None) + return copy.deepcopy(getter()) if callable(getter) else None + + def _episode_state(self, episode: _Episode) -> Dict[str, Any]: + now = time.monotonic() + return { + 'episode_id': episode.episode_id, + 'group_key': episode.group.key, + 'role': episode.role, + 'version': episode.version, + 'traj': episode.traj, + 'sample': episode.sample, + 'done': episode.done, + 'finished': episode.finished, + 'lost': episode.lost, + 'orm': _dump_pending(episode.orm), + 'orm_pending': episode.orm_pending, + 'prm': _dump_pending(episode.prm), + 'prm_turns': list(episode.prm_turns), + 'prm_pending': episode.prm_pending, + 'held': episode.held, + 'deliver': list(episode.deliver), + 'submit_traj': episode.submit_traj, + 'no_slot_retry_in': (None if episode.no_slot_retry_at is None + else max(0.0, episode.no_slot_retry_at - now)), + 'no_slot_deadline_in': (None if episode.no_slot_deadline is None + else max(0.0, episode.no_slot_deadline - now)), + 'no_slot_attempts': episode.no_slot_attempts, + 'counted_inflight': episode.counted_inflight, + } + + def _group_state(self, group: _Group) -> Dict[str, Any]: + return { + 'key': group.key, + 'row': group.row, + 'version': group.version, + 'adapter_path': group.adapter_path, + 'attempt': group.attempt, + 'source': list(group.source), + 'members': [self._episode_state(episode) for episode in group.members], + 'baselines': [self._episode_state(episode) for episode in group.baselines], + 'missing': group.missing, + } + + def _snapshot(self) -> Dict[str, Any]: + return { + 'format': 'twinkle.streaming-driver.v1', + 'run_id': self.run_id, + 'handed': self._handed, + 'prompts_drawn': self._prompt_seq, + 'version': self._version, + 'base_version': self._base_version, + 'exhausted': self._exhausted, + 'counters': dict(self._counters), + 'loader_state': self._loader_state(), + 'groups': [self._group_state(group) for group in self._groups.values()], + 'ready': [[self._episode_state(episode) for episode in members] for members in self._ready], + 'ready_groups': [self._group_state(members[0].group) for members in self._ready if members], + 'lease': self._lease, + } + @remote_function(execute='first', collect='first', lazy_collect=False) def state_dict(self) -> Dict[str, Any]: - """What a resumed run restores: the batches handed out and the prompt rows drawn. + """Snapshot prompts, complete groups, ready groups and the open batch lease. - TODO: resuming re-reads the dataloader from its own saved position, which is ahead of the rows - that were drawn but not yet trained (in flight or buffered); up to one buffer of prompts, - ``(max_staleness + 1) * sync_interval * batch_size`` rows, is skipped. Keeping them would mean - saving the in-flight episodes, which live in the rollout and env sessions. + Live episodes are paired with their last durable rollout turn checkpoint. A checkpoint taken + while a generation is running therefore resumes from the preceding turn boundary rather than + pretending the in-memory partial response is durable. """ with self._lock: - return {'handed': self._handed, 'prompts_drawn': self._prompt_seq} + state = self._snapshot() + if self.resume_store is not None: + self.resume_store.save_object('driver', self.run_id, state) + return state + + def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: + episode = _Episode( + episode_id=str(state['episode_id']), group=group, role=str(state.get('role') or ''), + version=int(state.get('version') or 0)) + episode.traj = state.get('traj') + episode.sample = state.get('sample') + episode.done = bool(state.get('done')) + episode.finished = bool(state.get('finished')) + episode.lost = bool(state.get('lost')) + episode.orm = _load_pending(state.get('orm')) + episode.orm_pending = int(state.get('orm_pending') or 0) + episode.prm = _load_pending(state.get('prm')) + episode.prm_turns = list(state.get('prm_turns') or ()) + episode.prm_pending = int(state.get('prm_pending') or 0) + episode.held = state.get('held') + episode.deliver = list(state.get('deliver') or ()) + episode.submit_traj = state.get('submit_traj') + now = time.monotonic() + if state.get('no_slot_retry_in') is not None: + episode.no_slot_retry_at = now + float(state['no_slot_retry_in']) + if state.get('no_slot_deadline_in') is not None: + episode.no_slot_deadline = now + float(state['no_slot_deadline_in']) + episode.no_slot_attempts = int(state.get('no_slot_attempts') or 0) + episode.counted_inflight = bool(state.get('counted_inflight')) + return episode + + def _restore_group(self, state: Dict[str, Any]) -> _Group: + members = state.get('members') or () + member_version = next( + (int(item.get('version') or 0) for item in members if item.get('version') is not None), 0) + version = int(state.get('version') if state.get('version') is not None else member_version) + adapter_path = state.get('adapter_path') + if adapter_path is None and self.checkpoint_manager is not None: + lookup = getattr(self.checkpoint_manager, 'adapter_path', None) + if callable(lookup): + adapter_path = lookup(version) + if adapter_path is None: + raise UnsafeResume(f'policy version {version} has no resolvable adapter path') + group = _Group( + key=str(state['key']), row=state.get('row'), version=version, adapter_path=adapter_path, + attempt=int(state.get('attempt') or 0), + source=list(state.get('source') or ()), missing=int(state.get('missing') or 0)) + group.members = [self._restore_episode(item, group) for item in state.get('members') or ()] + group.baselines = [self._restore_episode(item, group) for item in state.get('baselines') or ()] + return group + + def _resume_scores(self, episode: _Episode) -> None: + """Reissue only score calls whose result was missing from the snapshot.""" + for index, value in enumerate(episode.orm or ()): + if value is not _PENDING: + continue + future = self.orms[index]([episode.traj]) + future.add_done_callback( + lambda f, episode=episode, index=index: self._events.put(('orm', episode, index, f))) + for scorer, column in enumerate(episode.prm or ()): + for segment, value in enumerate(column): + if value is not _PENDING: + continue + future = self.prms[scorer]([episode.traj]) + future.add_done_callback( + lambda f, episode=episode, key=(segment, scorer): self._events.put(('prm', episode, key, f))) + + def _resume_live_episode(self, episode: _Episode) -> None: + if episode.finished or episode.lost or episode.done: + if not episode.finished and not episode.lost: + self._resume_scores(episode) + return + self._counters['resumed_members'] += 1 + state_key = str((episode.submit_traj or {}).get('state_key') or '') + if self.resume_store is not None and state_key and self.resume_store.has_object('episodes', state_key): + self.rollout.restore_episode_from_store(state_key) + route = dict(episode.traj or episode.submit_traj or {}) + route.setdefault('turns', 0) + self._step(episode, route) + else: + # No turn boundary committed yet: opening the episode again repeats no external tool call. + self._step(episode, episode.submit_traj) + + @remote_function(execute='first', collect='first', lazy_collect=False) + def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: + """Rebuild a fresh driver from a snapshot, or from the store's latest snapshot.""" + if state is None: + if self.resume_store is None: + raise UnsafeResume('load_state_dict() without state needs a resume store') + state = self.resume_store.load_object('driver', self.run_id) + if state.get('format') != 'twinkle.streaming-driver.v1': + raise UnsafeResume('unsupported StreamingDriver checkpoint format') + if str(state.get('run_id')) != self.run_id: + raise UnsafeResume(f'driver snapshot belongs to run {state.get("run_id")!r}, not {self.run_id!r}') + observed_version = int(self.checkpoint_manager.version()) if self.checkpoint_manager is not None else 0 + with self._lock: + if self._thread is not None or self._iter_started: + raise UnsafeResume('load_state_dict must run before the driver starts') + self._groups = {} + for item in state.get('groups') or (): + group = self._restore_group(item) + self._groups[group.key] = group + ready_groups = {group.key: group for group in + (self._restore_group(item) for item in state.get('ready_groups') or ())} + self._ready = deque() + for members in state.get('ready') or (): + restored = [] + for item in members: + key = str(item.get('group_key')) + group = ready_groups.get(key) + if group is None: + raise UnsafeResume(f'ready episode references unknown group {key!r}') + restored.append(self._restore_episode(item, group)) + self._ready.append(restored) + self._ready_rows = sum(len(episode.deliver) for members in self._ready for episode in members) + self._handed = int(state.get('handed') or 0) + self._prompt_seq = int(state.get('prompts_drawn') or 0) + self._version = max(int(state.get('version') or 0), observed_version) + self._base_version = int(state.get('base_version') or 0) + self._exhausted = bool(state.get('exhausted')) + self._counters = dict(state.get('counters') or self._counters) + lease = state.get('lease') + if lease is not None and self.resume_store is not None: + last = self.resume_store.journal.last( + str(lease['lease_id']), events=(JournalEvent.BATCH_LEASED, + JournalEvent.MODEL_CHECKPOINT_COMMITTED)) + if last is not None and last.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED: + lease = None + self._lease = lease + self._lease_returned = False + self._drop_stale() + for group in list(self._groups.values()): + if self.checkpoint_manager is not None and self._version - group.version > self.max_staleness: + self._retire_stale_group(group) + self._live = sum(not episode.lost for group in self._groups.values() + for episode in group.members) + self._live += sum(not episode.lost for members in self._ready for episode in members) + self._inflight = sum(episode.counted_inflight for group in self._groups.values() + for episode in group.members + group.baselines) + self._counters['resumed_groups'] += len(self._groups) + live = [episode for group in self._groups.values() + for episode in group.members + group.baselines] + loader_state = state.get('loader_state') + loader = getattr(self.dataloader, 'load_state_dict', None) or getattr(self.dataloader, 'set_state', None) + if loader_state is not None: + if not callable(loader): + raise UnsafeResume('snapshot has DataLoader state but the dataloader cannot load it') + loader(loader_state) + for episode in live: + self._resume_live_episode(episode) + with self._lock: + for group in list(self._groups.values()): + self._settle(group) + self._lock.notify_all() + + @remote_function(execute='first', collect='first', lazy_collect=False) + def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, Any]] = None) -> Optional[str]: + """Mark the open lease trained after its model checkpoint is durable.""" + with self._lock: + lease = self._lease + if lease is None: + return None + if self.resume_store is not None and not checkpoint_ref: + raise UnsafeResume('commit_batch() needs the durable model checkpoint reference') + lease_id = str(lease['lease_id']) + if self.resume_store is not None: + self.resume_store.journal.append( + JournalEvent.MODEL_CHECKPOINT_COMMITTED, lease_id, + { + 'checkpoint': str(checkpoint_ref), + 'batch': lease['batch'], + 'policy_versions': list(lease.get('policy_versions') or ()), + 'manifest': dict(manifest or {}), + }) + self.resume_store.delete_object('leases', lease_id) + self._lease = None + self._lease_returned = False + self._lock.notify_all() + return lease_id @remote_function(execute='first', collect='first', lazy_collect=False) def close(self) -> None: @@ -677,8 +970,22 @@ def _admit(self) -> None: return key = str(self._prompt_seq) self._prompt_seq += 1 - group = _Group(key=key, row=row) + version = self._version + adapter_path = None + if self.checkpoint_manager is not None: + lookup = getattr(self.checkpoint_manager, 'adapter_path', None) + if callable(lookup): + adapter_path = lookup(version) + if adapter_path is None: + raise UnsafeResume( + f'checkpoint manager has no adapter path for admitted policy version {version}') + group = _Group(key=key, row=row, version=version, adapter_path=adapter_path) self._groups[key] = group + if self.resume_store is not None: + prompt_key = f'{self.run_id}/prompt/{key}' + self.resume_store.save_object('prompts', prompt_key, row) + self.resume_store.journal.append( + JournalEvent.PROMPT_ASSIGNED, prompt_key, {'group_key': key, 'object': prompt_key}) self._start_attempt(group, [copy.deepcopy(row) for _ in range(self.num_generations)]) def _next_row(self) -> Any: @@ -709,18 +1016,23 @@ def _start_attempt(self, group: _Group, trajectories: List[Any]) -> None: self._live += len(members) self._counters['admitted'] += len(members) group.baselines = [] - for traj in members: - group.members.append(self._submit(group, traj, '')) - for traj in baselines: - group.baselines.append(self._submit(group, traj, _BASELINE)) - - def _submit(self, group: _Group, traj: Any, role: str) -> _Episode: - episode = _Episode(episode_id=uuid.uuid4().hex, group=group, role=role, version=self._version) + for slot, traj in enumerate(members): + group.members.append(self._submit(group, traj, '', slot)) + for slot, traj in enumerate(baselines): + group.baselines.append(self._submit(group, traj, _BASELINE, slot)) + + def _submit(self, group: _Group, traj: Any, role: str, slot: int) -> _Episode: + kind = 'baseline' if role == _BASELINE else 'member' + episode_id = f'{self.run_id}:g{group.key}:a{group.attempt}:{kind}:{slot}' + episode = _Episode(episode_id=episode_id, group=group, role=role, version=group.version) # The identity travels on top of the trajectory: episode / group / role / the admission # version. The rollout reads the episode id to route its steps back to this episode. traj = dict(traj) traj.update(episode_id=episode.episode_id, group_key=group.key, role=role, - policy_version=episode.version, group_attempt=group.attempt) + policy_version=group.version, group_attempt=group.attempt, + state_key=f'{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}') + if group.adapter_path is not None: + traj['adapter_path'] = group.adapter_path episode.submit_traj = traj self._inflight += 1 episode.counted_inflight = True @@ -899,7 +1211,7 @@ def _retry_no_slot_due(self) -> None: self._drop_group(group) break episode.no_slot_retry_at = None - fresh = self._submit(group, copy.deepcopy(episode.submit_traj), episode.role) + fresh = self._submit(group, copy.deepcopy(episode.submit_traj), episode.role, index) fresh.no_slot_attempts = episode.no_slot_attempts fresh.no_slot_deadline = episode.no_slot_deadline slots[index] = fresh @@ -940,6 +1252,9 @@ def _settle(self, group: _Group) -> None: return if any(not (e.finished or e.lost) for e in group.members + group.baselines): return + if self.checkpoint_manager is not None and self._version - group.version > self.max_staleness: + self._retire_stale_group(group) + return if group.missing: if group.attempt >= self.max_group_regenerations: self._drop_group(group) @@ -952,7 +1267,7 @@ def _settle(self, group: _Group) -> None: group.missing = 0 for index, episode in enumerate(group.members): if episode.lost: - group.members[index] = self._submit(group, copy.deepcopy(group.source[index]), '') + group.members[index] = self._submit(group, copy.deepcopy(group.source[index]), '', index) return if group.baselines: rows = [list(e.sample.orm_reward) for e in group.baselines] @@ -985,6 +1300,15 @@ def _accept(self, group: _Group) -> None: del self._groups[group.key] self._ready.append(list(group.members)) self._ready_rows += sum(len(episode.deliver) for episode in group.members) + if self.resume_store is not None: + state_key = f'{self.run_id}/group/{group.key}' + self.resume_store.journal.append(JournalEvent.GROUP_READY, state_key, { + 'group_key': group.key, + 'policy_version': group.version, + 'adapter_path': group.adapter_path, + 'attempt': group.attempt, + 'episodes': [episode.episode_id for episode in group.members], + }) def _drop_group(self, group: _Group) -> None: """Give the group up: its counted rows leave the bound, its unfinished episodes stop (under the lock).""" @@ -1007,3 +1331,25 @@ def _drop_group(self, group: _Group) -> None: #: Placeholder for a score whose Future has not completed yet. _PENDING = object() +_PENDING_KEY = '__twinkle_streaming_pending__' + + +def _dump_pending(value: Any) -> Any: + """Turn process-local score placeholders into values a snapshot can carry.""" + if value is _PENDING: + return {_PENDING_KEY: True} + if isinstance(value, dict): + return {key: _dump_pending(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_dump_pending(item) for item in value] + return copy.deepcopy(value) + + +def _load_pending(value: Any) -> Any: + if isinstance(value, dict) and value.get(_PENDING_KEY) is True: + return _PENDING + if isinstance(value, dict): + return {key: _load_pending(item) for key, item in value.items()} + if isinstance(value, list): + return [_load_pending(item) for item in value] + return copy.deepcopy(value) diff --git a/src/twinkle_agentic/envs/__init__.py b/src/twinkle_agentic/envs/__init__.py index a4a70ce4b..c10cb045a 100644 --- a/src/twinkle_agentic/envs/__init__.py +++ b/src/twinkle_agentic/envs/__init__.py @@ -1,11 +1,12 @@ # Copyright (c) ModelScope Contributors. All rights reserved. from .agentenv import AgentEnv, AgentSandbox -from .base import Env, NoSlot, SessionNotFound, StepResult +from .base import (Env, EnvResumeCapability, NoSlot, SessionNotFound, StepResult, UnsafeCheckpoint, + UnsupportedEnvResume) from .env_tool import EnvTool from .localenv import LocalEnv from .openenv import ClientSession, OpenEnv, OpenEnvClient __all__ = [ 'AgentEnv', 'AgentSandbox', 'ClientSession', 'Env', 'EnvTool', 'LocalEnv', 'NoSlot', 'OpenEnv', 'OpenEnvClient', - 'SessionNotFound', 'StepResult' + 'EnvResumeCapability', 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', 'UnsupportedEnvResume' ] diff --git a/src/twinkle_agentic/envs/base.py b/src/twinkle_agentic/envs/base.py index 6c71211b8..a08c804f3 100644 --- a/src/twinkle_agentic/envs/base.py +++ b/src/twinkle_agentic/envs/base.py @@ -3,6 +3,7 @@ import time from abc import ABC, abstractmethod from dataclasses import dataclass, field +from enum import Enum from typing import Any, Dict, List, Optional, Sequence, Tuple from twinkle import remote_function @@ -136,6 +137,22 @@ class NoSlot: """ +class EnvResumeCapability(str, Enum): + """How an environment can survive a different Twinkle process.""" + + NONE = 'none' + LIVE_ATTACH = 'live_attach' + DURABLE_CHECKPOINT = 'durable_checkpoint' + + +class UnsupportedEnvResume(NotImplementedError): + """The environment has no safe way to resume this episode.""" + + +class UnsafeCheckpoint(RuntimeError): + """The episode is not at a point where its workspace can be captured.""" + + class _Session: __slots__ = ('state', 'reward', 'touched', 'script_inflight') @@ -174,6 +191,10 @@ class Env(ABC): ``_close(state)`` and ``_workspace(state)``; plus :meth:`tools`. """ + #: Environments default to no recovery. A backend opts in explicitly and + #: the rollout refuses to mutate or retry an episode when this is NONE. + resume_capability = EnvResumeCapability.NONE + #: What :meth:`snapshot` shows of the workspace: how many files to name, how #: many bytes of each body, how many bytes of bodies in total, and which #: directories not to walk into. Class attributes rather than constructor @@ -201,6 +222,26 @@ def __init__(self, max_sessions: int = 64, session_wait_timeout: Optional[float] #: many seconds then raise; None = wait forever; 0 = return :class:`NoSlot` immediately. self.session_wait_timeout = session_wait_timeout + def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: + """Capture one episode at a stable boundary for a later process. + + ``state_key`` is the rollout's internal stable identity, never a random + session id. The returned value must be self-contained metadata that + :meth:`restore_episode` accepts after this process exits. + """ + raise UnsupportedEnvResume(f'{type(self).__name__} cannot checkpoint episode {episode_id!r}') + + def restore_episode(self, + episode_id: str, + state_key: str, + state: Dict[str, Any], + trajectory: Optional[Trajectory] = None) -> None: + """Rebind a checkpoint to a newly allocated episode session.""" + raise UnsupportedEnvResume(f'{type(self).__name__} cannot restore episode {episode_id!r}') + + def discard_episode_state(self, state_key: str) -> None: + """Remove durable state once the owning group is committed and trained.""" + # ------------------------------------------------------------------ # Hooks # ------------------------------------------------------------------ diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 2064f692a..46e21b40a 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -21,6 +21,8 @@ Every episode gets its own directory under ``root`` as the working directory of all its calls; closing the episode removes it, and kills whatever it still had running. """ +import hashlib +import json import os import resource import shlex @@ -30,13 +32,16 @@ import sys import tempfile import threading +import time +import uuid +from pathlib import Path from typing import Any, Dict, List, Optional, Tuple from twinkle import remote_class, remote_function from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, StepResult, format_command_output, - truncate_observation) +from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, EnvResumeCapability, StepResult, + UnsafeCheckpoint, format_command_output, truncate_observation) logger = get_logger() @@ -65,6 +70,8 @@ def __init__(self, workspace: str): class LocalEnv(Env): """Run scripts and tool calls on this machine. See the module docstring.""" + resume_capability = EnvResumeCapability.DURABLE_CHECKPOINT + def __init__(self, root: Optional[str] = None, max_sessions: int = 64, @@ -91,6 +98,7 @@ def __init__(self, self._command_timeout = command_timeout self._memory_limit_gb = memory_limit_gb self._envs = dict(envs or {}) + self._resume_root = Path(self._root) / '.twinkle-resume' # ------------------------------------------------------------------ # Session hooks @@ -111,6 +119,119 @@ def _close(self, state: _LocalSession) -> None: def _workspace(self, state: _LocalSession) -> str: return state.workspace + # ------------------------------------------------------------------ + # Durable session state + # ------------------------------------------------------------------ + + @staticmethod + def _state_dir_name(state_key: str) -> str: + # Keep the durable path short enough for Windows' classic MAX_PATH. + return hashlib.sha256(state_key.encode('utf-8')).hexdigest()[:24] + + @staticmethod + def _tree_digest(root: Path) -> Dict[str, Any]: + digest = hashlib.sha256() + files = [] + total = 0 + for path in sorted(root.rglob('*')): + if path.is_symlink(): + raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') + if not path.is_file(): + continue + relative = path.relative_to(root).as_posix() + data = path.read_bytes() + file_digest = hashlib.sha256(data).hexdigest() + digest.update(relative.encode('utf-8')) + digest.update(b'\0') + digest.update(file_digest.encode('ascii')) + files.append({'path': relative, 'size': len(data), 'sha256': file_digest}) + total += len(data) + return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} + + def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: + """Copy one quiescent workspace behind a new atomic generation pointer.""" + session = self._session(episode_id) + state = session.state + if session.script_inflight: + raise UnsafeCheckpoint(f'episode {episode_id!r} has a script in flight') + with state.lock: + if state.closed: + raise UnsafeCheckpoint(f'episode {episode_id!r} is already closed') + if state.procs: + raise UnsafeCheckpoint(f'episode {episode_id!r} has a running process') + + generation = f'{time.time_ns():x}-{uuid.uuid4().hex[:8]}' + key_root = self._resume_root / self._state_dir_name(state_key) + generation_root = key_root / generation + workspace_copy = generation_root / 'workspace' + generation_root.mkdir(parents=True, exist_ok=False) + try: + shutil.copytree(state.workspace, workspace_copy) + tree = self._tree_digest(workspace_copy) + manifest = { + 'format': 'twinkle.localenv.v1', + 'state_key': state_key, + 'generation': generation, + 'workspace': tree, + } + manifest_bytes = json.dumps(manifest, ensure_ascii=False, sort_keys=True, + separators=(',', ':')).encode('utf-8') + manifest_path = generation_root / 'manifest.json' + manifest_path.write_bytes(manifest_bytes) + with open(manifest_path, 'r+b') as stream: + os.fsync(stream.fileno()) + head = { + 'generation': generation, + 'manifest_sha256': hashlib.sha256(manifest_bytes).hexdigest(), + } + head_bytes = json.dumps(head, sort_keys=True).encode('utf-8') + pending = key_root / f'.head.{generation}.tmp' + key_root.mkdir(parents=True, exist_ok=True) + with open(pending, 'wb') as stream: + stream.write(head_bytes) + stream.flush() + os.fsync(stream.fileno()) + os.replace(pending, key_root / 'head.json') + except BaseException: + shutil.rmtree(generation_root, ignore_errors=True) + raise + return {'format': 'twinkle.localenv.v1', 'state_key': state_key, 'generation': generation, + 'manifest_sha256': head['manifest_sha256'], 'files': len(tree['files']), 'bytes': tree['bytes'], + 'reward': session.reward} + + def restore_episode(self, + episode_id: str, + state_key: str, + state: Dict[str, Any], + trajectory=None) -> None: + """Allocate a fresh session and rehydrate the snapshot named by ``state``.""" + if state.get('format') != 'twinkle.localenv.v1' or state.get('state_key') != state_key: + raise UnsafeCheckpoint('LocalEnv restore metadata does not match the episode state key') + generation = str(state.get('generation') or '') + if not generation: + raise UnsafeCheckpoint('LocalEnv restore metadata has no generation') + generation_root = self._resume_root / self._state_dir_name(state_key) / generation + manifest_path = generation_root / 'manifest.json' + manifest_bytes = manifest_path.read_bytes() + if hashlib.sha256(manifest_bytes).hexdigest() != state.get('manifest_sha256'): + raise UnsafeCheckpoint('LocalEnv snapshot manifest checksum mismatch') + manifest = json.loads(manifest_bytes) + source = generation_root / 'workspace' + if self._tree_digest(source)['digest'] != manifest['workspace']['digest']: + raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') + + self.reset(episode_id, trajectory) + try: + self._session(episode_id).reward = float(state.get('reward') or 0.0) + target = Path(self.workspace(episode_id)) + shutil.copytree(source, target, dirs_exist_ok=True) + except BaseException: + self.close(episode_id) + raise + + def discard_episode_state(self, state_key: str) -> None: + shutil.rmtree(self._resume_root / self._state_dir_name(state_key), ignore_errors=True) + def _run_script(self, state: _LocalSession, source: str, interpreter: str = 'python', timeout: Optional[float] = None) -> Tuple[int, str]: timeout = self._command_timeout if timeout is None else timeout diff --git a/src/twinkle_agentic/rollout/ledger.py b/src/twinkle_agentic/rollout/ledger.py index d7333a906..12eebb65f 100644 --- a/src/twinkle_agentic/rollout/ledger.py +++ b/src/twinkle_agentic/rollout/ledger.py @@ -26,6 +26,7 @@ re-encoding to make it fit. """ +import copy import inspect from collections.abc import Sequence from dataclasses import replace @@ -107,6 +108,44 @@ def __init__( self._sampling_masks: Any = None self._turns = 0 + # ---------------------------------------------------------------- durability + + def state_dict(self) -> dict[str, Any]: + """Export the sampled token account without re-encoding any text. + + ``_pif`` contains the exact sampler-returned ids, labels and masks; the + optional ``RolloutState`` carries template-engine state such as engine + ids and tokenizer-side metadata. Values are copied so a caller may + serialize them while the live ledger continues to evolve. + """ + self.audit() + return { + 'format': 'twinkle.turn-ledger.v1', + 'input_feature': copy.deepcopy(self._pif), + 'state': copy.deepcopy(self._state), + 'logprobs': copy.deepcopy(self._logprobs), + 'sampling_masks': copy.deepcopy(self._sampling_masks), + 'turns': self._turns, + } + + def load_state_dict(self, state: dict[str, Any]) -> None: + """Replace the mutable account with a previously exported one.""" + if state.get('format') != 'twinkle.turn-ledger.v1': + raise ValueError('unsupported TurnLedger checkpoint format') + input_feature = state.get('input_feature') + logprobs = state.get('logprobs') + turns = state.get('turns') + if not isinstance(input_feature, dict) or 'input_ids' not in input_feature: + raise ValueError('TurnLedger checkpoint is missing input_feature.input_ids') + if not isinstance(logprobs, list) or not isinstance(turns, int) or turns < 0: + raise ValueError('TurnLedger checkpoint has invalid logprobs or turns') + self._pif = copy.deepcopy(input_feature) + self._state = copy.deepcopy(state.get('state')) + self._logprobs = copy.deepcopy(logprobs) + self._sampling_masks = copy.deepcopy(state.get('sampling_masks')) + self._turns = turns + self.audit() + # ---------------------------------------------------------------- reading @property diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 24e993604..af3e9587d 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -7,6 +7,7 @@ merged, trainable trajectory and releases everything. A caller that drives many episodes (the streaming driver) interleaves their steps; a caller that wants whole episodes uses ``__call__``. """ +import hashlib import json import queue import re @@ -24,7 +25,8 @@ from twinkle.protocol.types.sampler import SampleResponseModel from twinkle.template.base import Template from twinkle.utils import get_logger -from twinkle_agentic.envs.base import NoSlot +from twinkle_agentic.async_rl.rollout_resume import ResumeStore, UnsafeResume +from twinkle_agentic.envs.base import EnvResumeCapability, NoSlot from twinkle_agentic.envs.env_tool import EnvTool from twinkle_agentic.protocol.api_sampler import APIGenerationError from twinkle_agentic.tools.tool_manager import ToolManager @@ -345,6 +347,13 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara #: Under segment_policy='collect': the rows of segments a compaction boundary already #: froze, oldest first; the final segment's row joins them when the episode ends. self.closed_rows: list = [] + #: Stable identity supplied by the driver. It is not a random session id. + self.state_key = str(trajectory.get('state_key') or '') + #: Behavior-policy binding for the whole episode. A resumed group keeps this adapter even + #: after the sampler's mutable default has moved on to a newer policy. + self.adapter_path: Optional[str] = trajectory.get('adapter_path') + #: Effects already represented by the latest durable episode checkpoint. + self.completed_effects: set[str] = set() @remote_class(max_concurrency=ROLLOUT_MAX_CONCURRENCY) @@ -426,6 +435,7 @@ def __init__( use_base_model: bool = False, concurrency: int | None = None, segment_policy: str = 'drop', + resume_store: ResumeStore | None = None, ): if sampler is None and response_callback is None: raise ValueError('MultiTurnRollout requires a sampler or a response_callback.') @@ -509,6 +519,144 @@ def __init__( self._endpoint_lock = threading.Lock() self._policy_endpoint: Optional[PolicyEndpoint] = None self._env_tool_infos: Optional[list] = None + self.resume_store = resume_store + + # ---------------------------------------------------------------- durable episode + + def bind_resume_store(self, store: ResumeStore) -> None: + """Inject the run store before the first episode starts.""" + with self._lock: + if self._episodes: + raise RuntimeError('bind_resume_store must run before any episode is opened') + self.resume_store = store + + def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: + if ep.busy and not allow_busy: + raise UnsafeResume(f'episode {ep.episode_id!r} is mid-step and cannot be checkpointed') + if self.harness is not None: + raise UnsafeResume('agent-program episodes own live processes and cannot be checkpointed yet') + if not ep.state_key: + raise UnsafeResume(f'episode {ep.episode_id!r} has no stable state_key') + if ep.ledger is None: + raise UnsafeResume(f'episode {ep.episode_id!r} has no token ledger yet') + if isinstance(ep.ledger, MessageLedger): + raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') + env_state = None + if ep.env_open: + capability = EnvResumeCapability(getattr(self.env, 'resume_capability', EnvResumeCapability.NONE)) + if capability == EnvResumeCapability.NONE: + raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') + env_state = self.env.checkpoint_episode(ep.episode_id, ep.state_key) + return { + 'format': 'twinkle.multi-turn-episode.v1', + 'state_key': ep.state_key, + 'episode_id': ep.episode_id, + 'trajectory': ep.trajectory, + 'params': ep.params, + 'ledger': ep.ledger.state_dict(), + 'env_state': env_state, + 'env_open': ep.env_open, + 'budget': ep.budget, + 'spent': ep.spent, + 'followups': ep.followups, + 'malformed': ep.malformed, + 'stuck': ep.stuck, + 'seen_calls': sorted(ep.seen_calls), + 'stuck_stop': ep.stuck_stop, + 'tool_stop': ep.tool_stop, + 'truncated': ep.truncated, + 'stop_reason': ep.stop_reason, + 'error': ep.error, + 'segments': ep.segments, + 'sent': ep.sent, + 'tools_key': ep.tools_key, + 'last_reply': ep.last_reply, + 'closed_rows': ep.closed_rows, + 'completed_effects': sorted(ep.completed_effects), + } + + @remote_function(execute='first', collect='first', lazy_collect=False) + def checkpoint_episode(self, episode_id: str) -> dict[str, Any]: + """Persist one episode at an externally stable boundary.""" + with self._lock: + ep = self._episodes.get(episode_id) + if ep is None: + raise EpisodeError(f'episode {episode_id!r} is not held by this rollout') + return self._checkpoint_episode(ep) + + def _checkpoint_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: + state = self._capture_episode(ep, allow_busy=allow_busy) + if self.resume_store is not None: + self.resume_store.checkpoint_episode(ep.state_key, state) + return state + + def restore_episode(self, state: dict[str, Any]) -> str: + """Rebuild an episode from a durable state before it is stepped again.""" + if state.get('format') != 'twinkle.multi-turn-episode.v1': + raise UnsafeResume('unsupported MultiTurnRollout episode format') + state_key = str(state.get('state_key') or '') + episode_id = str(state.get('episode_id') or '') + if not state_key or not episode_id: + raise UnsafeResume('episode checkpoint has no state_key or episode_id') + if self.resume_store is not None: + checkpointed = set(state.get('completed_effects') or ()) + pending = set(self.resume_store.pending_effects(state_key)) + unsafe_pending = pending - checkpointed + if unsafe_pending: + raise UnsafeResume(f'episode {state_key} has pending tool effects: {sorted(unsafe_pending)!r}') + # The checkpoint is written after the tool messages enter the ledger but before the + # result journal record. If only that final record is missing, the checkpoint proves + # the effect happened and already contains its observation; close the journal gap + # instead of rejecting a state that cannot repeat the external call. + for effect_key in pending & checkpointed: + self.resume_store.finish_effect(effect_key, {'recovered_from_checkpoint': True}) + completed = set(self.resume_store.completed_effects(state_key)) + missing = completed - checkpointed + if missing: + raise UnsafeResume(f'effect results exist without a matching episode checkpoint: {sorted(missing)!r}') + + ep = _Episode(episode_id, dict(state['trajectory']), state['params']) + ep.state_key = state_key + ep.ledger = self._new_ledger(episode_id) + if isinstance(ep.ledger, MessageLedger): + raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') + ep.ledger.load_state_dict(state['ledger']) + ep.env_open = bool(state.get('env_open')) + if ep.env_open: + if self.env is None: + raise UnsafeResume('checkpoint has an environment state but this rollout has no env') + capability = EnvResumeCapability(getattr(self.env, 'resume_capability', EnvResumeCapability.NONE)) + if capability == EnvResumeCapability.NONE: + raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') + self.env.restore_episode(episode_id, state_key, state['env_state'], ep.trajectory) + ep.budget = int(state['budget']) + ep.spent = int(state['spent']) + ep.followups = int(state['followups']) + ep.malformed = int(state['malformed']) + ep.stuck = int(state['stuck']) + ep.seen_calls = set(state.get('seen_calls') or ()) + ep.stuck_stop = bool(state.get('stuck_stop')) + ep.tool_stop = state.get('tool_stop') + ep.truncated = bool(state.get('truncated')) + ep.stop_reason = state.get('stop_reason') + ep.error = state.get('error') + ep.segments = int(state.get('segments') or 0) + ep.sent = list(state.get('sent') or ()) + ep.tools_key = state.get('tools_key') + ep.last_reply = state.get('last_reply') + ep.closed_rows = list(state.get('closed_rows') or ()) + ep.completed_effects = set(state.get('completed_effects') or ()) + ep.tool_manager = self._episode_tools(episode_id) + with self._lock: + if episode_id in self._episodes: + raise UnsafeResume(f'episode {episode_id!r} is already held by this rollout') + self._episodes[episode_id] = ep + return episode_id + + def restore_episode_from_store(self, state_key: str) -> str: + if self.resume_store is None: + raise UnsafeResume('no resume store is bound to this rollout') + return self.restore_episode(self.resume_store.load_episode(state_key)) # ------------------------------------------------------------------ entries @@ -883,10 +1031,13 @@ def _generate(self, ep: _Episode, ledger, params: SamplingParams) -> SampledSequ seq = self.response_callback(self._view(ep), state, params) else: use_state = ledger.state is not None and getattr(type(self.sampler), 'accepts_rollout_state', False) + adapter_kwargs = dict(self._adapter_kwargs) + if ep.adapter_path is not None: + adapter_kwargs['adapter_path'] = ep.adapter_path responses = self.sampler.sample([ledger.state if use_state else ledger.input_feature], sampling_params=params, session_id=ep.episode_id, - **self._adapter_kwargs) + **adapter_kwargs) seq = _single_sequence(responses) if not isinstance(seq, SampledSequence): raise TypeError(f'expected SampledSequence, got {type(seq).__name__}') @@ -908,10 +1059,33 @@ def _run_tools(tool_manager: ToolManager, tool_calls: list[dict[str, Any]]) -> l obs[i] = '' if content is None else str(content) return obs + def _begin_tool_effect(self, ep: _Episode, + tool_calls: list[dict[str, Any]]) -> tuple[Optional[str], Optional[list[str]]]: + if self.resume_store is None or not ep.state_key: + return None, None + calls = json.dumps(tool_calls, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + digest = hashlib.sha256(calls.encode('utf-8')).hexdigest()[:20] + effect_key = f'{ep.state_key}/effect/{ep.spent}/{digest}' + completed = self.resume_store.begin_effect(effect_key, {'calls': tool_calls}) + if completed is None: + return effect_key, None + return effect_key, list(completed.get('observations') or ()) + + def _commit_tool_effect(self, ep: _Episode, effect_key: Optional[str], observations: list[str]) -> None: + if effect_key is None or self.resume_store is None: + return + ep.completed_effects.add(effect_key) + # The checkpoint includes both the appended observation and the effect key. + # Only after it is durable may the result record make crash recovery safe. + self._checkpoint_episode(ep, allow_busy=True) + self.resume_store.finish_effect(effect_key, {'observations': observations}) + # ---------------------------------------------------------------- tool loop def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: """One generation and, when it called tools, their round.""" + if self.resume_store is not None: + self._checkpoint_episode(ep, allow_busy=True) ledger = ep.ledger ep.spent += 1 @@ -993,7 +1167,9 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: ep.malformed = 0 if ep.tool_manager is None: raise ValueError('the model emitted tool_calls but this rollout has no tools (tool_manager= or env=).') - observations = self._run_tools(ep.tool_manager, tool_calls) + effect_key, cached_observations = self._begin_tool_effect(ep, tool_calls) + observations = (cached_observations if cached_observations is not None else + self._run_tools(ep.tool_manager, tool_calls)) if self.stop_after_stuck_turns: keys = [_call_key(tc) for tc in tool_calls] all_repeats = bool(keys) and all(k in ep.seen_calls for k in keys) @@ -1009,12 +1185,15 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: if self.stop_after_stuck_turns and ep.stuck >= self.stop_after_stuck_turns: ep.stuck_stop = True ep.tool_stop = 'stuck' + self._commit_tool_effect(ep, effect_key, observations) if not overflowed and self._grant_followup(ep): return self._next_turn(ep) ep.truncated = True return self._finish_tool_episode(ep) if overflowed: + self._commit_tool_effect(ep, effect_key, observations) return self._finish_tool_episode(ep) + self._commit_tool_effect(ep, effect_key, observations) return self._next_turn(ep) def _next_turn(self, ep: _Episode) -> tuple[list, RolloutStatus]: diff --git a/src/twinkle_client/rollout/_http_sampler.py b/src/twinkle_client/rollout/_http_sampler.py index 47e80d32d..4a326c7f0 100644 --- a/src/twinkle_client/rollout/_http_sampler.py +++ b/src/twinkle_client/rollout/_http_sampler.py @@ -89,17 +89,25 @@ def __init__(self, model, sampler: HTTPSampler, *, name_prefix: str = 'policy'): self.sampler = sampler self.name_prefix = name_prefix self._version = 0 + self._paths: Dict[int, str] = {} self._lock = threading.Lock() def sync_weights(self) -> None: with self._lock: saved = self.model.save(f'{self.name_prefix}-{self._version}', save_optimizer=False) - self.sampler.adapter_path = saved.twinkle_path + path = saved.twinkle_path + self._paths[self._version] = path + self.sampler.adapter_path = path self._version += 1 def version(self) -> int: return self._version + def adapter_path(self, version: int) -> Optional[str]: + """The durable adapter a group sampled from, retained for resume.""" + with self._lock: + return self._paths.get(int(version)) + def _wire_media(media: Any) -> Dict[str, List[str]]: """The media of a RolloutState as the strings the wire carries (URL or ``data:`` URI).""" diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py new file mode 100644 index 000000000..96f7e6cad --- /dev/null +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -0,0 +1,48 @@ +import os +import sys +import types + +import pytest + +if os.name == "nt" and "resource" not in sys.modules: + resource = types.ModuleType("resource") + resource.RLIMIT_AS = 0 + resource.setrlimit = lambda *args, **kwargs: None + sys.modules["resource"] = resource + +if "ray" not in sys.modules: + ray = types.ModuleType("ray") + ray.ObjectRef = type("ObjectRef", (), {}) + ray.is_initialized = lambda: False + sys.modules["ray"] = ray + +from twinkle_agentic.envs.base import UnsafeCheckpoint # noqa: E402 +from twinkle_agentic.envs.localenv import LocalEnv # noqa: E402 + + +def test_localenv_workspace_round_trip_uses_a_new_session(tmp_path): + source = LocalEnv(root=str(tmp_path)) + source.reset("episode-1") + source.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "turn-boundary"}) + state_key = "run-1/group-0/episode-1/attempt-0" + + snapshot = source.checkpoint_episode("episode-1", state_key) + source.close("episode-1") + + restored = LocalEnv(root=str(tmp_path)) + restored.restore_episode("episode-1", state_key, snapshot) + result = restored.step("episode-1", "read_file", {"path": "nested/state.txt"}) + assert result.observation == "turn-boundary" + + restored.discard_episode_state(state_key) + assert not restored._resume_root.exists() or not any(restored._resume_root.iterdir()) + restored.close("episode-1") + + +def test_localenv_checkpoint_refuses_a_running_process(tmp_path): + env = LocalEnv(root=str(tmp_path)) + env.reset("episode-1") + env._session("episode-1").state.procs.add(object()) + with pytest.raises(UnsafeCheckpoint, match="running process"): + env.checkpoint_episode("episode-1", "run-1/group-0/episode-1") + env.close("episode-1") diff --git a/tests/twinkle_agentic/test_multi_turn_resume.py b/tests/twinkle_agentic/test_multi_turn_resume.py new file mode 100644 index 000000000..cf4a1aacc --- /dev/null +++ b/tests/twinkle_agentic/test_multi_turn_resume.py @@ -0,0 +1,144 @@ +import pytest + +from twinkle.data_format import SampleResponse +from twinkle.data_format.sampling import SampledSequence, SamplingParams +from twinkle_agentic.async_rl.rollout_resume import ResumeStore, UnsafeResume +from twinkle_agentic.envs.localenv import LocalEnv +from twinkle_agentic.rollout.multi_turn import MultiTurnRollout, _Episode + + +class _Template: + max_length = 32 + truncation_strategy = "right" + + +def _rollout(store=None): + return MultiTurnRollout(response_callback=lambda *args: None, template=_Template(), resume_store=store) + + +def _episode(rollout, state_key="run/group-0/episode-0/attempt-0", adapter_path=None): + trajectory = {"messages": [{"role": "user", "content": "hello"}], "state_key": state_key} + if adapter_path is not None: + trajectory["adapter_path"] = adapter_path + ep = _Episode("episode-0", trajectory, rollout._params(SamplingParams())) + ep.ledger = rollout._new_ledger("episode-0") + ep.ledger._pif = { + "input_ids": [1, 2, 3], + "labels": [-100, 2, 3], + "completion_mask": [0, 1, 1], + "messages": trajectory["messages"], + } + ep.ledger._turns = 1 + ep.budget = 3 + ep.spent = 1 + return ep + + +def test_multi_turn_episode_round_trip_from_store(tmp_path): + store = ResumeStore(tmp_path, "run") + source = _rollout(store) + ep = _episode(source, adapter_path="/policies/policy-1.adapter") + source._episodes[ep.episode_id] = ep + source.checkpoint_episode(ep.episode_id) + + restored = _rollout(store) + restored.restore_episode_from_store(ep.state_key) + again = restored._episodes[ep.episode_id] + assert again.state_key == ep.state_key + assert again.budget == ep.budget and again.spent == ep.spent + assert again.ledger.input_feature["input_ids"] == [1, 2, 3] + assert again.ledger.turns == 1 + assert again.adapter_path == "/policies/policy-1.adapter" + + +def test_multi_turn_restore_refuses_effect_without_tool_checkpoint(tmp_path): + store = ResumeStore(tmp_path, "run") + source = _rollout(store) + ep = _episode(source) + source._episodes[ep.episode_id] = ep + state = source.checkpoint_episode(ep.episode_id) + + pending_effect = ep.state_key + "/effect/1/abc" + store.begin_effect(pending_effect, {"calls": []}) + with pytest.raises(UnsafeResume, match="pending tool effects"): + _rollout(store).restore_episode(state) + + ep.completed_effects.add(pending_effect) + safe_state = source.checkpoint_episode(ep.episode_id) + restored_episode = _rollout(store).restore_episode(safe_state) + assert restored_episode == ep.episode_id + assert store.begin_effect(pending_effect, {"calls": []}) == {"recovered_from_checkpoint": True} + + uncheckpointed_effect = ep.state_key + "/effect/2/def" + store.begin_effect(uncheckpointed_effect, {"calls": []}) + store.finish_effect(uncheckpointed_effect, {"observations": []}) + with pytest.raises(UnsafeResume, match="without a matching episode checkpoint"): + _rollout(store).restore_episode(safe_state) + + ep.completed_effects.add(uncheckpointed_effect) + final_state = source.checkpoint_episode(ep.episode_id) + restored = _rollout(store).restore_episode_from_store(ep.state_key) + assert restored == ep.episode_id + assert pending_effect in final_state["completed_effects"] + assert uncheckpointed_effect in store.completed_effects(ep.state_key) + + +def test_multi_turn_refuses_message_ledger_checkpoint(): + rollout = MultiTurnRollout(response_callback=lambda *args: None) + ep = _episode(rollout) + rollout._episodes[ep.episode_id] = ep + with pytest.raises(UnsafeResume, match="lose sampled token ids"): + rollout.checkpoint_episode(ep.episode_id) + + +def test_multi_turn_restores_localenv_at_turn_boundary(tmp_path): + store = ResumeStore(tmp_path / "resume", "run") + env = LocalEnv(root=str(tmp_path / "workspace")) + episode_id = "episode-env" + state_key = "run/group-0/attempt-0/member/0" + env.reset(episode_id) + env.step(episode_id, "write_file", {"path": "state.txt", "content": "durable-turn"}) + + source = MultiTurnRollout(response_callback=lambda *args: None, template=_Template(), env=env, resume_store=store) + ep = _episode(source, state_key) + ep.episode_id = episode_id + ep.trajectory["episode_id"] = episode_id + ep.trajectory["state_key"] = state_key + ep.env_open = True + source._episodes[episode_id] = ep + source.checkpoint_episode(episode_id) + env.close(episode_id) + + restored = MultiTurnRollout( + response_callback=lambda *args: None, + template=_Template(), + env=LocalEnv(root=str(tmp_path / "workspace")), + resume_store=store, + ) + restored.restore_episode_from_store(state_key) + result = restored.env.step(episode_id, "read_file", {"path": "state.txt"}) + assert result.observation == "durable-turn" + restored.env.close(episode_id) + + +def test_episode_policy_binding_overrides_the_samplers_mutable_default(): + class _Sampler: + accepts_rollout_state = False + + def __init__(self): + self.adapter_paths = [] + + def sample(self, _inputs, sampling_params=None, *, adapter_path=None, **_kwargs): + self.adapter_paths.append(adapter_path) + return [ + SampleResponse( + sequences=[SampledSequence(stop_reason="stop", tokens=[7], logprobs=[[(7, -0.1)]], decoded="x")] + ) + ] + + sampler = _Sampler() + rollout = MultiTurnRollout(sampler=sampler) + ep = _Episode("episode-pinned", {"adapter_path": "/policies/policy-1.adapter"}, rollout._params(SamplingParams())) + rollout._generate(ep, type("Ledger", (), {"state": None, "input_feature": {}})(), SamplingParams()) + + assert sampler.adapter_paths == ["/policies/policy-1.adapter"] diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py new file mode 100644 index 000000000..ac59c09ca --- /dev/null +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -0,0 +1,69 @@ +import json +import pytest + +from twinkle_agentic.async_rl.rollout_resume import ( + DurableJournal, + JournalCorrupt, + JournalEvent, + ResumeError, + ResumeStore, + UnsafeResume, +) + + +def test_journal_repairs_only_a_torn_final_line(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0", {"row": 0}) + journal.append(JournalEvent.GROUP_READY, "run/0", {"members": 2}) + with open(path, "ab") as stream: + stream.write(b'{"seq":2') + + repaired = DurableJournal(path) + record = repaired.append(JournalEvent.BATCH_LEASED, "run/0", {"handed": 1}) + assert record.seq == 2 + assert [item.event for item in repaired.records()] == [ + JournalEvent.PROMPT_ASSIGNED, + JournalEvent.GROUP_READY, + JournalEvent.BATCH_LEASED, + ] + + +def test_journal_refuses_damage_before_a_complete_later_record(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + first = journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0", {"row": 0}) + journal.append(JournalEvent.GROUP_READY, "run/0", {"members": 2}) + lines = path.read_text(encoding="utf-8").splitlines() + broken = json.loads(lines[0]) + broken["payload"]["row"] = 99 + lines[0] = json.dumps(broken, sort_keys=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + with pytest.raises(JournalCorrupt): + DurableJournal(path) + assert first.seq == 0 + + +def test_resume_store_checks_object_checksum(tmp_path): + store = ResumeStore(tmp_path, "run") + store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) + assert store.load_object("episodes", "run/episode/0") == {"tokens": [1, 2, 3]} + + object_path = next((tmp_path / "objects" / "episodes").iterdir()) + data = bytearray(object_path.read_bytes()) + data[-1] ^= 0xFF + object_path.write_bytes(data) + with pytest.raises(ResumeError, match="checksum"): + store.load_object("episodes", "run/episode/0") + + +def test_effect_intent_without_result_fails_closed_then_result_is_replayable(tmp_path): + store = ResumeStore(tmp_path, "run") + effect = "run/group-0/episode-0/turn-1" + assert store.begin_effect(effect, {"calls": ["write_file"]}) is None + with pytest.raises(UnsafeResume, match="intent without a result"): + store.begin_effect(effect, {"calls": ["write_file"]}) + + store.finish_effect(effect, {"observations": ["File written"]}) + assert store.begin_effect(effect, {"calls": ["ignored"]}) == {"observations": ["File written"]} diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py new file mode 100644 index 000000000..6daba163f --- /dev/null +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -0,0 +1,329 @@ +import pickle +import time + +import pytest + +from twinkle_agentic.async_rl.rollout_resume import ResumeStore +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver +from twinkle_agentic.rollout.multi_turn import RolloutStatus + + +class _Future: + def __init__(self, value=None): + self._value = value + + def exception(self): + return None + + def result(self): + return self._value + + def add_done_callback(self, callback): + callback(self) + + +class _BlockingFuture: + def add_done_callback(self, callback): + self.callback = callback + + +class _DoneRollout: + def __init__(self): + self.calls = [] + + def step(self, trajectory, episode_id=None, session_wait=None): + self.calls.append(episode_id) + row = dict(trajectory, turns=1) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + return None + + +class _BoundRollout(_DoneRollout): + def step(self, trajectory, episode_id=None, session_wait=None): + self.calls.append((episode_id, trajectory.get("policy_version"), trajectory.get("adapter_path"))) + row = dict(trajectory, turns=1) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + return _Future(([row], sample)) + + +class _PolicyManager: + def __init__(self, version, paths): + self._version = version + self._paths = dict(paths) + + def version(self): + return self._version + + def adapter_path(self, version): + return self._paths.get(version) + + +class _PartiallyBlockingRollout(_DoneRollout): + def step(self, trajectory, episode_id=None, session_wait=None): + self.calls.append(episode_id) + if episode_id.endswith("member:1"): + return _BlockingFuture() + row = dict(trajectory, turns=1) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + return _Future(([row], sample)) + + +class _BlockingRollout(_DoneRollout): + def step(self, trajectory, episode_id=None, session_wait=None): + self.calls.append(episode_id) + return _BlockingFuture() + + +def _prompts(count=2): + return [{"messages": [{"role": "user", "content": f"prompt-{index}"}]} for index in range(count)] + + +def _wait_until(predicate, timeout=2.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.01) + raise AssertionError("condition was not reached before timeout") + + +def test_inflight_prompt_and_group_survive_snapshot(tmp_path): + store = ResumeStore(tmp_path, "run-inflight") + rollout = _BlockingRollout() + driver = StreamingDriver(_prompts(), rollout, batch_size=2, num_generations=2, max_staleness=0, resume_store=store) + driver._admit() + state = driver.state_dict() + + restored_rollout = _BlockingRollout() + restored = StreamingDriver( + _prompts(), restored_rollout, batch_size=2, num_generations=2, max_staleness=0, resume_store=store + ) + restored.load_state_dict(state) + + assert restored._prompt_seq == 1 + assert list(restored._groups) == ["0"] + assert restored._groups["0"].row == _prompts()[0] + assert len(restored._groups["0"].members) == 2 + assert restored._inflight == 2 + assert len(restored_rollout.calls) == 2 + assert [member.episode_id for member in restored._groups["0"].members] == [ + member.episode_id for member in driver._groups["0"].members + ] + assert [member.submit_traj["state_key"] for member in restored._groups["0"].members] == [ + member.submit_traj["state_key"] for member in driver._groups["0"].members + ] + + +def test_ready_group_round_trip_and_lease_redelivery(tmp_path): + store = ResumeStore(tmp_path, "run-ready") + source = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + source._start() + _wait_until(lambda: source._ready_rows == 2) + ready_state = source.state_dict() + source.close() + + restored = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + restored.load_state_dict(ready_state) + rows, facts = restored._next_batch() + assert len(rows) == 2 + assert facts["policy_versions"] == [0] + assert restored._handed == 1 + + leased_state = restored.state_dict() + after_crash = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + after_crash.load_state_dict(leased_state) + again_rows, again_facts = after_crash._next_batch() + assert again_rows == rows + assert again_facts == facts + with pytest.raises(Exception, match="durable model checkpoint"): + after_crash.commit_batch("") + after_crash.commit_batch("checkpoint-1", manifest={"optimizer_step": 7}) + commit = store.journal.records()[-1] + assert commit.payload["checkpoint"] == "checkpoint-1" + assert commit.payload["manifest"] == {"optimizer_step": 7} + + stale = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + stale.load_state_dict(leased_state) + assert stale._lease is None + + +def test_resumed_group_keeps_its_pinned_adapter_after_policy_advances(tmp_path): + store = ResumeStore(tmp_path, "run-policy") + manager = _PolicyManager(1, {1: "/policies/policy-1.adapter"}) + driver = StreamingDriver( + _prompts(1), + _BlockingRollout(), + batch_size=2, + num_generations=2, + max_staleness=1, + checkpoint_manager=manager, + resume_store=store, + ) + driver._version = manager.version() + driver._admit() + state = driver.state_dict() + assert driver._groups["0"].version == 1 + assert driver._groups["0"].adapter_path == "/policies/policy-1.adapter" + driver.close() + + manager._version = 2 + manager._paths[2] = "/policies/policy-2.adapter" + rollout = _BoundRollout() + restored = StreamingDriver( + _prompts(1), + rollout, + batch_size=2, + num_generations=2, + max_staleness=1, + checkpoint_manager=manager, + resume_store=store, + ) + restored.load_state_dict(pickle.loads(pickle.dumps(state))) + + assert restored._groups["0"].version == 1 + assert restored._groups["0"].adapter_path == "/policies/policy-1.adapter" + assert {call[1:] for call in rollout.calls} == {(1, "/policies/policy-1.adapter")} + assert restored.stats()["resumed_groups"] == 1 + + +def test_ready_group_over_staleness_is_dropped_whole(tmp_path): + store = ResumeStore(tmp_path, "run-stale") + manager = _PolicyManager(1, {1: "/policies/policy-1.adapter"}) + source = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + source._start() + _wait_until(lambda: source._ready_rows == 2) + state = source.state_dict() + state["exhausted"] = True + source.close() + + manager._version = 2 + manager._paths[2] = "/policies/policy-2.adapter" + rollout = _BoundRollout() + restored = StreamingDriver( + _prompts(1), + rollout, + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + restored.load_state_dict(state) + assert restored._next_batch() is None + assert restoration_stats(restored) == { + "dropped_stale": 2, + "dropped_group": 1, + "ready_rows": 0, + "live": 0, + } + assert rollout.calls == [] + + +def test_resume_retains_a_partially_finished_group_for_training(tmp_path): + store = ResumeStore(tmp_path, "run-partial") + manager = _PolicyManager(1, {1: "/policies/policy-1.adapter"}) + rollout = _PartiallyBlockingRollout() + driver = StreamingDriver( + _prompts(1), + rollout, + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + driver._version = manager.version() + driver._admit() + while not driver._events.empty(): + driver._handle(*driver._events.get_nowait()) + assert driver._groups["0"].members[0].finished + assert not driver._groups["0"].members[1].finished + state = driver.state_dict() + driver.close() + + resumed_rollout = _BoundRollout() + resumed = StreamingDriver( + _prompts(1), + resumed_rollout, + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + resumed.load_state_dict(state) + rows, facts = resumed._next_batch() + + assert len(rows) == 2 + assert facts["policy_versions"] == [1] + assert resumed.stats()["resumed_groups"] == 1 + assert resumed.stats()["resumed_members"] == 1 + assert resumed_rollout.calls == [("run-partial:g0:a0:member:1", 1, "/policies/policy-1.adapter")] + + lease_id = resumed.commit_batch("checkpoint/policy-1", manifest={"optimizer_step": 1}) + assert lease_id == "run-partial/batch/0" + assert resumed._next_batch() is None + + after_commit = StreamingDriver( + _prompts(1), + _BoundRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + checkpoint_manager=manager, + resume_store=store, + ) + after_commit.load_state_dict(resumed.state_dict()) + assert after_commit._lease is None + + +def test_delivered_groups_release_the_admission_window(tmp_path): + manager = _PolicyManager(1, {1: "/policies/policy-1.adapter"}) + driver = StreamingDriver( + _prompts(3), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=2, + checkpoint_manager=manager, + ) + try: + first, _ = driver._next_batch() + driver.commit_batch("checkpoint/one") + second, _ = driver._next_batch() + driver.commit_batch("checkpoint/two") + assert len(first) == len(second) == 2 + assert driver.stats()["live"] == 0 + assert driver._next_batch() is None + finally: + driver.close() + + +def restoration_stats(driver): + stats = driver.stats() + return {key: stats[key] for key in ("dropped_stale", "dropped_group", "ready_rows", "live")} diff --git a/tests/twinkle_agentic/test_turn_ledger_resume.py b/tests/twinkle_agentic/test_turn_ledger_resume.py new file mode 100644 index 000000000..83212776d --- /dev/null +++ b/tests/twinkle_agentic/test_turn_ledger_resume.py @@ -0,0 +1,37 @@ +import pytest + +from twinkle_agentic.rollout.ledger import TurnLedger + + +class _Template: + max_length = 32 + + +def test_turn_ledger_round_trip_keeps_exact_sampler_state(): + ledger = TurnLedger(_Template(), label="gate0") + ledger._pif = { + "input_ids": [10, 11, 12, 13], + "labels": [-100, -100, 12, 13], + "completion_mask": [0, 0, 1, 1], + "response_positions": [1, 2], + "messages": [{"role": "user", "content": "hello"}], + } + ledger._logprobs = [[(12, -0.1)], [(13, -0.2)]] + ledger._sampling_masks = {"blocks": [1, 2]} + ledger._turns = 2 + + state = ledger.state_dict() + restored = TurnLedger(_Template(), label="gate0") + restored.load_state_dict(state) + + assert restored.input_feature == ledger.input_feature + assert restored.logprobs == ledger.logprobs + assert restored.turns == 2 + restored.input_feature["input_ids"].append(99) + assert ledger.input_feature["input_ids"] == [10, 11, 12, 13] + + +def test_turn_ledger_refuses_an_incomplete_checkpoint(): + ledger = TurnLedger(_Template()) + with pytest.raises(ValueError, match="missing input_feature"): + ledger.load_state_dict({"format": "twinkle.turn-ledger.v1", "input_feature": {}, "logprobs": [], "turns": 0}) diff --git a/tests/twinkle_client/test_checkpoint_policy_history.py b/tests/twinkle_client/test_checkpoint_policy_history.py new file mode 100644 index 000000000..8c0bc3394 --- /dev/null +++ b/tests/twinkle_client/test_checkpoint_policy_history.py @@ -0,0 +1,35 @@ +from types import SimpleNamespace + +from twinkle_client.rollout import ClientCheckpointManager + + +class _Model: + def __init__(self): + self.saved = [] + + def save(self, name, **_kwargs): + self.saved.append(name) + return SimpleNamespace(twinkle_path=f"/policies/{name}.adapter") + + +class _Sampler: + def __init__(self): + self.adapter_path = None + + +def test_checkpoint_manager_retains_each_policy_adapter_for_resume(): + model = _Model() + sampler = _Sampler() + manager = ClientCheckpointManager(model, sampler, name_prefix="durable") + + manager.sync_weights() + first = sampler.adapter_path + manager.sync_weights() + second = sampler.adapter_path + + assert first == "/policies/durable-0.adapter" + assert second == "/policies/durable-1.adapter" + assert manager.adapter_path(0) == first + assert manager.adapter_path(1) == second + assert manager.adapter_path(99) is None + assert manager.version() == 2 From ecd6be65130b93e5c369119fc7d298f86fa51374 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 15:25:02 +0800 Subject: [PATCH 02/45] fix(agentic): harden durable resume and record NPU evidence --- review/a2/BOUNDARY_TEST_RESULTS_20261119.md | 157 + review/a2/GSM8K_AB_20261118.md | 146 + .../NPU_CHECKPOINT_KILL_RESULTS_20261119.md | 120 + review/a2/PR399_RESULTS_20261119.md | 160 + review/a2/README.md | 5 + .../README.md | 33 + .../adapter_temp_uncommitted/ready.json | 102 + .../adapter_temp_uncommitted/verify.json | 29 + .../checkpoint_committed/ready.json | 104 + .../checkpoint_committed/verify.json | 29 + .../ready.json | 104 + .../verify.json | 29 + .../optimizer_step_uncommitted/ready.json | 92 + .../optimizer_step_uncommitted/verify.json | 25 + .../report.json | 561 ++ .../a2/npu-checkpoint-kill-results/.gitignore | 2 + review/a2/run_checkpoint_transaction_probe.py | 226 + review/a2/run_focused_tests.py | 1 + review/a2/run_grpo_reward_ab.py | 430 ++ review/a2/run_kill_phase_probe.py | 360 + review/a2/run_npu_checkpoint_kill_probe.py | 706 ++ review/a2/run_resume_overhead_bench.py | 170 + review/a2/summarize_gsm8k_ab.py | 74 + .../report.json | 6214 +++++++++++++++++ .../report.json | 3142 +++++++++ .../async_rl/rollout_resume.py | 94 +- .../twinkle_agentic/test_resume_boundaries.py | 335 + 27 files changed, 13431 insertions(+), 19 deletions(-) create mode 100644 review/a2/BOUNDARY_TEST_RESULTS_20261119.md create mode 100644 review/a2/GSM8K_AB_20261118.md create mode 100644 review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md create mode 100644 review/a2/PR399_RESULTS_20261119.md create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/README.md create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/ready.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/verify.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/ready.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/verify.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/ready.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/verify.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/ready.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/verify.json create mode 100644 review/a2/npu-checkpoint-kill-evidence-20261119/report.json create mode 100644 review/a2/npu-checkpoint-kill-results/.gitignore create mode 100644 review/a2/run_checkpoint_transaction_probe.py create mode 100644 review/a2/run_grpo_reward_ab.py create mode 100644 review/a2/run_kill_phase_probe.py create mode 100644 review/a2/run_npu_checkpoint_kill_probe.py create mode 100644 review/a2/run_resume_overhead_bench.py create mode 100644 review/a2/summarize_gsm8k_ab.py create mode 100644 review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json create mode 100644 review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json create mode 100644 tests/twinkle_agentic/test_resume_boundaries.py diff --git a/review/a2/BOUNDARY_TEST_RESULTS_20261119.md b/review/a2/BOUNDARY_TEST_RESULTS_20261119.md new file mode 100644 index 000000000..06d415f9b --- /dev/null +++ b/review/a2/BOUNDARY_TEST_RESULTS_20261119.md @@ -0,0 +1,157 @@ +# RolloutResume 边界测试结果 + +日期:2026-11-19 + +## 结论 + +八组边界均已有自动化测试或独立探针: + +| 组别 | 结果 | 证据 | +|---|---|---| +| 1. 无故障等价与开销 | 通过 | 确定性 A/B 训练信号和评测样本逐值一致;journal/object 吞吐与空间放大已测量 | +| 2. trainer checkpoint 事务 | 通过 | 真实 `torch.optim.SGD` step、checkpoint 原子写、commit、回滚和 lease 清理 | +| 3. 完整进程强杀阶段 | 通过 | A2 Linux 五个阶段均以 `SIGKILL(-9)` 终止并正确恢复 | +| 4. exactly-once 边界 | 通过 | 缺失 checkpoint ref、重复 commit、已提交后旧快照、旧 policy 组均有测试 | +| 5. journal 故障注入 | 通过 | 截断、中间损坏、SHA 不匹配、ENOSPC、rename 中断、线程/进程并发 writer | +| 6. 环境 fail-closed | 通过 | 无恢复能力 Env、AgentEnv、OpenEnv、OpenEnvClient 均不允许静默恢复 | +| 7. 非幂等工具 | 通过 | 工具 intent 未提交时恢复拒绝,已完成 effect 使用缓存 observation,不重复调用 | +| 8. adapter 生命周期 | 通过 | 缺失路径拒绝恢复,同 version 不同路径固定原 adapter,过期组整组淘汰 | + +本地聚焦测试:`33 passed`。 + +A2 Python 3.10 环境聚焦测试:`33 passed`。 + +## 无故障对照 + +确定性控制配置: + +- `fault_period=0` +- 8 个训练组 +- LoRA dropout `0` +- `torch.use_deterministic_algorithms(True, warn_only=True)` +- 16 条固定测试 + +结果: + +- baseline/durable 均为 8 次 optimizer update、0 丢失组。 +- 两组训练信号逐值一致。 +- 16 条评测样本逐值一致。 +- `accuracy_delta=0`,`reward_delta=0`。 + +随机采样小样本无故障对照仍观察到非确定性指标波动,但训练步数和丢失组完全一致。 +因此精确等价结论只使用确定性控制;随机模式不能用于逐值比较。 + +## 性能与空间开销 + +A2、Python 3.10、500 次 journal append: + +| 指标 | 结果 | +|---|---:| +| durable journal | `5.1788 s` | +| 单次 append | `10.358 ms` | +| journal 吞吐 | `96.55 events/s` | +| journal bytes/event | `530.56 B` | +| 重开并扫描 500 条 | `18.60 ms` | + +50 个对象保存: + +| 指标 | 结果 | +|---|---:| +| durable object save | `0.02754 s` | +| 单对象 | `0.551 ms` | +| 对象吞吐 | `1815.7 objects/s` | +| 存储放大 | `1.0326x` | + +4 个独立进程各写 50 条: + +- 共 200 条记录。 +- sequence 连续为 `0..199`。 +- hash chain 有效。 +- 总耗时 `9.352 s`。 + +结论:单事件 fsync 成本明显,约 10 ms;批量高频小 journal 记录会成为吞吐瓶颈。 +后续若接入真实训练,需要按 turn/score/lease 等关键边界写入,而不是每个细粒度事件 +都同步 fsync。 + +## SIGKILL 阶段矩阵 + +A2 Linux 实测,子进程返回码均为 `-9`: + +| 阶段 | 恢复结果 | +|---|---| +| prompt 已分配 | prompt/group/state_key 恢复 | +| group 已 ready | 重新交付 2 行、policy version 0 | +| batch 已 lease | 相同 lease 重新交付 | +| optimizer 已 step、checkpoint 未提交 | 回退上一 checkpoint,同一 batch 再交付 | +| checkpoint 已提交 | lease 清空,batch 不再交付 | + +## 真实 Qwen + NPU checkpoint 强杀 + +在上述轻量事务探针之外,补充了真实 Qwen3-0.6B LoRA 训练进程验证: + +- A2 Ascend 910B4、32 GB HBM、单卡 `npu:0`; +- 官方 GSM8K 训练记录,真实 Qwen forward/backward 和 AdamW step; +- 分别强杀 optimizer step 后、临时 checkpoint 保存后、checkpoint 原子发布后和 + journal commit 后; +- 4 个场景的 worker 返回码均为 `-9`,恢复验证全部通过; +- 3 个未提交边界恢复 `step-0` 并重新交付同一 lease; +- commit 后恢复 `step-1`、optimizer step `[1]`,lease 清空且不再交付。 + +详细结果见: + +```text +review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md +review/a2/npu-checkpoint-kill-results/npu-checkpoint-kill-20261119/report.json +``` + +## 故障注入 + +- journal 最后一行截断:只删除 torn tail。 +- 中间记录损坏:`JournalCorrupt` fail closed。 +- 对象 SHA 不匹配:拒绝加载。 +- `fsync` 返回 `ENOSPC`:append 回滚到原文件长度。 +- `os.replace` 中断:旧对象保持完整,临时文件清理。 +- 多线程/多进程 journal writer:共享文件锁并重新扫描,sequence 与 hash chain 连续。 + +本轮修复了两个实际缺陷: + +1. `DurableJournal` 原锁仅限单实例,多 writer 会生成分叉链;现增加线程锁与跨进程 + 文件锁,并在 append 前重新扫描。 +2. append 在 fsync/磁盘错误后没有回滚;现恢复原文件长度,避免“调用报错但记录已写入”。 + +## 产物位置 + +本地 Windows 探针结果: + +```text +review/a2/boundary-results/checkpoint-transaction.json +review/a2/boundary-results/kill-phases-windows.json +review/a2/boundary-results/overhead-windows.json +review/a2/boundary-results/focused-tests-local.log +``` + +A2 同步结果: + +```text +review/a2/boundary-results/a2-20261119/ +``` + +关键文件: + +```text +boundary/focused-tests.log +boundary-source-hashes.txt +boundary-kill-phases.json +boundary-checkpoint-transaction.json +boundary-overhead.json +boundary-no-fault-deterministic/report.json +``` + +## 未覆盖的真实线上边界 + +- AgentEnv、OpenEnv、OpenEnvClient 本组只验证了无恢复能力时 fail closed;真实沙箱 + suspend/attach 服务协议未测试。 +- 磁盘满使用 `ENOSPC` 注入,没有实际写满测试盘。 +- checkpoint 事务已使用真实 Qwen3-0.6B LoRA/NPU,但尚未接入完整 Twinkle training + cookbook 的 optimizer、scheduler、DataLoader 全量状态。 +- 性能数据是单机本地文件系统结果,不代表网络存储、分布式文件系统或高并发多卡。 diff --git a/review/a2/GSM8K_AB_20261118.md b/review/a2/GSM8K_AB_20261118.md new file mode 100644 index 000000000..1df974081 --- /dev/null +++ b/review/a2/GSM8K_AB_20261118.md @@ -0,0 +1,146 @@ +# GSM8K 训练收益 A/B 实验记录 + +日期:2026-11-18 + +## 目的 + +验证 `Group-Atomic Durable GRPO` 不只是能够续跑,还能把故障窗口内原本会丢失的 +完整 GRPO 组转化为有效 optimizer update,并改善固定官方测试集上的任务指标。 + +## 数据与环境 + +- 数据集:OpenAI 官方 `grade-school-math` GSM8K JSONL。 +- train SHA-256:`17f347dc51477c50d4efb83959dbb7c56297aba886e5544ee2aaed3024813465` +- test SHA-256:`3730d312f6e3440559ace48831e51066acaca737f6eabec99bccb9e4b3c39d14` +- 调参切分:官方 `test[0:128]`。 +- 确认切分:官方 `test[128:256]`,在最终参数冻结前不使用。 +- 模型:Qwen3-0.6B。 +- 后端:Ascend 910B4,32 GB HBM,单卡 `npu:0`。 +- 训练方式:LoRA rank 8,group size 4,最多生成 160 token。 + +## 对照 + +- `cursor_restart`:故障点丢弃当前完整组,不生成 optimizer update。 +- `durable`:保留同一 behavior policy 下的完整组并正常训练。 + +两个分支使用同一初始 LoRA、同一数据、同一采样预算和同一评测 prompt。 + +## 25% 故障率 + +配置:64 个训练组,`fault_period=4`,`lr=5e-5`,128 条测试。 + +| seed | baseline 正确 | durable 正确 | 准确率差 | reward 差 | 有效 step | 丢失组 | +|---:|---:|---:|---:|---:|---:|---:| +| 20261119 | 48/128 | 58/128 | +7.8125pp | +0.1047 | 48 -> 64 | 16 -> 0 | +| 20261120 | 54/128 | 56/128 | +1.5625pp | -0.0109 | 48 -> 64 | 16 -> 0 | +| 20261121 | 61/128 | 55/128 | -4.6875pp | -0.0578 | 48 -> 64 | 16 -> 0 | + +三次均值:准确率 `+1.5625pp`,reward `+0.01198`。机制收益稳定,但最终模型 +质量收益不稳定,不能作为获奖结论。 + +## 25% 故障率与较低学习率 + +配置:64 个训练组,`fault_period=4`,`lr=2e-5`,128 条测试。 + +| seed | baseline 正确 | durable 正确 | 准确率差 | reward 差 | 有效 step | 丢失组 | +|---:|---:|---:|---:|---:|---:|---:| +| 20261122 | 58/128 | 56/128 | -1.5625pp | +0.0078 | 48 -> 64 | 16 -> 0 | + +训练分布上的样本准确率为 `+7.8125pp`,但没有转化为测试集准确率提升。 + +## 50% 故障率与较低学习率 + +配置:64 个训练组,`fault_period=2`,`lr=2e-5`,调参测试 `test[0:128]`。 + +| seed | baseline 正确 | durable 正确 | 准确率差 | reward 差 | 有效 step | 丢失组 | +|---:|---:|---:|---:|---:|---:|---:| +| 20261123 | 42/128 | 59/128 | +13.28125pp | +0.1750 | 32 -> 64 | 32 -> 0 | + +配对结果: + +- baseline 独有正确:6。 +- durable 独有正确:23。 +- 精确 McNemar 双侧 `p=0.0023157`。 + +该结果说明收益随故障导致的组损失比例上升,符合机制预期。它仍是调参切分结果, +必须由官方 test 的未参与调参区间确认。 + +## 50% 故障率确认切分 + +参数冻结后,在未参与调参的官方 `test[128:256]` 上运行两个独立种子: + +| seed | baseline 正确 | durable 正确 | 准确率差 | reward 差 | 配对翻转 | 有效 step | 丢失组 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 20261124 | 43/128 | 46/128 | +2.34375pp | +0.05156 | 6 -> 9 | 32 -> 64 | 32 -> 0 | +| 20261125 | 45/128 | 48/128 | +2.34375pp | +0.02969 | 3 -> 6 | 32 -> 64 | 32 -> 0 | + +两个确认种子的均值: + +- 准确率:`+2.34375pp`。 +- reward:`+0.040625`。 +- 正向数:准确率 `2/2`,reward `2/2`。 +- 合并配对翻转:baseline 独有正确 9,durable 独有正确 15。 +- 合并精确 McNemar:`p=0.3075`。 + +确认集方向一致,但样本量下没有达到统计显著。把调参种子和两个确认种子合并, +三个 50% 故障种子均正向,平均准确率 `+5.9896pp`,平均 reward `+0.08542`。 + +## 512 条独立测试 + +参数冻结后,在从未用于调参或确认的官方 `test[256:768]` 上运行 512 条测试: + +| seed | baseline 正确 | durable 正确 | 准确率差 | reward 差 | 配对翻转 | 有效 step | 丢失组 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 20261126 | 167/512 | 191/512 | +4.6875pp | +0.06680 | 16 -> 40 | 32 -> 64 | 32 -> 0 | + +统计结果: + +- 精确 McNemar 双侧 `p=0.0018416`。 +- paired bootstrap 95% 区间:`[+1.953125pp, +7.6171875pp]`,不包含 0。 +- baseline reward:`0.42617`。 +- durable reward:`0.49297`。 + +该结果满足大样本固定测试门槛:512 条未参与前序调参或确认,准确率提升超过 +4 个百分点,且 95% 区间不跨 0。 + +## 128 个训练组扩展实验 + +配置:128 个训练组、50% 故障、`lr=2e-5`,在全新的官方 +`test[768:1024]` 上评测 256 条: + +| seed | baseline 正确 | durable 正确 | 准确率差 | reward 差 | 配对翻转 | 有效 step | 丢失组 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 20261127 | 92/256 | 116/256 | +9.375pp | +0.13516 | 12 -> 36 | 64 -> 128 | 64 -> 0 | + +统计结果: + +- 精确 McNemar 双侧 `p=0.0007173`。 +- paired bootstrap 95% 区间:`[+4.296875pp, +14.453125pp]`,不包含 0。 +- baseline reward:`0.47578`。 +- durable reward:`0.61094`。 + +把训练规模从 64 组扩展到 128 组后,收益没有消失,反而更大;同时仍然保持 +`0 lost groups`,有效 optimizer update 从 64 提升到 128。 + +## 当前结论 + +已经证明: + +1. durable 在 25% 和 50% 故障率下都保持 `0 lost groups`。 +2. 在 50% 故障、64 组同采样预算下,有效 optimizer update 从 32 提升到 64。 +3. 50% 故障的调参切分上出现 `+13.28125pp` 的统计显著任务收益。 +4. 两个独立确认种子在未参与调参的测试切分上均为正收益,平均准确率 + `+2.34375pp`,平均 reward `+0.040625`。 +5. 512 条独立测试上准确率 `+4.6875pp`、reward `+0.06680`, + McNemar `p=0.00184`,95% 区间不跨 0。 +6. 128 个训练组、256 条全新测试上准确率 `+9.375pp`、reward `+0.13516`, + McNemar `p=0.0007173`,95% 区间不跨 0。 + +尚未证明: + +1. 真实训练 cookbook 中 checkpoint commit 与 rollout journal 的端到端事务。 +2. 无故障路径的吞吐、存储和恢复开销。 +3. 更大模型、多卡分布式训练下的恢复并发与 adapter 生命周期。 + +当前可以作为“高故障率下恢复完整组带来一致任务收益趋势”的证据,但不能宣称在 +所有故障率下都稳定提升模型质量。 diff --git a/review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md b/review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md new file mode 100644 index 000000000..6343f926a --- /dev/null +++ b/review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md @@ -0,0 +1,120 @@ +# Qwen NPU Checkpoint 强杀验证结果 + +日期:2026-11-19 + +## 结论 + +真实 Qwen3-0.6B LoRA 训练进程在 4 个 checkpoint 事务边界执行 Linux `SIGKILL`, +全部恢复成功: + +| 强杀边界 | 进程返回码 | 恢复 checkpoint | optimizer step | lease 重交付 | +|---|---:|---|---:|---| +| optimizer step 后、adapter 保存前 | `-9` | `step-0` | 空 | 同一 lease,2 行 | +| 临时 adapter/optimizer 保存后、发布前 | `-9` | `step-0` | 空 | 同一 lease,2 行 | +| checkpoint 原子发布后、journal commit 前 | `-9` | `step-0` | 空 | 同一 lease,2 行 | +| checkpoint journal commit 后 | `-9` | `step-1` | `[1]` | 不重交付 | + +该结果证明 checkpoint、optimizer state、batch lease 和 commit journal 在真实 NPU +训练进程被强杀后保持一致的提交/回退语义。 + +## 环境 + +- 主机:A2 `e1f3eeac3fc6` +- 设备:Ascend 910B4,32 GB HBM,单卡 `npu:0` +- Python:3.10.12 +- torch:2.10.0+cpu +- torch_npu:2.10.0 +- transformers:5.20.2 +- peft:0.21.3 +- 模型:`/workspace/shared_assets/models/Qwen/Qwen3-0.6B` +- 训练:LoRA rank 8,BF16,真实 Qwen forward/backward,AdamW optimizer step +- 数据:官方 GSM8K `train.jsonl` 第一条记录 + +为保证 GRPO 组存在非零 advantage,探针使用 GSM8K 标准问题及固定正确/错误 completion +对。模型前向、反向、AdamW 更新、LoRA adapter 保存、optimizer checkpoint 和进程 +SIGKILL 都是真实执行,不是 mock。 + +## 事务判定 + +### 未提交边界 + +以下三个边界恢复后都选择上一份 `step-0` checkpoint: + +1. 内存中已经完成 optimizer step,但尚未保存。 +2. 新 adapter 和 optimizer 已完整写入临时目录,但尚未原子发布。 +3. 新 checkpoint 已原子发布为 `step-1`,但 journal 尚未记录 commit。 + +三者共同验证: + +- 恢复后的 LoRA 权重 digest 等于 `step-0`。 +- optimizer state 为空,未泄漏内存中那一次 AdamW step。 +- 同一个 batch lease 被重新交付 2 行。 +- 临时或已发布但未提交的 `step-1` 不会成为恢复依据。 + +### 已提交边界 + +journal commit 后 `SIGKILL`,恢复结果: + +- 选择 journal 中登记的 `step-1`。 +- LoRA digest 与训练后内存权重完全一致。 +- optimizer step 恢复为 `[1]`。 +- lease 已清除。 +- 同一 batch 不再交付,`redelivered_rows=0`。 + +## 产物 + +探针: + +```text +review/a2/run_npu_checkpoint_kill_probe.py +``` + +完整结果: + +```text +review/a2/npu-checkpoint-kill-results/npu-checkpoint-kill-20261119/ +``` + +PR 可审查摘要: + +```text +review/a2/npu-checkpoint-kill-evidence-20261119/ +``` + +关键文件: + +```text +report.json +run.log +*/ready.json +*/worker.log +*/verify.json +*/verify.log +*/checkpoints/step-0/ +*/checkpoints/step-1/ +*/resume/rollout.jsonl +*/resume/objects/ +``` + +打包文件: + +```text +review/a2/npu-checkpoint-kill-results/npu-checkpoint-kill-20261119.tar.gz +``` + +SHA-256: + +```text +探针:A082C5A67037FE305B98CA91FE4DCCA493A762C24C44103E3B3E65394A615EAB +结果包:4CCBA9F9B55657E9288838E8C58E489DC19815F07C94E863869D3481DC6EF968 +``` + +本地与 A2 上的探针 SHA-256 一致。 + +## 尚未覆盖 + +- checkpoint 目录位于 A2 本地 overlay 文件系统,不是可写 NFS、GlusterFS 或对象存储。 +- 当前是单卡 LoRA,不是多卡 HCCL/FSDP2 或全参数训练。 +- 当前探针使用真实训练 step 和真实 checkpoint,但尚未接入完整 Twinkle training + cookbook 的 optimizer/scheduler/DataLoader 全量状态。 +- 未验证网络存储延迟、超时、连接重置和对象存储最终一致性。 diff --git a/review/a2/PR399_RESULTS_20261119.md b/review/a2/PR399_RESULTS_20261119.md new file mode 100644 index 000000000..392af1c46 --- /dev/null +++ b/review/a2/PR399_RESULTS_20261119.md @@ -0,0 +1,160 @@ +## 目标 + +把 streaming rollout 的断点恢复升级为 Group-Atomic Durable GRPO: + +- 恢复后保留完整 GRPO 组; +- group 从准入到训练固定 behavior policy 和 adapter; +- 禁止旧组用新 policy 补采成员; +- batch lease 与训练 checkpoint 建立可验证关联; +- 工具副作用无法证明幂等时 fail closed。 + +## 核心改动 + +- 新增 hash-chain JSONL journal、对象 SHA-256 校验和原子写入。 +- `DurableJournal` 增加线程锁、跨进程文件锁和写入失败回滚,避免并发 writer + 分叉 hash chain。 +- `StreamingDriver` 保存 prompt、未完成组、ready 组、DataLoader state 与 batch lease。 +- group 固定 `policy_version + adapter_path`;恢复、no-slot retry 和成员补采沿用同一绑定。 +- ready group 超 staleness 时整组淘汰,禁止混入新策略。 +- `commit_batch(checkpoint_ref, manifest)` 记录训练 checkpoint、batch 和 policy versions; + 空 checkpoint reference 被拒绝。 +- `ClientCheckpointManager` 保留历史 adapter path;episode 每次采样显式使用绑定路径。 +- `MultiTurnRollout` 保存/恢复 token 真值、tool loop 状态和 LocalEnv workspace。 +- 工具 effect 使用 intent/result 边界;无法确认结果时拒绝不安全恢复。 + +核心生产代码新增约 1100 行,低于 2000 行预算。 + +## 验证结果 + +### 1. 聚焦回归 + +- 本地:`33 passed` +- A2 Python 3.10:`33 passed` + +新增边界覆盖: + +1. 无故障等价与 journal/object 开销; +2. 真实 torch optimizer checkpoint 事务; +3. Linux `SIGKILL` 五阶段恢复; +4. exactly-once lease/commit; +5. journal 截断、损坏、SHA 错误、ENOSPC、rename 中断和并发 writer; +6. Env 无恢复能力时 fail closed; +7. 非幂等工具不重复执行; +8. adapter 缺失、路径复用和 staleness 淘汰。 + +### 2. 真实 Qwen + NPU checkpoint 强杀 + +A2 Ascend 910B4、Qwen3-0.6B、LoRA rank 8、BF16、官方 GSM8K: + +| 强杀边界 | 进程返回码 | 恢复结果 | +|---|---:|---| +| optimizer step 后、adapter 保存前 | `-9` | 恢复 `step-0`,同一 lease 重交付 2 行 | +| 临时 adapter/optimizer 保存后 | `-9` | 临时 checkpoint 不生效,恢复 `step-0` | +| checkpoint 原子发布后、journal commit 前 | `-9` | 已发布 checkpoint 不生效,恢复 `step-0` | +| journal commit 后 | `-9` | 恢复 `step-1`,optimizer step `[1]`,不再交付 | + +四个场景的 LoRA 权重 digest 和 optimizer state 均通过恢复校验。未提交更新不会泄漏, +已提交 batch 不会重复训练。 + +### 3. A2 Qwen 真实采样进程恢复 + +- 24 个已采样 token 逐值保留; +- token/labels/mask/old logprob 不重新编码; +- 恢复后继续采样 16 token,logprob 有限; +- LocalEnv 恢复后读到 `turn-1-durable`。 + +### 4. 无故障等价与开销 + +确定性无故障控制: + +- baseline 与 durable 均为 8 次 optimizer update、0 丢失组; +- 训练信号逐值一致; +- 16 条评测样本逐值一致; +- `accuracy_delta=0`、`reward_delta=0`。 + +A2 本地文件系统开销: + +| 指标 | 结果 | +|---|---:| +| journal append | `10.36 ms/event` | +| journal 吞吐 | `96.55 events/s` | +| journal 存储 | `530.56 B/event` | +| object save | `0.55 ms/object` | +| 存储放大 | `1.0326x` | + +4 个独立进程并发写 200 条 journal,sequence 连续且 hash chain 有效。 + +### 5. GSM8K 故障恢复训练 A/B + +对照为“故障点丢弃整个 ready group”与“durable 保留同一 policy 的完整组”。 +使用官方 GSM8K、Qwen3-0.6B、LoRA、单卡 910B4。 + +25% 故障率下最终质量收益不稳定,因此不作为主要结论。 + +50% 故障率、64 个训练组、512 条未参与调参的官方测试: + +| 指标 | baseline | durable | 差值 | +|---|---:|---:|---:| +| 准确率 | `167/512` | `191/512` | `+4.6875pp` | +| reward | `0.42617` | `0.49297` | `+0.06680` | +| 有效 optimizer step | `32` | `64` | `+32` | +| 丢失完整组 | `32` | `0` | `-32` | + +精确 McNemar 双侧 `p=0.0018416`;paired bootstrap 95% 区间 +`[+1.953125pp, +7.6171875pp]`。 + +扩展到 128 个训练组、50% 故障,并在全新的官方 `test[768:1024]` 上评测 256 条: + +| 指标 | baseline | durable | 差值 | +|---|---:|---:|---:| +| 准确率 | `92/256` | `116/256` | `+9.375pp` | +| reward | `0.47578` | `0.61094` | `+0.13516` | +| 有效 optimizer step | `64` | `128` | `+64` | +| 丢失完整组 | `64` | `0` | `-64` | + +精确 McNemar 双侧 `p=0.0007173`;paired bootstrap 95% 区间 +`[+4.296875pp, +14.453125pp]`。 + +两个独立确认种子在未参与调参的测试切分上分别取得 `+2.34375pp`,方向一致。 + +## 结论边界 + +已经证明: + +- 真实 Qwen/NPU 训练进程强杀后,模型 checkpoint、optimizer、lease 和 journal + 保持提交/回退一致; +- 不提交的 optimizer step 不会泄漏,已提交 batch 不会重复训练; +- 无故障路径质量等价; +- 50% 组丢失故障下,durable 机制显著提高固定预算下的有效训练组和 GSM8K 指标。 + +尚未证明: + +- GSM8K A/B 使用独立训练脚本模拟“组被丢弃/被保留”,尚未把完整故障注入接到 + 真实 Twinkle training cookbook 的 `StreamingDriver + commit_batch`; +- 尚未完成可写 NFS/对象存储下的 lease/journal/adapter 故障矩阵; +- 尚未完成多卡 HCCL/FSDP2 和更大模型验证; +- agent-program harness 及无法 checkpoint 的远端正环境继续 fail closed。 + +因此本 PR 当前结论限定为“故障条件下保留完整 GRPO 组、维持事务一致性并改善 +固定预算训练收益”,不宣称所有故障率或生产存储下均无条件提升。 + +## 复现与证据 + +- `review/a2/BOUNDARY_TEST_RESULTS_20261119.md` +- `review/a2/GSM8K_AB_20261118.md` +- `review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md` +- `review/a2/npu-checkpoint-kill-evidence-20261119/` +- `review/a2/run_npu_checkpoint_kill_probe.py` +- `review/a2/run_grpo_reward_ab.py` +- `review/a2/run_checkpoint_transaction_probe.py` +- `review/a2/run_kill_phase_probe.py` +- `review/a2/run_resume_overhead_bench.py` + +完整 A2 结果位于本地验证目录,不包含权重和 optimizer 二进制。 + +## 希望 maintainer 确认 + +1. 是否接受 group 级固定 `state_key + policy_version + adapter_path`。 +2. 是否接受 `commit_batch(checkpoint_ref, manifest)` 作为训练 checkpoint 与 rollout + lease 的关联接口。 +3. 是否将 Env 恢复能力作为现有 `Env` 扩展点,还是拆成独立 `ResumableEnv` protocol。 diff --git a/review/a2/README.md b/review/a2/README.md index d78ffa769..f69a9a40e 100644 --- a/review/a2/README.md +++ b/review/a2/README.md @@ -21,7 +21,12 @@ cd $STAGE /workspace/npu-ai-env/bin/python review/a2/run_group_yield_probe.py /workspace/npu-ai-env/bin/python review/a2/run_npu_resume_probe.py \ --root $STAGE/results/npu-probe +/workspace/npu-ai-env/bin/python review/a2/run_npu_checkpoint_kill_probe.py \ + --root $STAGE/results/npu-checkpoint-kill-20261119 \ + --train-jsonl $STAGE/data/gsm8k/train.jsonl ``` 成功标准:父进程观察到第一阶段返回 `-9/137`,第二阶段输出 JSON 中 `restored_exact=true`、`tool_observation=turn-1-durable`,且两轮 logprob 都是有限值。 +checkpoint 强杀探针的 4 个场景都应满足 `worker_returncode=-9` 和 `report.json` +中的 `ok=true`。 diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/README.md b/review/a2/npu-checkpoint-kill-evidence-20261119/README.md new file mode 100644 index 000000000..23ff2a509 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/README.md @@ -0,0 +1,33 @@ +# Qwen NPU Checkpoint 强杀证据摘要 + +本目录只保留可审查的 JSON 和日志,不包含 LoRA adapter、optimizer checkpoint、 +`.resume` 对象或 tar 包。 + +四个场景均为真实 Qwen3-0.6B LoRA/NPU 训练进程 `SIGKILL`: + +| 场景 | worker 返回码 | 恢复 checkpoint | lease 重交付 | +|---|---:|---|---| +| `optimizer_step_uncommitted` | `-9` | `step-0` | 2 行 | +| `adapter_temp_uncommitted` | `-9` | `step-0` | 2 行 | +| `checkpoint_promoted_uncommitted` | `-9` | `step-0` | 2 行 | +| `checkpoint_committed` | `-9` | `step-1` | 0 行 | + +汇总报告:`report.json` + +完整本地证据目录(不提交 Git): + +```text +review/a2/npu-checkpoint-kill-results/npu-checkpoint-kill-20261119/ +``` + +完整结果包 SHA-256: + +```text +4CCBA9F9B55657E9288838E8C58E489DC19815F07C94E863869D3481DC6EF968 +``` + +复现脚本: + +```text +review/a2/run_npu_checkpoint_kill_probe.py +``` diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/ready.json new file mode 100644 index 000000000..97bf31fc7 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/ready.json @@ -0,0 +1,102 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "78ef13e5483edc47cf05609288375178e8bc3873df184fa5288a51ef6b48655c", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/.step-1.tmp.12223", + "step": 1 + }, + "case": "adapter_temp_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "30c4bd15898aa3e6b8a71f89403a3928288e67ad80978871adff6839d3cdcc8c", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071756.4613972, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/.step-1.tmp.12223", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/verify.json new file mode 100644 index 000000000..41228831e --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/adapter_temp_uncommitted/verify.json @@ -0,0 +1,29 @@ +{ + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "adapter_temp_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "final_absent": true, + "pending_exists": true, + "pending_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/ready.json b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/ready.json new file mode 100644 index 000000000..b230d0c34 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/ready.json @@ -0,0 +1,104 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "231e61afd3c1807f0f2204a8515bc9251db0afa90cbc9bdac8cfaead51d72bc8", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/.step-1.tmp.13716", + "promoted_checkpoint_digest": "231e61afd3c1807f0f2204a8515bc9251db0afa90cbc9bdac8cfaead51d72bc8", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_committed", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "e7fcb9e91d68440d0d70c92d531865a9b134e4a04b33e9ce1f270b870174e2bd", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071825.787351, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/.step-1.tmp.13716", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/verify.json b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/verify.json new file mode 100644 index 000000000..8e326ed0e --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_committed/verify.json @@ -0,0 +1,29 @@ +{ + "actual_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "actual_optimizer_steps": [ + 1 + ], + "case": "checkpoint_committed", + "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "committed": true, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "expected_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "expected_optimizer_steps": [ + 1 + ], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": false, + "redelivered_rows": 0, + "restored_lease": null +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/ready.json new file mode 100644 index 000000000..82bd632ed --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/ready.json @@ -0,0 +1,104 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "29d259da8ac0a49ecc6fb77ca38e26f87102d60c6a5b9ff37e790ae75c831fb0", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.12974", + "promoted_checkpoint_digest": "29d259da8ac0a49ecc6fb77ca38e26f87102d60c6a5b9ff37e790ae75c831fb0", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_promoted_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "855331c3daff50e02d3bdef16354840c16b9cb5a2489b4880977fcb60a6287bb", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071790.8915293, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.12974", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/verify.json new file mode 100644 index 000000000..5b497015c --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/checkpoint_promoted_uncommitted/verify.json @@ -0,0 +1,29 @@ +{ + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "checkpoint_promoted_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "journal_left_it_uncommitted": true, + "promoted_exists": true, + "promoted_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/ready.json new file mode 100644 index 000000000..d43f19e41 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/ready.json @@ -0,0 +1,92 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": null, + "case": "optimizer_step_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "3505b9e140f9ee5cea63fb08e0141e27029c436bf7a22c1d34cbbd0a609d960e", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071722.3203564, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/.step-1.tmp.11484", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/verify.json new file mode 100644 index 000000000..908861c96 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/optimizer_step_uncommitted/verify.json @@ -0,0 +1,25 @@ +{ + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "optimizer_step_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" +} diff --git a/review/a2/npu-checkpoint-kill-evidence-20261119/report.json b/review/a2/npu-checkpoint-kill-evidence-20261119/report.json new file mode 100644 index 000000000..a8fe39fe8 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-evidence-20261119/report.json @@ -0,0 +1,561 @@ +{ + "cases": [ + { + "case": "optimizer_step_uncommitted", + "elapsed_s": 34.1689932346344, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": null, + "case": "optimizer_step_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "3505b9e140f9ee5cea63fb08e0141e27029c436bf7a22c1d34cbbd0a609d960e", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071722.3203564, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/.step-1.tmp.11484", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "optimizer_step_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/optimizer_step_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + }, + { + "case": "adapter_temp_uncommitted", + "elapsed_s": 34.1208872795105, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "78ef13e5483edc47cf05609288375178e8bc3873df184fa5288a51ef6b48655c", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/.step-1.tmp.12223", + "step": 1 + }, + "case": "adapter_temp_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "30c4bd15898aa3e6b8a71f89403a3928288e67ad80978871adff6839d3cdcc8c", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071756.4613972, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/.step-1.tmp.12223", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "adapter_temp_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/adapter_temp_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "final_absent": true, + "pending_exists": true, + "pending_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + }, + { + "case": "checkpoint_promoted_uncommitted", + "elapsed_s": 35.28103852272034, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "29d259da8ac0a49ecc6fb77ca38e26f87102d60c6a5b9ff37e790ae75c831fb0", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.12974", + "promoted_checkpoint_digest": "29d259da8ac0a49ecc6fb77ca38e26f87102d60c6a5b9ff37e790ae75c831fb0", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_promoted_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "855331c3daff50e02d3bdef16354840c16b9cb5a2489b4880977fcb60a6287bb", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071790.8915293, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.12974", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "checkpoint_promoted_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_promoted_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "journal_left_it_uncommitted": true, + "promoted_exists": true, + "promoted_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + }, + { + "case": "checkpoint_committed", + "elapsed_s": 35.085686445236206, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "231e61afd3c1807f0f2204a8515bc9251db0afa90cbc9bdac8cfaead51d72bc8", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/.step-1.tmp.13716", + "promoted_checkpoint_digest": "231e61afd3c1807f0f2204a8515bc9251db0afa90cbc9bdac8cfaead51d72bc8", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_committed", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "e7fcb9e91d68440d0d70c92d531865a9b134e4a04b33e9ce1f270b870174e2bd", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795071825.787351, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/.step-1.tmp.13716", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "actual_optimizer_steps": [ + 1 + ], + "case": "checkpoint_committed", + "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "committed": true, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-20261119/checkpoint_committed/checkpoints/step-1", + "expected_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "expected_optimizer_steps": [ + 1 + ], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": false, + "redelivered_rows": 0, + "restored_lease": null + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + } + ], + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "finished_unix": 1795071845.4710953, + "format": "twinkle.npu-checkpoint-kill-report.v1", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "ok": true, + "seed": 20261119, + "started_unix": 1795071706.805929, + "train_jsonl": "data/gsm8k/train.jsonl" +} diff --git a/review/a2/npu-checkpoint-kill-results/.gitignore b/review/a2/npu-checkpoint-kill-results/.gitignore new file mode 100644 index 000000000..d6b7ef32c --- /dev/null +++ b/review/a2/npu-checkpoint-kill-results/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/review/a2/run_checkpoint_transaction_probe.py b/review/a2/run_checkpoint_transaction_probe.py new file mode 100644 index 000000000..68c5974d1 --- /dev/null +++ b/review/a2/run_checkpoint_transaction_probe.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Exercise a real torch optimizer step around the durable batch commit boundary.""" + +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import argparse +import io +import json +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: E402,F401 +import run_gate0 # noqa: E402,F401 + +import torch # noqa: E402 +from twinkle_agentic.async_rl.rollout_resume import ResumeStore, atomic_write_bytes # noqa: E402 +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver # noqa: E402 +from twinkle_agentic.rollout.multi_turn import RolloutStatus # noqa: E402 + + +class _Future: + def __init__(self, value): + self._value = value + + def exception(self): + return None + + def result(self): + return self._value + + def add_done_callback(self, callback): + callback(self) + + +class _DoneRollout: + def step(self, trajectory, episode_id=None, session_wait=None): + row = dict(trajectory, turns=1) + sample = RolloutStatus( + episode_id=episode_id, + turns=1, + done=True, + token_lengths=(1, 1), + stop_reason="stop", + ) + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + return None + + +def _prompts(): + return [{"messages": [{"role": "user", "content": "trainer-checkpoint-probe"}]}] + + +def _save_trainer_state(model, optimizer, path: Path): + buffer = io.BytesIO() + torch.save( + { + "model": model.state_dict(), + "optimizer": optimizer.state_dict(), + }, + buffer, + ) + atomic_write_bytes(path, buffer.getvalue()) + + +def _load_trainer_state(model, optimizer, path: Path): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + + +def _ready_driver(root: Path): + store = ResumeStore(root, "trainer-transaction") + driver = StreamingDriver( + _prompts(), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + driver._start() + deadline = time.monotonic() + 5 + while driver._ready_rows < 2 and time.monotonic() < deadline: + time.sleep(0.01) + if driver._ready_rows != 2: + raise AssertionError("group did not become ready") + return store, driver + + +def _optimizer_step(model, optimizer): + optimizer.zero_grad(set_to_none=True) + loss = (model.weight - 3.0).square().sum() + loss.backward() + optimizer.step() + return float(loss.detach()) + + +def run(root: Path) -> dict: + root.mkdir(parents=True, exist_ok=True) + store, driver = _ready_driver(root / "uncommitted") + model = torch.nn.Linear(1, 1, bias=False) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + initial_path = root / "initial.pt" + _save_trainer_state(model, optimizer, initial_path) + initial_weight = float(model.weight.detach()) + try: + rows, facts = driver._next_batch() + loss = _optimizer_step(model, optimizer) + stepped_weight = float(model.weight.detach()) + uncommitted_state = driver.state_dict() + finally: + driver.close() + + recovered_store = ResumeStore(root / "uncommitted", "trainer-transaction") + recovered = StreamingDriver( + _prompts(), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=recovered_store, + ) + recovered_model = torch.nn.Linear(1, 1, bias=False) + recovered_optimizer = torch.optim.SGD(recovered_model.parameters(), lr=0.1) + _load_trainer_state(recovered_model, recovered_optimizer, initial_path) + recovered.load_state_dict(uncommitted_state) + redelivered_rows, redelivered_facts = recovered._next_batch() + recovered.close() + + committed_store, committed_driver = _ready_driver(root / "committed") + committed_model = torch.nn.Linear(1, 1, bias=False) + committed_optimizer = torch.optim.SGD(committed_model.parameters(), lr=0.1) + committed_path = root / "committed.pt" + try: + committed_rows, _ = committed_driver._next_batch() + _optimizer_step(committed_model, committed_optimizer) + _save_trainer_state(committed_model, committed_optimizer, committed_path) + committed_weight = float(committed_model.weight.detach()) + lease_id = committed_driver.commit_batch( + str(committed_path), + {"optimizer_step": 1, "loss": loss}, + ) + committed_state = committed_driver.state_dict() + finally: + committed_driver.close() + + after_commit_store = ResumeStore(root / "committed", "trainer-transaction") + after_commit = StreamingDriver( + _prompts(), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=after_commit_store, + ) + restored_committed_model = torch.nn.Linear(1, 1, bias=False) + restored_committed_optimizer = torch.optim.SGD(restored_committed_model.parameters(), lr=0.1) + _load_trainer_state(restored_committed_model, restored_committed_optimizer, committed_path) + after_commit.load_state_dict(committed_state) + no_redelivery = after_commit._next_batch() is None + after_commit.close() + + report = { + "ok": True, + "uncommitted": { + "initial_weight": initial_weight, + "stepped_weight": stepped_weight, + "optimizer_changed_weights": stepped_weight != initial_weight, + "recovered_weight": float(recovered_model.weight.detach()), + "rollback_to_previous_checkpoint": float(recovered_model.weight.detach()) == initial_weight, + "same_batch_redelivered": redelivered_rows == rows, + "same_facts_redelivered": redelivered_facts == facts, + }, + "committed": { + "committed_weight": committed_weight, + "restored_weight": float(restored_committed_model.weight.detach()), + "checkpoint_restored": float(restored_committed_model.weight.detach()) == committed_weight, + "lease_id": lease_id, + "lease_cleared": after_commit._lease is None, + "no_redelivery_after_commit": no_redelivery, + "journal_tail": [record.event.value for record in after_commit_store.journal.records()][-2:], + "committed_rows": len(committed_rows), + }, + } + report["ok"] = all( + ( + report["uncommitted"]["optimizer_changed_weights"], + report["uncommitted"]["rollback_to_previous_checkpoint"], + report["uncommitted"]["same_batch_redelivered"], + report["uncommitted"]["same_facts_redelivered"], + report["committed"]["checkpoint_restored"], + report["committed"]["lease_cleared"], + report["committed"]["no_redelivery_after_commit"], + report["committed"]["journal_tail"][-1] == "MODEL_CHECKPOINT_COMMITTED", + ) + ) + return report + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + report = run(args.root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/a2/run_focused_tests.py b/review/a2/run_focused_tests.py index d680cca61..11ddeb5f8 100644 --- a/review/a2/run_focused_tests.py +++ b/review/a2/run_focused_tests.py @@ -29,6 +29,7 @@ "tests/twinkle_agentic/test_turn_ledger_resume.py", "tests/twinkle_agentic/test_multi_turn_resume.py", "tests/twinkle_agentic/test_streaming_driver_resume.py", + "tests/twinkle_agentic/test_resume_boundaries.py", "tests/twinkle_agentic/test_tail_prefetch.py", "tests/twinkle_client/test_checkpoint_policy_history.py", ] diff --git a/review/a2/run_grpo_reward_ab.py b/review/a2/run_grpo_reward_ab.py new file mode 100644 index 000000000..18e2dd20e --- /dev/null +++ b/review/a2/run_grpo_reward_ab.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python3 +"""在 A2 上用官方 GSM8K 数据比较故障恢复的训练收益。 + +两次运行使用同一 Qwen3-0.6B、同一 LoRA 初态、同一 GSM8K train 子集、同一 test +子集和同一采样预算。普通恢复在故障点丢掉当前完整组;durable 保留该组并训练。 +奖励使用仓库标准 GSM8KAccuracyReward + GSM8KFormatReward。 +""" +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import argparse +import json +import random +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: E402,F401 +import run_gate0 # noqa: E402,F401 + +import torch # noqa: E402 +from peft import LoraConfig, get_peft_model # noqa: E402 +from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402 +from twinkle.advantage.grpo import GRPOAdvantage # noqa: E402 +from twinkle.loss.grpo import GRPOLoss # noqa: E402 +from twinkle.reward import GSM8KAccuracyReward, GSM8KFormatReward # noqa: E402 + + +def _device(): + import torch_npu # noqa: F401 + + torch.npu.set_device(0) + return torch.device("npu:0") + + +def _load_jsonl(path: str, limit: int, offset: int = 0) -> list[dict[str, str]]: + records = [] + with open(path, encoding="utf-8") as stream: + for index, line in enumerate(stream): + if index < offset: + continue + if line.strip(): + records.append(json.loads(line)) + if limit > 0 and len(records) >= limit: + break + if not records: + raise ValueError(f"no GSM8K records loaded from {path}") + return records + + +def _ground_truth(answer: str) -> str: + if "####" not in answer: + raise ValueError("GSM8K answer has no #### marker") + return answer.rsplit("####", 1)[1].strip().replace(",", "") + + +def _render(tokenizer, question: str, *, max_length: int) -> str: + messages = [ + { + "role": "system", + "content": "Solve the math problem with brief reasoning. Put the final answer within \\boxed{}.", + }, + {"role": "user", "content": question}, + ] + try: + return tokenizer.apply_chat_template( + messages, + tokenize=False, + add_generation_prompt=True, + enable_thinking=False, + truncation=True, + max_length=max_length, + ) + except TypeError: + return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + + +def _tokenized_prompt(tokenizer, device, question: str, *, max_length: int): + rendered = _render(tokenizer, question, max_length=max_length) + encoded = tokenizer(rendered, return_tensors="pt", truncation=True, max_length=max_length) + return {key: value.to(device) for key, value in encoded.items()} + + +def _tokenized_prompt_batch(tokenizer, device, questions: list[str], *, max_length: int): + rendered = [_render(tokenizer, question, max_length=max_length) for question in questions] + encoded = tokenizer( + rendered, + return_tensors="pt", + padding=True, + truncation=True, + max_length=max_length, + ) + return {key: value.to(device) for key, value in encoded.items()} + + +def _trajectory(question: str, completion: str, target: str) -> dict: + return { + "messages": [ + {"role": "user", "content": question}, + {"role": "assistant", "content": completion}, + ], + "user_data": [["ground_truth", target]], + } + + +def _rewards(question: str, texts: list[str], target: str, *, format_weight: float) -> tuple[list[float], dict]: + trajectories = [_trajectory(question, text, target) for text in texts] + accuracy = GSM8KAccuracyReward()(trajectories) + formatting = GSM8KFormatReward()(trajectories) + rewards = [acc + format_weight * fmt for acc, fmt in zip(accuracy, formatting, strict=True)] + return rewards, { + "accuracy": sum(accuracy) / len(accuracy), + "format": sum(formatting) / len(formatting), + "reward": sum(rewards) / len(rewards), + } + + +def _generate_group(model, tokenizer, device, prompt, *, group_size: int, max_new_tokens: int): + prompt_ids = prompt["input_ids"] + attention_mask = prompt["attention_mask"] + with torch.no_grad(): + output = model.generate( + input_ids=prompt_ids.repeat(group_size, 1), + attention_mask=attention_mask.repeat(group_size, 1), + max_new_tokens=max_new_tokens, + do_sample=True, + temperature=1.0, + top_p=0.95, + num_return_sequences=1, + return_dict_in_generate=True, + output_scores=True, + pad_token_id=tokenizer.pad_token_id, + ) + prompt_length = int(prompt_ids.shape[1]) + generated = output.sequences[:, prompt_length:] + old_logps: list[list[float]] = [] + for row in range(group_size): + row_logps = [] + for step, score in enumerate(output.scores): + token = int(generated[row, step]) + values = torch.log_softmax(score[row].float(), dim=-1) + row_logps.append(float(values[token].detach().cpu())) + old_logps.append(row_logps) + texts = [tokenizer.decode(row, skip_special_tokens=True) for row in generated] + return generated, old_logps, texts + + +def _train_group(model, optimizer, prompt, generated, old_logps, rewards): + group_size = generated.shape[0] + prompt_ids = prompt["input_ids"].repeat(group_size, 1) + attention_mask = prompt["attention_mask"].repeat(group_size, 1) + input_ids = torch.cat((prompt_ids, generated), dim=1) + attention_mask = torch.cat((attention_mask, torch.ones_like(generated)), dim=1) + labels = torch.full_like(input_ids, -100) + labels[:, prompt_ids.shape[1] :] = generated + completion_mask = torch.zeros_like(input_ids) + completion_mask[:, prompt_ids.shape[1] :] = 1 + + model.train() + outputs = model(input_ids=input_ids, attention_mask=attention_mask) + logits = outputs.logits.float() + shift_logits = logits[:, :-1] + shift_labels = labels[:, 1:] + gathered = torch.log_softmax(shift_logits, dim=-1).gather(-1, shift_labels.clamp(min=0).unsqueeze(-1)).squeeze(-1) + logps = torch.zeros_like(labels, dtype=torch.float32) + logps[:, 1:] = gathered + + advantages = GRPOAdvantage()._per_sequence(rewards, num_generations=group_size, scale="group") + result = GRPOLoss(epsilon=0.2, beta=0.0)( + {"labels": labels, "completion_mask": completion_mask}, + {"logps": logps}, + old_logps=old_logps, + advantages=advantages, + ) + loss = result["loss"] + optimizer.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_([parameter for parameter in model.parameters() if parameter.requires_grad], 1.0) + optimizer.step() + return { + "loss": float(loss.detach().cpu()), + "nontrivial": bool(torch.any(torch.abs(advantages) > 1e-8)), + } + + +def _evaluate( + model, + tokenizer, + device, + records, + *, + max_new_tokens: int, + prompt_max_length: int, + format_weight: float, + eval_batch_size: int, +) -> dict: + model.eval() + samples = [] + with torch.no_grad(): + for offset in range(0, len(records), eval_batch_size): + batch = records[offset : offset + eval_batch_size] + prompt = _tokenized_prompt_batch( + tokenizer, + device, + [record["question"] for record in batch], + max_length=prompt_max_length, + ) + output = model.generate( + **prompt, + max_new_tokens=max_new_tokens, + do_sample=False, + return_dict_in_generate=True, + pad_token_id=tokenizer.pad_token_id, + ) + prompt_length = int(prompt["input_ids"].shape[1]) + for row, record in enumerate(batch): + generated = output.sequences[row, prompt_length:] + text = tokenizer.decode(generated, skip_special_tokens=True) + target = _ground_truth(record["answer"]) + _, metrics = _rewards(record["question"], [text], target, format_weight=format_weight) + samples.append({**metrics, "completion": text}) + return { + "accuracy": sum(sample["accuracy"] for sample in samples) / len(samples), + "format": sum(sample["format"] for sample in samples) / len(samples), + "reward": sum(sample["reward"] for sample in samples) / len(samples), + "samples": samples, + } + + +def _reset_lora(model, initial: dict[str, torch.Tensor]) -> None: + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name in initial: + parameter.copy_(initial[name]) + + +def _run_variant( + model, + tokenizer, + device, + records, + *, + durable: bool, + attempts: int, + fault_period: int, + group_size: int, + max_new_tokens: int, + prompt_max_length: int, + format_weight: float, + lr: float, + seed: int, +) -> dict: + torch.manual_seed(seed) + torch.npu.manual_seed_all(seed) + random.seed(seed) + parameters = [parameter for parameter in model.parameters() if parameter.requires_grad] + optimizer = torch.optim.AdamW(parameters, lr=lr) + steps = 0 + nontrivial = 0 + lost_groups = 0 + metric_sums = {"accuracy": 0.0, "format": 0.0, "reward": 0.0} + sampled = 0 + losses = [] + started = time.perf_counter() + variant = "durable" if durable else "cursor_restart" + for attempt in range(attempts): + record = records[attempt % len(records)] + target = _ground_truth(record["answer"]) + prompt = _tokenized_prompt(tokenizer, device, record["question"], max_length=prompt_max_length) + generated, old_logps, texts = _generate_group( + model, tokenizer, device, prompt, group_size=group_size, max_new_tokens=max_new_tokens + ) + rewards, metrics = _rewards(record["question"], texts, target, format_weight=format_weight) + sampled += len(texts) + for key in metric_sums: + metric_sums[key] += metrics[key] * len(texts) + is_fault = fault_period > 0 and (attempt + 1) % fault_period == 0 + if is_fault and not durable: + lost_groups += 1 + continue + trained = _train_group(model, optimizer, prompt, generated, old_logps, rewards) + steps += 1 + nontrivial += int(trained["nontrivial"]) + losses.append(trained["loss"]) + if (attempt + 1) % 8 == 0 or attempt + 1 == attempts: + print( + f"[{variant}] {attempt + 1}/{attempts} attempts, {steps} steps, {lost_groups} lost groups", + file=sys.stderr, + flush=True, + ) + torch.npu.synchronize() + elapsed = time.perf_counter() - started + return { + "variant": variant, + "seed": seed, + "attempted_groups": attempts, + "train_steps": steps, + "lost_groups": lost_groups, + "sampled_sequences": sampled, + "nontrivial_advantage_groups": nontrivial, + "sample_accuracy": metric_sums["accuracy"] / max(sampled, 1), + "sample_format": metric_sums["format"] / max(sampled, 1), + "sample_reward": metric_sums["reward"] / max(sampled, 1), + "mean_loss": sum(losses) / max(len(losses), 1), + "elapsed_s": elapsed, + } + + +def run(args) -> dict: + if args.deterministic_control: + torch.use_deterministic_algorithms(True, warn_only=True) + train = _load_jsonl(args.train_jsonl, args.train_limit, args.train_offset) + test = _load_jsonl(args.test_jsonl, args.eval_limit, args.eval_offset) + device = _device() + tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) + if tokenizer.pad_token_id is None: + tokenizer.pad_token = tokenizer.eos_token + tokenizer.padding_side = "left" + base = AutoModelForCausalLM.from_pretrained( + args.model, trust_remote_code=True, dtype=torch.bfloat16, low_cpu_mem_usage=True + ).to(device) + model = get_peft_model( + base, + LoraConfig( + task_type="CAUSAL_LM", + r=args.lora_rank, + lora_alpha=args.lora_rank * 2, + lora_dropout=0.0 if args.deterministic_control else 0.05, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], + bias="none", + ), + ) + initial = {name: parameter.detach().clone() for name, parameter in model.named_parameters() if "lora_" in name} + eval_kwargs = { + "max_new_tokens": args.max_new_tokens, + "prompt_max_length": args.prompt_max_length, + "format_weight": args.format_weight, + "eval_batch_size": args.eval_batch_size, + } + before = None if args.skip_before else _evaluate(model, tokenizer, device, test, **eval_kwargs) + variant_kwargs = { + "attempts": args.attempts, + "fault_period": args.fault_period, + "group_size": args.group_size, + "lr": args.lr, + "seed": args.seed, + "max_new_tokens": args.max_new_tokens, + "prompt_max_length": args.prompt_max_length, + "format_weight": args.format_weight, + } + _reset_lora(model, initial) + baseline = _run_variant(model, tokenizer, device, train, durable=False, **variant_kwargs) + baseline_eval = _evaluate(model, tokenizer, device, test, **eval_kwargs) + _reset_lora(model, initial) + durable = _run_variant(model, tokenizer, device, train, durable=True, **variant_kwargs) + durable_eval = _evaluate(model, tokenizer, device, test, **eval_kwargs) + return { + "ok": True, + "dataset": "openai/grade-school-math GSM8K official JSONL", + "seed": args.seed, + "config": { + "train_limit": args.train_limit, + "train_offset": args.train_offset, + "eval_limit": args.eval_limit, + "eval_offset": args.eval_offset, + "attempts": args.attempts, + "fault_period": args.fault_period, + "group_size": args.group_size, + "max_new_tokens": args.max_new_tokens, + "prompt_max_length": args.prompt_max_length, + "format_weight": args.format_weight, + "eval_batch_size": args.eval_batch_size, + "lora_rank": args.lora_rank, + "lr": args.lr, + "skip_before": args.skip_before, + "deterministic_control": args.deterministic_control, + }, + "train_records": len(train), + "eval_records": len(test), + "model": args.model, + "device": str(device), + "before": before, + "baseline": baseline, + "baseline_eval": baseline_eval, + "durable": durable, + "durable_eval": durable_eval, + "accuracy_delta": durable_eval["accuracy"] - baseline_eval["accuracy"], + "reward_delta": durable_eval["reward"] - baseline_eval["reward"], + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--model", default="/workspace/shared_assets/models/Qwen/Qwen3-0.6B") + parser.add_argument("--train-jsonl", required=True) + parser.add_argument("--test-jsonl", required=True) + parser.add_argument("--train-limit", type=int, default=32) + parser.add_argument("--train-offset", type=int, default=0) + parser.add_argument("--eval-limit", type=int, default=32) + parser.add_argument("--eval-offset", type=int, default=0) + parser.add_argument("--attempts", type=int, default=32) + parser.add_argument("--fault-period", type=int, default=4) + parser.add_argument("--group-size", type=int, default=4) + parser.add_argument("--max-new-tokens", type=int, default=96) + parser.add_argument("--prompt-max-length", type=int, default=768) + parser.add_argument("--format-weight", type=float, default=0.2) + parser.add_argument("--eval-batch-size", type=int, default=8) + parser.add_argument("--lora-rank", type=int, default=8) + parser.add_argument("--lr", type=float, default=5e-5) + parser.add_argument("--seed", type=int, default=20261118) + parser.add_argument("--skip-before", action="store_true") + parser.add_argument("--deterministic-control", action="store_true") + parser.add_argument("--output", default="") + args = parser.parse_args() + report = run(args) + text = json.dumps(report, ensure_ascii=False, indent=2) + if args.output: + Path(args.output).write_text(text, encoding="utf-8") + print(text) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/a2/run_kill_phase_probe.py b/review/a2/run_kill_phase_probe.py new file mode 100644 index 000000000..abb941e87 --- /dev/null +++ b/review/a2/run_kill_phase_probe.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +"""SIGKILL a rollout process at each durable transaction boundary.""" + +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import argparse +import io +import json +import os +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: E402,F401 +import run_gate0 # noqa: E402,F401 + +import torch # noqa: E402 +from twinkle_agentic.async_rl.rollout_resume import ( # noqa: E402 + JournalEvent, + ResumeStore, + atomic_write_bytes, +) +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver # noqa: E402 +from twinkle_agentic.rollout.multi_turn import RolloutStatus # noqa: E402 + + +class _Future: + def __init__(self, value): + self._value = value + + def exception(self): + return None + + def result(self): + return self._value + + def add_done_callback(self, callback): + callback(self) + + +class _PendingFuture: + def add_done_callback(self, callback): + self.callback = callback + + +class _DoneRollout: + def step(self, trajectory, episode_id=None, session_wait=None): + row = dict(trajectory, turns=1) + sample = RolloutStatus( + episode_id=episode_id, + turns=1, + done=True, + token_lengths=(1, 1), + stop_reason="stop", + ) + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + return None + + +class _BlockingRollout(_DoneRollout): + def step(self, trajectory, episode_id=None, session_wait=None): + return _PendingFuture() + + +def _prompts(): + return [{"messages": [{"role": "user", "content": "kill-phase-probe"}]}] + + +def _ready_driver(root: Path): + store = ResumeStore(root, "kill-phase") + driver = StreamingDriver( + _prompts(), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + driver._start() + deadline = time.monotonic() + 5 + while driver._ready_rows < 2 and time.monotonic() < deadline: + time.sleep(0.01) + if driver._ready_rows != 2: + raise AssertionError("group did not become ready") + return store, driver + + +def _save_trainer_state(model, optimizer, path: Path): + buffer = io.BytesIO() + torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict()}, buffer) + atomic_write_bytes(path, buffer.getvalue()) + + +def _load_trainer_state(model, optimizer, path: Path): + state = torch.load(path, map_location="cpu", weights_only=False) + model.load_state_dict(state["model"]) + optimizer.load_state_dict(state["optimizer"]) + + +def _optimizer_step(model, optimizer): + optimizer.zero_grad(set_to_none=True) + (model.weight - 2.0).square().sum().backward() + optimizer.step() + + +def _signal_ready(root: Path): + (root / "ready").write_text("ready", encoding="utf-8") + while True: + time.sleep(60) + + +def _worker(phase: str, root: Path) -> None: + root.mkdir(parents=True, exist_ok=True) + if phase == "prompt_assigned": + store = ResumeStore(root, "kill-phase") + driver = StreamingDriver( + _prompts(), + _BlockingRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + driver._admit() + driver.state_dict() + _signal_ready(root) + + if phase == "group_ready": + _, driver = _ready_driver(root) + driver.state_dict() + _signal_ready(root) + + if phase == "batch_leased": + _, driver = _ready_driver(root) + driver._next_batch() + driver.state_dict() + _signal_ready(root) + + if phase in {"optimizer_step_uncommitted", "checkpoint_committed"}: + _, driver = _ready_driver(root) + model = torch.nn.Linear(1, 1, bias=False) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + initial = root / "initial.pt" + _save_trainer_state(model, optimizer, initial) + driver._next_batch() + _optimizer_step(model, optimizer) + if phase == "checkpoint_committed": + committed = root / "committed.pt" + _save_trainer_state(model, optimizer, committed) + driver.commit_batch(str(committed), {"optimizer_step": 1}) + driver.state_dict() + _signal_ready(root) + + +def _wait_for_marker(root: Path, process: subprocess.Popen, timeout: float = 30.0): + deadline = time.monotonic() + timeout + marker = root / "ready" + while time.monotonic() < deadline: + if marker.exists(): + return + if process.poll() is not None: + stdout, stderr = process.communicate(timeout=1) + raise RuntimeError(f"worker exited before marker: {stdout}\n{stderr}") + time.sleep(0.01) + raise TimeoutError(f"worker {process.pid} did not reach {marker}") + + +def _kill(process: subprocess.Popen): + if os.name == "nt": + process.kill() + else: + os.kill(process.pid, signal.SIGKILL) + process.wait(timeout=10) + + +def _new_driver(root: Path, rollout=None): + store = ResumeStore(root, "kill-phase") + driver = StreamingDriver( + _prompts(), + rollout or _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + state = store.load_object("driver", "kill-phase") + driver.load_state_dict(state) + return store, driver, state + + +def _verify(phase: str, root: Path) -> dict: + if phase == "prompt_assigned": + _, driver, state = _new_driver(root) + try: + result = { + "prompt_drawn": state["prompts_drawn"] == 1, + "group_restored": list(driver._groups) == ["0"], + "stable_state_key": driver._groups["0"] + .members[0] + .submit_traj["state_key"] + .startswith("kill-phase/group/0/"), + } + finally: + driver.close() + return result + + if phase == "group_ready": + _, driver, _ = _new_driver(root) + try: + rows, facts = driver._next_batch() + return {"rows": len(rows), "policy_versions": facts["policy_versions"]} + finally: + driver.close() + + if phase == "batch_leased": + _, driver, state = _new_driver(root) + try: + rows, facts = driver._next_batch() + return { + "rows": len(rows), + "same_lease": facts == state["lease"]["facts"], + "lease_id": driver._lease["lease_id"], + } + finally: + driver.close() + + model = torch.nn.Linear(1, 1, bias=False) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + checkpoint = root / ("committed.pt" if phase == "checkpoint_committed" else "initial.pt") + _load_trainer_state(model, optimizer, checkpoint) + if phase == "optimizer_step_uncommitted": + _, driver, state = _new_driver(root) + try: + rows, _ = driver._next_batch() + committed = driver.resume_store.journal.last( + state["lease"]["lease_id"], events=(JournalEvent.MODEL_CHECKPOINT_COMMITTED,) + ) + return { + "recovered_weight": float(model.weight.detach()), + "same_batch_redelivered": len(rows) == 2, + "checkpoint_not_committed": committed is None, + } + finally: + driver.close() + + store, driver, _ = _new_driver(root) + try: + commit_record = next( + record + for record in reversed(tuple(store.journal.records())) + if record.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED + ) + return { + "recovered_weight": float(model.weight.detach()), + "lease_cleared": driver._lease is None, + "no_redelivery": driver._next_batch() is None, + "checkpoint_committed": commit_record.state_key.startswith("kill-phase/batch/"), + } + finally: + driver.close() + + +def run(output_root: Path) -> dict: + phases = [ + "prompt_assigned", + "group_ready", + "batch_leased", + "optimizer_step_uncommitted", + "checkpoint_committed", + ] + report = {"ok": True, "phases": {}} + for phase in phases: + root = output_root / phase + if root.exists(): + shutil.rmtree(root) + root.mkdir(parents=True) + process = subprocess.Popen( + [sys.executable, str(Path(__file__).resolve()), "--worker", phase, "--root", str(root)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="replace", + ) + started = time.perf_counter() + _wait_for_marker(root, process) + _kill(process) + killed_after = time.perf_counter() - started + evidence = _verify(phase, root) + checks = { + "prompt_assigned": lambda item: all( + item[key] for key in ("prompt_drawn", "group_restored", "stable_state_key") + ), + "group_ready": lambda item: item["rows"] == 2, + "batch_leased": lambda item: item["rows"] == 2 and item["same_lease"], + "optimizer_step_uncommitted": lambda item: ( + item["same_batch_redelivered"] and item["checkpoint_not_committed"] + ), + "checkpoint_committed": lambda item: ( + item["lease_cleared"] and item["no_redelivery"] and item["checkpoint_committed"] + ), + } + ok = checks[phase](evidence) + report["phases"][phase] = { + "ok": ok, + "kill_after_s": killed_after, + "process_returncode": process.returncode, + "evidence": evidence, + } + report["ok"] = report["ok"] and ok + return report + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "--worker", + choices=[ + "prompt_assigned", + "group_ready", + "batch_leased", + "optimizer_step_uncommitted", + "checkpoint_committed", + ], + ) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-root", type=Path) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + if args.worker: + if args.root is None: + parser.error("--root is required in worker mode") + _worker(args.worker, args.root) + return 0 + if args.output_root is None or args.output is None: + parser.error("--output-root and --output are required outside worker mode") + report = run(args.output_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/a2/run_npu_checkpoint_kill_probe.py b/review/a2/run_npu_checkpoint_kill_probe.py new file mode 100644 index 000000000..6565c5008 --- /dev/null +++ b/review/a2/run_npu_checkpoint_kill_probe.py @@ -0,0 +1,706 @@ +#!/usr/bin/env python3 +"""SIGKILL a real Qwen LoRA training process around checkpoint boundaries.""" + +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import argparse +import hashlib +import importlib.metadata +import io +import json +import os +import platform +import shutil +import signal +import subprocess +import sys +import time +import traceback +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0", ROOT / "review" / "a2"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: E402,F401 +import run_gate0 # noqa: E402,F401 + +import torch # noqa: E402 +from peft import LoraConfig, PeftModel, get_peft_model # noqa: E402 +from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402 + +import run_grpo_reward_ab as train_lib # noqa: E402 +from twinkle_agentic.async_rl.rollout_resume import ( # noqa: E402 + JournalEvent, + ResumeStore, +) +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver # noqa: E402 +from twinkle_agentic.rollout.multi_turn import RolloutStatus # noqa: E402 + +RUN_ID = "npu-checkpoint-kill" +CASES = ( + "optimizer_step_uncommitted", + "adapter_temp_uncommitted", + "checkpoint_promoted_uncommitted", + "checkpoint_committed", +) + + +class _Future: + def __init__(self, value): + self._value = value + + def exception(self): + return None + + def result(self): + return self._value + + def add_done_callback(self, callback): + callback(self) + + +class _DoneRollout: + def step(self, trajectory, episode_id=None, session_wait=None): + row = dict(trajectory, turns=1) + sample = RolloutStatus( + episode_id=episode_id, + turns=1, + done=True, + token_lengths=(1, 1), + stop_reason="stop", + ) + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + return None + + +def _prompts(): + return [{"messages": [{"role": "user", "content": "npu-checkpoint-kill"}]}] + + +def _atomic_write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + pending = path.with_name(f".{path.name}.{os.getpid()}.tmp") + data = json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + with open(pending, "wb") as stream: + stream.write(data.encode("utf-8")) + stream.flush() + os.fsync(stream.fileno()) + os.replace(pending, path) + + +def _sync_tree(path: Path) -> None: + for item in sorted(path.rglob("*")): + if item.is_file(): + with open(item, "rb") as stream: + os.fsync(stream.fileno()) + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _to_cpu(value: Any) -> Any: + if torch.is_tensor(value): + return value.detach().cpu() + if isinstance(value, dict): + return {key: _to_cpu(item) for key, item in value.items()} + if isinstance(value, list): + return [_to_cpu(item) for item in value] + if isinstance(value, tuple): + return tuple(_to_cpu(item) for item in value) + return value + + +def _lora_digest(model) -> str: + digest = hashlib.sha256() + parameters = 0 + for name, parameter in sorted(model.named_parameters()): + if "lora_" not in name or not parameter.requires_grad: + continue + tensor = parameter.detach().float().cpu().contiguous() + digest.update(name.encode("utf-8")) + digest.update(str(tuple(tensor.shape)).encode("ascii")) + digest.update(tensor.numpy().tobytes()) + parameters += tensor.numel() + if parameters == 0: + raise RuntimeError("model has no trainable LoRA parameters") + return digest.hexdigest() + + +def _optimizer_steps(optimizer) -> list[int]: + steps = [] + for state in optimizer.state_dict()["state"].values(): + step = state.get("step") + if torch.is_tensor(step): + steps.append(int(step.detach().cpu())) + elif step is not None: + steps.append(int(step)) + return sorted(set(steps)) + + +def _checkpoint_digest(path: Path) -> str: + digest = hashlib.sha256() + for item in sorted(candidate for candidate in path.rglob("*") if candidate.is_file()): + relative = item.relative_to(path).as_posix() + digest.update(relative.encode("utf-8")) + digest.update(b"\0") + digest.update(item.read_bytes()) + return digest.hexdigest() + + +def _write_checkpoint( + model, + optimizer, + path: Path, + *, + step: int, + model_path: str, +) -> dict[str, Any]: + if path.exists(): + raise FileExistsError(f"checkpoint already exists: {path}") + path.mkdir(parents=True) + model.save_pretrained(str(path), safe_serialization=True) + torch.save(_to_cpu(optimizer.state_dict()), path / "optimizer.pt") + metadata = { + "format": "twinkle.npu-checkpoint-kill.v1", + "step": step, + "model": model_path, + "lora_digest": _lora_digest(model), + "optimizer_steps": _optimizer_steps(optimizer), + } + _atomic_write_json(path / "metadata.json", metadata) + _sync_tree(path) + return { + **metadata, + "path": str(path), + "checkpoint_digest": _checkpoint_digest(path), + } + + +def _promote_checkpoint(pending: Path, committed: Path) -> None: + if committed.exists(): + raise FileExistsError(f"checkpoint target already exists: {committed}") + os.replace(pending, committed) + descriptor = os.open(committed.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _device(): + import torch_npu # noqa: F401 + + torch.npu.set_device(0) + return torch.device("npu:0") + + +def _load_base(model_path: str, device): + tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + if tokenizer.pad_token_id is None: + tokenizer.pad_token = tokenizer.eos_token + tokenizer.padding_side = "left" + model = AutoModelForCausalLM.from_pretrained( + model_path, + trust_remote_code=True, + dtype=torch.bfloat16, + low_cpu_mem_usage=True, + ).to(device) + return tokenizer, model + + +def _trainable_model(model_path: str, device, seed: int): + torch.manual_seed(seed) + torch.npu.manual_seed_all(seed) + tokenizer, base = _load_base(model_path, device) + model = get_peft_model( + base, + LoraConfig( + task_type="CAUSAL_LM", + r=8, + lora_alpha=16, + lora_dropout=0.0, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], + bias="none", + ), + ) + return tokenizer, model + + +def _load_checkpoint_model(checkpoint: Path, model_path: str, device, seed: int): + torch.manual_seed(seed) + torch.npu.manual_seed_all(seed) + tokenizer, base = _load_base(model_path, device) + model = PeftModel.from_pretrained(base, str(checkpoint), is_trainable=True) + optimizer = torch.optim.AdamW( + [parameter for parameter in model.parameters() if parameter.requires_grad], + lr=5e-5, + weight_decay=0.0, + ) + optimizer.load_state_dict(torch.load(checkpoint / "optimizer.pt", map_location="cpu", weights_only=False)) + return tokenizer, model, optimizer + + +def _ready_driver(root: Path): + store = ResumeStore(root / "resume", RUN_ID) + driver = StreamingDriver( + _prompts(), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + driver._start() + deadline = time.monotonic() + 10 + while driver._ready_rows < 2 and time.monotonic() < deadline: + time.sleep(0.01) + if driver._ready_rows != 2: + raise AssertionError("group did not become ready") + return store, driver + + +def _response_logps(model, prompt, generated) -> list[list[float]]: + group_size = generated.shape[0] + prompt_ids = prompt["input_ids"].repeat(group_size, 1) + attention_mask = prompt["attention_mask"].repeat(group_size, 1) + input_ids = torch.cat((prompt_ids, generated), dim=1) + full_mask = torch.cat((attention_mask, torch.ones_like(generated)), dim=1) + model.eval() + with torch.no_grad(): + logits = model(input_ids=input_ids, attention_mask=full_mask).logits.float() + offset = prompt_ids.shape[1] - 1 + response_logits = logits[:, offset : offset + generated.shape[1]] + logps = ( + torch.log_softmax(response_logits, dim=-1) + .gather( + -1, + generated.unsqueeze(-1), + ) + .squeeze(-1) + ) + return logps.detach().cpu().tolist() + + +def _tokenize_group(tokenizer, device, question: str, target: str): + prompt = train_lib._tokenized_prompt(tokenizer, device, question, max_length=512) + correct = f"The final answer is \\boxed{{{target}}}." + wrong = "The final answer is \\boxed{0}." + encoded = [ + tokenizer(text, add_special_tokens=False).input_ids + [tokenizer.eos_token_id] for text in (correct, wrong) + ] + width = max(len(tokens) for tokens in encoded) + encoded = [tokens + [tokenizer.eos_token_id] * (width - len(tokens)) for tokens in encoded] + generated = torch.tensor(encoded, dtype=torch.long, device=device) + rewards, metrics = train_lib._rewards(question, [correct, wrong], target, format_weight=0.2) + if rewards[0] <= rewards[1]: + raise AssertionError(f"fixed GSM8K pair did not produce a nontrivial reward: {rewards}") + return prompt, generated, rewards, {"correct": correct, "wrong": wrong, **metrics} + + +def _container_info() -> dict[str, Any]: + def version(name: str) -> str | None: + try: + return importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + return None + + return { + "hostname": platform.node(), + "python": sys.version, + "torch": torch.__version__, + "torch_npu": version("torch-npu"), + "transformers": version("transformers"), + "peft": version("peft"), + } + + +def _worker(case: str, root: Path, model_path: str, train_jsonl: str, seed: int) -> int: + device = _device() + tokenizer, model = _trainable_model(model_path, device, seed) + optimizer = torch.optim.AdamW( + [parameter for parameter in model.parameters() if parameter.requires_grad], + lr=5e-5, + weight_decay=0.0, + ) + records = train_lib._load_jsonl(train_jsonl, 1, 0) + record = records[0] + target = train_lib._ground_truth(record["answer"]) + + checkpoints = root / "checkpoints" + initial_path = checkpoints / "step-0" + initial = _write_checkpoint(model, optimizer, initial_path, step=0, model_path=model_path) + initial_digest = initial["lora_digest"] + + store, driver = _ready_driver(root) + rows, facts = driver._next_batch() + lease_id = str(driver._lease["lease_id"]) + prompt, generated, rewards, trajectory = _tokenize_group( + tokenizer, + device, + record["question"], + target, + ) + old_logps = _response_logps(model, prompt, generated) + trained = train_lib._train_group(model, optimizer, prompt, generated, old_logps, rewards) + torch.npu.synchronize() + trained_digest = _lora_digest(model) + if trained_digest == initial_digest: + raise AssertionError("real NPU optimizer step did not change LoRA weights") + trained_steps = _optimizer_steps(optimizer) + if trained_steps != [1]: + raise AssertionError(f"optimizer state was not advanced exactly once: {trained_steps}") + + final_path = checkpoints / "step-1" + pending_path = checkpoints / f".step-1.tmp.{os.getpid()}" + candidate = None + committed_lease = None + if case != "optimizer_step_uncommitted": + candidate = _write_checkpoint(model, optimizer, pending_path, step=1, model_path=model_path) + if candidate["lora_digest"] != trained_digest: + raise AssertionError("saved adapter does not match the in-memory trained LoRA") + if case in {"checkpoint_promoted_uncommitted", "checkpoint_committed"}: + _promote_checkpoint(pending_path, final_path) + candidate["promoted_path"] = str(final_path) + candidate["promoted_checkpoint_digest"] = _checkpoint_digest(final_path) + if case == "checkpoint_committed": + committed_lease = driver.commit_batch( + str(final_path), + { + "optimizer_step": 1, + "adapter_path": str(final_path), + "lora_digest": trained_digest, + }, + ) + if committed_lease != lease_id: + raise AssertionError(f"commit returned {committed_lease!r}, expected {lease_id!r}") + + state = driver.state_dict() + marker = { + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "case": case, + "root": str(root), + "device": str(device), + "seed": seed, + "run_id": RUN_ID, + "lease_id": lease_id, + "batch_rows": len(rows), + "batch_facts": _to_cpu(facts), + "initial_checkpoint": initial, + "candidate_checkpoint": candidate, + "final_checkpoint_path": str(final_path), + "pending_checkpoint_path": str(pending_path), + "initial_lora_digest": initial_digest, + "trained_lora_digest": trained_digest, + "trained_optimizer_steps": trained_steps, + "optimizer_loss": trained["loss"], + "driver_state_path": str(store.root / "objects" / "driver"), + "driver_handed": state["handed"], + "trajectory": trajectory, + "container": _container_info(), + "marker_created_unix": time.time(), + } + _atomic_write_json(root / "ready.json", marker) + print(json.dumps({"case": case, "ready": True, "lease_id": lease_id}, ensure_ascii=False)) + sys.stdout.flush() + sys.stderr.flush() + os.kill(os.getpid(), signal.SIGKILL) + raise AssertionError("SIGKILL returned unexpectedly") + + +def _last_commit(store: ResumeStore, lease_id: str): + return store.journal.last( + lease_id, + events=(JournalEvent.MODEL_CHECKPOINT_COMMITTED,), + ) + + +def _verify(case: str, root: Path, model_path: str, seed: int) -> int: + marker = json.loads((root / "ready.json").read_text(encoding="utf-8")) + if marker["case"] != case: + raise AssertionError(f"marker case {marker['case']!r} != {case!r}") + device = _device() + store = ResumeStore(root / "resume", RUN_ID) + driver = StreamingDriver( + _prompts(), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + driver.load_state_dict() + recovered_batch = driver._next_batch() + lease_id = marker["lease_id"] + commit = _last_commit(store, lease_id) + committed = case == "checkpoint_committed" + + if committed: + if commit is None: + raise AssertionError("checkpoint_committed case has no commit journal record") + expected_checkpoint = Path(commit.payload["checkpoint"]) + expected_digest = marker["trained_lora_digest"] + expected_steps = [1] + if recovered_batch is not None: + raise AssertionError("committed batch was delivered again") + if driver._lease is not None: + raise AssertionError("committed lease was not cleared") + else: + if commit is not None: + raise AssertionError("uncommitted case unexpectedly has a checkpoint commit") + expected_checkpoint = Path(marker["initial_checkpoint"]["path"]) + expected_digest = marker["initial_lora_digest"] + expected_steps = [] + if recovered_batch is None: + raise AssertionError("uncommitted batch was not redelivered") + if driver._lease is None or str(driver._lease["lease_id"]) != lease_id: + raise AssertionError("uncommitted lease identity was not restored") + + _, model, optimizer = _load_checkpoint_model(expected_checkpoint, model_path, device, seed) + actual_digest = _lora_digest(model) + actual_steps = _optimizer_steps(optimizer) + if actual_digest != expected_digest: + raise AssertionError("loaded LoRA checkpoint does not match the transaction decision") + if actual_steps != expected_steps: + raise AssertionError(f"loaded optimizer steps {actual_steps} != expected {expected_steps}") + + orphan_check = None + if case == "adapter_temp_uncommitted": + pending = Path(marker["pending_checkpoint_path"]) + final = Path(marker["final_checkpoint_path"]) + if not pending.is_dir(): + raise AssertionError("temporary adapter checkpoint was not preserved for the probe") + if final.exists(): + raise AssertionError("temporary adapter unexpectedly reached its final path") + orphan_check = { + "pending_exists": True, + "pending_matches_trained": _checkpoint_digest(pending) + == marker["candidate_checkpoint"]["checkpoint_digest"], + "final_absent": True, + } + elif case == "checkpoint_promoted_uncommitted": + final = Path(marker["final_checkpoint_path"]) + if not final.is_dir(): + raise AssertionError("promoted checkpoint is missing") + orphan_check = { + "promoted_exists": True, + "promoted_matches_trained": _checkpoint_digest(final) + == marker["candidate_checkpoint"]["promoted_checkpoint_digest"], + "journal_left_it_uncommitted": commit is None, + } + + report = { + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": True, + "case": case, + "device": str(device), + "expected_checkpoint": str(expected_checkpoint), + "expected_lora_digest": expected_digest, + "actual_lora_digest": actual_digest, + "expected_optimizer_steps": expected_steps, + "actual_optimizer_steps": actual_steps, + "committed": committed, + "commit_checkpoint": None if commit is None else commit.payload["checkpoint"], + "redelivered_batch": recovered_batch is not None, + "redelivered_rows": 0 if recovered_batch is None else len(recovered_batch[0]), + "restored_lease": None if driver._lease is None else driver._lease["lease_id"], + "orphan_check": orphan_check, + "container": _container_info(), + } + driver.close() + _atomic_write_json(root / "verify.json", report) + print(json.dumps(report, ensure_ascii=False, indent=2)) + return 0 + + +def _safe_case_root(root: Path, case: str) -> Path: + root = root.resolve() + case_root = (root / case).resolve() + if case_root.parent != root: + raise ValueError(f"case root escaped output root: {case_root}") + if case_root.exists(): + shutil.rmtree(case_root) + case_root.mkdir(parents=True) + return case_root + + +def _wait_for_marker(process: subprocess.Popen, marker: Path, timeout: float) -> dict[str, Any]: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if marker.is_file(): + return json.loads(marker.read_text(encoding="utf-8")) + return_code = process.poll() + if return_code is not None: + raise RuntimeError(f"worker exited {return_code} before writing {marker}") + time.sleep(0.05) + raise TimeoutError(f"worker {process.pid} did not reach {marker} within {timeout}s") + + +def _run_child(arguments: list[str]) -> subprocess.Popen: + return subprocess.Popen( + [sys.executable, str(Path(__file__).resolve()), *arguments], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + ) + + +def run_case( + case: str, + root: Path, + model_path: str, + train_jsonl: str, + seed: int, + timeout: float, +) -> dict[str, Any]: + case_root = _safe_case_root(root, case) + marker_path = case_root / "ready.json" + worker = _run_child( + [ + "--mode", + "worker", + "--case", + case, + "--root", + str(case_root), + "--model", + model_path, + "--train-jsonl", + train_jsonl, + "--seed", + str(seed), + ] + ) + started = time.time() + try: + marker = _wait_for_marker(worker, marker_path, timeout) + output, _ = worker.communicate(timeout=20) + except Exception: + worker.kill() + output, _ = worker.communicate(timeout=20) + raise + return_code = worker.returncode + (case_root / "worker.log").write_text(output or "", encoding="utf-8") + if return_code not in (-9, 137): + raise AssertionError(f"worker was not killed by SIGKILL: returncode={return_code}\n{output}") + + verify = _run_child( + [ + "--mode", + "verify", + "--case", + case, + "--root", + str(case_root), + "--model", + model_path, + "--seed", + str(seed), + ] + ) + verify_output, _ = verify.communicate(timeout=timeout) + (case_root / "verify.log").write_text(verify_output, encoding="utf-8") + if verify.returncode != 0: + raise AssertionError(f"verification failed with {verify.returncode}\n{verify_output}") + verification = json.loads((case_root / "verify.json").read_text(encoding="utf-8")) + return { + "case": case, + "ok": bool(verification["ok"]), + "worker_returncode": return_code, + "worker_killed_by_sigkill": return_code in (-9, 137), + "marker": marker, + "verification": verification, + "elapsed_s": time.time() - started, + } + + +def _parent(args) -> int: + if args.cases: + selected = [item.strip() for item in args.cases.split(",") if item.strip()] + else: + selected = list(CASES) + invalid = sorted(set(selected) - set(CASES)) + if invalid: + raise SystemExit(f"unknown cases: {invalid}") + root = args.root.resolve() + root.mkdir(parents=True, exist_ok=True) + report = { + "format": "twinkle.npu-checkpoint-kill-report.v1", + "ok": False, + "started_unix": time.time(), + "model": args.model, + "train_jsonl": args.train_jsonl, + "seed": args.seed, + "container": _container_info(), + "cases": [], + } + try: + for case in selected: + result = run_case( + case, + root, + args.model, + args.train_jsonl, + args.seed, + args.timeout, + ) + report["cases"].append(result) + print( + f"[{case}] worker={result['worker_returncode']} " + f"redelivered={result['verification']['redelivered_batch']} " + f"steps={result['verification']['actual_optimizer_steps']}", + file=sys.stderr, + flush=True, + ) + report["ok"] = all(item["ok"] for item in report["cases"]) + except BaseException as exc: + report["error"] = f"{type(exc).__name__}: {exc}" + report["traceback"] = traceback.format_exc() + raise + finally: + report["finished_unix"] = time.time() + _atomic_write_json(root / "report.json", report) + if args.output: + _atomic_write_json(args.output, report) + print(json.dumps(report, ensure_ascii=False, indent=2)) + return 0 if report["ok"] else 1 + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--mode", choices=("parent", "worker", "verify"), default="parent") + parser.add_argument("--case", choices=CASES) + parser.add_argument("--cases", default="") + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path) + parser.add_argument("--model", default="/workspace/shared_assets/models/Qwen/Qwen3-0.6B") + parser.add_argument("--train-jsonl", default="data/gsm8k/train.jsonl") + parser.add_argument("--seed", type=int, default=20261119) + parser.add_argument("--timeout", type=float, default=300.0) + args = parser.parse_args() + if args.mode == "worker": + if not args.case: + parser.error("--case is required for worker mode") + return _worker(args.case, args.root.resolve(), args.model, args.train_jsonl, args.seed) + if args.mode == "verify": + if not args.case: + parser.error("--case is required for verify mode") + return _verify(args.case, args.root.resolve(), args.model, args.seed) + return _parent(args) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/a2/run_resume_overhead_bench.py b/review/a2/run_resume_overhead_bench.py new file mode 100644 index 000000000..57b5894bc --- /dev/null +++ b/review/a2/run_resume_overhead_bench.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Measure durable journal/object overhead and cross-process journal serialization.""" + +# ruff: noqa: E402, I001, T201 + +from __future__ import annotations + +import argparse +import json +import multiprocessing +import pickle +import statistics +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +for path in (ROOT / "src", ROOT / "review" / "gate0"): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import py310_compat # noqa: F401 +import run_gate0 # noqa: F401 + +from twinkle_agentic.async_rl.rollout_resume import DurableJournal, JournalEvent, ResumeStore + + +def _payload(): + return {"tokens": list(range(64)), "state_key": "run/group/attempt/member"} + + +def _writer_worker(root: str, writer_index: int, count: int): + journal = DurableJournal(Path(root) / "concurrent.jsonl") + for item in range(count): + journal.append(JournalEvent.PROMPT_ASSIGNED, f"run/{writer_index}/{item}", _payload()) + + +def _journal_benchmark(root: Path, iterations: int) -> dict: + payload = _payload() + memory_records = [] + started = time.perf_counter() + for index in range(iterations): + memory_records.append( + { + "seq": index, + "event": JournalEvent.PROMPT_ASSIGNED.value, + "state_key": f"run/{index}", + "payload": payload, + } + ) + memory_s = time.perf_counter() - started + + path = root / "journal" / "rollout.jsonl" + journal = DurableJournal(path) + started = time.perf_counter() + for index in range(iterations): + journal.append(JournalEvent.PROMPT_ASSIGNED, f"run/{index}", payload) + durable_s = time.perf_counter() - started + + started = time.perf_counter() + reopened = DurableJournal(path) + reopen_s = time.perf_counter() - started + if len(tuple(reopened.records())) != iterations: + raise AssertionError("journal lost records") + return { + "iterations": iterations, + "memory_s": memory_s, + "durable_s": durable_s, + "reopen_s": reopen_s, + "durable_us_per_append": durable_s / iterations * 1_000_000, + "durable_appends_per_s": iterations / durable_s, + "slowdown_vs_memory": durable_s / max(memory_s, 1e-9), + "journal_bytes": path.stat().st_size, + "bytes_per_append": path.stat().st_size / iterations, + "memory_records": len(memory_records), + } + + +def _object_benchmark(root: Path, iterations: int) -> dict: + value = {"tokens": list(range(256)), "messages": [{"role": "assistant", "content": "x" * 512}]} + started = time.perf_counter() + serialized = 0 + for _ in range(iterations): + serialized += len(pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)) + pickle_s = time.perf_counter() - started + + store = ResumeStore(root / "objects", "objects") + started = time.perf_counter() + for index in range(iterations): + store.save_object("episodes", f"episode-{index}", value) + durable_s = time.perf_counter() - started + object_bytes = sum(path.stat().st_size for path in (root / "objects" / "objects").rglob("*.resume")) + return { + "iterations": iterations, + "pickle_s": pickle_s, + "durable_s": durable_s, + "durable_us_per_object": durable_s / iterations * 1_000_000, + "objects_per_s": iterations / durable_s, + "slowdown_vs_pickle": durable_s / max(pickle_s, 1e-9), + "pickle_bytes": serialized, + "object_bytes": object_bytes, + "storage_amplification": object_bytes / max(serialized, 1), + } + + +def _concurrent_process_benchmark(root: Path, writers: int, per_writer: int) -> dict: + path = root / "concurrent.jsonl" + context = multiprocessing.get_context("spawn") + processes = [ + context.Process(target=_writer_worker, args=(str(root), index, per_writer)) for index in range(writers) + ] + started = time.perf_counter() + for process in processes: + process.start() + for process in processes: + process.join(timeout=60) + if process.exitcode != 0: + raise RuntimeError(f"journal writer exited with {process.exitcode}") + elapsed = time.perf_counter() - started + records = tuple(DurableJournal(path).records()) + return { + "writers": writers, + "per_writer": per_writer, + "elapsed_s": elapsed, + "records": len(records), + "contiguous_sequence": [record.seq for record in records] == list(range(writers * per_writer)), + "journal_bytes": path.stat().st_size, + } + + +def run(root: Path, iterations: int) -> dict: + root.mkdir(parents=True, exist_ok=True) + journal = _journal_benchmark(root, iterations) + objects = _object_benchmark(root, max(20, iterations // 10)) + concurrent = _concurrent_process_benchmark(root, writers=4, per_writer=max(10, iterations // 10)) + ok = ( + journal["durable_appends_per_s"] > 0 + and concurrent["records"] == concurrent["writers"] * concurrent["per_writer"] + and concurrent["contiguous_sequence"] + ) + return { + "ok": ok, + "python": sys.version, + "platform": sys.platform, + "journal": journal, + "objects": objects, + "concurrent_processes": concurrent, + "summary": { + "journal_overhead_factor": journal["slowdown_vs_memory"], + "object_overhead_factor": objects["slowdown_vs_pickle"], + "median_durable_events_per_s": statistics.median([journal["durable_appends_per_s"]]), + }, + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--iterations", type=int, default=500) + args = parser.parse_args() + report = run(args.root, args.iterations) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, ensure_ascii=False, indent=2)) + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/a2/summarize_gsm8k_ab.py b/review/a2/summarize_gsm8k_ab.py new file mode 100644 index 000000000..d1370eb1f --- /dev/null +++ b/review/a2/summarize_gsm8k_ab.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Summarize paired GSM8K A/B reports produced by run_grpo_reward_ab.py.""" +# ruff: noqa: T201 + +from __future__ import annotations +import argparse +import math +import statistics +from pathlib import Path + +import json + + +def _mcnemar_exact(baseline_only: int, durable_only: int) -> float: + discordant = baseline_only + durable_only + if discordant == 0: + return 1.0 + tail = sum(math.comb(discordant, count) for count in range(min(baseline_only, durable_only) + 1)) + return min(1.0, 2.0 * tail / (2**discordant)) + + +def _summarize(path: Path) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + baseline = [sample["accuracy"] for sample in report["baseline_eval"]["samples"]] + durable = [sample["accuracy"] for sample in report["durable_eval"]["samples"]] + if len(baseline) != len(durable): + raise ValueError(f"{path}: baseline and durable evaluation sizes differ") + + baseline_only = sum(left == 1 and right == 0 for left, right in zip(baseline, durable, strict=True)) + durable_only = sum(left == 0 and right == 1 for left, right in zip(baseline, durable, strict=True)) + return { + "file": path.name, + "seed": report["seed"], + "lr": report["config"]["lr"], + "eval_records": len(baseline), + "baseline_correct": int(sum(baseline)), + "durable_correct": int(sum(durable)), + "baseline_only": baseline_only, + "durable_only": durable_only, + "accuracy_delta": report["accuracy_delta"], + "reward_delta": report["reward_delta"], + "mcnemar_exact_p": _mcnemar_exact(baseline_only, durable_only), + "baseline_steps": report["baseline"]["train_steps"], + "durable_steps": report["durable"]["train_steps"], + "baseline_lost_groups": report["baseline"]["lost_groups"], + "durable_lost_groups": report["durable"]["lost_groups"], + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("reports", nargs="+", type=Path) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + + runs = [_summarize(path) for path in args.reports] + result = { + "runs": runs, + "mean_accuracy_delta": statistics.mean(run["accuracy_delta"] for run in runs), + "median_accuracy_delta": statistics.median(run["accuracy_delta"] for run in runs), + "mean_reward_delta": statistics.mean(run["reward_delta"] for run in runs), + "positive_accuracy_runs": sum(run["accuracy_delta"] > 0 for run in runs), + "positive_reward_runs": sum(run["reward_delta"] > 0 for run in runs), + "run_count": len(runs), + } + text = json.dumps(result, ensure_ascii=False, indent=2) + "\n" + if args.output: + args.output.write_text(text, encoding="utf-8") + print(text, end="") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json b/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json new file mode 100644 index 000000000..3d47f63c2 --- /dev/null +++ b/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json @@ -0,0 +1,6214 @@ +{ + "ok": true, + "dataset": "openai/grade-school-math GSM8K official JSONL", + "seed": 20261126, + "config": { + "train_limit": 64, + "train_offset": 0, + "eval_limit": 512, + "eval_offset": 256, + "attempts": 64, + "fault_period": 2, + "group_size": 4, + "max_new_tokens": 160, + "prompt_max_length": 768, + "format_weight": 0.2, + "eval_batch_size": 16, + "lora_rank": 8, + "lr": 2e-05, + "skip_before": true + }, + "train_records": 64, + "eval_records": 512, + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "device": "npu:0", + "before": null, + "baseline": { + "variant": "cursor_restart", + "seed": 20261126, + "attempted_groups": 64, + "train_steps": 32, + "lost_groups": 32, + "sampled_sequences": 256, + "nontrivial_advantage_groups": 20, + "sample_accuracy": 0.296875, + "sample_format": 0.4296875, + "sample_reward": 0.3828125, + "mean_loss": 0.22947604302316904, + "elapsed_s": 1218.6441411208361 + }, + "baseline_eval": { + "accuracy": 0.326171875, + "format": 0.5, + "reward": 0.4261718749999982, + "samples": [ + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Brady has:\n\n- 100 pennies = $100\n- 40 nickels = $40\n- 20 dimes = $20\n- 40 dollar bills = $40\n\nSo, the total amount in his piggy bank is:\n\n$$\n100 + 40 + 20 + 40 = \\boxed{200} \\text{ dollars}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Each 10-foot section of the redwood tree weighs **400 pounds**.\n- Termites ate **30%** of this redwood's wood.\n- The redwood is **200 feet tall**.\n\n---\n\n### Step 1: Find the total weight of the redwood tree\n\nSince each 10-foot section weighs 400 pounds, the total weight of the redwood tree is:\n\n$$\n\\text{Total weight} = 10 \\text{ feet} \\times 400 \\text{ pounds/ft} = 4000 \\text{ pounds}\n$$\n\n---\n\n### Step 2: Find the weight of the wood eaten by the termites\n\nThe termites ate **3" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Nancy owes:\n\n- **$0.50** for each of the 8 books.\n- **$2.00** for having at least one book overdue for a week.\n\nSo, the total amount she owes is:\n\n$$\n0.50 \\times 8 + 2.00 = 4.00 + 2.00 = \\boxed{6.00} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{6.00}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Andrea has 8 more apples than Jamal.\n- Andrea has half as many bananas as Jamal.\n- Jamal has 4 more bananas than apples.\n- Andrea has 52 apples.\n\nLet's define the variables:\n\n- Let $ A $ be the number of apples Andrea has.\n- Let $ B $ be the number of bananas Andrea has.\n- Let $ J $ be the number of bananas Jamal has.\n\nFrom the problem:\n\n1. Andrea has 8 more apples than Jamal: \n $ A = J + 8 $\n\n2. Andrea has half as many bananas as Jamal: \n $ B = \\frac{1}{2}J $\n\n3. Jamal has 4 more bananas than apples: \n $ J = A + 4" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that **two cups of flour are needed to make a dozen cookies**.\n\n- Today, Carla is making **36 cookies**.\n- Tomorrow, she is making **30 cookies**.\n\n---\n\n### Step 1: Find how many dozen cookies each cup makes\n\n$$\n\\frac{2 \\text{ cups}}{12 \\text{ cookies}} = \\frac{1}{6} \\text{ cup per cookie}\n$$\n\n---\n\n### Step 2: Calculate the total cups needed for today and tomorrow\n\n- **Today**: $ 36 \\text{ cookies} \\times \\frac{1}{6} \\text{ cup per cookie} = 6 \\text{ cups} $\n- **Tomorrow**: $ 30 \\text{ cookies}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- There are **9,300 pennies** in a cup.\n\nWe are asked to find the **total dollar amount** in a stack that contains **two-thirds** of the pennies.\n\n### Step 1: Find two-thirds of 9,300\n\n$$\n\\frac{2}{3} \\times 9,300 = 6,200\n$$\n\n### Step 2: Convert the amount to dollars\n\nSince 1 dollar = 100 pennies, we convert 6,200 pennies to dollars:\n\n$$\n6,200 \\text{ pennies} = 62 \\text{ dollars}\n$$\n\n### Final Answer:\n\n$$\n\\boxed{62}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Maddison starts with:\n\n- 5 boxes × 50 marbles = **250 marbles**\n\nShe then gets 20 more marbles from her friend.\n\nSo, total marbles now:\n\n$$\n250 + 20 = \\boxed{270}\n$$\n\n**Answer:** $\\boxed{270}$ marbles." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n1. Let the number of trees in **Chris's** yard be $ C $.\n\n2. Ferdinand has **half** the number of trees that Chris has, so:\n $$\n F = \\frac{1}{2}C\n $$\n\n3. Harry has **5 more than twice** the number of trees that Ferdinand has:\n $$\n H = 2F + 5\n $$\n\n4. Substitute $ F = \\frac{1}{2}C $ into the expression for $ H $:\n $$\n H = 2 \\left( \\frac{1}{2}C \\right) + 5 = C + 5\n $$\n\n5. Now, to find how" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carmen has $100.\n\nSamantha has $25 more than Carmen: \n$$ 100 + 25 = 125 $$\n\nDaisy has $50 more than Samantha: \n$$ 125 + 50 = 175 $$\n\nNow, add all three amounts together: \n$$ 100 + 125 + 175 = \\boxed{395} $$\n\nSo, all three girls have **$395** combined." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find how much more the total price of the house is than Mrs. Cruz's budget, we need to calculate the **total price** of the house and subtract the **budget**.\n\n### Step 1: Calculate the total price of the house\n\n- Selling price: $350,000 \n- Brokerage fee: 5% of $350,000 = $17,500 \n- Transfer fee: 12% of $350,000 = $42,000 \n\n**Total price = Selling price + Brokerage fee + Transfer fee** \n$$\n350,000 + 17,500 + 42,000 = 40" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find Mr. Tan's **net proceeds**, we need to subtract the **total costs** (transfer fees and brokerage fee) from the **selling price**.\n\n### Given:\n- Selling price = $400,000 \n- Transfer fees = 3% of selling price = $0.03 \\times 400,000 = 12,000 \n- Brokerage fee = 5% of selling price = $0.05 \\times 400,000 = 20,000 \n- Loan amount = $250,000 \n\n### Total costs:\n$$\n\\text{Total costs} = 12,000 + 20,00" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- It takes **20 minutes** to heat up the oil to **300 degrees**.\n- It then takes **40% longer** for the oil to reach **400 degrees**.\n- After warming the oil, it takes **5 minutes less** than the time to warm it up.\n\n---\n\n### Step 1: Time to heat up to 300 degrees\n- 20 minutes.\n\n---\n\n### Step 2: Time to heat up to 400 degrees (40% longer than 300)\n\n- 40% of 300 = 120\n- So, 300 + 120 = **420 degrees**\n\nSo, the time" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The real estate agent spent:\n\n- $5 on each newspaper ad: $5 × 50 = $250 \n- $75 on each television ad: $75 × 15 = $1,125 \n\nTotal cost: \n$250 + $1,125 = **$1,375**\n\n$$\n\\boxed{1375}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- The juggler can juggle **16 balls**.\n- **Half** of the balls are **golf balls**.\n- **Half** of the golf balls are **blue**.\n\n---\n\n### Step 1: Find the number of golf balls\n\nSince half of the balls are golf balls:\n\n$$\n\\text{Number of golf balls} = \\frac{1}{2} \\times 16 = 8\n$$\n\n---\n\n### Step 2: Find the number of blue golf balls\n\nSince half of the golf balls are blue:\n\n$$\n\\text{Number of blue golf balls} = \\frac{1}{2} \\times 8 = 4\n$$\n\n---\n\n### ✅ Final Answer:\n\n$$\n\\boxed{4" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mary buys 3 bags of M&Ms:\n\n- First bag: 300 M&Ms \n- Second bag: 300 + 12 = **312 M&Ms** \n- Third bag: Half of the first bag = 300 / 2 = **150 M&Ms**\n\nNow, add them together:\n\n$$\n300 + 312 + 150 = \\boxed{762} \\text{ M&Ms}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John has:\n\n- 2 houses \n- Each house has 3 bedrooms, and each bedroom has 2 windows \n- There are 4 additional windows in each house not connected to bedrooms\n\n### Step-by-step:\n\n1. **Number of windows in each house:**\n - 3 bedrooms × 2 windows = **6 windows per house**\n\n2. **Number of additional windows per house:**\n - 4 windows not connected to bedrooms\n\n3. **Total windows per house:**\n - 6 + 4 = **10 windows per house**\n\n4. **Total windows for 2 houses:**\n - 2 houses × 10 windows = **20 windows**\n\n### Final Answer:\n$$\n\\boxed{20}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The mother buys:\n\n- Cocoa: $4.20 \n- Laundry: $9.45 \n- Pasta: $1.35 \n\nTotal cost: \n$4.20 + $9.45 + $1.35 = $14.90 \n\nShe pays $20. \n\nChange: \n$20 - $14.90 = **$5.10** \n\n**Answer:** $\\boxed{5.10}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The **body** of the sweater takes **900 stitches**.\n- The **collar** takes **1/10** of the body's stitches.\n- The **rosette** takes **twice as many as the collar**.\n- The **total** number of stitches is **1800**.\n\n---\n\n### Step 1: Find the number of stitches for the collar\n\n$$\n\\text{Collar stitches} = \\frac{1}{10} \\times 900 = 90\n$$\n\n---\n\n### Step 2: Find the number of stitches for the rosette\n\n$$\n\\text{Rossette stitches} = 2 \\times 90 = 1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mrs. Rylan bought:\n\n- 20 packets of tomato seeds at $40 each: \n $ 20 \\times 40 = 800 $\n\n- 80 packets of celery seeds at $30 each: \n $ 80 \\times 30 = 2400 $\n\nTotal cost: \n$ 800 + 2400 = \\boxed{3200} $ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Sean has to memorize:\n\n- **2 scenes**, each with **twice the number of lines** in the first scene, but **a third of them** are his lines.\n- **1 solo song**, with **54 lines**, and **four-fifths** of them are his lines.\n\nLet's break it down step by step:\n\n---\n\n### **First Scene:**\n- Total lines: $2 \\times 54 = 108$\n- His lines: $ \\frac{1}{3} \\times 108 = 36 $\n\n---\n\n### **Second Scene:**\n- Total lines: $6 + 54 = 60$\n- His lines: $ \\frac{4}{5} \\times 60 = 4" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total cards: 80 \n- $ \\frac{2}{5} $ of the cards had the letter **A** \n- $ \\frac{1}{2} $ of the remaining had the letter **B** \n- $ \\frac{5}{8} $ of the rest had the letter **C** \n- The rest had the letter **D**\n\n---\n\n### Step 1: Find the number of cards with **A**\n\n$$\n\\frac{2}{5} \\times 80 = 32\n$$\n\nSo, 32 cards had **A**.\n\n---\n\n### Step 2: Find the number of cards remaining after **A**\n\n$$\n80 - 32 = 48\n$$\n\nSo" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Matthew digs:\n- 1 small hole in 3 minutes\n- 1 large hole in 10 minutes\n\nSo, the time to dig 1 small hole is **3 minutes**, and 1 large hole is **10 minutes**.\n\nTo find the time to dig **30 small holes** and **15 large holes**:\n\n- Time for small holes: $ 30 \\times 3 = 90 $ minutes\n- Time for large holes: $ 15 \\times 10 = 150 $ minutes\n\nTotal time = $ 90 + 150 = 240 $ minutes\n\nConvert minutes to hours: $ 240 \\div 60 = 4 $ hours\n\n**Final Answer:**" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told that the **sum of their current ages is 20**.\n\nIf we are to find the **sum of their ages in 10 years**, we add 10 to their current age.\n\nSo, the sum of their ages in 10 years will be:\n\n$$\n20 + 10 = \\boxed{30}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the current ages of Ruby and Sam as $ R $ and $ S $, respectively.\n\nWe are told:\n\n1. Ruby is 6 times older than Sam: \n $ R = 6S $\n\n2. In 9 years, Ruby will be 3 times as old as Sam: \n $ R + 9 = 3(S + 9) $\n\nNow, substitute $ R = 6S $ into the second equation:\n\n$$\n6S + 9 = 3(S + 9)\n$$\n\nSimplify both sides:\n\n$$\n6S + 9 = 3S + 27\n$$\n\nSubtract $ 3S $ from both sides:\n\n$$\n3S + 9 = 27\n$$\n\nSub" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Peter purchased:\n\n- 20 popsicles at $0.25 each: \n $ 20 \\times 0.25 = 5 $ dollars.\n\n- 4 ice cream bars at $0.50 each: \n $ 4 \\times 0.50 = 2 $ dollars.\n\nTotal cost: \n$ 5 + 2 = \\boxed{7} $ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A cobra has **70 spots**.\n- A mamba has **twice as many spots** as a cobra: $ 2 \\times 70 = 140 $ spots.\n- There are **40 cobras** and **60 mambas** in the park.\n\n---\n\n### Step 1: Calculate the total number of spots\n\n- Total spots from cobras: \n $ 40 \\times 70 = 2800 $\n\n- Total spots from mambas: \n $ 60 \\times 140 = 8400 $\n\n- **Total spots in the park**: \n $ 2800 + 8400 = 11" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Maddy is buying pizza for 12 team members and 3 coaches, and each person brings 2 guests. So, the total number of people is:\n\n$$\n12 + 3 + 2 \\times 3 = 12 + 3 + 6 = 21\n$$\n\nEach pizza serves 3 people, and each pizza costs $15.\n\nSo, the total cost is:\n\n$$\n\\frac{21}{3} \\times 15 = 7 \\times 15 = 105\n$$\n\n**Final Answer:** $\\boxed{105}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Each **topaz gemstone** is **1 inch** long.\n- Each **sterling silver bead** is **1/4 inch** long.\n- Each **necklace** is made to a **total length of 25 inches**.\n- Each necklace uses **8 topaz gemstones**.\n\n---\n\n### Step 1: Find the total length of the necklace\n\nSince the necklace is 25 inches long, and it uses 8 topaz gemstones, we can find the **length of one topaz gemstone**:\n\n$$\n\\text{Length of one topaz gemstone} = \\frac{25}{8} = 3.125 \\text{ inches}\n$$\n\n---\n\n### Step 2: Find the" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Alani wrote 20 stories in the first week.\n\nHer brother Braylen wrote 40 stories in the first week.\n\nHer sister Margot wrote 60 stories in the first week.\n\nIn the second week, each person doubled the number of stories they wrote in the first week.\n\n- Alani: $20 \\times 2 = 40$\n- Braylen: $40 \\times 2 = 80$\n- Margot: $60 \\times 2 = 120$\n\nNow, add the number of stories from all three weeks:\n\n$$\n40 + 80 + 120 = \\boxed{240}\n$$\n\nSo, the total number of stories they wrote altogether is $\\boxed{240" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ann is 9 years old, and her brother is **twice** her age. \nSo, the brother's current age is: \n$$ 2 \\times 9 = 18 \\text{ years old} $$\n\nIn **3 years**, the brother will be: \n$$ 18 + 3 = 21 \\text{ years old} $$\n\n**Final Answer:** $\\boxed{21}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kelly has:\n\n- 5 quarters = 5 × 25 = **125 cents**\n- 2 dimes = 2 × 10 = **20 cents**\n\nTotal amount she has: \n125 + 20 = **145 cents**\n\nShe buys a can of pop for **55 cents**\n\nSo, she will have: \n145 - 55 = **90 cents**\n\n**Answer:** $\\boxed{90}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told that a 76-star flag has:\n\n- 3 rows of 8 stars \n- 2 rows of 6 stars \n- The rest are 5-star rows\n\nLet's calculate the total number of 5-star rows:\n\n$$\n\\text{Number of 5-star rows} = 76 - (3 \\times 8 + 2 \\times 6)\n$$\n\n$$\n= 76 - (24 + 12) = 76 - 36 = 40\n$$\n\n### Final Answer:\n$$\n\\boxed{40}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Each flagstone weighs **75 pounds**, and the total weight capacity of the delivery truck is **2000 pounds**.\n\nWe are asked to find how many **trucks** are needed to transport **80 flagstones**.\n\n### Step 1: Calculate the weight of 80 flagstones\n$$\n80 \\text{ flagstones} \\times 75 \\text{ pounds/flagstone} = 6000 \\text{ pounds}\n$$\n\n### Step 2: Determine how many trucks are needed\nEach truck can carry **2000 pounds**.\n\n$$\n\\frac{6000 \\text{ pounds}}{2000 \\text{ pounds/truck}} = 3 \\text{ trucks}\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Speed of the **fast lane car** = 60 miles/hour \n- Speed of the **slow lane car** = half of the fast lane speed = $ \\frac{1}{2} \\times 60 = 30 $ miles/hour \n- Distance covered by the **fast lane car** = 480 miles \n\nWe are to find the **time** the **slow lane car** took to cover the same distance (480 miles).\n\n### Step 1: Use the formula for time = distance / speed\n\nFor the **slow lane car**:\n\n$$\n\\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{480}{30} = 1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Ali has **22 medals**.\n- Izzy has **5 less** than Ali, so:\n $$\n \\text{Izzy's medals} = 22 - 5 = 17\n $$\n- Together, they have:\n $$\n 22 + 17 = 39 \\text{ medals}\n $$\n- The problem states that **they have 10 times less** than the medals that have been given out for counting.\n\nSo, we can write:\n$$\n39 = \\frac{1}{10} \\times \\text{Total medals given out}\n$$\n$$\n\\text{Total medals given out} = 39 \\times" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 4 adults and 8 children = 12 people \n- 8 packets of chocolate bars \n- Each packet contains 5 chocolate bars \n- Each adult gets 6 chocolate bars \n- The rest (i.e., 8 - 4 = 4) are to be shared equally among the children\n\n### Step 1: Total chocolate bars\nEach packet has 5 bars, and there are 8 packets:\n$$\n8 \\times 5 = 40 \\text{ chocolate bars}\n$$\n\n### Step 2: Total chocolate bars given to adults\nEach adult gets 6 bars, and there are 4 adults:\n$$\n4 \\times 6 = 24 \\text{ bars}\n$$\n\n### Step 3:" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Susan works between **8 a.m. and 11 a.m.**, which is a total of **4 hours**. She pauses in between for **half an hour**, so the total time she works is:\n\n$$\n4 \\text{ hours} - 0.5 \\text{ hour} = 3.5 \\text{ hours}\n$$\n\nShe earns **$5 every 10 minutes**. So, in 3.5 hours, how many 10-minute intervals are there?\n\n$$\n3.5 \\text{ hours} \\times 60 \\text{ minutes/hour} = 210 \\text{ minutes}\n$$\n\n$$\n210 \\div 10 = 21 \\text{ intervals}\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Mike has **21 points**.\n- Jim has **3 points less than Mike**, so Jim has **21 - 3 = 18 points**.\n- Tony has **2 times more than Mike**, so Tony has **2 × 21 = 42 points**.\n\nNow, in the **fourth round**, every player gets an **extra point** if they have **over 20 points**.\n\n- Mike: 21 points → **21 > 20**, so he gets an extra point → **22 points**.\n- Jim: 18 points → **18 ≤ 20**, so no extra point.\n- Tony: 42 points → **42 > 20" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- The **oldest son is 8 years old**.\n- The **youngest son is half as old as the oldest**, so:\n $$\n \\text{Youngest son's age} = \\frac{8}{2} = 4 \\text{ years old}\n $$\n\n- The **total number of oranges** is 15.\n\n- The **number of oranges washed** is equal to the **sum of the ages of the two sons**.\n\n- The **oldest son** is 8, and the **youngest son** is 4.\n\n- So, the total number of oranges washed is:\n $$\n 8 + 4 = 12\n $$\n\n- The number" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Day 1:**\n - Pushups: 100\n - Squats: 50\n - Dumbbell presses: 20\n\n- **Day 2:**\n - Pushups: 100 + 20 = 120\n - Squats: 50 - 10 = 40\n - Dumbbell presses: 20 × 2 = 40\n\n- **Total activities done in two days:**\n - Pushups: 100 + 120 = 220\n - Squats: 50 + 40 = 90\n - Dumbbell" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Each person in the household consumes **0.2 kg of rice per meal**. \nThere are **5 members** in the household, and they eat rice **every lunch and dinner**, so **2 meals per person per week**.\n\n### Step 1: Calculate total rice consumption per week\n$$\n\\text{Total rice per week} = 5 \\, \\text{members} \\times 2 \\, \\text{meals per person} \\times 0.2 \\, \\text{kg per meal} = 2 \\, \\text{kg per week}\n$$\n\n### Step 2: Calculate how many weeks a 42 kg bag will last\n$$\n\\text{Number of weeks} = \\frac{42 \\, \\text" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Sam's total sales for the week are:\n\n- Monday: 0 crates \n- Tuesday: 15 crates \n- Wednesday: 12 crates \n- Thursday: 18 crates \n- Friday: 0 crates \n- Saturday: 20 crates \n\n**Total sales = 0 + 15 + 12 + 18 + 0 + 20 = 75 crates**\n\nSam's target was to sell **120 crates**.\n\n**Difference = 120 - 75 = 45 crates**\n\n**Answer:** $\\boxed{45}$ crates." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carmen starts with a bid of **$200**. The bids increase by **$50** each time, and she bids **after each of the 3 other people**. That means she bids **4 times** (including her own initial bid).\n\nSo, the total amount she wins is:\n\n$$\n200 + 50 \\times 4 = 200 + 200 = \\boxed{400}\n$$\n\n**Answer:** $\\boxed{400}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John drives 30 miles to work and 30 miles back each day. So, per day, he drives **60 miles**.\n\nHe drives **5 days a week** and **50 weeks a year**, so:\n\n$$\n\\text{Total miles per year} = 60 \\, \\text{miles/day} \\times 5 \\, \\text{days/week} \\times 50 \\, \\text{weeks/year} = 15,000 \\, \\text{miles}\n$$\n\nHe is charged **$2 per mile**:\n\n$$\n\\text{Total driving cost} = 15,000 \\, \\text{miles} \\times 2 \\, \\text{\\$/" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Peter wants to exercise for **twice the amount of time he exercised on Monday and Sunday combined**. On **Sunday**, he exercised for **23 minutes**, and on **Monday**, he exercised for **16 minutes**.\n\nSo, the total time he exercised on Monday and Sunday is:\n\n$$\n16 + 23 = 39 \\text{ minutes}\n$$\n\nHe wants to exercise for **twice** that amount:\n\n$$\n2 \\times 39 = 78 \\text{ minutes}\n$$\n\n**Answer:** $\\boxed{78}$ minutes." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "To determine how many pieces of paper are used in a 32-page tabloid, we need to understand how the folding and printing process works.\n\n- A **32-page tabloid** means **32 pages** are printed.\n- Each **page** is printed on **2 sides** of a single piece of paper.\n- Therefore, the total number of **paper pieces** used is:\n\n$$\n32 \\text{ pages} \\times 2 \\text{ sides per page} = 64 \\text{ pieces of paper}\n$$\n\n### Final Answer:\n$$\n\\boxed{64}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Annika started with $50.\n\nShe spent half of it on food and snacks: \n$$\n\\frac{1}{2} \\times 50 = 25\n$$\n\nThen she spent an additional $10 for rides: \n$$\n25 + 10 = 35\n$$\n\nSo, the amount left is: \n$$\n50 - 35 = \\boxed{15} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Elise has a collection of **250 books**.\n- Each book sells for **$20**.\n- She sold **twice as many books in the first year as she has sold in the current year**.\n- There are **currently 50 unsold books**.\n- Her **sales number this year is 45**.\n\n---\n\n### Step 1: Let the number of books sold in the **current year** be $ x $.\n\nThen, the number of books sold in the **first year** is $ 2x $.\n\n---\n\n### Step 2: Total books sold in the **two years** is:\n\n$$\nx + 2x = 3x\n$$\n\n---\n\n### Step 3" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Watson works a **10-hour shift** each day, **five days a week**, and earns **$10 per hour**. He also earns a **$300 bonus** each week if the company performs well.\n\n### Step 1: Calculate his weekly earnings\n- Hours per week: $10 \\, \\text{hours/day} \\times 5 \\, \\text{days/week} = 50 \\, \\text{hours/week}$\n- Earnings per week: $50 \\, \\text{hours} \\times \\$10/\\text{hour} = \\$500$\n\n### Step 2: Add the bonus\n- Bonus: \\$300\n- Total earnings for the week: \\$50" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John arm wrestles 20 people, and he beats **80%** of them. To find out how many people he **lost to**, we can calculate:\n\n$$\n\\text{Number of people lost to} = \\text{Total people} - \\text{Number of people he beat}\n$$\n\n$$\n\\text{Number of people lost to} = 20 - (0.80 \\times 20) = 20 - 16 = 4\n$$\n\n**Answer:** $\\boxed{4}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 60 loaves of bread are produced each day.\n- **2/3** of the loaves are sold in the **morning**.\n- The remaining **1/3** is sold in the **afternoon** and **evening** equally.\n\n### Step 1: Total loaves sold in the morning\n$$\n\\frac{2}{3} \\times 60 = 40 \\text{ loaves}\n$$\n\n### Step 2: Remaining loaves after morning sales\n$$\n60 - 40 = 20 \\text{ loaves}\n$$\n\n### Step 3: Half of the remaining loaves is sold in the afternoon\n$$\n\\frac{1}{2} \\times 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Joey loses **8 pounds in 4 weeks**.\n- Sandy wants to **lose the same amount of weight** as Joey, but **needs 4 weeks** to do so.\n- We are to find how many **weeks** it will take Sandy to lose the same amount of weight.\n\n---\n\n### Step 1: Find the rate at which Joey loses weight\n\nJoey loses **8 pounds in 4 weeks**.\n\nSo, the rate of weight loss per week is:\n\n$$\n\\frac{8 \\text{ pounds}}{4 \\text{ weeks}} = 2 \\text{ pounds per week}\n$$\n\n---\n\n### Step 2: Find how many weeks it will take Sandy to lose the same amount\n\nSandy needs to lose **8 pounds" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A tub of ice cream costs $13.\n- A packet of milk is sold at a **discount of $0.5**.\n- You buy **2 tubs of ice cream** and **4 packets of milk**.\n\n### Step 1: Calculate the cost of 2 tubs of ice cream\n- 1 tub = $13\n- 2 tubs = $13 × 2 = **$26**\n\n### Step 2: Calculate the cost of 4 packets of milk\n- 1 packet = $0.5 discount\n- 4 packets = $0.5 × 4 = **$2**\n\n### Step 3: Total cost\n- Ice cream: $26\n- Milk: $2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Helena's serum causes a person to grow an extra arm every 3 days and an extra leg every 5 days. After 15 days, we need to calculate how many limbs are added.\n\n- Number of arms added: \n $ \\frac{15}{3} = 5 $\n\n- Number of legs added: \n $ \\frac{15}{5} = 3 $\n\n- Total number of limbs added: \n $ 5 + 3 = 8 $\n\n**Answer:** $ \\boxed{8} $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n---\n\n### Step 1: Cost of Business Suits\n\n- Theo buys **6 business suits** at $100 each:\n $$\n 6 \\times 100 = 600\n $$\n\n---\n\n### Step 2: Cost of Suitcases\n\n- He buys **3 suitcases** at $50 each:\n $$\n 3 \\times 50 = 150\n $$\n\n---\n\n### Step 3: Cost of the Flight Ticket\n\n- The flight ticket costs **$700 more than 5 times the cost of a business suit**:\n $$\n 5 \\times 100 = 500\n $$\n " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There are **5 people** in the family.\n- **3 people** eat **3 eggs each day**.\n- The **remaining 2 people** eat **2 eggs each day**.\n- They eat **eggs every day**.\n\n### Step 1: Calculate daily egg consumption\n\n- 3 people × 3 eggs/day = **9 eggs/day**\n- 2 people × 2 eggs/day = **4 eggs/day**\n- Total daily consumption = 9 + 4 = **13 eggs/day**\n\n### Step 2: Calculate weekly consumption\n\n- 13 eggs/day × 7 days = **91 eggs/week**\n\n### Final Answer:\n\n$$\n\\boxed{91}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the following relationships:\n\n- Trent is 5 years older than Jane.\n- Jane is 3 years younger than Quinn.\n\nWe are also told that **Quinn is 30 years old**.\n\n---\n\n### Step 1: Express Jane's age in terms of Quinn.\n\nSince Jane is 3 years younger than Quinn, and Quinn is 30:\n\n$$\n\\text{Jane} = 30 - 3 = 27\n$$\n\n---\n\n### Step 2: Express Trent's age in terms of Jane.\n\nSince Trent is 5 years older than Jane:\n\n$$\n\\text{Trent} = 27 + 5 = 32\n$$\n\n---\n\n### ✅ Final Answer:\n\n$$\n\\boxed{32}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- **Currently, Cera is 46 years old.**\n- **Six years ago, Noah was half as old as Cera.**\n- **Six years ago, the population of Chile was 3000 times the age of Noah.**\n- **The population of Chile now is to be calculated.**\n\n---\n\n### Step 1: Determine Noah's age six years ago\n\nSix years ago, Noah was half as old as Cera.\n\n- Cera is currently 46 years old.\n- So, six years ago, Cera was $ 46 - 6 = 40 $ years old.\n- Noah was half as old as Cera: \n $$\n \\text{Noah's age six years" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the number of players on the **defense** be $ x $. \nThen: \n- The number of players on the **offense** is $ 2x $, \n- The number of players on the **special teams** is $ \\frac{1}{2}x $.\n\nWe are told that the total number of players is 105. So:\n\n$$\nx + 2x + \\frac{1}{2}x = 105\n$$\n\n$$\n\\left(1 + 2 + \\frac{1}{2}\\right)x = 105\n$$\n\n$$\n\\frac{3.5}{1}x = 105\n$$\n\n$$\nx = 105 \\div 3" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Martha invited:\n\n- 2 families with 6 people: $2 \\times 6 = 12$ people \n- 3 families with 4 people: $3 \\times 4 = 12$ people \n- Total invited people: $12 + 12 = 24$\n\n8 people couldn't come due to illness.\n\n1/4 of the 8 people had previous commitments, so 2 people had commitments.\n\nSo, the number of people who **show up** is:\n\n$$\n24 - 8 - 2 = 14\n$$\n\n**Answer:** $\\boxed{14}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Solomon bought 20 marbles from Johanna and added them to a store that had 50 marbles. His father gave him **$\\frac{2}{5}$ times** as many marbles as he bought from Johanna, so:\n\n$$\n\\frac{2}{5} \\times 20 = 8 \\text{ marbles}\n$$\n\nNow, the total number of marbles Solomon has is:\n\n$$\n20 + 50 + 8 = 78 \\text{ marbles}\n$$\n\nEach marble weighs **2kgs**, so the total weight is:\n\n$$\n78 \\times 2k = 156k \\text{ grams}\n$$\n\n**Final Answer:** $\\boxed{156k}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "First, calculate the volume of the pool:\n\n$$\n\\text{Volume} = \\text{length} \\times \\text{width} \\times \\text{depth} = 6 \\, \\text{ft} \\times 4 \\, \\text{ft} \\times 5 \\, \\text{ft} = 120 \\, \\text{cubic feet}\n$$\n\nNext, calculate the cost:\n\n$$\n\\text{Cost} = \\text{Volume} \\times \\text{Cost per cubic foot} = 120 \\, \\text{ft}^3 \\times 0.1 \\, \\text{\\$/ft}^3 = 12 \\, \\text{\\$}\n$$\n\n**Final Answer:**" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- The classroom has **3 times as many girls as boys**.\n- The classroom has **1/10 as many non-gendered children as boys**.\n- The classroom has **30 boys**.\n\nLet's denote:\n\n- Number of boys = 30\n- Number of girls = 3 × number of boys = $3 \\times 30 = 90$\n- Number of non-gendered children = $ \\frac{1}{10} \\times 30 = 3 $\n\nSo, total number of children = number of boys + number of girls + number of non-gendered children \n= $30 + 90 + 3 = \\boxed{123}$\n\n**Answer:** $\\boxed" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The ratio of electric poles to electric wires is **1:3**.\n- The total number of electric wires is **45**.\n\nWe need to find the **total number of electric poles**.\n\n### Step 1: Use the ratio\nThe ratio is **1:3**, meaning for every **3 wires**, there are **1 pole**.\n\nSo, for every 3 wires, there is 1 pole.\n\n### Step 2: Find how many poles correspond to 45 wires\nWe can write this as:\n\n$$\n\\frac{1 \\text{ pole}}{3 \\text{ wires}} = \\frac{1}{3}\n$$\n\nSo, to find the number of poles for 45 wires:\n\n$$\n\\text{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- At the beginning: 25 men and 15 women → total = 25 + 15 = 40 people.\n- After an hour: 1/4 of the total number of people left → 1/4 of 40 = 10 people left.\n- 22 men stayed at the party → so 22 men are still at the party, and the remaining 10 people (1/4) are women.\n\nSo, the number of women left is:\n\n$$\n15 - 22 = -7\n$$\n\nThis is negative, which doesn't make sense. This suggests that the problem might have a typo or requires a different interpretation.\n\nLet’s re-express the problem:\n\n- Total" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- A book costs $4.\n- A magazine costs half as much as a book: $ \\frac{1}{2} \\times 4 = 2 $ dollars.\n- A pen costs $1 less than a magazine: $ 2 - 1 = 1 $.\n\nSo, the pen costs **$1**.\n\n$$\n\\boxed{1}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- Jam has **3 boxes** of full pencils and **2 loose pencils**.\n- Total pencils: $ 3 \\times 1 + 2 = 5 $.\n- Meg has **46 pencils**.\n\nSo, the total number of pencils that need to be stored is:\n\n$$\n5 + 46 = 51 \\text{ pencils}\n$$\n\nNow, we need to find how many **boxes** are required to store 51 pencils. Since each box contains **1 pencil**, we need:\n\n$$\n51 \\text{ boxes}\n$$\n\n### Final Answer:\n$$\n\\boxed{51}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Each ice cube cools the coffee by **13 degrees**.\n- Each ice cube **weakened** the coffee by **12 milliliters**.\n- Shannon adds **15 milliliters** of cream.\n- The coffee is cooled by **65 degrees**.\n\n---\n\n### Step 1: Determine how many ice cubes were added\n\nSince the coffee cools by **13 degrees**, and the total cooling is **65 degrees**, the number of ice cubes added is:\n\n$$\n\\frac{65}{13} = 5\n$$\n\nSo, **5 ice cubes** were added.\n\n---\n\n### Step 2: Calculate the total milliliters of weaker coffee\n\nEach ice cube weakened the coffee by **12" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that:\n\n- 2 old records can be traded for 1 new record.\n- 5 people come in with old records and leave with 7 new records.\n- We need to find how many old records the 5 people brought in.\n\nLet’s denote the number of old records brought in by the 5 people as $ x $.\n\nEach person trades 2 old records for 1 new record. So, if 5 people trade their old records, they will exchange:\n\n$$\n5 \\times 2 = 10 \\text{ old records}\n$$\n\nEach new record comes from trading 2 old records, so the number of new records is also 10.\n\nBut the problem says that the 5 people leave with 7 new records. This suggests" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The company currently has **100 employees**.\n- Senior programmers are paid **$400 more** than junior programmers.\n- The number of **Junior programmers** is **2/5** of the total number of employees.\n- Each junior programmer is paid **$2000** per month.\n\n---\n\n### Step 1: Find the number of junior programmers\n\n$$\n\\text{Number of junior programmers} = \\frac{2}{5} \\times 100 = 40\n$$\n\n---\n\n### Step 2: Find the number of senior programmers\n\n$$\n\\text{Senior programmers} = 100 - 40 = 60\n$$\n\n---\n\n### Step 3: Find" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- At the **first stop**, 5 more people got in.\n- At the **second stop**, 7 people got down and 8 more got in.\n- At the **third stop**, there were a total of 20 people.\n\nWe are to find how many people **got on the bus at the terminal**.\n\n---\n\n### Step 1: Start with the number of people at the terminal.\n\nLet $ x $ be the number of people who got on the bus at the terminal.\n\n---\n\n### Step 2: Add people who got on at the first stop.\n\n- 5 people got in at the first stop → total people now: $ x + 5 $\n\n---\n\n### Step 3: Add people who got on at the second stop.\n\n- " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Start with 24 lollipops.**\n- **Eats 2 lollipops on his way to school:** \n $ 24 - 2 = 22 $\n- **Passes 14 lollipops to his friends:** \n $ 22 - 14 = 8 $\n- **Buys twice as many lollipops on his way home as he gave to his friends:** \n $ 14 \\times 2 = 28 $\n- **Eats 3 more lollipops that night:** \n $ 8 - 3 = 5 $\n- **Eats 2 more in the morning:** \n $ " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The phone recharges at a rate of **1 percentage-point per 3 minutes**.\n- The phone is currently at **60% charged**.\n- We need to find how long it will take to **fully charge** (i.e., reach 100%).\n\n---\n\n### Step 1: Calculate the number of percentage-points needed\n\nThe phone needs to go from 60% to 100%, so it needs:\n\n$$\n100\\% - 60\\% = 40\\% \\text{ of charge}\n$$\n\nEach 3 minutes corresponds to 1 percentage-point. So, 40 percentage-points take:\n\n$$\n40 \\times 3 = 120 \\text{ minutes}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Erin starts with 7 lollipops. \nHer mother gives her another 10 lollipops, so she now has:\n\n$$\n7 + 10 = 17 \\text{ lollipops}\n$$\n\nThen, Erin gives 3 of her lollipops to Ella, so she has:\n\n$$\n17 - 3 = 14 \\text{ lollipops}\n$$\n\n**Final answer:** $\\boxed{14}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- The customer's loyalty card gives them **$1 off their next purchase** for every **$20** they spend.\n- Their **last shopping trip** was $80.\n- This **shopping trip** was $43, and they used their **rewards** to **apply a coupon** that took **twice the amount of rewards** off the price.\n\n---\n\n### Step 1: Calculate the rewards for the first trip\n\n- The customer spent $80.\n- For every $20 spent, they get $1 off.\n- So, the number of $20 increments is $80 ÷ 20 = 4.\n\n- Rewards = $1 × 4 = **$4**\n\n---\n\n### Step 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To determine how much more money Nick will make at the job with the higher net pay rate, we need to calculate the net pay for both jobs and then find the difference.\n\n---\n\n### **Job A:**\n- Hourly wage: $15\n- Annual hours: 2000\n- Total tax rate: 20%\n\n**Net pay for Job A:**\n$$\n\\text{Net pay} = \\text{Hourly wage} \\times \\text{Hours} - \\text{Tax}\n$$\n$$\n= 15 \\times 2000 - 0.20 \\times 15 \\times 2000\n$$\n$$\n= 30000 - 6000 = " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- There are **220 castles** in Scotland.\n- **40%** of them are ruins.\n- **Half of the ruined castles** are unmanned.\n\n---\n\n### Step 1: Find the number of ruined castles\n\n$$\n40\\% \\text{ of } 220 = 0.40 \\times 220 = 88\n$$\n\nSo, there are **88 ruined castles**.\n\n---\n\n### Step 2: Find the number of unmanned ruined castles\n\n$$\n\\frac{1}{2} \\text{ of } 88 = 44\n$$\n\n---\n\n### Final Answer:\n\n$$\n\\boxed{44}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find the cost difference between the two offers, we first calculate the total cost of each:\n\n- **Furniture United**:\n - $1,350 (advance payment) + 6 × $350 (installments) = $1,350 + $2,100 = **$3,450**\n\n- **Cozy Homes**:\n - $1,100 (advance payment) + 9 × $250 (installments) = $1,100 + $2,250 = **$3,350**\n\nNow, subtract the total cost of the cheaper offer from the more expensive one:\n\n$$\n\\$3,450 - \\$3,350 = \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "To find out how many guns each person would have if they share the total number of guns equally, we first add up all the guns:\n\n- DJ: 8\n- Nick: 10\n- RJ: 1\n- Richard: 5\n\nTotal guns = $ 8 + 10 + 1 + 5 = 24 $\n\nNow, divide the total number of guns by the number of people:\n\n$$\n\\frac{24}{4} = 6\n$$\n\nSo, each person would have **6 guns**.\n\n$$\n\\boxed{6}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mason needs:\n\n- 30 ounces of sugar for 1 batch of suckers \n- 70 ounces of sugar for 1 batch of fudge\n\nTo find the total sugar needed for 8 batches of suckers and 1 batch of fudge:\n\n- For suckers: $ 8 \\times 30 = 240 $ ounces \n- For fudge: $ 1 \\times 70 = 70 $ ounces \n\nTotal sugar needed: \n$$ 240 + 70 = \\boxed{310} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Maria buys 8 shares of a stock for $8 each. \n- First year: The stock price increases by 50%, so the new price is $8 × 1.50 = $12. \n- Second year: The stock price decreases by 25%, so the new price is $12 × 0.75 = $9. \n\nNow, the total value of Maria's shares is: \n$$\n8 \\text{ shares} \\times 9 = \\boxed{72} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Luke ate **2 hot dogs**.\n\nThomas ate **3 times more** than Luke, so:\n\n$$\n3 \\times 2 = 6 \\text{ hot dogs}\n$$\n\nJohn ate **half** the amount Thomas ate:\n\n$$\n\\frac{6}{2} = 3 \\text{ hot dogs}\n$$\n\nNow, to find how many more hot dogs John ate than Luke:\n\n$$\n3 - 2 = 1\n$$\n\n**Answer:** $\\boxed{1}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A class of 200 students.\n- 3 groups: 2 groups are equal in size, and the **smallest** group is 10 less than each of the other groups.\n\nLet the number of students in each of the two equal groups be $ x $. Then the number of students in the smallest group is $ x - 10 $.\n\nSo, the total number of students is:\n\n$$\n2x + (x - 10) = 200\n$$\n\nSimplify:\n\n$$\n2x + x - 10 = 200 \\\\\n3x - 10 = 200 \\\\\n3x = 210 \\\\\nx = 70\n$$\n\nSo, the number" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Farmer Brown has 60 animals, and he has **twice as many chickens as cows**.\n\nLet:\n- $ c $ = number of cows\n- $ h $ = number of chickens\n\nWe are told:\n- $ c + h = 60 $\n- $ h = 2c $\n\nSubstitute $ h = 2c $ into the first equation:\n$$\nc + 2c = 60 \\Rightarrow 3c = 60 \\Rightarrow c = 20\n$$\n\nSo:\n- $ c = 20 $ cows\n- $ h = 2 \\times 20 = 40 $ chickens\n\nNow, calculate the total number of legs:\n- Cows: $ 20 \\times 4 =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Josh starts with 3 balls and adds 1 ball each week. After 4 weeks, he has:\n\n$$\n3 + 4 = 7 \\text{ balls}\n$$\n\nBut he slips and drops 3 balls. Of those, 2 are caught by people and 1 is lost. So the number of balls he is juggling is:\n\n$$\n7 - 3 = 4\n$$\n\n**Final Answer:** $\\boxed{4}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following relationships:\n\n- The pink frog weighs the same as the blue beetle.\n- The pink frog weighs the same as the green toad.\n- The pink frog weighs 10 pounds less than the yellow snake.\n- The pink frog weighs 20 pounds more than the red bird.\n- The pink frog weighs **50 pounds**.\n- The container carrying one of each animal weighs **20 pounds**.\n\n---\n\n### Step 1: Find the weight of the yellow snake\n\nFrom the problem:\n\n- Pink frog = yellow snake - 10 \n So, \n $ 50 = \\text{yellow snake} - 10 $ \n $ \\Rightarrow \\text{yellow snake} = 50 + 10 = 6" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Laurel's friend gave her **24** baby outfits. \nAt her baby shower, Laurel received **twice** that amount: \n$$ 2 \\times 24 = 48 $$\n\nThen, her mom gifted her **15** baby outfits. \nSo, the total number of outfits Laurel has is: \n$$ 48 + 15 = \\boxed{63} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tyson currently runs **5000 meters** every day. His coach wants him to run **1/5 times more** meters per day. \n\nTo find the new daily distance:\n\n$$\n\\text{New daily distance} = 5000 \\times \\left(1 + \\frac{1}{5}\\right) = 5000 \\times \\frac{6}{5} = 6000 \\text{ meters}\n$$\n\nNow, he trains for **a month**. Assuming a month has **30 days**, the total distance he runs in June is:\n\n$$\n6000 \\times 30 = 180,000 \\text{ meters}\n$$\n\n$$\n\\boxed{18" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Juice Box A = $4 \n- Juice Box B = $5 more than Juice Box A → $4 + $5 = $9 \n- Juice Box C = $7 more than Juice Box A → $4 + $7 = $11 \n\nNow, we are asked how much more Juice Box C is than Juice Box B.\n\n$$\n\\text{Difference} = \\text{C} - \\text{B} = 11 - 9 = \\boxed{2}\n$$\n\n**Answer:** $\\boxed{2}$ dollars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 40 tables with 4 legs \n- 50 tables with 3 legs \n\nWe need to calculate the total number of legs.\n\n### Step 1: Calculate legs from 40 tables\n$$\n40 \\times 4 = 160 \\text{ legs}\n$$\n\n### Step 2: Calculate legs from 50 tables\n$$\n50 \\times 3 = 150 \\text{ legs}\n$$\n\n### Step 3: Add the legs from both types of tables\n$$\n160 + 150 = \\boxed{310}\n$$\n\n**Answer:** $\\boxed{310}$ legs." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jenny buys 1 bag of cookies a week, which contains 36 cookies. She puts 4 cookies in her son's lunch box 5 days a week. Her husband eats 1 cookie a day for 7 days.\n\n### Step 1: Calculate the number of cookies used by the son and the husband\n- **Son's cookies per week**: $ 4 \\text{ cookies/day} \\times 5 \\text{ days} = 20 \\text{ cookies} $\n- **Husband's cookies per week**: $ 1 \\text{ cookie/day} \\times 7 \\text{ days} = 7 \\text{ cookies} $\n\n### Step 2: Total cookies used by the son and the husband\n$$\n20 + 7" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Davos bought 2 shirts at $30 each, and there is a 40% discount.\n\n1. The cost of one shirt is $30.\n2. The discount is 40%, so the discount amount is:\n $$\n 30 \\times 0.40 = 12\n $$\n3. The discounted price of one shirt is:\n $$\n 30 - 12 = 18\n $$\n4. The total cost for 2 shirts is:\n $$\n 18 \\times 2 = 36\n $$\n\n**Answer:** $\\boxed{36}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- When they made tractors, they sold **10 tractors a day** and made **$100 per tractor**.\n- Now, they sell **5 silos a day** and make **$220 per silo**.\n\nWe are to find **what percentage more** they are making per day now.\n\n---\n\n### Step 1: Find the original daily revenue\n\n- 10 tractors × $100 per tractor = **$1,000**\n\n---\n\n### Step 2: Find the new daily revenue\n\n- 5 silos × $220 per silo = **$1,100**\n\n---\n\n### Step 3: Find the difference in revenue\n\n- $1,100 (" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Madeline buys food, treats, and medicine for her dog every month. \n- Food costs $25 per week \n- Treats cost $20 per month \n- Medicine costs $100 per month \n\nThere are **4 weeks in a month**, so: \n- Food cost: $25 × 4 = $100 \n- Treats cost: $20 × 1 = $20 \n- Medicine cost: $100 × 1 = $100 \n\nTotal monthly cost: \n$100 (food) + $20 (treats) + $100 (medicine) = **$220**\n\nMadeline spends **$220** on her dog per month.\n\n**Answer:**" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break down the problem step by step:\n\n- **Yoga class on Monday**: 1 hour \n- **Cooking class on Tuesday**: 3 times longer than Monday’s yoga = $3 \\times 1 = 3$ hours \n- **Cheese-tasting event on Wednesday**: 0.5 hour \n- **Museum tour on Thursday**: Half as long as the cooking class on Tuesday = $0.5 \\times 3 = 1.5$ hours \n- **Errands on Friday**: 2 hours \n\nNow, add all these durations together:\n\n$$\n1 + 3 + 0.5 + 1.5 + 2 = 8 \\text{ hours}\n$$\n\n### Final Answer:\n$$\n\\boxed{8}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "April had already bought **100 plant pots** from the garden center.\n\nShe needs:\n\n- 30 plant pots for daisies \n- Twice as many for roses = 60 plant pots\n\nSo, total pots needed = 30 + 60 = **90 pots**\n\nApril has **100 pots** to start with.\n\nThe number of plant pots **left over** is:\n\n$$\n100 - 90 = \\boxed{10}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- Andrea had $36 in the beginning.\n- She spent the rest of her money on an $11 sweater.\n- She gave her brother $4.\n\nLet’s break it down:\n\n1. She spent the rest of her money on the sweater. \n So, the amount she spent on the sweater is: \n $ 36 - 11 = 25 $.\n\n2. She gave her brother $4. \n So, the total amount she spent is: \n $ 25 + 4 = 29 $.\n\n3. Therefore, the amount she saved is: \n $ 36 - 29 = 7 $.\n\n**Answer:** $\\boxed{7}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John spends:\n\n- 6 hours boating \n- Half that time swimming: $ \\frac{6}{2} = 3 $ hours \n- 3 shows, each 2 hours: $ 3 \\times 2 = 6 $ hours \n\nTotal time spent on activities: \n$$ 6 + 3 + 6 = 15 \\text{ hours} $$\n\nHe spends **30%** of his time on activities. \nSo, the time he spent sightseeing is: \n$$ 0.3 \\times 15 = 4.5 \\text{ hours} $$\n\n**Answer:** $ \\boxed{4.5} $ hours." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Annabelle already has $80 in her savings. She earns:\n\n- $10 per hour for 20 hours: $10 × 20 = $200\n- $5 per hour for 15 hours: $5 × 15 = $75\n\nTotal earnings: $200 + $75 = $275\n\nShe needs: $400 - $80 = $320\n\n**Answer:** $\\boxed{320}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The **shortest tree** has a height of **6 feet**.\n- The **second tree** has a height that is **5 feet more** than the shortest tree: \n $ 6 + 5 = 11 $ feet.\n- The **tallest tree** has a height that is **twice** the **combined height** of the two shortest and second trees.\n\n### Step 1: Find the combined height of the two trees\n$$\n6 + 11 = 17 \\text{ feet}\n$$\n\n### Step 2: Find the height of the tallest tree\n$$\n\\text{Height of tallest tree} = 2 \\times 17 = 34 \\text{ feet}\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Dean's original amount is $28.\n\nHe bought:\n- 6 toy cars at $2 each: $6 \\times 2 = 12\n- 5 teddy bears at $1 each: $5 \\times 1 = 5\n\nTotal spent: $12 + $5 = $17\n\nHis mother gives him an extra $10.\n\nSo, total money left: $28 - $17 + $10 = $11\n\n**Final Answer:** $\\boxed{11}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Morgan's dad said she has $90 for her birthday party. Here's the breakdown:\n\n- Mini-golf: $5 per round\n- Arcade tokens: $5\n- Go-karts: $10 per ride\n\nShe wants to play **1 round of mini-golf**, **1 game of arcade tokens**, and **2 rides of go-karts**.\n\nLet's calculate the total cost:\n\n- Mini-golf: $5 × 1 = $5 \n- Arcade tokens: $5 × 1 = $5 \n- Go-karts: $10 × 2 = $20\n\nTotal cost = $5 + $5 + $20 = **$30**\n\nMorgan has $90, so she can invite:\n\n$$\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Marisa gets $5 every day from her parents. She buys 4 lollipops worth 25 cents each, so the total cost of the lollipops is:\n\n$$\n4 \\times 25 = 100 \\text{ cents}\n$$\n\nShe saves the change in her piggy bank. So, the amount she saves each day is:\n\n$$\n5 \\text{ dollars} - 100 \\text{ cents} = 5 \\text{ dollars} - 1 \\text{ dollar} = 4 \\text{ dollars}\n$$\n\nShe saves this amount for 5 days, so the total amount she saves is:\n\n$$\n4 \\text{ dollars/day} \\times 5 \\text{ days} = 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Billy starts with $10 from his father. The candy costs $1.5 per pound, and he buys 40 gumballs that cost $0.05 each. Let's break it down step by step:\n\n1. **Cost of candy**: \n $ 1.5 \\, \\text{pounds} \\times 40 = 60 \\, \\text{pounds} $\n\n2. **Change he takes**: \n $ 10 - 60 = -50 $, which means he **does not have any change**.\n\n3. **He spends half his change on gumballs**: \n Since he has no change, he can't spend anything on gumballs. This implies that the 40 g" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the son's current age be $ x $.\n\nCarver just turned 45, so he is 45 years old.\n\nAccording to the problem, Carver's age is 5 years less than twice the age of his son:\n\n$$\n45 = 2x - 5\n$$\n\nSolving for $ x $:\n\n$$\n2x = 45 + 5 = 50\n$$\n$$\nx = \\frac{50}{2} = 25\n$$\n\nSo, the son is **25 years old**.\n\n$$\n\\boxed{25}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- The train travels:\n - 75 miles from the first to the second city,\n - 100 miles from the second to the third city,\n - 50 miles less than the combined distance to the first city from the third city.\n\nLet’s calculate the distance from the third city to the first city:\n\n- Combined distance from 2nd to 3rd: $100 + 75 = 175$ miles.\n- Distance from 3rd to 1st: $175 - 50 = 125$ miles.\n\nSo the train travels 125 miles from the third city to the first city.\n\nThe train does this trip **3 times a day**, so the" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- A **Rottweiler bed** takes **8 pounds** of stuffing.\n- A **chihuahua bed** takes **2 pounds** of stuffing.\n- A **collie bed** takes the **average** of the stuffing used for a Rottweiler and a chihuahua bed.\n\nSo, the stuffing for a collie bed is:\n\n$$\n\\text{Collie bed} = \\frac{8 + 2}{2} = 5 \\text{ pounds}\n$$\n\nNow, we are asked to find how many pounds of stuffing Mark needs to make:\n\n- **4 chihuahua beds** \n- **3 collie beds**\n\nSo, total stuffing needed:\n\n$$\n\\text{Total} =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John's total trip consists of two parts:\n\n1. **Going to his friend's house**: \n - Distance: 200 miles \n - Speed: 70 mph \n - Time: $ \\frac{200}{70} = \\frac{20}{7} \\approx 2.86 \\text{ hours} $\n\n2. **Taking a detour**: \n - Distance: 10 miles \n - No change in speed \n - Time: $ \\frac{10}{70} = \\frac{1}{7} \\approx 0.14 \\text{ hours} $\n\n3. **Going back home**: \n - Distance: 240 miles \n - Speed: 8" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total number of fourth-grade students: 96 \n- Number of girls: 43 \n- Number of girls absent: 5 \n- Number of boys absent: 4 \n\n### Step 1: Find the number of students present on Friday\n\n$$\n\\text{Students present} = \\text{Total students} - \\text{Absent students}\n$$\n\n$$\n\\text{Students present} = 96 - (5 + 4) = 96 - 9 = 87\n$$\n\n### Step 2: Find the number of boys present\n\n$$\n\\text{Number of boys present} = \\text{Students present} - \\text{Number of girls present}\n$$\n\n$$\n\\text{Number" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **6 girls** in the park.\n- There are **twice the number of boys** in the park.\n\nLet the number of boys be $ x $.\n\nThen, the number of boys is $ 2x $.\n\nSo, the total number of kids in the park is:\n\n$$\n6 + 2x\n$$\n\nWe are not given the number of boys, so we need to express the total in terms of $ x $.\n\nHowever, if we assume that the number of boys is the same as the number of girls (which is not stated), then:\n\n$$\nx = 6 \\Rightarrow \\text{Number of boys} = 6\n$$\n\nThen the total number of kids is:\n\n$$\n6 + 2 \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jane needs a total of **at least 42 points** from her three tests. She has already scored:\n\n- First test: 15 points \n- Second test: 18 points \n\nLet the third test score be $ x $. Then:\n\n$$\n15 + 18 + x \\geq 42\n$$\n\n$$\n33 + x \\geq 42\n$$\n\n$$\nx \\geq 9\n$$\n\nSo, the minimum number of points Jane must score on the third test is:\n\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- 3 customers were kicked out of the Walmart for refusing to wear masks.\n- A number equals to **4 times that many minus 5**.\n- 3 times the number of **shoplifters** were kicked out for **physical violence over goods on sale**.\n- A total of **50 people** were kicked out of the Walmart.\n\nLet’s define the number of customers kicked out for refusing to wear masks as $ x $.\n\nFrom the problem:\n\n- $ x = 3 $ (given)\n- The number of people kicked out for **shoplifting** is $ 4x - 5 = 4(3) - 5 = 12 - 5 = 7 $\n- The number of people kicked out for **" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's define the variables:\n\n- Let $ E $ be the number of points Erin had before.\n- Sara scored 8 points.\n- After scoring 14 points, Erin has three times more points than Sara.\n\nSo, Erin's total points after scoring 14 is:\n\n$$\n3 \\times 8 = 24\n$$\n\nThis means Erin had 24 points after scoring 14, and she had $ E $ points before. Therefore:\n\n$$\nE + 14 = 24\n$$\n\n$$\nE = 24 - 14 = 10\n$$\n\n### Final Answer:\n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- **44 seniors** need to receive awards.\n- **Each senior receives a picture frame** that costs **$20**.\n- **Each picture frame needs to be etched with a logo** for an additional **20% cost**.\n- **2 seniors** will also receive **pins** that cost **$5**.\n- **1/4 of the seniors** are officers and they will need to receive **cords** that cost **$12** each.\n\n---\n\n### Step 1: Calculate the cost of picture frames\n\n- Each picture frame costs **$20**.\n- 44 seniors, each gets 1 frame:\n $$\n 44 \\times 20 = 880" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break it down step by step:\n\n- The **original cost** of the hand-painted wallpaper is **$400**.\n- The **DIY saves 20%** of the original cost.\n- So, the **materials cost** is 20% of $400.\n\n$$\n\\text{Materials cost} = 400 \\times 0.20 = 80\n$$\n\n- The **total cost** Ethan paid is the original cost minus the materials cost:\n\n$$\n\\text{Total cost} = 400 - 80 = 320\n$$\n\n### Final Answer:\n$$\n\\boxed{320}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Friday**: 14 pairs sold.\n- **Saturday**: Double the number of shoes sold on Friday: \n $ 2 \\times 14 = 28 $ pairs.\n- **Sunday**: One-half the amount sold on Saturday, but **6 people returned** their shoes. \n So, the number of shoes sold on Sunday is: \n $ \\frac{1}{2} \\times 28 = 14 $ pairs. \n However, 6 people returned, so the actual number of shoes sold on Sunday is: \n $ 14 - 6 = 8 $ pairs.\n\n- **Total shoes sold by the end of the sale**: \n $ 14 +" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Hallie had dance practice for:\n\n- **1 hour** on **Tuesday** \n- **2 hours** on **Thursday** \n- **Twice as long** on **Saturday** as on Tuesday: $2 \\times 1 = 2$ hours\n\nSo, the total dance practice time per week is:\n\n$$\n1 + 2 + 2 = \\boxed{5} \\text{ hours}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- The total value of the equipment is **$400,000**.\n- 40% of this value is **faulty equipment**.\n- The remaining 60% is **functional equipment**.\n\n### Step 1: Calculate the value of faulty equipment\n$$\n40\\% \\text{ of } 400,000 = 0.40 \\times 400,000 = 160,000\n$$\n\n### Step 2: Calculate the value of functional equipment\n$$\n100\\% - 40\\% = 60\\%\n$$\n$$\n60\\% \\text{ of }" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mary has **30 sheep**, and she gets **1 kg of milk from half** of them and **2 kg of milk from the other half** every day.\n\n- Half of 30 sheep = **15 sheep**\n- 15 sheep contribute **1 kg of milk** per day\n- The other half (15 sheep) contribute **2 kg of milk** per day\n\nSo, total milk per day:\n\n$$\n15 \\text{ kg} + 15 \\text{ kg} = \\boxed{30} \\text{ kg}\n$$\n\n**Answer:** $\\boxed{30}$ kg of milk per day." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mrs. Sherman made a dozen bread rolls, which is 12 rolls.\n\nShe fed 6 children with one roll each, so she fed **6 rolls** to the children.\n\nAfter that, she broke each of the remaining rolls into 8 pieces.\n\nSo, the number of rolls remaining is:\n\n$$\n12 - 6 = 6\n$$\n\nEach of these 6 rolls was broken into 8 pieces, so the total number of pieces is:\n\n$$\n6 \\times 8 = 48\n$$\n\n**Answer:** $\\boxed{48}$ pieces of rolls." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **40 pupils** in the class.\n- **Half** of the class likes **blue** → $ \\frac{1}{2} \\times 40 = 20 $ pupils like blue.\n- The remaining pupils like **green** and **yellow**.\n\nSo, the number of pupils who like **green** is:\n$$\n40 - 20 = 20\n$$\n\nSince **one-fourth** of the remaining likes green, the number of pupils who like **green** is:\n$$\n\\frac{1}{4} \\times 20 = 5\n$$\n\nThe rest of the pupils (i.e., the ones who like **yellow**) are:\n$$\n20 - 5 =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Lucy sells apples at $4 per piece.\n- On **Monday**, she sold all the apples picked.\n- On **Tuesday**, she picked **12 apples**.\n- On **Wednesday**, she picked **double** the number of apples she picked on Tuesday.\n- Lucy got **$56** from selling the apples picked on Monday.\n\nWe are to find the **total number of apples** she picked over the three days.\n\n---\n\n### Step 1: Find the number of apples picked on Monday\n\nLucy sold all the apples on Monday, and she got **$56** from that day.\n\nSo, the number of apples on Monday is:\n\n$$\n\\text{Apples on Monday} = \\frac{56}{4}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Lindsay has 50 socks in total. She washed 10 pairs of socks and 15 loose socks.\n\n- 1 pair = 2 socks, so 10 pairs = $10 \\times 2 = 20$ socks.\n- 15 loose socks = 15 socks.\n\nSo, the total number of socks Lindsay has is:\n\n$$\n20 + 15 = 35 \\text{ socks}\n$$\n\nSince she has 50 socks in total, the number of socks Lindsay **missed** is:\n\n$$\n50 - 35 = \\boxed{15}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Rachel initially had 23 cookies, and Janet gave her 42 more. So, the total number of cookies Rachel had at the start was:\n\n$$\n23 + 42 = 65\n$$\n\nThen, her brother ate 44 of those cookies. So, the number of cookies left for Rachel is:\n\n$$\n65 - 44 = 21\n$$\n\n**Final Answer:** $\\boxed{21}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Karan borrowed $3,650 for 5 months at an interest rate of 10%. She has to pay an equal amount every month.\n\n### Step 1: Understand the problem\nThis is a **simple interest** problem. The formula for simple interest is:\n\n$$\nI = P \\times r \\times t\n$$\n\nWhere:\n- $ P = 3650 $ (principal amount),\n- $ r = 0.10 $ (annual interest rate),\n- $ t = 5 $ months.\n\n### Step 2: Calculate the interest\n$$\nI = 3650 \\times 0.10 \\times 5 = 3650 \\times 0.5 = 1825\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Chloe hiked **9 km/h** for **5 hours**.\n- Chloe hiked **14 km/h** for **8 hours**.\n\nWe are to find how many **kilometers farther** Chloe hiked.\n\n### Step 1: Calculate the distance Chloe hiked\n\n- For 5 hours at 9 km/h:\n $$\n 9 \\times 5 = 45 \\text{ km}\n $$\n\n- For 8 hours at 14 km/h:\n $$\n 14 \\times 8 = 112 \\text{ km}\n $$\n\n### Step 2: Find the difference\n\n$$\n112 - 45 = 67 \\text{ km}\n$$\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Axel has:\n- 50 silver pesos \n- 80 gold pesos\n\nAnna has:\n- Twice as many silver pesos as Axel: $ 2 \\times 50 = 100 $ silver pesos \n- 40 more gold pesos than Axel: $ 80 + 40 = 120 $ gold pesos\n\nTotal pesos together:\n- Silver: $ 50 + 100 = 150 $ \n- Gold: $ 80 + 120 = 200 $ \n- Total: $ 150 + 200 = \\boxed{350} $ pesos." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Millie spends $18 to buy supplies to make 3 pitchers of lemonade.\n- Each pitcher holds 12 cups of lemonade.\n- She sells each cup of lemonade for $1.\n- She sells an average of 4 cups per hour.\n- We are to find her **profit per hour**.\n\n---\n\n### Step 1: Calculate the total amount of lemonade she makes\n\n- 3 pitchers × 12 cups per pitcher = **36 cups**\n- She sells 36 cups at $1 per cup = **$36**\n\n---\n\n### Step 2: Calculate the total revenue per hour\n\n- She sells 4 cups per hour, so in 1 hour, she makes 4 cups × $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the total amount of land Mr. Ruther had at first.\n\nHe sold $ \\frac{3}{5} $ of his land, so the remaining land is:\n\n$$\nx - \\frac{3}{5}x = \\frac{2}{5}x\n$$\n\nHe had 12.8 hectares left, so:\n\n$$\n\\frac{2}{5}x = 12.8\n$$\n\nSolving for $ x $:\n\n$$\nx = 12.8 \\div \\frac{2}{5} = 12.8 \\times \\frac{5}{2} = 32\n$$\n\nSo, Mr. Ruther had **32 hectares** at first. \n\n$$\n\\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Lisa is part of a choir with **52 members**, and **50% are boys** and **50% are girls**. So:\n\n- Number of **boys** = 50% of 52 = 26 \n- Number of **girls** = 50% of 52 = 26\n\nThe choir decides to perform **only with its female members**, so:\n\n- Total female members = 26 (boys + girls) = **26**\n\nHowever, **half the people performing can't make it** because their bus breaks down. So:\n\n- Number of people who **can't make it** = 26 / 2 = 13 \n- Therefore, the number of people **who did make it** =" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "To find Wilson's math grade, we need to calculate the **average** of his 5 test scores.\n\nGiven:\n- Test scores: 65, 94, 81, 86, 74\n\nWe add them together:\n\n$$\n65 + 94 + 81 + 86 + 74 = 390\n$$\n\nNow divide by 5:\n\n$$\n\\frac{390}{5} = 78\n$$\n\nSo, Wilson's current math grade is:\n\n$$\n\\boxed{78}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n- 1 eraser costs $2.\n- 1 pencil costs $3.\n\nWe need to find the total cost for:\n- 6 erasers\n- 8 pencils\n\nSo, the total cost is:\n$$\n6 \\times 2 + 8 \\times 3 = 12 + 24 = \\boxed{36}\n$$\n\nThe final answer is $\\boxed{36}$." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James delivers:\n\n- 66 messages to Ms. Thompson \n- $ \\frac{1}{3} \\times 66 = 22 $ messages to Mr. Yu\n\nSo, the total number of messages is:\n\n$$\n66 + 22 = \\boxed{88}\n$$\n\nJames delivers **88 messages** in total." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "David and Dasha ride all 9 rides. Each ride costs 2 ride tickets at $2 per ticket, so the total cost for the rides is:\n\n$$\n9 \\times 2 \\times 2 = 36 \\text{ ride tickets}\n$$\n\nDavid buys a ride bracelet for $30, which gives him 9 rides. So, he saves:\n\n$$\n36 - 30 = 6 \\text{ ride tickets}\n$$\n\nSince each ride ticket is $2, the total savings is:\n\n$$\n6 \\times 2 = \\boxed{12} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{12}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Monica has 6 gifts for her family, 4 gifts for her friends, and 2 gifts for her teachers. \nTotal gifts = $6 + 4 + 2 = 12$ gifts.\n\nShe has 144 inches of ribbon and wants to use it for each gift. \nSo, the amount of ribbon used per gift is:\n\n$$\n\\frac{144 \\text{ inches}}{12 \\text{ gifts}} = 12 \\text{ inches per gift}\n$$\n\n**Answer:** $\\boxed{12}$ inches." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The ratio of popsicles that Betty and Sam have is **5:6**.\n- The total number of popsicles they have together is **165**.\n\nLet’s solve this step by step.\n\n---\n\n### Step 1: Let the number of popsicles Betty has be $ 5x $, and Sam has $ 6x $.\n\nSo, the total number of popsicles is:\n\n$$\n5x + 6x = 165\n$$\n\n$$\n11x = 165\n$$\n\n$$\nx = \\frac{165}{11} = 15\n$$\n\n---\n\n### Step 2: Find how many more popsicles Sam has than Betty.\n\nSam has $ 6x" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tim cancels his cable subscription and switches to streaming services. He pays:\n\n- **Netflix**: $10/month \n- **Hulu**: $10/month \n- **Disney Plus**: $10/month \n\n**Total monthly cost without bundling**: \n$10 + $10 + $10 = **$30/month**\n\n**Total monthly cost with bundling**: \n$10 + $10 + $10 = **$30/month**\n\n**Savings from bundling**: \n$30 - $30 = **$0**\n\n**Answer**: $\\boxed{0}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carol spends:\n\n- 4 hours writing a song \n- Half that time: $ \\frac{4}{2} = 2 $ hours recording \n- 90 minutes editing\n\nConvert all times to hours:\n\n- 4 hours \n- 2 hours \n- 90 minutes = 1.5 hours\n\nTotal time = $ 4 + 2 + 1.5 = 7.5 $ hours\n\nPercentage of time spent editing:\n\n$$\n\\frac{1.5}{7.5} \\times 100 = 20\\%\n$$\n\n**Answer:** $\\boxed{20\\%}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n1. **Double the number of books in a row**: \n If there are 6 rows and 6 columns, the total number of books is:\n $$\n 6 \\times 6 = 36\n $$\n\n2. **Double the number of books**: \n So, the number of books to place in the system is:\n $$\n 2 \\times 36 = 72\n $$\n\n3. **Add 20 more than double**: \n The problem says \"20 more than double the number of books\", so we add 20 to the doubled number:\n $$\n 72 + 20 = 92\n $$\n\n###" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Erica started with **20** Valentine's cards. \nHer dad brought her **2 boxes**, each with **15 cards**, so that's:\n\n$$\n2 \\times 15 = 30 \\text{ cards}\n$$\n\nNow, she passed out:\n\n- **24** to her classmates \n- **5** to her family \n- **17** from family and friends \n\nSo, total cards passed out:\n\n$$\n24 + 5 + 17 = 46\n$$\n\nNow, the total number of cards Erica has is:\n\n$$\n20 + 30 - 46 = \\boxed{4} \\text{ cards}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jenny is dividing up a pizza with 12 slices.\n\n- She gives **1/3** to Bill: \n $ \\frac{1}{3} \\times 12 = 4 $ slices.\n\n- She gives **1/4** to Mark: \n $ \\frac{1}{4} \\times 12 = 3 $ slices.\n\n- Jenny eats **2 slices**: \n $ 2 $ slices.\n\nSo, the total number of slices eaten is: \n$ 4 + 3 + 2 = 9 $ slices.\n\nThe number of slices **left** is: \n$ 12 - 9 = 3 $ slices.\n\n**Final Answer:** $ \\boxed{3} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mark earns $10 per day, so his daily earnings are:\n\n$$\n10 \\text{ dollars/day}\n$$\n\nHe wants to save money for a bike that costs $300. To find out how many days he needs to save, we divide the total cost by his daily savings:\n\n$$\n\\frac{300}{10} = 30 \\text{ days}\n$$\n\n**Final Answer:** $\\boxed{30}$ days." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Nancy saw **90 spiders**.\n- The number of **millipedes** is **1/3** as many as the spiders, so:\n $$\n \\text{Millipedes} = \\frac{1}{3} \\times 90 = 30\n $$\n- The number of **stink bugs** is **twice the number of millipedes minus 12**, so:\n $$\n \\text{Stink bugs} = 2 \\times 30 - 12 = 60 - 12 = 48\n $$\n\nNow, we add the number of spiders, millipedes, and stink bugs together:\n\n$$\n\\text{Total" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Alice is 7 years older than Beth.\n- Beth is 5 years older than Erica.\n- Erica is 30 years old.\n\nLet's find the difference between the ages of Alice and Erica.\n\n1. Erica is 30 years old.\n2. Beth is 5 years older than Erica: \n $ 30 + 5 = 35 $ years old.\n3. Alice is 7 years older than Beth: \n $ 35 + 7 = 42 $ years old.\n\nSo, the difference between Alice and Erica is: \n$$\n42 - 30 = \\boxed{12} \\text{ years.}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John drinks **2 glasses of milk**, and each glass contains **8 ounces of milk**.\n\n- Total milk consumed: $ 2 \\times 8 = 16 $ ounces \n- Calories from milk: $ 16 \\times 3 = 48 $ calories\n\n**Final Answer:** $\\boxed{48}$ calories." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- He works **4 weeks** every **month**.\n- He works **6 days** every **week**.\n- He gets paid **$50 every day**.\n\nWe need to find his **earnings for a year**.\n\n### Step 1: Calculate the number of days in a year\n\n- A year has **365 days**.\n\n### Step 2: Calculate the number of days he works in a year\n\n- He works **6 days per week**.\n- He works **4 weeks per month**.\n- There are **52 weeks in a year**.\n\n$$\n\\text{Days per year} = 6 \\, \\text{days/week} \\times 52 \\, \\text{weeks/year}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark is making a **quadruple batch** of brownies, which means he needs **4 cups of flour** and **1 cup of milk**.\n\n- **Flour**: 4 cups \n- **Milk**: 1 cup\n\nNow, the **flour** is sold in **2-cup bags**, and the **milk** is sold in **2-cup bottles**.\n\n- Number of **flour bags needed**: $ \\frac{4}{2} = 2 $ \n- Number of **milk bottles needed**: $ \\frac{1}{2} = 0.5 $\n\nSince Mark can't buy half a bottle, he needs **1 bottle of milk**.\n\nNow, the question asks: **how many more bags of flour than bottles" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mel uses a 900-watt air conditioner for 8 hours a day. \nEach hour, the AC uses **900 watts** of energy. \n\n### Step 1: Calculate energy used per day \n- Energy used per day = 900 watts × 8 hours = **7200 watt-hours** (W·h)\n\n### Step 2: Calculate energy saved in 30 days \n- Energy saved per day = 7200 W·h \n- Energy saved in 30 days = 7200 W·h × 30 = **216,000 W·h**\n\n### Step 3: Convert energy to kilowatts \n- 1 kilowatt-hour (kWh" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jane has:\n\n- 2 zebras with 17 stripes each: $ 2 \\times 17 = 34 $ stripes \n- 1 zebra with 36 stripes \n- 1 zebra with half the number of stripes: $ \\frac{36}{2} = 18 $ stripes\n\nSo, the total number of stripes is:\n\n$$\n34 + 36 + 18 = 88 \\text{ stripes}\n$$\n\nThe number of zebras is 2.\n\nTo find the average number of stripes per zebra:\n\n$$\n\\frac{88}{2} = 44\n$$\n\n**Answer:** $\\boxed{44}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tyson needs to make **20 people** serve **4 people per sandwich**, so he needs to make:\n\n$$\n\\frac{20}{4} = 5 \\text{ sandwiches}\n$$\n\nEach sandwich requires **1 pound of meat** and **1 pound of cheese**, so he needs:\n\n$$\n5 \\text{ pounds of meat} + 5 \\text{ pounds of cheese} = 10 \\text{ pounds total}\n$$\n\nThe meat costs **$7.00 per pound**, and the cheese costs **$3.00 per pound**.\n\nSo, the total cost is:\n\n$$\n10 \\times 7 + 10 \\times 3 = 70 + 30 = \\boxed{100}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n---\n\nWe are told:\n\n- There is **twice as much corn as cannolis**.\n- Allan has a total of **40 cannolis**.\n- He bought **60 more cannolis** at the store and **40 fewer corns** than the number of cannolis.\n\n---\n\n### Step 1: Find the number of corns\n\nSince there is **twice as much corn as cannolis**, and there are **40 cannolis**, then:\n\n$$\n\\text{Number of corns} = 2 \\times 40 = 80\n$$\n\n---\n\n### Step 2: Find the number of cannolis he bought\n\nHe bought **60 more cannolis** than he had initially:\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n1. **Total steps Elliott is trying to walk:** \n $ 10,000 $\n\n2. **He finished half of his steps on his walks to and from school:** \n $ \\frac{1}{2} \\times 10,000 = 5,000 $ steps\n\n3. **He also did another 1,000 steps going for a short walk with his friend:** \n $ 1,000 $ steps\n\n4. **After finishing his jog, he had 2,000 steps left:** \n So, the total steps he took so far is: \n $ 5,000 + 1,00" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total pages in the book: 45 \n- Average words per page: 200 \n- Reading rate: 300 words per minute \n- Time to get to the airport: 10 minutes \n- Time to finish the book: 60 minutes \n\n### Step 1: Calculate the total number of words in the book\n\n$$\n\\text{Total words} = 45 \\times 200 = 9000 \\text{ words}\n$$\n\n### Step 2: Calculate the time Toby would take to read the book\n\n$$\n\\text{Time to read the book} = \\frac{9000}{300} = 30 \\text{ minutes}\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Carolyn's company hired 40 employees in May, and each employee worked 40 hours a week. So, the total pay for May is:\n\n$$\n40 \\text{ employees} \\times 40 \\text{ hours} \\times \\$15/\\text{hour} = 24,000\n$$\n\nIn June, 1/4 of the employees' contracts expired. Since there are 40 employees, 1/4 of that is:\n\n$$\n\\frac{1}{4} \\times 40 = 10 \\text{ employees}\n$$\n\nSo, the company paid 10 employees for 40 hours each in June:\n\n$$\n10 \\text{ employees} \\times 40 \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Sally starts with $10.\n\nShe buys:\n- 2 pounds of taffy: $3 per pound = $6\n- 1 pound of taffy with 1/2 off: $3 - $1.50 = $1.50\n- 2 pounds of taffy: $3 per pound = $6\n\nTotal for taffy: $6 + $1.50 + $6 = $13.50\n\nShe also buys:\n- 1 mixed bag of seashells: $1.50\n- 4 magnets: $0.25 × 4 = $1.00\n\nTotal for seashells and magnets: $1.50 + $1.00 =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tim buys:\n\n- A package of fireworks worth $400 \n- Another pack worth twice that much: $400 × 2 = $800 \n\nHe gets a **20% discount** on the total of $400 + $800 = $1200.\n\nSo, the discounted price is:\n\n$$\n1200 \\times (1 - 0.20) = 1200 \\times 0.80 = 960\n$$\n\nHe also buys a **final firework** that costs $150.\n\nSo, the total amount he spent is:\n\n$$\n960 + 150 = \\boxed{1110}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Shannon eats **2 madeleine cookies per night** for **30 days**.\n\n- Total cookies needed = $ 2 \\text{ cookies/day} \\times 30 \\text{ days} = 60 \\text{ cookies} $\n- Each recipe makes **1 dozen** = 12 cookies\n\n- Number of dozens needed = $ \\frac{60 \\text{ cookies}}{12 \\text{ cookies/dozen}} = 5 \\text{ dozens} $\n\n### Final Answer:\n$$\n\\boxed{5} \\text{ dozens of cookies}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total number of candles: 50,000\n- 5% of the candles have a defect that makes them smell like wet dog.\n- 5% of the candles also have a defect that makes them explode.\n\nWe are to find how many candles will **both** smell like wet dog and explode.\n\n### Step 1: Find the number of candles that smell like wet dog\n\n5% of 50,000 = $ 0.05 \\times 50,000 = 2,500 $\n\n### Step 2: Find the number of candles that both smell like wet dog and explode\n\nThis is the **intersection** of the two sets: those that smell like wet dog and those that explode" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Misha picks out 4 blouses from the 30% off rack. \n- Each blouse is **$20** in regular price. \n- 30% off means the price is **70%** of the original price. \n\nSo, the discounted price per blouse is: \n$$ 20 \\times 0.70 = 14 $$\n\nNow, multiply by 4 to find the total cost: \n$$ 14 \\times 4 = 56 $$\n\n**Final Answer:** $\\boxed{56}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n---\n\n### Step 1: Define variables\n\nLet:\n- $ A $ = number of apples Joanne gathers from the **average trees**\n- $ B $ = number of apples Joanne gathers from the **shortest trees**\n- $ C $ = number of apples Joanne gathers from the **tallest trees**\n\nFrom the problem:\n- Joanne gathers **30 apples** from the tallest trees: $ C = 30 $\n- She gathers **half** from the shortest trees: $ B = \\frac{1}{2} \\times 30 = 15 $\n- She gathers **more** from the average trees: $ A > 15 $\n\n---\n\n### Step 2: Determine the sister's apples\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total heads: 180 \n- Total bumps: 304 \n- Camels have **2 humps** each \n- Dromedaries have **1 hump** each \n\nLet:\n\n- $ x $ = number of camels \n- $ y $ = number of dromedaries \n\nWe can set up the following system of equations:\n\n1. $ x + y = 180 $ (total heads) \n2. $ 2x + y = 304 $ (total bumps) \n\nSubtract the first equation from the second:\n\n$$\n(2x + y) - (x + y) = 304 - 180 \\\\\nx = 124\n$$\n\nSo" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tom's trip consists of two weeks. Let's break it down:\n\n- **First 4 days**: He traveled 200 km/day. \n Total distance: $ 4 \\times 200 = 800 $ km.\n\n- **Next 2 days**: He traveled 30% of the first 4 days' distance. \n $ 0.3 \\times 800 = 240 $ km.\n\n- **On the next day**: He didn't travel at all.\n\n- **Second week**: He traveled 300 km/day for 7 days (since 2 weeks = 14 days, and 14 - 7 = 7). \n Total distance: $ 7 \\times 3" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Peter's locker is **1/4 as big as Zack's locker**.\n- Peter's locker is **5 cubic inches**.\n- We are to find **Timothy's locker** in cubic inches.\n\n---\n\n### Step 1: Find Zack's locker size\n\nSince Peter's locker is **1/4 as big as Zack's**, we can write:\n\n$$\n\\text{Peter's locker} = \\frac{1}{4} \\times \\text{Zack's locker}\n$$\n\n$$\n5 = \\frac{1}{4} \\times \\text{Zack's locker}\n$$\n\nMultiply both sides by 4:\n\n$$\n\\text{Zack's locker} = 5 \\times 4 = 20 \\text" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Stanley's comb fell 4,000 feet from an elevation of 10,000 feet to a ledge below. So, the comb is now at:\n\n$$\n10,000 - 4,000 = 6,000 \\text{ feet}\n$$\n\nOliver is at an elevation of 3,000 feet. To reach the elevation of Stanley's comb (6,000 feet), he must climb:\n\n$$\n6,000 - 3,000 = 3,000 \\text{ feet}\n$$\n\n**Final Answer:** $\\boxed{3000}$ feet." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Josue initially had $5000 in capital.\n\n- The first bank gave him $4000.\n- The second company gave him twice as much as the first bank, so $2 \\times 4000 = 8000.\n\nNow, add the amounts together:\n\n$$\n5000 + 4000 + 8000 = \\boxed{17000}\n$$\n\nMr. Josue now has **$17,000** in capital." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 50 cats on the rock initially.\n- 4 boats carry away 5 cats each: \n $ 4 \\times 5 = 20 $ cats.\n- Then, $ \\frac{3}{5} $ of the remaining cats ran after a mouse: \n $ \\frac{3}{5} \\times (50 - 20) = \\frac{3}{5} \\times 30 = 18 $ cats.\n\nSo, the total number of cats left on the rock is:\n\n$$\n50 - 20 - 18 = 12\n$$\n\n**Final Answer:** $\\boxed{12}$ cats." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break down the cost of 2 years (24 months) of the service:\n\n- **First 6 months**: $8/month \n- **Next 8 months**: $12/month \n- **Remaining 12 months**: $14/month \n\nSo, the total cost is:\n\n$$\n6 \\times 8 + 8 \\times 12 + 12 \\times 14\n$$\n\n$$\n= 48 + 96 + 168 = \\boxed{312} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{312}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n- The **tattered jeans** cost **$28**.\n- The **jogger jeans** cost **$6 less than the tattered jeans**, so:\n $$\n \\text{Jogger jeans} = 28 - 6 = 22\n $$\n- He **saved a total of $6**.\n- He **saved 1/3 of the total savings from the jogger jeans** and the **rest from the tattered jeans**.\n\nLet’s denote:\n- $ x $ = cost of the tattered jeans\n- $ y $ = cost of the jogger jeans\n\nWe are given:\n- $ x = 28 $\n- $ y = x - 6" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- 4 buses can hold 60 employees each.\n- 6 minibuses can hold 30 employees each.\n- 10 minivans can hold 15 employees each.\n\nWe need to find the total number of employees that can join the day trip.\n\n### Step 1: Calculate the total capacity of each type of vehicle\n\n- **Buses**: \n $ 4 \\text{ buses} \\times 60 = 240 $ employees\n\n- **Minibuses**: \n $ 6 \\text{ minibuses} \\times 30 = 180 $ employees\n\n- **Minivans**: \n $ 10 \\text{ minivans} \\times 15" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Lillian builds 3 bird feeders and buys 3 others, so she has a total of:\n\n$$\n3 + 3 = 6 \\text{ bird feeders}\n$$\n\nEach store-bought feeder attracts **10 more birds** than the feeders she made herself. Since she made 3 feeders, each attracting 10 birds, she expects:\n\n$$\n3 \\times 10 = 30 \\text{ birds}\n$$\n\nSo, the total number of birds she can expect to see in her garden each day is:\n\n$$\n6 \\text{ feeders} \\times 30 \\text{ birds per feeder} = \\boxed{180} \\text{ birds} \\text{ total} \\text{ each day}." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Aleksandra ordered:\n\n- A **bagel** for $4 \n- A **soup** that is **25% more** than the bagel: \n $ 25\\% \\text{ of } 4 = 1 $, so the soup costs $4 + 1 = \\$5 $ \n- A **cake** that is **half the price of the bagel**: \n $ \\frac{1}{2} \\times 4 = 2 $, so the cake costs $2\n\nNow, add all the costs together:\n\n$$\n4 + 5 + 2 = \\boxed{11}\n$$\n\nAleksandra needs to pay **\\$11** for the dinner." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the number of cards Kenny has.\n\nHe sells $ x $ cards for $1.5 each, so he earns:\n\n$$\n1.5x\n$$\n\nHe keeps $ \\frac{1}{3} $ of the cards, so he keeps:\n\n$$\n\\frac{1}{3}x\n$$\n\nHe gets to go to the amusement park with $50 in cash, so the remaining money he has is:\n\n$$\n1.5x - \\frac{1}{3}x - 50 = 0\n$$\n\nSimplify:\n\n$$\n\\frac{4}{3}x - 50 = 0\n$$\n\n$$\n\\frac{4}{3}x = 50\n$$\n\n$$\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- Total guests: 36\n- Half of the guests (i.e., 18) were given **two hotdogs**.\n- 40 guests showed up, and everyone wanted a **second hotdog**.\n\nSo, the number of guests who **did not** get a second hotdog is:\n\n$$\n36 - 18 = \\boxed{18}\n$$\n\n**Answer:** $\\boxed{18}$ guests did not get a second hotdog." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Let the number of letters in Indras' name be $ x $.\n\n- Indras has 6 letters in her name.\n\nSo, $ x = 6 $.\n\n---\n\n### Step 2: The sister's name has **4 more letters than half of the letters in Indras' name**.\n\n- Half of Indras' name: $ \\frac{6}{2} = 3 $\n- The sister's name has 4 more letters than that: $ 3 + 4 = 7 $\n\n---\n\n### Step 3: Add the number of letters in Indras and her sister's names.\n\n- Indras: 6 letters \n- Sister: 7 letters \n- Total: $ " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Charlotte's order includes:\n\n- A set of pot and pans: $120.00 \n- A set of mixing bowls: $20.00 \n- 5 utensils at $5.00 each: $25.00 \n\nTotal cost before discount: \n$120.00 + $20.00 + $25.00 = **$165.00**\n\nThe clerk told her everything was **20% off**. \nSo, the discount is: \n$165.00 × 20% = $33.00 \n\nFinal amount: \n$165.00 - $33.00 = **$132.00" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dora has saved $2 and her mother gave her $16, so she has a total of:\n\n$$\n2 + 16 = 18 \\text{ dollars}\n$$\n\nThe total cost of the items she wants to buy is:\n\n$$\n6 + 11 + 2 = 19 \\text{ dollars}\n$$\n\nSo, the amount she **needs** more is:\n\n$$\n19 - 18 = \\boxed{1} \\text{ dollar}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Define the unknowns\n\nLet:\n- $ x $ = number of dragons slain by **Prince Thaddeus**\n- $ y $ = number of dragons slain by **Prince Arthur**\n- $ z $ = number of dragons slain by **Prince Walter**\n- $ w $ = number of dragons slain by **Prince Bruce**\n\nWe are given:\n\n- $ x = 100 $\n- $ y = \\frac{3}{4}x = \\frac{3}{4} \\times 100 = 75 $\n- $ z = 2y = 2 \\times 75 = 150 $\n- $ w = \\frac{1}{5}z = \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- 15 gallons of gas were equally divided into **5 containers**.\n- Josey needed **1/4 of a container** to run her lawnmower.\n\n---\n\n### Step 1: Find the amount of gas in one container\n\n$$\n\\text{Gas per container} = \\frac{15}{5} = 3 \\text{ gallons}\n$$\n\n---\n\n### Step 2: Find the amount of gas Josey needed\n\n$$\n\\text{Gas needed} = \\frac{1}{4} \\times 3 = \\frac{3}{4} \\text{ gallons}\n$$\n\n---\n\n### Step 3: Convert gallons to pints\n\nSince 1 gallon = 8 pints:\n\n$$\n\\frac{3" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Let the number of candy bars George bought be $ x $.\n\n- Each candy bar costs **75 cents**.\n- George spent **$5** (i.e., 500 cents).\n- He had **1% of his money left**.\n\nSo, the amount he spent is **90%** of his total money.\n\n---\n\n### Step 2: Set up the equation.\n\nHe spent 90% of his money, so:\n\n$$\n0.9 \\times 500 = 450 \\text{ cents}\n$$\n\nHe spent **450 cents**, and he had **1%** left, so the remaining amount is:\n\n$$\n0.01" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ray had 25 lollipops. He kept 5 lollipops for himself, so the remaining is:\n\n$$\n25 - 5 = 20 \\text{ lollipops}\n$$\n\nHe shared the remaining 20 lollipops equally among his 4 friends:\n\n$$\n\\frac{20}{4} = 5\n$$\n\nSo, each of his friends received **5 lollipops**.\n\n$$\n\\boxed{5}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Rory makes a cake that weighs **20 ounces**, and she cuts it into **8 pieces**. Rory and her mom each have **1 piece**. \n\nSo, the remaining cake is:\n\n$$\n20 - 8 = 12 \\text{ ounces}\n$$\n\n**Answer:** $\\boxed{12}$ ounces." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Sitti and Juris bought 34 and 22 oranges, respectively. \nThey share the oranges equally with their 6 other friends. \n\nSo, the total number of oranges is: \n$$ 34 + 22 = 56 $$\n\nThey share them equally with 6 friends, so: \n$$ \\frac{56}{6} = 9 \\text{ oranges per person} $$\n\n**Answer:** $\\boxed{9}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Antoine's recipe requires **2 pounds of onions**.\n- He **doubles** that amount, so he uses **4 pounds of onions**.\n- The onions are **on sale for $2.00 per pound**.\n- He **serves 6 people**.\n- He also needs **2 boxes of beef stock**, which are **on sale for $2.00 per box**.\n\nWe are to find the **cost per serving**.\n\n---\n\n### Step 1: Calculate the cost of onions\n\n- 2 pounds of onions at $2.00 per pound = $2.00 × 2 = **$4.00**\n\n- 4 pounds of onions at $2.00 per pound = $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- **Wayne** drives to the theater in **4 minutes**.\n- **Bernadette** drives to the theater **5 minutes** early.\n- The **drive from Bernadette’s apartment** takes **4 times as long** as the drive from Wayne’s hotel.\n\nLet’s denote:\n\n- Let $ x $ be the time (in minutes) that **Bernadette** leaves her apartment to arrive at the theater **5 minutes early**.\n\nThen:\n\n- The time it takes for **Bernadette** to drive from her apartment to the theater is $ 4x $ minutes.\n- The time it takes for **Wayne** to drive from his hotel to the theater is 4 minutes.\n\nWe are told that the drive from **Bernadette" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Area of the bedroom: $ 360 \\, \\text{square feet} $\n- Length of the room: $ 3 \\, \\text{yards} $\n\n---\n\n### Step 1: Convert the length from yards to feet\n\nSince 1 yard = 3 feet:\n\n$$\n3 \\, \\text{yards} = 3 \\times 3 = 9 \\, \\text{feet}\n$$\n\n---\n\n### Step 2: Use the formula for the area of a rectangle\n\n$$\n\\text{Area} = \\text{Length} \\times \\text{Width}\n$$\n\nWe know the area is 360 square feet, and the length is 9 feet. Let the width be $ x $:\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- **Elizabeth** bought: \n - 1 pack of red beads \n - 2 packs of clear beads \n - Total beads: $1 \\times 20 + 2 \\times 20 = 60$ beads\n\n- **Margareth** bought: \n - 3 packs of blue beads \n - 4 packs of red beads \n - Total beads: $3 \\times 20 + 4 \\times 20 = 140$ beads\n\nNow, we calculate the difference:\n\n$$\n140 - 60 = \\boxed{80}\n$$\n\n**Answer:** $\\boxed{80}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Marcus starts with a house temperature of **40 degrees**.\n\nHe spends **3 hours baking**, and during this time, the oven raises the temperature by:\n\n$$\n3 \\text{ hours} \\times 5 \\text{ degrees/hour} = 15 \\text{ degrees}\n$$\n\nSo, after baking, the temperature is:\n\n$$\n40 + 15 = 55 \\text{ degrees}\n$$\n\nThen, Marcus opens a window for **30 minutes**, and the house cools down by:\n\n$$\n\\frac{2 \\text{ degrees}}{10 \\text{ minutes}} \\times 30 \\text{ minutes} = 6 \\text{ degrees}\n$$\n\nSo, the final temperature is:\n\n$$\n55" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Jon's total time:\n - Swim: 40 minutes\n - Bike: 1 hour (60 minutes)\n - Run: 50 minutes\n\n- James finishes the swim **10% faster** than Jon, but **5 minutes longer** on the bike.\n\nLet’s denote:\n\n- Jon's total time: $ T = 40 + 60 + 50 = 150 $ minutes\n\n- James's total time:\n - Swim: $ 40 + 0.10 \\times 40 = 40 + 4 = 44 $ minutes\n - Bike: $ 60 + 5 = 65 $ minutes\n - Run:" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Movie A is **one-fourth** the length of Movie B.\n- Movie B is **5 minutes longer** than Movie C.\n- Movie C is **1.25 hours** long.\n\n---\n\n### Step 1: Convert all times to minutes\n\n- 1.25 hours = 1.25 × 60 = **75 minutes**\n\nNow, we can write the relationships:\n\n- Let $ x $ = length of Movie C = 75 minutes \n- Then, length of Movie B = $ x + 5 = 75 + 5 = 80 $ minutes \n- Length of Movie A = $ \\frac{1}{4} \\times \\text{length of Movie B} = \\frac{1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "First, convert the time from minutes to hours:\n\n$$\n30 \\text{ minutes} = \\frac{30}{60} = 0.5 \\text{ hours}\n$$\n\nNow, calculate the distance the horse runs:\n\n$$\n\\text{Distance} = \\text{Speed} \\times \\text{Time} = 32 \\text{ mph} \\times 0.5 \\text{ hours} = 16 \\text{ miles}\n$$\n\nSince the horse runs 16 miles for every 2 miles of hay eaten, the number of bails of hay needed is:\n\n$$\n\\frac{16}{2} = 8 \\text{ bails}\n$$\n\nEach bail costs $3, so the total cost of" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Rozanne uses:\n\n- 4 dozen eggs = 4 × 12 = **48 eggs**\n- 2 eggs that were loose in the cupboard\n\nSo, total eggs used = 48 + 2 = **50 eggs**\n\nShe puts out **trays that each hold 5 glasses of eggnog**, and each glass needs **5 eggs**.\n\nSo, the number of trays = total eggs ÷ eggs per glass = 50 ÷ 5 = **10 trays**\n\n**Answer:** $\\boxed{10}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joey starts with **214 points**. He scores **26 points**, so his total becomes:\n\n$$\n214 + 26 = 240 \\text{ points}\n$$\n\nMarcy starts with **225 points** and scores **10 points**, so her total becomes:\n\n$$\n225 + 10 = 235 \\text{ points}\n$$\n\nNow, to find out how many points Joey is winning, we subtract Marcy's total from Joey's total:\n\n$$\n240 - 235 = 5 \\text{ points}\n$$\n\n### Final Answer:\n$$\n\\boxed{5} \\text{ points}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total sneakers bought: 48 \n- Total cost: $576 \n- 17 sneakers sold at $20 each (flash sale on Monday) \n- Remaining 31 sneakers sold at $25 each (throughout the week)\n\n### Step 1: Calculate total revenue from Monday\n\n$$\n17 \\times 20 = 340\n$$\n\n### Step 2: Calculate total revenue from the rest of the week\n\n$$\n31 \\times 25 = 775\n$$\n\n### Step 3: Total revenue\n\n$$\n340 + 775 = 1115\n$$\n\n### Step 4: Total cost\n\n$$\n576\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Beatrice bought:\n\n- 6 packets × 8 pieces = 48 pieces \n- 4 packets × 16 pieces = 64 pieces\n\nTotal number of colors = 48 + 64 = **112**\n\n$$\n\\boxed{112}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A **super ticket** costs **$20**.\n- It includes movie rights and a **popcorn with a soda** for **$1** extra.\n- A **regular ticket** costs **$12**.\n- The **regular price of popcorn** is **$x**.\n- The **soda costs $3**.\n- You **did not buy the super ticket** and **saved $2**.\n\nLet's break it down:\n\n### Step 1: Cost of the super ticket\n- Super ticket: $20 (includes movie rights and popcorn + soda for $1 extra)\n\n### Step 2: Cost of the regular ticket\n- Regular ticket: $12 (includes movie rights, popcorn, and soda)\n\n### Step " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Let the original cost of filling one balloon be $ x $ dollars.\n\n- On the first day, the cost of filling 20 balloons was $900.\n- So, the original cost per balloon is:\n $$\n x = \\frac{900}{20} = 45 \\text{ dollars}\n $$\n\n---\n\n### Step 2: The price increased by $20 on two days later.\n\n- So, the new cost per balloon is:\n $$\n 45 + 20 = 65 \\text{ dollars}\n $$\n\n---\n\n### Step 3: Calculate the cost of filling 170 balloons at the new price:\n\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find the **average speed** of the car during the trip, we use the formula:\n\n$$\n\\text{Average speed} = \\frac{\\text{Total distance}}{\\text{Total time}}\n$$\n\n### Step 1: Calculate total distance\n\n- The car drives at **60 mph** for **2 hours**:\n $$\n \\text{Distance} = 60 \\, \\text{mph} \\times 2 \\, \\text{hours} = 120 \\, \\text{miles}\n $$\n\n- The car drives at **30 mph** for **1 hour**:\n $$\n \\text{Distance} = 30 \\, \\text{mph} \\times 1 \\, \\text" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jenna starts with 8 sapphires. She trades 3 sapphires for 2 rubies. So, she gains 2 rubies for every 3 sapphires traded.\n\nLet's calculate the total value:\n\n- Sapphires: 8 sapphires × $800 = $6,400\n- Rubies: 2 rubies × $1200 = $2,400\n\nNow, since she trades 3 sapphires for 2 rubies, the value of the rubies is 2/3 of the value of the sapphires. So:\n\n- Value of rubies = $2,400\n- Value of sapphires = $6" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Marin and his neighbor Nancy each eat 4 apples a day. \nIn 30 days, they eat:\n\n$$\n4 \\text{ apples/day} \\times 30 \\text{ days} = 120 \\text{ apples}\n$$\n\n**Answer:** $\\boxed{120}$ apples." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bob has 10 raised beds, each of which is 2 feet wide, 8 feet long, and 2 feet tall.\n\n### Step 1: Calculate the volume of one raised bed\n$$\n\\text{Volume} = \\text{width} \\times \\text{length} \\times \\text{height} = 2 \\times 8 \\times 2 = 32 \\text{ cubic feet}\n$$\n\n### Step 2: Calculate the total volume of all 10 raised beds\n$$\n\\text{Total volume} = 10 \\times 32 = 320 \\text{ cubic feet}\n$$\n\n### Step 3: Determine the number of bags needed\nEach bag holds 2 cubic feet, so:\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **15 red cards**.\n- There are **60% more green cards** than red.\n- Yellow cards are as many as the **sum of red and green cards**.\n\n---\n\n### Step 1: Find the number of green cards\n\nSince there are **60% more green cards** than red:\n\n$$\n\\text{Green cards} = \\text{Red cards} + 60\\% \\times \\text{Red cards} = 15 + 0.6 \\times 15 = 15 + 9 = 24\n$$\n\n---\n\n### Step 2: Find the number of yellow cards\n\nYellow cards = **sum of red and green cards**\n\n$$\n\\text{Yellow cards" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Katelyn saw **50 fairies** flying.\n\n- After **20 minutes**, one of her friends saw **half as many** fairies as Katelyn saw come from the east and join the fairies that were there. \n So, half of 50 is **25**.\n\n- Therefore, **25 fairies** joined the original 50, making a total of **75**.\n\n- Ten minutes later, **30 fairies** flew away.\n\nSo, the number of fairies remaining is:\n\n$$\n75 - 30 = \\boxed{45}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jennifer's dog has 8 puppies, 3 of which have spots. \nBrandon's dog has 12 puppies, 4 of which have spots. \n\nTotal number of puppies = 8 + 12 = 20. \nNumber of puppies with spots = 3 + 4 = 7. \n\nPercentage of all puppies with spots = (7 / 20) × 100 = **35%**. \n\n$$\n\\boxed{35}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following quantities of feed:\n\n- **Sugars**: 2 boxes × 1 lb = 2 lb \n- **Carrots**: 4 bags × 12 lb = 48 lb \n- **Hay**: 42 bales × 75 lb = 3150 lb \n- **Oats**: 20 sacks × 65 lb = 1300 lb \n\nTotal weight = 2 + 48 + 3150 + 1300 = **3500 lb**\n\nThe truck can carry **2250 pounds at a time**.\n\nNow, to find how many trips are needed:\n\n$$\n\\frac{3500}{2250} =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Grayson drinks:\n\n- **3 aluminum cans** of soda, each worth **2 cents** → $ 3 \\times 2 = 6 $ cents \n- **5 plastic bottles** of water, each worth **3 cents** → $ 5 \\times 3 = 15 $ cents \n\nTotal earnings per week: \n$ 6 + 15 = 21 $ cents\n\nIn a **4-week month**, she earns: \n$ 21 \\times 4 = 84 $ cents\n\n### Final Answer: \n$$\n\\boxed{84}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Frederick has 10 plants.\n- Toni has **60% more** plants than Frederick.\n- Shondra has **7 fewer** plants than Toni.\n\n---\n\n### Step 1: Find the number of plants Toni has\n\nToni has **60% more** than Frederick.\n\n$$\n\\text{Toni} = \\text{Frederick} + 60\\% \\times \\text{Frederick} = 10 + 0.6 \\times 10 = 10 + 6 = 16\n$$\n\nSo, Toni has **16 plants**.\n\n---\n\n### Step 2: Find the number of plants Shondra has\n\nShondra has **7 fewer** plants than Toni.\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ali had $21.\n\nLeila gave him half of her $100, which is:\n\n$$\n\\frac{1}{2} \\times 100 = 50\n$$\n\nSo, Ali now has:\n\n$$\n21 + 50 = \\boxed{71}\n$$\n\nAli now has **$71**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ashley's pizza delivery costs **$15**, and she wants to give a **tip that is 1/5 of the amount she ordered**.\n\nLet the amount she ordered be $ x $. Then:\n\n- Delivery cost: $ 15 $\n- Tip: $ \\frac{1}{5}x $\n\nTotal amount Ashley should pay is:\n\n$$\n15 + \\frac{1}{5}x\n$$\n\nSince the problem does not specify the amount she ordered, we cannot determine the exact total amount unless we assume a value for $ x $. However, if we assume that the amount she ordered is the same as the delivery cost, then:\n\n$$\n\\text{Total amount} = 15 + \\frac{1}{5} \\times 15" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Finley started in **first place**. \n- She fell back 5 spots: **first → sixth** \n- Then moved ahead 2 spots: **sixth → eighth** \n- Then fell behind 3 spots: **eighth → fifth** \n- Finally, she jumped ahead 1 spot: **fifth → fifth** \n\nSo, she **finishes in fifth place**.\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Miss Maria has:\n\n- **6 decks × 25 basketball cards per deck** = **150 basketball cards**\n- **5 boxes × 40 baseball cards per box** = **200 baseball cards**\n\nShe keeps **50 cards** and gives the remaining to her students.\n\nSo, the number of cards she gives to her students is:\n\n$$\n150 + 200 - 50 = 300\n$$\n\nShe gives **10 cards to each student**, so the number of students is:\n\n$$\n\\frac{300}{10} = 30\n$$\n\n**Answer:** $\\boxed{30}$ students." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Becky bought 20 apples for 45 cents each, and received a $1 discount. So, Becky's total cost is:\n\n$$\n20 \\times 45 = 900 \\text{ cents} \\\\\n\\text{After discount: } 900 - 100 = 800 \\text{ cents}\n$$\n\nKelly bought 20 apples for 50 cents each, and received a 10% discount. So, Kelly's total cost is:\n\n$$\n20 \\times 50 = 1000 \\text{ cents} \\\\\n\\text{After 10% discount: } 1000 - 100 = 900 \\text{ cents}\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n- Each room has:\n - 2 sheets\n - 1 comforter\n - 2 pillow cases\n - 2 towels\n\nSo, per room, the total number of items is:\n$$\n2 \\text{ sheets} + 1 \\text{ comforter} + 2 \\text{ pillow cases} + 2 \\text{ towels} = 7 \\text{ items per room}\n$$\n\nNow, we need to find the total number of pieces of laundry in **80 rooms**:\n$$\n80 \\text{ rooms} \\times 7 \\text{ items per room} = 560 \\text{ pieces of laundry}\n$$\n\n### Final Answer:\n$$\n\\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Frank starts with **200 shoes**.\n\n- On **Monday**, he gets **5 pairs** of shoes: \n $ 5 \\times 2 = 10 $ shoes.\n\n- On **Wednesday**, he gains **15 new pairs**: \n $ 15 \\times 2 = 30 $ shoes.\n\n- On **Friday**, he gains **30 new pairs**: \n $ 30 \\times 2 = 60 $ shoes.\n\n- On **Saturday**, he **gains 180 shoes**.\n\nNow, let's calculate the total number of shoes he has on **Sunday**:\n\n$$\n\\text{Total shoes} = 200 + 10 + 30 + 60 - " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mary has 6 jars of sprinkles, and each jar can decorate 8 cupcakes. So, the total number of cupcakes she can decorate is:\n\n$$\n6 \\times 8 = 48 \\text{ cupcakes}\n$$\n\nEach pan holds 12 cupcakes, so the number of pans she needs to bake is:\n\n$$\n\\frac{48}{12} = 4\n$$\n\n**Final Answer:** $\\boxed{4}$ pans worth of cupcakes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. The price of the pen is $2.\n2. The price of the paper is $1 less than three times the price of the pen:\n $$\n 3 \\times 2 = 6 \\Rightarrow 6 - 1 = 5\n $$\n So, the paper costs $5.\n3. The total cost of the pen and the paper is:\n $$\n 2 + 5 = 7\n $$\n4. Theo gave the cashier $10.\n5. The amount of change she received is:\n $$\n 10 - 7 = \\boxed{3}\n $$\n\n**Answer:** $\\boxed{3}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **30 students** in Marissa’s class.\n- Each student started with **10 pencils**.\n- **1/5** of the total pencils were used.\n- **1/3** of the remaining pencils were left at the end of the year.\n\n---\n\n### Step 1: Total pencils initially\n\n$$\n\\text{Total pencils} = 30 \\times 10 = 300\n$$\n\n---\n\n### Step 2: Pencils used\n\n$$\n\\frac{1}{5} \\text{ of } 300 = 60\n$$\n\nSo, **60 pencils were used**.\n\n---\n\n### Step 3: Remaining pencils after use\n\n$$\n300 - " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the number of carrot sticks Matt eats as $ x $. According to the problem:\n\n- Matt wants to eat **5 cookies** in total.\n- He eats **half as many cookies as the number of carrot sticks** plus **2 extra for cleaning his room**.\n\nSo, the equation is:\n\n$$\n\\text{Cookies} = \\frac{1}{2}x + 2\n$$\n\nWe are told that Matt wants to eat **5 cookies**, so:\n\n$$\n\\frac{1}{2}x + 2 = 5\n$$\n\nSubtract 2 from both sides:\n\n$$\n\\frac{1}{2}x = 3\n$$\n\nMultiply both sides by 2:\n\n$$\nx = 6\n$$\n\n### Final Answer" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Benny saw a **10-foot** shark with **2 remoras**, each **6 inches** long. \n\nFirst, convert the shark's body length to inches: \n$$ 10 \\text{ feet} = 10 \\times 12 = 120 \\text{ inches} $$\n\nNow, calculate the combined length of the remoras: \n$$ 2 \\times 6 = 12 \\text{ inches} $$\n\nTo find the percentage of the shark's body length that the remoras occupy: \n$$ \\frac{12}{120} \\times 100 = 10\\% $$\n\n**Answer:** $\\boxed{10\\%}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Three-fourths of students have a desktop computer at home.\n- 20 students do **not** have desktop computers.\n\nLet the total number of students be $ x $.\n\n- 3/4 of $ x $ have desktop computers: $ \\frac{3}{4}x $\n- The remaining 1/4 of $ x $ do **not** have desktop computers: $ x - \\frac{3}{4}x = \\frac{1}{4}x $\n\nWe are told that 20 students do **not** have desktop computers:\n\n$$\n\\frac{1}{4}x = 20\n$$\n\nSolving for $ x $:\n\n$$\nx = 20 \\times 4 = 80\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jason wants to try out for the track team in **3 weeks**. He walks **4 days a week** to break in the new shoes.\n\n- Total time for 3 weeks: \n $ 3 \\text{ weeks} \\times 4 \\text{ days/week} = 12 \\text{ days} $\n\n- Time per day: \n $ \\frac{12 \\text{ days}}{1} = 12 \\text{ days} $\n\nSo, Jason has **12 days** to spend walking each day. \n\n$$\n\\boxed{12} \\text{ days}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah spent $300 on books, and each book costs $15. So, the number of books is:\n\n$$\n\\frac{300}{15} = 20\n$$\n\nShe gave an equal number of books to her 4 kids. So, each child got:\n\n$$\n\\frac{20}{4} = 5\n$$\n\n**Answer:** $\\boxed{5}$ books." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 9 kids are allergic to **dairy**.\n- 6 kids are allergic to **peanuts**.\n- 3 kids are allergic to **both** dairy and peanuts.\n- There are **32 kids** in total.\n\nWe are to find how many **aren't allergic to anything**.\n\n---\n\n### Step 1: Find how many kids are allergic to **dairy only**.\n\nWe know:\n\n- Total = 32\n- 9 are allergic to **dairy**\n- 3 are allergic to both\n\nSo, the number of kids allergic to **dairy only** is:\n\n$$\n9 - 3 = 6\n$$\n\n---\n\n### Step 2: Find how many kids are allergic to **peanuts only**\n\nWe" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- There are **3 groups**, each with **200 employees**.\n- Each group is assigned **7 tour guides**.\n\nTo find the **total number of people going on the tour**, we calculate:\n\n$$\n\\text{Total people} = \\text{Number of groups} \\times \\text{Employees per group} = 3 \\times 200 = 600\n$$\n\nSo, the total number of people going on the tour is:\n\n$$\n\\boxed{600}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tom's trip includes:\n\n- **Plane tickets**: $5000 each \n- **Hotel**: 20% more expensive than normal ($1500 per day) \n- **Total days**: 3\n\n### Step 1: Calculate the cost of the hotel for 3 days\n\nThe normal price is $1500 per day. \n20% more expensive means the hotel cost is:\n\n$$\n1500 \\times 1.20 = 1800 \\text{ per day}\n$$\n\nFor 3 days:\n\n$$\n1800 \\times 3 = 5400\n$$\n\n### Step 2: Add the cost of the plane tickets\n\nThe plane tickets cost $5000 each" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ben has 4 blue tubes and 3 yellow tubes. \nJasper has half as many blue tubes as Ben: \n$$\n\\frac{1}{2} \\times 4 = 2 \\text{ blue tubes}\n$$\n\nJasper has three times as many yellow tubes as Ben: \n$$\n3 \\times 3 = 9 \\text{ yellow tubes}\n$$\n\nSo, Jasper has: \n$$\n2 \\text{ blue tubes} + 9 \\text{ yellow tubes} = \\boxed{11} \\text{ tubes of paint}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- The **1959 penny** weighs **48 grains**.\n- The **2010 penny** is **three-quarters** the weight of the 1959 penny.\n\n---\n\n### Step 1: Find the weight of the 2010 penny\n\n$$\n\\text{Weight of 2010 penny} = \\frac{3}{4} \\times 48 = 36 \\text{ grains}\n$$\n\n---\n\n### Step 2: Add the weights of both pennies\n\n$$\n\\text{Total weight} = 48 + 36 = 84 \\text{ grains}\n$$\n\n---\n\n### Final Answer:\n\n$$\n\\boxed{84} \\text{ grains}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Keegan earned $83 and Tasha earned $91. Together, they have earned:\n\n$$\n83 + 91 = 174\n$$\n\nThey need to raise $200 - $174 = $26 more.\n\n**Final Answer:** $\\boxed{26}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gabriel has 20 songs on his portable media player, and Luri has **3 times as many** songs as Gabriel. So:\n\n- Gabriel: 20 songs \n- Luri: $3 \\times 20 = 60$ songs\n\nNow, we need to find how many fewer songs Luri can add to his player **than** Gabriel can add.\n\n- Gabriel can add up to 100 songs \n- Luri can add up to 100 songs \n\nSo, the difference is:\n\n$$\n100 - 60 = 40\n$$\n\n**Answer:** $\\boxed{40}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Stetson ate $ \\frac{2}{5} $ of the 60 oranges. \nSo, the number of oranges he ate is: \n$$\n\\frac{2}{5} \\times 60 = 24 \\text{ oranges}\n$$\n\nSince he gave up $10 for each orange, the total amount of money he gave up is: \n$$\n24 \\times 10 = \\boxed{240} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jillian's handbag cost **$20 less than 3 times** as much as her shoes cost.\n\nGiven:\n- Her shoes cost $80.\n\nLet the cost of her handbag be $ x $.\n\nThen:\n$$\nx = 3 \\times 80 - 20 = 240 - 20 = 220\n$$\n\nSo, the cost of her handbag is **$220**.\n\n$$\n\\boxed{220}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James runs 12 miles a day for 5 days a week. \nHe runs at a rate of 10 miles per hour.\n\nTo find the total number of hours he runs in a week:\n\n$$\n\\text{Total hours} = \\text{Miles per day} \\times \\text{Days per week} \\times \\text{Rate per hour}\n$$\n\n$$\n\\text{Total hours} = 12 \\times 5 \\times 10 = 600 \\text{ hours}\n$$\n\n**Answer:** $\\boxed{600}$ hours." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Uncle Ben has **4 horses**, each consuming **5 pounds of oats per meal**, and he feeds them **twice a day**.\n\n### Step 1: Calculate the daily oats consumption per horse\n- Each horse eats **5 pounds per meal** \n- He feeds them **twice a day** \n- So, per horse per day: $ 5 \\, \\text{pounds/meal} \\times 2 = 10 \\, \\text{pounds/day} $\n\n### Step 2: Total daily consumption for all horses\n- 4 horses × 10 pounds/day = **40 pounds/day**\n\n### Step 3: Total oats needed for 5 days\n- 40 pounds/day × 5 days = **200" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jana has 27 puppies.\n\n- Two-thirds of the puppies are Pomeranians: \n $$\n \\frac{2}{3} \\times 27 = 18\n $$\n\n- One third of the Pomeranians are girls: \n $$\n \\frac{1}{3} \\times 18 = 6\n $$\n\n**Answer:** $\\boxed{6}$ girl Pomeranians." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "To find the **average highest temperature** of the three countries, we add up the temperatures and divide by 3:\n\n$$\n\\text{Average} = \\frac{-48 + 21 + (-3)}{3}\n$$\n\n$$\n\\text{Average} = \\frac{-48 + 21 - 3}{3} = \\frac{-30}{3} = -10\n$$\n\n### Final Answer:\n$$\n\\boxed{-10}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The child wants to save $12 in total. He already has $4, so the remaining amount to save is:\n\n$$\n12 - 4 = 8\n$$\n\nHe promises to save $2 daily. To find out how many days it will take him to save $8:\n\n$$\n\\frac{8}{2} = 4\n$$\n\nSo, it will take **4 days**.\n\n$$\n\\boxed{4} \\text{ days}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jaime has **64 eggs** and **2 trays**, each holding **24 eggs**.\n\n- First, calculate how many full trays he can place the eggs: \n $ 2 \\times 24 = 48 $ eggs.\n\n- Subtract the number of eggs he can place from the total: \n $ 64 - 48 = 16 $.\n\nSo, **16 eggs won't be able to be placed on the tray**.\n\n$$\n\\boxed{16}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sally buys:\n- 1 small pizza at $8,\n- 1 family-size pizza that costs 3 times as much as the small pizza, which is $3 \\times 8 = 24.\n\nSo, the total cost is:\n$$\n8 + 24 = \\boxed{32}\n$$\n\nSally spends **$32** in all." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Heather buys **2 packs** of razors, and each pack costs **$4.00**. The **discount** is **buy one get one free**, and she also has a **$2.00 coupon**.\n\n### Step 1: Calculate the total cost of 2 packs\n- Each pack costs $4.00, so 2 packs = $8.00.\n\n### Step 2: Apply the coupon\n- She gets **$2.00 off** on the total, so she pays $8.00 - $2.00 = **$6.00**.\n\n### Step 3: Calculate the cost per individual razor\n- She buys **2 packs**, so there are **4 razors** in total" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 9 out of 10 cheerleaders are **64\" tall**.\n- The **10th cheerleader** is **60\" tall**.\n- The pyramid has:\n - 4 girls on the **bottom**.\n - 3 girls on top of the 4.\n - 2 girls on top of the 3.\n - The **shortest girl** is at the **top**.\n\n---\n\n### Step 1: Determine the height of the shortest girl\n\nWe are told that the **shortest girl** is at the **top**. So, the **height of the shortest girl** is **60\"**.\n\n---\n\n### Step 2: Determine the height of the pyramid\n\nWe can count the layers" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Charisma works **8 hours** every day. \nShe walks **5 minutes** for each hour she's at work. \n\nSo, in 1 day: \n$$ 8 \\text{ hours} \\times 5 \\text{ minutes/hour} = 40 \\text{ minutes} $$\n\nAfter **5 days**: \n$$ 40 \\text{ minutes/day} \\times 5 \\text{ days} = 200 \\text{ minutes} $$\n\n**Final Answer:** \n$$\n\\boxed{200}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step.\n\nLet:\n- Brett's current age = 14 years\n- Let Angela's current age = $ x $ years\n\nIn **four years**, Brett will be $ 14 + 4 = 18 $ years old.\n\nAccording to the problem, in four years, Angela will be **three times as old** as Brett is now.\n\nSo, we can write the equation:\n\n$$\nx + 4 = 3 \\times 14\n$$\n\n$$\nx + 4 = 42\n$$\n\n$$\nx = 42 - 4 = 38\n$$\n\n### Final Answer:\n$$\n\\boxed{38}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Paul drives his car **twice a day** — once in the **morning** and once in the **afternoon**. \n- Each morning ride costs **$6**, \n- Each afternoon ride costs **$2**.\n\nHe does this **for 14 days**.\n\n### Step 1: Calculate the number of rides per day \n- 2 rides/day × 14 days = **28 rides**\n\n### Step 2: Calculate total cost \n- 28 rides × $6 (morning) + 28 rides × $2 (afternoon) \n- = $168 + $56 = **$224**\n\n### Final Answer: \n$$\n\\boxed{224}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. **Ashley's oranges**: \n She brought 5 boxes × 10 oranges per box = **50 oranges**.\n\n2. **Brianne's oranges**: \n She brought 20 more oranges than Ashley, so: \n $ 50 + 20 = 70 $ oranges.\n\n3. **Total oranges**: \n $ 50 + 70 = 120 $ oranges.\n\n4. **Number of greek orange pies**: \n Each pie requires 3 oranges, so: \n $ \\frac{120}{3} = 40 $ pies.\n\n**Final Answer**: \n$$\n\\boxed{40}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark is trying to choose between two venues for a surprise party:\n\n- **Venue 1**: $200 flat fee, no food.\n- **Venue 2**: $25 per person, with food included.\n\nWe are to find the number of guests $ x $ such that the total cost of both venues is equal.\n\n### Venue 1:\nCost = $200 (flat fee) + $5 per guest (food) = $205 per guest.\n\n### Venue 2:\nCost = $25 per guest (food included) = $25x.\n\nSet the costs equal:\n\n$$\n205x = 25x\n$$\n\nSubtract $25x$ from both sides:\n\n$$\n205x - 25" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ x $ be the number of insects Bodhi found.\n- Then David found half of what Bodhi found, so David found $ \\frac{x}{2} $.\n- Lily found 7 more than David, so Lily found $ \\frac{x}{2} + 7 $.\n\nThe total number of insects is 43:\n\n$$\nx + \\frac{x}{2} + \\frac{x}{2} + 7 = 43\n$$\n\nSimplify:\n\n$$\nx + x + 7 = 43\n$$\n\n$$\n2x + 7 = 43\n$$\n\n$$\n2x = 36\n$$\n\n$$\nx = 18\n$$\n\nSo, Bod" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mariah used $ \\frac{1}{4} $ of a skein of yarn, and her grandma used $ \\frac{1}{2} $ of a skein of yarn. There are 364 yards in a skein.\n\nSo, the total yards used is:\n\n$$\n\\frac{1}{4} + \\frac{1}{2} = \\frac{1}{4} + \\frac{2}{4} = \\frac{3}{4}\n$$\n\nMultiply by the number of yards in a skein:\n\n$$\n\\frac{3}{4} \\times 364 = \\frac{1092}{4} = 273\n$$\n\n**Answer:** $\\boxed{273}$ yards." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cherrie has:\n\n- 2 friends who want 5 gifts each: $2 \\times 5 = 10$ gifts \n- 3 friends who want 2 gifts each: $3 \\times 2 = 6$ gifts \n- 10 more random gifts\n\nSo, the total number of gifts Cherrie bought is:\n\n$$\n10 + 6 + 10 = \\boxed{26}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The rug is **5 feet wider** than the chair.\n- The couch is **2 feet longer than twice the width of the rug**.\n- The chair is **3 feet wide**.\n\n---\n\n### Step 1: Find the width of the rug\n\nSince the rug is **5 feet wider** than the chair, and the chair is **3 feet wide**, then:\n\n$$\n\\text{Width of rug} = \\text{Width of chair} + 5 = 3 + 5 = 8 \\text{ feet}\n$$\n\n---\n\n### Step 2: Find the length of the couch\n\nThe couch is **2 feet longer than twice the width of the rug**. So:\n\n$$\n\\text{Length of couch} = 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- Suzie bought **4 packs** of gum.\n- She got **2 packs** of **strawberry** gum.\n- She paid **$2** for a pack of **grape gum**.\n- She paid **half as much** for a **small pack of green apple gum**.\n- She paid **$7** in total.\n\nLet’s define the cost of each pack:\n\n- Let $ x $ be the cost of each strawberry gum pack.\n- The cost of each green apple gum pack is $ \\frac{1}{2}x $.\n\nNow, Suzie bought:\n- 2 strawberry gum packs: $ 2x $\n- 1 grape gum pack: $ 2 $\n- 1 green apple" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A **2 x 4** piece of wood can make **200 sticks**.\n- A **2 x 8** piece of wood can make **400 sticks**.\n- The cost of a **2 x 4** piece is **$4**.\n- The cost of a **2 x 8** piece is **$6**.\n- He has **$24** to spend on wood.\n\nWe want to **maximize the number of popsicles** he can make, **using the cheapest lumber**.\n\n---\n\n### Step 1: Determine the cost per stick\n\n- 200 sticks from 2 x 4: \n Cost = $4 → Cost per stick = $4 / 200 =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mario has 6 sled dogs, and each dog has 4 legs. So, the total number of legs is:\n\n$$\n6 \\text{ dogs} \\times 4 \\text{ legs per dog} = 24 \\text{ legs}\n$$\n\nEach pair of snowshoes costs $12.00, and each pair covers 2 legs. So, the number of pairs needed is:\n\n$$\n\\frac{24 \\text{ legs}}{2 \\text{ legs per pair}} = 12 \\text{ pairs}\n$$\n\nNow, the total cost is:\n\n$$\n12 \\text{ pairs} \\times \\$12.00 = \\$144.00\n$$\n\n$$\n\\boxed{\\$14" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Janet takes **two bus trips five days a week**. \nEach trip costs **$2.20**.\n\n### Step 1: Calculate total cost of trips \n$$\n2 \\text{ trips/day} \\times 5 \\text{ days} = 10 \\text{ trips/week}\n$$\n$$\n10 \\text{ trips/week} \\times \\$2.20 = \\$22.00\n$$\n\n### Step 2: Calculate cost of weekly bus pass \n$$\n\\$20\n$$\n\n### Step 3: Find the savings \n$$\n\\$22.00 - \\$20 = \\$2.00\n$$\n\n### Final Answer: \n$$\n\\boxed{\\$2.00" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The farm has **30 cows**.\n- The zoo has **20 sheep**.\n- The zoo has **twice as many cows as the farm**.\n- The farm has **half as many sheep as the zoo**.\n\nLet's break this down step by step:\n\n1. The zoo has **20 sheep**.\n2. The zoo has **twice as many cows as the farm**:\n - So, the number of cows in the zoo is $ 2 \\times 30 = 60 $.\n3. The farm has **half as many sheep as the zoo**:\n - So, the number of sheep in the farm is $ \\frac{1}{2} \\times 20 = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Rose bought **4 times the number of onions** as Sophia bought. \n So, if Sophia bought $ x $ onions, Rose bought $ 4x $ onions.\n\n- Rose also bought **4 times the number of potatoes** as Sophia bought. \n So, if Sophia bought $ y $ potatoes, Rose bought $ 4y $ potatoes.\n\n- We are given that Rose bought **12 onions** and **4 potatoes**.\n\nSo, from the information:\n\n- $ 4x = 12 $ → $ x = 3 $\n\n- $ 4y = 4 $ → $ y = 1 $\n\nNow, Sophia bought $ x = 3 $ onions and $ y = 1 $ potatoes.\n\n**" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Andy wants to lose **30 pounds** by his birthday on **July 19th**. He burns **3500 calories per pound**.\n\nTo find the **net calorie deficit** (calories burned minus calories consumed), we calculate:\n\n$$\n\\text{Total calories burned} = 30 \\, \\text{pounds} \\times 3500 \\, \\text{calories/pound} = 105,000 \\, \\text{calories}\n$$\n\nSince he is losing weight, the **net calorie deficit** is:\n\n$$\n\\text{Net deficit} = 105,000 \\, \\text{calories} - 0 = 105,000" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gerald works **$30 every day** and worked for **an entire week** (7 days). \nHe spent a total of **$100**.\n\nSo, the total amount he earned is:\n\n$$\n30 \\times 7 = 210\n$$\n\nHe spent **$100**, so the amount he has left is:\n\n$$\n210 - 100 = \\boxed{110}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Hannah needs to drink **60 ml per kilometer**.\n\nShe runs **8 laps**, and each lap is **0.25 km**.\n\nSo, the total distance she runs is:\n\n$$\n8 \\text{ laps} \\times 0.25 \\text{ km/lap} = 2 \\text{ km}\n$$\n\nNow, multiply by the amount of water per kilometer:\n\n$$\n2 \\text{ km} \\times 60 \\text{ ml/km} = 120 \\text{ ml}\n$$\n\n**Final Answer:** $\\boxed{120}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Julie had $500.\n\n1. She spent **20%** of it on clothes:\n $$\n 0.20 \\times 500 = 100\n $$\n So, she spent $100.\n\n2. She spent **25%** of the remaining money on CDs:\n $$\n 0.25 \\times (500 - 100) = 0.25 \\times 400 = 100\n $$\n So, she spent $100 on CDs.\n\n3. The remaining money is:\n $$\n 500 - 100 - 100 = 300\n $$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that the house and the lot together cost **$120,000**, and the house costs **three times as much as the lot**.\n\nLet the cost of the lot be $ x $. Then the cost of the house is $ 3x $.\n\nSo, the total cost is:\n$$\nx + 3x = 120,000\n$$\n\n$$\n4x = 120,000\n$$\n\n$$\nx = \\frac{120,000}{4} = 30,000\n$$\n\nTherefore, the house costs:\n$$\n3x = 3 \\times 30,000 = 90,000\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tara bought 8 packs of 5 canvas bags for $4 each, so the total cost is:\n\n$$\n8 \\times 4 = 32 \\text{ dollars}\n$$\n\nShe sold each bag for $8, so the total revenue is:\n\n$$\n8 \\times 5 = 40 \\text{ dollars}\n$$\n\nNow, to find the profit, subtract the cost from the revenue:\n\n$$\n40 - 32 = 8 \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{8}$ dollars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joe throws **25 punches per minute**, and a fight lasts **5 rounds of 3 minutes**.\n\nSo, the total number of punches Joe threw is:\n\n$$\n25 \\text{ punches/minute} \\times 3 \\text{ minutes} \\times 5 \\text{ rounds} = 375 \\text{ punches}\n$$\n\n**Final Answer:** $\\boxed{375}$ punches." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Suzanne made **36** cookies.\n- Josh made **one-fourth** the number of cookies that Suzanne made.\n- Kelsie made **two times more** than Josh.\n\n---\n\n### Step 1: Find how many cookies Josh made\n\nJosh made **one-fourth** of what Suzanne made:\n\n$$\n\\text{Josh} = \\frac{1}{4} \\times 36 = 9\n$$\n\n---\n\n### Step 2: Find how many cookies Kelsie made\n\nKelsie made **two times more** than Josh, which means:\n\n$$\n\\text{Kelsie} = 2 \\times 9 = 18\n$$\n\n---\n\n### ✅ Final Answer:\n\n$$\n\\boxed{18" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ali has:\n\n- 4 bills of $10: $4 \\times 10 = 40\n- 6 bills of $20: $6 \\times 20 = 120\n\nTotal money: \n$$ 40 + 120 = 160 $$\n\nHe gives half to his sister: \n$$ \\frac{1}{2} \\times 160 = 80 $$\n\nRemaining money after giving to sister: \n$$ 160 - 80 = 80 $$\n\nHe uses $3/5 of the remaining money to buy dinner: \n$$ \\frac{3}{5} \\times 80 = 48 $$\n\nRemaining money after buying dinner: \n$$ " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Royce takes **40 minutes more than double Rob** to shingle a house.\n\n- Rob takes **2 hours** = **120 minutes**.\n\n- So, double Rob's time = $ 2 \\times 120 = 240 $ minutes.\n\n- Royce takes **40 minutes more** than double Rob: \n $ 240 + 40 = 280 $ minutes.\n\n**Answer:** $\\boxed{280}$ minutes." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Martha has 3 grandchildren, and they are all the same size. She needs:\n\n- 1 hat: 2 skeins \n- 1 scarf: 4 skeins \n- 1 sweater: 12 skeins \n- 1 pair of mittens: 1 skein \n- 1 pair of socks: 2 skeins \n\nSo, total skeins needed:\n\n$$\n2 + 4 + 12 + 1 + 2 = 21 \\text{ skeins}\n$$\n\n**Answer:** $\\boxed{21}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Chris has 100 math problems in total.\n\n- **Monday**: 12 problems \n- **Tuesday**: 3 times as many as Monday = $3 \\times 12 = 36$ problems \n- **Wednesday**: One-quarter of the remaining problems = $ \\frac{1}{4} \\times (100 - 12 - 36) = \\frac{1}{4} \\times 42 = 10.5$ problems\n\nSo, the remaining problems on **Thursday** are:\n\n$$\n100 - 12 - 36 - 10.5 = 42 - 10.5 = 31.5\n$$\n\nSince the number of problems must be an integer" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tony picks 6 quarts per hour.\n\nBobby picks 1 less quart than Tony: \n$$ 6 - 1 = 5 \\text{ quarts per hour} $$\n\nKathy picks twice as many as Bobby: \n$$ 2 \\times 5 = 10 \\text{ quarts per hour} $$\n\nRicky picks 2 fewer quarts than Kathy: \n$$ 10 - 2 = 8 \\text{ quarts per hour} $$\n\nNow, add up the quarts picked by Tony, Bobby, Ricky, and Kathy:\n$$ 6 + 5 + 8 + 10 = \\boxed{30} \\text{ quarts per hour} $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We start with the total number of loaves baked:\n\n$$\n200 \\text{ loaves}\n$$\n\nThey sold:\n\n- 93 loaves in the morning \n- 39 loaves in the afternoon\n\nSo, the total loaves sold is:\n\n$$\n93 + 39 = 132 \\text{ loaves}\n$$\n\nThey returned 6 unsold loaves.\n\nTherefore, the number of loaves left is:\n\n$$\n200 - 132 - 6 = \\boxed{58} \\text{ loaves}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jackson has 36 red tulips and 24 blue tulips.\n\n- He can fit **6 red tulips** in a row.\n- He can fit **8 blue tulips** in a row.\n\n### Step 1: Calculate the number of rows for red tulips\n$$\n\\frac{36}{6} = 6 \\text{ rows}\n$$\n\n### Step 2: Calculate the number of rows for blue tulips\n$$\n\\frac{24}{8} = 3 \\text{ rows}\n$$\n\n### Step 3: Add the rows together\n$$\n6 + 3 = \\boxed{9}\n$$\n\n**Answer:** $\\boxed{9}$ rows of flowers." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Heather has 27 cups of raisins. She wants to divide them equally among **3** types of mixes: oatmeal cookies, granola, and snack mix.\n\n- Each batch of oatmeal cookies uses **$\\frac{3}{4}$** cups of raisins.\n- So, the number of batches she can make is:\n\n$$\n\\frac{27}{\\frac{3}{4}} = 27 \\times \\frac{4}{3} = 36\n$$\n\n**Answer:** $\\boxed{36}$ batches." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ada's daily electric consumption is 12 kilowatts per hour, and she adds a device that consumes 2 kilowatts per hour a day. The cost per kilowatt per hour is $1.50.\n\n### Before adding the device:\n- Daily consumption: 12 kWh\n- Cost: $12 \\times 1.50 = 18$ dollars\n\n### After adding the device:\n- Daily consumption: 14 kWh\n- Cost: $14 \\times 1.50 = 21$ dollars\n\n### Difference:\n$$\n21 - 18 = 3\n$$\n\n**Answer:** $\\boxed{3}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 1 person can paint **half a house** in **5 days**.\n\nWe are asked: **How many hours would it take for 5 people to paint a whole house?**\n\n---\n\n### Step 1: Find the rate of painting per person per day\n\n- 1 person paints **½ house** in **5 days**.\n\nSo, the rate is:\n\n$$\n\\frac{1}{5} \\text{ house per person per day}\n$$\n\n---\n\n### Step 2: Find the total work for 5 people\n\n- 5 people can paint **1 house** in **x days**.\n\nSo, the total work is:\n\n$$\n5 \\text{ people} \\times x \\text{ days} = 1 \\text{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Ophelia has **20 sofas**.\n- Each sofa is **2 fewer** than a chair.\n- Jenna has **3 times as many chairs** as Ophelia.\n\n---\n\n### Step 1: Find the number of chairs Ophelia has\n\nLet the number of chairs Ophelia has be $ x $.\n\nThen, since each sofa is 2 fewer than a chair, the number of chairs Ophelia has is:\n\n$$\nx = \\text{number of sofas} + 2 = 20 + 2 = 22\n$$\n\nSo, Ophelia has **22 chairs**.\n\n---\n\n### Step 2: Find the number of chairs Jenna has\n\nJenna has **3 times as many chairs** as" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tom bought a CD for $4 and a headphone set for a total of $48. Let's break this down:\n\n- The cost of the CD is $4.\n- The cost of the headphone set is $48 - $4 = $44.\n\nIf Tom had decided not to buy the headphone set, he would only be able to buy the CD for $4.\n\nSo, how many more CDs would he have been able to buy?\n\n$$\n\\frac{44}{4} = 11\n$$\n\n**Answer:** $\\boxed{11}$ more CDs." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Josh spent 4 hours every week **except on some occasions**, and **at one point**, he spent 5 hours each for two consecutive weeks. Another time, he spent 6 hours in one week.\n\nLet’s break it down:\n\n- He spent **4 hours** every week **except** on some occasions.\n- At one point, he spent **5 hours** for **2 consecutive weeks**.\n- At another point, he spent **6 hours** in **one week**.\n\nWe need to find the **total number of hours** he spent working out across the 8 weeks.\n\nLet’s assume that **only one occasion** (the 5-hour period) was not a regular 4-hour week. That means the other 7 weeks were 4 hours each.\n\nSo:\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 48 people are riding the bus.\n- On the **first stop**, 8 passengers get off, and 5 times as many get on.\n- On the **second stop**, 21 passengers get off, and 3 times fewer get on.\n\nLet's solve step by step.\n\n---\n\n### **First Stop:**\n\n- 8 passengers get off.\n- 5 times as many get on: \n $ 5 \\times 8 = 40 $ passengers get on.\n\nSo, after the first stop:\n\n- Total passengers = 48 (initial) - 8 (get off) + 40 (get on) \n = $ 48 - 8 + 40 = 80 $\n\n---\n\n### **" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Let:\n- $ x $ = current age of Jame\n- $ y $ = current age of his cousin\n\n---\n\n### Given:\n1. Jame will turn 27 in 5 years. \n So, $ x + 5 = 27 $ \n → $ x = 22 $\n\n2. In 8 years, Jame's age will be **5 years younger** than twice his cousin's age. \n So, $ x + 8 = 2(y - 5) $\n\n---\n\n### Substitute $ x = 22 $ into the second equation:\n\n$$\n22 + 8 = 2(y - 5)\n$$\n$$\n30 = 2y - 1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Errol bought a **computer**, **2 monitors**, and a **printer** for **$2,400**.\n- He paid **$400 less** for the **printer** than the **computer**.\n- The **computer** cost **$1,100**.\n\n---\n\n### Step 1: Find the cost of the printer\n\nHe paid **$400 less** for the printer than the computer.\n\n$$\n\\text{Cost of printer} = \\text{Cost of computer} - 400 = 1,100 - 400 = 700\n$$\n\n---\n\n### Step 2: Find the cost of one monitor\n\nWe know that Errol bought" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- There are **20 kids** in total.\n- They were divided into **two equal groups** of **girls and boys**.\n- The **boys** brought **60 shells each**.\n- The **girls** brought an amount equal to the number of shells brought by the boys **plus** four times as many seashells as the boys.\n\nLet’s define:\n\n- Let $ x $ be the number of seashells brought by each girl.\n\nWe are told:\n\n- The boys brought **60 shells each**, so the total number of shells brought by the boys is $ 60 \\times 2 = 120 $.\n- The girls brought an amount equal to the number of shells brought by the boys **plus** four" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. Let the number of candies George originally had be $ x $.\n\n2. According to the problem, Nick had **twice as many** candies as George. So, Nick had $ 2x $ candies.\n\n3. George ate 5 candies, and now he has 3 candies left. So, the total number of candies George has is:\n $$\n x - 5 = 3\n $$\n\n4. Solving for $ x $:\n $$\n x = 3 + 5 = 8\n $$\n\n5. Therefore, Nick had $ 2x = 2 \\times 8 = 16 $ candies.\n\n**Final Answer:** $\\boxed{16}$ candies." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Chenny is 10 years old. \nAlyana is 4 years younger than Chenny, so Alyana is:\n\n$$\n10 - 4 = 6 \\text{ years old}\n$$\n\nAnne is 2 years older than Alyana, so Anne is:\n\n$$\n6 + 2 = 8 \\text{ years old}\n$$\n\n**Final Answer:** $\\boxed{8}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the following thicknesses of the four books:\n\n- First book: 31 mm \n- Second book: 50 mm \n- Third book: 5 mm less than the second book → $ 50 - 5 = 45 $ mm \n- Fourth book: Twice as thick as the first book → $ 2 \\times 31 = 62 $ mm \n\nNow, add them all together:\n\n$$\n31 + 50 + 45 + 62 = \\boxed{188} \\text{ mm}\n$$\n\nThe total thickness of the four books is **188 mm**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Emma can make and upload **72 vlogs per month**, but she only made **18 vlogs** for the first week, **21 vlogs** for the second week, and **15 vlogs** for the third week. We need to find out how many vlogs she should do **to complete the 72 vlogs per month**.\n\n### Step-by-step:\n\n1. Add the vlogs she made in the first three weeks:\n $$\n 18 + 21 + 15 = 54\n $$\n\n2. Subtract this from the total vlogs she can make per month:\n $$\n 72 - 54 = 18\n $$\n\n### Final Answer:\n$$\n\\boxed" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Your wife wants to split the $50 dinner bill, and you want to pay an additional **20% tip**. Let's calculate the total amount you end up paying:\n\n1. **Calculate the tip amount:**\n $$\n 20\\% \\text{ of } \\$50 = 0.20 \\times 50 = \\$10\n $$\n\n2. **Add the tip to the original bill:**\n $$\n \\$50 + \\$10 = \\$60\n $$\n\n**Final Answer:** \n$$\n\\boxed{\\$60}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- 18 is shared among 3 boys.\n- The **eldest** added $5 to his share and another $10 the following day.\n- He spent $8 from his total.\n- After saving some more, he was able to **triply** the amount he had left after spending the $8.\n\nLet’s break it down step by step.\n\n---\n\n### Step 1: Find the eldest's initial share\n\n- 18 is shared among 3 boys.\n- So, each boy gets: \n $$\n \\frac{18}{3} = 6\n $$\n\nSo, the eldest's **initial share** is **$6**.\n\n---\n\n### Step 2: Add $5 and $1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break this down step by step.\n\nLet:\n- $ x $ = amount he saves **daily** in the **first half** of the month.\n- $ y $ = amount he saves **daily** in the **second half** of the month.\n\nWe are told:\n- He wants to save **twice as much daily** in the second half of the month as in the first half.\n- So, $ y = 2x $.\n\nHe has a **monthly saving target** of $1125.\n\nAssuming the month has **30 days**, the total amount he saves in the month is:\n$$\n\\text{Total} = x \\times 30 + y \\times 30 = 30(x + y)\n$$\n\nSub" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Verna bought:\n\n- 3 apples at $1.50 each: $3 \\times 1.50 = 4.50\n- 5 oranges at $0.80 each: $5 \\times 0.80 = 4.00\n- 6 peaches at $0.75 each: $6 \\times 0.75 = 4.50\n\nTotal cost: \n$4.50 (apples) + $4.00 (oranges) + $4.50 (peaches) = **$13.00**\n\nShe gave $20, so the change is: \n$20 - $13.00 = **$7.00" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jairus gets $0.8 per task, and Jenny gets $0.5 per task. Each of them finished 20 tasks.\n\n- Jairus gets: $0.8 × 20 = 16$ dollars \n- Jenny gets: $0.5 × 20 = 10$ dollars\n\nJairus gets **$16** and Jenny gets **$10**, so the difference is:\n\n$$\n16 - 10 = \\boxed{6} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the amount Jeff gets. Since Jeff gets 4 times as much as Brad, we can write:\n\n$$\nx = 4 \\times \\text{Brad's amount}\n$$\n\nLet $ y $ be the amount Brad gets. Then:\n\n$$\nx = 4y\n$$\n\nWe are told that the total amount is $ 100 $, so:\n\n$$\nx + y = 100\n$$\n\nSubstitute $ x = 4y $ into the equation:\n\n$$\n4y + y = 100\n$$\n\n$$\n5y = 100\n$$\n\n$$\ny = 20\n$$\n\nSo, Brad gets $ 20 $, and Jeff gets $ 4 \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jeff walks 3 miles to work and 3 miles back home each day. He works 5 times a week.\n\nSo, the total distance he walks per day is:\n$$ 3 \\text{ miles (to work)} + 3 \\text{ miles (back home)} = 6 \\text{ miles per day} $$\n\nHe works 5 times a week, so the total distance he walks is:\n$$ 6 \\text{ miles/day} \\times 5 \\text{ days} = \\boxed{30} \\text{ miles} $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Elise writes the alphabet **twice**, then writes **half** of it once, and then re-writes everything she has already written.\n\n- First, she writes the alphabet **twice**: 26 letters.\n- Then, she writes **half** of it once: 13 letters.\n- Finally, she re-writes everything she has already written: 26 letters.\n\nSo, the total number of letters Elise has written is:\n\n$$\n26 + 13 + 26 = \\boxed{65}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told that:\n\n- **1st round**: 3 families are notified.\n- **2nd round**: Each of the 3 families calls 3 others → 3 × 3 = 9 families are notified.\n- **3rd round**: Each of the 9 families calls 3 others → 9 × 3 = 27 families are notified.\n- **4th round**: Each of the 27 families calls 3 others → 27 × 3 = **81 families** are notified.\n\n### Final Answer:\n$$\n\\boxed{81}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark was unwell for 3 months, during which he lost 10 pounds per month. His final weight was 70 pounds.\n\nLet’s denote his initial weight as $ x $ pounds.\n\n- He lost 10 pounds per month for 3 months.\n- So, total weight loss = $ 10 \\times 3 = 30 $ pounds.\n- His final weight is 70 pounds, so his initial weight is:\n $$\n x = 70 + 30 = \\boxed{100}\n $$\n\n**Answer:** $\\boxed{100}$ pounds." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the number of toys Jonathan currently has as $ x $.\n\n---\n\n### Step 1: Understand the problem\n\n- James's play set has **80 toys**.\n- Jonathan needs **2 more toys** than he already had to make a **five times larger** play set than James's.\n\nSo, the number of toys in **Jonathan's play set** is:\n\n$$\n5 \\times 80 = 400\n$$\n\n---\n\n### Step 2: Set up the equation\n\nJonathan needs **2 more toys** than he already had. So:\n\n$$\nx + 2 = 400\n$$\n\n---\n\n### Step 3: Solve for $ x $\n\n$$\nx = 400 - 2 = 398" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Daniel wants to buy:\n\n- 5 notebooks at $1.50 each: $5 \\times 1.50 = 7.50\n- 2 pens at $0.25 each: $2 \\times 0.25 = 0.50\n- 1 calculator at $12: $12\n- 1 geometry set at $10: $10\n\nTotal cost without discount: \n$7.50 + $0.50 + $12 + $10 = $30.00\n\nSince the shop gives a **10% discount**, we calculate the discount first: \n$30.00 \\times 0.10 = 3.00\n\nNow" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carly orders:\n- 5 hamburgers at $4 each: $5 \\times 4 = \\$20\n- 10 packs of potato fries at $0.30 each: $10 \\times 0.30 = \\$3\n- 5 cans of fruit drinks at $2 each: $5 \\times 2 = \\$10\n\nTotal cost: \n$$\n20 + 3 + 10 = \\$33\n$$\n\nShe gives $150 (one fifty-dollar bill). \n$$\n150 - 33 = \\boxed{117}\n$$\n\nCarly gets back **$117**." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "To calculate the amount of money Antonella earned:\n\n1. **First commission**: \n $ 30\\% \\text{ of } 2500 = 0.30 \\times 2500 = 750 $\n\n2. **Second commission**: \n $ 10\\% \\text{ of } 2500 = 0.10 \\times 2500 = 250 $\n\n3. **Total commission**: \n $ 750 + 250 = \\boxed{1000} $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bill starts with:\n\n- 2 cases of water, each with 24 bottles: \n $ 2 \\times 24 = 48 $ bottles.\n\nHe has 70 guests, and he wants to have **2 bottles for each guest**: \n$ 70 \\times 2 = 140 $ bottles.\n\nHe needs: \n$ 140 - 48 = 92 $ additional bottles.\n\n**Final Answer:** $\\boxed{92}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Define the variables\n\nLet:\n- $ x $ = time (in minutes) it takes Ray to swim a mile on a **cold day**.\n- $ x + 2 $ = time (in minutes) it takes Ray to swim a mile on a **hot day**.\n\n---\n\n### Step 2: Use the given information\n\n- On a **cold day**, Ray swims a mile in 16 minutes: \n $ x = 16 $\n\n- On a **hot day**, Ray swims a mile in $ 2x + 2 $ minutes: \n $ x + 2 = 2(16) + 2 = 34 $\n\n---\n\n### Step 3: Find" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John earns $2 per hour and works 5 hours a day for 4 days a week. \nSo, his daily earnings are: \n$$ 5 \\text{ hours/day} \\times 2 \\text{ dollars/hour} = 10 \\text{ dollars/day} $$\n\nHe wants to save $80. \nSo, the number of weeks he needs to work is: \n$$ \\frac{80 \\text{ dollars}}{10 \\text{ dollars/day}} = 8 \\text{ days} $$\n\nSince he works 4 days a week, the number of weeks is: \n$$ \\frac{8 \\text{ days}}{4 \\text{ days/week}} = 2 \\text{ weeks} $$\n\n**Final" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "First, let's break down the problem:\n\n- The cost of a **foot-long fish sub** is **$40**.\n- The cost of a **six-inch cold-cut combo sub** is **thrice as much** as the fish sub.\n\nSo, the cost of the cold-cut combo sub is:\n\n$$\n3 \\times 40 = 120\n$$\n\nNow, the total cost for lunch today is:\n\n$$\n40 + 120 = \\boxed{160}\n$$\n\nSo, the total cost for lunch today is **$160**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- A bag of buttons has **21 buttons**.\n- **7 buttons** have **2 holes** each.\n- The remaining **14 buttons** have **4 holes** each.\n\nSo, the total number of holes is:\n\n$$\n7 \\times 2 + 14 \\times 4 = 14 + 56 = 70\n$$\n\n**Final Answer:** $\\boxed{70}$ holes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Timothy's locker is **24 cubic inches**.\n\nZack's locker is **half as big** as Timothy's, so:\n\n$$\n\\text{Zack's locker} = \\frac{1}{2} \\times 24 = 12 \\text{ cubic inches}\n$$\n\nPeter's locker is **1/4 as big** as Zack's locker, so:\n\n$$\n\\text{Peter's locker} = \\frac{1}{4} \\times 12 = 3 \\text{ cubic inches}\n$$\n\n### Final Answer:\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Octavia drinks **half** of the daily recommended cups of coffee, so she drinks:\n\n$$\n\\frac{1}{2} \\times \\text{Recommended cups}\n$$\n\nJuan drinks **10 times** the amount Octavia drinks, so:\n\n$$\n10 \\times \\frac{1}{2} \\times \\text{Recommended cups} = 5 \\times \\text{Recommended cups}\n$$\n\nJuan’s doctor has asked him to reduce his daily coffee intake to the **daily recommendation of 4 cups**.\n\nSo, the amount Juan must reduce is:\n\n$$\n4 - 5 = -1\n$$\n\nSince he must reduce, he must reduce **1 cup**.\n\n$$\n\\boxed{1} \\text{ cup}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 3 cages have 10 hamsters each.\n- 3 cages have 5 guinea pigs each.\n\nSo, the total number of rodents is:\n\n$$\n3 \\times 10 + 3 \\times 5 = 30 + 15 = \\boxed{45}\n$$\n\n**Answer:** $\\boxed{45}$ rodents." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark's weight = 150 pounds \nSusan's weight = Mark's weight - 20 = 150 - 20 = 130 pounds \nBob's weight = 2 × Susan's weight = 2 × 130 = 260 pounds \n\nNow, the average weight of the 3 friends is: \n$$\n\\frac{150 + 130 + 260}{3} = \\frac{540}{3} = 180\n$$\n\n**Final Answer:** $\\boxed{180}$ pounds." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The angle of the pyramid from the ground is **32°**.\n- The sun is moving **5° per hour** upward from the pyramid.\n- The sun starts at the tip of the pyramid and moves for **10 hours**.\n\n---\n\n### Step 1: Determine the total angle of the sun from the pyramid\n\nSince the sun moves **5° per hour**, in 10 hours, it moves:\n\n$$\n5 \\, \\text{°/hour} \\times 10 \\, \\text{hours} = 50°\n$$\n\nSo, the sun moves **50°** from the pyramid.\n\n---\n\n### Step 2: Find the total angle from the ground\n\nThe total angle from the ground is the angle" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James buys birthday candles for his two sons. One son is 12 years old, and the other is 4 years younger, so the other son is 8 years old.\n\nHe buys a pack of 5 candles for $3. \nSo, the number of packs he needs is: \n$$\n\\frac{8 + 12}{5} = \\frac{20}{5} = 4 \\text{ packs}\n$$\n\nJames spends: \n$$\n4 \\text{ packs} \\times 3 \\text{ dollars per pack} = 12 \\text{ dollars}\n$$\n\n**Final Answer:** $\\boxed{12}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- In the **first week**, Judy reads **15 minutes each night**.\n- In the **second week**, she reads a total of **100 pages**.\n- She can read **2 pages per 1.5 minutes**.\n\nWe need to find how many **pages** she read in **two weeks**.\n\n---\n\n### Step 1: Find how many pages she reads in one night\n\nShe reads **15 minutes** each night, and she reads **2 pages per 1.5 minutes**.\n\nSo, in 15 minutes, she reads:\n\n$$\n\\frac{15}{1.5} \\times 2 = 10 \\times 2 = 20 \\text{ pages}\n$$\n\n---\n\n###" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cody ate a third of the sandwiches: \n$$\n\\frac{1}{3} \\times 12 = 4 \\text{ sandwiches}\n$$\n\nTrevor ate a quarter of the sandwiches: \n$$\n\\frac{1}{4} \\times 12 = 3 \\text{ sandwiches}\n$$\n\nTotal sandwiches eaten: \n$$\n4 + 3 = 7 \\text{ sandwiches}\n$$\n\nSandwiches left: \n$$\n12 - 7 = \\boxed{5} \\text{ sandwiches}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's define the current age of the nephew as $ x $.\n\nShiloh is currently 44 years old, and in 7 years, he will be $ 44 + 7 = 51 $ years old.\n\nAccording to the problem, in 7 years, Shiloh will be **three times** as old as his nephew.\n\nSo, we can write the equation:\n\n$$\n51 = 3x\n$$\n\nSolving for $ x $:\n\n$$\nx = \\frac{51}{3} = 17\n$$\n\n### Final Answer:\n$$\n\\boxed{17}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n- The **first tooth** Sharon lost: $5.00\n- For each of the **next three teeth**, the tooth fairy gave Sharon **$1.00** each.\n- For each of the **last 2 teeth**, the tooth fairy gave Sharon **half the amount** of money per tooth as for the first 3 teeth.\n\nSo, for the last 2 teeth:\n- Each tooth gave Sharon **$1.00** (half of $2.00)\n- Total for these 2 teeth: $2.00\n\nNow, add up all the amounts:\n\n- First tooth: $5.00\n- Next 3 teeth: $1.00 × 3 = $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Richie scored **80 goals**.\n- Richie scored **20 more goals than Mark**.\n- Richie scored **45 more goals than Anna**.\n\n---\n\n### Step 1: Find how many goals Mark scored\n\nSince Richie scored **20 more goals than Mark**, and Richie scored **80**, then:\n\n$$\n\\text{Mark} = 80 - 20 = 60\n$$\n\n---\n\n### Step 2: Find how many goals Anna scored\n\nSince Richie scored **45 more goals than Anna**, and Richie scored **80**, then:\n\n$$\n\\text{Anna} = 80 - 45 = 35\n$$\n\n---\n\n### Step 3: Add up the goals scored by all" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Liam made $63 in total.\n\nMitchell sold 21 lemonades at $4 each, so he made:\n\n$$\n21 \\times 4 = 84 \\text{ dollars}\n$$\n\nNow, to find how many more dollars Mitchell made than Liam:\n\n$$\n84 - 63 = 21\n$$\n\n**Answer:** $\\boxed{21}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Peter has $70 and wants to spend an equal amount each day for one week. Since there are 7 days in a week, he will spend:\n\n$$\n\\frac{70}{7} = 10 \\text{ dollars per day}\n$$\n\nFrom **Sunday to Wednesday**, he spends $10 each day on wooden action figures, which cost $5 each. So, the number of wooden action figures he buys is:\n\n$$\n10 \\div 5 = 2 \\text{ figures}\n$$\n\nFor the **remaining 4 days** (Thursday to Saturday), he spends $10 each day on plastic action figures, which cost $2 each. So, the number of plastic action figures he buys is:\n\n$$\n10 \\div 2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Leah's total cost can be calculated as follows:\n\n- **Spaying cost**: $200 \n- **3 vaccines**: $3 \\times 20 = 60 \n- **4 vases**: $4 \\times 12 = 48 \n\nTotal cost = $200 + $60 + $48 = **$308**\n\nSo, the kitten has cost **$308** so far. \n\n$$\n\\boxed{308}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ford grows **40 roses every week**. \nHe supplies roses to **three flower shops**:\n\n- First shop: 20 roses \n- Second shop: 15 roses \n- Third shop: 30 roses \n\nSo, the total number of roses he supplies per week is:\n\n$$\n20 + 15 + 30 = 65 \\text{ roses}\n$$\n\nHe grows **40 roses every week**, so he **lacks**:\n\n$$\n65 - 40 = 25 \\text{ roses}\n$$\n\n**Answer:** $\\boxed{25}$ roses." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Katina starts with $3000 in her savings account.\n\nShe removes $100 every month for 2 years.\n\nFirst, convert 2 years to months: \n2 years × 12 months/year = 24 months.\n\nNow, calculate the total amount removed: \n$100/month × 24 months = $2400.\n\nSubtract the total amount removed from the initial amount: \n$3000 - $2400 = $600.\n\n**Final Answer:** $\\boxed{600}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Bread costs $3.00 per loaf.\n- Each loaf makes 10 sandwiches.\n- They spend $30.00 on cheese and condiments per 10 sandwiches.\n- They sell 10 sandwiches for $7.00 each.\n- We are to find their **net profit**.\n\n---\n\n### Step 1: Calculate the number of sandwiches made from 30.00\n\nThey spend $30.00 on cheese and condiments per 10 sandwiches. \nSo, the number of sandwiches made from $30.00 is:\n\n$$\n\\frac{30.00}{30.00} = 1 \\text{ loaf of bread} \\times 1" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Kate has 3 boxes of 64 crayons each, so she has:\n\n$$\n3 \\times 64 = 192 \\text{ crayons}\n$$\n\nShe melts 8 small pieces of crayons together in a muffin tin. Since she sells each piece for $1.50, the total money she can make is:\n\n$$\n8 \\times 1.50 = 12 \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{12}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find the total cost for Michael to replace the carpet, we need to calculate the cost of the new carpet, the cost of the padding, the cost of removing the old carpet, and the cost of installing the new carpet, and then sum them up.\n\n### Step 1: Calculate the area of the bedroom\nThe bedroom measures **18 feet by 12 feet**, so the area is:\n\n$$\n18 \\times 12 = 216 \\text{ square feet}\n$$\n\n### Step 2: Cost of new carpet\n- New carpet costs **$12 per square foot**.\n- So, the cost of the carpet is:\n\n$$\n12 \\times 216 = 2592 \\text{ dollars}\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the number of birds Mack saw on several days:\n\n- Day 1: 50 birds \n- Day 2: 50 birds \n- Day 3: 0 birds \n- Day 4: 120 birds \n- Day 5: 120 birds \n- Day 6: 20 birds \n- Day 7: 90 birds \n\nWe are to find the **average number of birds** Mack saw in a day.\n\n### Step 1: Add up the total number of birds\n$$\n50 + 50 + 0 + 120 + 120 + 20 + 90 = 500\n$$\n\n### Step 2: Count the number of" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given the following steps:\n\n1. Start value: $ 20 $\n2. Add half the number: $ 20 + \\frac{1}{2} \\times 20 = 20 + 10 = 30 $\n3. Divide the result by 5: $ \\frac{30}{5} = 6 $\n4. Multiply the starting value by $ 6 - 12 = -6 $: $ 20 \\times (-6) = -120 $\n\n### Final Answer:\n$$\n\\boxed{-120}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The boy has 5 cards, and his brother has 3 fewer cards than he has. So, the brother has:\n\n$$\n5 - 3 = 2 \\text{ cards}\n$$\n\nTogether, they have:\n\n$$\n5 + 2 = 7 \\text{ cards}\n$$\n\n**Answer:** $\\boxed{7}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### **Given:**\n\n- When Maggie sets the oven to **450**, the actual temperature is **468**.\n- The oven is **off by the same percentage** for any recipe.\n- The recipe calls for **520 degrees**.\n\nWe need to find the **temperature** Maggie should set the oven to, **if it's off by the same percentage**.\n\n---\n\n### **Step 1: Find the percentage off the oven temperature**\n\nThe oven is off by the same percentage for any recipe. So, the oven temperature is **450**, and the actual temperature is **468**.\n\nSo, the oven is **off by**:\n\n$$\n\\text{Percentage off} = \\frac" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Max plans to watch two movies:\n\n- The first movie is **1 hour and 30 minutes**, which is **90 minutes**.\n- The second movie is **2 hours and 5 minutes**, which is **135 minutes**.\n\nAdding these together:\n\n$$\n90 + 135 = 225 \\text{ minutes}\n$$\n\n**Final Answer:** $\\boxed{225}$ minutes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n1. **Let the value of Herb's house be $ H $.** \n Since Juan's house is 30% less expensive than Herb's, we can express Juan's house value as: \n $$\n \\text{Juan's house value} = H - 0.30H = 0.70H\n $$\n\n2. **We are told that Herb's house is worth $76,000.** \n So, \n $$\n H = 76,000\n $$\n\n3. **Now calculate Juan's house value:** \n $$\n 0.70 \\times 76,000 = 53," + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Judy bought a dozen cups, which is 12 cups. She also bought **twice as many dishes** as the number of cups she bought. So, she bought:\n\n$$\n2 \\times 12 = 24 \\text{ dishes}\n$$\n\nHer friend had brought:\n\n- 40 cups\n- 20 more dishes than she had brought: $ 40 + 20 = 60 $ dishes\n\nNow, the total number of utensils brought by Judy and her friend is:\n\n$$\n12 \\text{ cups} + 24 \\text{ dishes} + 40 \\text{ cups} + 60 \\text{ dishes} = 12 + 40 + 24 + 6" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 90 single-use contacts come in 1 box.\n- Each box costs $100.00, with a 10% discount.\n- Pete buys 2 boxes of contacts.\n- We are to find the cost of **each pair** of contacts.\n\n---\n\n### Step 1: Find the number of contacts in 2 boxes\n\n- 1 box = 90 contacts \n- 2 boxes = $2 \\times 90 = 180$ contacts\n\n---\n\n### Step 2: Find the cost of 2 boxes\n\n- Each box is $100.00 with a 10% discount \n- So, each box costs: \n $100.00 × (1 -" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tabitha agreed to pay John and Jill $10 per hour to help clean out her attic and basement.\n\n- **Jill worked:**\n - Saturday: 2 hours \n - Sunday: 1 hour \n - Total: $2 + 1 = 3$ hours\n\n- **John worked:**\n - Saturday: 2 hours (twice as long as Jill) \n - Sunday: 1 hour (three times as long as Jill) \n - Total: $2 + 1 = 3$ hours\n\nNow, calculate the total money earned by each:\n\n- **Jill's total earnings:** \n $3 \\text{ hours} \\times \\$10 = \\$30$\n\n- **John's total earnings:** \n " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Hannah burns:\n\n- 2 hours of aerobics: $ 2 \\times 500 = 1000 $ calories \n- 1 hour of running: $ 1 \\times 600 = 600 $ calories\n\nTotal calories burned: \n$$ 1000 + 600 = 1600 \\text{ calories} $$\n\nShe needs to drink **100 ml of water for every 200 calories**.\n\nSo, the total ml of water needed is: \n$$ \\frac{1600}{200} \\times 100 = 80 \\times 100 = \\boxed{8000} \\text{ ml} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The jar contains **4500 jelly beans**.\n- The jar contains **1% fewer red jelly beans than blue jelly beans**.\n- The jar contains **1% more green jelly beans than blue jelly beans**.\n\nLet’s define:\n\n- Let $ B $ be the number of blue jelly beans.\n- Then, the number of red jelly beans is $ B - 1\\% \\times B = 0.9B $.\n- The number of green jelly beans is $ B + 1\\% \\times B = 1.1B $.\n\nSo, the total number of jelly beans is:\n\n$$\nB + 0.9B + 1.1B = 4500\n$$\n\n$$\n(1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jared starts at 47 WPM, then increases to 52 WPM, and continues to increase by 5 words per lesson. So, the three measurements are:\n\n- First measurement: 47 WPM \n- Second measurement: 52 WPM \n- Third measurement: 52 + 5 = 57 WPM \n\nNow, to find the **average** of the three measurements:\n\n$$\n\\text{Average} = \\frac{47 + 52 + 57}{3} = \\frac{156}{3} = 52\n$$\n\n**Final Answer:** $\\boxed{52}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n### Given:\n- Martin eats **Cheerios** every day for breakfast:\n - He loses **1.25 pounds/week**.\n- Martin eats **donuts** every day for breakfast:\n - He gains **1.75 pounds/week**.\n\nWe are to find the **difference in weight** between the two breakfast options after **5 weeks**.\n\n---\n\n### Step 1: Calculate weight loss from Cheerios over 5 weeks\n\n- Weight loss per week: 1.25 pounds\n- Over 5 weeks: \n $$\n 1.25 \\times 5 = 6.25 \\text{ pounds}\n $$\n\n---\n\n### Step 2: Calculate weight gain from" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Alex invites 100 people. Each of these 100 people also invites 2 of their friends, so:\n\n- Total people invited: 100 \n- Friends invited: $ 100 \\times 2 = 200 $\n\nThen, 10 of her friends are called to invite them too, and 8 of them say they will be bringing their spouses. So:\n\n- Friends invited: $ 200 + 10 + 8 = 218 $\n\nTherefore, Alex needs **218 seats**.\n\n$$\n\\boxed{218}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the weights of four dogs in a line:\n\n- **Affenpinscher (Aff)**: 10 pounds \n- **Dachshund**: 2 × 10 = **20 pounds** \n- **Papillon**: 1/4 × 20 = **5 pounds** \n- **Mastiff**: 44 × 5 = **220 pounds**\n\n### Final Answer:\n$$\n\\boxed{220}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Marilyn wants to buy a pair of boots online. On **Amazon**, the boots cost **$16** and shipping costs **$4**. On **eBay**, the same boots cost **$13**, but shipping costs **twice as much** as on Amazon.\n\n### Step 1: Calculate shipping cost on eBay\nSince shipping costs **twice as much** as on Amazon, and Amazon shipping is **$4**, then eBay shipping is:\n\n$$\n2 \\times 4 = \\boxed{8}\n$$\n\n### Step 2: Add the cost of the boots to the shipping cost on eBay\n$$\n13 + 8 = \\boxed{21}\n$$\n\n### Final Answer:\nThe boots are **$21** more expensive on" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark plants a beanstalk below his second-story window, which is **20 feet off the ground**. The beanstalk **doubles its height every day**, starting from **4 feet**.\n\nWe are to find how many days it will take for the beanstalk to be **taller than 20 feet**.\n\n### Step-by-step:\n\n- **Initial height**: 4 feet \n- **Daily doubling**: 4 × 2 = 8 feet \n- **After 1 day**: 8 feet \n- **After 2 days**: 16 feet \n- **After 3 days**: 32 feet \n- **After 4 days**: 64 feet \n- **After 5 days**: 128 feet \n\nWe need to find the" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A cup of mushrooms weighs **100 grams**.\n- It contains **3 grams of protein**.\n- John eats **200 grams of mushrooms every day**.\n- We are to find how many grams of protein he gets **per week**.\n\n---\n\n### Step 1: Find the protein content per day\n\n- 1 cup = 100 grams, 3 grams protein\n- So, per day, John gets:\n\n$$\n\\frac{3 \\text{ grams of protein}}{100 \\text{ grams of mushrooms}} \\times 200 \\text{ grams of mushrooms} = 6 \\text{ grams of protein per day}\n$$\n\n---\n\n### Step 2: Find the protein content per week\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. Let $ x $ be Jerry's current age.\n2. The problem says Jerry is **twice as old as he was 5 years ago**.\n3. That means: \n $ x = 2(x - 5) $\n\n4. Solve the equation:\n $$\n x = 2(x - 5) \\\\\n x = 2x - 10 \\\\\n x - 2x = -10 \\\\\n -x = -10 \\\\\n x = 10\n $$\n\nSo, Jerry is currently **10 years old**.\n\n5. In 3 years, Jerry will be:\n $$\n 10 + 3 = \\boxed{13}\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "George needs to pay for dental work, which includes:\n\n- 2 implants: $2000 each → $4000\n- A porcelain crown: $500\n- A deposit: $600\n\nSo the total cost is:\n\n$$\n4000 + 500 + 600 = 4100\n$$\n\nHe makes $15 per hour. Let’s find out how many hours he needs to work to pay for the dental work:\n\n$$\n\\text{Hours} = \\frac{4100}{15} = 273.33\n$$\n\nSince he can't work a fraction of an hour, he needs to work **274 hours**.\n\n$$\n\\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The three angles in a triangle add up to **180 degrees**.\n- One angle is **twice** the smallest angle.\n- One angle is **three times** the smallest angle.\n\nLet the smallest angle be $ x $.\n\nThen:\n\n- The two other angles are:\n - $ 2x $\n - $ 3x $\n\nSo the three angles are:\n- $ x $\n- $ 2x $\n- $ 3x $\n\nTheir sum is:\n$$\nx + 2x + 3x = 6x = 180^\\circ\n$$\n\nSolving for $ x $:\n$$\nx = \\frac{180^\\circ}{6} = 30^\\circ\n$$\n\nNow" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Colby has:\n\n- 8 quarters = 8 × 25 = 200 cents \n- 6 dimes = 6 × 10 = 60 cents \n- 14 nickels = 14 × 5 = 70 cents \n- 15 pennies = 15 × 1 = 15 cents \n\nTotal amount: \n200 + 60 + 70 + 15 = **345 cents**\n\nEach gumball costs 5 cents. \nNumber of gumballs: \n345 ÷ 5 = **69**\n\n**Answer:** $\\boxed{69}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- 5 dogs \n- 2 cats \n- 10 birds \n\nEach pet has **4 legs**.\n\nSo, the total number of legs is:\n\n$$\n5 \\text{ dogs} \\times 4 \\text{ legs} + 2 \\text{ cats} \\times 4 \\text{ legs} + 10 \\text{ birds} \\times 4 \\text{ legs}\n$$\n\n$$\n= 20 + 8 + 40 = \\boxed{68} \\text{ legs}\n$$\n\n**Answer:** $\\boxed{68}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jamaal starts with an 8-pound weight. He increases it by 50%, so:\n\n$$\n8 + 0.5 \\times 8 = 8 + 4 = 12 \\text{ pounds}\n$$\n\nThen, he uses a weight **two pounds lighter** than that, so:\n\n$$\n12 - 2 = 10 \\text{ pounds}\n$$\n\n### Final Answer:\n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Steve starts with 5 games for his birthday. \nHe saves up 1 game per month for a year, so that's 12 games. \nThen he buys 2 games per month for the next year, so that's 24 games. \nHe also gets 5 games for Christmas every year. \n\nSo, total games after 3 years: \n5 + 12 + 24 + 5 = **46 games**. \n\n**Answer:** $\\boxed{46}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given that a plane travels **1200 miles in 3 hours**.\n\n### Step 1: Find the speed of the plane\n$$\n\\text{Speed} = \\frac{\\text{Distance}}{\\text{Time}} = \\frac{1200 \\text{ miles}}{3 \\text{ hours}} = 400 \\text{ miles per hour}\n$$\n\n### Step 2: Find the time it would take to travel an additional 2000 miles at this speed\n\n$$\n\\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{2000 \\text{ miles}}{400 \\text{ miles per hour}} = 5 \\text{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ruiz can make **120 pounds** of chocolates in **2 hours**. \nSo, in **1 hour**, he makes: \n$$\n\\frac{120}{2} = 60 \\text{ pounds}\n$$\n\nMarissa makes **$\\frac{3}{4}$ times** as many pounds of chocolates in an hour as Ruiz does. \nSo, in an hour, Marissa makes: \n$$\n60 \\times \\frac{3}{4} = 45 \\text{ pounds}\n$$\n\nThey worked for **12 hours** in a day. \nSo, the total amount of chocolate pounds they made together is: \n$$\n12 \\times (60 + 45) = 12 \\times" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- On **Monday**, Howard spends **$8**.\n- On **Tuesday**, he spends **twice** as much as Monday: \n $ 2 \\times 8 = 16 $ dollars.\n- On **Wednesday**, he spends **4 times** as much as Tuesday: \n $ 4 \\times 16 = 64 $ dollars.\n\nNow, add up the amounts he spent:\n\n$$\n8 + 16 + 64 = 88\n$$\n\nHe originally had **$100**, so the amount he has left is:\n\n$$\n100 - 88 = \\boxed{12}\n$$\n\n**Answer:** $\\boxed{12}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Patrick sold lemonade for **6 hours** in total. Let's break it down:\n\n- In the first **4 hours**, he sold **15 cups/hour** at **$0.50 per cup**:\n $$\n 15 \\text{ cups/hour} \\times 4 \\text{ hours} = 60 \\text{ cups}\n $$\n $$\n 60 \\text{ cups} \\times 0.50 \\text{ dollars/cup} = 30 \\text{ dollars}\n $$\n\n- In the next **2 hours**, he sold **10 cups/hour** at **$0.60 per cup**:\n $$\n 10 \\text{ cups/hour" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- **Every 2 miles**, a car drives the tires, and the tires rotate **725 times**.\n- **Jeremy drives 400 miles per month**.\n- Each tire can undergo **10,440,000 rotations**.\n\nWe are to find how many **years** before the tire needs to be replaced.\n\n---\n\n### Step 1: Find the number of rotations per mile\n\n$$\n\\text{Rotations per mile} = \\frac{725 \\text{ rotations}}{2 \\text{ miles}} = 362.5 \\text{ rotations/mile}\n$$\n\n---\n\n### Step 2: Find the number of rotations for 400 miles\n\n$$\n\\text{Rot" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- The cost of the shampoo bottle is **$24.00**.\n- It requires **2 pumps** to provide **120 washings**.\n- Jackie uses **1 pump per wash**.\n\n### Step 1: Find the cost per pump\n\nSince 2 pumps are needed for 120 washings, the cost per pump is:\n\n$$\n\\frac{24.00}{120} = 0.20 \\text{ dollars per pump}\n$$\n\nConvert this to cents:\n\n$$\n0.20 \\text{ dollars} = 20 \\text{ cents}\n$$\n\n### Final Answer:\n\n$$\n\\boxed{20} \\text{ cents per pump}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Joe has $50 to buy an outfit. The shirt is $25, and the pair of shorts is $35. There is a 30% discount on the shirt and the shorts.\n\n1. **Calculate the discounted price of the shirt:**\n $$\n 25 \\times (1 - 0.30) = 25 \\times 0.70 = 17.50\n $$\n\n2. **Calculate the discounted price of the shorts:**\n $$\n 35 \\times 0.70 = 24.50\n $$\n\n3. **Total cost of the outfit:**\n $$\n 17.50 + 24.50 = " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Juan wants to make **4 dozen** of croissants **per day** for **a week**. \nWe are told that **1 dozen** requires **1/4 pound** of butter.\n\n### Step 1: Find how many dozens he needs in a week\n- 1 day = 4 dozen \n- 7 days = $ 4 \\times 7 = 28 $ dozen\n\n### Step 2: Calculate the total pounds of butter needed\n- 28 dozen × $ \\frac{1}{4} $ pound/dozen = $ \\frac{28}{4} = 7 $ pounds\n\n### ✅ Final Answer: \n$$\n\\boxed{7}\n$$ pounds of butter." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Monica's street is 150 meters long, and it costs $194 per meter. \nSo, the cost to repave Monica's street is: \n$$ 150 \\times 194 = 29,100 $$\n\nLewis' street is 490 meters long. \nThe cost to repave Lewis' street is: \n$$ 490 \\times 194 = 94,660 $$\n\nThe difference in cost is: \n$$ 94,660 - 29,100 = \\boxed{65,560} $$\n\nIt costs **$65,560** more to repave Lewis' street." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John's research cost is calculated as follows:\n\n- Initial funding: $100,000\n- First 5 months: $100,000\n- After 5 months, the funding increases by 50% per month, so the cost becomes:\n $$\n 100,000 \\times 1.5 = 150,000\n $$\n- The research took 10 times the time it took for the initial funding, so the total cost is:\n $$\n 100,000 + 150,000 = \\boxed{250,000}\n $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- **First player**: 6 ounces of steak \n- **Second player**: 8 beef tips, each 1 ounce \n- **Third player**: 1 pound of steak \n- **Fourth and fifth players**: Vegetarian meals, which we assume to be **0 ounces** of meat (since they didn't eat meat).\n\n### Step-by-step calculation:\n\n1. **First player**: 6 ounces \n2. **Second player**: 8 beef tips × 1 ounce = 8 ounces \n3. **Third player**: 1 pound = 16 ounces \n4. **Fourth and fifth players**: 0 ounces\n\n### Total meat consumed:\n\n$$\n6 + 8 + 16 + 0 + 0 = \\boxed{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Number of members: $ 1000 $\n- Average number of posts per member per day: $ 3 $\n\nWe need to find the total number of posts in **March**.\n\n### Step 1: Find the number of days in March\nMarch has **31 days**.\n\n### Step 2: Calculate total posts\n$$\n\\text{Total posts} = \\text{Number of members} \\times \\text{Average posts per member per day} \\times \\text{Number of days in March}\n$$\n$$\n\\text{Total posts} = 1000 \\times 3 \\times 31 = 93,000\n$$\n\n### Final Answer:\n$$\n\\boxed{93" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gary does laundry **twice a week**. Each load uses **20 gallons of water**, and each gallon costs **$0.15**.\n\n### Step 1: Calculate the total water used per week\n- 2 loads × 20 gallons = **40 gallons** of water per week.\n\n### Step 2: Calculate the cost per week\n- 40 gallons × $0.15 = **$6** per week.\n\n### Step 3: Calculate the cost for a year\n- 52 weeks/year × $6 = **$312**.\n\n### Final Answer:\n$$\n\\boxed{312}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Scarlett spent the following:\n\n- $10.00 at the yard sale \n- $2.50 × 2 = $5.00 for the rocks \n- $2.00 × 3 = $6.00 for the coral \n- $0.50 × 20 = $10.00 for the fish \n- $2.00 for the fish food \n\nTotal cost: \n$$\n10 + 5 + 6 + 10 + 2 = \\boxed{33} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- After the **first week**, the beanstalk is **3 inches** tall.\n- It **doubled** in the **second week**, so it becomes $ 3 \\times 2 = 6 $ inches.\n- Then, it **grew another 4 inches**, so it becomes $ 6 + 4 = 10 $ inches.\n\n### Final Answer:\n$$\n\\boxed{10} \\text{ inches}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Prince sells 15 kg of meat every hour he works, and he works 10 hours a day. So, in one day, he sells:\n\n$$\n15 \\, \\text{kg/hour} \\times 10 \\, \\text{hours} = 150 \\, \\text{kg/day}\n$$\n\nBill's bull weighs 750 kg. So, the number of days it will take for Prince to sell the bull is:\n\n$$\n\\frac{750 \\, \\text{kg}}{150 \\, \\text{kg/day}} = 5 \\, \\text{days}\n$$\n\n**Final Answer:** $\\boxed{5}$ days." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 4 rows of seats \n- 18 seats per row \n- One-fourth of the seats were occupied by the **administrators** \n- One-third of the **remaining seats** were occupied by the **parents** \n- The rest were occupied by the **students**\n\n---\n\n### Step 1: Total number of seats\n\n$$\n\\text{Total seats} = 4 \\text{ rows} \\times 18 \\text{ seats per row} = 72 \\text{ seats}\n$$\n\n---\n\n### Step 2: Seats occupied by administrators\n\n$$\n\\frac{1}{4} \\text{ of } 72 = 18 \\text{ seats}\n$$\n\n---\n\n### Step 3: Remaining seats after" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Each pole has **4 street lights**.\n- There are **6 poles** at each intersection.\n- There are **4 intersections**.\n- **20 streetlights** are not working.\n\n---\n\n### Step 1: Calculate the total number of street lights\n\nEach intersection has 6 poles × 4 street lights = **24 street lights**\n\nThere are 4 intersections, so:\n\n$$\n\\text{Total street lights} = 24 \\times 4 = 96\n$$\n\n---\n\n### Step 2: Subtract the number of working streetlights\n\nWe are told **20 streetlights are not working**, so:\n\n$$\n\\text{Number of working streetlights} = 96 - 20 = 76\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- A DVD can be played **1000 times** before it breaks.\n- The first DVD has been played **356 times**.\n- The second DVD has been played **135 times**.\n\nWe are to find how many **total times** both DVDs can be played **before** they break.\n\n### Step-by-step:\n\n- The first DVD has been played **356 times**, and it can last **1000 times** before breaking.\n- The second DVD has been played **135 times**, and it can last **1000 times** before breaking.\n\nSo, the **maximum number of times** both DVDs can be played before they break is:\n\n$$\n\\min(356 + 13" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John went to physical therapy for **6 weeks**, and each week he went **2 sessions** for **2 hours**. \nEach session costs **$125 per hour**.\n\n### Step 1: Calculate the total number of hours per week\n- 2 sessions × 2 hours = **4 hours per week**\n\n### Step 2: Calculate the total number of hours over 6 weeks\n- 4 hours/week × 6 weeks = **24 hours**\n\n### Step 3: Calculate the total cost\n- 24 hours × $125/hour = **$3000**\n\n### Final Answer:\n$$\n\\boxed{\\$3000}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jim has a **20-pack** of gum, which means he starts with **20 pieces**.\n\nHe chews **1 piece per 2 hours** while at school. Since the school day lasts **8 hours**, he eats:\n\n$$\n\\frac{1}{2} \\times 8 = 4 \\text{ pieces}\n$$\n\nHe also chews **1 piece on the way home** from school, so that's **1 piece**.\n\nHe also chews **1 stick after dinner**, which is **1 piece**.\n\nNow, let's calculate how many pieces he has left:\n\n- Total gum: 20\n- Gum eaten: 4 (school) + 1 (home) + 1 (after dinner) = 6\n- Remaining" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Charmaine will be 16 years old in **12 years**, so in **4 years from now**, she will be:\n\n$$\n16 + 4 = \\boxed{20}\n$$\n\nTherefore, she will be **20 years old** 4 years from now." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The baseball coach bought 9 new baseballs for $3 each, so the total cost is:\n\n$$\n9 \\times 3 = 27 \\text{ dollars}\n$$\n\nThe basketball coach bought 8 new basketballs for $14 each, so the total cost is:\n\n$$\n8 \\times 14 = 112 \\text{ dollars}\n$$\n\nThe basketball coach spent **$112** and the baseball coach spent **$27**, so the difference is:\n\n$$\n112 - 27 = \\boxed{85} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Arianna's garden has:\n\n- 10 rows \n- 20 flowers per row \n- Total flowers = $10 \\times 20 = 200$\n\nCurrently, **4/5** of the flowers have bloomed. So:\n\n$$\n\\text{Bloomed flowers} = \\frac{4}{5} \\times 200 = 160\n$$\n\n**Answer:** $\\boxed{160}$ flowers have bloomed." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ashley's internet connection speed is given as **20 kb/s**.\n\nWe are told that **1 Mb = 1000 kb**, so we need to convert **kb/s** to **Mb/s**.\n\n1 Mb = 1000 kb \n1 Mb/s = 1000 kb/s\n\nSo, \n20 kb/s = $ \\frac{20}{1000} $ Mb/s = **0.02 Mb/s**\n\nNow, we want to find the speed in **Mb per hour**.\n\nSince 1 Mb/s = 1 Mb/h, \n0.02 Mb/s = **0.02 Mb/h**\n\n### Final Answer:\n$$\n\\boxed{0.02} \\text{ Mb" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- The truck pulled **10 cars** for each of the **first 3 days**.\n- Then, it pulled **4 fewer cars** on each of the remaining **days**.\n\nSo, the total number of days is:\n\n$$\n3 + 7 = 10 \\text{ days}\n$$\n\n- First 3 days: $ 3 \\times 10 = 30 $ cars\n- Remaining 7 days: $ 7 \\times (10 - 4) = 7 \\times 6 = 42 $ cars\n\n$$\n\\text{Total cars towed} = 30 + 42 = \\boxed{72}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Adam's height is 40 inches, and he grows 2 inches per year. We need to find out how many years it will take for him to reach 4 feet (which is 48 inches).\n\n1. Convert 4 feet to inches: \n $ 4 \\text{ feet} = 48 \\text{ inches} $\n\n2. Subtract Adam's current height from the target height: \n $ 48 \\text{ inches} - 40 \\text{ inches} = 8 \\text{ inches} $\n\n3. Since he grows 2 inches per year, the number of years required is: \n $ \\frac{8 \\text{ inches}}{2 \\text{ inches/year}} = 4 \\text{ years}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James sold 10 cars, each costing $25,000. \nTotal cost of cars = $25,000 × 10 = $250,000.\n\nHe received a 30% commission on the cost of the cars: \n$250,000 × 30% = $75,000.\n\nHe also received a 10% commission on the profit: \nProfit = $250,000 - $75,000 = $175,000 \nCommission = 10% of $175,000 = $17,500.\n\nTotal amount James made: \n$75,00" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **100 riders**.\n- When a wave over 30 feet arrives, **25%** of the riders can stay upright.\n- Of these **25%**, **60%** are **women**.\n- We are to find how many **men** can stay upright.\n\n---\n\n### Step 1: Find the number of riders who can stay upright\n\n$$\n25\\% \\text{ of } 100 = 0.25 \\times 100 = 25 \\text{ riders}\n$$\n\n---\n\n### Step 2: Find the number of women who can stay upright\n\n$$\n60\\% \\text{ of } 25 = 0.60 \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The price of a **gold Jewell** is $ \\frac{4}{5} $ times the price of a **diamond Jewell**.\n- The price of a **silver Jewell** is $400 less than the price of a gold Jewell.\n- The price of a **diamond Jewell** is $2000.\n\n---\n\n### Step 1: Find the price of a gold Jewell\n\nLet the price of a diamond Jewell be $ D = 2000 $.\n\nThen the price of a gold Jewell is:\n\n$$\n\\text{Price of gold} = \\frac{4}{5} \\times D = \\frac{4}{5} \\times 2000 = 16" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Max bought:\n\n- 16 snowflake stamps \n- 3 more truck stamps than snowflake: $ 16 + 3 = 19 $ truck stamps \n- 9 fewer rose stamps than truck: $ 19 - 9 = 10 $ rose stamps \n\nTotal stamps: \n$$\n16 + 19 + 10 = \\boxed{45}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bob is 75 miles ahead of Tom, and both are driving towards each other. Bob is driving at 55 mph, and Tom is driving at 70 mph.\n\nLet $ t $ be the time in hours it takes for Tom to catch up with Bob.\n\nIn that time, Bob will have traveled:\n$$\n55t \\text{ miles}\n$$\n\nSince Bob is 75 miles ahead, the distance Tom covers must be equal to the distance Bob has traveled plus 75 miles:\n$$\n70t = 55t + 75\n$$\n\nSolving for $ t $:\n$$\n70t - 55t = 75 \\\\\n15t = 75 \\\\\nt = 5\n$$\n\n**" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the following information:\n\n- Naomi caught **17 fish**.\n- Darren caught **6 less** than Naomi → $ 17 - 6 = 11 $ fish.\n- Tommy caught **3 more** than Darren → $ 11 + 3 = 14 $ fish.\n\n### Final Answer:\n$$\n\\boxed{14}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Manny signed up for **60 classes**, and his parents will **not** sign him up again if the **total cost exceeds $10 per class**.\n\n- There are **10 total classes**.\n- If the total cost exceeds $10 per class, then **he will be missed**.\n\nSo, the number of classes he can **miss** before they don't sign him up again is:\n\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Julie processes 50 customers daily. \nSince she operates the cash register **twice as fast** as Jewel, she processes **100 customers** daily.\n\nIf they work **all days of the week**, and there are **7 days in a week**, then:\n\n- Total weekly production = $50 \\text{ (Jewel)} + 100 \\text{ (Julie)} = 150 \\text{ customers per week}$.\n\n**Final Answer:** $\\boxed{150}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step.\n\n---\n\nWe are told:\n\n- **Paisley ran 4 miles**.\n- **Reggie ran 5 times what Paisley ran**.\n- **Reggie ran 3 miles farther than Lynn**.\n\n---\n\nLet’s define:\n\n- Let $ x $ be the number of miles Lynn ran.\n\nThen:\n\n- Reggie ran $ 5 \\times 4 = 20 $ miles.\n- Reggie also ran 3 miles farther than Lynn, so:\n\n$$\n20 = x + 3\n$$\n\nSolving for $ x $:\n\n$$\nx = 20 - 3 = 17\n$$\n\n---\n\n### ✅ Final Answer:\n$$\n\\boxed{17}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 4 apples = $5.20 \n- 3 oranges = $3.30\n\nWe are asked to find the cost for:\n\n- 5 apples \n- 5 oranges\n\n### Step 1: Find the cost of 1 apple \n$$\n\\text{Cost of 1 apple} = \\frac{5.20}{4} = 1.30\n$$\n\n### Step 2: Find the cost of 1 orange \n$$\n\\text{Cost of 1 orange} = \\frac{3.30}{3} = 1.10\n$$\n\n### Step 3: Find the cost for 5 apples \n$$\n5 \\times 1.30 = 6." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bob wants to dig a hole that is **6 feet long, 4 feet wide, and 3 feet deep**.\n\nHe shovels **1 cubic foot of earth in 3 seconds**.\n\nSo, the total volume of the hole is:\n\n$$\n6 \\times 4 \\times 3 = 72 \\text{ cubic feet}\n$$\n\nSince it takes him **3 seconds per cubic foot**, the total time required is:\n\n$$\n72 \\times 3 = 216 \\text{ seconds}\n$$\n\n**Final Answer:** $\\boxed{216}$ seconds." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the base price of the truck as **$30,000**, and the other features are at **extra cost**. Let's break down the additional costs:\n\n- **King cab upgrade**: $7,500 \n- **Leather seats**: $1/3 of the king cab upgrade = $7,500 ÷ 3 = **$2,500** \n- **Running boards**: $500 less than leather seats = $2,500 - $500 = **$2,000** \n- **Upgraded exterior light package**: $1,500 \n\nNow, add all these costs to the base price:\n\n$$\n30,000 + 7," + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tim gets a **5% raise** on his **$20,000 a month salary**, and an additional **$5,000** as a **bonus**.\n\n### Step 1: Calculate the raise\n- 5% of $20,000 = $1,000\n- New salary after raise = $20,000 + $1,000 = **$21,000**\n\n### Step 2: Add the bonus\n- Bonus = $5,000\n- Total salary = $21,000 + $5,000 = **$26,000**\n\n### Step 3: Calculate the annual salary\n- There are 1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James buys:\n\n- 10 suits: $750 each → $750 × 10 = $7,500 \n- 10 dress pants: $1/5 of the cost of the suits → $750 × 1/5 = $150 → $150 × 10 = $1,500 \n- 3 dress shirts per suit: 3 × 10 = 30 shirts → $60 each → $60 × 30 = $1,800 \n\nTotal cost = $7,500 + $1,500 + $1,800 = **$10,800**\n\n$$\n\\boxed{10" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The first website publishes **20 political and weather news articles** every day: \n $ 20 $ articles/day\n\n- The second website publishes **10 business news articles** every day: \n $ 10 $ articles/day\n\n- There are **28 days** in February.\n\n### Step 1: Calculate the total number of articles published by each website in February\n\n- First website: \n $ 20 \\text{ articles/day} \\times 28 \\text{ days} = 560 $ articles\n\n- Second website: \n $ 10 \\text{ articles/day} \\times 28 \\text{ days} = 280 $ articles\n\n### Step 2: Add the" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Steve is 60 years old. His wife is 4 years older than him, so her age is:\n\n$$\n60 + 4 = 64 \\text{ years old}\n$$\n\nTheir son is currently half as old as his mom. Let the son's age be $ x $. Then:\n\n$$\nx = \\frac{1}{2} \\times \\text{Mom's age}\n$$\n\nWe don't know the mom's age yet, but we can express it in terms of the son's age:\n\n$$\n\\text{Mom's age} = 2x\n$$\n\nWe also know that their son's wife is 3 years younger than her husband:\n\n$$\n\\text{Son's wife's age} = 64 - 3" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told that a bag of flour is divided into **8 portions of 2 kilograms each**. \nSo, the total weight of the original bag is:\n\n$$\n8 \\times 2 = 16 \\text{ kilograms}\n$$\n\nNow, the question asks how much flour was in **three bags** in total before it was divided into portions.\n\nSince the original bag is 16 kilograms, and it is divided into 8 portions, each portion is 2 kilograms, then:\n\n$$\n3 \\times 2 = 6 \\text{ kilograms}\n$$\n\n### Final Answer:\n$$\n\\boxed{6} \\text{ kilograms}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Alisa biked at **12 miles per hour** for **4.5 hours**, so the distance she covered is:\n\n$$\n12 \\times 4.5 = 54 \\text{ miles}\n$$\n\nStanley biked at **10 miles per hour** for **2.5 hours**, so the distance he covered is:\n\n$$\n10 \\times 2.5 = 25 \\text{ miles}\n$$\n\nTotal distance biked by both:\n\n$$\n54 + 25 = \\boxed{79} \\text{ miles}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bill digs 4 feet per hour through soil and half that fast through clay, which is 2 feet per hour.\n\nHe needs to dig:\n- 24 feet of soil\n- 8 feet of clay\n\nSo the total time is:\n\n$$\n\\frac{24 \\text{ feet}}{4 \\text{ feet/hour}} + \\frac{8 \\text{ feet}}{2 \\text{ feet/hour}} = 6 \\text{ hours} + 4 \\text{ hours} = \\boxed{10} \\text{ hours}\n$$\n\n**Answer:** $\\boxed{10}$ hours." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Howie wants to buy cupcakes for himself, his teacher, and his 25 classmates. He gets **one of each** for everyone.\n\n- He gets **1 cupcake** for himself.\n- His teacher gets **1 cupcake**.\n- His 25 classmates get **1 cupcake each**.\n\nSo, the total number of cupcakes is:\n\n$$\n1 + 1 + 25 = 27\n$$\n\n**Answer:** $\\boxed{27}$ cupcakes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the initial number of likes as $ x $.\n\n- After 1 week, the number of likes becomes $ x + 2000 $.\n- After 3 weeks, the number of likes becomes $ x + 2000 + 70x = 71x $.\n\nWe are told that the number of likes after 3 weeks is 70 times the initial number of likes:\n\n$$\n71x = 70x\n$$\n\nThis implies:\n\n$$\nx = 0\n$$\n\nBut this can't be correct, since the number of likes can't be zero. So, there must be a mistake in the interpretation.\n\nLet’s re-express the problem:\n\n- After 1 week: $ x + 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n---\n\n### **Day 1:**\n\n- Clara buys 20 pomegranates at $20 each.\n- Total cost: $20 × 20 = $400\n- She gets a $2 discount (voucher): $400 - $2 = $398\n\nSo, **Clara pays $398** on Day 1.\n\n---\n\n### **Day 2:**\n\n- The price is now $30 per fruit.\n- She buys 20 pomegranates: $30 × 20 = $600\n- The store also offers a **10% discount** on the total cost.\n\nSo, the total cost after discount is:\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ R $ be the total sales from red hats in the first month.\n- Let $ G $ be the total sales from green hats in the first month.\n\nFrom the problem:\n\n- Sales from red hats in the first month: $ R = 400 $\n- Sales from green hats in the first month: $ G = \\frac{R}{2} = \\frac{400}{2} = 200 $\n\nIn the second month:\n\n- Sales from red hats: $ \\frac{3}{4}R = \\frac{3}{4} \\times 400 = 300 $\n- Sales from green hats: $ \\frac{1}{2}G = \\frac{1}{2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James hires a horse-drawn carriage from **5 PM to 9 PM**, which is **2 hours**. He gets **1 hour free**. The first paid hour is **$15**, and each hour after that is **twice the cost**.\n\n### Step 1: Determine the number of paid hours\n- Total time: 2 hours\n- Free time: 1 hour\n- Paid time: $2 - 1 = 1$ hour\n\n### Step 2: Calculate the cost of the paid hour\n- First paid hour: $15\n\n### Step 3: Calculate the cost of the remaining hours\n- The next hour is **twice the cost** of the first hour.\n- So, the cost of the second hour is $1" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Sally's bank account started with $200 and now has $420. The difference is:\n\n$$\n420 - 200 = 220\n$$\n\nThis $220 represents the amount withheld from her wage.\n\nSince her weekly wage should be $300, and she was withheld $220, the answer is:\n\n$$\n\\boxed{220}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Lori needs **1 whole egg** to make **2 deviled egg halves**. \nEach guest will eat **3 deviled egg halves**. \nThere are **16 guests**.\n\n---\n\n### Step 1: Find out how many deviled egg halves Lori needs for 16 guests.\n\n$$\n16 \\text{ guests} \\times 3 \\text{ halves per guest} = 48 \\text{ deviled egg halves}\n$$\n\n---\n\n### Step 2: Find out how many eggs are needed for 48 deviled egg halves.\n\nSince 1 whole egg = 2 deviled egg halves:\n\n$$\n48 \\text{ halves} \\div 2 \\text{ halves per egg} = 24 \\text{ eggs}\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Shiela has already written $ \\frac{1}{3} $ of the 15-page paper. To find out how many pages she has left to write:\n\n$$\n15 - \\frac{1}{3} = \\frac{45}{3} - \\frac{1}{3} = \\frac{44}{3}\n$$\n\nSince $ \\frac{44}{3} $ is not an integer, this means she has **not** completed the paper completely. She has written $ \\frac{1}{3} $ of the paper, and there is a remainder of $ \\frac{44}{3} $ pages.\n\nSo, the answer is:\n\n$$\n\\boxed{\\frac{44}{3}}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mike reads 10 pages a day for 30 days, so the total number of pages he will read is:\n\n$$\n10 \\text{ pages/day} \\times 30 \\text{ days} = 300 \\text{ pages}\n$$\n\nSince the book is 200 pages, Mike will finish the reading **200 pages** before the deadline. Therefore, the number of days before the deadline is:\n\n$$\n\\boxed{200} \\text{ days}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James buys a plane for $150,000. \nHe pays $5,000 per month to rent a hanger. \nHe spends twice as much as that on fuel per month, so $10,000 per month.\n\nTo find the total cost for the first year:\n\n- Monthly cost: $5,000 (rent) + $10,000 (fuel) = $15,000/month \n- Yearly cost: $15,000/month × 12 months = $180,000\n\n**Answer:** $\\boxed{180000}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- It took **20 more minutes** to cook **pork** than rice.\n- The **combined cooking time of pork and rice** is **half the time it took to cook beans**.\n- It took **30 minutes** to cook rice.\n\nLet’s define the cooking times:\n\n- Let $ R $ be the time to cook rice = 30 minutes.\n- Let $ P $ be the time to cook pork = $ R + 20 = 30 + 20 = 50 $ minutes.\n- Let $ B $ be the time to cook beans = $ \\frac{1}{2}(P + R) = \\frac{1}{2}(50 + 30) = \\frac{1" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- Cost of 1 pound of almonds: $10 \n- Cost of 1 pound of walnuts: $15\n\nWe are asked to find how much more it costs for a **mixture of 1/2 pound almonds and 1/3 pound walnuts** compared to a **mixture of 1/5 pound almonds and 1/3 pound walnuts**.\n\n---\n\n### Step 1: Cost of the first mixture\n\n- Almonds: $ \\frac{1}{2} \\times 10 = 5 $\n- Walnuts: $ \\frac{1}{3} \\times 15 = 5 $\n- Total cost: $ 5 + 5 = \\boxed{10} $\n\n---\n\n### Step" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total number of animal legs = 70 \n- Total number of animal heads = 20\n\nLet:\n- $ s $ = number of sheep \n- $ g $ = number of geese\n\nWe know:\n- Each sheep has 4 legs and 1 head \n- Each goose has 2 legs and 1 head\n\nSo:\n$$\ns + g = 20 \\quad \\text{(1)}\n$$\n$$\n4s + 2g = 70 \\quad \\text{(2)}\n$$\n\nWe can solve this system of equations.\n\n**Step 1:** Multiply equation (1) by 2:\n$$\n2s + 2g = 40 \\quad \\text{(3)}\n$$\n\n**Step" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Roger buys coffee for a week, which is 7 days. He uses 1 pound of coffee per day, so he buys:\n\n$$\n7 \\text{ pounds of coffee}\n$$\n\nHe also buys a donut for $2.\n\nThe cost of the coffee is:\n\n$$\n5 \\text{ dollars per pound} \\times 7 \\text{ pounds} = 35 \\text{ dollars}\n$$\n\nSo the total cost is:\n\n$$\n35 \\text{ dollars (coffee)} + 2 \\text{ dollars (donut)} = \\boxed{37} \\text{ dollars}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gus spent $20.00 at the grocery store. He bought:\n\n- 2 bag of chips for $2.00 each → $2.00 × 2 = $4.00 \n- A bucket of fried chicken for $8.00 \n- A bottle of soda for $1.00 \n\nSo, the total spent on chips, chicken, and soda is:\n\n$$\n4.00 + 8.00 + 1.00 = 13.00\n$$\n\nSince Gus spent $20.00 in total, the cost of the apple pie is:\n\n$$\n20.00 - 13.00 = \\boxed{7.00}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James delivers:\n\n- 600 newspapers in a day,\n- 198 newspapers to District A,\n- 209 newspapers to District C.\n\nTo find the number of newspapers delivered to **District B**, we subtract the known quantities from the total:\n\n$$\n600 - 198 - 209 = \\boxed{193}\n$$\n\n**Answer:** $\\boxed{193}$ newspapers." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John takes a cooking class 4 times a week, 2 hours each time, for 6 weeks. \nHe learns a new recipe for every 1.5 hours of class time.\n\n### Step 1: Calculate total class time\n- 4 times a week × 2 hours = 8 hours per week \n- Over 6 weeks = 8 hours/week × 6 weeks = **48 hours**\n\n### Step 2: Calculate total recipe time\n- 48 hours × (1.5 hours/recipe) = **72 recipes**\n\n### Final Answer:\n$$\n\\boxed{72}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Total number of teachers on the school basketball court: $150$\n- 60% of them are history teachers: \n $0.60 \\times 150 = 90$ teachers\n- The rest are math teachers: \n $150 - 90 = 60$ teachers\n\nEach teacher sleeps for **6 hours a day**.\n\nSo, the total time the math teachers spend sleeping in one day is: \n$$\n60 \\text{ teachers} \\times 6 \\text{ hours/day} = 360 \\text{ hours}$$\n\n### Final Answer:\n$$\n\\boxed{360}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Arelia has $120.\n- Kassidy has $3/4$ times as much as Arelia.\n- Rayna has $60 more than Kassidy.\n\n---\n\n### Step 1: Express Kassidy's money in terms of Arelia's.\n\nSince Kassidy has $ \\frac{3}{4} $ times as much as Arelia:\n\n$$\n\\text{Kassidy's money} = \\frac{3}{4} \\times 120 = 90\n$$\n\n---\n\n### Step 2: Find Rayna's money.\n\nRayna has $60 more than Kassidy:\n\n$$\n\\text{Rayna's money} = 90" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah’s basketball games are 4 quarters, each 12 minutes long. However, in the last quarter, there was a tie, which extended the game for an additional **5 minutes**.\n\n- First quarter: 12 minutes \n- Second quarter: 12 minutes \n- Third quarter: 12 minutes \n- Fourth quarter: 12 minutes + 5 minutes = 17 minutes \n\nSo, the entire game lasted:\n\n$$\n12 + 12 + 12 + 17 = \\boxed{53} \\text{ minutes}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Total employees = 50 \n- 20% of employees are management → 20% of 50 = 10 \n- Out of this 10 management employees, 30% oversee the entire company → 30% of 10 = 3 \n\nSo, the number of employees who oversee the company is:\n\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Svetlana needs:\n\n- 5 tablespoons of flour per muffin \n- 3 tablespoons of sugar per muffin \n- 0.25 tablespoons of salt per muffin \n\nSo, for **16 muffins**, the total amount of dry ingredients is:\n\n$$\n16 \\times (5 + 3 + 0.25) = 16 \\times 8.25 = 132 \\text{ tablespoons}\n$$\n\n$$\n\\boxed{132} \\text{ tablespoons} \\text{ of dry ingredients}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Robert had 3 pounds of candy, Cindy had 5 pounds, and Aaron had 4 pounds. They pool and share their candy equally.\n\n- Total candy = 3 + 5 + 4 = **12 pounds**\n- Each person gets 12 ÷ 3 = **4 pounds**\n\n**Answer:** Each person would have $\\boxed{4}$ pounds of candy." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Adam bought:\n- 7 candies of type A, each costing $0.5 → total cost for A: $7 \\times 0.5 = 3.5$\n- 10 candies of type B, each costing $0.75 → total cost for B: $10 \\times 0.75 = 7.5$\n\nTotal cost: $3.5 + 7.5 = 11$\n\nAdam paid the cashier $15, so the change is:\n\n$$\n15 - 11 = \\boxed{4} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Christina's moods over the past 30 days are as follows:\n\n- **Good days**: 12 \n- **Bad days**: 8 \n- **Neutral days**: 10 (since 30 - 12 - 8 = 10)\n\nShe has already recorded:\n\n- **First 8 days**: Good \n- **Next 8 days**: Bad \n- **Next 8 days**: Neutral\n\nSo far, she has:\n\n- **Good days**: 8 (first 8) + 3 (next 3) = **11** \n- **Bad days**: 8 (second 8) + 0 = **8** \n- **Neutral days**: 10 (third 8) + 0 = **" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let $ S $ represent the number of books Sally has. According to the problem:\n\n- Janey has 3 more than twice the number of books that Sally has.\n- So, Janey's books = $ 2S + 3 $\n- We are told Janey has 21 books.\n\nSet up the equation:\n\n$$\n2S + 3 = 21\n$$\n\nSubtract 3 from both sides:\n\n$$\n2S = 18\n$$\n\nDivide by 2:\n\n$$\nS = 9\n$$\n\n### Final Answer:\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The bamboo grows **30 inches per day**.\n- Today, its height is **20 feet**.\n- We want to find how many **days** it will take for its height to reach **600 inches**.\n\n---\n\n### Step 1: Convert 20 feet to inches\n\nSince 1 foot = 12 inches:\n\n$$\n20 \\text{ feet} = 20 \\times 12 = 240 \\text{ inches}\n$$\n\nSo, today, the bamboo is 240 inches tall.\n\n---\n\n### Step 2: Find the total growth needed\n\n$$\n600 \\text{ inches} - 240 \\text{ inches} = 360 \\text" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n1. **Initial state**: \n James has 4 toys for 4 dogs. \n So, each dog gets **1 toy**.\n\n2. **Shelter has 8 more dogs**: \n So, there are now **4 + 8 = 12 dogs** in the shelter.\n\n3. **After buying toys**: \n James buys the toys to get the remaining 12 dogs. \n So, he now has **4 + 12 = 16 toys**.\n\n4. **3 dogs were gone**: \n So, he now has **16 - 3 = 13 toys**.\n\n5. **Total toys needed**: \n James needs **13 toys** in" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total investment: $1200\n- Dylan invested $ \\frac{2}{5} $ of the total amount.\n- Frances invested $ \\frac{2}{3} $ of the **remaining** amount after Dylan's investment.\n- Skyler invested the **remaining** amount.\n\n---\n\n### Step 1: Dylan's investment\n\nDylan invested $ \\frac{2}{5} $ of the total amount:\n\n$$\n\\text{Dylan's investment} = \\frac{2}{5} \\times 1200 = 480\n$$\n\n---\n\n### Step 2: Remaining amount after Dylan\n\n$$\n\\text{Remaining amount} = 1200 - 480 = 720\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Carol has 20 signatures, and Jennifer has 44. Together, they have:\n\n$$\n20 + 44 = 64 \\text{ signatures}\n$$\n\nThey want to reach **100 signatures** by the end of the summer. Since they have already collected 64 signatures, they need:\n\n$$\n100 - 64 = 36 \\text{ signatures}\n$$\n\n**Answer:** $\\boxed{36}$ signatures." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Lorie earns $10 per hour, so Karen earns:\n\n$$\n2 \\times 10 = 20 \\text{ dollars per hour}\n$$\n\nKaren works 3 hours per day, so her daily earnings are:\n\n$$\n20 \\times 3 = 60 \\text{ dollars per day}\n$$\n\nIn two days, her total earnings are:\n\n$$\n60 \\times 2 = \\boxed{120} \\text{ dollars}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given that **6 potatoes make 36 hash browks**.\n\nLet's find out how many hash browks can be made from **96 potatoes**.\n\n1. First, find out how many hash browks are made per potato:\n $$\n \\frac{36 \\text{ hash browks}}{6 \\text{ potatoes}} = 6 \\text{ hash browks per potato}\n $$\n\n2. Now, use this rate to find how many hash browks can be made from 96 potatoes:\n $$\n 96 \\text{ potatoes} \\times 6 \\text{ hash browks per potato} = 576 \\text{ hash browks}\n $$\n\n### Final Answer:\n$$\n\\boxed" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The elevator supports a maximum load of **700 kg**. \nAn adult weighs an average of **80 kg**, and **Jack rides the elevator with 8 other adults**.\n\nSo, the total weight of the group is:\n\n$$\n8 \\text{ adults} \\times 80 \\text{ kg/adult} = 640 \\text{ kg}\n$$\n\nSince the elevator can only support **700 kg**, the group will **exceed** the maximum load by:\n\n$$\n700 \\text{ kg} - 640 \\text{ kg} = 60 \\text{ kg}\n$$\n\n### Final Answer:\n$$\n\\boxed{60} \\text{ kg}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following relationships:\n\n- Max has 12 more cookies than the Cookie Monster.\n- Summer has 23 more cookies than Max.\n- Katarina has 5 less cookies than Max.\n\nLet’s define:\n\n- Let $ M $ be the number of cookies Max has.\n- Then the Cookie Monster has $ M - 12 $ cookies.\n- Summer has $ M - 12 + 23 = M + 11 $ cookies.\n- Katarina has $ M - 5 $ cookies.\n\nWe are told that Katarina has 68 cookies:\n\n$$\nM - 5 = 68\n$$\n\nSolving for $ M $:\n\n$$\nM = 68 + 5 = 73\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the original length of the dress as $ x $ cm.\n\n- She extends the dress by **50% of its original length**, so the extended length is $ 1.5x $ cm.\n- She adds **20 cm** to the bottom of the dress, so the total length becomes $ 1.5x + 20 $ cm.\n- The final design is given as **140 cm** long.\n\nWe are asked to find the original length $ x $.\n\n$$\n1.5x + 20 = 140\n$$\n\nSubtract 20 from both sides:\n\n$$\n1.5x = 120\n$$\n\nDivide both sides by 1.5:\n\n$$\nx = \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ T $ be the time in turtle mode (1 hour = 60 minutes).\n- Let $ R $ be the time in rabbit mode (40 minutes).\n\nWe are told:\n\n- In turtle mode, he can mow the entire lawn in 1 hour.\n- In rabbit mode, he can mow the entire lawn in 40 minutes.\n\nHe experimented by mowing **half** in turtle mode and **half** in rabbit mode.\n\nSo, the total time is:\n\n$$\n\\text{Total time} = \\frac{1}{2} \\times 60 + \\frac{1}{2} \\times 40 = 30 + 20 = 50 \\text{ minutes}\n$$\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John and Jack have **30 minutes** to walk to school together. They arrive at the **library** in **6 minutes**, and then **another 13 minutes** to reach the **fire station**. \n\nSo, the total time they spend walking to the library and the fire station is:\n\n$$\n6 + 13 = 19 \\text{ minutes}\n$$\n\nThey have **30 minutes** to walk to school, so the time they have **left** to get to school without being late is:\n\n$$\n30 - 19 = 11 \\text{ minutes}\n$$\n\n---\n\n**Final Answer:** $\\boxed{11}$ minutes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Catherine buys:\n\n- 1 kilo of apples for $4 \n- 2 kilos of bananas for $2 per kilo → $2 × 2 = $4 \n- 2 kilos of oranges for $3 per kilo → $3 × 2 = $6 \n\nTotal cost = $4 + $4 + $6 = **$14**\n\n$$\n\\boxed{14}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Greta bakes **30** cookies.\n\nCelinda bakes **twice as many** as Greta, so:\n\n$$\n30 \\times 2 = 60 \\text{ cookies}\n$$\n\nThey eat **10** of the cookies while cooling, so the number of cookies left in the box is:\n\n$$\n60 - 10 = 50\n$$\n\n### Final Answer:\n$$\n\\boxed{50}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ x $ be the age of one triplet.\n- Then, the age of the twin is $ x + 7 $, since one twin is 7 years older than one triplet.\n\nThe combined ages of the twins and triplets are:\n\n$$\n(x + (x + 7)) + x = 44\n$$\n\nSimplify:\n\n$$\n(2x + 7) + x = 44\n$$\n\n$$\n3x + 7 = 44\n$$\n\n$$\n3x = 37\n$$\n\n$$\nx = \\frac{37}{3}\n$$\n\nThis is not an integer, which suggests a mistake in the problem setup.\n\nLet's try again:\n\nLet $ x $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John has 20 minutes of math homework, 40 minutes of reading homework, and 20 minutes of history homework. He also has 3 hours before dinner.\n\nFirst, convert 3 hours to minutes: \n$$ 3 \\text{ hours} = 3 \\times 60 = 180 \\text{ minutes} $$\n\nNow, add the time he has to do his homework: \n$$ 20 + 40 + 20 = 80 \\text{ minutes} $$\n\nSubtract this from the total time before dinner: \n$$ 180 - 80 = 100 \\text{ minutes} $$\n\nSo, John has **100 minutes** to nap. \n\n$$\n\\boxed" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Manolo bought **5 lollipops** and **4 candies**. \n- Each lollipop costs **$0.40**, so the total cost of lollipops is: \n $ 5 \\times 0.40 = 2.00 $ \n- Each candy costs **$3.20**, so the total cost of candies is: \n $ 4 \\times 3.20 = 12.80 $ \n\nTotal cost: \n$ 2.00 + 12.80 = 14.80 $ \n\nNow, he wants to buy **10 lollipops** and **10 candies**. \n- Cost of 10 lollipops: $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Rong saves **20 coins** per month.\n\nNeil saves **2/5 times more** coins than Rong per month. \nSo, Neil saves: \n$$\n20 \\times \\left(1 + \\frac{2}{5}\\right) = 20 \\times \\frac{7}{5} = 28 \\text{ coins per month}\n$$\n\nAfter **10 years**, there are $10 \\times 12 = 120$ months in a year. \nSo, the total number of coins saved by both Rong and Neil is: \n$$\n20 \\times 120 + 28 \\times 120 = (20 + 28) \\times 120" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John brings his dog to the vet. The total cost includes:\n\n- 2 vaccines at $20 each: $2 \\times 20 = 40\n- A heartworm check: $60\\%$ of the total bill = $0.60 \\times (40 + 60) = 0.60 \\times 100 = 60\n\nSo, the total bill is $40 + 60 = 100.\n\nHe brought $125 with him, so he leaves with:\n\n$$\n125 - 100 = \\boxed{25}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- A crate contains:\n - 5 bananas\n - 12 apples\n - 7 oranges\n\n- The price of each fruit depends on the price of its individual type:\n - 1 apple = $0.5\n - 1 banana = $2 (twice the price of an apple)\n - 1 orange = 3 times the price of a banana\n\nLet’s calculate the price of the crate:\n\n1. **Price of 1 banana**: \n $ 2 \\times 0.5 = 1 $\n\n2. **Price of 1 apple**: \n $ 0.5 $\n\n3. **Price of 1 orange**: \n $ 3 \\times 1 = 3" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the number of colored squares in Brittany's comforter:\n\n- Red squares: 14 \n- Blue squares: 14 + 4 = 18 \n- Green squares: 18 + 6 = 24 \n- White squares: 24 - 12 = 12 \n\nNow, we need to find the total area of the comforter in square feet.\n\nEach square is 1 foot by 1 foot, so the total area is:\n\n$$\n14 + 18 + 24 + 12 = 68 \\text{ square feet}\n$$\n\n$$\n\\boxed{68} \\text{ square feet}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 42 adults and 15 babies will attend the function.\n- The restaurant has 5 times as many **regular** chairs as **high** chairs.\n- There are 8 high chairs.\n\nLet’s solve step by step:\n\n---\n\n### Step 1: Find the number of **regular** chairs\n\nWe are told that the restaurant has **5 times as many regular chairs as high chairs**.\n\n$$\n\\text{Number of regular chairs} = 5 \\times 8 = 40\n$$\n\n---\n\n### Step 2: Find the total number of chairs\n\n$$\n\\text{Total chairs} = \\text{Regular chairs} + \\text{High chairs} = 40 + 8 = 48\n$$\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- There are **50 deer** in the field.\n- **50%** of them are **bucks**.\n- **20%** of the **bucks** are **8 points**.\n\n---\n\n### Step 1: Find the number of bucks\n\n$$\n\\text{Number of bucks} = 50 \\times 0.50 = 25\n$$\n\n---\n\n### Step 2: Find the number of 8-point bucks\n\n$$\n\\text{Number of 8-point bucks} = 25 \\times 0.20 = 5\n$$\n\n---\n\n### ✅ Final Answer:\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Adam has collected **50 points**.\n- Betty was **30% more** than Adam, so she has:\n $$\n 50 + 0.30 \\times 50 = 50 + 15 = 65 \\text{ points}\n $$\n- Marta collected **3 times more** than Tom, and Tom has **30 points less** than Betty. So:\n - Tom has: $65 - 30 = 35$ points\n - Marta has: $3 \\times 35 = 105$ points\n\nNow, we need to find how many points the class is missing to reach **400 points**.\n\n$$\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Great Grandma Jones has **3 children**.\n- Each of these **3 children** has **3 grandchildren**.\n- Each of these **3 grandchildren** has **3 babies**.\n- All the family (Grandma Jones, her children, grandchildren, and great-grandchildren) show up.\n\nLet’s break it down step by step:\n\n1. **Grandma Jones** has 3 children.\n2. Each child has 3 grandchildren: \n $ 3 \\text{ children} \\times 3 \\text{ grandchildren} = 9 \\text{ grandchildren} $\n3. Each of these 9 grandchildren has 3 babies: \n $ 9 \\text{ grandchildren} \\times 3 \\text{ babies} = 27 \\text" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Greta's total paycheck is $2400.00.\n\n1. She puts **50%** of her pay into her retirement account:\n $$\n 0.5 \\times 2400 = 1200\n $$\n\n2. She uses **20%** of her paycheck to make her monthly car payment:\n $$\n 0.2 \\times 2400 = 480\n $$\n\n3. After funding her retirement and car payment, the remaining amount is:\n $$\n 2400 - 1200 - 480 = 720\n $$\n\n**Answer:** $\\boxed{720}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There is **20 pencils** in the box.\n- **4 pencils are missing** from the box.\n\nSo, the number of pencils in the box after removing 4 is:\n\n$$\n20 - 4 = 16 \\text{ pencils}\n$$\n\nNow, we are asked to find how many **pairs** of pencils are in the box.\n\n- Each pair consists of **2 pencils**.\n- So, the number of pairs is:\n\n$$\n\\frac{16}{2} = 8 \\text{ pairs}\n$$\n\n### Final Answer:\n$$\n\\boxed{8}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Hannah's city has 15 boxes of 20 fireworks each, so the total number of fireworks is:\n\n$$\n15 \\times 20 = 300 \\text{ fireworks}\n$$\n\nHannah's house is at a right angle to see **40%** of the city's fireworks. So she will see:\n\n$$\n0.40 \\times 300 = 120 \\text{ fireworks}\n$$\n\nHannah also sets off 3 boxes of 5 fireworks each, which is:\n\n$$\n3 \\times 5 = 15 \\text{ fireworks}\n$$\n\nSo the total number of fireworks Hannah will see is:\n\n$$\n120 + 15 = \\boxed{135}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Aiden and 12 friends = 13 people\n- 7 more friends = 13 + 7 = 20 people\n- Total people = 20\n- Each seat can hold 1 person, 2 drinks, and 3 snacks\n- Cost of drinks and snacks per person = $2\n\n### Step 1: Determine the number of seats needed\n\nEach seat can hold 1 person, 2 drinks, and 3 snacks. So, for 20 people, the number of seats is:\n\n$$\n20 \\text{ seats}\n$$\n\n### Step 2: Calculate the cost of snacks and drinks\n\nEach seat costs $2 for drinks and $2 for snacks, so each seat costs" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Gissela's truck can haul **4,000 pounds** of gravel.\n- Gordy's truck can haul **800 pounds more** than Gissela's, so Gordy's truck can haul:\n $$\n 4,000 + 800 = 4,800 \\text{ pounds}\n $$\n- Let $ x $ be the amount of gravel Gary's truck can haul.\n\nWe are told that when Gary joins Gissela and Gordy, the **total** amount of gravel they can haul is **11,600 pounds**.\n\nSo, the total amount is:\n$$\n4,000 + 4,800 + x = 1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **8 males** and **6 females**.\n- Each **male ate 1 more dumpling** than each **female**.\n- Each **female ate 3 dumplings**.\n- There were **no leftovers**.\n\nLet’s define:\n\n- Let $ x $ be the number of dumplings each female ate.\n\nWe are told that each female ate **3 dumplings**, so:\n\n$$\nx = 3\n$$\n\nSince each male ate **1 more** than each female, each male ate:\n\n$$\nx + 1 = 3 + 1 = 4\n$$\n\nNow, there are **8 males**, so the total number of dumplings eaten by males is:\n\n$$\n8 \\times 4 = 32" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gerald and Julia divided $100 in the ratio 3:2. \nSo, the total parts = 3 + 2 = 5.\n\nGerald's share = $ \\frac{3}{5} \\times 100 = 60 $.\n\nGerald spent $10 on a book, so he had:\n\n$$\n60 - 10 = \\boxed{50}\n$$\n\n**Answer:** $\\boxed{50}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Martha's cat is 5 times faster than her turtle. \n- The cat's speed is 15 feet per second. \n- Therefore, the turtle's speed is: \n $$\n \\frac{15 \\text{ feet/second}}{5} = 3 \\text{ feet/second}\n $$\n\nNow, the turtle crawls for 40 seconds: \n$$\n3 \\text{ feet/second} \\times 40 \\text{ seconds} = 120 \\text{ feet}\n$$\n\n**Final Answer:** $\\boxed{120}$ feet." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that:\n\n- The goal is to raise **$6300**.\n- After **3 hours**, they have raised **$2100**.\n- They raise **an equal amount per hour**.\n\nLet’s find the amount raised per hour:\n\n$$\n\\text{Amount per hour} = \\frac{6300 - 2100}{3} = \\frac{4200}{3} = 1400\n$$\n\nNow, to reach the goal of **$6300**, they need:\n\n$$\n\\frac{6300 - 2100}{1400} = \\frac{4200}{1400} = 3 \\text{" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- Colorado City uses **40%** of the water from the **Colorado River**.\n- **80%** of that water is used for **industrial purposes**.\n\nTo find the percentage of the river's total water used by the city for **non-industrial purposes**, we subtract the industrial usage from the total usage:\n\n$$\n100\\% - 40\\% = 60\\%\n$$\n\nSo, **60% of the river's total water is used by the city for non-industrial purposes**.\n\n$$\n\\boxed{60\\%}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Alex charges $12 per day for tutoring. \nFor 2 weeks, there are 2 × 7 = 14 days.\n\nSo, the total amount she charges for 2 weeks is:\n\n$$\n14 \\text{ days} \\times 12 \\text{ dollars/day} = \\boxed{168} \\text{ dollars}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 100 quarts of chocolate ice cream in 2 hours.\n- 50 quarts of vanilla ice cream in 4 hours.\n\nWe are asked to find how many quarts in total would be made in **48 hours**.\n\n---\n\n### Step 1: Find the rate of chocolate ice cream per hour\n\n$$\n\\text{Rate of chocolate} = \\frac{100 \\text{ quarts}}{2 \\text{ hours}} = 50 \\text{ quarts/hour}\n$$\n\n---\n\n### Step 2: Find the rate of vanilla ice cream per hour\n\n$$\n\\text{Rate of vanilla} = \\frac{50 \\text{ quarts}}{4 \\text{ hours}} =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Marcus ordered:\n\n- 5 croissants at $3.00 each: $5 × $3.00 = **$15.00**\n- 4 cinnamon rolls at $2.50 each: $4 × $2.50 = **$10.00**\n- 3 mini quiches at $4.00 each: $3 × $4.00 = **$12.00**\n- 13 blueberry muffins at $1.00 each: $13 × $1.00 = **$13.00**\n\n**Total cost before loyalty card discount:** \n$15.00 + $10.00 + $12.00 +" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that:\n\n- Each scoop costs **$1.50**\n- Buy **2 scoops = 1 free scoop**\n- Total money available: **$6.00**\n\n---\n\n### Step 1: Determine how many free scoops Erin gets\n\nSince buying 2 scoops gives her 1 free scoop, the number of free scoops is **half** of the number of scoops she buys.\n\nLet $ x $ be the number of scoops Erin buys.\n\nThen, the number of free scoops is $ \\frac{x}{2} $.\n\n---\n\n### Step 2: Total cost\n\nThe total cost is:\n\n$$\n1.50 \\times x\n$$\n\nWe know the total money she has is **$6.00**, so" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ginger eats 4 pieces a day, and Amy eats 3 pieces a day. Both start with 100 pieces of candy.\n\n### Step 1: Calculate how many days in a week\nA week has 7 days.\n\n### Step 2: Calculate how much candy each person eats in a week\n- **Ginger**: $ 4 \\text{ pieces/day} \\times 7 \\text{ days} = 28 \\text{ pieces} $\n- **Amy**: $ 3 \\text{ pieces/day} \\times 7 \\text{ days} = 21 \\text{ pieces} $\n\n### Step 3: Subtract the amount eaten from the initial amount\n- **Ginger's remaining candy**: $ 100 - 2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Boarden needs to cover **two-thirds** of his **36 sq ft** bathroom.\n\n- First, calculate **two-thirds** of 36:\n $$\n \\frac{2}{3} \\times 36 = 24 \\text{ sq ft}\n $$\n\n- Since he needs **24 mosaic tiles per square foot**, the total number of tiles needed is:\n $$\n 24 \\times 24 = \\boxed{576} \\text{ mosaic tiles}\n $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James picks blueberries:\n\n- **Cost to pick**: $20 \n- **Cost per pound**: $1.5 \n- **Picked**: 30 pounds \n\n### Step 1: Total cost to pick 30 pounds \n$$\n20 + 1.5 \\times 30 = 20 + 45 = 65\n$$\n\n### Step 2: Total cost if buying at the store for $2.5 per pound \n$$\n2.5 \\times 30 = 75\n$$\n\n### Step 3: Savings \n$$\n75 - 65 = 10\n$$\n\n### Final Answer: \n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. **Original price per computer**: $700 \n2. **Price increased by 10%**: \n $ 700 \\times 1.10 = 770 $\n\n3. **Number of computers**: 500 \n4. **Total cost at new prices**: \n $ 500 \\times 770 = 385,000 $\n\n**Final Answer**: \n$$\n\\boxed{385000}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John makes a 6-egg omelet with:\n\n- 2 oz of cheese \n- 2 oz of ham \n\nEggs are 75 calories each, cheese is 120 calories per ounce, and ham is 40 calories per ounce.\n\nSo, the total calories are:\n\n- Calories from eggs: $ 6 \\times 75 = 450 $ calories \n- Calories from cheese: $ 2 \\times 120 = 240 $ calories \n- Calories from ham: $ 2 \\times 40 = 80 $ calories \n\nTotal calories = $ 450 + 240 + 80 = \\boxed{770} $ calories." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Cost of 1 pencil = $0.50 \n- Cost of 1 eraser = $0.25 \n- Number of pencils = 6 \n- Number of erasers = 8 \n- Total amount paid = $10 \n\n### Step 1: Calculate total cost of pencils and erasers\n\n- Cost of pencils: \n $ 6 \\times 0.50 = 3.00 $\n\n- Cost of erasers: \n $ 8 \\times 0.25 = 2.00 $\n\n- Total cost: \n $ 3.00 + 2.00 = 5.00 $\n\n### Step 2: Calculate change\n\n- Total amount paid: $1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- **100 people apply**.\n- **30%** of them receive interviews.\n- **20%** of those who receive interviews get a job offer.\n- **30%** of those who get a job offer accept the position.\n\nWe need to find how many people **accept the position**.\n\n---\n\n### Step 1: Calculate how many people receive interviews\n\n$$\n30\\% \\text{ of } 100 = 0.30 \\times 100 = 30\n$$\n\nSo, **30 people receive interviews**.\n\n---\n\n### Step 2: Calculate how many people get a job offer\n\n$$\n20\\% \\text{ of } 30 = " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Goldy bought 20 sacks of rice. She gave 3 to her cousin and 4 to her brother. \n\n- Total sacks given: $ 3 + 4 = 7 $ sacks.\n- Total rice given: $ 7 \\text{ sacks} \\times 25 \\text{ kg/sack} = 175 \\text{ kg} $.\n\n**Answer:** $\\boxed{175}$ kilograms." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Castle bought:\n\n- 3 boxes of Coco Crunch \n- 5 boxes of Fruit Loops \n- 4 boxes of cereal this week\n\nTo find how many more boxes of cereal she bought this week than last week, we subtract the cereal boxes from the cereal boxes she bought last week:\n\n$$\n4 - 0 = 4\n$$\n\nSo, she bought **4 more boxes of cereal this week than last week**.\n\n$$\n\\boxed{4}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Helga taps both feet at different rates depending on whether she is raising her arms or not. Here's the breakdown:\n\n- **When raising her arms**: \n - Right foot: 200 taps per minute \n - Left foot: 200 taps per minute \n - Total taps per minute: $200 + 200 = 400$ taps\n\n- **When not raising her arms**: \n - Right foot: 300 taps per minute \n - Left foot: 250 taps per minute \n - Total taps per minute: $300 + 250 = 550$ taps\n\n- **Total time**: 5 minutes \n- **Number of minutes with arms raised**: " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ron will save money by fixing the pothole himself. Let's break it down:\n\n- **Cost of fixing the pothole**: $450 (damage to his car)\n- **Cost of buying asphalt**: $3 \\times 25 = 75\n- **Fines from the city council**: $120\n\nRon saves:\n$$\n450 + 75 - 120 = \\boxed{395}\n$$\n\nSo, Ron saves **$395** by fixing the pothole himself." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The restaurant has:\n\n- 170 normal chairs \n- 23 baby chairs\n\n**Total chairs initially:** \n$ 170 + 23 = 193 $ chairs\n\n**Chairs sent to the carpenter:** \n- 20 normal chairs \n- 13 baby chairs\n\n**Total chairs sent:** \n$ 20 + 13 = 33 $ chairs\n\n**Chairs remaining:** \n$ 193 - 33 = \\boxed{160} $ chairs." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bryce and four of his friends ordered their pizzas. Each pizza had 12 slices, so:\n\n- Total number of pizzas = 5 (Bryce + 4 friends)\n- Total number of slices = $ 5 \\times 12 = 60 $\n\nNow, Bryce and two friends ate $ \\frac{2}{3} $ of their pizzas. Let's calculate how many slices they ate:\n\n- Number of pizzas eaten by Bryce and two friends = $ \\frac{2}{3} \\times 5 = \\frac{10}{3} $ pizzas\n- Number of slices eaten = $ \\frac{10}{3} \\times 12 = 40 $ slices\n\nThe remaining two friends ate $ \\frac{3}{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A cat eats **9 sausages** in **30 minutes**.\n- A dog eats the **same number of sausages** in **$ \\frac{2}{3} $** the time the cat takes.\n\n---\n\n### Step 1: Find the rate of the cat\n\nThe cat eats 9 sausages in 30 minutes. So, its rate is:\n\n$$\n\\text{Rate of cat} = \\frac{9 \\text{ sausages}}{30 \\text{ minutes}} = \\frac{3}{10} \\text{ sausages per minute}\n$$\n\n---\n\n### Step 2: Find the rate of the dog\n\nThe dog eats the same number of sausages in $ \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The length of one of Topher’s shoes is **8 feet 4 inches**.\n- The length of one of Topher’s shoes is **10 inches longer than 9 times the length of one of Bobby’s shoes**.\n\nLet’s denote the length of one of Bobby’s shoes in inches as $ x $.\n\nThen, the length of one of Topher’s shoes is:\n\n$$\n8 \\text{ feet} + 4 \\text{ inches} = 8 \\times 12 + 4 = 96 + 4 = 100 \\text{ inches}\n$$\n\nWe are told that:\n\n$$\n100 = 9x + 10\n$$\n\nSolving for $ x $:\n\n$$\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- 64 students' cars, each with 4 windows.\n- 32 teachers' cars, each with 2 windows.\n\nHannah smashes:\n\n- $ \\frac{1}{4} $ of the students' cars' windows: \n $ \\frac{1}{4} \\times 64 = 16 $\n\n- $ \\frac{3}{4} $ of the teachers' cars' windows: \n $ \\frac{3}{4} \\times 32 = 24 $\n\nSo, the total number of windows Hannah smashes is:\n\n$$\n16 + 24 = \\boxed{40}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "To find the **percent of her spools that are blue**, we first calculate the total number of spools:\n\n$$\n15 \\text{ (light blue)} + 45 \\text{ (dark blue)} + 40 \\text{ (light green)} + 50 \\text{ (dark green)} = 150 \\text{ spools}\n$$\n\nNow, we find the **percent of blue spools**:\n\n$$\n\\frac{15 + 45}{150} \\times 100 = \\frac{60}{150} \\times 100 = 40\\%\n$$\n\n### Final Answer:\n$$\n\\boxed{40\\%}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- At 8:00, 5000 people lined up.\n- By **midday 2/5** of the people had voted.\n- By **16:00** (which is **2/5** of the day), **2/3** of the remaining people had voted.\n\nWe need to find the number of people who had **not** voted by **16:00**.\n\n---\n\n### Step 1: Total number of people\n\nAt 8:00, 5000 people were in line.\n\n---\n\n### Step 2: People who had voted by 8:00\n\n- **2/5** of 5000 = $ \\frac{2}{5} \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Parker chews 4 pieces of gum a day. \nA pack has 15 pieces. \nWe need to find how many packs he needs to last him 30 days.\n\n1. **Total pieces Parker eats in 30 days**:\n $$\n 4 \\text{ pieces/day} \\times 30 \\text{ days} = 120 \\text{ pieces}\n $$\n\n2. **Number of packs needed**:\n $$\n \\frac{120 \\text{ pieces}}{15 \\text{ pieces/pack}} = 8 \\text{ packs}\n $$\n\n**Answer**: $\\boxed{8}$ packs of gum." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Each sleeve of Graham crackers makes the base for **8 large smores**.\n- There are **3 sleeves in a box**.\n- There are **9 kids** who want **2 smores each**.\n- There are **6 adults** who want **1 smore each**.\n\n---\n\n### Step 1: Calculate the total number of smores needed\n\n- **Smores from kids**: \n $ 9 \\text{ kids} \\times 2 = 18 \\text{ smores} $\n\n- **Smores from adults**: \n $ 6 \\text{ adults} \\times 1 = 6 \\text{ smores} $\n\n- **Total smores needed**: \n $ 18 + 6 = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Dora's age = 15 years.\n- Dora's mother is 4 years younger than Dora's father.\n- Dora's father's age is 8 more than twice Dora's age.\n\n---\n\n### Step 1: Express Dora's father's age\n\nLet $ D $ be Dora's age. Then:\n\n- Dora's father's age = $ 2D + 8 = 2(15) + 8 = 30 + 8 = 38 $ years.\n\n---\n\n### Step 2: Express Dora's mother's age\n\n- Dora's mother is 4 years younger than Dora's father, so:\n\n$$\n\\text{Dora's mother's age" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Greg has 20 dollars and he wants to split it equally among his 3 younger siblings. To find out how much each sibling gets, we divide the total amount by the number of siblings:\n\n$$\n\\frac{20}{3} = 6.67\n$$\n\nSo, each of them gets **$6.67**. \n\n$$\n\\boxed{6.67}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cindy's math and science books weigh **2 pounds each**, so together they weigh:\n\n$$\n2 + 2 = 4 \\text{ pounds}\n$$\n\nHer French book weighs **4 pounds**, and her English book weighs **3 pounds**. Adding these:\n\n$$\n4 + 3 = 7 \\text{ pounds}\n$$\n\nHer history book weighs **twice as much as her English book**, so:\n\n$$\n2 \\times 3 = 6 \\text{ pounds}\n$$\n\nNow, add all the weights together:\n\n$$\n4 + 7 + 6 = \\boxed{17} \\text{ pounds}\n$$\n\nSo, the total weight of the books Cindy is carrying is **17 pounds**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Candidate A got **20%** of the votes.\n- Candidate B got **50% more** than candidate A's votes.\n- The rest of the votes (i.e., the remaining votes) went to candidate C.\n- There were **100 voters** in total.\n\n---\n\n### Step 1: Calculate the number of votes for candidate A\n\n- Candidate A got **20%** of 100 voters:\n $$\n 0.20 \\times 100 = 20 \\text{ votes}\n $$\n\n---\n\n### Step 2: Calculate the number of votes for candidate B\n\n- Candidate B got **50% more** than candidate A's votes:\n $$\n 20" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Boris has 100 apples.\n\nBeck has 23 fewer apples than Boris, so:\n\n$$\n\\text{Beck's apples} = 100 - 23 = 77\n$$\n\nBoris gives Beck 10 apples, so now:\n\n$$\n\\text{Beck's apples} = 77 - 10 = 67\n$$\n\nNow, how many fewer apples does Beck have than Boris?\n\n$$\n100 - 67 = 33\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{33}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Peter wants to make ice cubes using 32 ounces of water. He makes:\n\n- 3 giant cubes: $ 3 \\times 4 = 12 $ ounces \n- 7 medium cubes: $ 7 \\times 2 = 14 $ ounces \n- 8 small cubes: $ 8 \\times 0.5 = 4 $ ounces \n\nTotal water used: \n$$ 12 + 14 + 4 = 30 \\text{ ounces} $$\n\nWater left: \n$$ 32 - 30 = \\boxed{2} \\text{ ounces} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Clara has 20 books.\n- Clara has **two times as many books as Steven**.\n- Alice has **6 more books than Steven**.\n\nLet’s define:\n\n- Let Steven have $ x $ books.\n- Then Clara has $ 2x $ books.\n- Alice has $ x + 6 $ books.\n\nWe are told Clara has 20 books, so:\n\n$$\n2x = 20 \\Rightarrow x = 10\n$$\n\nNow, substitute $ x = 10 $ into the expressions:\n\n- Steven has 10 books.\n- Alice has $ 10 + 6 = 16 $ books.\n- Clara has 20 books.\n\nNow, to find how many more books Clara has than Alice" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Find the cost of a **half-gallon jar**\n\nWe are told that a **gallon jar costs $5**. \nAlso, a **gallon jar costs $2 more than a half-gallon jar**.\n\nSo, let the cost of a **half-gallon jar** be $ x $.\n\n$$\n\\text{Cost of a gallon jar} = x + 2 = 5\n$$\n\n$$\nx + 2 = 5 \\Rightarrow x = 3\n$$\n\nSo, a **half-gallon jar costs $3**.\n\n---\n\n### Step 2: Calculate the total cost for 10-gallon jars and 16 half-gallon jars\n\n- Each **" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- There are **50 students** in total.\n- **10 like to bake**.\n- **5 like to play basketball**.\n- The rest like to **either play video games or play music**.\n- The number that like to play **music is twice** the number that like to play basketball.\n\n---\n\n### Step 1: Find the number of students who like **video games or music**\n\nWe know:\n\n- Total students = 50 \n- Students who like to bake = 10 \n- Students who like to play basketball = 5 \n\nSo, the remaining students are:\n\n$$\n50 - 10 - 5 = 35\n$$\n\nThese 35 students like **either video games or music" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jeremy saw **12 birds** in their backyard and threw a stone at them, scaring away **1/3** of that number. \nSo, the number of birds that were scared away is: \n$$\n\\frac{1}{3} \\times 12 = 4\n$$\n\nAfter that, **20 more birds** joined the fearless birds. \nSo, the total number of birds now in the backyard is: \n$$\n12 - 4 + 20 = 28\n$$\n\n**Final Answer:** $\\boxed{28}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Total students in both classes: $ 80 $\n- Each class has the same number of students\n- In each class, $ 40\\% $ of the students are girls\n\nLet the number of students in each class be $ x $.\n\nThen:\n\n- Number of girls in each class: $ 0.4x $\n- Number of boys in each class: $ x - 0.4x = 0.6x $\n\nWe are told that the total number of students in both classes is 80, so:\n\n$$\nx + x = 80\n$$\n\n$$\n2x = 80\n$$\n\n$$\nx = 40\n$$\n\nSo, each class has 40 students.\n\nNumber" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mara initially had 2 slices on the plate. \nShe added 3 slices, making it **5 slices**. \nThen she tripled the number of slices, so she had **15 slices**. \nShe ate 2 slices, leaving **13 slices**. \nHer friend stole 5 slices, so the final number of cake slices is:\n\n$$\n\\boxed{13}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Melissa has:\n\n- 8 dogs \n- 5 cats \n- 3 birds \n- 12 horses\n\nTotal animals = 8 + 5 + 3 + 12 = **28 animals**\n\nShe splits the grooming jobs evenly over the **7 days** of the week.\n\nSo, the number of animals she grooms each day = **28 ÷ 7 = 4**\n\n**Answer:** $\\boxed{4}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark buys 3 packs of cards for $1800 each, so the total cost is:\n\n$$\n3 \\times 1800 = 5400\n$$\n\nHe also gets 1 card worth $4000 and another card worth $1000, so the total value of these cards is:\n\n$$\n4000 + 1000 = 5000\n$$\n\nHe also gets 30 more cards, each worth an average of $50. So the total value of these 30 cards is:\n\n$$\n30 \\times 50 = 1500\n$$\n\nNow, add all the values together:\n\n$$\n5400 + 5000" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- **First amusement park**:\n - $26 per adult\n - $12 per child\n\n- **Second amusement park**:\n - $14 per adult\n - $10 per child\n\n**Family members**:\n- 2 adults\n- 2 children\n\n### Step 1: Calculate total cost at each park\n\n#### First park:\n- Adults: $26 × 2 = 52\n- Children: $12 × 2 = 24\n- **Total cost**: $52 + $24 = **$76**\n\n#### Second park:\n- Adults: $14 × 2 = $28\n- Children: $10 × 2 = $20\n-" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **He sells 500 tomatoes a day** at $0.4 each.\n- **He used to buy them for $0.5 each**.\n- **He saves money by switching vendors**.\n\n### Step 1: Calculate the cost of 500 tomatoes if he buys them at $0.5 each\n$$\n500 \\times 0.5 = 250 \\text{ dollars}\n$$\n\n### Step 2: Calculate the cost of 500 tomatoes if he buys them at $0.4 each\n$$\n500 \\times 0.4 = 200 \\text{ dollars}\n$$\n\n### Step 3: Find the difference in cost" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Sean has 56 marbles.\n- Sean has **half as many marbles as Cal**.\n- Carl has **four times as many marbles as Sean**.\n\n---\n\n### Step 1: Express Cal's marbles in terms of Sean's.\n\nSince Sean has **half as many marbles as Cal**, we can write:\n\n$$\n\\text{Sean} = \\frac{1}{2} \\times \\text{Cal}\n$$\n\n$$\n56 = \\frac{1}{2} \\times \\text{Cal}\n$$\n\nMultiply both sides by 2:\n\n$$\n\\text{Cal} = 112\n$$\n\n---\n\n### Step 2: Express Carl's marbles in terms of Sean's.\n\nSince Carl has" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **54 students**.\n- These students are to be separated into **6 groups of equal size**.\n- The activity requires **12 groups**.\n\nWe are to find how many **more groups** are needed to form.\n\n### Step 1: Find the size of each group\n\nSince there are 54 students and 6 groups, each group will have:\n\n$$\n\\frac{54}{6} = 9 \\text{ students per group}\n$$\n\n### Step 2: Find how many groups are needed for 12 groups\n\nWe are told that the activity requires **12 groups**, and we need to find how many **more** groups are needed.\n\n$$\n12 \\text{ groups} - 6" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- On **weekdays**, 60 chairs are rented each day.\n- On **weekends**, 100 chairs are rented each day.\n\nCandy rents out **2 4-week months**.\n\n### Step 1: Calculate the number of days in 2 4-week months\n\n- 1 month = 4 weeks \n- 2 4-week months = 2 × 4 = 8 weeks \n- Total days = 8 × 7 = **56 days**\n\n### Step 2: Calculate total chairs rented\n\n- On weekdays (7 days): 60 chairs/day × 56 days = 3,360 chairs \n- On weekends (7 days): 100 chairs/day × 56" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n1. **Initial pile**: Gunther had 48 bananas.\n\n2. **Arnold steals half**: \n - Arnold steals half of 48 bananas → 24 bananas are stolen. \n - Remaining bananas: $ 48 - 24 = 24 $.\n\n3. **Arnold steals another 12 bananas**: \n - Arnold steals 12 more → 24 - 12 = 12 bananas are stolen. \n - Remaining bananas: $ 24 - 12 = 12 $.\n\n4. **Gunther adds 25 bananas**: \n - He adds 25 bananas → 12 + 25 = 37" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jenna has 4 roommates, and each month the electricity bill is **$100**.\n\n- There are **12 months** in a year.\n- So, the total annual electricity bill is:\n $$\n 100 \\times 12 = 1200\n $$\n\n- Dividing this by 4 roommates:\n $$\n \\frac{1200}{4} = 300\n $$\n\n**Each roommate will pay $300 per year.**\n\n$$\n\\boxed{300}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jeff sent:\n\n- 8 dozen glasses \n- 4 dozen plates\n\nSo, the total number of glasses is:\n\n$$\n8 \\times 12 = 96 \\text{ glasses}\n$$\n\nThe total number of plates is:\n\n$$\n4 \\times 12 = 48 \\text{ plates}\n$$\n\nWhen they were returned, 10 glasses and 6 plates were broken. So, the number of glasses and plates Jeff has now is:\n\n$$\n96 - 10 = 86 \\text{ glasses}\n$$\n$$\n48 - 6 = 42 \\text{ plates}\n$$\n\nSo, Jeff now has:\n\n$$\n\\boxed{86 \\text{ glasses and } 42 \\text{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Lorraine starts with:\n - 30 small stickers\n - 40 large stickers\n\n- She trades:\n - 90% of her small stickers for large buttons\n - 50% of her large stickers for large buttons\n - The rest of her large stickers for small buttons\n\nLet's break it down step by step.\n\n---\n\n### Step 1: Calculate the number of small and large stickers traded\n\n- **Small stickers traded for large buttons**: \n $ 90\\% \\times 30 = 0.9 \\times 30 = 27 $\n\n- **Large stickers traded for large buttons**: \n $ 50\\% \\times 40 = 0.5 \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joey played:\n\n- **2 matches on Monday** \n- **1 match on Friday** \n- **Double the number of matches on Monday** = $2 \\times 2 = 4$ matches on Saturday\n\nSo, total matches played in the week:\n\n$$\n2 + 1 + 4 = \\boxed{7}\n$$\n\n**Answer:** $\\boxed{7}$ matches." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the number of votes in favor of the new regulation be $ x $, and the number of votes against it be $ y $.\n\nWe are told:\n- The vote passed with **twice as many votes in favor** as there were against.\n- There are 33 people on the council.\n\nSo:\n$$\nx = 2y\n$$\n\nAlso, since the total number of people is 33:\n$$\nx + y = 33\n$$\n\nSubstitute $ x = 2y $ into the second equation:\n$$\n2y + y = 33\n$$\n$$\n3y = 33\n$$\n$$\ny = 11\n$$\n\nThen:\n$$\nx = 2y = 22" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the number of students needing each size of shirts:\n\n- **Extra-small**: 11 students \n- **Small**: 2 × 11 = **22 students** \n- **Medium**: 4 less than small = 22 - 4 = **18 students** \n- **Large**: Half as many as medium = 18 / 2 = **9 students** \n- **Extra-large**: 6 more than large = 9 + 6 = **15 students**\n\nNow, add all the students:\n\n$$\n11 + 22 + 18 + 9 + 15 = \\boxed{75}\n$$\n\n**Answer:** $\\boxed{75}$ shirts." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The original price is $140, and there is a 5% discount.\n\n1. Calculate the discount amount:\n $$\n 5\\% \\text{ of } 140 = 0.05 \\times 140 = 7\n $$\n\n2. Subtract the discount from the original price:\n $$\n 140 - 7 = 133\n $$\n\nSo, the final price after the discount is **$133**. \n\n$$\n\\boxed{133}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Total number of songs in the playlist: 300 \n- Number of playlists: 20 \n- Each song is 10 hours long\n\n### Step 1: Calculate the total number of song hours\n\n$$\n\\text{Total song hours} = 300 \\text{ songs} \\times 10 \\text{ hours/song} = 3000 \\text{ hours}\n$$\n\n### Step 2: Multiply by the number of playlists\n\n$$\n\\text{Total hours} = 3000 \\text{ hours} \\times 20 = 60000 \\text{ hours}\n$$\n\n### Final Answer:\n\n$$\n\\boxed{60000}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 20% of 50 people think horse #2 will win.\n- 60% of the remaining people think horse #7 will win.\n- The rest of the people think horse #12 will win.\n\n---\n\n### Step 1: Calculate the number of people who think horse #2 will win.\n\n$$\n20\\% \\text{ of } 50 = 0.20 \\times 50 = 10 \\text{ people}\n$$\n\nSo, **10 people** think horse #2 will win.\n\n---\n\n### Step 2: Find the remaining people.\n\n$$\n50 - 10 = 40 \\text{ people}\n$$\n\n---\n\n### Step 3: Calculate how many of" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\nWe are told:\n\n- **Two-thirds of Jana's puppies are Pomeranians**.\n- **One-third of the Pomeranians are girls**.\n- There are **6 Pomeranian girls**.\n\n---\n\n### Step 1: Let the total number of puppies be $ x $.\n\nThen:\n\n- Number of Pomeranians = $ \\frac{2}{3}x $\n- Number of Pomeranians that are girls = $ \\frac{1}{3} \\times \\frac{2}{3}x = \\frac{2}{9}x $\n\nWe are told that the number of Pomeranian girls is 6:\n\n$$\n\\frac{2}{9}x = 6\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jayden had $70 from selling pictures. His sister Ava gave him half of her $90 allowance to help him buy a new camera that costs $200.\n\n- Ava gave him half of her $90: \n $$\n \\frac{1}{2} \\times 90 = 45\n $$\n\n- So, Jayden now has: \n $$\n 70 + 45 = 115\n $$\n\n- The camera costs $200, so Jayden needs: \n $$\n 200 - 115 = 85\n $$\n\n**Final Answer:** $\\boxed{85}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The first house needs $ \\frac{1}{2} $ of the second house.\n- The third house needs double the first house.\n- The total number of cases needed is 250.\n\nLet’s define:\n\n- Let $ x $ be the number of cases needed for the **first house**.\n- Then the **second house** needs $ 2x $ cases.\n- The **third house** needs $ 2x $ cases.\n\nSo the total number of cases is:\n\n$$\nx + 2x + 2x = 5x = 250\n$$\n\nSolving for $ x $:\n\n$$\nx = \\frac{250}{5} = 50\n$$\n\nTherefore, the **third" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Leila spends:\n$$ 3 \\times 2 = 6 \\text{ dollars} $$\n\nJack spends:\n$$ 5 \\times 1 = 5 \\text{ dollars} $$\n\nChase spends:\n$$ 1 \\times 3 = 3 \\text{ dollars} $$\n\nTotal cost:\n$$ 6 + 5 + 3 = \\boxed{14} \\text{ dollars} $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "George has 45% more pears than bananas. He has 200 bananas.\n\n- 45% of 200 bananas = 0.45 × 200 = 90 pears \n- Total fruits = 200 bananas + 90 pears = 290 fruits\n\n**Answer:** $\\boxed{290}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Marissa had $80 on her.\n\nShe used the rest of the money to buy candy bars, which cost $5 each.\n\nSo, the number of candy bars she bought is:\n\n$$\n\\frac{80 - 20}{5} = \\frac{60}{5} = 12\n$$\n\n**Answer:** $\\boxed{12}$ candy bars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sam needs **5 kilograms** of oranges to make **1 liter** of juice. \nSo, for **4 liters**, he needs:\n\n$$\n5 \\, \\text{kg/liter} \\times 4 \\, \\text{liters} = 20 \\, \\text{kg}\n$$\n\nEach kilogram costs **$3**, so the total cost is:\n\n$$\n20 \\, \\text{kg} \\times 3 \\, \\text{\\$/kg} = \\boxed{60} \\, \\text{\\$}\n$$\n\n**Answer:** $\\boxed{60}$ dollars." + } + ] + }, + "durable": { + "variant": "durable", + "seed": 20261126, + "attempted_groups": 64, + "train_steps": 64, + "lost_groups": 0, + "sampled_sequences": 256, + "nontrivial_advantage_groups": 37, + "sample_accuracy": 0.328125, + "sample_format": 0.484375, + "sample_reward": 0.42499999999999993, + "mean_loss": 0.8641465820837766, + "elapsed_s": 1175.8001729194075 + }, + "durable_eval": { + "accuracy": 0.373046875, + "format": 0.599609375, + "reward": 0.4929687499999971, + "samples": [ + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Brady has:\n\n- 100 pennies = $100\n- 40 nickels = $40\n- 20 dimes = $20\n- 40 dollar bills = $40\n\nSo, total amount is:\n\n$$\n100 + 40 + 20 + 40 = \\boxed{200} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Each 10-foot section of the redwood tree weighs 400 pounds. \nThe redwood is 200 feet tall, so the total weight is:\n\n$$\n\\text{Total weight} = 200 \\text{ feet} \\times 400 \\text{ pounds/foot} = 80,000 \\text{ pounds}\n$$\n\n**Answer:** $\\boxed{80000}$ pounds." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Nancy owes:\n\n- $0.50 cents for each of 8 books: \n $ 8 \\times 0.50 = 4.00 $ cents.\n\n- A flat fee of $2.00 for having at least one book overdue for a week.\n\nSo, the total amount she has to pay is:\n\n$$\n4.00 + 2.00 = \\boxed{6.00} \\text{ cents}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ x $ be the number of apples.\n- Since Andrea has 8 more apples than Jamal, and we are told Andrea has 52 apples, then Jamal has $ x - 8 $ apples.\n\n- Jamal has 4 more bananas than apples. So, the number of bananas Jamal has is $ x - 8 + 4 = x - 4 $.\n\n- Since Andrea has half as many bananas as Jamal, and Andrea has 52 apples, then the number of bananas Andrea has is $ 52 \\times 2 = 104 $.\n\nNow, we know that the number of bananas Andrea has is also equal to the number of bananas Jamal has. So:\n\n$$\nx - 4 = 10" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that **two cups of flour are needed to make a dozen cookies**.\n\n- Today, Carla is making **36 cookies**.\n- Tomorrow, she is making **30 cookies**.\n\n### Step 1: Find how many dozen cookies each cup makes.\n\n$$\n\\frac{2 \\text{ cups}}{12 \\text{ cookies}} = \\frac{1}{6} \\text{ cup per cookie}\n$$\n\n### Step 2: Calculate the total cups needed for today and tomorrow.\n\n- Today: $ 36 \\text{ cookies} \\times \\frac{1}{6} \\text{ cup per cookie} = 6 \\text{ cups} $\n- Tomorrow: $ 30 \\text{ cookies} \\times \\frac" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told there are **9,300 pennies** in a cup. Two-thirds of these are in a stack.\n\n1. Calculate two-thirds of 9,300:\n $$\n \\frac{2}{3} \\times 9,300 = 6,200\n $$\n\n2. The total dollar amount in the stack is the number of pennies in the stack, which is **6,200**.\n\nSo, the final answer is:\n\n$$\n\\boxed{6200}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Maddison starts with:\n- 5 boxes × 50 marbles = **250 marbles**\n\nShe then gets 20 more marbles from her friend.\n\nSo, total marbles now:\n- 250 + 20 = **270 marbles**\n\n**Final answer:** $\\boxed{270}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n1. Let the number of trees in **Chris's** yard be $ C $.\n\n2. Ferdinand has **half** the number of trees that Chris has, so:\n $$\n F = \\frac{1}{2}C\n $$\n\n3. Harry has **5 more than twice** the number of trees that Ferdinand has:\n $$\n H = 2F + 5\n $$\n\n4. Substitute $ F = \\frac{1}{2}C $ into the expression for $ H $:\n $$\n H = 2 \\left( \\frac{1}{2}C \\right) + 5 = C + 5\n $$\n\n5. Now, to find how" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carmen has $100.\n\nSamantha has $25 more than Carmen: \n$$ 100 + 25 = 125 $$\n\nDaisy has $50 more than Samantha: \n$$ 125 + 50 = 175 $$\n\nNow, add all three amounts together: \n$$ 100 + 125 + 175 = \\boxed{395} $$\n\nSo, all three girls have **$395** combined." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "First, calculate the **total price of the house**:\n\n- Selling price: $350,000 \n- Brokerage fee: 5% of $350,000 = $17,500 \n- Transfer fee: 12% of $350,000 = $42,000 \n\n**Total price = 350,000 + 17,500 + 42,000 = 410,500**\n\nNow, subtract Mrs. Cruz's budget of $400,000 from the total price:\n\n$$\n410,500 - 400,000 = 10," + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mr. Tan sold his house for **$400,000**.\n\nHe paid:\n- **3%** of the selling price for transfer fees: \n $ 0.03 \\times 400,000 = 12,000 $\n\n- **5%** of the selling price for a brokerage fee: \n $ 0.05 \\times 400,000 = 20,000 $\n\nSo, the total amount paid for transfer and brokerage is: \n$ 12,000 + 20,000 = 32,000 $\n\nHe also paid **$250,000** for the remaining loan amount.\n\n---\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- It takes **20 minutes** to warm the oil to **300 degrees**.\n- It then takes **40% longer** for the oil to reach **400 degrees**.\n- After warming the oil, it takes **5 minutes less** than the time to warm it.\n\n---\n\n### Step 1: Time to warm to 300 degrees = 20 minutes.\n\nSo, the time to warm to **400 degrees** is:\n\n$$\n40\\% \\text{ longer} = 20 + 0.4 \\times 20 = 20 + 8 = 28 \\text{ minutes}\n$$\n\n---\n\n### Step 2: Time to cook after warming =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The real estate agent spent:\n\n- $5 on each newspaper ad: $5 × 50 = $250 \n- $75 on each television ad: $75 × 15 = $1,125 \n\nTotal cost: \n$250 + $1,125 = **$1,375**\n\n$$\n\\boxed{1375}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- The juggler can juggle **16 balls**.\n- **Half** of the balls are **golf balls**.\n- **Half** of the golf balls are **blue**.\n\n---\n\n### Step 1: Find the number of golf balls\n\nSince half of the 16 balls are golf balls:\n\n$$\n\\frac{1}{2} \\times 16 = 8 \\text{ golf balls}\n$$\n\n---\n\n### Step 2: Find the number of blue golf balls\n\nSince half of the golf balls are blue:\n\n$$\n\\frac{1}{2} \\times 8 = 4 \\text{ blue golf balls}\n$$\n\n---\n\n### ✅ Final Answer:\n\n$$\n\\boxed{4}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "First, let's break down the problem step by step:\n\n- **First bag**: 300 M&Ms \n- **Second bag**: 12 more than the first bag → $ 300 + 12 = 312 $ M&Ms \n- **Third bag**: Half the number of M&Ms in the first bag → $ \\frac{300}{2} = 150 $ M&Ms \n\nNow, add them all together:\n\n$$\n300 + 312 + 150 = \\boxed{762}\n$$\n\nMary got a total of **762 M&Ms**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John has:\n\n- 2 houses \n- Each house has 3 bedrooms, and each bedroom has 2 windows \n- Each house has 4 additional windows not connected to bedrooms \n\n### Step-by-step:\n\n1. **Number of windows in one house**:\n - Bedrooms: 3 × 2 = 6 windows \n - Additional windows: 4 \n - Total per house: 6 + 4 = **10 windows**\n\n2. **Total windows between the houses**:\n - 2 houses × 10 windows = **20 windows**\n\n### Final Answer:\n$$\n\\boxed{20}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The mother buys:\n- Cocoa: $4.20 \n- Laundry: $9.45 \n- Pasta: $1.35 \n\nTotal cost: \n$4.20 + $9.45 + $1.35 = $14.90 \n\nShe pays $20. \n\nChange: \n$20 - $14.90 = **$5.10** \n\n**Answer:** $\\boxed{5.10}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The **body** of the sweater takes **900 stitches**.\n- The **collar** takes **1/10** of the body's stitches.\n- The **rosette** takes **twice as many as the collar**.\n- The **total** stitches of the sweater is **1800**.\n\n---\n\n### Step 1: Find the number of stitches for the collar\n\n$$\n\\text{Collar stitches} = \\frac{1}{10} \\times 900 = 90\n$$\n\n---\n\n### Step 2: Find the number of stitches for the rosette\n\n$$\n\\text{Rossette stitches} = 2 \\times 90 = " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mrs. Rylan bought:\n\n- 20 packets of tomato seeds at $40 each: \n $ 20 \\times 40 = 800 $\n\n- 80 packets of celery seeds at $30 each: \n $ 80 \\times 30 = 2400 $\n\nTotal cost: \n$ 800 + 2400 = \\boxed{3200} $ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Sean has to memorize:\n\n- **2 scenes**, each with **twice the number of lines** in the first scene, but **a third of them** are his lines.\n- **1 solo song**, with **54 lines**, and **four-fifths** of them are his lines.\n\nLet's break it down:\n\n### First Scene:\n- Total lines: $2 \\times 54 = 108$\n- His lines: $\\frac{1}{3} \\times 108 = 36$\n\n### Second Scene:\n- Total lines: $6 + 54 = 60$\n- His lines: $\\frac{4}{5} \\times 60 = 48$\n\n### Total lines Sean has to memorize:\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total cards: 80 \n- $ \\frac{2}{5} $ of the cards had the letter **A** \n- $ \\frac{1}{2} $ of the remaining had the letter **B** \n- $ \\frac{5}{8} $ of the rest had the letter **C** \n- The rest had the letter **D**\n\n---\n\n### Step 1: Find the number of cards with **A**\n\n$$\n\\frac{2}{5} \\times 80 = 32\n$$\n\nSo, 32 cards had **A**.\n\n---\n\n### Step 2: Find the number of cards remaining after **A**\n\n$$\n80 - 32 = 48\n$$\n\nSo" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Matthew digs:\n- 1 small hole in 3 minutes\n- 1 large hole in 10 minutes\n\nSo, for 1 small hole: 3 minutes \nFor 1 large hole: 10 minutes\n\nTo dig 30 small holes: \n$$ 30 \\times 3 = 90 \\text{ minutes} $$\n\nTo dig 15 large holes: \n$$ 15 \\times 10 = 150 \\text{ minutes} $$\n\nTotal time: \n$$ 90 + 150 = 240 \\text{ minutes} $$\n\nConvert minutes to hours: \n$$ 240 \\div 60 = 4 \\text{ hours} $$\n\n**Final Answer:**" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told that the **sum of their current ages is 20**.\n\nIf we are to find the **sum of their ages in 10 years**, we add 10 to their current age.\n\nSo, the answer is:\n\n$$\n\\boxed{30}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the current ages of Ruby and Sam as $ R $ and $ S $, respectively.\n\nWe are told:\n\n1. Ruby is 6 times older than Sam: \n $ R = 6S $\n\n2. In 9 years, Ruby will be 3 times as old as Sam: \n $ R + 9 = 3(S + 9) $\n\nNow solve the system of equations:\n\nFrom the first equation: \n$ R = 6S $\n\nSubstitute into the second equation: \n$ 6S + 9 = 3(S + 9) $\n\nExpand the right-hand side: \n$ 6S + 9 = 3S + 27 $\n\nSubtract $ 3S $ from both sides: \n$ " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Peter purchased:\n\n- 20 popsicles at $0.25 each: \n $ 20 \\times 0.25 = 5 $ dollars.\n\n- 4 ice cream bars at $0.50 each: \n $ 4 \\times 0.50 = 2 $ dollars.\n\nTotal cost: \n$ 5 + 2 = \\boxed{7} $ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A cobra has **70 spots**.\n- A mamba has **twice as many spots** as a cobra: $ 2 \\times 70 = 140 $ spots.\n- There are **40 cobras** and **60 mambas** in the park.\n\n### Step 1: Calculate the total number of spots\n\n$$\n\\text{Total spots} = (40 \\times 70) + (60 \\times 140)\n$$\n\n$$\n= 2800 + 8400 = 11200\n$$\n\n### Step 2: Find half the total number of spots\n\n$$\n\\frac{1}{2} \\times" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Maddy is buying pizza for 12 team members and 3 coaches, and each person brings 2 guests. So the total number of people is:\n\n$$\n12 + 3 + 3 \\times 2 = 12 + 3 + 6 = 21\n$$\n\nEach pizza serves 3 people, so the number of pizzas needed is:\n\n$$\n\\frac{21}{3} = 7\n$$\n\nEach pizza costs $15, so Maddy will spend:\n\n$$\n7 \\times 15 = \\boxed{105} \\text{ dollars}.\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Katerina uses **8 topaz gemstones** per necklace, and each gemstone is **1 inch long**. \nShe uses **1 quarter-inch** (i.e., 0.25 inches) of **sterling silver beads** between each gemstone.\n\nSo, the number of silver beads per necklace is:\n\n$$\n\\frac{25 \\text{ inches}}{1 \\text{ inch per gemstone}} \\times \\frac{1}{0.25} \\text{ silver beads per quarter-inch}\n$$\n\n$$\n= 25 \\times 4 = \\boxed{100}\n$$\n\n**Answer:** $\\boxed{100}$ sterling silver beads per necklace." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Alani wrote 20 stories in the first week.\n\nHer brother Braylen wrote 40 stories in the first week.\n\nHer sister Margot wrote 60 stories in the first week.\n\nIn the second week, each person doubled the number of stories they wrote in the first week.\n\n- Alani: $20 \\times 2 = 40$\n- Braylen: $40 \\times 2 = 80$\n- Margot: $60 \\times 2 = 120$\n\nTotal number of stories written in the second week: \n$$ 40 + 80 + 120 = 240 $$\n\nTotal number of stories written altogether: \n$$ 20 + 40 + 60 +" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ann is 9 years old, and her brother is **twice** her age. \nSo, the brother is: \n$$ 2 \\times 9 = 18 \\text{ years old} $$\n\nIn **3 years**, the brother will be: \n$$ 18 + 3 = 21 \\text{ years old} $$\n\n**Final Answer:** $\\boxed{21}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kelly has:\n\n- 5 quarters = 5 × 25 = **125 cents**\n- 2 dimes = 2 × 10 = **20 cents**\n\nTotal amount she has: \n125 + 20 = **145 cents**\n\nShe buys a can of pop for **55 cents**\n\nSo, she will have: \n145 - 55 = **90 cents**\n\n**Answer:** $\\boxed{90}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- The flag has **3 rows of 8 stars**.\n- It has **2 rows of 6 stars**.\n- The rest of the rows are **5-star rows**.\n\nLet's calculate the total number of rows:\n\n- Rows of 8: 3\n- Rows of 6: 2\n\nSo, the total number of rows is:\n\n$$\n3 + 2 = 5\n$$\n\nTherefore, the number of **5-star rows** is:\n\n$$\n\\boxed{5}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Each flagstone weighs **75 pounds**, and the total weight capacity of the delivery truck is **2000 pounds**.\n\nWe are asked to find how many **trucks** are needed to transport **80 flagstones**.\n\n### Step 1: Calculate the weight of 80 flagstones\n$$\n80 \\text{ flagstones} \\times 75 \\text{ pounds/flagstone} = 6000 \\text{ pounds}\n$$\n\n### Step 2: Determine how many trucks are needed\nEach truck can carry **2000 pounds**.\n\n$$\n\\frac{6000 \\text{ pounds}}{2000 \\text{ pounds/truck}} = 3 \\text{ trucks}\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "The car in the **fast lane** is traveling at **60 mph**, and it traveled **480 miles**.\n\n- Time in the fast lane: \n $$\n \\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{480}{60} = 8 \\text{ hours}\n $$\n\nThe car in the **slow lane** is traveling at **half the speed** of the fast lane, so it is traveling at **30 mph**.\n\n- Time in the slow lane: \n $$\n \\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{480}{30} = 16 \\text{ hours}\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Ali has **22** medals.\n- Izzy has **5 less** than Ali, so she has $ 22 - 5 = 17 $ medals.\n- Together, they have $ 22 + 17 = 39 $ medals.\n\n- The problem states that **they have 10 times less** than the medals that have been given out for counting.\n\nSo, we can write the equation:\n\n$$\n39 = \\frac{1}{10} \\times \\text{Total medals given out}\n$$\n\n$$\n\\text{Total medals given out} = 39 \\times 10 = 390\n$$\n\n### Final Answer:\n$$\n\\boxed{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 4 adults and 8 children = 12 people \n- 8 packets of chocolate bars \n- Each packet contains 5 chocolate bars \n- Each adult gets 6 chocolate bars \n- The rest (i.e., 8 - 4 = 4) are to be shared equally among the children\n\n### Step 1: Total chocolate bars\nEach packet has 5 bars, and there are 8 packets:\n$$\n8 \\times 5 = 40 \\text{ chocolate bars}\n$$\n\n### Step 2: Total chocolate bars given to adults\nEach adult gets 6 bars, and there are 4 adults:\n$$\n4 \\times 6 = 24 \\text{ bars}\n$$\n\n### Step 3:" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Susan works between **8 a.m. and 11 a.m.**, which is a total of **3 hours**. She pauses for **half an hour**, so the total time she works is:\n\n$$\n3 \\text{ hours} - 0.5 \\text{ hour} = 2.5 \\text{ hours}\n$$\n\nShe earns **$5 every 10 minutes**. So, in 2.5 hours, how many 10-minute intervals are there?\n\n$$\n2.5 \\text{ hours} \\times 60 \\text{ minutes/hour} = 150 \\text{ minutes}\n$$\n\n$$\n\\frac{150 \\text{ minutes}}{10 \\text{ minutes}} = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break it down step by step.\n\n---\n\n### Step 1: Points in each round\n\n- **Mike** has **21 points**.\n- **Jim** has **3 points less than Mike**, so:\n $$\n \\text{Jim's points} = 21 - 3 = 18\n $$\n- **Tony** has **2 times more than Mike**, so:\n $$\n \\text{Tony's points} = 2 \\times 21 = 42\n $$\n\n---\n\n### Step 2: Extra points in the fourth round\n\n- Every player gets an extra point **if they have over 20 points**.\n\n- **Mike**: 21 points → **not over 20**, so" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- The **oldest son is 8 years old**.\n- The **youngest son is half as old as the oldest**, so:\n $$\n \\text{Youngest son's age} = \\frac{8}{2} = 4 \\text{ years old}\n $$\n\n- The **total number of oranges** is 15.\n\n- The **sons are washing oranges** as many as their ages. So, the oldest son is washing 8 oranges, and the youngest is washing 4 oranges.\n\n- The **total number of oranges washed** is:\n $$\n 8 + 4 = 12\n $$\n\n- The **oranges left unwashed** is:\n $$\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Day 1:**\n - Pushups: 100\n - Squats: 50\n - Dumbbell presses: 20\n\n- **Day 2:**\n - Pushups: 100 + 20 = 120\n - Squats: 50 - 10 = 40\n - Dumbbell presses: 20 × 2 = 40\n\n- **Total for both days:**\n - Pushups: 100 + 120 = 220\n - Squats: 50 + 40 = 90\n - Dumbbell presses:" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Each person in the household consumes **0.2 kg of rice per meal**. \nThere are **5 members** eating rice every lunch and dinner. \n\nSo, the total rice consumed per week is: \n$$\n5 \\text{ members} \\times 0.2 \\text{ kg/meal} \\times 2 \\text{ meals/week} = 2 \\text{ kg/week}\n$$\n\nNow, we need to find how many weeks a **42 kg bag** will last: \n$$\n\\frac{42 \\text{ kg}}{2 \\text{ kg/week}} = 21 \\text{ weeks}\n$$\n\n**Final Answer:** $\\boxed{21}$ weeks." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Sam's total sales for the week:\n\n- Monday: 0 \n- Tuesday: 15 \n- Wednesday: 12 \n- Thursday: 18 \n- Friday: 0 \n- Saturday: 20 \n\nTotal sales = 0 + 15 + 12 + 18 + 0 + 20 = **75 crates**\n\nSam's target was **120 crates**.\n\nDifference = 120 - 75 = **45 crates**\n\n**Answer:** $\\boxed{45}$ crates." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carmen starts with a bid of **$200**.\n\nEach subsequent bid increases by **$50**, and she **continues bidding** after **3 other people**. So, the total number of bids she makes is:\n\n$$\n200 + 50 \\times (n - 1) = 200 + 50 \\times 3 = 200 + 150 = 350\n$$\n\nShe wins at the **350th bid**, which means the total cost of the desk is:\n\n$$\n200 + 50 \\times 350 = 200 + 17500 = \\boxed{17700} \\text{ dollars" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John drives 30 miles to work and 30 miles back each day. So, per day, he drives **60 miles**.\n\nHe drives **5 days a week** and **50 weeks a year**, so:\n\n$$\n\\text{Total miles per year} = 60 \\, \\text{miles/day} \\times 5 \\, \\text{days/week} \\times 50 \\, \\text{weeks/year} = 15,000 \\, \\text{miles}\n$$\n\nHe is charged **$2 per mile**:\n\n$$\n\\text{Total driving cost} = 15,000 \\, \\text{miles} \\times 2 \\, \\text{\\$/" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Peter wants to exercise for **twice the amount of time he exercised on Monday and Sunday combined**. On **Monday**, he exercised for **16 minutes**, and on **Sunday**, he exercised for **23 minutes**. \n\nSo, the total time he exercised on Monday and Sunday is:\n\n$$\n16 + 23 = 39 \\text{ minutes}\n$$\n\nHe wants to exercise for **twice** that amount:\n\n$$\n2 \\times 39 = 78 \\text{ minutes}\n$$\n\n**Answer:** $\\boxed{78}$ minutes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To solve this problem, we need to understand how the paper is folded and how the pages are arranged.\n\n- A **32-page tabloid** means there are **32 pages**.\n- Each page is printed on **two sides** of the paper.\n- When folded, each page becomes **one side** of the folded paper.\n\nSo, the total number of **pages** is equal to the number of **sheets** of paper used.\n\n- Each sheet of paper can hold **2 pages**.\n- Therefore, the number of sheets is: \n $$\n \\frac{32}{2} = 16\n $$\n\n- Since each sheet is folded, the total number of **pieces of paper** used is: \n $$\n 16" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Annika started with $50.\n\nShe spent half of it on food and snacks: \n$$\n\\frac{1}{2} \\times 50 = 25\n$$\n\nThen she spent an additional $10 for rides: \n$$\n25 + 10 = 35\n$$\n\nSo, the amount left is: \n$$\n50 - 35 = \\boxed{15}\n$$\n\n**Answer:** $\\boxed{15}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Define variables\n\nLet:\n- $ x $ = number of books sold in the **first year**\n- $ y $ = number of books sold in the **current year** (which is the second year)\n\nWe are told:\n- Total books sold = 250\n- $ x + y = 250 $\n- She sold **twice as many books in the first year** as in the second year: $ x = 2y $\n\n---\n\n### Step 2: Solve for $ x $ and $ y $\n\nFrom $ x = 2y $, substitute into $ x + y = 250 $:\n\n$$\n2y + y = 250 \\Rightarrow " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Watson works a **10-hour shift** each day, **5 days a week**, and earns **$10 per hour**. He also earns a **$300 bonus** each week if the company performs well.\n\n### Step 1: Calculate his weekly earnings\n- Hours per week: $10 \\, \\text{hours/day} \\times 5 \\, \\text{days/week} = 50 \\, \\text{hours/week}$\n- Earnings per week: $50 \\, \\text{hours} \\times \\$10/\\text{hour} = \\$500$\n\n### Step 2: Add the bonus\n- Bonus: \\$300\n- Total earnings: \\$500 + \\$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John beats **80%** of 20 people. \nSo, the number of people he **loses to** is:\n\n$$\n20 \\times (1 - 0.80) = 20 \\times 0.20 = 4\n$$\n\n**Answer:** $\\boxed{4}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "The bakery produces 60 loaves of bread each day.\n\n- **Two-thirds** of the loaves are sold in the morning: \n $$\n \\frac{2}{3} \\times 60 = 40 \\text{ loaves}\n $$\n\n- **Half of what is left** is sold in the afternoon and evening. \n So, the remaining loaves after the morning sales are: \n $$\n 60 - 40 = 20 \\text{ loaves}\n $$\n\n- **Half of the remaining loaves** is sold in the afternoon and evening: \n $$\n \\frac{1}{2} \\times 20 = 10 \\text{ loaves}\n $$\n\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Joey loses **8 pounds in 4 weeks**.\n\nSo, in **1 week**, Joey loses:\n\n$$\n\\frac{8 \\text{ pounds}}{4 \\text{ weeks}} = 2 \\text{ pounds/week}\n$$\n\nSandy wants to lose **as much weight as Joey does** in **4 weeks**, so she needs to lose:\n\n$$\n2 \\text{ pounds/week} \\times 4 \\text{ weeks} = 8 \\text{ pounds}\n$$\n\nTherefore, it will take Sandy:\n\n$$\n\\frac{8 \\text{ pounds}}{2 \\text{ pounds/week}} = 4 \\text{ weeks}\n$$\n\n### Final Answer:\n$$\n\\boxed{4} \\text{ weeks}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "The original price of 1 tub of ice cream is $13, and the discount is $0.5 for a packet of milk. \n\n- For 2 tubs of ice cream: \n $2 \\times 13 = 26$ dollars.\n\n- For 4 packets of milk: \n $4 \\times (13 - 0.5) = 4 \\times 12.5 = 50$ dollars.\n\nThe total amount saved is: \n$26 - 50 = -24$ dollars.\n\nSo, you **do not save** money if you buy 2 tubs of ice cream and 4 packets of milk." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Helena's serum causes a person to grow an extra arm every 3 days and an extra leg every 5 days. After 15 days, we need to calculate how many arms and legs are added.\n\n- Number of arms added: \n $ \\frac{15}{3} = 5 $ arms\n\n- Number of legs added: \n $ \\frac{15}{5} = 3 $ legs\n\nTotal new limbs: \n$ 5 + 3 = \\boxed{8} $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n1. **Cost of business suits**:\n - 6 suits at $100 each: \n $ 6 \\times 100 = 600 $\n\n2. **Cost of suitcases**:\n - 3 suitcases at $50 each: \n $ 3 \\times 50 = 150 $\n\n3. **Cost of flight ticket**:\n - The flight ticket costs $700 more than 5 times the cost of a business suit. \n $ 5 \\times 100 = 500 $, so the flight ticket is: \n $ 500 + 700 = 1200 $\n\n4" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break it down step by step:\n\n- The family has **5 people**.\n- **3 people** eat **3 eggs each day**.\n- The remaining **2 people** eat **2 eggs each day**.\n- Each day, the total number of eggs consumed is:\n $$\n (3 \\times 3) + (2 \\times 2) = 9 + 4 = 13 \\text{ eggs}\n $$\n- In a week (7 days), the total number of eggs consumed is:\n $$\n 13 \\times 7 = 91 \\text{ eggs}\n $$\n\n**Final Answer:**\n$$\n\\boxed{91}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Quinn is 30 years old.\n- Jane is 3 years younger than Quinn.\n- Trent is 5 years older than Jane.\n\n### Step 1: Find Jane's age\nJane is 3 years younger than Quinn:\n$$\n\\text{Jane} = 30 - 3 = 27\n$$\n\n### Step 2: Find Trent's age\nTrent is 5 years older than Jane:\n$$\n\\text{Trent} = 27 + 5 = 32\n$$\n\n### Final Answer:\n$$\n\\boxed{32}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Define variables\n\nLet:\n\n- $ C $ = Cera's current age = 46 years\n- $ N $ = Noah's current age\n- $ P $ = Population of Chile now\n\nWe are told:\n\n- Six years ago, Noah was **half as old** as Cera.\n- Six years ago, the population of Chile was **half what it is now**.\n- Six years ago, the population of Chile was **3000 times the age of Noah**.\n\n---\n\n### Step 2: Use the information about age\n\n#### Six years ago:\n\n- Noah was $ N - 6 $ years old\n- Cera was $ C - 6 = 46 - " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the number of players on the **defense** be $ x $.\n\n- The number of players on the **offense** is **twice** the number on the defense: $ 2x $.\n- The number of players on the **special teams** is **half** the number on the defense: $ \\frac{x}{2} $.\n\nWe are told that the total number of players is 105:\n\n$$\n\\text{Offense} + \\text{Defense} + \\text{Special Teams} = 105\n$$\n\n$$\n2x + x + \\frac{x}{2} = 105\n$$\n\n$$\n\\frac{4x + 2x + x}{2} = 105\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Martha invited:\n\n- 2 families with 6 people: $2 \\times 6 = 12$ people \n- 3 families with 4 people: $3 \\times 4 = 12$ people \n- Total invited people: $12 + 12 = 24$\n\n8 people couldn't come due to illness.\n\n1/4 of the 8 people had previous commitments, so 2 people had commitments.\n\nSo, the number of people who **show up** is:\n\n$$\n24 - 8 - 2 = 14\n$$\n\n**Answer:** $\\boxed{14}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Solomon bought 20 marbles from Johanna and added them to a store that had 50 marbles. His father gave him $ \\frac{2}{5} $ times as many marbles as he bought from Johanna, which is:\n\n$$\n\\frac{2}{5} \\times 20 = 8 \\text{ marbles}\n$$\n\nSo, the total number of marbles Solomon has is:\n\n$$\n20 + 50 + 8 = 78 \\text{ marbles}\n$$\n\nEach marble weighs $ 2k $ kg, so the total weight is:\n\n$$\n78 \\times 2k = 156k \\text{ kg}\n$$\n\n**Final Answer:** $\\boxed{15" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "First, calculate the volume of the pool:\n\n$$\n\\text{Volume} = \\text{length} \\times \\text{width} \\times \\text{depth} = 6 \\, \\text{ft} \\times 4 \\, \\text{ft} \\times 5 \\, \\text{ft} = 120 \\, \\text{cubic feet}\n$$\n\nThen, multiply by the cost per cubic foot:\n\n$$\n\\text{Cost} = 120 \\, \\text{cubic feet} \\times 0.1 \\, \\text{\\$/cubic foot} = 12 \\, \\text{\\$}\n$$\n\n**Final Answer:** $\\boxed{12}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **3 times as many girls as boys**.\n- There are **1/10 as many non-gendered children as boys**.\n- There are **30 boys**.\n\nLet’s define:\n\n- Let $ B $ = number of boys = 30\n- Let $ G $ = number of girls = 3 × $ B $ = 90\n- Let $ N $ = number of non-gendered children = $ \\frac{1}{10} \\times B $ = $ \\frac{1}{10} \\times 30 = 3 $\n\nNow, the total number of children is:\n\n$$\n\\text{Total children} = \\text{Boys} + \\text{Girls}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The ratio of electric poles to electric wires is **1:3**.\n- The total number of electric wires is **45**.\n\nWe need to find the **total number of electric poles**.\n\n### Step 1: Use the ratio\nThe ratio is **1:3**, meaning for every **3 wires**, there are **1 pole**.\n\nSo, for every 3 wires, there is 1 pole.\n\n### Step 2: Find how many poles correspond to 45 wires\nWe can write this as:\n\n$$\n\\frac{1 \\text{ pole}}{3 \\text{ wires}} = \\frac{1}{3}\n$$\n\nSo, to find the number of poles for 45 wires:\n\n$$\n\\frac{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "At the beginning of the party, there were:\n\n- **25 men** \n- **15 women**\n\nAfter an hour, **1/4 of the total number of people left**.\n\nSo, the total number of people at the party at the end of the hour is:\n\n$$\n\\frac{1}{4} \\times (25 + 15) = \\frac{1}{4} \\times 40 = 10\n$$\n\nThis means **10 people** left the party.\n\nNow, **22 men stayed at the party**, so the number of women who stayed is:\n\n$$\n15 - 22 = -7\n$$\n\nSince the number of women cannot be negative, this suggests that **22 men stayed**," + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- The book costs **$4**.\n- A magazine costs **half as much as a book**, so:\n $$\n \\text{Magazine cost} = \\frac{1}{2} \\times 4 = 2 \\text{ dollars}\n $$\n- A pen costs **$1 less than a magazine**, so:\n $$\n \\text{Pen cost} = 2 - 1 = 1 \\text{ dollar}\n $$\n\n### Final Answer:\n$$\n\\boxed{1}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jam has:\n\n- 3 boxes of pencils \n- 2 loose pencils\n\nSo, total pencils = $ 3 \\times 1 + 2 = 5 $ boxes.\n\nMeg has 46 pencils.\n\nNow, we need to store all of Meg's pencils in boxes. Since each box can hold 1 pencil, we need **46 boxes**.\n\n**Final answer:** $\\boxed{46}$ boxes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Each ice cube cools the coffee by **13 degrees**.\n- Each ice cube **weakened** the coffee by **12 milliliters**.\n- Shannon adds **15 milliliters** of cream.\n\nWe are to find how many **milliliters weaker** Shannon’s iced coffee is **when it is cooled by 65 degrees**.\n\n---\n\n### Step-by-step:\n\n1. **Cooling by 65 degrees**:\n - Each ice cube cools the coffee by **13 degrees**.\n - So, the number of ice cubes used is:\n $$\n \\frac{65}{13} = 5 \\text{ ice cubes}\n $$\n\n2. **Weakening due to" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the number of old records that the 5 people brought in as $ x $.\n\nEach person trades 2 old records for 1 new record. So, if 5 people trade their old records, they will exchange:\n\n$$\n5 \\times 2 = 10 \\text{ old records}\n$$\n\nEach new record is worth 1 old record, so the 10 old records will be exchanged for 10 new records.\n\nBut the problem says that the 5 people leave with 7 new records. So, the total number of new records they have is 7.\n\nThis means that the 10 old records they brought in were all traded for 10 new records, and they only have 7 left. So, the 5 people" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n---\n\n### Step 1: Define variables\n\nLet:\n- $ J $ = number of **Junior programmers**\n- $ S $ = number of **Senior programmers**\n\nWe are told:\n- $ J = \\frac{2}{5} \\times \\text{Total employees} $\n- Total employees = 100\n\nSo:\n- $ J = \\frac{2}{5} \\times 100 = 40 $\n- $ S = 100 - J = 60 $\n\n---\n\n### Step 2: Calculate the total monthly salary\n\n- Each **Junior programmer** is paid $2000\n- Each **Senior programmer** is paid $400 more than a junior programmer\n\nSo:\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Let $ x $ be the number of people who got on the bus at the **terminal**.\n\n- At the **first** stop: 5 more people got in → total people now is $ x + 5 $.\n\n- At the **second** stop: 7 people got down and 8 more got in → total people now is $ x + 5 - 7 + 8 = x + 6 $.\n\n- At the **third** stop: 20 people are heading to the stop → total people now is $ x + 6 + 20 = x + 26 $.\n\nBut we are told that **at the third stop**, there were 20 people heading to the third stop." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Start with 24 lollipops.**\n- **Eats 2 lollipops on his way to school:** \n $ 24 - 2 = 22 $\n- **Passes 14 lollipops to his friends:** \n $ 22 - 14 = 8 $\n- **Buys twice as many lollipops on his way home as he passed:** \n $ 2 \\times 14 = 28 $\n- **Eats 3 more lollipops that night:** \n $ 8 - 3 = 5 $\n- **Eats 2 more in the morning:** \n $ 5 - " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "The phone recharges at a rate of **1 percentage-point per 3 minutes**.\n\nWe are told the phone is at **60% charged**, and we want to know how long it will take to **fully charge** (to 100%).\n\n### Step 1: Calculate the number of percentage-points needed to charge the phone\n\n- From 60% to 100% = **40 percentage-points**\n\n### Step 2: Convert percentage points to minutes\n\n- 1 percentage-point = 3 minutes \n- So, 40 percentage-points = $ 40 \\times 3 = 120 $ minutes\n\n### Step 3: Convert minutes to hours\n\n- 1 hour = 60 minutes \n- So, 1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Erin starts with 7 lollipops. \nHer mother gives her another 10 lollipops, so she now has:\n\n$$\n7 + 10 = 17 \\text{ lollipops}\n$$\n\nThen, Erin gives 3 of her lollipops to Ella:\n\n$$\n17 - 3 = 14 \\text{ lollipops}\n$$\n\n**Final answer:** $\\boxed{14}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The customer spent **$80** on their first shopping trip.\n- They used their **$1 off every $20** reward.\n- On the second trip, they spent **$43**, used the rewards, and applied a **coupon that took twice the amount of rewards off the price**.\n\n---\n\n### Step 1: Calculate the rewards for the first trip\n\n- $20 worth of purchase = $1 reward\n- So, for every $20 spent, they get $1 off.\n\n$$\n\\text{Rewards} = \\frac{80}{20} = 4\n$$\n\nSo, they had **$4** worth of rewards.\n\n---\n\n### Step 2: Apply the coupon on the second trip\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Nick is choosing between two jobs:\n\n- **Job A**: \n - Hourly wage: $15 \n - Annual hours: 2000 \n - Total tax: 20% \n - Net pay: $15 × 2000 - 0.20 × $15 × 2000 = $30,000 - $6,000 = **$24,000**\n\n- **Job B**: \n - Annual salary: $42,000 \n - Property tax: $6,000 \n - Net income after property tax: $42,000 - $6,000 = $36,000" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 220 castles in Scotland.\n\n- 40% of them are ruins: \n $ 220 \\times 0.40 = 88 $ castles are ruins.\n\n- Half of the ruined castles are unmanned: \n $ 88 \\div 2 = 44 $ castles are unmanned.\n\n**Final Answer:** $\\boxed{44}$ unmanned ruined castles." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find the cost difference between the two offers, we calculate the total cost for each and subtract them.\n\n- **Furniture United**:\n - $1,350 (advance payment) + 6 × $350 (installments) = $1,350 + $2,100 = **$3,450**\n\n- **Cozy Homes**:\n - $1,100 (advance payment) + 9 × $250 (installments) = $1,100 + $2,250 = **$3,350**\n\nNow, subtract the total cost of the cheaper offer from the more expensive one:\n\n$$\n\\$3,450 - \\$3,350" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- DJ has **8** guns \n- Nick has **10** guns \n- RJ has **1** gun \n- Richard has **5** guns \n\nThey want to **share their guns equally**.\n\nTo find out how many guns each person would have, we add up all the guns and divide by 4 (since there are 4 people):\n\n$$\n\\text{Total guns} = 8 + 10 + 1 + 5 = 24\n$$\n\n$$\n\\text{Guns per person} = \\frac{24}{4} = 6\n$$\n\n### Final Answer:\n$$\n\\boxed{6}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mason needs:\n\n- 30 ounces of sugar for 1 batch of suckers \n- 70 ounces of sugar for 1 batch of fudge\n\nTo find the total sugar needed for 8 batches of suckers and 1 batch of fudge:\n\n- For suckers: $ 8 \\times 30 = 240 $ ounces \n- For fudge: $ 1 \\times 70 = 70 $ ounces \n\nTotal sugar needed: \n$$ 240 + 70 = \\boxed{310} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Maria buys 8 shares of a stock for $8 each. \n- First year: The stock price increases by 50%, so the new price is $8 × 1.50 = $12. \n- Second year: The stock price decreases by 25%, so the new price is $12 × 0.75 = $9. \n\nNow, the total value of Maria's shares is: \n$$\n8 \\text{ shares} \\times 9 = 72\n$$\n\n**Final value of all Maria's shares:** $\\boxed{72}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Luke ate **2** hot dogs.\n\nThomas ate **3 times more** than Luke, so:\n\n$$\n3 \\times 2 = 6 \\text{ hot dogs}\n$$\n\nJohn ate **half** the amount Thomas ate:\n\n$$\n\\frac{6}{2} = 3 \\text{ hot dogs}\n$$\n\nNow, to find how many more hot dogs John ate than Luke:\n\n$$\n3 - 2 = 1\n$$\n\n**Answer:** $\\boxed{1}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the number of students in the smallest group be $ x $. Then:\n\n- The two equal groups have $ x + 10 $ students each.\n- The largest group has $ x + 10 + 10 = x + 20 $ students.\n\nWe know the total number of students is 200:\n\n$$\n(x + 10) + (x + 10) + (x + 20) = 200\n$$\n\nSimplify:\n\n$$\n3x + 40 = 200\n$$\n\n$$\n3x = 160\n$$\n\n$$\nx = \\frac{160}{3} \\approx 53.33\n$$\n\nThis is not an integer" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Farmer Brown has 60 animals, and he has **twice as many chickens as cows**.\n\nLet:\n- $ c $ = number of cows\n- $ h $ = number of chickens\n\nWe are told:\n- $ c + h = 60 $\n- $ h = 2c $\n\nSubstitute $ h = 2c $ into the first equation:\n$$\nc + 2c = 60 \\Rightarrow 3c = 60 \\Rightarrow c = 20\n$$\n\nSo:\n- $ c = 20 $ cows\n- $ h = 2 \\times 20 = 40 $ chickens\n\nNow, calculate the total number of legs:\n- Cows: $ 20 \\times 4 =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Josh starts with 3 balls and adds 1 ball each week. After 4 weeks, he has:\n\n$$\n3 + 4 = 7 \\text{ balls}\n$$\n\nBut he slips and drops 3 balls. Of those, 2 are caught by people and 1 is lost. So the number of balls he is juggling is:\n\n$$\n7 - 3 = 4\n$$\n\n**Final Answer:** $\\boxed{4}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A pink frog = a blue beetle = a green toad = 10 pounds less than a yellow snake \n- A pink frog = 20 pounds more than a red bird \n- The pink frog weighs **50 pounds** \n- The container carrying one of each animal weighs **20 pounds**\n\n---\n\n### Step 1: Find the weight of the yellow snake\n\nLet the weight of the yellow snake be $ S $.\n\nFrom the information:\n\n- Pink frog = yellow snake - 10 \n $ 50 = S - 10 $ \n $ S = 60 $ pounds\n\n---\n\n### Step 2: Find the weight of the red bird\n\nFrom the information:\n\n- Pink frog = red bird + 20" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Laurel's friend gave her **24** baby outfits. \nAt her baby shower, Laurel received **twice** that amount: \n$$ 2 \\times 24 = 48 $$\n\nThen, her mom gifted her **15** baby outfits. \nSo, the total number of outfits Laurel has is: \n$$ 48 + 15 = \\boxed{63} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tyson currently runs **5000 meters** every day. His coach wants him to run **1/5 times more** meters per day. \n\nTo find the new daily distance:\n\n$$\n\\text{New daily distance} = 5000 \\times \\left(1 + \\frac{1}{5}\\right) = 5000 \\times \\frac{6}{5} = 6000 \\text{ meters}\n$$\n\nNow, he trains for **a month**. Assuming a month has **30 days**, the total distance he runs in June is:\n\n$$\n6000 \\times 30 = 180,000 \\text{ meters}\n$$\n\n### Final Answer:\n$$\n\\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Juice Box A = $4 \n- Juice Box B = $4 + $5 = $9 \n- Juice Box C = $4 + $7 = $11 \n\nNow, find how much more Juice Box C is than Juice Box B: \n$$\n11 - 9 = 2\n$$\n\n**Final Answer:** $\\boxed{2}$ dollars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 40 tables with 4 legs \n- 50 tables with 3 legs \n\nWe can calculate the total number of legs as:\n\n$$\n(40 \\times 4) + (50 \\times 3) = 160 + 150 = \\boxed{310}\n$$\n\n**Answer:** $\\boxed{310}$ legs." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jenny buys 1 bag of cookies a week, which contains 36 cookies. She puts 4 cookies in her son's lunch box 5 days a week. Her husband eats 1 cookie a day for 7 days.\n\n### Step 1: Calculate the number of cookies used by the son and the husband\n- **Son's cookies per week**: $ 4 \\text{ cookies/day} \\times 5 \\text{ days} = 20 \\text{ cookies} $\n- **Husband's cookies per week**: $ 1 \\text{ cookie/day} \\times 7 \\text{ days} = 7 \\text{ cookies} $\n\n### Step 2: Total cookies used by the son and the husband\n$$\n20 + 7" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Davos bought 2 shirts at $30 each, and there is a 40% discount.\n\n1. The cost of one shirt is $30.\n2. With a 40% discount, the price of one shirt becomes:\n $$\n 30 \\times (1 - 0.40) = 30 \\times 0.60 = 18\n $$\n3. For 2 shirts:\n $$\n 18 \\times 2 = 36\n $$\n\nSo, Davos paid **$36** for the 2 shirts. \n\n$$\n\\boxed{36}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The factory used to make tractors and sell 10 tractors a day for $100 each. Now, they sell 5 silos a day for $220 each.\n\n### Step 1: Find the difference in price per day\n$$\n\\text{Difference} = 220 - 100 = 120\n$$\n\n### Step 2: Find the percentage increase\n$$\n\\text{Percentage increase} = \\left( \\frac{120}{100} \\right) \\times 100 = 120\\%\n$$\n\n### Final Answer:\n$$\n\\boxed{120\\%}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Madeline buys food, treats, and medicine for her dog every month. \n- Food: $25 per week \n- Treats: $20 per month \n- Medicine: $100 per month \n\nThere are **4 weeks in a month**, so: \n- Food cost: $25 × 4 = **$100** \n- Treats cost: $20 × 12 = **$240** \n- Medicine cost: $100 × 12 = **$1200**\n\nTotal cost per year: \n$100 + $240 + $1200 = **$1340**\n\n**Answer:** $\\boxed{1340}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break down the problem step by step:\n\n- **Yoga class on Monday**: 1 hour \n- **Cooking class on Tuesday**: 3 times longer than Monday’s yoga = $3 \\times 1 = 3$ hours \n- **Cheese-tasting event on Wednesday**: 0.5 hour \n- **Museum tour on Thursday**: Half as long as the cooking class on Tuesday = $0.5 \\times 3 = 1.5$ hours \n- **Errands on Friday**: 2 hours \n\nNow, add all these times together:\n\n$$\n1 + 3 + 0.5 + 1.5 + 2 = 8 \\text{ hours}\n$$\n\n### Final Answer:\n$$\n\\boxed{8}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "April had already bought **100 plant pots** from the garden center.\n\nShe needs:\n\n- 30 plant pots for daisies \n- Twice as many for roses = 60 plant pots\n\nSo, total pots needed = 30 + 60 = **90 pots**\n\nApril has **100 pots** to start with.\n\n**Leftover pots = 100 - 90 = 10**\n\n**Answer:** $\\boxed{10}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's solve the problem step by step:\n\n- Andrea had **$36** in the beginning.\n- She spent the **rest** of her money on an **$11 sweater**.\n- She gave **$4** to her brother.\n\nSo, the amount she spent on the sweater is:\n\n$$\n36 - 11 = 25\n$$\n\nThen, she gave $4 to her brother, so the total amount she spent is:\n\n$$\n25 + 4 = 29\n$$\n\nTherefore, the amount she saved is:\n\n$$\n36 - 29 = \\boxed{7}\n$$\n\n**Answer:** $\\boxed{7}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John spends:\n\n- 6 hours boating \n- Half that time swimming: $ \\frac{6}{2} = 3 $ hours \n- 3 shows, each 2 hours: $ 3 \\times 2 = 6 $ hours \n\nTotal time spent: \n$ 6 + 3 + 6 = 15 $ hours\n\nHe spends **30%** of his time on activities. \nSo, the time he spent sightseeing is: \n$ 15 \\times 0.3 = 4.5 $ hours\n\n**Answer:** $ \\boxed{4.5} $ hours." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Annabelle already has $80 in her savings. She earns:\n\n- $10 per hour for 20 hours: $10 × 20 = $200\n- $5 per hour for 15 hours: $5 × 15 = $75\n\nTotal earnings: $200 + $75 = $275\n\nShe needs: $400 - $80 = $320\n\n**Answer:** $\\boxed{320}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The **shortest tree** has a height of **6 feet**.\n- The **second tree** has a height of **5 feet more** than the shortest tree: \n $ 6 + 5 = 11 $ feet.\n- The **tallest tree** has a height that is **twice** the **sum** of the heights of the two shortest and second trees.\n\nLet’s calculate the **sum** of the two shortest trees:\n\n$$\n6 + 11 = 17 \\text{ feet}\n$$\n\nThen, the **tallest tree** has a height that is **twice** this sum:\n\n$$\n2 \\times 17 = 34 \\text{ feet}\n$$\n\n### ✅ Final" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Dean's original amount is $28.\n\nHe bought:\n- 6 toy cars at $2 each: $6 × $2 = $12 \n- 5 teddy bears at $1 each: $5 × $1 = $5\n\nTotal spent: $12 + $5 = $17\n\nHis mother gives him an extra $10.\n\nTotal money left: $28 - $17 + $10 = $11\n\n**Final Answer:** $\\boxed{11}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Morgan's dad said she has $90 for her birthday party. Here's the breakdown:\n\n- Mini-golf: $5 per round\n- Arcade tokens: $5\n- Go-karts: $10 per ride\n\nShe wants to play **1 round of mini-golf**, **1 game of arcade tokens**, and **2 rides of go-karts**.\n\nLet's calculate the total cost:\n\n- Mini-golf: $5 × 1 = $5 \n- Arcade tokens: $5 × 1 = $5 \n- Go-karts: $10 × 2 = $20\n\nTotal cost = $5 + $5 + $20 = **$30**\n\nMorgan has $90, so she can invite:\n\n$$\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Marisa gets $5 every day from her parents. She buys 4 lollipops worth 25 cents each, so:\n\n- Each lollipop costs **25 cents**.\n- She buys **4 lollipops** per day: \n $ 4 \\times 25 = 100 \\text{ cents} $.\n\n- She saves the **change** from the lollipops. \n So, she saves **100 cents** per day.\n\n- She saves for **5 days**. \n So, she saves: \n $ 100 \\text{ cents/day} \\times 5 = 500 \\text{ cents} $.\n\nConvert cents to dollars: \n$ 500 \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Billy buys candy for $10, and the candy costs $1.5 per pound. He spends half of his change on gumballs, which cost $0.05 each, and buys 40 gumballs.\n\n### Step 1: Find the total cost of candy\nLet $ x $ be the number of pounds of candy Billy buys.\n\nCost of candy: $ 1.5x $\n\nBilly gives $10, so his change is $ 10 - 1.5x $.\n\nHe takes half of his change and spends it on gumballs:\n- Cost of gumballs: $ 0.05 \\times 40 = 2 $\n\nSo, the amount he spent on gumballs is $ 2 $, which" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the son's current age be $ x $.\n\nCarver is 45 years old, so he is 5 years less than twice the age of his son:\n\n$$\n45 = 2x - 5\n$$\n\nSolve for $ x $:\n\n$$\n2x = 45 + 5 = 50\n$$\n\n$$\nx = \\frac{50}{2} = 25\n$$\n\n### Final Answer:\n$$\n\\boxed{25}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step.\n\n---\n\n### **Step 1: Understand the distances**\n\n- From the first to the second city: **75 miles**\n- From the second to the third city: **100 miles**\n- From the third to the first city: **50 miles less than the combined distance to the second and third cities**\n\nSo, the distance from the third to the first city is:\n\n$$\n100 + 75 = 175 \\quad \\text{miles}\n$$\n\nTherefore, the distance from the third to the first city is:\n\n$$\n175 - 50 = 125 \\quad \\text{miles}\n$$\n\n---\n\n### **Step 2: Total distance of the" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark makes:\n\n- A Rottweiler bed: 8 pounds \n- A chihuahua bed: 2 pounds \n- A collie bed: average of Rottweiler and chihuahua = (8 + 2) / 2 = 5 pounds\n\nSo, for **1 collie bed**, Mark needs **5 pounds** of stuffing.\n\nNow, he needs:\n\n- 4 chihuahua beds: 4 × 2 = 8 pounds \n- 3 collie beds: 3 × 5 = 15 pounds\n\nTotal stuffing needed = 8 + 15 = **23 pounds**\n\n$$\n\\boxed{23}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John's total trip consists of:\n\n- **Going to his friend's house**: 200 miles at 70 mph \n- **Taking a detour**: 10 miles \n- **Going back home**: 240 miles at 80 mph\n\n### Step 1: Time to go to friend's house\n\n$$\n\\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{200}{70} \\approx 2.857 \\text{ hours}\n$$\n\n### Step 2: Time to go back home\n\n$$\n\\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{240}{80} = 3" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "There are 96 fourth-grade students at Small Tree School. \n43 of them are girls, and 54 are boys (since 96 - 43 = 53, but the problem says 54 boys). \nOn Friday, 5 girls and 4 boys were absent. \n\nSo, the number of boys at school on Friday is: \n**54 - 4 = 50**. \n\n**Answer:** $\\boxed{50}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 6 girls in the park.\n\nIf there are **twice** the number of boys, then the number of boys is:\n\n$$\n2 \\times 6 = 12\n$$\n\nSo, the total number of kids in the park is:\n\n$$\n6 + 12 = \\boxed{18}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jane needs a total of **at least 42 points** from **3 tests**. She has already taken **2 tests** with scores of **15** and **18**. Let the score on the third test be $ x $.\n\nSo, the total score is:\n\n$$\n15 + 18 + x \\geq 42\n$$\n\n$$\n33 + x \\geq 42\n$$\n\n$$\nx \\geq 9\n$$\n\nThus, the minimum number of points Jane must score on the third test is:\n\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the number of people kicked out for **refusing to wear masks** be $ x $. \nThen, the number of people kicked out for **shoplifting** is $ 4x - 5 $.\n\nNext, the number of people kicked out for **physical violence over goods on sale** is $ 3 \\times (4x - 5) $.\n\nWe are told that the total number of people kicked out is 50. So:\n\n$$\nx + (4x - 5) + 3(4x - 5) = 50\n$$\n\nSimplify:\n\n$$\nx + 4x - 5 + 12x - 15 = 50\n$$\n$$\n17x - 20 =" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let’s define the variables:\n\n- Let $ E $ be the number of points Erin had before.\n- Sara scored 8 points.\n- After scoring 14 points, Erin has three times more points than Sara.\n\nSo, Erin’s total points after scoring 14 is:\n\n$$\n3 \\times 8 = 24\n$$\n\nThis means Erin had 24 points after scoring 14, and she had $ E $ points before. So:\n\n$$\nE + 14 = 24\n$$\n\n$$\nE = 24 - 14 = 10\n$$\n\n### Final Answer:\n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- **44 seniors** need to receive awards.\n- **Each senior receives a picture frame** that costs **$20**.\n- **Each picture frame needs to be etched with a logo** for an additional **20%** cost.\n- **2 seniors** will also receive **pins** that cost **$5**.\n- **1/4 of the seniors** are officers and they will need to receive **cords** that cost **$12** each.\n\n---\n\n### Step 1: Calculate the cost of picture frames\n\n- Each picture frame costs **$20**.\n- 44 seniors, each gets 1 frame:\n $$\n 44 \\times 20 = 880" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break it down step by step:\n\n- The **original cost** of the hand-painted wallpaper is **$400**.\n- The **DIY version saves 20%** of the original cost.\n- So, the **discount amount** is:\n $$\n 20\\% \\times 400 = 0.20 \\times 400 = 80\n $$\n- Therefore, the **new cost** (after discount) is:\n $$\n 400 - 80 = 320\n $$\n\n### Final Answer:\n$$\n\\boxed{320}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Friday**: 14 pairs sold.\n- **Saturday**: Double the number of shoes sold on Friday: \n $ 2 \\times 14 = 28 $ pairs.\n- **Sunday**: One-half the amount sold on Saturday, but **6 people returned** their shoes. \n So, the number of shoes sold on Sunday is: \n $ \\frac{1}{2} \\times 28 = 14 $ pairs. \n However, 6 people returned, so the actual number of shoes sold on Sunday is: \n $ 14 - 6 = 8 $ pairs.\n\n- **Total shoes sold by the end of the sale**: \n $ 14 +" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Hallie had dance practice:\n\n- On **Tuesday**: 1 hour \n- On **Thursday**: 2 hours \n- On **Saturday**: 2 times as long as Tuesday's, so **2 × 1 = 2 hours**\n\nNow, add up the hours:\n\n$$\n1 + 2 + 2 = 5 \\text{ hours}\n$$\n\n**Answer:** $\\boxed{5}$ hours a week." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- The total value of the equipment is **$400,000**.\n- 40% of this amount is **faulty equipment**.\n- The remaining 60% is **functioning equipment**.\n\n### Step 1: Calculate the value of faulty equipment\n$$\n40\\% \\text{ of } 400,000 = 0.40 \\times 400,000 = 160,000\n$$\n\n### Step 2: Calculate the value of functioning equipment\n$$\n60\\% \\text{ of } 400,000 = 0.60 \\times 400" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mary has **30 sheep**. She gets:\n\n- **1 kg of milk** from **half** of them every day.\n- **2 kg of milk** from the **other half** every day.\n\nSo, the total milk per day is:\n\n$$\n\\frac{1}{2} \\times 1 \\, \\text{kg} + \\frac{1}{2} \\times 2 \\, \\text{kg} = 0.5 + 1 = 1.5 \\, \\text{kg}\n$$\n\n**Answer:** $\\boxed{1.5}$ kg of milk per day." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mrs. Sherman made **12 bread rolls** for breakfast.\n\n- She fed **6 children** with **1 roll each**, so she fed **6 rolls** to the children.\n- The remaining **6 rolls** were broken into **8 pieces** each, so she fed **6 × 8 = 48 pieces** to the chickens.\n\n**Answer:** $\\boxed{48}$ pieces of rolls." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 40 pupils in the class.\n\n- Half like blue: $ \\frac{1}{2} \\times 40 = 20 $ pupils like blue.\n- One-fourth of the remaining (after subtracting blue) like green: \n $ \\frac{1}{4} \\times (40 - 20) = \\frac{1}{4} \\times 20 = 5 $ pupils like green.\n- The rest like yellow: \n $ 40 - 20 - 5 = 15 $ pupils like yellow.\n\n**Answer:** $ \\boxed{15} $ pupils like yellow." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Lucy sold all the apples on Monday, and she got $56 from that. Since she sold apples at $4 per piece, the number of apples she picked on Monday is:\n\n$$\n\\frac{56}{4} = 14 \\text{ apples}\n$$\n\nOn Tuesday, she picked 12 apples.\n\nOn Wednesday, she picked double the number of apples she picked on Tuesday:\n\n$$\n12 \\times 2 = 24 \\text{ apples}\n$$\n\nSo, the total number of apples she picked over the three days is:\n\n$$\n14 + 12 + 24 = \\boxed{50} \\text{ apples}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Lindsay has 50 socks in total. She washed 10 pairs of socks and 15 loose socks.\n\n- 1 pair = 2 socks, so 10 pairs = $10 \\times 2 = 20$ socks.\n- 15 loose socks = 15 socks.\n\nSo, the total socks she washed is $20 + 15 = 35$ socks.\n\nSince she has 50 socks in total, the number of socks Lindsay missed is:\n\n$$\n50 - 35 = \\boxed{15}\n$$\n\n**Answer:** $\\boxed{15}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Rachel initially had 23 cookies. Janet gave her 42 more. So, the total number of cookies Rachel had is:\n\n$$\n23 + 42 = 65\n$$\n\nHer brother ate 44 of those cookies. So, the number of cookies left for Rachel is:\n\n$$\n65 - 44 = 21\n$$\n\n**Answer:** $\\boxed{21}$ cookies." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Karan borrowed $3,650 for 5 months at an interest rate of 10%. She has to pay an equal amount every month.\n\n### Step 1: Understand the problem\nThis is a **simple interest** problem. The formula for simple interest is:\n\n$$\nI = P \\times r \\times t\n$$\n\nWhere:\n- $ P = 3650 $ (principal amount),\n- $ r = 0.10 $ (annual interest rate),\n- $ t = 5 $ months.\n\n### Step 2: Calculate the interest\n$$\nI = 3650 \\times 0.10 \\times 5 = 1825\n$$\n\n### Step 3: Calculate the monthly payment\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Chloe hiked for 5 hours at 9 km/h, so she hiked:\n\n$$\n9 \\times 5 = 45 \\text{ km}\n$$\n\nChloe hiked for 8 hours at 14 km/h, so she hiked:\n\n$$\n14 \\times 8 = 112 \\text{ km}\n$$\n\nThe difference in distance is:\n\n$$\n112 - 45 = 67 \\text{ km}\n$$\n\n**Answer:** $\\boxed{67}$ kilometers." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Axel has:\n- 50 silver pesos \n- 80 gold pesos\n\nAnna has:\n- Twice as many silver pesos as Axel: $ 2 \\times 50 = 100 $ silver pesos \n- 40 more gold pesos than Axel: $ 80 + 40 = 120 $ gold pesos\n\nTotal pesos together:\n- Silver: $ 50 + 100 = 150 $ \n- Gold: $ 80 + 120 = 200 $ \n- Total: $ 150 + 200 = \\boxed{350} $ pesos." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Millie buys 3 pitchers of lemonade, each holding 12 cups, for $18. \nSo, the total amount of lemonade she buys is: \n$$ 3 \\times 12 = 36 \\text{ cups} $$\n\nShe sells each cup for $1, so her total revenue is: \n$$ 36 \\times 1 = 36 \\text{ dollars} $$\n\nShe sells 4 cups per hour, so her profit per hour is: \n$$ 36 \\text{ dollars} - (4 \\text{ cups/hour} \\times 1 \\text{ dollar/cup}) = 32 \\text{ dollars/hour} $$\n\n**Answer:** $\\boxed{32}$ dollars per hour" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the total amount of land Mr. Ruther had at first.\n\nHe sold $ \\frac{3}{5} $ of his land, so he has $ 1 - \\frac{3}{5} = \\frac{2}{5} $ of his land left.\n\nHe has 12.8 hectares left, so:\n\n$$\n\\frac{2}{5}x = 12.8\n$$\n\nSolving for $ x $:\n\n$$\nx = 12.8 \\div \\frac{2}{5} = 12.8 \\times \\frac{5}{2} = 32\n$$\n\nSo, Mr. Ruther had **32 hectares** of land at first. \n\n$$\n\\" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Lisa is part of a choir with 52 members, 50% of which are boys and 50% of which are girls. So, there are 52 members in total.\n\nHalf the people performing can't make it to the show because their bus breaks down. That means **half of 52** are left.\n\n$$\n\\frac{1}{2} \\times 52 = 26\n$$\n\nThe choir's 3 teachers then decide to sing with them. So, the total number of people who sang in the performance is:\n\n$$\n26 + 3 = \\boxed{29}\n$$\n\n**Answer:** $\\boxed{29}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "To find Wilson's math grade, we need to calculate the **average** of his 5 test scores:\n\n$$\n\\text{Average} = \\frac{65 + 94 + 81 + 86 + 74}{5}\n$$\n\n$$\n\\text{Average} = \\frac{390}{5} = 78\n$$\n\nSince 78 is **80 or higher**, Wilson's report card shows that he received a **78** in his math class.\n\n$$\n\\boxed{78}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- 1 eraser costs $2 \n- 1 pencil costs $3 \n\n- 6 erasers = $6 × $2 = $12 \n- 8 pencils = $8 × $3 = $24 \n\n- Total cost = $12 + $24 = **$36**\n\n$$\n\\boxed{36}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James delivers:\n\n- 66 messages to Ms. Thompson \n- $ \\frac{1}{3} \\times 66 = 22 $ messages to Mr. Yu\n\nSo, the total number of messages is:\n\n$$\n66 + 22 = \\boxed{88}\n$$\n\nJames delivers **88 messages** in total." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "David and Dasha ride all 9 rides. Each ride costs:\n\n- 2 ride tickets at $2 per ticket → 2 × 2 = $4 per ride.\n\nSo, total cost for 9 rides is:\n\n$$\n9 \\times 4 = 36 \\text{ dollars}\n$$\n\nDavid buys a **ride bracelet** for $30, which gives him 9 rides. So, he saves:\n\n$$\n36 - 30 = 6 \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{6}$ dollars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Monica has 6 gifts for her family, 4 gifts for her friends, and 2 gifts for her teachers. \nTotal gifts = $6 + 4 + 2 = 12$ gifts.\n\nShe has 144 inches of ribbon and wants to use it for each gift. \nSo, the amount of ribbon used per gift is: \n$$\n\\frac{144 \\text{ inches}}{12 \\text{ gifts}} = 12 \\text{ inches per gift}\n$$\n\n**Answer:** $\\boxed{12}$ inches." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The ratio of popsicles that Betty and Sam have is **5:6**.\n- The total number of popsicles they have together is **165**.\n\nLet’s denote the number of popsicles Betty has as $ 5x $ and Sam as $ 6x $.\n\nSo:\n\n$$\n5x + 6x = 165\n$$\n\n$$\n11x = 165\n$$\n\n$$\nx = \\frac{165}{11} = 15\n$$\n\nNow, the number of popsicles:\n\n- Betty has $ 5x = 5 \\times 15 = 75 $\n- Sam has $ 6x = 6 \\times 15 =" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tim cancels his cable package for $60, and instead gets:\n\n- **Netflix**: $10/month \n- **Hulu + Disney Plus**: $10 + $10 = $20/month\n\nSo, he saves:\n\n$$\n60 - (10 + 20) = 60 - 30 = \\boxed{30} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{30}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carol spends:\n\n- 4 hours writing a song \n- Half that time: $ \\frac{4}{2} = 2 $ hours recording \n- 90 minutes editing\n\nConvert all times to hours:\n\n- 4 hours \n- 2 hours \n- 90 minutes = 1.5 hours\n\nTotal time = $ 4 + 2 + 1.5 = 7.5 $ hours\n\nPercentage of time spent editing:\n\n$$\n\\frac{1.5}{7.5} \\times 100 = 20\\%\n$$\n\n**Answer:** $\\boxed{20\\%}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- The number of books is **20 more than double** the number of books in a shelf.\n- There are **6 rows and 6 columns**, so the total number of books is:\n $$\n 6 \\times 6 = 36 \\text{ books}\n $$\n- Double the number of books:\n $$\n 2 \\times 36 = 72 \\text{ books}\n $$\n- Add 20 to this:\n $$\n 72 + 20 = 92 \\text{ books}\n $$\n\n### Final Answer:\n$$\n\\boxed{92}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Erica started with **20** Valentine's cards. \nHer dad brought her **2 boxes**, each with **15 cards**, so that's:\n\n$$\n2 \\times 15 = 30 \\text{ cards}\n$$\n\nNow, she passed out:\n\n- **24** to classmates \n- **5** to family \n- **17** from family and friends \n\nSo, total cards passed out:\n\n$$\n24 + 5 + 17 = 46\n$$\n\nNow, she has:\n\n$$\n20 + 30 - 46 = -16\n$$\n\n**But this result is negative, which means she doesn't have any cards.**\n\nWait — let's double-check:\n\n- 20 initial" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jenny is dividing up a pizza with 12 slices.\n\n- She gives **1/3** to Bill: \n $ \\frac{1}{3} \\times 12 = 4 $ slices.\n\n- She gives **1/4** to Mark: \n $ \\frac{1}{4} \\times 12 = 3 $ slices.\n\n- Jenny eats **2 slices**: \n $ 2 $ slices.\n\nSo, the total number of slices eaten is: \n$ 4 + 3 + 2 = 9 $ slices.\n\n**Leftover slices = 12 - 9 = 3**\n\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mark earns $10 per day, so his daily earnings are:\n\n$$\n10 \\text{ dollars/day}\n$$\n\nHe wants to save money to buy a bike that costs $300. So, the number of days he needs to save is:\n\n$$\n\\frac{300}{10} = 30 \\text{ days}\n$$\n\n**Final Answer:** $\\boxed{30}$ days." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Nancy saw:\n\n- 90 spiders \n- $ \\frac{1}{3} \\times 90 = 30 $ millipedes \n- $ 2 \\times 30 - 12 = 60 - 12 = 48 $ stink bugs\n\nTotal bugs = $ 90 + 30 + 48 = \\boxed{168} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Alice is 7 years older than Beth.\n- Beth is 5 years older than Erica.\n- Erica is 30 years old.\n\nLet's find the difference between the ages of Alice and Erica.\n\n1. Erica is 30 years old.\n2. Beth is 5 years older than Erica: \n $ 30 + 5 = 35 $ years old.\n3. Alice is 7 years older than Beth: \n $ 35 + 7 = 42 $ years old.\n\nSo, the difference between Alice and Erica is: \n$ 42 - 30 = \\boxed{12} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John drinks **2 glasses of milk**, and each glass contains **8 ounces of milk**.\n\n- Total milk consumed: $ 2 \\times 8 = 16 $ ounces \n- Calories from milk: $ 16 \\times 3 = 48 $ calories\n\n**Final Answer:** $\\boxed{48}$ calories." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "- A builder works **4 weeks** every **month**.\n- He works **6 days** every **week**.\n- He gets paid **$50 every day**.\n\n### Step 1: Calculate the number of days in a year\n\n- 1 year = 12 months \n- 1 month = 4 weeks \n- 1 week = 6 days\n\nSo, 1 year = 12 × 4 × 6 = **288 days**\n\n### Step 2: Calculate his earnings\n\n- He gets paid **$50 every day**\n\nSo, his total earnings = 288 days × $50/day = **$14,400**\n\n### Final Answer:\n\n$$\n\\boxed{1440" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark is making a **quadruple batch** of brownies, which means he needs **4 cups of flour** and **1 cup of milk**.\n\n- **Flour**: 4 cups \n- **Milk**: 1 cup\n\nNow, the **flour** is sold in **2-cup bags**, and the **milk** is sold in **2-cup bottles**.\n\n- Number of **flour bags** needed: $ \\frac{4}{2} = 2 $ \n- Number of **milk bottles** needed: $ \\frac{1}{2} = 0.5 $\n\nSince Mark can't buy half a bottle, he needs **1 bottle of milk**.\n\nNow, the difference between the number of **flour bags**" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mel uses a 900-watt air conditioner for 8 hours a day. \nSo, each hour, the AC uses **900 watts** of energy.\n\nIf he reduces the time by 5 hours, the new time is:\n\n$$\n8 - 5 = 3 \\text{ hours per day}\n$$\n\nIn 30 days, the total energy used is:\n\n$$\n900 \\text{ watts/hour} \\times 3 \\text{ hours/day} \\times 30 \\text{ days} = 81,000 \\text{ watt-hours}\n$$\n\nConvert watts to kilowatts:\n\n$$\n81,000 \\text{ watt-hours} = 81 \\text{ kilowatts" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jane has:\n\n- 2 zebras with 17 stripes each: $ 2 \\times 17 = 34 $ stripes \n- 1 zebra with 36 stripes \n- 1 zebra with half that many stripes: $ \\frac{36}{2} = 18 $ stripes\n\nSo, the total number of stripes is:\n\n$$\n34 + 36 + 18 = 98 \\text{ stripes}\n$$\n\nThe number of zebras is 2.\n\nSo, the average number of stripes per zebra is:\n\n$$\n\\frac{98}{2} = 49\n$$\n\n**Final Answer:** $\\boxed{49}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tyson needs to make **20 people** serve **4 people per sandwich**, so he needs to make:\n\n$$\n\\frac{20}{4} = 5 \\text{ sandwiches}\n$$\n\nEach sandwich requires **1 pound of meat** and **1 pound of cheese**, so he needs:\n\n$$\n5 \\text{ pounds of meat} + 5 \\text{ pounds of cheese} = 10 \\text{ pounds total}\n$$\n\nThe meat costs **$7.00 per pound**, and the cheese costs **$3.00 per pound**.\n\nSo, the total cost is:\n\n$$\n10 \\times 7 + 10 \\times 3 = 70 + 30 = \\boxed{100}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Let the number of **cannolis** be $ x $.\n- Since there is **twice as much corn** as cannolis, the number of **corns** is $ 2x $.\n- He has a total of 40 cannolis, so $ x = 40 $.\n- Therefore, the number of **corns** is $ 2 \\times 40 = 80 $.\n\nHe bought:\n- 60 more cannolis: $ 40 + 60 = 100 $ cannolis.\n- 40 fewer corns: $ 80 - 40 = 40 $ corns.\n\nNow, the **combined total** of the" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n1. **Total steps Elliott is trying to walk:** \n $ 10,000 $\n\n2. **He finished half of his steps on his walks to and from school:** \n $ \\frac{1}{2} \\times 10,000 = 5,000 $ steps\n\n3. **He also did another 1,000 steps going for a short walk with his friend:** \n $ 1,000 $ steps\n\n4. **After finishing his jog, he had 2,000 steps left:** \n So, the total steps he took so far is: \n $ 5,000 + 1,00" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Toby is reading a book that is **45 pages long**, and it averages **200 words per page**. \nHe reads at a rate of **300 words per minute**. \nHe has to be at the airport in **60 minutes**, and it takes **10 minutes** to get there. \nWe need to find how many **minutes early** he will be.\n\n---\n\n### Step 1: Calculate the total number of words in the book\n\n$$\n\\text{Total words} = 45 \\text{ pages} \\times 200 \\text{ words per page} = 9000 \\text{ words}\n$$\n\n---\n\n### Step 2: Calculate how long it takes Toby to read 900" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carolyn's company hired 40 employees in May, and each employee worked 40 hours a week. So:\n\n- May: $ 40 \\times 40 \\times 15 = 24,000 $ dollars.\n\nIn June, 1/4 of the employees' contracts expired. That means only 3/4 of the employees are still employed. So:\n\n- June: $ 40 \\times \\frac{3}{4} \\times 40 \\times 15 = 30,000 $ dollars.\n\nTotal amount paid in both months:\n\n$$\n24,000 + 30,000 = \\boxed{54,000} \\text{ dollars}.\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Sally starts with $10.\n\nShe buys:\n- 2 pounds of taffy: $3 per pound = $6\n- 1 pound of taffy with 1/2 off: $3 - $1.50 = $1.50\n- 2 pounds of taffy: $3 per pound = $6\n\nTotal for taffy: $6 + $1.50 + $6 = $13.50\n\nShe also buys:\n- 1 bag of seashells: $1.50\n- 4 magnets: $0.25 × 4 = $1.00\n\nTotal for seashells and magnets: $1.50 + $1.00 = $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tim buys:\n\n- A package of fireworks worth $400 \n- Another pack worth twice that much: $400 × 2 = $800 \n\nSo, the total cost of the fireworks is $400 + $800 = $1200.\n\nHe gets a **20% discount** on the fireworks: \n$1200 × 20% = $240 \n\nHe also buys a finale firework that costs $150.\n\nSo, the total amount he spent is:\n\n$1200 (fireworks) - $240 (discount) + $150 (firework) = **$1110**\n\n**Final Answer:** $\\boxed{1110}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Shannon eats **2 cookies per night** for **30 days**.\n\nSo, the total number of cookies needed is:\n\n$$\n2 \\text{ cookies/day} \\times 30 \\text{ days} = 60 \\text{ cookies}\n$$\n\nShe makes **1 dozen** = 12 cookies.\n\nSo, the number of dozens needed is:\n\n$$\n\\frac{60 \\text{ cookies}}{12 \\text{ cookies/dozen}} = 5 \\text{ dozens}\n$$\n\n**Answer:** $\\boxed{5}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 50000 candles are made.\n- 5% of the candles have a defect that makes them smell like wet dog.\n- 5% of the candles also have a defect that makes them explode.\n\nWe are to find how many candles will **both** smell like wet dog and explode.\n\nLet’s denote:\n\n- Total candles = 50,000\n- Percentage of candles that smell like wet dog = 5% = 0.05\n- Percentage of candles that explode = 5% = 0.05\n\nWe are to find the number of candles that **both** smell like wet dog and explode.\n\nThis is the **intersection** of the two sets:\n\n$$\n\\text{Number of candles that both" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Misha picks out 4 blouses from the 30% off rack. \n- Each blouse is **$20** in regular price. \n- 30% off means the price is **70%** of $20. \n- So, each blouse costs: \n $ 20 \\times 0.70 = 14 $ dollars. \n\n- Total cost for 4 blouses: \n $ 4 \\times 14 = 56 $ dollars. \n\n**Final answer:** $\\boxed{56}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ A $ be the number of apples Joanne gathers from the **average trees**.\n\n- Joanne gathers:\n - 30 apples from the **tallest trees**\n - $ \\frac{1}{2} \\times 30 = 15 $ apples from the **shortest trees**\n - $ A $ apples from the **average trees**\n\nSo, Joanne's total apples from all trees is:\n$$\n30 + 15 + A = 45 + A\n$$\n\n---\n\nNow, the sister gathers:\n\n- Twice as many as Joanne from the **tallest trees**: $ 2 \\times 30 = 60 $\n- Three times as many as Joanne from the **" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total heads: 180 \n- Total bumps: 304 \n- Camels have **2 humps** each \n- Dromedaries have **1 hump** each \n\nLet:\n\n- $ x $ = number of camels \n- $ y $ = number of dromedaries \n\nWe can set up the following system of equations:\n\n1. $ x + y = 180 $ (total heads) \n2. $ 2x + y = 304 $ (total bumps) \n\nSubtract the first equation from the second:\n\n$$\n(2x + y) - (x + y) = 304 - 180 \\\\\nx = 124\n$$\n\nSo" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tom's trip consists of two weeks. Let's break it down:\n\n- **First 4 days**: He traveled 200 km/day. \n Total distance: $ 4 \\times 200 = 800 $ km.\n\n- **Next 2 days**: He traveled 30% of the first 4-day distance. \n $ 0.3 \\times 800 = 240 $ km.\n\n- **On the next day**: He didn't travel at all.\n\n- **Second week**: He traveled 300 km/day for 7 days (since 2 weeks = 14 days, and 14 - 7 = 7). \n Total distance: $ 7 \\times 30" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Let the volume of Timothy's locker be $ T $ cubic inches.\n- Zack's locker is **half** as big as Timothy's: $ Z = \\frac{1}{2}T $.\n- Peter's locker is **1/4** as big as Zack's: $ P = \\frac{1}{4}Z $.\n- We are given that Peter's locker is 5 cubic inches: $ P = 5 $.\n\nSubstitute $ Z = \\frac{1}{2}T $ into the expression for Peter's locker:\n\n$$\n5 = \\frac{1}{4} \\cdot \\frac{1}{2}T = \\frac{1}{8}T\n$$\n\nNow solve for $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Stanley's comb fell 4,000 feet from an elevation of 10,000 feet to a ledge below. So, the comb is now at:\n\n$$\n10,000 - 4,000 = 6,000 \\text{ feet}\n$$\n\nOliver is at an elevation of 3,000 feet. To reach the elevation of Stanley's comb (6,000 feet), he must climb:\n\n$$\n6,000 - 3,000 = 3,000 \\text{ feet}\n$$\n\n**Answer:** $\\boxed{3000}$ feet." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Josue initially had $5000 in capital.\n\n- First bank gave him $4000.\n- Second company gave him twice as much as the first bank: $2 \\times 4000 = 8000.\n\nNow, he has:\n$$\n5000 + 4000 + 8000 = \\boxed{17000}\n$$\n\n**Answer:** $\\boxed{17000}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Initially, there are **50 cats** on the rock.\n\n- **4 boats** carry away **5 cats each**: \n $ 4 \\times 5 = 20 $ cats.\n\n- **3/5 of the remaining cats** ran after a mouse: \n $ \\frac{3}{5} \\times (50 - 20) = \\frac{3}{5} \\times 30 = 18 $ cats.\n\nSo, the total number of cats left on the rock is:\n\n$$\n50 - 20 - 18 = 12\n$$\n\n**Final Answer:** $\\boxed{12}$ cats." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break down the cost of 2 years (24 months) of the service:\n\n- **First 6 months**: $8/month \n- **Next 8 months**: $12/month \n- **Remaining 12 months**: $14/month \n\nSo, the total cost is:\n\n$$\n6 \\times 8 + 8 \\times 12 + 12 \\times 14\n$$\n\n$$\n= 48 + 96 + 168 = \\boxed{312} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{312}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- The **tattered jeans** cost **$28**.\n- The **jogger jeans** cost **$6 less than the tattered jeans**, so:\n $$\n \\text{Jogger jeans} = 28 - 6 = 22\n $$\n- He **saved a total of $6**.\n- He **saved 1/3 of the total savings from the jogger jeans** and the **rest from the tattered jeans**.\n\nLet’s denote:\n- $ x $ = cost of the tattered jeans = $28\n- $ y $ = cost of the jogger jeans = $22\n\nHe saved:\n- $ \\frac{1}{3} \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 4 buses, each holding 60 employees \n- 6 minibuses, each holding 30 employees \n- 10 minivans, each holding 15 employees \n\nWe need to find the total number of employees that can join the day trip.\n\n### Step 1: Calculate the total capacity of each type of vehicle\n\n- Buses: $ 4 \\times 60 = 240 $ employees \n- Minibuses: $ 6 \\times 30 = 180 $ employees \n- Minivans: $ 10 \\times 15 = 150 $ employees \n\n### Step 2: Add all the capacities together\n\n$$\n240 + 180 +" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Lillian builds 3 bird feeders and buys 3 others, so she has a total of:\n\n$$\n3 + 3 = 6 \\text{ bird feeders}\n$$\n\nEach store-bought feeder attracts **10 more birds** than the feeders she made herself. Let’s assume the store-bought feeders attract **x** birds each. Then Lillian’s feeders attract:\n\n- 10 more birds per store-bought feeder: $ x + 10 $\n- 10 more birds per her own feeders: $ x + 10 $\n\nSo, the total number of birds per feeder is:\n\n- Store-bought: $ x + 10 $\n- Lillian’s: $ x + 10 $\n\nSince the problem says" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- The **bagel** costs **$4**.\n- The **soup** is **25% more** than the bagel: \n $ 4 \\times 1.25 = 5 $ dollars.\n- The **cake** is **half the price of the bagel**: \n $ \\frac{4}{2} = 2 $ dollars.\n\nNow, add all the costs together:\n\n$$\n4 + 5 + 2 = \\boxed{11}\n$$\n\nAleksandra needs to pay **$11** for the dinner." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the number of cards Kenny has.\n\nHe sells $ x $ cards for $1.5 each, so he earns:\n\n$$\n1.5x\n$$\n\nHe keeps $ \\frac{1}{3} $ of the cards, so he keeps:\n\n$$\n\\frac{1}{3}x\n$$\n\nHe gets to go to the amusement park with $50 in cash, so he spends:\n\n$$\n50\n$$\n\nHe also has $50 in cash from the sales, so the remaining money after spending is:\n\n$$\n1.5x - \\frac{1}{3}x - 50 = 0\n$$\n\nSimplify:\n\n$$\n\\frac{4}{3}x - 50 = " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break it down step by step:\n\n- Total guests: 36\n- Half of the guests wanted **2 hotdogs** each: \n $ \\frac{36}{2} = 18 $ guests\n- 40 guests showed up, and everyone wanted a **second hotdog**.\n\nSo, the number of guests who **did not** get a second hotdog is:\n\n$$\n36 - 18 = 18\n$$\n\n---\n\n**Final Answer:** $\\boxed{18}$ guests did not get a second hotdog." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let’s solve the problem step by step:\n\n- Indras has **6 letters** in her name.\n- Her sister's name has **4 more letters than half of the letters in Indras' name**.\n\nSo, the sister's name has:\n\n$$\n\\frac{6}{2} + 4 = 3 + 4 = 7 \\text{ letters}\n$$\n\nNow, the total number of letters in both names is:\n\n$$\n6 + 7 = \\boxed{13}\n$$\n\n**Answer:** $\\boxed{13}$ letters." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Charlotte's order was:\n\n- $120.00 for pot and pans \n- $20.00 for mixing bowls \n- $5 × $5.00 = $25.00 for utensils\n\nTotal = $120 + $20 + $25 = **$165.00**\n\nAt checkout, everything was **20% off**, so:\n\n**20% of $165.00 = $33.00**\n\n**Total amount after discount = $165.00 - $33.00 = $132.00**\n\n### Final Answer: $\\boxed{132.00}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dora has saved $2 and her mother gave her $16, so she has a total of:\n\n$$\n2 + 16 = 18 \\text{ dollars}\n$$\n\nThe total cost of the items she wants to buy is:\n\n$$\n6 + 11 + 2 = 19 \\text{ dollars}\n$$\n\nSo, the amount she **needs** more is:\n\n$$\n19 - 18 = \\boxed{1} \\text{ dollar}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Prince Thaddeus slew **100** dragons.\n\nPrince Arthur slew **three quarters** as many as Prince Thaddeus:\n$$\n\\frac{3}{4} \\times 100 = 75 \\text{ dragons}\n$$\n\nPrince Walter slew **twice as many** as Prince Arthur:\n$$\n2 \\times 75 = 150 \\text{ dragons}\n$$\n\nPrince Bruce slew **one-fifth** as many as Prince Walter:\n$$\n\\frac{1}{5} \\times 150 = 30 \\text{ dragons}\n$$\n\n### Final Answer:\n$$\n\\boxed{30}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- 15 gallons of gas were divided equally into **5 containers**.\n- Josey needed **1/4 of a container** to run her lawnmower.\n\n---\n\n### Step 1: Find the amount of gas in one container\n\n$$\n\\text{Gas per container} = \\frac{15}{5} = 3 \\text{ gallons}\n$$\n\n---\n\n### Step 2: Find how much gas Josey needed\n\n$$\n\\text{Gas needed} = \\frac{1}{4} \\times 3 = \\frac{3}{4} \\text{ gallons}\n$$\n\n---\n\n### Step 3: Convert gallons to pints\n\nSince 1 gallon = 8 pints:\n\n$$\n\\frac{3}{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Let the number of candy bars George bought be $ x $.\n\n- Each candy bar costs **75 cents**.\n- George spent **$5** (i.e., 500 cents).\n- He had **1% of his money left**.\n\nSo, the amount he spent is **90%** of his money.\n\n$$\n0.9 \\times 500 = 450 \\text{ cents}\n$$\n\n---\n\n### Step 2: Set up the equation.\n\nHe spent 450 cents, and he had 1% left.\n\n$$\n\\text{Total money} = \\text{Amount spent} + \\text{Amount left}\n$$\n\n$$\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ray had 25 lollipops. He kept 5, so the remaining is:\n\n$$\n25 - 5 = 20 \\text{ lollipops}\n$$\n\nHe shared the remaining 20 equally among his 4 friends:\n\n$$\n\\frac{20}{4} = 5\n$$\n\nSo, each of his friends received **5 lollipops**.\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Rory makes a cake that weighs **20 ounces**, and she cuts it into **8 pieces**. Rory and her mom each have **1 piece**. \n\nSo, the remaining cake is:\n\n$$\n20 - 8 = 12 \\text{ ounces}\n$$\n\n**Answer:** $\\boxed{12}$ ounces." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Sitti and Juris bought 34 and 22 oranges, respectively. \nThey share the fruits equally with their 6 other friends. \n\nSo, the total number of fruits is: \n34 + 22 = 56 oranges.\n\nThey share them equally with 6 friends, so: \n56 ÷ 6 = 9.333... oranges per person.\n\nSince the problem asks for the number of oranges everyone will get, and it's likely expecting a whole number, we round down to the nearest whole number.\n\n**Final Answer:** $\\boxed{9}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Antoine's recipe requires:\n\n- **2 pounds of onions** \n- **2 boxes of beef stock** (each $2.00)\n\nHe serves **6 people**.\n\n### Step 1: Cost of onions\n- 2 pounds at $2.00 per pound = $4.00\n\n### Step 2: Cost of beef stock\n- 2 boxes at $2.00 per box = $4.00\n\n### Step 3: Total cost\n- $4.00 (onions) + $4.00 (beef stock) = **$8.00**\n\n### Step 4: Cost per serving\n- $8.00 ÷ 6 people = **$1.333..." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- **Wayne's driving time to the theater:** 4 minutes.\n- **Bernadette's driving time to the theater:** Let’s call this $ x $ minutes.\n- **The drive from Bernadette’s apartment to the theater takes 4 times as long as the drive from Wayne’s hotel to the theater.**\n\nSo, the drive from Bernadette’s apartment to the theater is **4 times** the drive from Wayne’s hotel to the theater.\n\nLet’s denote:\n- $ x $ = time for Bernadette to drive to the theater.\n- Then, the time for Wayne to drive to the theater is 4 minutes.\n\nWe are told that **Bernadette wants to arrive 5 minutes before Wayne**.\n\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Area of the bedroom: $ 360 \\, \\text{square feet} $\n- Length of the room: $ 3 \\, \\text{yards} $\n\n---\n\n### Step 1: Convert the length from yards to feet\n\nSince 1 yard = 3 feet:\n\n$$\n3 \\, \\text{yards} = 3 \\times 3 = 9 \\, \\text{feet}\n$$\n\n---\n\n### Step 2: Use the formula for the area of a rectangle\n\n$$\n\\text{Area} = \\text{Length} \\times \\text{Width}\n$$\n\nWe know the area is 360 square feet, and the length is 9 feet. Let the width be $ x $:\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each pack contains 20 pieces of beads.\n\n- **Elizabeth** bought:\n - 1 pack of red + 2 packs of clear = $1 \\times 20 + 2 \\times 20 = 20 + 40 = 60$ beads.\n\n- **Margareth** bought:\n - 3 packs of blue + 4 packs of red = $3 \\times 20 + 4 \\times 20 = 60 + 80 = 140$ beads.\n\n- **Difference**:\n $140 - 60 = \\boxed{80}$\n\n**Answer:** $\\boxed{80}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Marcus starts with a house temperature of **40 degrees**.\n\nHe spends **3 hours baking**, and during this time, the oven raises the temperature by:\n\n$$\n3 \\text{ hours} \\times 5 \\text{ degrees/hour} = 15 \\text{ degrees}\n$$\n\nSo, after baking, the temperature is:\n\n$$\n40 + 15 = 55 \\text{ degrees}\n$$\n\nThen, Marcus opens a window for **30 minutes**, and the house cools down by:\n\n$$\n\\frac{2 \\text{ degrees}}{10 \\text{ minutes}} \\times 30 \\text{ minutes} = 6 \\text{ degrees}\n$$\n\nSo, the final temperature is:\n\n$$\n55" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Jon's total time:\n - Swim: 40 minutes\n - Bike: 1 hour (60 minutes)\n - Run: 50 minutes\n\n- James finishes the swim **10% faster** than Jon, but **5 minutes longer** on the bike.\n\nLet’s denote:\n\n- Jon's total time: $ T = 40 + 60 + 50 = 150 $ minutes\n\n- James's total time:\n - Swim: $ 40 + 0.10 \\times 40 = 40 + 4 = 44 $ minutes\n - Bike: $ 60 + 5 = 65 $ minutes\n - Run: $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Movie A is **one-fourth** the length of Movie B.\n- Movie B is **5 minutes longer** than Movie C.\n- Movie C is **1.25 hours** long.\n\n---\n\n### Step 1: Convert all times to minutes\n\n- 1.25 hours = 1.25 × 60 = **75 minutes**\n\n---\n\n### Step 2: Find the length of Movie B\n\nMovie B is **5 minutes longer** than Movie C:\n\n$$\n\\text{Length of Movie B} = \\text{Length of Movie C} + 5 = 75 + 5 = 80 \\text{ minutes}\n$$\n\n---\n\n### Step 3: Find the length of Movie A\n\nMovie A" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "First, convert the time from minutes to hours:\n\n$$\n30 \\text{ minutes} = \\frac{30}{60} = 0.5 \\text{ hours}\n$$\n\nNow, calculate the distance the horse runs:\n\n$$\n\\text{Distance} = \\text{Speed} \\times \\text{Time} = 32 \\text{ mph} \\times 0.5 \\text{ hours} = 16 \\text{ miles}\n$$\n\nSince the horse runs 16 miles for every 2 miles of hay eaten, Michael eats:\n\n$$\n\\frac{16}{2} = 8 \\text{ bails of hay}\n$$\n\nEach bail costs $3, so the total cost is:\n\n$$\n8 \\" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Rozanne uses:\n\n- 4 dozen eggs = 4 × 12 = **48 eggs**\n- 2 eggs that were loose in the cupboard\n\nSo, total eggs used = 48 + 2 = **50 eggs**\n\nEach tray holds 5 glasses of eggnog, and each glass needs 5 eggs.\n\nSo, the number of trays = total eggs ÷ eggs per glass = 50 ÷ 5 = **10 trays**\n\n**Answer:** $\\boxed{10}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joey starts with **214 points**. He scores **26 points**, so his total becomes:\n\n$$\n214 + 26 = 240 \\text{ points}\n$$\n\nMarcy starts with **225 points** and scores **10 points**, so her total becomes:\n\n$$\n225 + 10 = 235 \\text{ points}\n$$\n\nNow, Joey has **240 points**, and Marcy has **235 points**. The difference is:\n\n$$\n240 - 235 = 5 \\text{ points}\n$$\n\nSo, **Joey is now winning by 5 points**.\n\n$$\n\\boxed{5} \\text{ points}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The salesman bought 48 sneakers for $576.\n\n- He sold 17 sneakers at $20 each: \n $ 17 \\times 20 = 340 $ dollars.\n\n- The remaining 31 sneakers were sold at $25 each: \n $ 31 \\times 25 = 775 $ dollars.\n\nNow, calculate the total revenue: \n$ 340 + 775 = 1115 $ dollars.\n\nThe salesman's profit is: \n$ 576 - 1115 = -539 $ dollars.\n\n**Profit = -$539** (a loss). \n\n$$\n\\boxed{-539}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Beatrice bought:\n\n- 6 packets × 8 pieces = 48 pieces \n- 4 packets × 16 pieces = 64 pieces\n\nTotal number of colors = 48 + 64 = **112**\n\nSo, the answer is:\n\n$$\n\\boxed{112}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break it down step by step.\n\n- **Super ticket price**: $20 \n- **Super ticket includes**: movie rights + popcorn + soda \n- **Regular ticket price**: $12 \n- **Regular ticket includes**: movie rights + popcorn + soda \n\nYou **did not** buy the super ticket, so you paid for the regular ticket. The **regular ticket cost** is $12.\n\nYou **saved** $2. That means the **regular ticket cost** is $12, and the **super ticket cost** is $20, so the **difference** is $2.\n\nSo, the **regular price of popcorn** is:\n\n$$\n\\boxed{2}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n---\n\n### Step 1: Let the original cost of filling one balloon be $ x $ dollars.\n\n- On the first day, the cost of filling 20 balloons was $900.\n- So, the cost per balloon is:\n $$\n x = \\frac{900}{20} = 45 \\text{ dollars per balloon}\n $$\n\n---\n\n### Step 2: The price increased by $20 on two days later.\n\n- So, the new cost per balloon is:\n $$\n 45 + 20 = 65 \\text{ dollars per balloon}\n $$\n\n---\n\n### Step 3: Fill 170 balloons at the new price.\n\n- Total" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To find the **average speed** of the car during the trip, we use the formula:\n\n$$\n\\text{Average speed} = \\frac{\\text{Total distance}}{\\text{Total time}}\n$$\n\n### Step 1: Calculate total distance\n\n- First leg: 60 mph for 2 hours \n Distance = $ 60 \\times 2 = 120 \\text{ miles} $\n\n- Second leg: 30 mph for 1 hour \n Distance = $ 30 \\times 1 = 30 \\text{ miles} $\n\n### Step 2: Calculate total time\n\n- Total time = $ 2 + 1 = 3 \\text{ hours} $\n\n### Step 3: Calculate average speed\n\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jenna starts with 8 sapphires. She trades 3 sapphires for 2 rubies. So, she gains 2 rubies for every 3 sapphires traded.\n\nLet's calculate the total value:\n\n- Sapphires: 8 sapphires × $800 = $6,400\n- Rubies: 2 rubies × $1200 = $2,400\n\nNow, since she trades 3 sapphires for 2 rubies, the value of the rubies is 2/3 of the value of the sapphires. So:\n\n- Value of rubies: $2,400\n- Value of sapphires: $6" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Marin and his neighbor Nancy each eat 4 apples a day. \nIn 30 days, they eat:\n\n$$\n4 \\text{ apples/day} \\times 30 \\text{ days} = 120 \\text{ apples}\n$$\n\n**Answer:** $\\boxed{120}$ apples." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bob has 10 raised beds, each of dimensions 2 ft × 8 ft × 2 ft.\n\n### Step 1: Calculate the volume of one raised bed\n$$\n\\text{Volume} = \\text{length} \\times \\text{width} \\times \\text{height} = 2 \\times 8 \\times 2 = 32 \\text{ cubic feet}\n$$\n\n### Step 2: Calculate the total volume of all 10 raised beds\n$$\n\\text{Total volume} = 10 \\times 32 = 320 \\text{ cubic feet}\n$$\n\n### Step 3: Determine the number of bags needed\nEach bag holds 2 cubic feet, so:\n$$\n\\text{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 15 red cards.\n- 60% more green cards than red cards.\n- Yellow cards are as many as the sum of red and green cards.\n\n---\n\n### Step 1: Find the number of green cards\n\nSince there are 60% more green cards than red cards, we can express this as:\n\n$$\n\\text{Green cards} = \\text{Red cards} + 60\\% \\times \\text{Red cards}\n$$\n\n$$\n\\text{Green cards} = 15 + 0.6 \\times 15 = 15 + 9 = 24\n$$\n\nSo, there are **24 green cards**.\n\n---\n\n### Step 2: Find the number of yellow" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Katelyn saw **50** fairies flying.\n\n- After **20 minutes**, one of her friends saw **half as many** fairies as Katelyn saw come from the east and join the fairies that were there. \n So, **half of 50** is **25**.\n\n- After **10 minutes**, **30** fairies flew away.\n\nSo, the total number of fairies remaining is:\n\n$$\n50 + 25 - 30 = \\boxed{45}\n$$\n\n**Answer:** $\\boxed{45}$ fairies are remaining." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jennifer's dog has 8 puppies, 3 of which have spots. \nBrandon's dog has 12 puppies, 4 of which have spots. \n\nTotal number of puppies = 8 + 12 = 20. \nNumber of puppies with spots = 3 + 4 = 7. \n\nPercentage of all puppies with spots = (7 / 20) × 100 = **35%**. \n\n$$\n\\boxed{35}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following quantities of feed:\n\n- **Sugars**: 2 boxes × 1 lb = 2 lb \n- **Carrots**: 4 bags × 12 lb = 48 lb \n- **Hay**: 42 bales × 75 lb = 3150 lb \n- **Oats**: 20 sacks × 65 lb = 1300 lb \n\nTotal weight = 2 + 48 + 3150 + 1300 = **3500 lb**\n\nThe truck can carry **2250 pounds at a time**.\n\nNow, to find how many trips:\n\n$$\n\\frac{3500}{2250} = 1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Grayson drinks:\n\n- **3 aluminum cans** of soda = $3 \\times 2 = 6$ cents \n- **5 plastic bottles** of water = $5 \\times 3 = 15$ cents\n\nTotal earnings per week: \n$6 + 15 = 21$ cents\n\nIn a **4-week month**, she earns: \n$21 \\times 4 = 84$ cents\n\n**Final Answer:** $\\boxed{84}$ cents." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- Frederick has **10 plants**.\n- Toni has **60% more plants** than Frederick.\n - 60% of 10 is $ 0.60 \\times 10 = 6 $.\n - So, Toni has $ 10 + 6 = 16 $ plants.\n\n- Shondra has **7 fewer plants** than Toni.\n - So, Shondra has $ 16 - 7 = 9 $ plants.\n\n### Final Answer:\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ali had $21.\n\nLeila gave him half of her $100, which is:\n\n$$\n\\frac{1}{2} \\times 100 = 50\n$$\n\nSo, Ali now has:\n\n$$\n21 + 50 = \\boxed{71}\n$$\n\nAli now has **$71**." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ashley's pizza delivery costs **$15**, and she wants to give a **tip that is 1/5 of the amount she ordered**.\n\nLet the amount she ordered be $ x $. Then:\n\n- Delivery cost: $ 15 $\n- Tip: $ \\frac{1}{5}x $\n\nTotal amount Ashley should pay:\n$$\n15 + \\frac{1}{5}x\n$$\n\nSince the problem doesn't specify the amount she ordered, we assume the delivery cost is the same as the tip. Therefore:\n\n$$\n15 = \\frac{1}{5}x \\Rightarrow x = 75\n$$\n\nSo, the total amount Ashley should pay is:\n\n$$\n15 + 75 = \\boxed{90}\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Finley started in **first place**. \n- She fell back 5 spots → **second place**. \n- Then moved ahead 2 spots → **third place**. \n- Then jumped ahead 1 spot → **fourth place**. \n\n**Finley finished in the 4th place.**\n\n$$\n\\boxed{4}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Miss Maria has:\n\n- 6 decks × 25 basketball cards = **150** basketball cards \n- 5 boxes × 40 baseball cards = **200** baseball cards \n\nShe keeps 50 cards, so she gives away **150 + 200 - 50 = 300** cards.\n\nShe gives **10 cards** to each student, so the number of students is:\n\n$$\n\\frac{300}{10} = \\boxed{30}\n$$\n\n**Answer:** $\\boxed{30}$ students." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Becky bought 20 apples for 45 cents each, and received a $1 discount. So, Becky's total cost is:\n\n$$\n20 \\times 45 = 900 \\text{ cents} \\\\\n\\text{After discount: } 900 - 100 = 800 \\text{ cents}\n$$\n\nKelly bought 20 apples for 50 cents each, and received a 10% discount. So, Kelly's total cost is:\n\n$$\n20 \\times 50 = 1000 \\text{ cents} \\\\\n\\text{After 10% discount: } 1000 - 100 = 900 \\text{ cents}\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break it down step by step:\n\n- Each room has:\n - 2 sheets\n - 1 comforter\n - 2 pillow cases\n - 2 towels\n\nSo, per room, there are:\n- 2 sheets + 1 comforter + 2 pillow cases + 2 towels = **7 items**\n\nNow, there are **80 rooms**, so the total number of pieces of laundry is:\n\n$$\n80 \\times 7 = \\boxed{560} \\text{ pieces}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Frank starts with **200 shoes**.\n\n- On **Monday**, he gets **5 pairs** of shoes: \n $ 5 \\times 2 = 10 $ shoes.\n\n- On **Wednesday**, he gains **15 new pairs**: \n $ 15 \\times 2 = 30 $ shoes.\n\n- On **Friday**, he gains **30 new pairs**: \n $ 30 \\times 2 = 60 $ shoes.\n\n- On **Saturday**, he **gains 180 shoes**.\n\nNow, let's add up the shoes he has on **Monday, Wednesday, Friday, and Saturday**:\n\n$$\n10 + 30 + 60 + 180 = 300" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mary has 6 jars of sprinkles, and each jar can decorate 8 cupcakes. So, the total number of cupcakes she can decorate is:\n\n$$\n6 \\times 8 = 48 \\text{ cupcakes}\n$$\n\nEach pan holds 12 cupcakes, so the number of pans she needs to bake is:\n\n$$\n\\frac{48}{12} = 4 \\text{ pans}\n$$\n\n**Final Answer:** $\\boxed{4}$ pans worth of cupcakes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. The price of the pen is $2.\n2. The price of the paper is $1 less than three times the price of the pen:\n $$\n 3 \\times 2 = 6 \\Rightarrow 6 - 1 = 5\n $$\n So, the paper costs $5.\n3. The total cost of the pen and the paper is:\n $$\n 2 + 5 = 7\n $$\n4. Theo gave the cashier $10.\n5. The amount of change she received is:\n $$\n 10 - 7 = \\boxed{3}\n $$\n\n**Answer:** $\\boxed{3}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- There are **30 students** in Marissa’s class.\n- Each student started with **10 pencils**.\n- So, the **total number of pencils** at the beginning is:\n $$\n 30 \\times 10 = 300 \\text{ pencils}\n $$\n\n- **1/5** of the total pencils were used:\n $$\n \\frac{1}{5} \\times 300 = 60 \\text{ pencils}\n $$\n\n- The remaining pencils after using 1/5 are:\n $$\n 300 - 60 = 240 \\text{ pencils}\n $$\n\n- **1/3** of" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the number of carrot sticks Matt eats be $ x $. According to the problem:\n\n- Matt eats **half as many cookies as the number of carrot sticks** plus **two extra for cleaning his room**.\n- He wants to eat **five cookies** in total.\n\nSo, the equation is:\n\n$$\n\\frac{1}{2}x + 2 = 5\n$$\n\nSubtract 2 from both sides:\n\n$$\n\\frac{1}{2}x = 3\n$$\n\nMultiply both sides by 2:\n\n$$\nx = 6\n$$\n\n### Final Answer:\n$$\n\\boxed{6}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Benny saw a **10-foot** shark with **2 remoras**, each **6 inches** long.\n\nFirst, convert the shark's length to inches:\n\n$$\n10 \\text{ feet} = 10 \\times 12 = 120 \\text{ inches}\n$$\n\nNow, calculate the combined length of the remoras:\n\n$$\n2 \\times 6 = 12 \\text{ inches}\n$$\n\nNow, find the percentage of the shark's body length that the remoras occupy:\n\n$$\n\\frac{12}{120} \\times 100 = 10\\%\n$$\n\n### Final Answer:\n$$\n\\boxed{10\\%}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Three-fourths of students have a desktop computer at home.\n- 20 students do **not** have desktop computers.\n\nLet the total number of students be $ x $.\n\n- 3/4 of $ x $ have desktop computers: $ \\frac{3}{4}x $\n- 1/4 of $ x $ do **not** have desktop computers: $ \\frac{1}{4}x $\n\nWe are told that 20 students do **not** have desktop computers:\n\n$$\n\\frac{1}{4}x = 20\n$$\n\nSolving for $ x $:\n\n$$\nx = 20 \\times 4 = 80\n$$\n\n### Final Answer:\n$$\n\\boxed{80" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jason wants to try out for the track team in **3 weeks**. He walks **4 days a week** to break in the new shoes.\n\n- Total time for 3 weeks: \n $ 3 \\text{ weeks} \\times 4 \\text{ days/week} = 12 \\text{ days} $\n\n- Time per day: \n $ \\frac{12 \\text{ days}}{1} = 12 \\text{ days} $\n\nSo, Jason has **12 days** to spend walking each day. \n\n$$\n\\boxed{12}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah spent $300 on books, and each book costs $15. So, the number of books is:\n\n$$\n\\frac{300}{15} = 20\n$$\n\nShe gave an equal number of books to her 4 kids, so each child got:\n\n$$\n\\frac{20}{4} = 5\n$$\n\n**Answer:** $\\boxed{5}$ books." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 9 kids are allergic to **dairy**.\n- 6 kids are allergic to **peanuts**.\n- 3 kids are allergic to **both** dairy and peanuts.\n- Total number of kids = 32.\n\nWe are to find how many **aren't allergic to anything**.\n\n---\n\n### Step 1: Find how many kids are allergic to **dairy only**.\n\nWe know:\n\n- Total allergic to dairy = 9\n- 3 kids are allergic to both dairy and peanuts\n\nSo, the number of kids allergic to **dairy only** = \n$$\n9 - 3 = 6\n$$\n\n---\n\n### Step 2: Find how many kids are allergic to **peanuts only**.\n\nWe know:\n\n- Total" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Each group has 200 employees, and there are 3 groups. So the total number of people going on the tour is:\n\n$$\n3 \\times 200 = \\boxed{600}\n$$\n\nTherefore, the total number of people going on the tour is **600**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tom's trip includes:\n\n- **Plane tickets**: $5000 each \n- **Hotel**: 20% more expensive than normal ($1500 per day) \n- **Total days**: 3\n\n### Step 1: Calculate the cost of the hotel for 3 days \nThe normal price is $1500 per day. \n20% more expensive means the hotel cost is: \n$$ 1500 \\times 1.20 = 1800 $$\n\nSo, for 3 days: \n$$ 1800 \\times 3 = 5400 $$\n\n### Step 2: Add the plane tickets \nPlane tickets cost $5000 each, and they are not included in" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ben has 4 blue tubes and 3 yellow tubes. \nJasper has half as many blue tubes as Ben: \n$$\n\\frac{1}{2} \\times 4 = 2 \\text{ blue tubes}\n$$\n\nJasper has three times as many yellow tubes as Ben: \n$$\n3 \\times 3 = 9 \\text{ yellow tubes}\n$$\n\nSo, Jasper has: \n$$\n2 \\text{ blue tubes} + 9 \\text{ yellow tubes} = \\boxed{11} \\text{ tubes of paint}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- The **1959 penny** weighs **48 grains**.\n- The **2010 penny** is **three-quarters** the weight of the 1959 penny.\n\n### Step 1: Find the weight of the 2010 penny\n\n$$\n\\text{Weight of 2010 penny} = \\frac{3}{4} \\times 48 = 36 \\text{ grains}\n$$\n\n### Step 2: Add the weights of both pennies\n\n$$\n\\text{Total weight} = 48 + 36 = 84 \\text{ grains}\n$$\n\n### Final Answer:\n\n$$\n\\boxed{84}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Keegan earned $83 and Tasha earned $91. Together, they have earned:\n\n$$\n83 + 91 = 174\n$$\n\nThey need to raise $200 - $174 = $26 more.\n\n**Final Answer:** $\\boxed{26}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gabriel has 20 songs on his player, and Luri has **3 times** as many songs as Gabriel. So:\n\n- Gabriel: 20 songs \n- Luri: $3 \\times 20 = 60$ songs\n\nNow, the question asks how many **fewer** songs Luri can add to his player than Gabriel can add to his.\n\n- Gabriel can add up to 100 songs to his player. \n- Luri can add up to 100 songs to his player.\n\nSo, the difference is:\n\n$$\n100 - 60 = 40\n$$\n\n**Answer:** $\\boxed{40}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Stetson ate $ \\frac{2}{5} $ of the 60 oranges. \nSo, the number of oranges he ate is: \n$$\n\\frac{2}{5} \\times 60 = 24 \\text{ oranges}\n$$\n\nSince he gave up $10 for each orange, the total amount of money he gave up is: \n$$\n24 \\times 10 = \\boxed{240} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jillian's handbag cost $20 less than 3 times as much as her shoes cost.\n\nLet the cost of her shoes be $80.\n\nThen, the cost of her handbag is:\n\n$$\n3 \\times 80 - 20 = 240 - 20 = 220\n$$\n\nSo, the cost of her handbag is $\\boxed{220}$." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James runs 12 miles a day for 5 days a week. \nHe runs at a rate of 10 miles per hour.\n\nSo, the total distance he runs in a week is:\n\n$$\n12 \\, \\text{miles/day} \\times 5 \\, \\text{days/week} = 60 \\, \\text{miles}\n$$\n\nNow, to find the total time he runs in a week:\n\n$$\n\\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\frac{60 \\, \\text{miles}}{10 \\, \\text{miles/hour}} = 6 \\, \\text{hours}\n$$\n\n**Answer:** $\\boxed{6" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Uncle Ben has **4 horses**, each consuming **5 pounds of oats per meal**, and he feeds them **twice a day**.\n\n### Step 1: Calculate daily oats consumption per horse\n- Each horse eats **5 pounds per meal** \n- He feeds them **2 times a day** \n- So, per horse per day: $ 5 \\, \\text{pounds/meal} \\times 2 = 10 \\, \\text{pounds/day} $\n\n### Step 2: Total daily oats consumption for all horses\n- 4 horses × 10 pounds/day = **40 pounds/day**\n\n### Step 3: Total oats needed for 5 days\n- 40 pounds/day × 5 days = **200" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jana has 27 puppies.\n\n- Two-thirds of the puppies are Pomeranians: \n $$\n \\frac{2}{3} \\times 27 = 18\n $$\n\n- One third of the Pomeranians are girls: \n $$\n \\frac{1}{3} \\times 18 = 6\n $$\n\n**Answer:** $\\boxed{6}$ girl Pomeranians." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "To find the **average highest temperature** of the three countries, we add up the temperatures and divide by 3:\n\n$$\n\\text{Average} = \\frac{-48 + 21 + (-3)}{3} = \\frac{-48 + 21 - 3}{3} = \\frac{-30}{3} = -10\n$$\n\n### Final Answer:\n$$\n\\boxed{-10}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The child has $4 already and wants to save $12 in total. \nHe promises to save $2 daily. \n\nSo, the number of days needed is: \n$$\n\\frac{12}{2} = 6 \\text{ days}\n$$\n\n**Answer:** $\\boxed{6}$ days." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jaime has **64 eggs** and **2 trays**, each holding **24 eggs**.\n\n- Each tray can hold 24 eggs.\n- So, 2 trays can hold $2 \\times 24 = 48$ eggs.\n\n- He has 64 eggs, which is more than 48.\n\n- The number of eggs **willingly** placed on the tray is **24** per tray.\n\n- The number of eggs **not** placed on the tray is:\n\n$$\n64 - 2 \\times 24 = 64 - 48 = \\boxed{16}\n$$\n\n**Answer:** $\\boxed{16}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sally buys:\n- 1 small pizza at $8,\n- 1 family-size pizza that costs 3 times as much as the small pizza, which is $3 × $8 = $24.\n\nSo, the total cost is:\n$$\n8 + 24 = \\boxed{32}\n$$\n\nSally spends **$32** in all." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Heather buys **2 packs** of razors, and each pack costs **$4.00**. \nShe also has a **$2.00 coupon**, so the total cost for 2 packs is:\n\n$$\n2 \\times 4.00 - 2.00 = 8.00 - 2.00 = 6.00\n$$\n\nEach individual razor costs:\n\n$$\n\\frac{6.00}{2} = 3.00\n$$\n\nSo, each individual razor costs **300 cents**.\n\n$$\n\\boxed{300}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 9 out of 10 cheerleaders are **64\" tall**.\n- The **10th cheerleader** is **60\" tall**.\n- The pyramid has:\n - 4 girls on the **bottom**.\n - 3 girls on top of the 4.\n - 2 girls on top of the 3.\n - The **shortest girl** is at the **top**.\n\n---\n\n### Step 1: Determine the height of the shortest girl\n\nWe are told that the **shortest girl** is at the **top**. So, the **height of the shortest girl** is **60\"**.\n\n---\n\n### Step 2: Build the pyramid\n\nWe can think of the pyramid as a" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Charisma works **8 hours** every day. \nShe walks **5 minutes** for each hour she's at work. \n\nSo, in 1 day: \n$$ 8 \\text{ hours} \\times 5 \\text{ minutes/hour} = 40 \\text{ minutes} $$\n\nAfter 5 days: \n$$ 40 \\text{ minutes/day} \\times 5 \\text{ days} = 200 \\text{ minutes} $$\n\n**Final Answer:** $\\boxed{200}$ minutes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\nLet:\n- Brett's current age = 14 years\n- Angela's current age = $ x $ years\n\nIn **four years**, Brett will be $ 14 + 4 = 18 $ years old.\n\nAccording to the problem, in four years, Angela will be **three times as old** as Brett is now:\n\n$$\nx + 4 = 3 \\times 14 = 42\n$$\n\nSo, Angela's current age is:\n\n$$\nx = 42 - 4 = 38\n$$\n\n### Final Answer:\n$$\n\\boxed{38}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Paul drives his car **twice a day** — once in the **morning** and once in the **afternoon**. \n- Each morning ride costs **$6**, \n- Each afternoon ride costs **$2**.\n\nHe does this **for 14 days**.\n\n### Step 1: Calculate the number of rides per day \n- 2 rides/day × 14 days = **28 rides**\n\n### Step 2: Calculate total cost \n- 28 rides × $6 (morning) + 28 rides × $2 (afternoon) \n- = $168 + $56 = **$224**\n\n### Final Answer: \n$$\n\\boxed{224}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's solve the problem step by step:\n\n- **Ashley's oranges**: 5 boxes × 10 oranges per box = **50 oranges**\n- **Brianne's oranges**: 20 more than Ashley = 50 + 20 = **70 oranges**\n- **Number of greek orange pies** each pie requires 3 oranges = 70 ÷ 3 ≈ **23.33**\n\nSince you can't make a fraction of a pie, they can make **23** greek orange pies.\n\n**Final Answer:** $\\boxed{23}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark is trying to choose between two venues for a surprise party:\n\n- **Venue 1**: $200 flat fee, **no food**.\n- **Venue 2**: $25 per person, **food included**.\n\nLet $ x $ be the number of guests.\n\n- **Venue 1 cost**: $ 200 + 5x $\n- **Venue 2 cost**: $ 25x $\n\nWe want to find the number of guests $ x $ such that the costs are equal:\n\n$$\n200 + 5x = 25x\n$$\n\nSubtract $ 5x $ from both sides:\n\n$$\n200 = 20x\n$$\n\nDivide both sides by 20:\n\n$$\nx =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ x $ be the number of insects Bodhi found.\n- Then David found half of what Bodhi found, so David found $ \\frac{x}{2} $.\n- Lily found 7 more than David, so Lily found $ \\frac{x}{2} + 7 $.\n\nThe total number of insects is 43:\n\n$$\nx + \\frac{x}{2} + \\frac{x}{2} + 7 = 43\n$$\n\nSimplify:\n\n$$\nx + x + 7 = 43\n$$\n\n$$\n2x + 7 = 43\n$$\n\n$$\n2x = 36\n$$\n\n$$\nx = 18\n$$\n\nSo, Bod" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mariah used $ \\frac{1}{4} $ of a skein of yarn, and her grandma used $ \\frac{1}{2} $ of a skein of yarn. There are 364 yards in a skein.\n\nSo, the total yards used is:\n\n$$\n\\frac{1}{4} + \\frac{1}{2} = \\frac{1}{4} + \\frac{2}{4} = \\frac{3}{4}\n$$\n\nMultiply by 364:\n\n$$\n\\frac{3}{4} \\times 364 = 273\n$$\n\n**Answer:** $\\boxed{273}$ yards." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cherrie has:\n\n- 2 friends who want 5 gifts each: $2 \\times 5 = 10$ gifts \n- 3 friends who want 2 gifts each: $3 \\times 2 = 6$ gifts \n- 10 more random gifts\n\nSo, the total number of gifts Cherrie bought is:\n\n$$\n10 + 6 + 10 = \\boxed{26}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The rug is **5 feet wider** than the chair.\n- The couch is **2 feet longer than twice the width of the rug**.\n- The chair is **3 feet wide**.\n\n---\n\n### Step 1: Find the width of the rug\n\nSince the rug is **5 feet wider** than the chair, and the chair is **3 feet wide**, then:\n\n$$\n\\text{Width of rug} = \\text{Width of chair} + 5 = 3 + 5 = 8 \\text{ feet}\n$$\n\n---\n\n### Step 2: Find the length of the couch\n\nThe couch is **2 feet longer than twice the width of the rug**. So:\n\n$$\n\\text{Length of couch} = 2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let’s define the cost of each pack of strawberry gum as $ x $ dollars.\n\n- She bought 2 packs of strawberry gum: $ 2x $\n- She paid $2 for a pack of grape gum: $2\n- She paid half as much for a small pack of green apple gum: $1\n\nSo, the total cost is:\n\n$$\n2x + 2 + 1 = 7\n$$\n\nSolving:\n\n$$\n2x + 3 = 7 \\\\\n2x = 4 \\\\\nx = 2\n$$\n\n**Answer:** Each pack of strawberry gum cost $ \\boxed{2} $." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A **2 x 4** piece of wood can make **200 sticks** for **$4**.\n- A **2 x 8** piece of wood can make **400 sticks** for **$6**.\n- He has **$24** to spend.\n- He wants to **make the most popsicles** by buying the **cheapest lumber**.\n\n---\n\n### Step 1: Determine the cost per stick\n\n- **2 x 4** sticks: \n $ \\frac{200 \\text{ sticks}}{4} = 50 \\text{ sticks per dollar} $ \n So, **$1 = 50 sticks**\n\n- **2 x 8** sticks: \n $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mario has 6 sled dogs, and each dog has 4 legs. So, the total number of legs is:\n\n$$\n6 \\text{ dogs} \\times 4 \\text{ legs per dog} = 24 \\text{ legs}\n$$\n\nEach pair of snowshoes costs $12.00, and each pair covers 2 legs. So, the number of pairs needed is:\n\n$$\n\\frac{24 \\text{ legs}}{2 \\text{ legs per pair}} = 12 \\text{ pairs}\n$$\n\nNow, the total cost is:\n\n$$\n12 \\text{ pairs} \\times \\$12.00 = \\$144.00\n$$\n\n**Final Answer:** $\\boxed{\\$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Janet takes **two bus trips five days a week**. \nEach trip costs **$2.20**.\n\n### Weekly cost of two trips:\n$$\n2 \\times 2.20 = 4.40\n$$\n\n### Weekly cost of a bus pass:\n$$\n20\n$$\n\n### Savings:\n$$\n20 - 4.40 = 15.60\n$$\n\n**Answer:** $\\boxed{15.60}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- The farm has **30 cows**.\n- The zoo has **20 sheep**.\n- The zoo has **twice as many cows as the farm**.\n- The farm has **half as many sheep as the zoo**.\n\nLet's solve step by step:\n\n1. The zoo has **20 sheep**.\n2. The zoo has **twice as many cows as the farm**:\n - So, the number of cows in the zoo is $ 2 \\times 30 = 60 $.\n3. The farm has **half as many sheep as the zoo**:\n - So, the number of sheep in the farm is $ \\frac{1}{2} \\times 20 = 10 $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let’s define the number of onions and potatoes Sophia bought as $ x $ and $ y $, respectively.\n\n- Rose bought 4 times the number of onions and potatoes: \n $ 4x = 12 $ (onions) \n $ 4y = 4 $ (potatoes)\n\nSolving for $ x $: \n$ 4x = 12 \\Rightarrow x = 3 $\n\nSolving for $ y $: \n$ 4y = 4 \\Rightarrow y = 1 $\n\nNow, the total number of onions and potatoes Sophia bought is: \n$ x + y = 3 + 1 = \\boxed{4} $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Andy wants to lose **30 pounds** by his birthday on **July 19th**. \nHe burns **3500 calories per pound** to lose a pound.\n\n### Step 1: Calculate the total calories he needs to burn\n$$\n30 \\text{ pounds} \\times 3500 \\text{ calories/pound} = 105,000 \\text{ calories}\n$$\n\n### Step 2: Determine the number of days between December 31st and July 19th\n\n- December has 31 days, so from December 31st to December 31st is 1 day.\n- January has 31 days, so from December 31st to January 31" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gerald works **$30 every day** and worked for **an entire week** (7 days). \nHe spent a total of **$100**.\n\nSo, his total earnings for the week are:\n\n$$\n30 \\times 7 = 210\n$$\n\nHe spent **$100**, so he has:\n\n$$\n210 - 100 = \\boxed{110}\n$$\n\n**Answer:** $\\boxed{110}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Hannah needs to drink **60 ml per kilometer**.\n\nShe runs **8 laps**, and each lap is **0.25 km**.\n\nSo, total distance = $ 8 \\times 0.25 = 2 $ km.\n\nTotal water needed = $ 60 \\, \\text{ml/km} \\times 2 = 120 \\, \\text{ml} $.\n\n**Final answer:** $\\boxed{120}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Julie had $500.\n\n1. She spent 20% of it on clothes:\n $$\n 0.20 \\times 500 = 100\n $$\n So, she spent $100.\n\n2. She spent 25% of the remaining money on CDs:\n $$\n 0.25 \\times (500 - 100) = 0.25 \\times 400 = 100\n $$\n So, she spent $100 on CDs.\n\n3. The remaining money is:\n $$\n 500 - 100 - 100 = 300\n $$\n\n**Answer" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the cost of the lot be $ L $, then the cost of the house is $ 3L $.\n\nWe are told that the total cost is $ 120,000 $, so:\n\n$$\nL + 3L = 120,000\n$$\n\n$$\n4L = 120,000\n$$\n\n$$\nL = \\frac{120,000}{4} = 30,000\n$$\n\nSo, the house cost is:\n\n$$\n3L = 3 \\times 30,000 = 90,000\n$$\n\n**Final Answer:** $\\boxed{90,000}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tara bought 8 packs of 5 canvas bags for $4 each:\n\n$$\n8 \\times 4 = 32 \\text{ dollars}\n$$\n\nShe sold them at $8 each:\n\n$$\n8 \\times 8 = 64 \\text{ dollars}\n$$\n\nProfit = Total revenue - Total cost\n\n$$\n64 - 32 = \\boxed{32} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{32}$ dollars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joe throws **25 punches per minute**, and a fight lasts **5 rounds of 3 minutes**.\n\nSo, the total number of punches Joe threw is:\n\n$$\n25 \\text{ punches/minute} \\times 5 \\text{ rounds} \\times 3 \\text{ minutes/round} = 375 \\text{ punches}\n$$\n\n**Final Answer:** $\\boxed{375}$ punches." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- **Suzanne made 36 cookies.**\n\n- **Josh made one-fourth of what Suzanne made.**\n\n $$\n \\text{Josh's cookies} = \\frac{1}{4} \\times 36 = 9\n $$\n\n- **Kelsie made two times more cookies than Josh.**\n\n $$\n \\text{Kelsie's cookies} = 2 \\times 9 = 18\n $$\n\n### ✅ Final Answer:\n$$\n\\boxed{18}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ali has:\n\n- 4 bills of $10: $4 \\times 10 = 40\n- 6 bills of $20: $6 \\times 20 = 120\n\nTotal money: \n$$ 40 + 120 = 160 $$\n\nHe gives half to his sister: \n$$ \\frac{1}{2} \\times 160 = 80 $$\n\nRemaining money after giving to sister: \n$$ 160 - 80 = 80 $$\n\nHe uses $3/5 of the remaining money to buy dinner: \n$$ \\frac{3}{5} \\times 80 = 48 $$\n\nRemaining money after buying dinner: \n$$ " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Royce takes **40 minutes more than double Rob** to shingle the house.\n\n- Rob takes **2 hours** = **120 minutes**.\n\n- So, Royce takes **2 * 2 = 40 minutes** more than Rob.\n\n- Therefore, Royce takes **120 + 40 = 160 minutes**.\n\n**Final answer:** $\\boxed{160}$ minutes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Martha needs to make 5 items for each of her 3 triplets:\n\n- 2 skeins for a hat \n- 4 skeins for a scarf \n- 12 skeins for a sweater \n- 1 skein for a pair of mittens \n- 2 skeins for a pair of socks \n\nSo, for each triplet: \n$$\n2 + 4 + 12 + 1 + 2 = 21 \\text{ skeins}\n$$\n\nSince there are 3 triplets: \n$$\n3 \\times 21 = \\boxed{63} \\text{ skeins}\n$$\n\n**Answer:** $\\boxed{63}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Chris has 100 math problems in total.\n\n- **Monday**: 12 problems \n- **Tuesday**: 3 times as many as Monday = $3 \\times 12 = 36$ problems \n- **Wednesday**: One-quarter of the remaining problems = $ \\frac{1}{4} \\times (100 - 12 - 36) = \\frac{1}{4} \\times 42 = 10.5$ problems\n\nSo, the remaining problems on **Thursday** are:\n\n$$\n100 - 12 - 36 - 10.5 = 42 - 10.5 = 31.5\n$$\n\nSince the number of problems must be an integer" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tony picks 6 quarts per hour.\n\nBobby picks 1 less quart per hour than Tony: \n$ 6 - 1 = 5 $ quarts per hour.\n\nKathy picks twice as many as Bobby: \n$ 2 \\times 5 = 10 $ quarts per hour.\n\nRicky picks 2 fewer quarts per hour than Kathy: \n$ 10 - 2 = 8 $ quarts per hour.\n\nNow, add up the quarts picked by all four: \n$ 6 + 5 + 10 + 8 = 29 $ quarts per hour.\n\n**Final Answer:** $\\boxed{29}$ quarts." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- **Initial loaves baked:** 200 \n- **Sold in the morning:** 93 \n- **Sold in the afternoon:** 39 \n- **Unsold loaves:** 6 \n\n**Total loaves sold:** \n$$ 93 + 39 = 132 $$\n\n**Total loaves left:** \n$$ 200 - 132 - 6 = \\boxed{58} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jackson plants tulips in rows. He has:\n\n- 36 red tulips\n- 24 blue tulips\n\nEach row can have:\n\n- 6 red tulips\n- 8 blue tulips\n\nSo, the number of rows is determined by how many full rows of tulips he can plant.\n\n### Step 1: Calculate the number of full rows of red tulips\n- 36 red tulips ÷ 6 = 6 rows\n\n### Step 2: Calculate the number of full rows of blue tulips\n- 24 blue tulips ÷ 8 = 3 rows\n\n### Step 3: Add the number of rows\n- 6 rows (red) + 3 rows (blue) = **9 rows**\n\n**" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Heather has 27 cups of raisins.\n\nEach batch of oatmeal cookies uses $ \\frac{3}{4} $ cup of raisins.\n\nTo find how many batches of oatmeal cookies Heather can make:\n\n$$\n\\text{Number of batches} = \\frac{27}{\\frac{3}{4}} = 27 \\times \\frac{4}{3} = 36\n$$\n\n**Answer:** $\\boxed{36}$ batches of oatmeal cookies." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ada's daily electric consumption is **12 kW/h**. \nShe adds a device that consumes **2 kW/h** per day. \nSo, her new daily consumption is: \n$$ 12 + 2 = 14 \\text{ kW/h} $$\n\nThe cost of 1 kW/h is **$1.50**, so the cost of her new daily consumption is: \n$$ 14 \\times 1.50 = 21 \\text{ dollars} $$\n\nBefore adding the device, her daily consumption was **12 kW/h**, so the cost was: \n$$ 12 \\times 1.50 = 18 \\text{ dollars} $$\n\nThe difference between the two bills is: \n$$ 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve this step by step.\n\n---\n\n### Step 1: Understand the rate of painting\n\n- One person can paint **half a house in 5 days**.\n\nSo, the **rate** of painting is:\n\n$$\n\\frac{1}{5} \\text{ house per day per person}\n$$\n\n---\n\n### Step 2: Find the total work (house) to be painted\n\nWe want to find out how many **hours** it would take for **5 people** to paint **1 house**.\n\nLet’s denote:\n\n- $ P $ = number of people = 5\n- $ H $ = total house = 1\n- $ D $ = days = ?\n\nWe can use the formula:\n\n$$\n\\text{Work} = \\text{Rate" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's solve the problem step by step:\n\n- **Ophelia has 20 sofas.**\n- Each sofa is 2 fewer than a chair. So, if Ophelia has 20 sofas, then she has $20 + 2 = 22$ chairs.\n\n- **Jenna has 3 times as many chairs as Ophelia.**\n - So, Jenna has $3 \\times 22 = 66$ chairs.\n\n- **Total number of sofas and chairs:**\n - Sofas: 20\n - Chairs: 22 (Ophelia) + 66 (Jenna) = 88\n\n**Final Answer:** $\\boxed{88}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tom paid $4 for a CD and $48 in total. He also bought a headphone set. If he had decided not to buy the headphone set, he would have paid only $4 for the CD.\n\nSo, the amount he would have paid for the CD is:\n\n$$\n4 \\text{ dollars}\n$$\n\nHe would have been able to buy **1 CD**.\n\nThus, the answer is:\n\n$$\n\\boxed{1}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- Josh spent **4 hours** working out **every week** **except on some occasions**.\n- At one point, he spent **5 hours** each for **2 consecutive weeks**.\n- At another point, he spent **6 hours** in **one week**.\n\nWe need to find the **total number of hours** he spent working out over **8 weeks**.\n\n### Step 1: Total hours if he worked 4 hours every week\nIf he worked 4 hours every week, then in 8 weeks:\n$$\n4 \\times 8 = 32 \\text{ hours}\n$$\n\n### Step 2: Add the extra hours from the special cases\n- 2 consecutive weeks of 5 hours:" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- **Initial number of passengers:** 48 \n- **First stop:** \n - 8 passengers get off. \n - 5 times as many get on as the number who got off: $ 5 \\times 8 = 40 $ passengers get on. \n - **Total passengers after first stop:** \n $ 48 - 8 + 40 = 80 $\n\n- **Second stop:** \n - 21 passengers get off. \n - 3 times fewer passengers get on than the number who got off: \n $ \\frac{21}{3} = 7 $ passengers get on. \n - **Total passengers after second stop:** \n $ " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Let:\n- $ x $ = current age of Jame\n- $ y $ = current age of his cousin\n\n---\n\n### Given:\n1. Jame will turn 27 in 5 years. \n So, $ x + 5 = 27 $ \n → $ x = 22 $\n\n2. In 8 years, Jame's age will be **5 years younger** than **twice** his cousin's age. \n So, $ x + 8 = 2(y - 5) $\n\n---\n\n### Substitute $ x = 22 $ into the second equation:\n\n$$\n22 + 8 = 2(y - 5)\n$$\n$$\n30 = 2y" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The total cost of the computer, monitor, and printer is $2,400.\n- The computer cost $1,100.\n- The printer cost $400 less than the computer.\n\n---\n\n### Step 1: Find the cost of the printer\n\nThe printer cost $400 less than the computer:\n\n$$\n\\text{Printer cost} = \\text{Computer cost} - 400 = 1,100 - 400 = 700\n$$\n\n---\n\n### Step 2: Find the cost of one monitor\n\nThe total cost of the computer, monitor, and printer is $2,400. We already know the cost of the computer and the printer. So:\n\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Understand the problem\n\n- There are **20 kids**.\n- They were divided into **two equal groups** of **girls and boys**.\n- The **boys** went out for the scavenger hunt and brought **60 shells each**.\n- The **girls** brought an amount **equal to the number of shells brought by the boys plus four times as many seashells as the boys**.\n\nWe are to find how many **seashells were brought by each girl**.\n\n---\n\n### Step 2: Let's define variables\n\nLet:\n\n- $ x $ = number of shells brought by each girl.\n\nWe are told:\n\n- The boys brought **60 shells each**, so total shells from boys" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n1. Let the number of candies George originally had be $ x $.\n\n2. According to the problem, Nick had **twice as many** candies as George. So, Nick had $ 2x $ candies.\n\n3. George ate 5 candies, and now he has 3 candies left. So, the total number of candies George has is:\n $$\n x - 5 = 3\n $$\n\n4. Solving for $ x $:\n $$\n x = 3 + 5 = 8\n $$\n\n5. Therefore, Nick had $ 2x = 2 \\times 8 = 16 $ candies.\n\n**Final Answer:** $\\boxed{16}$ candies." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Chenny is 10 years old. \nAlyana is 4 years younger than Chenny, so she is **6 years old**. \n\nAnne is 2 years older than Alyana, so she is **8 years old**. \n\n**Answer:** $\\boxed{8}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the following thicknesses of the four books:\n\n- First book: 31 mm \n- Second book: 50 mm \n- Third book: 5 mm less than the second book → $ 50 - 5 = 45 $ mm \n- Fourth book: twice as thick as the first book → $ 2 \\times 31 = 62 $ mm \n\nNow, add them all together:\n\n$$\n31 + 50 + 45 + 62 = \\boxed{188} \\text{ mm}\n$$\n\nThe total thickness of the four books is **188 mm**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Emma can make and upload **72 vlogs per month**, but she only made **18 vlogs** for the first week, **21 vlogs** for the second week, and **15 vlogs** for the third week. We need to find out how many vlogs she should do **to complete the 72 vlogs per month**.\n\n### Step-by-step:\n\n- Total vlogs per month: **72**\n- Vlogs made in the first 3 weeks: \n $ 18 + 21 + 15 = 54 $\n- Remaining vlogs to complete: \n $ 72 - 54 = 18 $\n\n### Final Answer:\n$$\n\\boxed{18}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Your wife wants to split the $50 dinner bill, and you want to pay an additional **20% tip**. Let's calculate the total amount you end up paying:\n\n1. **Calculate the tip amount:**\n $$\n 20\\% \\text{ of } \\$50 = 0.20 \\times 50 = \\$10\n $$\n\n2. **Add the tip to the original bill:**\n $$\n \\$50 + \\$10 = \\$60\n $$\n\n**Final Answer:** \n$$\n\\boxed{\\$60}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Find the eldest's original share\n\nThe problem says:\n\n> 18 is shared among 3 boys.\n\nSo, each boy gets:\n\n$$\n\\frac{18}{3} = 6\n$$\n\nSo, the eldest's **original share** is **$6**.\n\n---\n\n### Step 2: Add $5 to his share\n\nHe adds **$5** to his share:\n\n$$\n6 + 5 = 11\n$$\n\nSo, after adding $5, his share is **$11**.\n\n---\n\n### Step 3: Add $10 the following day\n\nHe adds **$10** to his share:\n\n$$\n11 + 10 =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the amount Elvis saves in the **first half of the month** as $ x $, and in the **second half** as $ 2x $, since he wants to save **twice as much daily** in the second half.\n\n### Step 1: Total monthly savings\nIn a month, there are 30 days. So, the total monthly savings would be:\n\n$$\n30x + 30(2x) = 30x + 60x = 90x\n$$\n\n### Step 2: Set up the equation\nElvis wants to save **$1125** in total. So:\n\n$$\n90x = 1125\n$$\n\n### Step 3: Solve for" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Verna bought:\n\n- 3 apples × $1.50 = $4.50 \n- 5 oranges × $0.80 = $4.00 \n- 6 peaches × $0.75 = $4.50 \n\nTotal cost = $4.50 + $4.00 + $4.50 = **$13.00**\n\nShe gave $20, so the change is:\n\n$$\n20 - 13 = \\boxed{7} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jairus gets $0.8 per task, and Jenny gets $0.5 per task.\n\nEach of them finished 20 tasks.\n\nSo, Jairus gets: \n$$ 0.8 \\times 20 = 16 $$\n\nJenny gets: \n$$ 0.5 \\times 20 = 10 $$\n\nThe difference is: \n$$ 16 - 10 = 6 $$\n\n**Answer:** $\\boxed{6}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the amount Jeff gets. Since Jeff gets 4 times as much as Brad, Brad gets $ x \\div 4 $.\n\nSo, Jeff gets $ 4x $, and Brad gets $ x \\div 4 $.\n\nJeff and Brad together get $ 4x + \\frac{x}{4} = 100 $.\n\nTo solve:\n\n$$\n4x + \\frac{x}{4} = 100\n$$\n\nMultiply both sides by 4 to eliminate the fraction:\n\n$$\n16x + x = 400\n$$\n\n$$\n17x = 400\n$$\n\n$$\nx = \\frac{400}{17}\n$$\n\n$$\nx \\approx 23" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jeff walks 3 miles to work and 3 miles back home each day. He works 5 times a week.\n\nSo, each day he walks: \n$$ 3 \\text{ miles to work} + 3 \\text{ miles back home} = 6 \\text{ miles per day} $$\n\nHe works 5 times a week, so:\n\n$$ 6 \\text{ miles/day} \\times 5 \\text{ days} = \\boxed{30} \\text{ miles} $$\n\n**Answer:** $\\boxed{30}$ miles." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Elise writes the alphabet **twice**, then writes **half** of it once, and then re-writes everything she has already written.\n\n- First, she writes the alphabet **twice**: 26 letters.\n- Then, she writes **half** of it once: 13 letters.\n- Then, she re-writes everything she has already written: 26 + 13 = 39 letters.\n\nSo, the total number of letters Elise has written is:\n\n$$\n\\boxed{39}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Each round of calls involves:\n\n- **1 family** being notified.\n- **3 families** being called by that family.\n- **3 families** being called by each of those 3 families.\n- **3 families** being called by each of those 3 families.\n\nSo, in **each round**, the number of families notified is:\n\n$$\n1 + 3 + 3 + 3 = 10\n$$\n\nSince this is the **fourth round**, the total number of families notified is:\n\n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark was unwell for 3 months, during which he lost 10 pounds per month. His final weight is 70 pounds.\n\nLet’s denote his initial weight as $ x $.\n\n- He lost 10 pounds per month for 3 months: \n $ 10 \\times 3 = 30 $ pounds.\n\n- His final weight is 70 pounds, so his initial weight is: \n $ x = 70 + 30 = \\boxed{100} $ pounds.\n\n**Answer:** $ \\boxed{100} $ pounds." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's define the number of toys Jonathan currently has as $ x $.\n\n- James's play set has 80 toys.\n- Jonathan needs 2 more toys than James's play set to make a five times larger play set.\n- So, the number of toys in James's play set is 80, and the number of toys in Jonathan's play set is $ 5 \\times 80 = 400 $.\n\nJonathan needs 2 more toys than he already had to make this play set. So, the number of toys he currently has is:\n\n$$\nx = 400 - 2 = 398\n$$\n\n### Final Answer:\n$$\n\\boxed{398}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Daniel wants to buy:\n\n- 5 notebooks × $1.50 = $7.50 \n- 2 pens × $0.25 = $0.50 \n- 1 calculator × $12 = $12 \n- 1 geometry set × $10 = $10 \n\nTotal cost before discount: \n$7.50 + $0.50 + $12 + $10 = **$30.00**\n\nSince the shop gives a **10% discount**, the total cost becomes: \n$30.00 × 90% = **$27.00**\n\n**Answer:** $\\boxed{27}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carly orders:\n- 5 hamburgers at $4 each: $5 \\times 4 = \\$20\n- 10 packs of potato fries at $0.30 each: $10 \\times 0.30 = \\$3\n- 5 cans of fruit drinks at $2 each: $5 \\times 2 = \\$10\n\nTotal cost: \n$$\n20 + 3 + 10 = \\$33\n$$\n\nShe gives $150 (one fifty-dollar bill). \n$$\n150 - 33 = \\boxed{117}\n$$\n\nCarly gets back **$117**." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Antonella sold goods worth **$2500**, which is **more than $1000**, so she earned:\n\n- A **30% commission** on $1000: \n $ 0.30 \\times 1000 = 30 $\n\n- An **additional 10% commission** on the **$1500** part of the sale (since $2500 - $1000 = $1500): \n $ 0.10 \\times 1500 = 150 $\n\nSo, Antonella earned a total of: \n$ 30 + 150 = \\boxed{180} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bill starts with:\n- 2 cases × 24 bottles = 48 bottles.\n\nHe has 70 guests, and wants 2 bottles for each guest:\n- 70 guests × 2 bottles = 140 bottles.\n\nHe needs:\n- 140 - 48 = 92 additional bottles.\n\n**Final Answer:** $\\boxed{92}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Define the variables\n\nLet:\n- $ x $ = time (in minutes) it takes Ray to swim a mile on a **cold day**.\n- $ x + 2 $ = time (in minutes) it takes Ray to swim a mile on a **hot day**.\n\n---\n\n### Step 2: Use the given information\n\n- On a **cold day**, Ray swims a mile in 16 minutes: \n $ x = 16 $\n\n- On a **hot day**, Ray swims a mile in $ 2x + 2 $ minutes: \n $ x + 2 = 2(16) + 2 = 34 $\n\n---\n\n### Step 3: Find" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John earns $2 per hour and works 5 hours a day for 4 days a week. \nSo, his daily earnings are: \n$$ 5 \\text{ hours/day} \\times 2 \\text{ dollars/hour} = 10 \\text{ dollars/day} $$\n\nHe wants to save $80. \nSo, the number of weeks needed is: \n$$ \\frac{80 \\text{ dollars}}{10 \\text{ dollars/day}} \\times 4 \\text{ days/week} = 32 \\text{ weeks} $$\n\n**Final Answer:** $\\boxed{32}$ weeks." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break it down step by step:\n\n- The cost of a **foot-long fish sub** is **$40**.\n- The cost of a **six-inch cold-cut combo sub** is **3 times** the price of the fish sub: \n $ 3 \\times 40 = 120 $.\n\nSo, the total cost for lunch today is:\n\n$$\n40 + 120 = \\boxed{160}\n$$\n\n**Answer:** $160." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There are **21 buttons** in the bag.\n- **7 buttons** have **2 holes** each.\n- The remaining **14 buttons** have **4 holes** each.\n\nSo, the total number of holes is:\n\n$$\n7 \\times 2 + 14 \\times 4 = 14 + 56 = 70\n$$\n\n**Final Answer:** $\\boxed{70}$ holes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Timothy's locker is **24 cubic inches**.\n\nZack's locker is **half as big** as Timothy's, so:\n\n$$\n\\text{Zack's locker} = \\frac{1}{2} \\times 24 = 12 \\text{ cubic inches}\n$$\n\nPeter's locker is **1/4 as big** as Zack's locker, so:\n\n$$\n\\text{Peter's locker} = \\frac{1}{4} \\times 12 = 3 \\text{ cubic inches}\n$$\n\n### Final Answer:\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Octavia drinks **half** of the daily recommended cups of coffee, so she drinks:\n\n$$\n\\frac{1}{2} \\times \\text{Recommended cups}\n$$\n\nJuan drinks **10 times** the amount Octavia drinks, so:\n\n$$\n10 \\times \\left( \\frac{1}{2} \\times \\text{Recommended cups} \\right) = 5 \\times \\text{Recommended cups}\n$$\n\nJuan’s doctor has asked him to reduce his daily coffee intake to the **daily recommendation of 4 cups**.\n\nSo, the amount Juan must reduce is:\n\n$$\n4 - 5 = -1\n$$\n\nSince he cannot reduce negative cups, the answer is:\n\n$$\n\\boxed{1} \\text{ cup} \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The pet shop had:\n\n- 3 cages with 10 hamsters each: $ 3 \\times 10 = 30 $ hamsters \n- 3 cages with 5 guinea pigs each: $ 3 \\times 5 = 15 $ guinea pigs \n\nTotal rodents = $ 30 + 15 = \\boxed{45} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark's weight = 150 pounds \nSusan's weight = Mark's weight - 20 = 150 - 20 = 130 pounds \nBob's weight = 2 × Susan's weight = 2 × 130 = 260 pounds \n\nNow, the average weight of the 3 friends is: \n$$\n\\frac{150 + 130 + 260}{3} = \\frac{540}{3} = 180\n$$\n\n**Final Answer:** $\\boxed{180}$ pounds." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The angle of the pyramid from the ground is **32°**.\n- The sun is moving **5° per hour** upward from the pyramid.\n- The sun starts at the tip of the pyramid and moves for **10 hours**.\n\n---\n\n### Step 1: Determine the total angle of the sun from the pyramid\n\nSince the sun moves **5° per hour**, in 10 hours, it moves:\n\n$$\n5 \\, \\text{°/hour} \\times 10 \\, \\text{hours} = 50°\n$$\n\nSo, the sun moves **50°** from the pyramid.\n\n---\n\n### Step 2: Add the angle from the ground\n\nThe pyramid is at **32°** from" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James buys birthday candles for his two sons. One son is 12 years old, and the other is 4 years younger, so the other son is 8 years old.\n\nHe buys a pack of 5 candles for $3.\n\nSo, the number of packs he needs is:\n\n$$\n\\frac{8 + 12}{5} = \\frac{20}{5} = 4 \\text{ packs}\n$$\n\nNow, the total cost is:\n\n$$\n4 \\text{ packs} \\times \\$3 = \\$12\n$$\n\n**Final Answer:** $\\boxed{\\$12}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Judy reads for 15 minutes each night in the first week. \nIn the second week, she reads a total of 100 pages. \nShe reads 2 pages per 1.5 minutes.\n\n### Step 1: Find how many pages she reads per night\nShe reads 15 minutes per night, and 2 pages per 1.5 minutes.\n\n$$\n\\text{Pages per night} = \\frac{15}{1.5} \\times 2 = 10 \\times 2 = 20 \\text{ pages}\n$$\n\n### Step 2: Find how many nights she reads in two weeks\nIn the first week, she reads 20 pages per night. \nIn the second week, she reads " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cody ate a third of the 12 sandwiches: \n$$\n\\frac{1}{3} \\times 12 = 4 \\text{ sandwiches}\n$$\n\nTrevor ate a quarter of the sandwiches: \n$$\n\\frac{1}{4} \\times 12 = 3 \\text{ sandwiches}\n$$\n\nTotal eaten: \n$$\n4 + 3 = 7 \\text{ sandwiches}\n$$\n\nSandwiches left: \n$$\n12 - 7 = \\boxed{5} \\text{ sandwiches}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let $ x $ be the current age of the nephew.\n\nShiloh is 44 years old today, so in 7 years, he will be $ 44 + 7 = 51 $ years old.\n\nIn 7 years, Shiloh will be three times as old as his nephew. So:\n\n$$\n51 = 3x\n$$\n\nSolving for $ x $:\n\n$$\nx = \\frac{51}{3} = 17\n$$\n\n### Final Answer:\n$$\n\\boxed{17}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break down the problem step by step.\n\n- The **first tooth** Sharon lost: $5.00\n- For each of the **next three teeth**, the tooth fairy gave Sharon **$1.00** each.\n- For each of the **last 2 teeth**, the tooth fairy gave Sharon **half the amount** of money per tooth as Sharon had received for the previous three teeth.\n\nSo, the total amount is:\n\n$$\n5.00 + 3 \\times 1.00 + 2 \\times (5.00 / 2) = 5.00 + 3.00 + 5.00 = \\boxed{13.00} \\text{ dollars}\n$$\n\n**Answer:** $\\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the number of goals scored by each teenager:\n\n- Let $ R $ be the number of goals scored by Richie.\n- Let $ A $ be the number of goals scored by Anna.\n- Let $ M $ be the number of goals scored by Mark.\n\nWe are told:\n\n- Richie scored 80 goals: $ R = 80 $\n- Richie scored 20 more goals than Mark: $ R = M + 20 $\n- Richie scored 45 more goals than Anna: $ R = A + 45 $\n\nWe can solve this step by step:\n\n1. From $ R = 80 $, we know that Mark scored $ M = R - 20 = 80 - 20 = 60 $\n2." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Liam made $63 in total.\n\nMitchell sold 21 lemonades at $4 each, so:\n\n$$\n21 \\times 4 = 84\n$$\n\nSo, Mitchell made **$84**.\n\nNow, the difference in their earnings is:\n\n$$\n84 - 63 = \\boxed{21}\n$$\n\n**Answer:** $\\boxed{21}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Peter has $70 and wants to spend an equal amount each day for one week. Since there are 7 days in a week, he will spend:\n\n$$\n\\frac{70}{7} = 10 \\text{ dollars per day}\n$$\n\nFrom **Sunday to Wednesday**, he spends $10 each day on wooden action figures, costing $5 each. So, the number of wooden action figures he buys is:\n\n$$\n10 \\text{ dollars/day} \\times 3 \\text{ days} = 30 \\text{ action figures}\n$$\n\nFor the **rest of the week (Thursday to Saturday)**, he spends $10 each day on plastic action figures, costing $2 each. So, the number of plastic action figures he" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Leah's total cost can be calculated as follows:\n\n- **Spaying cost**: $200 \n- **3 vaccines**: $3 \\times 20 = 60 \n- **4 vases**: $4 \\times 12 = 48 \n\nTotal cost = $200 + $60 + $48 = **$308**\n\n**Answer:** $\\boxed{308}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ford grows **40 roses every week**. \nHe supplies roses to **3 flower shops**:\n\n- First shop: 20 roses \n- Second shop: 15 roses \n- Third shop: 30 roses \n\nSo, the total number of roses he supplies per week is:\n\n$$\n20 + 15 + 30 = 65 \\text{ roses}\n$$\n\nHe grows **40 roses every week**, so he **lacks**:\n\n$$\n65 - 40 = \\boxed{25} \\text{ roses per week}\n$$\n\nThis is the number of roses he lacks to supply all the flower shops every month." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Katina starts with $3000 in her savings account.\n\nShe removes $100 every month for 2 years.\n\nFirst, convert 2 years to months: \n2 years × 12 months/year = 24 months.\n\nNow, calculate the total amount removed: \n$100/month × 24 months = $2400.\n\nSubtract the total amount removed from the initial amount: \n$3000 - $2400 = $600.\n\n**Final Answer:** $\\boxed{600}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Bread costs $3.00 per loaf.\n- Each loaf makes 10 sandwiches.\n- They spend $30.00 on cheese and condiments per 10 sandwiches.\n- They sell 10 sandwiches for $7.00 each.\n\n---\n\n### Step 1: Find the number of sandwiches made from 30.00\n\nThey spend $30.00 on cheese and condiments per 10 sandwiches. \nSo, the number of sandwiches made from $30.00 is:\n\n$$\n\\frac{30.00}{30.00} = 1 \\text{ loaf of bread} \\times 10 \\text{ sandwiches} = 10 \\text" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Kate has 3 boxes of 64 crayons each, so she has:\n\n$$\n3 \\times 64 = 192 \\text{ small pieces of crayons}\n$$\n\nShe melts 8 small pieces of crayons into a muffin, so she makes:\n\n$$\n8 \\text{ muffins}\n$$\n\nEach muffin sells for $1.50, so she makes:\n\n$$\n8 \\times 1.50 = 12 \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{12}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Michael is replacing the carpet in his bedroom. Let's break down the total cost:\n\n1. **Cost of new carpet**: \n $12 per square foot × 18 feet × 12 feet = $2,592\n\n2. **Cost of padding underneath**: \n $2 per square foot × 18 feet × 12 feet = $432\n\n3. **Cost to remove old carpet**: \n $4 per square foot × 18 feet × 12 feet = $864\n\n4. **Cost to install new carpet**: \n $34 per square foot × 18 feet × 12 feet = $7,440\n\nNow, add all the costs together:\n\n$$\n2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the number of birds Mack saw on several days:\n\n- Day 1: 50 birds \n- Day 2: 50 birds \n- Day 3: 0 birds \n- Day 4: 120 birds \n- Day 5: 120 birds \n- Day 6: 20 birds \n- Day 7: 90 birds \n\nWe are to find the **average number of birds** Mack saw in a day.\n\n### Step 1: Add up the total number of birds\n$$\n50 + 50 + 0 + 120 + 120 + 20 + 90 = 500\n$$\n\n### Step 2: Count the number of" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Start with the initial value\n\n- The starting value is **20**.\n\n---\n\n### Step 2: Divide the starting value by 5\n\n$$\n\\frac{20}{5} = 4\n$$\n\n---\n\n### Step 3: Multiply the result by the starting value minus 12\n\n$$\n4 \\times (20 - 12) = 4 \\times 8 = 32\n$$\n\n---\n\n### ✅ Final Answer:\n\n$$\n\\boxed{32}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The boy has 5 cards, and his brother has 3 fewer cards, so he has 5 - 3 = 2 cards.\n\nTogether, they have:\n$$ 5 + 2 = 7 $$\n\n**Answer:** $\\boxed{7}$ cards." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### **Given:**\n\n- When Maggie sets the oven to **450**, the actual temperature is **468**.\n- The oven is **off by the same percentage** for any recipe.\n- The recipe calls for **520 degrees**.\n\nWe need to find the **temperature** Maggie should set the oven to, **if it's off by the same percentage**.\n\n---\n\n### **Step 1: Find the percentage off the oven temperature**\n\nThe oven is off by the same percentage for any recipe. So, the oven temperature is **450**, and the actual temperature is **468**.\n\nSo, the oven is **off by**:\n\n$$\n\\text{Percentage off} = \\frac" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The first movie is 1 hour and 30 minutes, which is **130 minutes**.\n\nThe second movie is 2 hours and 5 minutes, which is **145 minutes**.\n\nAdding them together: \n130 + 145 = **275 minutes**.\n\n**Final answer:** $\\boxed{275}$ minutes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the value of Herb's house be $ H $.\n\nSince Juan's house is 30% less expensive than Herb's, we can express Juan's house value as:\n\n$$\n\\text{Juan's house value} = H - 0.30H = 0.70H\n$$\n\nWe are told that Herb's house is worth $76,000, so:\n\n$$\nH = 76,000\n$$\n\nNow, Juan's house is:\n\n$$\n0.70 \\times 76,000 = 53,200\n$$\n\nThe combined value of the two houses is:\n\n$$\n76,000 + 53,200 = \\boxed{" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Judy bought a dozen cups, so she had **12 cups**.\n\nShe also bought **twice as many dishes** as the number of cups she bought, so she had:\n\n$$\n2 \\times 12 = 24 \\text{ dishes}\n$$\n\nHer friend had brought:\n\n- 40 cups\n- 20 more dishes than she had brought, so:\n\n$$\n40 + 20 = 60 \\text{ dishes}\n$$\n\nNow, the total number of utensils brought by Judy and her friend is:\n\n$$\n12 + 24 + 40 + 60 = \\boxed{136} \\text{ utensils} \\text{ total} \\text{ brought by the two}." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 90 single-use contacts come in 1 box.\n- Each box costs $100.00, with a 10% discount.\n- Pete buys 2 boxes of contacts.\n- We are to find the cost of **each pair** of contacts.\n\n---\n\n### Step 1: Find the number of contacts in 2 boxes\n\n- 1 box = 90 contacts \n- 2 boxes = $2 \\times 90 = 180$ contacts\n\n---\n\n### Step 2: Find the cost of 2 boxes\n\n- Each box is $100.00 with a 10% discount \n- So, each box costs: \n $100.00 × (1 -" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tabitha agreed to pay $10 per hour for cleaning. Let's break down the information:\n\n- **Jill worked**:\n - 2 hours on Saturday\n - 1 hour on Sunday\n - Total: $2 + 1 = 3$ hours\n\n- **John worked**:\n - Twice as long as Jill on Saturday: $2 \\times 3 = 6$ hours\n - Three times as long as Jill on Sunday: $3 \\times 1 = 3$ hours\n - Total: $6 + 3 = 9$ hours\n\nNow, calculate the total money earned:\n\n- **Jill's total earnings**: $3 \\text{ hours} \\times 10 = 30$\n- **" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Hannah burns:\n\n- 2 hours of aerobics: $ 2 \\times 500 = 1000 $ calories \n- 1 hour of running: $ 1 \\times 600 = 600 $ calories\n\nTotal calories burned: \n$$ 1000 + 600 = 1600 \\text{ calories} $$\n\nShe needs to drink **100 ml of water for every 200 calories**.\n\nSo, the amount of water needed is: \n$$ \\frac{1600}{200} = 8 \\text{ ml} $$\n\n**Final Answer:** $\\boxed{8}$ ml of water." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total jelly beans = 4500\n- The jar contains **1% fewer red jelly beans than blue jelly beans**\n- The jar contains **1% more green jelly beans than blue jelly beans**\n\nLet’s define:\n\n- Let $ B $ = number of blue jelly beans\n- Let $ R $ = number of red jelly beans\n- Let $ G $ = number of green jelly beans\n\nFrom the problem:\n\n1. $ R = B - 0.01B = 0.99B $\n2. $ G = B + 0.01B = 1.01B $\n\nTotal jelly beans:\n\n$$\nR + B + G = 4500\n$$\n\nSubstitute:\n\n$$\n0." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jared starts at 47 WPM, then increases to 52 WPM, and then increases by 5 words to 57 WPM. The average of these three measurements is:\n\n$$\n\\frac{47 + 52 + 57}{3} = \\frac{156}{3} = 52\n$$\n\n**Final Answer:** $\\boxed{52}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n### Given:\n- Martin eats **Cheerios** every day for breakfast:\n - He loses **1.25 pounds/week**.\n- Martin eats **donuts** every day for breakfast:\n - He gains **1.75 pounds/week**.\n\nWe are to find the **difference in weight** at the end of **5 weeks** between the two breakfast options.\n\n---\n\n### Step 1: Calculate weight loss from Cheerios over 5 weeks\n\n- Weight loss per week: 1.25 pounds\n- Over 5 weeks: \n $$\n 1.25 \\times 5 = 6.25 \\text{ pounds}\n $$\n\n---\n\n### Step 2: Calculate" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Alex invites 100 people. Each of these 100 people also invites 2 of their friends, so:\n\n- 100 people × 2 friends = **200 friends**.\n\nThen, 10 of her friends are invited to join her, and 8 of them say they will bring their spouses. So:\n\n- 10 + 8 = **18 people**.\n\nNow, the total number of people Alex needs to seat is:\n\n- 100 (original) + 200 (friends) + 18 (spouses) = **318 people**.\n\nSo, Alex needs **318 seats**.\n\n$$\n\\boxed{318}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the weights of four dogs in a line:\n\n- **Affenpinscher (Aff)**: 10 pounds \n- **Dachshund**: 2 × 10 = **20 pounds** \n- **Papillon**: 1/4 × 20 = **5 pounds** \n- **Mastiff**: 44 × 5 = **220 pounds**\n\n### Final Answer:\n$$\n\\boxed{220}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Marilyn wants to buy a pair of boots online. On **Amazon**, the boots cost **$16**, and shipping costs **$4**. On **eBay**, the same boots cost **$13**, but shipping costs **twice as much** as on Amazon.\n\nSo, the shipping cost on eBay is:\n\n$$\n2 \\times 4 = 8\n$$\n\nNow, the total cost on eBay is:\n\n$$\n13 + 8 = 21\n$$\n\nThe total cost on Amazon is:\n\n$$\n16 + 4 = 20\n$$\n\nSo, the boots are **$1 more** expensive on eBay.\n\n$$\n\\boxed{1}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark plants a beanstalk below his second-story window, which is **20 feet off the ground**. The beanstalk **doubles its height every day**, starting from **4 feet**.\n\nWe are to find how many days it will take for the beanstalk to be **taller than 20 feet**.\n\n### Step-by-step:\n\n- **Initial height**: 4 feet \n- **Daily doubling**: 4 × 2 = 8 feet \n- **After 1 day**: 8 feet \n- **After 2 days**: 16 feet \n- **After 3 days**: 32 feet \n- **After 4 days**: 64 feet \n- **After 5 days**: 128 feet \n\nWe need to find the" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John eats **200 grams of mushrooms every day**. \nThere are **7 days in a week**.\n\n- Total mushrooms per day: 200 grams \n- Protein in mushrooms: 3 grams per 100 grams = 0.03 grams per gram\n\nSo, protein per day: \n$$\n200 \\, \\text{g} \\times 0.03 \\, \\text{g/g} = 6 \\, \\text{g/day}\n$$\n\nTotal protein per week: \n$$\n6 \\, \\text{g/day} \\times 7 \\, \\text{days} = 42 \\, \\text{g}\n$$\n\n**Answer:** $\\boxed{42}$ grams of protein" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n1. Let $ x $ be Jerry's current age.\n2. He is **twice as old as he was 5 years ago**. \n That means his age 5 years ago was $ x - 5 $, and now he is $ 2(x - 5) $.\n\n3. Since he is currently $ x $, we can set up the equation:\n $$\n x = 2(x - 5)\n $$\n\n4. Solve the equation:\n $$\n x = 2x - 10\n $$\n $$\n x - 2x = -10\n $$\n $$\n -x = -10\n $$\n $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "George needs to pay for dental work, which includes:\n\n- 2 implants: $2000 each → $4000\n- A porcelain crown: $500\n- A deposit: $600\n\nSo the total cost is:\n\n$$\n4000 + 500 + 600 = 4100\n$$\n\nHe earns $15 per hour. Let’s find out how many hours he needs to work to earn $4100:\n\n$$\n\\text{Hours} = \\frac{4100}{15} = 273.33\n$$\n\nSince he can't work a fraction of an hour, he needs to work **274 hours**.\n\n$$\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the smallest angle be $ x $. \nThen: \n- The second angle is $ 2x $, \n- The third angle is $ 3x $.\n\nSince the three angles in a triangle add up to 180°, we have:\n\n$$\nx + 2x + 3x = 180\n$$\n\n$$\n6x = 180\n$$\n\n$$\nx = 30\n$$\n\nNow, the angles are: \n- Smallest: $ 30^\\circ $ \n- Second: $ 60^\\circ $ \n- Third: $ 90^\\circ $\n\nThe largest angle is $ 90^\\circ $.\n\n$$\n\\boxed{90}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Colby has:\n\n- 8 quarters = 8 × 25 = 200 cents \n- 6 dimes = 6 × 10 = 60 cents \n- 14 nickels = 14 × 5 = 70 cents \n- 15 pennies = 15 × 1 = 15 cents \n\nTotal amount: \n200 + 60 + 70 + 15 = **345 cents**\n\nEach gumball costs **5 cents**. \nSo, how many gumballs can he buy: \n345 ÷ 5 = **69 gumballs**\n\n**Answer:** $\\boxed{69}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The store has:\n\n- 5 dogs: 5 × 4 = 20 legs \n- 2 cats: 2 × 2 = 4 legs \n- 10 birds: 10 × 2 = 20 legs \n\nTotal legs = 20 + 4 + 20 = **44 legs**\n\n$$\n\\boxed{44}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jamaal starts with an 8-pound weight. He increases it by 50%, so:\n\n$$\n8 + 0.5 \\times 8 = 8 + 4 = 12 \\text{ pounds}\n$$\n\nThen, he uses a weight **two pounds lighter** than that, so:\n\n$$\n12 - 2 = 10 \\text{ pounds}\n$$\n\n### Final Answer:\n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Steve starts with 5 games for his birthday. \nHe saves up 1 game per month for a year, so that's 12 games. \nThen he buys 2 games a month for the next year, so that's 24 games. \nHe also gets 5 games for Christmas every year. \n\nSo, total games after 3 years: \n5 + 12 + 24 + 5 = **46 games**. \n\n**Answer:** $\\boxed{46}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A plane travels **1200 miles** in **3 hours**.\n- We are to find how many **additional hours** it would take to travel an **additional 2000 miles** at the same rate.\n\n### Step 1: Find the speed of the plane\n\n$$\n\\text{Speed} = \\frac{\\text{Distance}}{\\text{Time}} = \\frac{1200 \\text{ miles}}{3 \\text{ hours}} = 400 \\text{ miles per hour}\n$$\n\n### Step 2: Find the time to travel 2000 miles at this speed\n\n$$\n\\text{Time} = \\frac{\\text{Distance}}{\\text{Speed}} = \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Ruiz can make **120 pounds** of chocolates in **2 hours**. \nSo, in **1 hour**, he makes: \n$$\n\\frac{120}{2} = 60 \\text{ pounds/hour}\n$$\n\nMarissa makes **$\\frac{3}{4}$ times** as many pounds of chocolates in an hour as Ruiz does. \nSo, Marissa makes: \n$$\n60 \\times \\frac{3}{4} = 45 \\text{ pounds/hour}\n$$\n\nThey worked for **12 hours** in a day. \nSo, the total amount of chocolate pounds they made together is: \n$$\n(60 + 45) \\times 12 = 105" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- On **Monday**, Howard spends **$8**.\n- On **Tuesday**, he spends **twice** as much as Monday: \n $ 2 \\times 8 = 16 $ dollars.\n- On **Wednesday**, he spends **4 times** as much as Tuesday: \n $ 4 \\times 16 = 64 $ dollars.\n\nNow, add up the amounts he spent:\n\n$$\n8 + 16 + 64 = 88\n$$\n\nHe originally had **$100**, so the amount he has left is:\n\n$$\n100 - 88 = \\boxed{12}\n$$\n\n**Answer:** $\\boxed{12}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Patrick sold lemonade for **6 hours** in total. Let's break it down:\n\n- In the first **4 hours**, he sold **15 cups/hour** at **$0.50 per cup**:\n $$\n 15 \\text{ cups/hour} \\times 4 \\text{ hours} = 60 \\text{ cups}\n $$\n $$\n 60 \\text{ cups} \\times 0.50 \\text{ dollars/cup} = 30 \\text{ dollars}\n $$\n\n- In the next **2 hours**, he sold **10 cups/hour** at **$0.60 per cup**:\n $$\n 10 \\text{ cups/hour" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Every 2 miles, the car drives the tires 725 times.\n- Jeremy drives 400 miles per month.\n- Each tire can undergo 10,440,000 rotations.\n\nWe are to find how many **years** before the tire needs to be replaced.\n\n---\n\n### Step 1: Find the number of rotations per mile\n\n$$\n\\text{Rotations per mile} = \\frac{725 \\text{ rotations}}{2 \\text{ miles}} = 362.5 \\text{ rotations/mile}\n$$\n\n---\n\n### Step 2: Find the number of rotations for 400 miles\n\n$$\n\\text{Rotations for 400 miles} = " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- The jumbo bottle of shampoo costs **$24.00**.\n- It requires **2 pumps** to give **120 washings**.\n- Jackie uses **1 pump per wash**.\n\n### Step 1: Find the cost per pump\n\n- 120 washings = 2 pumps \n- So, 1 pump = $24.00 / 2 = **$12.00**\n\n### Step 2: Convert to cents\n\n- $12.00 = 1200 cents\n\n### Final Answer:\n\n$$\n\\boxed{1200}\n$$\n\nEach pump costs **1200 cents**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Joe has $50 to buy an outfit. The shirt is $25, the shorts are $35, and there is a 30% discount on the shirt. Let's calculate the total cost:\n\n1. **Cost of shirt with discount**: \n $25 - (30% of 25) = 25 - 7.5 = $17.50\n\n2. **Total cost of outfit**: \n $17.50 (shirt) + $35 (shorts) = $52.50\n\n3. **Sales tax is included**, so Joe doesn't need to pay tax. \n He has $50, so he will have:\n\n$$\n50 - 52.5" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Juan wants to make **4 dozen** of croissants **per day** for **a week**.\n\n- 1 dozen = 12 croissants \n- 1 dozen croissants = 1/4 pound of butter \n- 4 dozen = 4 × 12 = 48 croissants \n- 48 croissants × 1/4 pound = 12 pounds of butter\n\n**Answer:** $\\boxed{12}$ pounds of butter." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Monica's street is 150 meters long, and it costs $194 per meter. \nSo, the cost for Monica's street is: \n$$ 150 \\times 194 = 29,100 $$\n\nLewis' street is 490 meters long. \nThe cost for Lewis' street is: \n$$ 490 \\times 194 = 94,660 $$\n\nThe difference in cost is: \n$$ 94,660 - 29,100 = 65,560 $$\n\n**Answer:** $\\boxed{65560}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John's research cost is calculated as follows:\n\n- Initial funding: $100,000\n- First 5 months: $100,000\n- After 5 months: 50% more funding per month, so each month's cost is 1.5 times the previous month's cost.\n\nSo, the total cost is:\n\n$$\n100,000 + 100,000 \\times 1.5 + 100,000 \\times 1.5^2 + \\dots + 100,000 \\times 1.5^{5}\n$$\n\nThis is a geometric series with first term $ a = 100,000 $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The problem gives the following information:\n\n- **First player**: 6 ounces of steak \n- **Second player**: 8 beef tips, each 1 ounce → $ 8 \\times 1 = 8 $ ounces \n- **Third player**: 1 pound of steak \n- **Fourth and fifth players**: Vegetarian meals, so no meat is consumed\n\nNow, convert the 1 pound of steak to ounces: \n1 pound = 16 ounces.\n\nSo, the total meat consumed is:\n\n$$\n6 + 8 + 16 = 20 \\text{ ounces}\n$$\n\n**Final Answer:** $\\boxed{20}$ ounces." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each member posts an average of 3 posts per day, and there are 1000 members.\n\n- Total number of posts in March = 1000 members × 3 posts/day × 31 days \n- Total number of posts = $ 1000 \\times 3 \\times 31 = 93,000 $\n\n**Final Answer:** $\\boxed{93000}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gary does laundry **twice a week**. \nEach load of laundry uses **20 gallons of water**, and **1 gallon costs $0.15**.\n\n### Step 1: Calculate the total water used per week \n- 2 loads × 20 gallons = **40 gallons** of water per week.\n\n### Step 2: Calculate the cost per week \n- 40 gallons × $0.15/gallon = **$6**.\n\n### Step 3: Calculate the cost for a year \n- 52 weeks/year × $6/week = **$312**.\n\n### Final Answer: \n$$\n\\boxed{312}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Scarlett spent:\n\n- $10.00 on the aquarium \n- $2.50 × 2 = $5.00 on the rocks \n- $2.00 × 3 = $6.00 on the coral \n- $0.50 × 20 = $10.00 on the fish \n- $2.00 for fish food \n\nTotal cost: \n$10.00 + $5.00 + $6.00 + $10.00 + $2.00 = **$33.00**\n\n**Answer:** $\\boxed{33.00}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Week 1: 3 inches \n- Week 2: 3 × 2 = **6 inches** \n- Week 3: 6 + 4 = **10 inches**\n\n**Final answer:** $\\boxed{10}$ inches." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Prince sells 15 kg of meat every hour he works, and he works 10 hours a day. So, in one day, he sells:\n\n$$\n15 \\, \\text{kg/hour} \\times 10 \\, \\text{hours} = 150 \\, \\text{kg/day}\n$$\n\nBill's bull weighs 750 kg. So, the number of days it will take for Prince to sell the bull is:\n\n$$\n\\frac{750 \\, \\text{kg}}{150 \\, \\text{kg/day}} = 5 \\, \\text{days}\n$$\n\n**Final Answer:** $\\boxed{5}$ days." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 4 rows of seats \n- 18 seats per row \n- 18 seats per row = 4 × 18 = 72 seats in total \n- One-fourth of the seats were occupied by the **administrators** \n- One-third of the **remaining seats** were occupied by the **parents** \n- The rest were occupied by the **students**\n\n---\n\n### Step 1: Total number of seats\n\n$$\n72 \\text{ seats}\n$$\n\n---\n\n### Step 2: Occupied by administrators\n\n$$\n\\frac{1}{4} \\times 72 = 18 \\text{ seats}\n$$\n\n---\n\n### Step 3: Remaining seats after administrators\n\n$$\n72 - 1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each pole has 4 street lights, and there are 6 poles at each intersection. There are 4 intersections.\n\n- Total number of poles: $ 6 \\text{ poles/intersection} \\times 4 \\text{ intersections} = 24 $ poles.\n- Total number of street lights: $ 24 \\text{ poles} \\times 4 \\text{ street lights/pole} = 96 $ street lights.\n- 20 streetlights are not working, so the number of functioning streetlights is:\n $$\n 96 - 20 = \\boxed{76}\n $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- A DVD can be played **1000 times** before it breaks.\n- The first DVD has been played **356 times**.\n- The second DVD has been played **135 times**.\n\nWe are to find how many **total times** both DVDs can be played **before** they break.\n\n### Step-by-step:\n\n- The first DVD has been played **356 times**.\n- The second DVD has been played **135 times**.\n- The total number of times both DVDs can be played **before** they break is:\n\n$$\n356 + 135 = 491\n$$\n\n### Final Answer:\n\n$$\n\\boxed{491}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John went to physical therapy for **6 weeks**, and each week he went **2 sessions** for **2 hours**. \nEach session costs **$125 per hour**.\n\n### Step 1: Calculate the number of hours per week\n- 2 sessions × 2 hours = **4 hours per week**\n\n### Step 2: Calculate the total number of hours over 6 weeks\n- 4 hours/week × 6 weeks = **24 hours**\n\n### Step 3: Calculate the total cost\n- 24 hours × $125/hour = **$3000**\n\n### Final Answer:\n$$\n\\boxed{\\$3000}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jim has a **20-pack** of gum, which means he starts with **20 pieces**.\n\nHe chews **1 piece per 2 hours** over a school day that lasts **8 hours**. \nSo, in 8 hours, he chews: \n$$\n\\frac{1}{2} \\times 8 = 4 \\text{ pieces}\n$$\n\nHe also chews **1 piece on the way home** and **1 stick after dinner**. \nSo, that's: \n$$\n1 + 1 = 2 \\text{ pieces}\n$$\n\nHe gives **half** of the remaining gum to his sister. \nSo, he gives away: \n$$\n\\frac{1}{2} \\times 20 = " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Charmaine will be 16 years old in **12 years**, so she will be **16 + 12 = 28 years old** in 12 years.\n\n4 years from now, she will be **28 + 4 = 32 years old**.\n\n$$\n\\boxed{32}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The baseball coach bought 9 baseballs for $3 each, so the total cost is:\n\n$$\n9 \\times 3 = 27 \\text{ dollars}\n$$\n\nThe basketball coach bought 8 basketballs for $14 each, so the total cost is:\n\n$$\n8 \\times 14 = 112 \\text{ dollars}\n$$\n\nThe basketball coach spent **$112** and the baseball coach spent **$27**, so the difference is:\n\n$$\n112 - 27 = \\boxed{85} \\text{ dollars}\n$$\n\nThe basketball coach spent **85 dollars more** than the baseball coach." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Arianna's garden has:\n\n- 10 rows \n- 20 flowers per row \n- Total flowers = $10 \\times 20 = 200$\n\nOnly $ \\frac{4}{5} $ of the flowers have bloomed.\n\nSo, the number of blooming flowers is:\n\n$$\n\\frac{4}{5} \\times 200 = 160\n$$\n\n**Answer:** $\\boxed{160}$ flowers have bloomed." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ashley's internet connection speed is **20 kb/s**.\n\nWe are given that:\n\n- 1 Mb = 1000 kb\n\nSo, to convert kb/s to Mb/s:\n\n$$\n20 \\, \\text{kb/s} = \\frac{20}{1000} \\, \\text{Mb/s} = 0.02 \\, \\text{Mb/s}\n$$\n\nNow, to convert Mb/s to Mb/hour:\n\n$$\n0.02 \\, \\text{Mb/s} \\times 3600 \\, \\text{s/h} = 72 \\, \\text{Mb/h}\n$$\n\n### Final Answer:\n$$\n\\boxed{72} \\, \\text{Mb" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break it down step by step:\n\n- On the first **3 days**, the truck towed **10 cars** each day.\n- On the remaining **7 days**, the truck towed **4 fewer cars** than on the first 3 days, so **6 cars** each day.\n\nSo, the total number of cars towed is:\n\n$$\n3 \\times 10 + 7 \\times 6 = 30 + 42 = \\boxed{72}\n$$\n\n**Answer:** $\\boxed{72}$ cars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Adam's height is 40 inches, and he grows 2 inches per year. We need to find how many years it will take for him to reach 4 feet (which is 48 inches).\n\n- 40 inches is the current height.\n- He grows 2 inches per year.\n- So, the number of years required is: \n $$\n \\frac{48 - 40}{2} = \\frac{8}{2} = 4 \\text{ years}\n $$\n\n**Answer:** $\\boxed{4}$ years." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James sold 10 cars, each costing $25,000. \nTotal cost of cars = $25,000 × 10 = $250,000.\n\nHe received a 30% commission on the cost of the cars: \n$250,000 × 30% = $75,000.\n\nHe also received a 10% commission on the profit: \nProfit = $250,000 - $75,000 = $175,000 \nCommission = 10% of $175,000 = $17,500.\n\nTotal amount James made: \n$75,00" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **100 riders**.\n- When a wave over 30 feet arrives, **25%** of the riders can stay upright.\n- Of these **25%**, **60%** are **women**.\n\n### Step 1: Find how many riders can stay upright\n\n$$\n25\\% \\text{ of } 100 = 0.25 \\times 100 = 25 \\text{ riders}\n$$\n\n### Step 2: Find how many of those 25 riders are women\n\n$$\n60\\% \\text{ of } 25 = 0.60 \\times 25 = 15 \\text{ women}\n$$\n\n###" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The price of a **diamond Jewell** is $2000.\n- The price of a **gold Jewell** is $ \\frac{4}{5} $ times the price of a diamond Jewell.\n- The price of a **silver Jewell** is $400 less than the price of a gold Jewell.\n\n---\n\n### Step 1: Find the price of the gold Jewell\n\n$$\n\\text{Price of gold} = \\frac{4}{5} \\times 2000 = 1600\n$$\n\n---\n\n### Step 2: Find the price of the silver Jewell\n\n$$\n\\text{Price of silver} = \\text{Price of gold} - 400" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Max bought:\n\n- 16 snowflake stamps \n- 3 more truck stamps than snowflake: $ 16 + 3 = 19 $ truck stamps \n- 9 fewer rose stamps than truck: $ 19 - 9 = 10 $ rose stamps \n\nTotal stamps: \n$$\n16 + 19 + 10 = \\boxed{45}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bob is 75 miles ahead of Tom, and both are driving towards each other. Bob is driving at 55 mph, and Tom is driving at 70 mph.\n\nLet $ t $ be the time in hours it takes for Tom to catch up with Bob.\n\nIn that time, Bob will have traveled:\n$$\n55t \\text{ miles}\n$$\n\nSince Bob is 75 miles ahead initially, and Tom catches up, the distance Tom covers must be equal to the distance Bob has covered plus 75 miles:\n$$\n70t = 55t + 75\n$$\n\nSolving for $ t $:\n$$\n70t - 55t = 75 \\\\\n15t = 75 \\\\\nt =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Naomi caught **17 fish**.\n- Darren caught **6 less** than Naomi → $ 17 - 6 = 11 $ fish.\n- Tommy caught **3 more** than Darren → $ 11 + 3 = 14 $ fish.\n\n### Final Answer:\n$$\n\\boxed{14}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Manny signed up for **60 classes**, and his parents will **not** sign him up again if the **total cost exceeds $10 per class**.\n\n- There are **10 total classes**.\n- If the total cost exceeds $10 per class, then **he will be missed**.\n\nSo, the number of classes he can **miss** before they don't sign him up again is:\n\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Julie processes 50 customers daily. \nSince Julie operates the cash register **twice as fast** as Jewel, she processes **100 customers** daily.\n\nIf they work **all days of the week**, and there are **7 days in a week**, then:\n\n- Julie's daily production: 100 customers \n- Jewel's daily production: 50 customers \n- Total weekly production: \n $ 100 \\times 7 + 50 \\times 7 = 170 \\times 7 = 1190 $ customers\n\n**Final Answer:** $\\boxed{1190}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- **Paisley ran 4 miles.**\n- **Reggie ran 5 times what Paisley ran:** \n $ 5 \\times 4 = 20 $ miles.\n- **Reggie ran 3 miles farther than Lynn.** \n So, if Reggie's distance is 20 miles, then Lynn's distance is: \n $ 20 - 3 = 17 $ miles.\n\n### Final Answer:\n$$\n\\boxed{17}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- 4 apples = $5.20 \n- 3 oranges = $3.30\n\nWe are to find the cost for:\n\n- 5 apples = 4 apples + 1 apple = $5.20 + $1.00 = $6.20 \n- 5 oranges = 3 oranges + 2 oranges = $3.30 + $2.00 = $5.30\n\nNow, add the cost of 5 apples and 5 oranges:\n\n$$\n6.20 + 5.30 = \\boxed{11.50}\n$$\n\nClyde will pay **$11.50**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bob wants to dig a hole that is **6 feet long, 4 feet wide, and 3 feet deep**.\n\n- The volume of the hole is:\n $$\n 6 \\times 4 \\times 3 = 72 \\text{ cubic feet}\n $$\n\n- It takes Bob **3 seconds per cubic foot** to shovel the earth.\n\n- Therefore, the total time required is:\n $$\n 72 \\times 3 = 216 \\text{ seconds}\n $$\n\n**Final Answer:** $\\boxed{216}$ seconds." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Bill's truck includes:\n\n- Base price: $30,000 \n- King cab upgrade: $7,500 \n- Leather seats: $7,500 ÷ 3 = $2,500 \n- Running boards: $2,500 + $500 = $3,000 \n- Upgraded exterior light package: $1,500 \n\n**Total cost = 30,000 + 7,500 + 2,500 + 3,000 + 1,500 = 45,500**\n\n**Answer:** $\\boxed{45500}$ dollars." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tim gets a **5% raise** on his **$20,000 a month salary**, and an additional **$5,000** as a **bonus**.\n\n### Step 1: Calculate the raise\n- 5% of $20,000 = $1,000\n- New salary after raise = $20,000 + $1,000 = **$21,000**\n\n### Step 2: Add the bonus\n- Bonus = $5,000\n- Total salary = $21,000 + $5,000 = **$26,000**\n\n### Step 3: Calculate the annual salary\n- 1 year =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James buys:\n\n- 10 suits: $750 each → $750 × 10 = $7,500 \n- 10 dress pants: $1/5 of the cost of the suits → $750 × 1/5 = $150 → $150 × 10 = $1,500 \n- 3 dress shirts per suit: 3 × 10 = 30 shirts → $60 each → $60 × 30 = $1,800 \n\nTotal cost = $7,500 + $1,500 + $1,800 = **$10,800**\n\n**Answer:** $\\boxed{1" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- The first website publishes **20 political and weather articles** every day: \n $ 20 \\text{ articles/day} $\n\n- The second website publishes **10 business news articles** every day: \n $ 10 \\text{ articles/day} $\n\n- There are **28 days** in February.\n\n- Total articles published in February: \n $ 20 \\times 28 + 10 \\times 28 = 380 + 280 = \\boxed{660} $ articles." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Steve is 60 years old. His wife is 4 years older than him, so her age is:\n\n$$\n60 + 4 = 64 \\text{ years old}\n$$\n\nTheir son is currently half as old as his mom. Let the son's age be $ x $. Then:\n\n$$\nx = \\frac{1}{2} \\times \\text{Mom's age}\n$$\n\nWe don't know the mom's age yet. However, we do know that the son's age is half of the mom's age. Let's denote the mom's age as $ y $. Then:\n\n$$\nx = \\frac{1}{2}y\n$$\n\nAlso, the son's wife is 3 years younger than his husband. Steve's husband" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The total amount of flour in the bag is:\n\n$$\n8 \\text{ portions} \\times 2 \\text{ kg per portion} = 16 \\text{ kg}\n$$\n\nBefore it was divided into portions, **three bags** of flour contained:\n\n$$\n3 \\times 16 = \\boxed{48} \\text{ kg}\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{48} \\text{ kg}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Alisa biked at **12 miles per hour** for **4.5 hours**, so the distance she covered is:\n\n$$\n12 \\times 4.5 = 54 \\text{ miles}\n$$\n\nStanley biked at **10 miles per hour** for **2.5 hours**, so the distance he covered is:\n\n$$\n10 \\times 2.5 = 25 \\text{ miles}\n$$\n\nTotal distance biked:\n\n$$\n54 + 25 = \\boxed{79} \\text{ miles}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bill digs 4 feet per hour through soil and half that fast through clay, so he digs **2 feet per hour** through clay.\n\nHe needs to dig:\n\n- **24 feet of soil** \n- **8 feet of clay**\n\nSo the total time is:\n\n$$\n\\frac{24 \\text{ feet}}{4 \\text{ feet/hour}} + \\frac{8 \\text{ feet}}{2 \\text{ feet/hour}} = 6 \\text{ hours} + 4 \\text{ hours} = \\boxed{10} \\text{ hours}\n$$\n\n**Answer:** $\\boxed{10}$ hours." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Howie wants to buy cupcakes for himself, his teacher, and his 25 classmates. He gets **one of each** for everyone.\n\n- He gets **1 cupcake** for himself.\n- His teacher gets **1 cupcake**.\n- His 25 classmates get **1 cupcake each**.\n\nSo, the total number of cupcakes is:\n\n$$\n1 + 1 + 25 = 27\n$$\n\n**Answer:** $\\boxed{27}$ cupcakes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the initial number of likes as $ x $.\n\n- After 1 week, the number of likes is $ x + 2000 $.\n- After 3 weeks, the number of likes is $ x + 2000 + 70x = 71x $.\n\nWe are told that the number of likes after 3 weeks is 70 times the initial number of likes:\n\n$$\n71x = 70x\n$$\n\nThis implies:\n\n$$\nx = 0\n$$\n\nBut this can't be correct, since the number of likes can't be zero. So, there must be a mistake in the setup.\n\nLet’s re-express the problem:\n\n- After 1 week: $ x + 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Clara bought 20 pomegranates at $20 each on Tuesday. She got a $2 discount, so the price was:\n\n$$\n20 \\times 20 - 2 = 400 - 2 = 398\n$$\n\nSheila bought 20 pomegranates at the discounted price of $30 each on the next day. The total cost for Sheila was:\n\n$$\n30 \\times 20 = 600\n$$\n\nNow, the store also offered a 10% discount on the total cost. So the final price for Sheila was:\n\n$$\n600 \\times (1 - 0.10) = 600 \\times 0.90 =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ R $ be the total sales from red hats in the first month.\n- Let $ G $ be the total sales from green hats in the first month.\n\nFrom the problem:\n\n- Sales from red hats in the first month: $ R = 400 $\n- Sales from green hats in the first month: $ G = \\frac{R}{2} = \\frac{400}{2} = 200 $\n\nIn the second month:\n\n- Sales from red hats: $ \\frac{3}{4}R = \\frac{3}{4} \\times 400 = 300 $\n- Sales from green hats: $ \\frac{1}{2}G = \\frac{1}{2" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James hires a horse-drawn carriage from **5 PM to 9 PM**, which is **2 hours**. He gets **1 hour free**.\n\n- The **first paid hour** is $15.\n- Each hour after that is **twice the cost** of the first hour.\n\nSo, the total cost is:\n\n$$\n15 + 2 \\times 15 = 15 + 30 = \\boxed{45}\n$$\n\n**Answer:** $\\boxed{45}$ dollars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sally's bank account increased from $200 to $420, so she received:\n\n$$\n420 - 200 = 220\n$$\n\nThis $220 is the amount she received from her employer.\n\nHer weekly wage should be $300, so the amount withheld is:\n\n$$\n300 - 220 = \\boxed{80}\n$$\n\n**Answer:** $\\boxed{80}$ dollars were withheld from Sally’s wage." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Lori needs **1 whole egg** to make **2 deviled egg halves**. \nSo, she needs **1 egg per 2 deviled egg halves**.\n\nShe is inviting **16 guests**, and each guest will eat **3 deviled egg halves**.\n\nLet's calculate the total number of deviled egg halves needed:\n\n$$\n16 \\text{ guests} \\times 3 \\text{ deviled egg halves per guest} = 48 \\text{ deviled egg halves}\n$$\n\nNow, since she needs **1 egg per 2 deviled egg halves**, the number of eggs required is:\n\n$$\n48 \\div 2 = 24 \\text{ eggs}\n$$\n\nSince **1 dozen = 12 eggs**, the number" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Shiela has written $ \\frac{1}{3} $ of a 15-page paper, which is:\n\n$$\n\\frac{1}{3} \\times 15 = 5 \\text{ pages}\n$$\n\nShe has **5 pages left** to write.\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mike reads **10 pages per day** for **30 days**, and the book is **200 pages**.\n\nSo, the number of days Mike will finish the reading is:\n\n$$\n\\frac{200}{10} = 20 \\text{ days}\n$$\n\nTherefore, **Mike will finish the reading 20 days before the deadline**.\n\n$$\n\\boxed{20}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James pays:\n\n- $5000 per month for rent \n- $10,000 per month for fuel (twice the rent)\n\nSo, per month, he spends:\n\n$$\n5000 + 10000 = 15000\n$$\n\nFor the **first year**, he pays:\n\n$$\n15000 \\times 12 = 180,000\n$$\n\n### Final Answer:\n$$\n\\boxed{180000}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break it down step by step:\n\n- It took **30 minutes** to cook rice.\n- It took **20 more minutes** to cook pork than rice, so pork took $ 30 + 20 = 50 $ minutes.\n- The time for **beans** is **half the combined cooking time** of pork and rice. \n So, beans took $ \\frac{50 + 30}{2} = \\frac{80}{2} = 40 $ minutes.\n\nNow, add up the times for all the food:\n\n- Rice: 30 minutes \n- Pork: 50 minutes \n- Beans: 40 minutes \n\nTotal time = $ 30 + 50 + 40 =" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- Cost of 1 pound of almonds: $10 \n- Cost of 1 pound of walnuts: $15\n\nWe are asked to find how much more it costs for a **mixture of 1/2 pound almonds and 1/3 pound walnuts** compared to a **mixture of 1/5 pound almonds and 1/3 pound walnuts**.\n\n---\n\n### Step 1: Cost of the first mixture\n\n- Almonds: $ \\frac{1}{2} \\times 10 = 5 $\n- Walnuts: $ \\frac{1}{3} \\times 15 = 5 $\n- Total cost: $ 5 + 5 = \\boxed{10} $\n\n---\n\n### Step" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total number of animal legs = 70 \n- Total number of animal heads = 20\n\nLet:\n- $ s $ = number of sheep \n- $ g $ = number of geese\n\nWe know:\n- Each sheep has 4 legs \n- Each goose has 2 legs \n- Each sheep has 1 head \n- Each goose has 1 head\n\nSo:\n$$\n4s + 2g = 70 \\quad \\text{(1)}\n$$\n$$\ns + g = 20 \\quad \\text{(2)}\n$$\n\nFrom equation (2), we can express $ g = 20 - s $.\n\nSubstitute into equation (1):\n$$\n4s + 2(20 - s" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Roger buys coffee for a week, which is 7 days. He uses 1 pound of coffee per day, so he buys:\n\n$$\n7 \\text{ pounds of coffee}\n$$\n\nHe also buys a donut for $2.\n\nThe cost of the coffee is:\n\n$$\n5 \\text{ dollars per pound} \\times 7 \\text{ pounds} = 35 \\text{ dollars}\n$$\n\nSo the total cost is:\n\n$$\n35 \\text{ dollars (coffee)} + 2 \\text{ dollars (donut)} = \\boxed{37} \\text{ dollars}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gus spent:\n\n- $2.00 on bag of chips (2 x $2.00) = $4.00 \n- $8.00 on bucket of fried chicken \n- $1.00 on bottle of soda \n\nTotal spent: \n$4.00 + $8.00 + $1.00 = $13.00 \n\nHe spent $20.00 in total, so the cost of the apple pie is: \n$20.00 - $13.00 = **$7.00**\n\n$$\n\\boxed{7}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James delivers:\n\n- 600 newspapers in a day,\n- 198 newspapers to District A,\n- 209 newspapers to District C.\n\nTo find the number of newspapers delivered to **District B**, subtract the known quantities from the total:\n\n$$\n600 - 198 - 209 = \\boxed{193}\n$$\n\n**Answer:** $\\boxed{193}$ newspapers." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John takes a cooking class 4 times a week, 2 hours each time, for 6 weeks. \nHe learns a new recipe for every 1.5 hours of class time.\n\n### Step 1: Calculate total class time\n- 4 times a week × 2 hours = 8 hours per week \n- Over 6 weeks = 8 hours/week × 6 weeks = **48 hours**\n\n### Step 2: Calculate total recipe time\n- 48 hours × (1.5 hours/recipe) = **72 recipes**\n\n### Final Answer:\n$$\n\\boxed{72}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Total number of teachers on the school basketball court: $150$\n- 60% of them are history teachers: \n $0.60 \\times 150 = 90$ teachers\n- The rest are math teachers: \n $150 - 90 = 60$ teachers\n\nEach teacher sleeps for **6 hours a day**.\n\nSo, the total time the math teachers spend sleeping in one day is: \n$$\n60 \\text{ teachers} \\times 6 \\text{ hours/day} = 360 \\text{ hours}$$\n\n### Final Answer:\n$$\n\\boxed{360}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Define variables\n\nLet:\n- $ A $ = amount Arelia has = $120\n- $ K $ = amount Kassidy has\n- $ R $ = amount Rayna has\n\n---\n\n### Step 2: Use the given information\n\n1. **Rayna has 60 more dollars than Kassidy**:\n $$\n R = K + 60\n $$\n\n2. **Kassidy has $ \\frac{3}{4} $ times as much money as Arelia**:\n $$\n K = \\frac{3}{4}A = \\frac{3}{4} \\times 120 = 90\n " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah’s basketball games are 4 quarters, each 12 minutes long. However, in the last quarter, there was a tie, which extended the game for an additional **5 minutes**.\n\n- 4 quarters × 12 minutes = 48 minutes \n- Last quarter extended by 5 minutes = 48 + 5 = **53 minutes**\n\n**Answer:** $\\boxed{53}$ minutes." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Total employees = 50 \n- 20% of employees are management → 20% of 50 = 10 \n- Out of this 10 management employees, 30% oversee the entire company → 30% of 10 = 3 \n\nSo, the number of employees who oversee the company is:\n\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Svetlana needs:\n- 5 tablespoons of flour per muffin\n- 3 tablespoons of sugar per muffin\n- 0.25 tablespoons of salt per muffin\n\nSo, for **16 muffins**, the total amount of dry ingredients is:\n\n$$\n16 \\times (5 + 3 + 0.25) = 16 \\times 8.25 = 132 \\text{ tablespoons}\n$$\n\n**Final Answer:** $\\boxed{132}$ tablespoons." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Robert had 3 pounds of candy, Cindy had 5 pounds, and Aaron had 4 pounds. They pool and share their candy equally.\n\n- Total candy = 3 + 5 + 4 = **12 pounds**\n- Each person gets 12 ÷ 3 = **4 pounds**\n\n**Answer:** Each person would have **4 pounds** of candy." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Adam bought:\n- 7 candies of type A: $ 7 \\times 0.5 = 3.5 $\n- 10 candies of type B: $ 10 \\times 0.75 = 7.5 $\n\nTotal cost: \n$ 3.5 + 7.5 = 11 $\n\nHe paid the cashier $15. \nSo, the change is: \n$ 15 - 11 = \\boxed{4} $." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Christina's moods over the past 30 days are as follows:\n\n- 12 good days \n- 8 bad days \n- 10 neutral days (since 12 + 8 = 20, and 30 - 20 = 10)\n\nShe has already recorded:\n\n- 8 good days (first 8 days) \n- 8 bad days (next 8 days) \n- 10 neutral days (last 10 days)\n\nNow, the next 3 days are:\n\n- Good \n- Neutral \n- Good\n\nSo, the total number of good days so far is:\n\n- 8 (first 8) + 2 (next 3) = **10 good days**\n\nThe number of good" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let $ S $ represent the number of books Sally has.\n\nJaney has 3 more than twice the number of books that Sally has, so:\n\n$$\n\\text{Janey's books} = 2S + 3\n$$\n\nWe are told that Janey has 21 books:\n\n$$\n2S + 3 = 21\n$$\n\nSubtract 3 from both sides:\n\n$$\n2S = 18\n$$\n\nDivide by 2:\n\n$$\nS = 9\n$$\n\n### Final Answer:\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Growth rate: 30 inches per day \n- Current height: 20 feet \n- Final height: 600 inches \n\nFirst, convert 20 feet to inches: \n$$ 20 \\text{ feet} = 20 \\times 12 = 240 \\text{ inches} $$\n\nNow, the bamboo is currently 240 inches tall, and it grows at 30 inches per day. We need to find how many days it will take to grow from 240 inches to 600 inches.\n\nLet $ x $ be the number of days. Then:\n\n$$\n30x = 600 - 240 = 360\n$$\n\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n1. **Initial state**: James has 4 toys for 4 dogs. \n So, each dog gets **1 toy**.\n\n2. **Shelter has 8 more dogs**: \n So, now there are **4 + 8 = 12 dogs** in the shelter.\n\n3. **After buying toys**: \n James now has **4 + 8 = 12 toys** for 12 dogs.\n\n4. **When he comes back**, 3 dogs are gone, so he no longer needs those toys. \n So, he now has **12 - 3 = 9 toys**.\n\n5. **Total toys needed**: \n James has 9 toys in total.\n\n**Answer" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n1. The total amount invested is $1200.\n\n2. Dylan invested $ \\frac{2}{5} $ of the total amount:\n $$\n \\frac{2}{5} \\times 1200 = 480\n $$\n\n3. The remaining amount after Dylan's investment is:\n $$\n 1200 - 480 = 720\n $$\n\n4. Frances invested $ \\frac{2}{3} $ of the remaining amount:\n $$\n \\frac{2}{3} \\times 720 = 480\n $$\n\n5. The remaining amount after Frances's investment is:\n $$\n " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Carol has 20 signatures, and Jennifer has 44. Together, they have:\n\n$$\n20 + 44 = 64 \\text{ signatures}\n$$\n\nThey want to reach **100 signatures** by the end of the summer. So, they need:\n\n$$\n100 - 64 = 36 \\text{ signatures}\n$$\n\n**Answer:** $\\boxed{36}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Lorie earns $10 per hour, so Karen earns:\n\n$$\n2 \\times 10 = 20 \\text{ dollars per hour}\n$$\n\nShe works 3 hours per day, so her daily earnings are:\n\n$$\n20 \\times 3 = 60 \\text{ dollars per day}\n$$\n\nIn two days, her earnings are:\n\n$$\n60 \\times 2 = \\boxed{120} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{120}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given that **6 potatoes make 36 hash browks**.\n\nSo, the ratio of potatoes to hash browks is:\n\n$$\n\\frac{6 \\text{ potatoes}}{36 \\text{ hash browks}} = \\frac{1}{6}\n$$\n\nNow, we want to find how many hash browks can be made from **96 potatoes**.\n\nWe can set up a proportion:\n\n$$\n\\frac{6 \\text{ potatoes}}{36 \\text{ hash browks}} = \\frac{96 \\text{ potatoes}}{x \\text{ hash browks}}\n$$\n\nSolving for $ x $:\n\n$$\n\\frac{6}{36} = \\frac{96}{x}\n$$\n\n$$\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The elevator can support a maximum load of **700 kg**.\n\n- An adult weighs an average of **80 kg**.\n- Jack rides the elevator with **8 other adults**.\n\nSo, the total weight is:\n\n$$\n8 \\times 80 = 640 \\text{ kg}\n$$\n\nSince the elevator can only support **700 kg**, the total weight will **exceed** the maximum load by:\n\n$$\n700 - 640 = 60 \\text{ kg}\n$$\n\n---\n\n**Final Answer:** $\\boxed{60}$ kg." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\nWe are told:\n\n- **Katarina has 5 less cookies than Max**.\n- **Max has 12 more cookies than the Cookie Monster**.\n- **Summer has 23 more cookies than Max**.\n- **Katarina has 68 cookies**.\n\nLet’s define:\n\n- Let $ M $ be the number of cookies Max has.\n- Then, **Katarina has $ M - 5 $**.\n- **Max has $ M + 12 $** (since he has 12 more than the Cookie Monster).\n- **Summer has $ M + 23 $**.\n\nWe are told that **Katarina has 68 cookies**, so:\n\n$$\nM - " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the original length of the dress in centimeters.\n\n- She extends the dress by 50% of its original length: \n $ 0.5x $\n\n- She adds 20 cm to the bottom of the dress: \n $ 20 \\, \\text{cm} $\n\n- The final design is 140 cm long: \n $ x + 0.5x + 20 = 140 $\n\nSimplify: \n$ 1.5x + 20 = 140 $\n\nSubtract 20: \n$ 1.5x = 120 $\n\nDivide by 1.5: \n$ x = 80 $\n\n### Final Answer: \n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ x $ be the time in minutes it takes to mow the entire lawn in **turtle mode**.\n- Let $ y $ be the time in minutes it takes to mow the entire lawn in **rabbit mode**.\n\nFrom the problem:\n\n- In 1 hour (60 minutes), he can mow the entire lawn in **turtle mode**, so:\n $$\n x = 60\n $$\n\n- In 40 minutes, he can mow the entire lawn in **rabbit mode**, so:\n $$\n y = 40\n $$\n\nHe experimented by mowing **half** in **turtle mode** and **half** in **rabbit mode**.\n\nSo, the total time is:\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John and Jack have **30 minutes** to walk to school together. They arrive at the **corner where the library is** in **6 minutes**, and then **another 13 minutes** to get to the **fire station**. \n\nSo, the total time they spend walking to the library and the fire station is:\n\n$$\n6 + 13 = 19 \\text{ minutes}\n$$\n\nThey have **30 minutes** to walk to school, so the time they have **left** to get to school without being late is:\n\n$$\n30 - 19 = 11 \\text{ minutes}\n$$\n\n### Final Answer:\n$$\n\\boxed{11}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Catherine buys:\n\n- 1 kilo of apples for $4 \n- 2 kilos of bananas for $2 per kilo → $2 × 2 = $4 \n- 2 kilos of oranges for $3 per kilo → $3 × 2 = $6 \n\nTotal cost = $4 + $4 + $6 = **$14**\n\n**Answer:** $\\boxed{14}$ dollars." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Greta bakes **30** cookies.\n\nCelinda bakes **twice as many** as Greta, so:\n\n$$\n30 \\times 2 = 60 \\text{ cookies}\n$$\n\nThey eat **10** of the cookies while cooling, so the number of cookies in the box is:\n\n$$\n60 - 10 = \\boxed{50}\n$$\n\n**Answer:** $\\boxed{50}$ cookies." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let the age of one triplet be $ x $ years. Since one twin is 7 years older than one triplet, the age of the twin is $ x + 7 $.\n\nThe combined ages of the twins and triplets are:\n\n$$\n(x + 7) + x = 44\n$$\n\n$$\n2x + 7 = 44\n$$\n\n$$\n2x = 37\n$$\n\n$$\nx = \\frac{37}{2} = 18.5\n$$\n\nSo, the age of one of the twins is:\n\n$$\nx + 7 = 18.5 + 7 = 25.5\n$$\n\n**Final Answer:** $\\boxed{25.5}$ years." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John has 20 minutes of math homework, 40 minutes of reading homework, and 20 minutes of history homework. He also has 3 hours before dinner.\n\nFirst, convert 3 hours to minutes: \n$$ 3 \\text{ hours} = 3 \\times 60 = 180 \\text{ minutes} $$\n\nNow, add the time he has to do homework: \n$$ 20 + 40 + 20 = 80 \\text{ minutes} $$\n\nHe has 180 minutes before dinner. So, the time he has to nap is: \n$$ 180 - 80 = 100 \\text{ minutes} $$\n\n**Final Answer:** $\\boxed{10" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Manolo bought:\n\n- 5 lollipops at $0.40 each: \n $ 5 \\times 0.40 = 2.00 $\n\n- 4 candies at $3.20 each: \n $ 4 \\times 3.20 = 12.80 $\n\nTotal cost: \n$ 2.00 + 12.80 = 14.80 $\n\nNow, he wants to buy 10 lollipops and 10 candies:\n\n- 10 lollipops: $ 10 \\times 0.40 = 4.00 $\n\n- 10 candies: $ 10 \\times 3.20 = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Rong saves **20 coins** per month.\n\nNeil saves **2/5 times more** coins than Rong per month. \nSo, Neil saves: \n$$\n20 \\times \\left(1 + \\frac{2}{5}\\right) = 20 \\times \\frac{7}{5} = 28 \\text{ coins per month}\n$$\n\nAfter **10 years**, there are $10 \\times 12 = 120$ months. \nSo, the total number of coins saved by both is: \n$$\n20 \\times 120 + 28 \\times 120 = (20 + 28) \\times 120 = 48 \\times " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John brings his dog to the vet. The total cost includes:\n\n- 2 vaccines at $20 each: $2 \\times 20 = 40\n- A heartworm check: $60\\%$ of the total bill = $0.60 \\times (40 + 60) = 0.60 \\times 100 = 60\n\nSo, the total bill is:\n\n$$\n40 + 60 = 100\n$$\n\nHe brings $125 with him, so he leaves:\n\n$$\n125 - 100 = \\boxed{25}\n$$\n\n**Answer:** $\\boxed{25}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- A crate contains:\n - 5 bananas\n - 12 apples\n - 7 oranges\n\n- The price of each fruit depends on the price of its individual items:\n - 1 apple = $0.5\n - 1 banana = $2 (twice the price of an apple)\n - 1 orange = 3 times the price of a banana\n\nLet's calculate the price of the crate:\n\n1. **Price of 1 banana**: \n $ 2 \\times 0.5 = 1 $\n\n2. **Price of 1 apple**: \n $ 0.5 $\n\n3. **Price of 1 orange**: \n $ 3 \\times 1 = 3 $\n\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given the number of colored squares in Brittany's comforter:\n\n- Red squares: 14 \n- Blue squares: 14 + 4 = 18 \n- Green squares: 18 + 6 = 24 \n- White squares: 24 - 12 = 12 \n\nNow, we calculate the total area in square feet:\n\n$$\n14 + 18 + 24 + 12 = 68 \\text{ square feet}\n$$\n\n**Final Answer:** $\\boxed{68}$ square feet." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **42 adults** and **15 babies**.\n- The restaurant has **5 times as many regular chairs as high chairs**.\n- There are **8 high chairs**.\n\nLet’s solve this step by step.\n\n---\n\n### Step 1: Find the number of **regular chairs**\n\nLet the number of **high chairs** be **8**.\n\nThen, the number of **regular chairs** is:\n\n$$\n5 \\times 8 = 40\n$$\n\n---\n\n### Step 2: Find the total number of chairs\n\n$$\n\\text{Total chairs} = \\text{High chairs} + \\text{Regular chairs} = 8 + 40 = 48\n$$\n\n---\n\n### Step 3: Find" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 50 deer in the field.\n\n- 50% of the deer are **bucks**: \n $ 0.50 \\times 50 = 25 $ bucks.\n\n- 20% of the bucks are **8 points**: \n $ 0.20 \\times 25 = 5 $.\n\n**Answer:** $\\boxed{5}$ 8-point bucks." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- Adam has collected **50 points**.\n- Betty was **30% more** than Adam, so:\n $$\n \\text{Betty's points} = 50 + 0.30 \\times 50 = 50 + 15 = 65\n $$\n- Marta collected **3 times more** than Tom, and Tom has **30 points less** than Betty. So:\n $$\n \\text{Tom's points} = 65 - 30 = 35\n $$\n $$\n \\text{Marta's points} = 3 \\times 35 = 105\n $$\n\nNow, the total points" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Great Grandma Jones has:\n\n- 3 children \n- Each child has 3 grandchildren → 3 × 3 = 9 grandchildren \n- Each of these grandchildren has 3 babies → 9 × 3 = 27 great grand-babies\n\nSo, the total number of great grand-babies is:\n\n$$\n\\boxed{27}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Greta's total paycheck is $2400.00.\n\n- She puts **50%** of her pay into her retirement account:\n $$\n 0.5 \\times 2400 = 1200\n $$\n\n- She uses **20%** of her paycheck to make her monthly car payment:\n $$\n 0.2 \\times 2400 = 480\n $$\n\n- After funding her retirement and car payment, the remaining amount is:\n $$\n 2400 - 1200 - 480 = 720\n $$\n\n**Answer:** $\\boxed{720}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 20 pencils in the box, and 4 are missing.\n\nSo, the number of pencils in the box is:\n\n$$\n20 - 4 = 16\n$$\n\nNow, we need to find how many **pairs** of pencils are in the box.\n\nEach pair consists of 2 pencils.\n\nSo, the number of pairs is:\n\n$$\n\\frac{16}{2} = 8\n$$\n\n### Final Answer:\n$$\n\\boxed{8}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Hannah's city has 15 boxes of 20 fireworks each: \n$$\n15 \\times 20 = 300 \\text{ fireworks}\n$$\n\nHannah's house is at a right angle to see **40%** of the city's fireworks: \n$$\n0.40 \\times 300 = 120 \\text{ fireworks}\n$$\n\nHannah also sets off 3 boxes of 5 fireworks each: \n$$\n3 \\times 5 = 15 \\text{ fireworks}\n$$\n\nNow, add the fireworks she sees from the city and her backyard: \n$$\n120 + 15 = \\boxed{135}\n$$\n\n**Answer:** $\\boxed{13" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Aiden and 12 of his friends = 13 people.\n\nThey meet up with 7 more friends = 13 + 7 = 20 people.\n\nEach seat can hold **1 person + 2 drinks + 3 snacks** = **6 units**.\n\nSo, the total number of seats needed is:\n\n$$\n20 \\text{ seats}\n$$\n\nEach seat costs **$2** for drinks and snacks.\n\nTotal cost = $2 \\times 20 = \\boxed{40}$." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the amount of gravel that Gissela’s truck can haul as $ x $ pounds.\n\n- Gissela’s truck: $ x $ pounds\n- Gordy’s truck: $ x + 800 $ pounds (since it can haul 800 pounds more than Gissela’s)\n- Gary’s truck: $ y $ pounds\n\nWe are told that the total amount of gravel that the three trucks can haul is 11,600 pounds:\n\n$$\nx + (x + 800) + y = 11,600\n$$\n\nSimplify:\n\n$$\n2x + 800 + y = 11,600\n$$\n\nNow, we need to find $ y $," + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Each female ate **3 dumplings**, and there are **6 females**. \nSo, each female ate **3 dumplings**, and there are **6 females**, so the total number of dumplings eaten by females is:\n\n$$\n6 \\times 3 = 18 \\text{ dumplings}\n$$\n\nEach male ate **1 more dumpling** than each female, so each male ate:\n\n$$\n3 + 1 = 4 \\text{ dumplings}\n$$\n\nThere are **8 males**, so the total number of dumplings eaten by males is:\n\n$$\n8 \\times 4 = 32 \\text{ dumplings}\n$$\n\nNow, the total number of dumplings is:\n\n$$\n18 + 32 = 50 \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gerald and Julia divided $100 in the ratio 3:2. \nSo, the total parts = 3 + 2 = 5.\n\nGerald's share = $ \\frac{3}{5} \\times 100 = 60 $.\n\nGerald spent $10 on a book, so he has:\n\n$$\n60 - 10 = \\boxed{50}\n$$\n\n**Answer:** $\\boxed{50}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Martha's cat is 5 times faster than her turtle. \n- The cat's speed is 15 feet per second. \n- So, the turtle's speed is: \n $$\n \\frac{15 \\text{ feet/second}}{5} = 3 \\text{ feet/second}\n $$\n\nNow, the turtle crawls for 40 seconds: \n$$\n3 \\text{ feet/second} \\times 40 \\text{ seconds} = 120 \\text{ feet}\n$$\n\n**Final Answer:** $\\boxed{120}$ feet." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- The goal is to raise **$6300**.\n- After **3 hours**, they have raised **$2100**.\n- They raise **an equal amount per hour**.\n\nLet’s find the amount raised per hour:\n\n$$\n\\text{Amount per hour} = \\frac{6300 - 2100}{3} = \\frac{4200}{3} = 1400\n$$\n\nNow, to reach the goal of **$6300**, they need:\n\n$$\n\\frac{6300 - 2100}{1400} = \\frac{4200}{1400} = 3 \\text{ hours" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break it down step by step:\n\n- Colorado City uses **40%** of the **total water** from the Colorado River.\n- Out of that 40%, **80%** is used for **industrial purposes**.\n- Therefore, the remaining **20%** of the river's total water is used for **non-industrial purposes**.\n\nSo, the answer is:\n\n$$\n\\boxed{20\\%}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Alex charges $12 per day. \nFor 2 weeks, there are $2 \\times 7 = 14$ days.\n\nSo, the total amount she charges for 2 weeks is:\n\n$$\n14 \\times 12 = \\boxed{168}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 100 quarts of chocolate ice cream in 2 hours.\n- 50 quarts of vanilla ice cream in 4 hours.\n\nWe are asked to find how many quarts in total would be made in **48 hours**.\n\n### Step 1: Find the rate of chocolate ice cream per hour\n\n$$\n\\text{Rate of chocolate ice cream} = \\frac{100 \\text{ quarts}}{2 \\text{ hours}} = 50 \\text{ quarts/hour}\n$$\n\n### Step 2: Find the rate of vanilla ice cream per hour\n\n$$\n\\text{Rate of vanilla ice cream} = \\frac{50 \\text{ quarts}}{4 \\text{ hours" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Marcus ordered:\n\n- 5 croissants at $3.00 each: $5 × $3.00 = **$15.00**\n- 4 cinnamon rolls at $2.50 each: $4 × $2.50 = **$10.00**\n- 3 mini quiches at $4.00 each: $3 × $4.00 = **$12.00**\n- 13 blueberry muffins at $1.00 each: $13 × $1.00 = **$13.00**\n\n**Total cost before loyalty card discount:** \n$15.00 + $10.00 + $12.00 +" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Erin has $6.00, and each scoop costs $1.50. She gets 1 free for every 2 scoops.\n\nSo, we can divide $6.00 by $1.50 to find out how many scoops she can buy:\n\n$$\n\\frac{6.00}{1.50} = 4\n$$\n\nSo, Erin should buy **4 scoops** of ice cream. \n\n$$\n\\boxed{4}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ginger eats 4 pieces a day, and Amy eats 3 pieces a day.\n\n- **Initial candy**: 100 pieces each\n- **Daily consumption**: 4 pieces for Ginger, 3 for Amy\n- **After 2 weeks** (14 days):\n\n**Ginger's total candy**: \n100 pieces/day × 14 days = 1400 pieces\n\n**Amy's total candy**: \n100 pieces/day × 14 days = 1400 pieces\n\n**Difference**: \n1400 - 1400 = 0\n\n**Answer**: $\\boxed{0}$ pieces." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Boarden needs to cover **two-thirds** of his **36 sq ft** bathroom.\n\n- Two-thirds of 36 is: \n $$\n \\frac{2}{3} \\times 36 = 24 \\text{ sq ft}\n $$\n\n- Since he needs **24 mosaic tiles per square foot**, the total number of tiles is: \n $$\n 24 \\times 24 = \\boxed{576}\n $$\n\n**Answer:** $\\boxed{576}$ mosaic tiles." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James picks blueberries:\n\n- **Cost to pick**: $20 \n- **Cost per pound**: $1.5 \n- **Picked**: 30 pounds \n\n### Step 1: Total cost to pick 30 pounds \n$$\n20 + 1.5 \\times 30 = 20 + 45 = 65\n$$\n\n### Step 2: Total cost if buying at the store for $2.5 per pound \n$$\n2.5 \\times 30 = 75\n$$\n\n### Step 3: Savings \n$$\n75 - 65 = 10\n$$\n\n### Final Answer: \n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- The company wanted to buy **500 computers**.\n- They had **$700** for each computer.\n- However, the **price of each computer was 10% higher** than planned.\n\n### Step 1: Calculate the original cost of 500 computers\n$$\n500 \\times 700 = 350,000\n$$\n\n### Step 2: Calculate the new price per computer\nThe price increased by 10%, so the new price is:\n$$\n700 \\times (1 + 0.10) = 700 \\times 1.10 = 770\n$$\n\n### Step 3:" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John makes a 6-egg omelet with:\n\n- 2 oz of cheese \n- 2 oz of ham \n\nEggs are 75 calories each, cheese is 120 calories per ounce, and ham is 40 calories per ounce.\n\nSo, the total calories are:\n\n- Calories from eggs: $ 6 \\times 75 = 450 $ calories \n- Calories from cheese: $ 2 \\times 120 = 240 $ calories \n- Calories from ham: $ 2 \\times 40 = 80 $ calories \n\nTotal calories = $ 450 + 240 + 80 = \\boxed{770} $ calories." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Cost of 1 pencil = $0.50 \n- Cost of 1 eraser = $0.25 \n- Number of pencils = 6 \n- Number of erasers = 8 \n- Total amount paid = $10 \n\n### Step 1: Calculate total cost of pencils and erasers\n\n- Cost of pencils: \n $ 6 \\times 0.50 = 3.00 $\n\n- Cost of erasers: \n $ 8 \\times 0.25 = 2.00 $\n\n- Total cost: \n $ 3.00 + 2.00 = 5.00 $\n\n### Step 2: Calculate change\n\n- Total amount paid: $1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- 100 people apply for a job at Google.\n- 30% of the applicants receive interviews.\n- 20% of those who receive interviews get a job offer.\n- 1/3 of those who get a job offer accept the position.\n\nLet's calculate the number of people who accept the position step by step.\n\n1. **Number of people who receive interviews**:\n $$\n 30\\% \\text{ of } 100 = 0.30 \\times 100 = 30\n $$\n\n2. **Number of people who get a job offer**:\n $$\n 20\\% \\text{ of } 30 = 0.2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Goldy bought 20 sacks of rice. She gave 3 to her cousin and 4 to her brother. \nTotal sacks given = $3 + 4 = 7$ sacks. \nTotal rice given = $7 \\times 25 = 175$ kilograms. \n\n**Answer:** $\\boxed{175}$ kilograms." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Castle bought:\n\n- 3 boxes of Coco Crunch \n- 5 boxes of Fruit Loops \n- 4 boxes of cereal this week\n\nSo, the total boxes she bought this week is:\n\n$$\n3 + 5 + 4 = 12 \\text{ boxes}\n$$\n\nLast week, she bought 4 boxes of cereal.\n\nThe difference in the number of cereal boxes she bought this week compared to last week is:\n\n$$\n12 - 4 = 8\n$$\n\n**Answer:** $\\boxed{8}$ boxes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Helga taps both feet at different rates depending on whether she is raising her arms or not.\n\n- **When she raises her arms (2 minutes):** \n - Right foot: 200 taps/min \n - Left foot: 200 taps/min \n - **Total taps per minute:** 400 taps\n\n- **When she doesn't raise her arms (3 minutes):** \n - Right foot: 300 taps/min \n - Left foot: 250 taps/min \n - **Total taps per minute:** 550 taps\n\nWe need to find the **combined total number of taps** she makes in 5 minutes.\n\n- **Total taps in 2 minutes (arms raised):** \n $ 2" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ron will save:\n\n- $450 in damage to his car.\n- $120 in fines for unauthorized road maintenance.\n- $3 buckets × $25 = $75 in asphalt cost.\n\nSo, total money saved is:\n\n$$\n450 + 120 + 75 = \\boxed{645}\n$$\n\nRon saves **$645** by fixing the pothole." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The restaurant has:\n\n- 170 normal chairs \n- 23 baby chairs\n\n**Total chairs initially:** \n$ 170 + 23 = 193 $ chairs\n\n**Chairs sent to the carpenter:** \n- 20 normal chairs \n- 13 baby chairs\n\n**Total chairs sent:** \n$ 20 + 13 = 33 $ chairs\n\n**Chairs remaining:** \n$ 193 - 33 = \\boxed{160} $ chairs." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bryce and four of his friends ordered their pizzas. Each pizza had 12 slices. So:\n\n- Total number of pizzas = 5 (Bryce + 4 friends)\n- Total slices = $ 5 \\times 12 = 60 $ slices\n\nBryce and two friends ate $ \\frac{2}{3} $ of their pizzas. \n- Number of pizzas eaten by them = $ 2 $ pizzas \n- Number of slices eaten by them = $ 2 \\times 12 = 24 $ slices\n\nThe remaining two friends ate $ \\frac{3}{4} $ of their pizzas. \n- Number of pizzas eaten by them = $ 2 $ pizzas \n- Number of slices eaten by them = $ 2" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Understand the given information\n\n- A **cat** eats **9 sausages** in **30 minutes**.\n- A **dog** eats the **same number of sausages** in **$ \\frac{2}{3} $** the time the cat takes.\n\n---\n\n### Step 2: Find the rate of eating\n\n- **Cat's rate**: \n $$\n \\frac{9 \\text{ sausages}}{30 \\text{ minutes}} = \\frac{3}{10} \\text{ sausages per minute}\n $$\n\n- **Dog's rate**: \n $$\n \\frac{9 \\text{ sausages}}{30" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- The length of one of Topher’s shoes is **8 feet 4 inches**.\n- The length of one of Topher’s shoes is **10 inches longer than 9 times the length of one of Bobby’s shoes**.\n\nLet’s denote the length of one of Bobby’s shoes in inches as $ x $.\n\nThen:\n\n$$\n8\\text{ ft} + 4\\text{ in} = 9x + 10\n$$\n\nConvert 8 feet 4 inches to inches:\n\n$$\n8 \\times 12 + 4 = 96 + 4 = 100 \\text{ inches}\n$$\n\nSo:\n\n$$\n100 = 9x + 10\n$$\n\nSubtract" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Hannah smashes:\n\n- $ \\frac{1}{4} \\times 64 = 16 $ windows from the students' cars.\n\n- $ \\frac{3}{4} \\times 32 = 24 $ windows from the teachers' cars.\n\nSo, the total number of windows she smashes is:\n\n$$\n16 + 24 = \\boxed{40}\n$$\n\nHannah smashes **40 windows**." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Candy has:\n\n- 15 light blue spools \n- 45 dark blue spools \n- 40 light green spools \n- 50 dark green spools \n\nTotal spools = $15 + 45 + 40 + 50 = 150$\n\nPercent of blue spools = $\\frac{15 + 45}{150} \\times 100 = \\frac{60}{150} \\times 100 = 40\\%$\n\n**Answer:** $\\boxed{40\\%}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- At 8:00, 5000 people lined up.\n- By **midday 2/5** of the people had voted.\n- By **16:00** (which is **2/5** of the day), **2/3** of the remaining people had voted.\n\nLet’s break it down step by step.\n\n---\n\n### Step 1: Total number of people at 8:00\n\n- 5000 people lined up.\n\n---\n\n### Step 2: At 8:00, 2/5 of the people had voted\n\n$$\n\\frac{2}{5} \\times 5000 = 2000 \\text{ people}\n$$\n\nSo," + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Parker chews 4 pieces of gum a day.\n\n- 1 pack = 15 pieces\n- 30 days = 30 × 15 = 450 pieces\n\nParker needs **450 pieces** of gum.\n\nSo, the number of packs he needs is:\n\n$$\n\\frac{450}{15} = 30\n$$\n\n**Final Answer:** $\\boxed{30}$ packs." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Each sleeve of Graham crackers makes the base for 8 large smores.\n\n- There are 3 sleeves in a box.\n- Each sleeve makes 8 smores.\n- So, 3 sleeves = $ 3 \\times 8 = 24 $ smores.\n\nNow, the problem says:\n\n- 9 kids want 2 smores each = $ 9 \\times 2 = 18 $ smores.\n- 6 adults will eat 1 smore each = $ 6 \\times 1 = 6 $ smores.\n\nTotal smores needed = $ 18 + 6 = 24 $ smores.\n\nEach box contains 3 sleeves, so the number of boxes needed is:\n\n$$\n\\frac{24}{3} =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Dora's age is **15 years**.\n- Dora's mother is **4 years younger** than Dora's father.\n- Dora's father's age is **8 more than twice Dora's age**.\n\n### Step 1: Express Dora's father's age\nLet Dora's age be $ D = 15 $.\n\nThen, Dora's father's age is:\n$$\n2 \\times D + 8 = 2 \\times 15 + 8 = 30 + 8 = 38\n$$\n\n### Step 2: Dora's mother's age\nDora's mother is **4 years younger** than Dora's father:\n$$\n38" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Greg has 20 dollars and he wants to split it equally among his 3 younger siblings. To find out how much each sibling gets, we divide the total amount by the number of siblings:\n\n$$\n\\frac{20}{3} = 6.67\n$$\n\nSo, each of them gets **$6.67**. \n\n$$\n\\boxed{6.67}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cindy's math and science books weigh **2 pounds each**, so together they weigh:\n\n$$\n2 + 2 = 4 \\text{ pounds}\n$$\n\nHer French book weighs **4 pounds**, and her English book weighs **3 pounds**. Adding these:\n\n$$\n4 + 3 = 7 \\text{ pounds}\n$$\n\nHer history book weighs **twice as much as her English book**, so:\n\n$$\n2 \\times 3 = 6 \\text{ pounds}\n$$\n\nNow, add all the weights together:\n\n$$\n4 + 7 + 6 = \\boxed{17} \\text{ pounds}\n$$\n\n**Answer:** $\\boxed{17}$ pounds." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Candidate A got **20%** of the votes.\n- Candidate B got **50% more than candidate A's votes**.\n- The rest of the votes (i.e., **C's votes**) were given to candidate C.\n\n### Step 1: Convert percentages to decimal form\n\n- 20% = 0.20\n- 50% more than 20% = 20% + 50% = 70% = 0.70\n\n### Step 2: Calculate the total votes\n\n- Total votes = 100\n\n### Step 3: Calculate the votes for candidate A and B\n\n- Votes for A = 20% of 1" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Boris has 100 apples.\n\nBeck has 23 fewer apples than Boris, so:\n\n$$\n\\text{Beck's apples} = 100 - 23 = 77\n$$\n\nBoris gives Beck 10 apples, so now:\n\n$$\n\\text{Beck's apples} = 77 - 10 = 67\n$$\n\nNow, how many fewer apples does Beck have than Boris?\n\n$$\n100 - 67 = 33\n$$\n\n**Answer:** $\\boxed{33}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Peter uses:\n\n- $3 \\times 4 = 12$ ounces for giant cubes \n- $7 \\times 2 = 14$ ounces for medium cubes \n- $8 \\times 0.5 = 4$ ounces for small cubes \n\nTotal water used: \n$$\n12 + 14 + 4 = 30 \\text{ ounces}\n$$\n\nHe starts with 32 ounces, so the remaining water is: \n$$\n32 - 30 = \\boxed{2} \\text{ ounces}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Let $ S $ be the number of books Steven has.\n- Alice has 6 more books than Steven: $ A = S + 6 $\n- Clara has 2 times as many books as Steven: $ C = 2S $\n- Clara has 20 books: $ 2S = 20 $\n\nSolving for $ S $:\n\n$$\n2S = 20 \\Rightarrow S = 10\n$$\n\nNow, substitute $ S = 10 $ into the equation for $ A $:\n\n$$\nA = S + 6 = 10 + 6 = 16\n$$\n\nNow, find how many more books Clara has than Alice:\n\n$$\nC - A = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Find the cost of a **half-gallon jar**\n\nWe are told that a **gallon jar costs $5**.\n\nLet the cost of a **half-gallon jar** be $ x $.\n\nWe are told that:\n\n- A **gallon jar costs $2 more than a half-gallon jar**.\n\nSo:\n\n$$\n5 = x + 2\n$$\n\nSubtract 2 from both sides:\n\n$$\nx = 3\n$$\n\nSo, a **half-gallon jar costs $3**.\n\n---\n\n### Step 2: Calculate the total cost for 10-gallon jars and 16 half-gallon jars\n\n- Each **gallon jar costs $5**, so for" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 10 students like to bake.\n- 5 students like to play basketball.\n- The rest like to either play video games or play music.\n- The number that like to play music is **twice** the number that like to play basketball.\n\n---\n\n### Step 1: Find the number of students who like to play music.\n\nWe are told that the number that like to play music is **twice** the number that like to play basketball.\n\n$$\n\\text{Number who like music} = 2 \\times 5 = 10\n$$\n\n---\n\n### Step 2: Find the total number of students.\n\n$$\n\\text{Total students} = \\text{Students who like bake} + \\text{Students who like basketball}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jeremy saw **12 birds** in their backyard and threw a stone at them, scaring away **1/3** of that number. \nSo, the number of birds that were scared away is: \n$$\n\\frac{1}{3} \\times 12 = 4\n$$\n\nAfter that, **20 more birds** joined the fearless birds. \nSo, the total number of birds now in the backyard is: \n$$\n12 - 4 + 20 = 28\n$$\n\n**Final Answer:** $\\boxed{28}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the number of students in each class be $ x $. Then the total number of students is:\n\n$$\n2x = 80\n$$\n\n$$\nx = 40\n$$\n\nEach class has **40 students**.\n\nNow, 40% of the students in each class are girls. So the number of girls in each class is:\n\n$$\n0.40 \\times 40 = 16\n$$\n\nTherefore, the number of boys in each class is:\n\n$$\n40 - 16 = 24\n$$\n\n**Final Answer: $\\boxed{24}$**" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mara initially had:\n\n- 2 slices on the plate.\n\nShe added 3 slices, making it:\n\n$$ 2 + 3 = 5 \\text{ slices} $$\n\nShe then tripled the number of slices:\n\n$$ 5 \\times 3 = 15 \\text{ slices} $$\n\nShe ate 2 slices:\n\n$$ 15 - 2 = 13 \\text{ slices} $$\n\nHer friend stole 5 slices:\n\n$$ 13 - 5 = 8 \\text{ slices} $$\n\n**Final answer:** $\\boxed{8}$ cake slices remained on the plate." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Melissa has:\n\n- 8 dogs \n- 5 cats \n- 3 birds \n- 12 horses\n\nTotal animals = 8 + 5 + 3 + 12 = **28 animals**\n\nShe splits the grooming jobs evenly over the **7 days** of the week.\n\nSo, she will groom **28 animals ÷ 7 days = 4 animals per day**.\n\n**Final Answer:** $\\boxed{4}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mark buys 3 packs of cards for $1800 each, so the total cost is:\n\n$$\n3 \\times 1800 = 5400\n$$\n\nHe also gets 1 card worth $4000 and another card worth $1000, so the total value of these cards is:\n\n$$\n4000 + 1000 = 5000\n$$\n\nHe also gets 30 more cards, each worth an average of $50. So the total value of these 30 cards is:\n\n$$\n30 \\times 50 = 1500\n$$\n\nNow, add all the values together:\n\n$$\n5400 + 5000" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- **First amusement park**:\n - $26 per adult\n - $12 per child\n\n- **Second amusement park**:\n - $14 per adult\n - $10 per child\n\n**Family members**:\n- 2 adults\n- 2 children\n\n### Step 1: Calculate total cost at each park\n\n#### First park:\n- Adults: $26 × 2 = 52\n- Children: $12 × 2 = 24\n- **Total cost**: $52 + $24 = **$76**\n\n#### Second park:\n- Adults: $14 × 2 = $28\n- Children: $10 × 2 = $20\n-" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break it down step by step:\n\n- **He sells 500 tomatoes a day** at $0.4 each.\n- **He buys them for $0.5 each**.\n\n### Step 1: Calculate the cost of buying 500 tomatoes a day:\n$$\n500 \\text{ tomatoes/day} \\times \\$0.5/\\text{tomato} = \\$250 \\text{ per day}\n$$\n\n### Step 2: Calculate the revenue from selling 500 tomatoes a day:\n$$\n500 \\text{ tomatoes/day} \\times \\$0.4/\\text{tomato} = \\$200 \\text{ per day}\n$$\n\n### Step 3: Calculate the savings per day:\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Let $ S $ be the number of marbles Sean has.\n- Since Sean has 56 marbles, $ S = 56 $.\n\n- Sean has **half as many marbles as Cal**, so:\n $$\n S = \\frac{1}{2}C \\Rightarrow 56 = \\frac{1}{2}C \\Rightarrow C = 112\n $$\n\n- Carl has **four times as many marbles as Sean**, so:\n $$\n C = 4S \\Rightarrow 112 = 4 \\times 56\n $$\n\n- Now, the total number of marbles Carl and Cal have is:\n $$\n C + \\text" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- There are **54 students**.\n- These students are to be separated into **6 groups of equal size**.\n- The activity requires **12 groups**.\n\nWe are to find how many **more groups** are needed to form.\n\n### Step-by-step:\n\n1. Each group has the same size.\n2. Total students = 54.\n3. Number of groups = 6.\n4. Each group has $ \\frac{54}{6} = 9 $ students.\n\nSo, each group has **9 students**.\n\n5. The activity requires **12 groups**.\n\nSo, the number of **more groups** needed is:\n\n$$\n12 - 6 = \\boxed{6}\n$$\n\n✅ The answer is **6" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Candy rents 60 chairs each weekday and 100 chairs each weekend.\n\nThere are 2 4-week months, so that's 2 × 4 = 8 weeks.\n\nIn each week:\n- 5 weekdays = 5 × 60 = 300 chairs\n- 2 weekend days = 2 × 100 = 200 chairs\n\nTotal chairs per week = 300 + 200 = 500 chairs\n\nTotal chairs in 8 weeks = 500 × 8 = 4000 chairs\n\n**Answer:** $\\boxed{4000}$ chairs." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break down the problem step by step:\n\n- **Initial pile**: 48 bananas \n- **Arnold steals half**: \n $ 48 \\div 2 = 24 $ bananas stolen \n Remaining: $ 48 - 24 = 24 $ bananas \n- **Arnold steals another 12 bananas**: \n $ 24 - 12 = 12 $ bananas remaining \n- **Gunther adds 25 bananas**: \n $ 12 + 25 = 37 $ bananas \n- **Gunther adds another 6 bananas**: \n $ 37 + 6 = 43 $ bananas\n\n### Final Answer:\n$$\n\\boxed{43}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jenna has 4 roommates, and each month the electricity bill is $100.\n\n- Each roommate pays $100 per month.\n- There are 4 roommates, so the total monthly bill is $100 × 4 = $400.\n- Over a year, there are 12 months, so the total annual bill is $400 × 12 = $4,800.\n\n- Each roommate will pay $4,800 ÷ 4 = $1,200 per year.\n\n**Final Answer:** $\\boxed{1200}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jeff sent:\n\n- 8 dozen glasses = $8 \\times 12 = 96$ glasses \n- 4 dozen plates = $4 \\times 12 = 48$ plates\n\nHe returned:\n\n- 10 broken glasses \n- 6 broken plates\n\nSo, the total number of glasses and plates Jeff has now is:\n\n$$\n96 + 48 - 10 - 6 = 130\n$$\n\n**Answer:** $\\boxed{130}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Lorraine starts with:\n\n- 30 small stickers \n- 40 large stickers\n\nShe trades:\n\n- 90% of her small stickers for large buttons: \n $ 0.9 \\times 30 = 27 $ small stickers \n- 50% of her large stickers for large buttons: \n $ 0.5 \\times 40 = 20 $ large stickers \n- The rest of her large stickers (10%) for small buttons: \n $ 0.1 \\times 40 = 4 $ large stickers\n\n### Step 1: Convert all stickers to buttons\n\n- **Small stickers to large buttons**: \n Each small sticker = 1 small button \n So 27 small stickers =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joey played:\n\n- **2 matches on Monday** \n- **1 match on Friday** \n- **Double the number of matches on Monday** = $2 \\times 2 = 4$ matches on Saturday\n\nSo, total matches played in the week:\n\n$$\n2 + 1 + 4 = \\boxed{7}\n$$\n\n**Answer:** $\\boxed{7}$ matches." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the number of votes in favor of the new regulation be $ x $, and the number of votes against it be $ y $.\n\nWe are told:\n- $ x = 2y $\n- Total number of people on the council is $ x + y = 33 $\n\nSubstitute $ x = 2y $ into the total:\n\n$$\n2y + y = 33\n$$\n$$\n3y = 33\n$$\n$$\ny = 11\n$$\n\nThen:\n$$\nx = 2y = 22\n$$\n\nSo, the number of votes in favor of the new regulation is $ \\boxed{22} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's break down the problem step by step:\n\n- **Extra-small**: 11 students \n- **Small**: 2 × 11 = **22 students** \n- **Medium**: 4 less than small = 22 - 4 = **18 students** \n- **Large**: Half as many as medium = 18 / 2 = **9 students** \n- **Extra-large**: 6 more than large = 9 + 6 = **15 students**\n\nNow, add them all together:\n\n$$\n11 + 22 + 18 + 9 + 15 = \\boxed{75}\n$$\n\n**Answer:** $\\boxed{75}$ shirts." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The original price is $140, and there is a 5% discount.\n\n1. Calculate the discount amount:\n $$\n 5\\% \\text{ of } 140 = 0.05 \\times 140 = 7\n $$\n\n2. Subtract the discount from the original price:\n $$\n 140 - 7 = 133\n $$\n\nSo, the final price after the discount is **$133**. \n\n$$\n\\boxed{133}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Number of songs in a playlist: 300 \n- Number of playlists: 20 \n- Each song is 10 hours long\n\n### Step 1: Find the total number of songs in 20 playlists\n\n$$\n20 \\text{ playlists} \\times 300 \\text{ songs per playlist} = 6000 \\text{ songs}\n$$\n\n### Step 2: Find the total duration\n\n$$\n6000 \\text{ songs} \\times 10 \\text{ hours per song} = 60,000 \\text{ hours}\n$$\n\n### Final Answer:\n\n$$\n\\boxed{60000}\n$$ hours" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 20% of 50 people think horse #2 will win.\n- 60% of the remaining people think horse #7 will win.\n- The rest of the people think horse #12 will win.\n\n---\n\n### Step 1: Calculate the number of people who think horse #2 will win.\n\n$$\n20\\% \\text{ of } 50 = 0.20 \\times 50 = 10 \\text{ people}\n$$\n\nSo, **10 people** think horse #2 will win.\n\n---\n\n### Step 2: Subtract the number of people who think horse #2 from the total.\n\n$$\n50 - 10 = 40 \\text{ people}\n$$\n\nSo" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\n- Let the total number of puppies be $ x $.\n\n- Two-thirds of the puppies are Pomeranians: \n $ \\frac{2}{3}x $\n\n- One-third of the Pomeranians are girls: \n $ \\frac{1}{3} \\times \\frac{2}{3}x = \\frac{2}{9}x $\n\n- We are told that there are 6 Pomeranian girls: \n $ \\frac{2}{9}x = 6 $\n\nNow solve for $ x $:\n\n$$\n\\frac{2}{9}x = 6 \\\\\nx = 6 \\times \\frac{9}{2} = 27\n$$\n\n### Final Answer" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jayden had $70 from selling pictures. His sister Ava gave him half of her $90 allowance to help him buy a new camera that costs $200.\n\n- Ava gave him $90 / 2 = $45.\n- So, Jayden now has $70 + $45 = $115.\n\n- The camera costs $200, so Jayden needs $200 - $115 = $85.\n\n**Final Answer:** $\\boxed{85}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the number of cases of shingles needed for each house:\n\n- Let $ x $ be the number of cases for the **first house**.\n- The **second house** needs $ \\frac{1}{2}x $ cases.\n- The **third house** needs $ 2x $ cases.\n\nWe are told that the total number of cases needed is 250:\n\n$$\nx + \\frac{1}{2}x + 2x = 250\n$$\n\nCombine like terms:\n\n$$\nx + \\frac{1}{2}x + 2x = \\frac{2}{2}x + \\frac{1}{2}x + \\frac{4}{2}x = \\frac{7}{2}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Leila spends: \n$3 \\times 2 = \\$6$\n\nJack spends: \n$5 \\times 1 = \\$5$\n\nChase spends: \n$1 \\times 3 = \\$3$\n\nTotal cost: \n\\$6 + \\$5 + \\$3 = **\\$14**\n\nSo, the answer is: \n$$\n\\boxed{14}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "George has 45% more pears than bananas. He has 200 bananas.\n\n- 45% of 200 bananas = 0.45 × 200 = 90 pears \n- Total fruits = 200 bananas + 90 pears = 290 fruits\n\n**Answer:** $\\boxed{290}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Marissa had $80 on her.\n\nShe used the rest of the money to buy candy bars, which cost $5 each.\n\nSo, the number of candy bars she bought is:\n\n$$\n\\frac{80 - 20}{5} = \\frac{60}{5} = 12\n$$\n\n**Answer:** $\\boxed{12}$ candy bars." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sam needs **5 kg of oranges** to make **1 liter** of juice. \nSo, for **4 liters**, he needs: \n$$\n5 \\, \\text{kg/liter} \\times 4 \\, \\text{liters} = 20 \\, \\text{kg}\n$$\n\nEach kilogram costs **$3**, so the total cost is: \n$$\n20 \\, \\text{kg} \\times 3 \\, \\text{\\$/kg} = \\boxed{60} \\, \\text{\\$}\n$$\n\n**Answer:** $\\boxed{60}$ dollars." + } + ] + }, + "accuracy_delta": 0.046875, + "reward_delta": 0.06679687499999892 +} \ No newline at end of file diff --git a/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json b/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json new file mode 100644 index 000000000..51fe00a6f --- /dev/null +++ b/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json @@ -0,0 +1,3142 @@ +{ + "ok": true, + "dataset": "openai/grade-school-math GSM8K official JSONL", + "seed": 20261127, + "config": { + "train_limit": 128, + "train_offset": 0, + "eval_limit": 256, + "eval_offset": 768, + "attempts": 128, + "fault_period": 2, + "group_size": 4, + "max_new_tokens": 160, + "prompt_max_length": 768, + "format_weight": 0.2, + "eval_batch_size": 16, + "lora_rank": 8, + "lr": 2e-05, + "skip_before": true + }, + "train_records": 128, + "eval_records": 256, + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "device": "npu:0", + "before": null, + "baseline": { + "variant": "cursor_restart", + "seed": 20261127, + "attempted_groups": 128, + "train_steps": 64, + "lost_groups": 64, + "sampled_sequences": 512, + "nontrivial_advantage_groups": 37, + "sample_accuracy": 0.361328125, + "sample_format": 0.525390625, + "sample_reward": 0.4664062500000004, + "mean_loss": 1.7446534621994942, + "elapsed_s": 2468.0363726001233 + }, + "baseline_eval": { + "accuracy": 0.359375, + "format": 0.58203125, + "reward": 0.47578125000000115, + "samples": [ + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Era read **300 books** this hour, and decided to read **150 more**. So, the total number of books they have read is:\n\n$$\n300 + 150 = \\boxed{450}\n$$\n\nThey have read **450 books** altogether." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tanya earns:\n\n- $15 for every hour.\n- $5 per day if she teaches more than 3 classes.\n\nOn Monday:\n- 4 classes for 5 hours → earns $15 × 5 = $75.\n\nOn Wednesday:\n- 2 classes for 2 hours → earns $15 × 2 = $30.\n\nTotal earnings = $75 + $30 = $\\boxed{105}$." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The perfume company has:\n\n- 4 vanilla scents\n- 8 fruity scents\n\nThey sell:\n\n- 5 vanilla scents\n- 2 fruity scents\n\nSo, the number of **more vanilla scents sold** than fruity scents is:\n\n$$\n5 - 2 = \\boxed{3}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bennet sells 20 eggplants for $3 each, so the total revenue from eggplants is:\n\n$$\n20 \\times 3 = 60 \\text{ dollars}\n$$\n\nHe wants to make a total of $135, so the remaining amount he needs to make from corn is:\n\n$$\n135 - 60 = 75 \\text{ dollars}\n$$\n\nHe has 25 ears of corn, so the price per ear of corn should be:\n\n$$\n\\frac{75}{25} = 3 \\text{ dollars per ear of corn}\n$$\n\n### Final Answer:\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tatiana has:\n\n- 7 hours on Saturday \n- 5 hours on Sunday \n\nTotal weekend time: \n$$ 7 + 5 = 12 \\text{ hours} $$\n\nShe reads for 3 hours. \nRemaining time after reading: \n$$ 12 - 3 = 9 \\text{ hours} $$\n\nShe plays video games for $ \\frac{1}{3} $ of the remaining time: \n$$ \\frac{1}{3} \\times 9 = 3 \\text{ hours} $$\n\nShe spends playing soccer for the remaining time: \n$$ 9 - 3 = 6 \\text{ hours} $$\n\nPercentage of her weekend playing soccer: \n$$ \\frac{6}{12} \\times " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Anthony had 50 pencils.\n\nHe gave:\n\n- $ \\frac{1}{2} $ of his pencils to Brandon: \n $ \\frac{1}{2} \\times 50 = 25 $ pencils.\n\n- $ \\frac{3}{5} $ of the remaining pencils to Charlie: \n $ \\frac{3}{5} \\times (50 - 25) = \\frac{3}{5} \\times 25 = 15 $ pencils.\n\nHe kept the remaining pencils: \n$ 50 - 25 - 15 = 10 $ pencils.\n\n**Answer:** $ \\boxed{10} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jack drives **150 miles** to the museum and **150 miles** back. \nHe drives at a speed of **75 mph**, so the total driving time is:\n\n$$\n\\frac{150 \\text{ miles}}{75 \\text{ mph}} = 2 \\text{ hours}\n$$\n\nHe spends **6 hours** at the museum. \nSo, the total time from home is:\n\n$$\n2 \\text{ hours (driving)} + 6 \\text{ hours (at museum)} = \\boxed{8} \\text{ hours}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Henry needs to assemble 57 cars and 73 motorcycles. \n- Each car requires **4 wheels**: \n $ 57 \\times 4 = 228 $ wheels. \n- Each motorcycle requires **2 wheels**: \n $ 73 \\times 2 = 146 $ wheels. \n- Total wheels needed: \n $ 228 + 146 = 374 $ wheels. \n\nHe has a box with **650 wheels**. \n- Wheels left: \n $ 650 - 374 = \\boxed{276} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "To find the amount you have to pay after a 20% discount:\n\n1. Calculate 20% of $1000:\n $$\n 0.20 \\times 1000 = 200\n $$\n\n2. Subtract the discount from the original price:\n $$\n 1000 - 200 = 800\n $$\n\nSo, the final amount you have to pay is:\n\n$$\n\\boxed{800}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mike has 600 movies:\n\n- **A third** of the movies are in series: \n $ \\frac{1}{3} \\times 600 = 200 $ movies.\n\n- The remaining movies are $ 600 - 200 = 400 $ movies.\n\n- **40%** of the remaining movies are older movies: \n $ 0.4 \\times 400 = 160 $ movies.\n\n- The remaining $ 400 - 160 = 240 $ movies are normal movies.\n\n- A normal movie costs $10, so the cost of the normal movies is: \n $ 240 \\times 10 = 24" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Winston picked:\n- 6 pounds of peaches at $2.00 per pound: $6 \\times 2 = 12\n- 8 pounds of plums at $1.00 per pound: $8 \\times 1 = 8\n- 6 pounds of apricots at $3.00 per pound: $6 \\times 3 = 18\n\nTotal cost: \n$$ 12 + 8 + 18 = \\boxed{38} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The total time they spent driving and hiking is **6 hours**.\n- They drove at **50 mph**.\n- They hiked at **half their driving speed** (i.e., $ \\frac{50}{2} = 25 $ mph).\n- The time they spent hiking is **1.5 hours**.\n\nLet’s find the distance to their vacation spot.\n\n### Step 1: Find the distance they drove\nThey drove for **6 hours** at **50 mph**:\n\n$$\n\\text{Distance} = \\text{Speed} \\times \\text{Time} = 50 \\times 6 = 300 \\text{ miles}\n$$\n\n### Step 2: Find the distance they hiked" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ E $ be the number of enemies Ava jumps on.\n- Let $ E' $ be the number of enemies Emma jumps on.\n- Let $ B $ be the number of berries Ava collects.\n- Let $ B' $ be the number of berries Emma collects.\n- Let $ T $ be the time Ava finishes the level.\n- Let $ T' $ be the time Emma finishes the level.\n\nWe are given:\n\n- Ava jumps on 8 more enemies than Emma: $ E = E' + 8 $\n- Ava collects 3 more berries: $ B = B' + 3 $\n- Ava finishes 4 seconds slower: $ T' = T - 4 $\n\nWe are also told that:\n\n- Ava gets 10 points" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- Four friends ordered **4 pizzas** for a total of **$64**.\n- Two of the pizzas cost **$30**.\n- The other two pizzas cost the **same amount**.\n\nLet the cost of each of the other two pizzas be $ x $.\n\nSo, the total cost is:\n\n$$\n2 \\times 30 + 2x = 64\n$$\n\n$$\n60 + 2x = 64\n$$\n\n$$\n2x = 4\n$$\n\n$$\nx = 2\n$$\n\n### Final Answer:\n$$\n\\boxed{2}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Chase and Rider ride their bikes **3 times a day** for **5 days**, and **2 times the times** on **2 other days**.\n\nSo, total rides per week:\n\n- 3 times/day × 5 days = 15 rides \n- 2 times/day × 2 days = 4 rides\n\nTotal rides per week = 15 + 4 = **19 rides**\n\n$$\n\\boxed{19}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step.\n\n---\n\n### Step 1: Let the number of white fish Bob buys be $ x $.\n\n- Initially, Bob has 7 fish in his pond:\n - 3 are **orange**\n - 4 are **white**\n\n- He buys $ x $ more white fish.\n\nSo, after buying, the total number of white fish is:\n$$\n4 + x\n$$\n\n- The total number of fish in the pond is:\n$$\n7 + x\n$$\n\n- The problem says he now has **twice as many orange fish as white fish**.\n\nSo, the number of **orange fish** is:\n$$\n3 + x\n$$\n\nAnd the number of **white fish** is:\n$$\n4 + x\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Andy's car consumes:\n\n- **10 MPG** (miles per gallon)\n- **$3/gallon** (price of regular gas)\n- **5 miles** per trip\n\nSo, the cost per week is:\n\n$$\n\\text{Cost per week} = 10 \\, \\text{MPG} \\times 3 \\, \\text{\\$/gallon} \\times 5 \\, \\text{miles} = 150 \\, \\text{\\$/week}\n$$\n\n**Final Answer:**\n\n$$\n\\boxed{150}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Carrie was given:\n\n- **10 twenties** = $10 \\times 20 = 200$ dollars \n- **140 quarters** = $140 \\times 25 = 3500$ dollars\n\nShe spent:\n\n- **3/5 of the twenties**: $ \\frac{3}{5} \\times 200 = 120 $ dollars \n- **3/5 of the quarters**: $ \\frac{3}{5} \\times 3500 = 2100 $ dollars\n\nTotal amount paid for lunch:\n\n$$\n200 + 3500 - 120 - 2100 = 3500 - 210" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ricardo has:\n\n- 5 tomato plants, each yielding 22 tomatoes.\n- 8 eggplant plants, each yielding 4 eggplants.\n\nSo, the total number of fruits is:\n\n$$\n5 \\times 22 + 8 \\times 4 = 110 + 32 = \\boxed{142}\n$$\n\n**Answer:** $\\boxed{142}$ fruits." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told that:\n\n- One-fourth of the sales are smart TVs.\n- One-eighth are analog TVs.\n- The rest are OLED TVs.\n\nLet the total number of TVs sold be 40.\n\n- Smart TVs: $ \\frac{1}{4} \\times 40 = 10 $\n- Analog TVs: $ \\frac{1}{8} \\times 40 = 5 $\n- OLED TVs: $ 40 - 10 - 5 = 25 $\n\nSo, the number of OLED TVs sold is:\n\n$$\n\\boxed{25}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John has $50 and the trip costs $300. Since the school covers half of the cost, the amount John is missing is:\n\n$$\n300 - 50 = \\boxed{250}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- The temperature during the day is **45 degrees**.\n- The temperature during the night is **33 degrees** colder than the day.\n- Each log of wood heats the house up by **5 degrees**.\n\nSo, the temperature during the night is:\n\n$$\n45 - 33 = 12 \\text{ degrees}\n$$\n\nSince each log heats the house by **5 degrees**, we need to find how many logs are required to raise the temperature from **12 degrees** to **32 degrees** (the freezing point of water):\n\n$$\n\\frac{32 - 12}{5} = \\frac{20}{5} = 4\n$$\n\nTherefore, Carson needs to burn **4 logs** to" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- 90 people were required to split into **9-person groups**.\n- 3/5 of the **number of groups** each had **2 seashells**.\n- We need to find the **total number of seashells** brought.\n\n### Step 1: Find the number of groups\n$$\n\\text{Number of groups} = \\frac{90}{9} = 10\n$$\n\n### Step 2: Find the number of seashells per group\n$$\n\\text{Seashells per group} = 2\n$$\n\n### Step 3: Find the total number of seashells\n$$\n\\text{Total seashells} = 10 \\times 2 = 2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We start with 172 people on the train.\n\n- At the first stop, 47 people get off and 13 more get on. \n So, the number of people on the train after this stop is: \n $ 172 - 47 + 13 = 138 $.\n\n- At the next stop, another 38 people get off. \n So, the number of people on the train after this stop is: \n $ 138 - 38 = 100 $.\n\n**Final Answer:** $\\boxed{100}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Damien finds **10 bottle caps a day** and each is worth **$.25**.\n\nIn a **30-day month**, he will have:\n\n$$\n10 \\text{ caps/day} \\times 30 \\text{ days} = 300 \\text{ bottle caps}\n$$\n\nNow, he earns **$0.25 per bottle cap**, so:\n\n$$\n300 \\times 0.25 = 75 \\text{ dollars}\n$$\n\n**Final Answer:** $\\boxed{75}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jamie earns $20 per hour for 8 hours each day. If she works additional hours beyond 8, she is paid a special hourly rate that is **150%** of her regular rate.\n\n- Regular hourly rate: $20 \n- Special hourly rate: $20 × 1.5 = $30\n\n- She worked **11 hours** on Tuesday, so she worked 3 regular hours and 8 special hours.\n\n- Regular pay: $20 × 3 = $60 \n- Special pay: $30 × 8 = $240\n\n- Total pay: $60 + $240 = **$300**\n\n$$\n\\boxed{300}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 12 female lions \n- Half as many male lions as female lions → $ \\frac{1}{2} \\times 12 = 6 $ male lions \n- 14 lion cubs \n\nSo, the total number of lions is:\n\n$$\n12 + 6 + 14 = \\boxed{32}\n$$\n\n**Answer:** $\\boxed{32}$ lions." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mike paid with a $50.00 bill, and the jeans were 25% off the original price of $40. \nSo, the discount amount is: \n$$ 25\\% \\text{ of } 40 = 0.25 \\times 40 = 10 $$\n\nMike will pay: \n$$ 50 - 10 = 40 $$\n\n**Answer:** $\\boxed{40}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The company pays:\n\n- 20 new employees per month \n- Each employee is paid $4000 per month \n- Initial employee number is 200\n\nAfter 3 months:\n\n- Total number of employees = $20 \\times 3 = 60$ \n- Total salary = $60 \\times 4000 = 240,000$\n\n**Answer:** $\\boxed{240000}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The choir plans to sing:\n\n- \"Deck the Halls\" twice: $ 150 \\, \\text{seconds} \\times 2 = 300 \\, \\text{seconds} $\n- \"Jingle Bells\" once: $ 240 \\, \\text{seconds} $\n\nSo, the total time is:\n\n$$\n300 + 240 = \\boxed{540} \\, \\text{seconds}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Billy's starting salary is $10 per hour. \nAfter 2 months, he gets a raise of $0.50 per hour, so his new salary is: \n$$ 10 + 0.50 = 10.50 \\, \\text{per hour} $$\n\nOn his first anniversary, he gets a raise of $1.00 per hour, so his final salary is: \n$$ 10.50 + 1.00 = 11.50 \\, \\text{per hour} $$\n\nSally starts with a salary of $0.50 more than Billy's, so her starting salary is: \n$$ 10 + 0.50 = 10.50" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 1 loaf of bread costs $2.\n- 1 bagel costs $1.\n\nWe are asked to find how much more 3 loaves of bread cost than 2 bagels.\n\n- Cost of 3 loaves of bread: $3 \\times 2 = 6$\n- Cost of 2 bagels: $2 \\times 1 = 2$\n\nSo, the difference is:\n\n$$\n6 - 2 = \\boxed{4}\n$$\n\nThe answer is $\\boxed{4}$." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- Pierson scored **278 points**.\n- Nikita scored **11 more than half as many as Pierson**.\n\nLet's break this down:\n\n- Half of Pierson's score is: \n $ \\frac{278}{2} = 139 $\n\n- Nikita scored **11 more** than that: \n $ 139 + 11 = 150 $\n\nNow, to find the total points scored by both:\n\n$$\n278 + 150 = \\boxed{428}\n$$\n\nSo, the total points scored by Pierson and Nikita is **428**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **40 classes**.\n- Each class has **25 students**.\n- Each class has **3 teachers**.\n- Each student plants **1 tree**.\n- Each teacher plants **2 trees**.\n\n### Step 1: Calculate the number of students\n$$\n\\text{Total students} = 40 \\text{ classes} \\times 25 \\text{ students/class} = 1000 \\text{ students}\n$$\n\n### Step 2: Calculate the number of trees planted by students\n$$\n\\text{Trees by students} = 1000 \\text{ students} \\times 1 \\text{ tree/student} = 1000 \\text{ trees}\n$$\n\n###" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bubbles has:\n\n- 3 stuffed puppies \n- 5 stuffed koalas \n- 2 stuffed zebras \n- 4 stuffed frogs \n\nTotal number of stuffed animals = $ 3 + 5 + 2 + 4 = 14 $\n\nShe wants to buy $ x $ stuffed goats, so the total number of stuffed animals becomes $ 14 + x $.\n\nShe wants the percentage of stuffed goats to be 30% of all stuffed animals:\n\n$$\n\\frac{x}{14 + x} = 0.30\n$$\n\nSolving:\n\n$$\nx = 0.30(14 + x) = 4.2 + 0.3x\n$$\n\n$$\nx - 0.3x =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kris plays for:\n\n- **0.5 hours** every day for **2 weeks** \n- **2 hours** every day for **1 week**\n\nLet's calculate the total hours she plays:\n\n- 2 weeks = 14 days \n- 0.5 hours/day × 14 days = 7 hours \n- 2 hours/day × 7 days = 14 hours \n\nTotal hours played: \n7 + 14 = **21 hours**\n\nShe needs to play for **30 hours** to earn the achievement. \nSo, the amount she still needs to play is: \n**30 - 21 = 9 hours**\n\n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- The first car is traveling at **60 mph**.\n- The second car is traveling at **70 mph**.\n- Both cars continue on the highway at the same speed.\n\nWe are to find how many **miles** will separate them **after 2 hours**.\n\n### Step-by-step:\n\n- The **relative speed** between the two cars is:\n $$\n 70 - 60 = 10 \\text{ mph}\n $$\n\n- After 2 hours, the distance between them will be:\n $$\n 10 \\text{ mph} \\times 2 \\text{ hours} = 20 \\text{ miles}\n $$\n\n### Final Answer:\n$$\n\\boxed{20}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James pays a 30% premium on the total cost of the ring and gold. The total cost is:\n\n$$\n600 + 300 = 900\n$$\n\nHe pays a 30% premium, so the amount he pays is:\n\n$$\n900 \\times 1.30 = 1170\n$$\n\n**Final Answer:** $\\boxed{1170}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following:\n\n- 340 out of 500 third-graders passed.\n- 40 out of 100 fourth graders passed.\n- 400 fifth graders had a pass rate that was **twice** the fourth graders' pass rate.\n\nWe are to find the **overall pass rate** of the school.\n\n---\n\n### Step 1: Find the pass rate for each grade\n\n- **Third graders**: \n $$\n \\frac{340}{500} = 0.68 \\text{ or } 68\\%\n $$\n\n- **Fourth graders**: \n $$\n \\frac{40}{100} = 0.40 \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Each square inch of the mosaic takes **12 glass chips**.\n- A bag contains **72 chips**.\n- Milo wants the mosaic to be **3 inches tall**.\n- He has **2 bags** of glass chips.\n\n---\n\n### Step 1: Find the total number of glass chips\n\n- Each bag has 72 chips, and he has 2 bags:\n $$\n 2 \\times 72 = 144 \\text{ chips}\n $$\n\n---\n\n### Step 2: Find the total area of the mosaic\n\n- Each square inch takes 12 chips, so the total area is:\n $$\n \\frac{144}{12} = 12 \\text{ square inches" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 10 quarts of tea left from the party.\n- 4 students each drank 1.5 quarts of tea.\n- 16 students each drank 2 quarts of tea.\n\n### Step 1: Calculate the total amount of tea consumed by students\n\n- 4 students × 1.5 quarts = $ 4 \\times 1.5 = 6 $ quarts\n- 16 students × 2 quarts = $ 16 \\times 2 = 32 $ quarts\n\n### Step 2: Add the total amount of tea consumed\n\n$$\n6 + 32 = 38 \\text{ quarts}\n$$\n\n### Step 3: Convert quarts to gallons\n\n1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dale started with 100 candies and sold 150. He then ordered 100 more. So, the total number of candies he has is:\n\n$$\n100 + 100 = 200\n$$\n\nHe needs to sell **all** of his candies, so the number of candies he still needs to sell is:\n\n$$\n200 - 150 = \\boxed{50}\n$$\n\nSo, Dale still needs to sell **50** candies." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that the number of students on campus **doubles every month** at the end of the month. At the **beginning of the year**, there are **10 students**.\n\nWe are to find how many **additional students** would have joined by the **end of May**, **above and beyond** the number of students already on campus at the **beginning of the year**.\n\n### Step-by-step:\n\n- **Start of the year**: 10 students.\n- **End of January**: 10 × 2 = 20 students.\n- **End of February**: 20 × 2 = 40 students.\n- **End of March**: 40 × 2 = 80 students.\n- **End of April**: " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Felix charges **$0.25 per branch**.\n- During the week, he made **$105**.\n- We are to find the **average number of branches** he climbed per day.\n\n---\n\n### Step 1: Find the total number of branches climbed in the week\n\nLet $ x $ be the number of branches climbed in the week.\n\n$$\n0.25x = 105\n$$\n\n$$\nx = \\frac{105}{0.25} = 420\n$$\n\nSo, Felix climbed **420 branches** in the week.\n\n---\n\n### Step 2: Find the average number of branches per day\n\n$$\n\\text{Average per day} = \\frac{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Rose starts by picking:\n\n- 3 flowers with 5 petals each: $ 3 \\times 5 = 15 $ petals \n- 4 flowers with 6 petals each: $ 4 \\times 6 = 24 $ petals \n- 5 flowers with 4 petals each: $ 5 \\times 4 = 20 $ petals \n- 6 flowers with 7 petals each: $ 6 \\times 7 = 42 $ petals \n\nTotal petals before any drops: \n$$ 15 + 24 + 20 + 42 = 101 $$\n\nShe drops 1 flower from each group, so she removes 1 petal from each group: \n$$ 1 + 1 + " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John and DeSean bought a bag of marshmallows with **35** marshmallows. Each S'more uses **1 marshmallow**.\n\n- John makes **9** S'mores.\n- DeSean makes **9** S'mores.\n\nThey **dropped 3** marshmallows.\n\nSo, the total number of marshmallows used is:\n\n$$\n9 + 9 = 18\n$$\n\nThe number of marshmallows left is:\n\n$$\n35 - 18 = 17\n$$\n\nNow, each S'more uses **1 marshmallow**, so they can have:\n\n$$\n17 \\div 1 = 17 \\text{ S'mores}\n$$\n\n### Final Answer:\n$$\n\\boxed{1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jack plays with his 3 friends, and the total time they play is 4 hours. Let's break it down:\n\n- Jack plays for **20 minutes**.\n- Two of his friends play for **half as long** (10 minutes each).\n- One of his friends plays for **1.5 times as long** (30 minutes).\n\nTotal time = 20 + 10 + 10 + 30 = **70 minutes**\n\nConvert 70 minutes to hours: \n$$ 70 \\text{ minutes} = \\frac{70}{60} = 1.1667 \\text{ hours} $$\n\nSince the game costs **1 quarter for 20 minutes**, the total cost is: \n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the quantities:\n\n- Let $ x $ be the amount of **salt** used.\n- Let $ y $ be the amount of **citrus zest** used.\n- Let $ z $ be the amount of **sugar** used.\n- Let $ o $ be the amount of **oil** used.\n\nWe are given:\n\n1. She uses the **same amount of citrus zest as fragrance** → $ y = z $\n2. She uses the **same amount of salt as sugar** → $ x = z $\n3. She uses **twice as much oil as salt** → $ o = 2x $\n4. She uses **twice as much salt as zest** → $ x = 2z $\n\nFrom (1) and (2), we have" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John buys:\n- 3 goats at $500 each: $3 \\times 500 = 1500\n- 2 cows at $1500 each: $2 \\times 1500 = 3000\n\nTotal cost: \n$$ 1500 + 3000 = \\boxed{4500} $$\n\nSo, John spent **$4500**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Paul needs **63 cupcakes** for the birthday party. He already has:\n\n- **8 chocolate cupcakes**\n- **40 toffee cupcakes**\n\nSo, the total number of cupcakes he already has is:\n\n$$\n8 + 40 = 48\n$$\n\nTo find how many more he needs, subtract the number of cupcakes he already has from the total he needs:\n\n$$\n63 - 48 = \\boxed{15}\n$$\n\n**Answer:** $\\boxed{15}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Joe has twice as many cars as Robert. Since Robert has 20 cars, Joe has:\n\n$$\n2 \\times 20 = 40 \\text{ cars}\n$$\n\nHe sells 20% of his cars. So he sells:\n\n$$\n0.20 \\times 40 = 8 \\text{ cars}\n$$\n\nHe gives away twice as many cars as the number he sold to his mother. Let’s denote the number of cars he gives away to his mother as $ x $. Then he gives away $ 2x $ cars.\n\nSo, the total number of cars he gives away is:\n\n$$\n8 + 2x\n$$\n\nBut we don’t know how many cars he gives away to his mother. However, we can assume" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There are **20 students**.\n- The total amount raised is **$175,000**.\n- $50,000 comes from **organizations**.\n- The rest of the money comes from the students.\n\nSo, the amount raised by the students is:\n\n$$\n175,000 - 50,000 = 125,000\n$$\n\nEach student raises:\n\n$$\n\\frac{125,000}{20} = 6,250\n$$\n\n**Final Answer:**\n\n$$\n\\boxed{6250}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let the time Sandy walked on the first day be $ x $ hours. Then, the time she walked on the second day is $ \\frac{x}{2} $ hours.\n\nThe total time she walked in both days is:\n\n$$\nx + \\frac{x}{2} = \\frac{3x}{2}\n$$\n\nConvert this to minutes:\n\n$$\n\\frac{3x}{2} \\times 60 = 90x\n$$\n\nSince the problem does not specify the value of $ x $, the total time is:\n\n$$\n\\boxed{90x}\n$$\n\n**Note:** If $ x $ is given, you can substitute it to find the exact total time in minutes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the total number of cars in the parking lot be $ x $.\n\n- Hunter counted 50 cars when entering class.\n- During the first break, he counted 20 more cars, so the total after the first break is $ 50 + 20 = 70 $.\n- When he got out of class for lunch, he realized that $ \\frac{1}{2} $ of the total number of cars had gone. So, $ \\frac{1}{2}x = 70 $.\n\nSolving for $ x $:\n\n$$\n\\frac{1}{2}x = 70 \\Rightarrow x = 140\n$$\n\nThus, the total number of cars he counted during lunch break is:\n\n$$\n\\boxed" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John does 30 cycles of work a day. \nEach cycle has 5 different tasks, and each task pays $1.20. \nHe works a full 7-day week.\n\n### Step-by-step:\n\n- **Daily earnings**: \n $ 30 \\text{ cycles/day} \\times 5 \\text{ tasks/cycle} \\times 1.20 \\text{ dollars/task} = 180 \\text{ dollars/day} $\n\n- **Weekly earnings**: \n $ 180 \\text{ dollars/day} \\times 7 \\text{ days/week} = 1260 \\text{ dollars} $\n\n### Final Answer:\n$$\n\\boxed{1260}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break down the problem step by step:\n\n- **First game:**\n - Sasha scored **14 points**.\n - Julie scored **4 fewer points** than Sasha: $ 14 - 4 = 10 $ points.\n\n- **Second game:**\n - Sasha scored **6 fewer points** than Julie's score in the first game: $ 10 - 6 = 4 $ points.\n\n- **Total points Sasha scored:**\n - First game: 14 points\n - Second game: 4 points\n - Total: $ 14 + 4 = \\boxed{18} $ points.\n\n**Answer:** $ \\boxed{18} $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kimberly bought:\n\n- 8 packages of cat food, each with 11 tins: \n $ 8 \\times 11 = 88 $ tins.\n\n- 6 packages of dog food, each with 6 tins: \n $ 6 \\times 6 = 36 $ tins.\n\nThe difference in the number of tins is: \n$$ 88 - 36 = 52 $$\n\n**Answer:** $\\boxed{52}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total cards: $ 341 $\n- Becca has 12 more than Smendrick\n- Smendrick has 3 times the amount of cards that PJ has\n\nLet:\n- $ x $ = number of cards PJ has\n- $ y $ = number of cards Smendrick has\n- $ z $ = number of cards Becca has\n\nFrom the problem:\n- $ y = z - 12 $\n- $ z = 3x $\n\nSubstitute $ z = 3x $ into $ y = z - 12 $:\n\n$$\ny = 3x - 12\n$$\n\nNow, the total number of cards is:\n\n$$\nx + y + z = 341\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cindy had:\n\n- 5 green eggs \n- Twice as many blue eggs as green: $ 2 \\times 5 = 10 $ blue eggs \n- One fewer pink eggs than blue: $ 10 - 1 = 9 $ pink eggs \n- One-third as many yellow eggs as pink: $ \\frac{1}{3} \\times 9 = 3 $ yellow eggs \n\nTotal eggs: \n$$\n5 + 10 + 9 + 3 = \\boxed{27}\n$$\n\nSo, Cindy had **27 eggs** in total." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Milly needs to return a book that weighs **4 pounds**, cost **$32**, and is **20 miles away**.\n\n### Step 1: Calculate shipping cost\n\n- **Per pound shipping cost**: $0.35 \n- **Per mile shipping cost**: $0.08 \n- **Total shipping cost**: \n $$\n 4 \\times 0.35 + 20 \\times 0.08 = 1.40 + 1.60 = 3.00\n $$\n\n### Step 2: Calculate refund amount\n\n- Amazon will only refund **75%** of the book's purchase price: \n $$\n 0.75 \\times 32 = 2" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mulan starts with $40. Her father gives her $100, so she has:\n\n$$\n100 + 40 = 140\n$$\n\nShe buys:\n- Two pairs of jeans at $30 each: $30 × 2 = $60\n- A bag for $20\n\nTotal spent: $60 + $20 = $80\n\nMulan has:\n\n$$\n140 - 80 = \\boxed{60}\n$$\n\nSo, Mulan has **$60** left." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Boris produces:\n\n- 50,000 bars of chocolate each month.\n\n- First week: 8,000 bars \n- Second week: half of the first week = $ \\frac{1}{2} \\times 8,000 = 4,000 $ bars \n- Third week: three times the first week = $ 3 \\times 8,000 = 24,000 $ bars\n\nThe fourth week is **not** mentioned. Since the problem only provides information about the first, second, and third weeks, we cannot determine the fourth week's production.\n\n**Final Answer:** $\\boxed{\\text{Not determined}}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Britany records **18 videos** each week, and each video is **4 minutes** long. \nSo, the total time spent on recording is: \n$$ 18 \\times 4 = 72 \\text{ minutes} $$\n\nShe spends **2 hours** writing songs each week, which is **120 minutes**. \nShe spends **15 minutes** doing makeup six days a week. \nSo, the total time spent on makeup is: \n$$ 15 \\times 6 = 90 \\text{ minutes} $$\n\nNow, add up all the time spent on TikTok: \n$$ 72 + 120 + 90 = \\boxed{300} \\text{ minutes} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Angela has:\n\n- 6 mirrors \n- 2 chandeliers \n- 20 pictures \n\nShe needs to install:\n\n- 4 mirrors \n- 2 shelves \n- 1 chandelier \n- 10 pictures \n\n**Cost of installation items:**\n\n- Mirrors: $129.00 \n- Shelves: $129.00 \n- Chandeliers: $129.00 \n- Pictures: $129.00 \n\n**Total cost for installation items:**\n\n$$\n4 \\times 129 + 2 \\times 129 + 1 \\times 129 + 10 \\times 129 = (4 + 2 + 1 + " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Roy has saved **40% more** than his brother Anthony. \nAnthony has saved **$10.00 more** than their sister Eva. \nEva has saved **$20.00**.\n\nLet's solve step by step:\n\n1. Eva has saved $20.00.\n2. Anthony has saved $10.00 more than Eva: \n $ 20 + 10 = 30 $\n3. Roy has saved **40% more** than Anthony: \n $ 30 \\times 1.40 = 42 $\n\n**Answer:** $\\boxed{42}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the relationships between the heights of the mountains that each person can lift:\n\n- **Pompei** can lift a mountain **1 inch**.\n- **Saskay** can lift a mountain **12 times higher** than Pompei.\n- **Kagiyami** can lift a mountain **4 times higher** than Saskay.\n- **Naruto** can lift a mountain **10 times higher** than Kagiyami.\n\nLet’s calculate the height of each person's mountain:\n\n1. **Pompei**: 1 inch \n2. **Saskay**: $12 \\times 1 = 12$ inches \n3. **Kagiyami**: $4 \\times 12 = 48$ inches \n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mason travels for 4 hours at 8 mph, so:\n\n$$\n8 \\times 4 = 32 \\text{ miles}\n$$\n\nThen he rests for some time, but the problem doesn't mention rest time. It only says he \"takes some rest\" and then goes on for another 6 hours. So we assume the rest time is not counted in the total distance.\n\nThus, the total distance Mason has traveled is:\n\n$$\n\\boxed{32} \\text{ miles}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 3 kangaroos take **18 hours** to travel across a highway.\n- We are to find how many hours it will take **4 turtles**, each traveling **half the speed** of a kangaroo, to do the same.\n\n---\n\n### Step 1: Determine the speed of a kangaroo\n\nLet the speed of a kangaroo be $ v $.\n\n- 3 kangaroos take 18 hours to travel the same distance.\n- So, the distance is $ 3v \\times 18 = 54v $.\n\nNow, the speed of a turtle is half the speed of a kangaroo, so:\n\n- Speed of a turtle = $ \\frac{v}{2} $\n\n---\n\n### Step 2: Find the" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- Kora made **20** dishes.\n- Rory made **20 more** than Kora, so Rory made $ 20 + 20 = 40 $ dishes.\n- Jada made **twice as many** as Rory, so Jada made $ 2 \\times 40 = 80 $ dishes.\n\nNow, add the number of dishes each person made:\n\n$$\n20 \\text{ (Kora)} + 40 \\text{ (Rory)} + 80 \\text{ (Jada)} = \\boxed{140}\n$$\n\nSo, the total number of clay dishes they all make together is $\\boxed{140}$." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Erika has already saved:\n\n- $150 from her part-time job \n- $80 from her mom \n- $600 from her savings\n\nSo, total money she has is:\n\n$$\n150 + 80 + 600 = \\boxed{830}\n$$\n\nShe needs an **extra $50** to buy the laptop. Therefore, the total amount she needs is:\n\n$$\n830 + 50 = \\boxed{880}\n$$\n\nSo, the final answer is:\n\n$$\n\\boxed{880}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Adam slices **3 large apples** and **5 small apples**, resulting in:\n\n- $3 \\times 5 = 15$ slices from large apples \n- $5 \\times 3 = 15$ slices from small apples \n\nSo, total slices = $15 + 15 = 30$ slices.\n\nAdam eats **15 slices**, so the number of apple slices **left** is:\n\n$$\n30 - 15 = \\boxed{15}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The farmer extracts 5 liters of milk from a single cow a day. Since he has 3 cows, the total milk extracted per day is:\n\n$$\n3 \\times 5 = 15 \\text{ liters}\n$$\n\nHe wants to produce **25 liters of milk a day**. To find out how many more cows he needs, we divide the desired milk by the milk per cow:\n\n$$\n\\frac{25}{5} = 5\n$$\n\nSo, he needs **5 more cows**.\n\n$$\n\\boxed{5}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- One glue stick has $ \\frac{1}{6} $ of its length left.\n- Another has $ \\frac{2}{3} $ of its length left.\n- The third has $ \\frac{1}{2} $ of its length left.\n\nThe total length of each stick is 12 millimeters.\n\nTo find the **total length of the glue sticks that are not used**, we subtract the fraction of the stick that is used from the full length:\n\n$$\n\\text{Length not used} = 12 - \\left( \\frac{1}{6} + \\frac{2}{3} + \\frac{1}{2} \\right)\n$$\n\nConvert all fractions to have a common denominator of 6:\n\n$$\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gabriel has:\n- $5000 from working on weekends\n- $200 from his brother\n\nSo, total money he has is:\n$$ 5000 + 200 = 5200 $$\n\nHe needs:\n$$ 10000 + 800 = 10800 $$\n\nHe still needs:\n$$ 10800 - 5200 = \\boxed{5600} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The craftsman gave Thea **four $20 bills**, which is a total of:\n\n$$\n4 \\times 20 = 80 \\text{ dollars}\n$$\n\nShe paid **$70**, so the change she received is:\n\n$$\n80 - 70 = \\boxed{10} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Craig has:\n\n- 2 twenty dollar bills = $40 \n- 6 squirt guns for $2 each = $12 \n- 3 packs of water balloons for $3 each = $9 \n\nTotal money spent: $40 + $12 + $9 = $61 \n\nHe has $40 left. \n\n**Answer:** $\\boxed{40}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ S $ be the number of socks Peter has.\n- Let $ D $ be the number of dishes Jack has.\n- From the problem, we are told:\n - Peter has **twice as many socks as Jack**: $ S = 2D $\n - Jack has **half as many dishes as socks**: $ D = \\frac{1}{2}S $\n - Jack collected **twice as many dishes as socks**: $ D = 2S $\n\nWe are told that Jack collected **60 dishes**, so:\n\n$$\nD = 60\n$$\n\nNow, substitute $ D = 60 $ into the equation for $ S $:\n\n$$\nS = 2D = 2 \\times 6" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- There are **20 students** in the class.\n- **5 students** are good at **only math**.\n- **8 students** are good at **only English**.\n- The rest are good at **both math and English**.\n\nLet’s find how many students are good at **math**.\n\n- Students who are good at **only math** = 5\n- Students who are good at **only English** = 8\n- Students who are good at **both** = 20 - 5 - 8 = 7\n\nSo, the number of students who are good at **math** is:\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Vicki's concert will be 2 hours long. She allows a 10-minute intermission, so the total time available for the performance is:\n\n$$\n2 \\text{ hours} - 10 \\text{ minutes} = 120 \\text{ minutes} - 10 \\text{ minutes} = 110 \\text{ minutes}\n$$\n\nEach group takes:\n\n- 2 minutes to get on stage \n- 6 minutes to perform \n- 2 minutes to exit the stage \n\nSo, each group takes $2 + 6 + 2 = 10$ minutes.\n\nNow, the number of groups that can perform is:\n\n$$\n\\frac{110 \\text{ minutes}}{10 \\text{ minutes" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "To solve the problem:\n\n- Brenda invested **$300** into a scheme that accumulates **simple interest** at the rate of **three-quarters of the original amount per year**.\n\nLet’s break it down step by step:\n\n1. **Simple interest formula**: \n $ I = P \\times r \\times t $\n\n Where:\n - $ P = 300 $ (original investment),\n - $ r = \\frac{3}{4} $ (rate),\n - $ t = 3 $ (time in years).\n\n2. **Calculate the interest**:\n $$\n I = 300 \\times \\frac{3}{4} \\times 3 = 300 \\times \\frac{9}{4} =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 40 white shirts \n- 50 floral shirts \n- Half of the white shirts have collars → $ \\frac{1}{2} \\times 40 = 20 $ \n- 20 of the floral shirts have buttons \n\nWe are asked to find how many more **floral shirts with no buttons** are there than **white shirts with no collars**.\n\n### Step 1: Calculate the number of white shirts with no collars \n- Total white shirts = 40 \n- Half have collars → 20 have collars \n- So, the remaining white shirts with no collars = $ 40 - 20 = 20 $\n\n### Step 2: Calculate the number of floral shirts" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The farmer places 900 eggs on a tray, which holds 30 eggs. \nWe divide 900 by 30 to find how many trays he can make: \n$$\n\\frac{900}{30} = 30\n$$\n\nHe sells each tray for $2.5, so the total earnings are: \n$$\n30 \\times 2.5 = \\boxed{75}\n$$\n\nThe farmer will earn **$75**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Smith has:\n\n- 55 goats in Farm X \n- 45 goats in Farm Y\n\nHe sold:\n\n- 10 goats from Farm X \n- Twice as many as from Farm Y → 2 × 10 = 20 goats from Farm Y\n\nSo, the number of goats left in the two farms is:\n\n- 55 - 10 = 45 goats in Farm X \n- 45 - 20 = 25 goats in Farm Y\n\nTotal goats left = 45 + 25 = **70**\n\n$$\n\\boxed{70}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James buys **2 pairs of shoes** a month, and **$2640** is spent on shoes **each year**.\n\nTo find the average cost per pair:\n\n$$\n\\text{Average cost per pair} = \\frac{\\text{Total annual cost}}{\\text{Number of pairs per year}} = \\frac{2640}{2} = 1320\n$$\n\n**Answer:** $\\boxed{1320}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- A basket of green food costs **$25**.\n- A basket of red food costs **$18**.\n- You buy **3 baskets of green food** and **1 basket of red food**.\n- You get **$2 off** for each basket of red food.\n\n### Step 1: Calculate the cost of 3 baskets of green food\n$$\n3 \\times 25 = 75\n$$\n\n### Step 2: Calculate the cost of 1 basket of red food\n$$\n1 \\times 18 = 18\n$$\n\n### Step 3: Add the costs\n$$\n75 + 18 = 93\n$$\n\n### Step 4: Apply the $2 discount" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **90 rooms** at the KozyInn Motel.\n- It takes **20 minutes** to clean each room.\n- We are to find how many **hours** it would take to clean **one-half** of the rooms.\n\n### Step 1: Calculate the number of rooms to clean\nOne-half of 90 rooms is:\n\n$$\n\\frac{90}{2} = 45 \\text{ rooms}\n$$\n\n### Step 2: Calculate the time required to clean 45 rooms\nEach room takes 20 minutes, so:\n\n$$\n45 \\times 20 = 900 \\text{ minutes}\n$$\n\n### Step 3: Convert minutes to hours\n$$\n9" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- In the **first year**, they build **12 homes**.\n- In the **second year**, they build **3 times** the number of homes from the first year: \n $ 3 \\times 12 = 36 $ homes.\n- In the **third year**, they build **double** the number of homes from the second year: \n $ 2 \\times 36 = 72 $ homes.\n\nNow, we add the number of homes over the three years:\n\n$$\n12 + 36 + 72 = \\boxed{120}\n$$\n\nSo, the town will have built **120 homes** over the next three years." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ x $ be the age of the **sister**.\n- Let $ y $ be the age of the **brother**.\n- Let $ z $ be the age of the **parent**.\n\nWe are told:\n\n1. I am **three years younger** than my brother: \n $ y = x + 3 $\n\n2. I am **2 years older** than my sister: \n $ z = y + 2 $\n\n3. The **mom's age** is **one less than three times the brother's age**: \n $ z = 3y - 1 $\n\n4. The **sum of all ages** is 87: \n $ x + y + z = 87 $\n\nNow" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We need to find how many packs of 8 glue sticks Mr. Jackson needs to buy to give 2 glue sticks to each of 27 students.\n\n- Each student gets **2 glue sticks**.\n- There are **27 students**.\n- Each pack contains **8 glue sticks**.\n\nSo, the total number of glue sticks needed is:\n\n$$\n27 \\times 2 = 54 \\text{ glue sticks}\n$$\n\nSince glue sticks come in packs of 8, we divide the total number of glue sticks by the number of sticks per pack:\n\n$$\n54 \\div 8 = 6.75\n$$\n\nSince Mr. Jackson can only buy whole packs, he will need to buy **7 packs**.\n\n$$\n\\boxed{" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- The amount of water passing through the river at one point in time is **4000 gallons**.\n- After a day of heavy rain, the amount doubles: $ 4000 \\times 2 = 8000 $ gallons.\n- On the **third day**, the volume increases by **6000 gallons**.\n\nSo, the total amount of water passing through the river at that point is:\n\n$$\n4000 + 6000 = \\boxed{10000} \\text{ gallons}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **10 people** initially.\n- Each infected person infects **6 others** every day.\n- The process continues for **3 days**.\n\nLet’s break it down:\n\n- **Day 1**: 10 people are infected.\n- **Day 2**: Each of the 10 infected people infects 6 others, so **60 new infections** occur.\n- **Day 3**: Each of the 60 infected people infects 6 others, so **360 new infections** occur.\n\nSo, the total number of people infected after 3 days is:\n\n$$\n10 + 60 + 360 = \\boxed{430}\n$$\n\n✅ The final answer is $\\boxed{" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each of the 40 customers gave Rafaela a $20 tip, so:\n\n$$\n40 \\times 20 = 800 \\text{ dollars}\n$$\n\nJulieta received **10% less** than Rafaela, so:\n\n$$\n800 - (0.10 \\times 800) = 800 - 80 = 720 \\text{ dollars}\n$$\n\nThus, the total amount of money received by both is:\n\n$$\n800 + 720 = \\boxed{1520} \\text{ dollars}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jennifer bought 12 oranges in total.\n\nShe gave her **3 daughters 2 oranges each**, so:\n$$ 3 \\times 2 = 6 \\text{ oranges} $$\n\nShe also gave her **only boy 3 oranges**.\n\nSo the total oranges given away are:\n$$ 6 + 3 = 9 \\text{ oranges} $$\n\nThe number of oranges she **remained with** is:\n$$ 12 - 9 = 3 $$\n\n**Final Answer:**\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break it down step by step:\n\n- Claire earns **1 badge per month**.\n- Amber earns **2 badges per month** (twice as long as Claire).\n- Wendy earns **3 times the amount of badges as Claire** in the same time frame (same month length).\n\n### Step 1: Calculate the number of badges each person earns in a year.\n\n- Claire: $1 \\text{ badge/month} \\times 12 = 12 \\text{ badges}$\n- Amber: $2 \\text{ badges/month} \\times 12 = 24 \\text{ badges}$\n- Wendy: $3 \\times 12 = 36 \\text{ badges}$\n\n### Step 2: Find how many more badges Wendy earns" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Every hour, Paige can bake 2 banana bread loaves. \nEach loaf is cut into 8 slices, and each slice is sold for 50 cents. \nShe baked from **1:00 PM to 6:00 PM**, which is **5 hours**.\n\n- Total loaves baked: $ 2 \\text{ loaves/hour} \\times 5 \\text{ hours} = 10 \\text{ loaves} $\n- Total slices: $ 10 \\text{ loaves} \\times 8 \\text{ slices/loaf} = 80 \\text{ slices} $\n- Total money raised: $ 80 \\text{ slices} \\times 50 \\text{ cents/slice} = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the number of silver coins be $ x $. \nThen the number of gold coins is $ x + 30 $.\n\nGretchen has a total of $ x + (x + 30) = 2x + 30 $ coins.\n\nIf she had 70 gold coins, the total number of coins would be:\n\n$$\n70 + x\n$$\n\nBut we are not told how many coins she has in total. So we need to find the value of $ x $.\n\nWe are told that there are 30 more gold coins than silver coins. So:\n\n$$\nx + 30 = \\text{number of gold coins}\n$$\n\nBut we are not told how many gold coins she has. So we need to find the value" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "George ordered 600 burritos for 50 students, and each student was given 10 burritos. So:\n\n- Total burritos given to students: \n $ 50 \\times 10 = 500 $\n\n- Mr. George eats 20 burritos, so the remaining burritos are: \n $ 500 - 20 = 480 $\n\n**Total number of leftover burritos:** \n$$\n\\boxed{480}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 12 red cars \n- 2 fewer green cars than red cars → 12 - 2 = 10 green cars \n- 3 times the number of blue cars as green cars → 3 × 10 = 30 blue cars \n- Total cars = 75 \n- Let $ y $ be the number of yellow cars\n\nSo:\n\n$$\n12 + 10 + 30 + y = 75\n$$\n\n$$\n52 + y = 75\n$$\n\n$$\ny = 75 - 52 = 23\n$$\n\n### Final Answer:\n$$\n\\boxed{23}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total books: 85 \n- Sofie has 25 more books than Anne \n- Anne has 12 fewer books than Fawn\n\nLet’s define:\n\n- Let $ A $ be the number of books Anne has \n- Then, Sofie has $ A + 25 $ \n- Fawn has $ A + 12 $ (since Anne has 12 fewer than Fawn)\n\nSo the total is:\n\n$$\nA + (A + 25) + (A + 12) = 85\n$$\n\nSimplify:\n\n$$\n3A + 37 = 85\n$$\n\nSubtract 37:\n\n$$\n3A = 48\n$$\n\nDivide by " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Daisy bought:\n\n- 5 pounds of potatoes.\n\nShe also bought:\n\n- A bag of **sweet potatoes** that weighed **2 times** as much as the potatoes. \n So, 2 × 5 = **10 pounds**.\n\n- A bag of **carrots** that weighed **3 pounds fewer** than the sweet potatoes. \n So, 10 - 3 = **7 pounds**.\n\n**Answer:** $\\boxed{7}$ pounds of carrots." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Greg wants to make **30 small jello cups** for **30 kids**, each with **4 cups**, so:\n\n$$\n30 \\text{ kids} \\times 4 \\text{ cups per kid} = 120 \\text{ cups}\n$$\n\nHe has **30 jello cups per 1 ounce**, so:\n\n$$\n120 \\text{ cups} \\div 30 \\text{ cups per box} = 4 \\text{ boxes}\n$$\n\nEach box costs **$1.25**, so:\n\n$$\n4 \\times 1.25 = \\boxed{5} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{5}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The seller bought 5 phones for $700 each, so the total cost is:\n\n$$\n5 \\times 700 = 3500\n$$\n\nHe gave the seller $4000 in dollar bills. The change he will give back is:\n\n$$\n4000 - 3500 = \\boxed{500}\n$$\n\nSo, the seller will give back **$500** in change." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Madeline and Keenan share the cost of groceries, and they spend about **$400 per month**. In a **four-week month**, we are to find how much **Keenan** spends per week.\n\n- Total monthly cost: $400 \n- 4 weeks = 4 months \n- Keenan's share per month: $400 / 4 = $100 \n- Keenan's share per week: $100 / 4 = $25\n\n**Answer:** $\\boxed{25}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total pizza pieces: $60$\n- First day: $\\frac{2}{5}$ of the pieces\n- Second day: $10$ pieces\n- Third day: $\\frac{7}{13}$ of the remaining pieces\n\n---\n\n### Step 1: First day\n\n$$\n\\frac{2}{5} \\times 60 = 24\n$$\n\nSo, he ate **24** pieces on the first day.\n\n---\n\n### Step 2: Remaining pieces after first day\n\n$$\n60 - 24 = 36\n$$\n\n---\n\n### Step 3: Second day\n\nHe ate **10** pieces on the second day.\n\n$$\n36 - 10 = 26\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 7 bottles of soda = $21.00 \n So, 1 bottle of soda = $3.00\n\n- 4 bottles of water = $8.00 \n So, 1 bottle of water = $2.00\n\nDavid wants to buy:\n\n- 3 bottles of soda \n- 2 bottles of water\n\nSo, the total cost is:\n\n$$\n3 \\times 3 + 2 \\times 2 = 9 + 4 = 13\n$$\n\nThus, the total cost is:\n\n$$\n\\boxed{13} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "David has $12.48 and buys 16 bolts at $0.03 each. \nTotal cost of bolts = $16 \\times 0.03 = 0.48$.\n\nDavid has $12.48, and after paying for the bolts, he has:\n\n$$\n12.48 - 0.48 = \\boxed{12}\n$$\n\nSo, David has **$12** left after paying for the bolts." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ella earns $33 for 3 hours of dog walking. \nTo find her earnings per hour: \n$$\n\\frac{33}{3} = 11 \\text{ dollars per hour}\n$$\n\nAfter 12 hours: \n$$\n11 \\times 12 = 132\n$$\n\n**Final Answer:** $\\boxed{132}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Paul starts with 52 marbles. His friend gives him 28 more, so he has:\n\n$$\n52 + 28 = 80 \\text{ marbles}\n$$\n\nThen, he loses $ \\frac{1}{4} $ of his marbles:\n\n$$\n\\frac{1}{4} \\times 80 = 20 \\text{ marbles}\n$$\n\nSo, Paul has:\n\n$$\n80 - 20 = 60 \\text{ marbles}\n$$\n\n**Final Answer:** $\\boxed{60}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Amy answers:\n\n- 80% of the multiple-choice questions: $ 0.8 \\times 10 = 8 $ points \n- 90% of the true/false questions: $ 0.9 \\times 20 = 18 $ points \n- 60% of the long-answer questions: $ 0.6 \\times 5 = 3 $ points \n\nTotal score: \n$$\n8 + 18 + 3 = \\boxed{29} \\text{ points}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Isaias has 300 chickens on his farm and plans to sell **3/5** of them. \nSo, the number of chickens he will sell is: \n$$\n\\frac{3}{5} \\times 300 = 180 \\text{ chickens}\n$$\n\nHe sells these 180 chickens at $50 each, so the total money he gets from selling the chickens is: \n$$\n180 \\times 50 = 9000 \\text{ dollars}\n$$\n\nHe needs a profit of $2000, so the amount he spends on buying the chickens is: \n$$\n9000 - 2000 = 7000 \\text{ dollars}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Julie sold 14 glasses. The boys sold an equal number of glasses, and together they sold 32 glasses. So, each boy sold:\n\n$$\n\\frac{32 - 14}{2} = \\frac{18}{2} = 9 \\text{ glasses}\n$$\n\nJulie sold 14, Micah sold 9, and the difference is:\n\n$$\n14 - 9 = 5\n$$\n\n**Final Answer:** $\\boxed{5}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let’s define the total amount of money spent at the spa as $ x $.\n\n- Iris spent $400 on her hair.\n- She spent $ \\frac{1}{4} $ of $400 on a manicure: $ \\frac{1}{4} \\times 400 = 100 $.\n- She spent $ \\frac{3}{4} $ of $100 on a pedicure: $ \\frac{3}{4} \\times 100 = 75 $.\n\nSo, the total amount spent at the spa is:\n\n$$\n400 + 100 + 75 = \\boxed{575}\n$$\n\n**Answer:** $ \\boxed{575}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Sarah has a rope that is 20 meters long. Her friend wants to buy the rope for $2 per meter. Sarah plans to use the profit to buy a new rope, which costs $1.5 per meter.\n\n1. **Calculate the total money Sarah earns:**\n $$\n 20 \\text{ meters} \\times 2 \\text{ dollars/meter} = 40 \\text{ dollars}\n $$\n\n2. **Calculate the cost of the new rope:**\n $$\n 20 \\text{ meters} \\times 1.5 \\text{ dollars/meter} = 30 \\text{ dollars}\n $$\n\n3. **Calculate the money left over:**\n $$\n 40 \\text" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's solve the problem step by step:\n\nLet Melanie's current age be $ x $.\n\nIn 10 years, her age will be $ x + 10 $, and this is equal to 18:\n\n$$\nx + 10 = 18\n$$\n\nSubtract 10 from both sides:\n\n$$\nx = 8\n$$\n\nSo, Melanie is currently 8 years old.\n\nWe are asked to find in how many years her age will be **three times** her current age.\n\nLet the number of years be $ y $.\n\nThen, her age in $ y $ years will be:\n\n$$\n8 + y = 3 \\times 8 = 24\n$$\n\nSo, we solve:\n\n$$\n8 + y" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Kelly's total budget is $65.\n\n- 5 packs of bacon cost $10.\n- 6 packets of chicken cost $10 (twice the price of a pack of bacon).\n- 3 packs of strawberries cost $4 each, so 3 packs = $12.\n- 7 packs of apples cost half the price of a pack of strawberries, so 7 packs = $28.\n\nTotal cost:\n$$\n10 + 10 + 12 + 28 = 60\n$$\n\nKelly has $60 in her budget.\n\nShe has $65 in total, so the amount left in her budget is:\n$$\n65 - 60 = \\boxed{5}\n$$\n\nAnswer: $\\boxed{5" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told that the final concert is **65 minutes** long, and it is **twice as long** as her usual concerts. Let the runtime of her usual concerts be $ x $ minutes.\n\nThen:\n\n$$\n2x = 65\n$$\n\nSolving for $ x $:\n\n$$\nx = \\frac{65}{2} = 32.5\n$$\n\nSo, her usual concerts run for **32.5 minutes**.\n\n$$\n\\boxed{32.5}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Argo starts with 200 toys. \nHe gives away: \n- 40 toys to Alyssa \n- 80 toys to Bonnie \n- 30 toys to Nicky \n\nSo, the total number of toys Argo has now is: \n$$ 200 - 40 - 80 - 30 = 80 $$\n\n**Final Answer:** $\\boxed{80}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "On **Tuesday**, they make **125 chimichangas**. \nOn **Wednesday**, they also make **125 chimichangas**. \nOn **Friday**, they make **twice as many** as on Tuesday, so:\n\n$$\n125 \\times 2 = 250\n$$\n\nNow, add the three days together:\n\n$$\n125 + 125 + 250 = \\boxed{500}\n$$\n\nSo, the total number of chimichangas made on those three days is **500**." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There are **50 microphones**.\n- 20% of them **won't** find space to fit in after arranging the rest in pairs.\n\nSo, 20% of 50 is:\n\n$$\n0.20 \\times 50 = 10\n$$\n\nThis means **10 microphones** won't fit in.\n\nTherefore, the number of microphones that **can** fit in pairs is:\n\n$$\n50 - 10 = 40\n$$\n\nNow, we divide the 40 microphones by 2 to find the number of pairs:\n\n$$\n\\frac{40}{2} = 20\n$$\n\n### Final Answer:\n$$\n\\boxed{20}\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jerry counts:\n\n- 6 birds nesting in the bushes,\n- $ \\frac{2}{3} \\times 6 = 4 $ birds flying overhead,\n- 3 groups of 8 birds each = $ 3 \\times 8 = 24 $ birds feeding.\n\nSo, the total number of birds is:\n\n$$\n6 + 4 + 24 = \\boxed{34}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Lani baked 55 cookies. She ate 5 five-cookie packages, so the remaining cookies are:\n\n$$\n55 - 5 \\times 5 = 55 - 25 = 30\n$$\n\nShe placed the remaining 30 cookies equally into 5 jars, so each jar has:\n\n$$\n\\frac{30}{5} = 6\n$$\n\n**Answer:** $\\boxed{6}$ cookies in each jar." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joelle has 5 orchids and 4 daisies.\n\n- Orchids have 5 petals each.\n- Daisies have 10 petals each.\n\nThe number of petals the daisies have compared to the orchids is:\n\n$$\n4 \\times 10 - 5 \\times 5 = 40 - 25 = \\boxed{15}\n$$\n\nSo, the daisies have **15 more petals** than the orchids." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total plants = 100 \n- One-fourth of the plants are indoor plants → $ \\frac{1}{4} \\times 100 = 25 $ \n- Remaining plants = $ 100 - 25 = 75 $ \n- Two-thirds of the remaining are outdoor plants → $ \\frac{2}{3} \\times 75 = 50 $ \n- The rest are flowering plants → $ 75 - 50 = 25 $ \n\nSo, the number of flowering plants is 25.\n\nTo find the percentage of flowering plants:\n\n$$\n\\frac{25}{100} \\times 100 = 25\\%\n$$\n\n**" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A **whirligig** spins at **5 times the speed** of a **thingamabob**.\n- A **whatchamacallit** spins **11 times faster** than a **thingamabob**.\n- A **whatchamacallit** spins at **121 m/s**.\n\nWe are to find the **speed of a whirligig**.\n\n---\n\n### Step 1: Express the speed of a whirligig in terms of a whatchamacallit\n\n- A whirligig spins at 5 times the speed of a thingamabob.\n- A thingamabob spins at 121 m/s.\n- So, a whirligig spins at:\n\n$$\n5 \\times" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ellen eats:\n- 2 carrots\n- 1 salad\n- 1 yogurt\n\nThe salad costs $6, and the yogurt is half the price of the salad, so the yogurt costs $3.\n\nTotal cost = 2 carrots × $1 + 1 salad × $6 + 1 yogurt × $3 = 2 + 6 + 3 = $11.\n\nWe are asked to find how much Ellen pays for **one carrot** every day.\n\nSo, the cost per carrot is:\n\n$$\n\\frac{1}{2} \\times 1 = \\boxed{0.5} \\text{ dollars per carrot}\n$$\n\nThus, the answer is:\n\n$$\n\\boxed{0.5}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark works:\n- 8 hours/day \n- 5 days/week\n\nHe used to make $10/hour, but now he makes $12/hour.\n\nSo, his weekly earnings are:\n\n$$\n8 \\text{ hours/day} \\times 5 \\text{ days/week} \\times 12 \\text{ dollars/hour} = 480 \\text{ dollars}\n$$\n\n**Final Answer:** $\\boxed{480}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ x $ be the number of times Tasha mowed **Joe's** lawn.\n- Then, she mowed Kamala's lawn $ 3x $ times.\n- She made $ 6 from Joe's work, so she earned $ 3x \\times 6 = 18x $ from mowing lawns.\n\nNow, the total earnings from lemonade sales are $ 80. Since she made $ 18x from mowing lawns, the remaining $ 80 - 18x $ must be from lemonade sales.\n\nWe are told that the total earnings are $ 80, so:\n\n$$\n18x + \\text{lemonade sales} = 80\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Martin's weight is 55 kg.\n\nCarl's weight is 16 kg more than Martin's, so:\n\n$$\n\\text{Carl's weight} = 55 + 16 = 71 \\text{ kg}\n$$\n\nChristian's weight is 8 kg more than Carl's, so:\n\n$$\n\\text{Christian's weight} = 71 + 8 = 79 \\text{ kg}\n$$\n\nHarry is 5 kg less than Christian's weight, so:\n\n$$\n\\text{Harry's weight} = 79 - 5 = 74 \\text{ kg}\n$$\n\n**Final answer:**\n\n$$\n\\boxed{74}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John rents his car out **10 times a month** for **3 hours each time**, and he is paid **$25 per hour**. His car payment is **$500**.\n\n### Step 1: Calculate total earnings from renting the car\n\n- Hours per month: $10 \\times 3 = 30$ hours \n- Earnings: $30 \\times 25 = 750$ dollars\n\n### Step 2: Subtract the car payment\n\n- Profit = Earnings - Car payment \n- Profit = $750 - 500 = \\boxed{250}$\n\n### Final Answer:\n$$\n\\boxed{250}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the variables:\n\n- Let $ x $ be the number of notebooks Joseph had initially.\n- Since Joseph had 3 times as many notebooks as Martha, Martha had $ \\frac{x}{3} $ notebooks.\n\nMartha then bought 5 more notebooks, making her total $ \\frac{x}{3} + 5 $.\n\nWe are asked to find how many **more** notebooks Martha now has compared to Joseph.\n\n- Joseph had $ x $ notebooks.\n- Martha now has $ \\frac{x}{3} + 5 $ notebooks.\n\nSo, the difference is:\n\n$$\n\\frac{x}{3} + 5 - x = -\\frac{2x}{3} + 5\n$$\n\nBut we are asked to find how many **more** Martha has" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dijana rowed **50 miles** the whole day.\n\nAnis rowed **1/5 times more** miles than Dijana. \nThis means Anis rowed:\n\n$$\n50 + \\left(\\frac{1}{5} \\times 50\\right) = 50 + 10 = 60 \\text{ miles}\n$$\n\nSo, the total distance they both rowed is:\n\n$$\n50 + 60 = \\boxed{110} \\text{ miles}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Susan made 100 cookies for Christmas and was going to divide them equally between her 6 nephews. Before Susan could package them, her husband snuck 4 cookies for himself.\n\nSo, the total number of cookies is 100, and 4 are taken by her husband. That leaves:\n\n$$\n100 - 4 = 96 \\text{ cookies}\n$$\n\nThese 96 cookies are divided equally among 6 nephews:\n\n$$\n\\frac{96}{6} = 16\n$$\n\nSo, each of Susan’s nephews will get **16 cookies**.\n\n$$\n\\boxed{16}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- Denise read **10 pages** yesterday.\n- Daniel read **13 pages** yesterday.\n- Today, Denise read **5 more pages** than Daniel read yesterday.\n- Daniel **did not read any pages** today.\n\nLet's calculate the number of pages Denise and Daniel read today:\n\n- Denise: $10 + 5 = 15$ pages\n- Daniel: $13$ pages\n\nNow, we find how many more pages Denise read than Daniel:\n\n$$\n15 - 13 = 2\n$$\n\n**Answer:** $\\boxed{2}$ pages." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- The pot can hold **4 adult bowls** or **8 child bowls**.\n- Calvin is eating with **his wife and two children**, so **5 people**.\n- Everyone eats **1 bowl**.\n\nSo, the total number of bowls used is:\n\n$$\n5 \\text{ bowls}\n$$\n\nThe pot can hold **4 adult bowls** or **8 child bowls**, so we need to find how many **child bowls** are used.\n\nLet’s solve this:\n\nLet $ x $ be the number of child bowls used.\n\nThen:\n\n$$\n4 \\text{ adult bowls} = 8 \\text{ child bowls} \\Rightarrow 1 \\text{ child bowl} = 4 \\text{ adult bowls}\n$$\n\nSo, 5 people eat" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "William bought 5 notebooks and 1 ballpen. \nEach notebook costs $1.50, and each ballpen costs $0.50. \n\nTotal cost = $1.50 × 5 + $0.50 × 1 \n= $7.50 + $0.50 \n= **$8.00**\n\nThe answer is: \n$$\n\\boxed{8}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jo can make 4 small masks with 2 yards of material, so the cost per small mask is:\n\n$$\n\\frac{2 \\text{ yards}}{4 \\text{ small masks}} = 0.5 \\text{ yards per small mask}\n$$\n\nShe can make 3 large masks with 2.25 yards of material, so the cost per large mask is:\n\n$$\n\\frac{2.25 \\text{ yards}}{3 \\text{ large masks}} = 0.75 \\text{ yards per large mask}\n$$\n\nNow, to make 20 small and 8 large masks:\n\n- For small masks: $20 \\times 0.5 = 10$ yards\n- For large masks: $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- There are **9 Fast and the Furious movies**.\n- Deepa has seen **each one in the theatre 3 times**.\n- She has spent **$216** in total.\n\nLet’s calculate the **average price per ticket**:\n\n$$\n\\text{Average price per ticket} = \\frac{\\text{Total cost}}{\\text{Number of movies}} = \\frac{216}{9} = 24\n$$\n\nSo, the average price per ticket is:\n\n$$\n\\boxed{24}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Harold sleeps for **10 hours** a night.\n\nHe works **2 hours less** than he sleeps, so he works for:\n\n$$\n10 - 2 = 8 \\text{ hours}\n$$\n\nHe walks his dog for **1 hour** each day.\n\nSo, the total time he spends in the day is:\n\n$$\n10 + 8 + 1 = 19 \\text{ hours}\n$$\n\nTherefore, the amount of **free time** he has left in his day is:\n\n$$\n24 - 19 = \\boxed{5} \\text{ hours}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tim has a box with:\n\n- 7 blue shoe boxes \n- 9 red shoe boxes\n\nHe uses:\n\n- 3 blue shoe boxes \n- $ \\frac{1}{3} $ of the red shoe boxes\n\nSo, the number of red shoe boxes used is:\n\n$$\n\\frac{1}{3} \\times 9 = 3\n$$\n\nNow, the number of red and blue shoe boxes left is:\n\n- Blue boxes: $ 7 - 3 = 4 $\n- Red boxes: $ 9 - 3 = 6 $\n\nSo, the final answer is:\n\n$$\n\\boxed{4 \\text{ red and } 6 \\text{ blue shoe boxes}}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah has 9 books. Joseph had **twice** the number of books Sarah had, so:\n\n$$\n\\text{Joseph's books} = 2 \\times 9 = 18\n$$\n\nBut Joseph **lost 2** books, so:\n\n$$\n\\text{Joseph's current books} = 18 - 2 = 16\n$$\n\n**Final Answer:** $\\boxed{16}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dean has 30 marbles. He gives:\n\n- $ \\frac{1}{5} \\times 30 = 6 $ marbles to Jamie,\n- 10 marbles to Donald.\n\nSo, the number of marbles left for Dean is:\n\n$$\n30 - 6 - 10 = 14\n$$\n\n**Final Answer:** $\\boxed{14}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Duncan's current age = 60 \n- Duncan's age 8 years ago = 2 × Adam's age 4 years ago\n\nLet’s define:\n\n- Let $ A $ be Adam's current age.\n\nFrom the problem:\n\n- Duncan's age 8 years ago = $ 60 - 8 = 52 $\n- $ 52 = 2 \\times (A - 4) $\n\nSolve for $ A $:\n\n$$\n52 = 2(A - 4) \\\\\nA - 4 = 26 \\\\\nA = 30\n$$\n\nSo, Adam's current age is 30.\n\nAdam will be $ 30 + 8 = \\boxed{38} $ years old in" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Farmer Brown's farm is 200 acres.\n\nFarmer Smith's farm is 100 acres more than twice that, so:\n\n$$\n2 \\times 200 + 100 = 400 + 100 = 500\n$$\n\nSo, Farmer Smith's farm is 500 acres.\n\nTogether, the two farms have:\n\n$$\n200 + 500 = \\boxed{700} \\text{ acres}.\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Colby works for 8 hours, and he completes **10 less than 50 packages per hour**. So, in one hour, he completes:\n\n$$\n50 - 10 = 40 \\text{ packages}\n$$\n\nIn 8 hours, he completes:\n\n$$\n40 \\times 8 = 320 \\text{ packages}\n$$\n\nHe is paid **$0.20 per package**, so his total earnings are:\n\n$$\n320 \\times 0.20 = \\boxed{64} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John drinks a bottle of water every **half hour**, so he drinks **1 bottle every 30 minutes**.\n\nA normal Sudoku puzzle takes him **45 minutes**, and an extreme Sudoku takes **4 times that time**, so:\n\n- Extreme Sudoku takes **180 minutes**.\n\nNow, how many bottles does he drink in 180 minutes?\n\n- He drinks 1 bottle every 30 minutes, so in 180 minutes, he drinks:\n\n$$\n\\frac{180}{30} = 6 \\text{ bottles}\n$$\n\n**Final Answer:**\n\n$$\n\\boxed{6}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Benny threw **2 pieces of bologna** at each **red balloon**.\n- He threw **3 pieces of bologna** at each **yellow balloon**.\n- There were **20 red balloons**.\n- The total number of **pieces of bologna** in the bundle is **58**.\n\nLet $ x $ be the number of **yellow balloons**.\n\nWe know:\n\n- Total bologna = $ 2 \\times 20 + 3 \\times x = 40 + 3x $\n- Total bologna = 58\n\nSo:\n\n$$\n40 + 3x = 58\n$$\n\nSubtract 40 from both sides:\n\n$$\n3x = 18\n$$\n\nDivide" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jon drives 100 miles per day for 30 days, so he drives:\n\n$$\n100 \\text{ miles/day} \\times 30 \\text{ days} = 3000 \\text{ miles}\n$$\n\nSince he needs a tune-up every 1000 miles, the number of tune-ups he needs is:\n\n$$\n\\frac{3000}{1000} = 3\n$$\n\n**Answer:** $\\boxed{3}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bruce works:\n\n- **5 hours** on Tuesday \n- **2 times** the time on Tuesday: $ 2 \\times 5 = 10 $ hours on Wednesday \n- **2 hours less** than Wednesday: $ 10 - 2 = 8 $ hours on Thursday \n\nTotal hours: \n$$ 5 + 10 + 8 = \\boxed{23} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the amount of money Julia and Nadine's mother gave each of them.\n\n- They bought a cake for $11.\n- They also bought 1 dozen balloons for $0.5 each, which is $0.5 \\times 12 = 6$.\n- The remaining money was used to buy 2 tubs of ice cream for $7 each, so the cost is $7 \\times 2 = 14$.\n\nSo the total cost of the items is:\n$$\n11 + 6 + 14 = 31\n$$\n\nSince the total amount of money given to Julia and Nadine is the same for both, we have:\n$$\nx + x = 31 \\Rightarrow 2x =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kira bought:\n- 3 apples \n- 5 bananas \n- 6 oranges \n\nLola ate **2 pieces** of fruit.\n\nSo, the total number of pieces is:\n\n$$\n3 + 5 + 6 = 14\n$$\n\nAfter Lola ate 2 pieces, the remaining pieces are:\n\n$$\n14 - 2 = 12\n$$\n\n**Final Answer:** $\\boxed{12}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There are **6 students** playing tennis.\n- There are **twice that number** playing volleyball: $ 2 \\times 6 = 12 $ students.\n- There are **16 boys** and **22 girls** playing soccer.\n\nNow, we add the students from all three groups:\n\n$$\n6 + 12 + 16 + 22 = \\boxed{56}\n$$\n\n**Answer:** $\\boxed{56}$ students in total." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each student sold 10 lollipops at $0.8 each, so:\n\n- Total number of lollipops sold = $30 \\times 10 = 300$\n- Total cost of lollipops = $300 \\times 0.5 = 150$\n\n- Profit = Total revenue - Total cost = $300 \\times 0.8 - 150 = 240 - 150 = 90$\n\nSo, the class raised **$90** in profit.\n\n$$\n\\boxed{90}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Larry has:\n\n- 3 cats \n- 3 times as many dogs as cats: $ 3 \\times 3 = 9 $ dogs \n- 2 fewer rabbits than dogs: $ 9 - 2 = 7 $ rabbits \n- 3 times as many fish as rabbits: $ 3 \\times 7 = 21 $ fish \n- 1/3 the number of fish as gerbils: $ \\frac{1}{3} \\times 21 = 7 $ gerbils \n\nNow, add all the pets together:\n\n$$\n3 \\text{ cats} + 9 \\text{ dogs} + 7 \\text{ rabbits} + 21 \\text{ fish} + 7 \\text{ gerbils" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 24 slices of bread\n- Abby eats **2 slices per day**\n- Josh eats **2 × 2 = 4 slices per day**\n\nWe need to find how many **days** the bread will last.\n\n$$\n\\text{Number of days} = \\frac{\\text{Total slices}}{\\text{Slices per day}} = \\frac{24}{2 + 4} = \\frac{24}{6} = 4\n$$\n\n**Answer:** $\\boxed{4}$ days." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Martha collects one shell every month. By her 10th birthday, she has collected:\n\n$$\n10 \\text{ months} \\times 1 \\text{ shell/month} = \\boxed{10} \\text{ shells}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **27 cups** in total.\n- These are divided into **3 rows**.\n- Each row has **equal amounts** of **chamomile and mint tea cups**.\n- The remaining **15 cups** are used to brew **cinnamon tea**.\n\nLet’s solve step by step:\n\n1. Each row has **equal amounts** of chamomile and mint tea. \n So, the total number of cups in each row is: \n $$\n \\frac{27}{3} = 9\n $$\n\n2. Each row has **9 cups** of chamomile and **9 cups** of mint tea. \n So, the number of cups of mint tea in each row is: \n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- A three-toed sloth takes **4 hours** to make a trip down the tree, pick up berries, and climb back up.\n- He picks the **same number of berries per trip**.\n- He wants to collect **24 berries** in **8 hours**.\n\nLet’s denote:\n\n- $ x $ = number of berries per trip\n- Time per trip = 4 hours\n\nSo, in 8 hours, he can make:\n\n$$\n\\frac{8}{4} = 2 \\text{ trips}\n$$\n\nTherefore, he can pick:\n\n$$\n2 \\times x = 24\n$$\n\n$$\nx = 12\n$$\n\n### Final Answer:\n\n$$\n\\boxed{12}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Initial amount of water in the pool: **10,000 gallons**\n- The water pump fills a tank with **half the amount of water in the pool** (i.e., 5,000 gallons)\n- The tank is **emptied at a rate of 500 gallons per day**\n- The time is **6 days**\n\n---\n\n### Step 1: Calculate the amount of water used in the garden\n\n- Water used in the garden = 5,000 gallons\n\n---\n\n### Step 2: Calculate the amount of water remaining in the tank\n\n- The tank is emptied at 500 gallons per day.\n- After 6 days, the water left in the tank is:\n\n$$\n\\text{Water" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Colby already saw:\n\n- 5 movies on **Friday or Saturday** \n- 8 movies on **other days** \n- 2 tubs of popcorn \n- 4 boxes of candy \n\nEach movie costs:\n\n- $10 for **Fridays and Saturdays** \n- $7 for **other days** \n\nPopcorn costs $8 and boxes of candy cost $2. \n\nHe wants to make sure he gets **both** popcorn and candy. \n\nLet’s calculate how many movies he can see:\n\n- **Fridays and Saturdays**: 5 movies \n- **Other days**: 8 movies \n- **Total movies**: 5 + 8 = **13 movies**\n\nHe already saw **13 movies**. \n\nHe wants to make sure he gets" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Andrew bakes:\n\n- 200 mini cinnamon rolls, each with 600 calories \n- 300 mini blueberry muffins, each with 450 calories \n\nA mini pastry has **1/3** of the calories of a normal version.\n\nSo, the calories of a mini pastry = 600 × (1/3) = **200 calories**\n\nNow, the total calories from the pastries:\n\n- Cinnamon rolls: 200 × 600 = **120,000 calories** \n- Blueberry muffins: 300 × 450 = **135,000 calories**\n\nTotal calories = 120,000 + 13" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the number of Junebugs removed each day:\n\n- Monday: 39 \n- Tuesday: $2 \\times 39 = 78$ \n- Wednesday: $2 \\times 39 = 78$ \n- Thursday: 48 \n- Friday: 57 \n\nNow, we calculate the total number of Junebugs removed:\n\n$$\n39 + 78 + 78 + 48 + 57 = 39 + 78 + 78 + 48 + 57\n$$\n\n$$\n= 39 + 78 = 117 \\\\\n117 + 78 = 195 \\\\\n195 + 48 = 24" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The bus travels **60 miles per hour** for **5 hours**.\n- The car travels **30 miles per hour** for **8 hours**.\n\nWe are to find how much farther the **bus** went than the **car**.\n\n### Step 1: Calculate the distance the bus traveled\n$$\n\\text{Distance} = \\text{Speed} \\times \\text{Time} = 60 \\, \\text{mph} \\times 5 \\, \\text{hours} = 300 \\, \\text{miles}\n$$\n\n### Step 2: Calculate the distance the car traveled\n$$\n\\text{Distance} = \\text{Speed} \\times \\text{Time} = 3" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- The bag of building blocks has 31 blocks.\n- The bin of stuffed animals has 8 stuffed animals.\n- The tower of stacking rings has 9 rings.\n- Sophie recently bought a tube of bouncy balls, bringing her total number of toys for her nephew up to 62.\n\nSo, the total number of toys is:\n\n$$\n31 \\text{ (blocks)} + 8 \\text{ (stuffed animals)} + 9 \\text{ (rings)} + x \\text{ (bouncy balls)} = 62\n$$\n\nSolving for $ x $:\n\n$$\n31 + 8 + 9 + x = 62 \\\\\n48 + x = 62 \\\\\nx = 62" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The combined age of Peter, Paul, and Jean is **100 years**.\n- Paul is **10 years older** than John.\n- Peter's age is equal to the **sum of Paul and John's age**.\n\nLet’s define the variables:\n\n- Let $ P $ be Peter's age.\n- Let $ J $ be John's age.\n- Let $ J + 10 = P $ (since Paul is 10 years older than John).\n- $ P = J + 10 $ (Peter's age is equal to the sum of Paul and John's age).\n\nWe are told that:\n\n$$\nP + J + J + 10 = 100\n$$\n\nSubstitute $ P = J + " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Maria invited 4 of her friends, so she has 4 friends. At the start, each friend got 2 water balloons, so that's $ 4 \\times 2 = 8 $ balloons. She had 1 water balloon for herself, so that's 1 more. Then her mom gave each person 3 more balloons, so that's $ 4 \\times 3 = 12 $ balloons.\n\nAdding them all together: \n$$ 8 + 1 + 12 = 21 $$\n\n**Final Answer:** $\\boxed{21}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- 10 people donate 5 boxes each → $10 \\times 5 = 50$ boxes.\n- They already have 10 boxes.\n- They can fit 2 boxes per table.\n- They already own 15 tables.\n\nSo, the total number of boxes they have is:\n\n$$\n50 + 10 = 60 \\text{ boxes}\n$$\n\nSince they can fit 2 boxes per table, the number of new tables needed is:\n\n$$\n\\frac{60}{2} = 30\n$$\n\n**Answer:** $\\boxed{30}$ new tables." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Zoey's total distance: \n- 40 seeds × 10 feet = **400 feet**\n\nSydney's total distance: \n- 35 seeds × 12 feet = **420 feet**\n\nAverage total distance: \n$$\n\\frac{400 + 420}{2} = \\frac{820}{2} = 410 \\text{ feet}\n$$\n\n**Final Answer:** $\\boxed{410}$ feet." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Fern will make the following money from each widget:\n\n- **Widgeteer 3000**: \n 60 widgets/hour × 24 hours/day × 30 days/month = 43,200 widgets \n 43,200 widgets × $6/widget = **$259,200**\n\n- **WidgetMaster 9000**: \n 45 widgets/hour × 24 hours/day × 30 days/month = 32,400 widgets \n 32,400 widgets × $6/widget = **$194,400**\n\nNow, the difference is:\n\n$$\n259,200 - 194," + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Cameron arrives at **5 pm** and wants to leave at **10 am** the next morning. This is a **12-hour stay** (from 5 pm to 10 am). However, he **chooses to add 70 pesos for every additional hour** after the 12-hour mark.\n\n### Step 1: Calculate the total cost for 12 hours\n- 12-hour stay = 1000 pesos.\n\n### Step 2: Calculate the additional cost for the extra 12 hours\n- 12 hours after 5 pm = 12 hours.\n- 70 pesos per hour = 70 × 12 = **840 pesos**.\n\n### Step 3: Total cost for " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each goat needs **5 pounds** of hay.\n\nEach sheep needs **3 pounds less than twice the amount each goat needs**, so:\n\n$$\n3 \\text{ pounds less than } 2 \\times 5 = 3 \\text{ pounds less than } 10 = 7 \\text{ pounds}\n$$\n\nSo, each sheep needs **7 pounds**.\n\nThere are **15 goats** and **12 sheep**, so the total amount of hay needed is:\n\n$$\n15 \\times 5 + 12 \\times 7 = 75 + 84 = \\boxed{159} \\text{ pounds}\n$$\n\n**Answer:** $\\boxed{159}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John earns $50 per hour and works 6 hours, so his total earnings are:\n\n$$\n50 \\times 6 = 300 \\text{ dollars}\n$$\n\nHe spends $50 on gas and wants to deposit $100 in the bank, so he has:\n\n$$\n300 - 50 = 250 \\text{ dollars left}\n$$\n\nHe also buys 5 pencils that cost $10 each, so the total cost of the pencils is:\n\n$$\n5 \\times 10 = 50 \\text{ dollars}\n$$\n\nNow, he has $250 left, and he wants to buy pens that cost $25 each. The number of pens he can buy is:\n\n$$\n\\" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Craig has spelled out **20 words**, each with **15 letters**, so the total number of letters is:\n\n$$\n20 \\times 15 = 300 \\text{ letters}\n$$\n\nCraig's brother has spelled out **50 more letters** than Craig, so the total number of letters is:\n\n$$\n300 + 50 = \\boxed{350}\n$$\n\n**Answer:** $\\boxed{350}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- There are **8 children** standing in a row.\n- There are **7 rows**, each containing **5 different Schools**.\n\nSo, the total number of children is:\n\n$$\n8 \\times 7 \\times 5 = 280\n$$\n\n$$\n\\boxed{280}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- There are **29 students** in the class.\n- Each student gets **2 bottles** of apple juice.\n- There are **9 coupons**, each worth **100 bottles**.\n\n### Step 1: Calculate the total number of bottles given to students\n$$\n29 \\text{ students} \\times 2 \\text{ bottles} = 58 \\text{ bottles}\n$$\n\n### Step 2: Calculate the total number of bottles the teacher has\n$$\n9 \\text{ coupons} \\times 100 \\text{ bottles} = 900 \\text{ bottles}\n$$\n\n### Step 3: Subtract the number of bottles given to students from the total\n$$\n900 - 58" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Patty's Plumbing charges:\n\n- $40 to visit the house\n- $35 per hour, or part thereof, for labor\n- $60 in parts\n\nThe job took **2.25 hours** and used **$60 in parts**.\n\n### Step 1: Calculate labor cost\n- Labor cost = $35 per hour × 2.25 hours \n = $35 × 2.25 \n = $81.75\n\n### Step 2: Add the visit fee and labor cost \n- Total cost = $40 + $81.75 = **$121.75**\n\n### Final Answer:\n$$\n\\boxed{121.75}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James gets 10 new CDs, each costing $15, and gets them for **40% off**. He sells 5 of them for $40 each.\n\n### Step 1: Calculate the total cost of the CDs\n- Total cost without discount: \n $ 10 \\times 15 = 150 $\n\n- Discount: \n $ 40\\% \\text{ of } 150 = 0.40 \\times 150 = 60 $\n\n- Total cost after discount: \n $ 150 - 60 = 90 $\n\n### Step 2: Calculate the total money spent\n- He sells 5 CDs for $40 each, so total revenue: \n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jen has:\n\n- 6 yams at $1.5 each: $6 \\times 1.5 = 9\n- 10 sweet potatoes at $2 each: $10 \\times 2 = 20\n- 4 carrots at $1.25 each: $4 \\times 1.25 = 5\n\nTotal earnings: \n$9 + $20 + $5 = $\\boxed{34}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James swims 60% of the 20-mile lake at a pace of 2 miles per hour. \n- Distance covered: $ 0.6 \\times 20 = 12 $ miles \n- Time taken: $ \\frac{12}{2} = 6 $ hours \n\nAfter that, he rests for half the time he spent swimming: \n- Rest time: $ \\frac{6}{2} = 3 $ hours \n\nThen, he swims the remaining 40% of the distance at half the speed: \n- Distance covered: $ 0.4 \\times 20 = 8 $ miles \n- Time taken: $ \\frac{8}{1} = 8 $ hours \n\nTotal time: \n- $ " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- Sam had **70** loaves of bread last Friday.\n- The bakery has **40 less than seven times** as many loaves as Sam had last Friday.\n\nSo, the number of loaves the bakery has is:\n\n$$\n7 \\times 70 - 40 = 490 - 40 = 450\n$$\n\n### Final Answer:\n$$\n\\boxed{450}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jasmine was given 15 stickers for participating in class, lost 7 during playtime, and received 5 more stickers for helping classmates.\n\nSo, the total number of stickers she has at the end is:\n\n$$\n15 - 7 + 5 = 13\n$$\n\n**Final Answer:** $\\boxed{13}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Cayley earns a commission of:\n\n- **10% on 6 copies of New York Times**: \n $ 6 \\times 10\\% = 6 \\times 0.10 = 0.60 $, so total commission: $ 0.60 \\times 5 = 3.00 $\n\n- **8% on 10 copies of Wall Street Journal**: \n $ 10 \\times 8\\% = 10 \\times 0.08 = 0.80 $, so total commission: $ 0.80 \\times 15 = 12.00 $\n\nTotal commission: \n$ 3.00 + 12.00 = \\" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- Marcus is **half** of Leo’s age.\n- Marcus is **five years younger** than Deanna.\n- Deanna is **26 years old**.\n\nLet’s define:\n\n- Let $ L $ be Leo’s age.\n- Then Marcus is $ \\frac{1}{2}L $, since Marcus is half of Leo’s age.\n- Marcus is also 5 years younger than Deanna, so:\n\n$$\n\\frac{1}{2}L = 26 - 5 = 21\n$$\n\nNow solve for $ L $:\n\n$$\n\\frac{1}{2}L = 21 \\Rightarrow L = 42\n$$\n\n### Final Answer:\n$$\n\\boxed{42}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the points scored by Dinar be $ x $. \nThen, the points scored by Azibo is $ x - 10 $, and the points scored by Bahati is $ x - 10 + 20 = x + 10 $.\n\nWe are told that the total points are 45. So:\n\n$$\nx + (x - 10) + (x + 10) = 45\n$$\n\nSimplify:\n\n$$\nx + x - 10 + x + 10 = 45\n$$\n\n$$\n3x = 45\n$$\n\n$$\nx = 15\n$$\n\nSo, Azibo scored:\n\n$$\nx - 10 = 15 - " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The book is printed on paper that is **100 pages to the inch**, meaning that **1 inch of paper = 100 pages**.\n\nEach paper has **2 sides**, and the book is **1.5 inches thick**.\n\nSo, the number of pages in the book is:\n\n$$\n1.5 \\text{ inches} \\times 100 \\text{ pages/inch} \\times 2 \\text{ sides} = 300 \\text{ pages}\n$$\n\n$$\n\\boxed{300} \\text{ pages}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Vince staples 30 reports every 15 minutes. \nHe works from **8:00 AM to 11:00 PM**, which is a total of:\n\n- 11:00 PM - 8:00 AM = **3 hours**.\n\nIn 3 hours, he staples:\n\n$$\n3 \\text{ hours} \\times 15 \\text{ minutes/hour} = 45 \\text{ minutes}\n$$\n\nSo, he staples:\n\n$$\n30 \\text{ reports/15 minutes} \\times 45 \\text{ minutes} = 900 \\text{ reports}\n$$\n\n**Final Answer:** $\\boxed{900}$ reports." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Kim usually sleeps from **10 p.m. to 6 a.m.**, which is a total of **12 hours**. \nShe wakes up **5 minutes earlier** than usual, so she wakes up at **5:05 a.m.** \nShe also wakes up **5 minutes earlier** than usual, so she wakes up at **2:15 a.m.** \nThis means she was **sleeping from 2:15 a.m. to 2:38 a.m.**, which is a total of **23 minutes**.\n\n**Answer:** $\\boxed{23}$ minutes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jonathan has **2/3 as many measuring spoons as measuring cups**. \nLet’s denote the number of measuring cups as $ C $, so the number of measuring spoons is $ \\frac{2}{3}C $.\n\nHe has **two dozen cups**, which is $ 2 \\times 12 = 24 $ cups.\n\nHe gifts **6 measuring spoons** to Pedro.\n\nTo find the **total number of utensils** Jonathan has remaining:\n\n- He has 24 cups.\n- He has $ \\frac{2}{3}C $ measuring spoons.\n- He gives 6 spoons to Pedro.\n\nSo, the total number of utensils is:\n\n$$\n24 + \\frac{2}{3}C - 6 =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The hospital has a capacity of 1000 beds and is currently occupied by $ \\frac{1}{5} $ of that, which is:\n\n$$\n\\frac{1}{5} \\times 1000 = 200 \\text{ beds}\n$$\n\nEach day, 50 patients are admitted, so after 2 weeks (which is 14 days), the total number of patients admitted is:\n\n$$\n50 \\times 14 = 700 \\text{ patients}\n$$\n\nThe number of unoccupied beds is:\n\n$$\n1000 - 200 - 700 = 100\n$$\n\n$$\n\\boxed{100} \\text{ unoccupied beds}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Robyn sends a total of **16 emails a day**.\n\n- **7 emails are work emails**.\n- The **remainder** is $ 16 - 7 = 9 $ emails.\n- **Two-thirds** of the remainder are to family: \n $ \\frac{2}{3} \\times 9 = 6 $ emails.\n- **One-third** of the other emails are to her boyfriend: \n $ \\frac{1}{3} \\times 9 = 3 $ emails.\n\nSo, the number of emails she sends to her boyfriend is:\n\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Shawna's father is **five times** as old as Shawna.\n- Shawna is **three times** as old as Aliya.\n- Aliya is **3 years old**.\n\nLet’s define:\n\n- Let $ A $ be the age of Aliya.\n- Then, Shawna is $ 3A $ years old.\n- Shawna's father is $ 5 \\times 3A = 15A $ years old.\n\nSince Aliya is 3 years old, and Shawna is 3 times as old as Aliya, we can also express Shawna's age as:\n\n- $ 3 \\times 3 = 9 $ years old.\n\nSo, Shawna's father is:\n\n$$\n15 \\times 9" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let $ x $ be the actual number of people who attended the concert.\n\nCourtney reported that the audience was 48, but she made a **mistake** of **20%**. That means she overstated the number by 20%, so the correct number is:\n\n$$\n48 - 0.20 \\times 48 = 48 - 9.6 = 38.4\n$$\n\nSince the number of people must be a whole number, we round to the nearest whole number.\n\n$$\n\\boxed{38}\n$$\n\nTherefore, if Kelly was right, **38 people** really attended the concert." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the number of balls carried by each person:\n\n- Let $ J $ be the number of balls Jordan carried.\n- Let $ S $ be the number of balls Jason carried.\n- Let $ Y $ be the number of balls Jeffrey carried.\n\nFrom the problem:\n\n- $ J = 2S $\n- $ S = 2Y $\n\nSubstitute $ S = 2Y $ into $ J = 2S $:\n\n- $ J = 2(2Y) = 4Y $\n\nSo, the total number of balls is:\n\n$$\nJ + S + Y = 4Y + 2Y + Y = 7Y\n$$\n\nWe are told that **Jason carried 2 balls**, so:\n\n$$\nS = 2\n$$\n\nSub" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- Day 1: 10 holes dug \n- Day 2: 13 holes dug \n- Day 3: 8 holes dug \n- On Day 3, they **filled in 2 holes** to fill in the treasure. \n- At the end of Day 3, the island had **4 times as many holes** as it had at the end of Day 1.\n\nLet’s denote:\n\n- $ H_1 $ = number of holes at the end of Day 1 \n- $ H_2 $ = number of holes at the end of Day 2 \n- $ H_3 $ = number of holes at the end of Day 3 \n\nWe are told:\n\n- $ H_3 = 4" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Amora and Lainey each got **70 corn chips**.\n- The total number of corn chips is **divisible by 3**, since they want to share equally.\n- However, **only two people** would get an equal amount, and the third person would receive **15 more** than the others.\n\nLet’s denote the total number of corn chips as $ T $.\n\nSince Amora and Lainey each got 70, and they are the only two who get an equal amount, the third person (Collins) would get:\n\n$$\nT - 2 \\times 70 = T - 140\n$$\n\nBut this person would receive **15 more** than the others, so:\n\n$$\nT" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jen has to pay **$400** for the **supplies**. The **travel cost** is **50% more** than the supplies.\n\n- 50% of $400 is $200.\n- So, the travel cost is $400 + $200 = **$600**.\n\n$$\n\\boxed{600}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the number of Pokemon caught by each person:\n\n- Let $ A $ = number of Pokemon caught by Alex \n- Let $ S $ = number of Pokemon caught by Stan \n- Let $ D $ = number of Pokemon caught by Adelwolfe \n\nWe are given:\n\n1. $ A = S + 5 $ (Alex has caught 5 more than Stan) \n2. $ S = 4D - 13 $ (Stan has caught 13 less than 4 times as many as Adelwolfe) \n3. $ A + S + D = 339 $ (Together, they have caught 339 Pokemon)\n\n---\n\nWe can substitute the expressions into the third equation:\n\n$$\n(S + 5) +" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let’s define the number of episodes as $ x $.\n\n- Each episode is 20 minutes long.\n- There are half as many episodes in total as there are minutes per episode.\n\nSo, the total time is:\n$$\n20 \\times x = 20x\n$$\n\nBut the problem says there are **half as many episodes in total as there are minutes per episode**. That means:\n$$\nx = \\frac{20}{2} = 10\n$$\n\nSo, there are 10 episodes.\n\nNow, the total time is:\n$$\n20 \\times 10 = 200 \\text{ minutes}\n$$\n\n**Final Answer:**\n$$\n\\boxed{200}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The bird flies **10 hours** at 30 mph in a **southerly** direction.\n- Then, the bird flies **2 hours** at 18 mph in a **northerly** direction.\n- Finally, the bird flies **5 hours** at 22 mph in a **southerly** direction.\n\nWe are to find the **distance** between the bird's **northern** and **southern** homes.\n\n### Step 1: Calculate the distance covered in each leg of the journey\n\n1. **First leg (southerly):**\n $$\n \\text{Distance} = \\text{Speed} \\times \\text{Time} = 30 \\," + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Greta made **1 dozen** of brownies for herself, which is **12 brownies**.\n\nAt her office, they sent her **1/2 a dozen**, which is **6 brownies**.\n\nWhen she arrived home, her friends had **4 dozen**, which is **48 brownies**.\n\nDuring the party, **1 1/2 dozen** (which is **15 brownies**) were eaten.\n\nSo, the total number of brownies used is:\n\n$$\n12 + 6 + 15 = 33\n$$\n\nThe number of brownies left is:\n\n$$\n48 - 33 = \\boxed{15}\n$$\n\n**Answer:** $\\boxed{15}$ individual brownies." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Nani is 8 years old. \nHis brother is **twice** his age, so the brother is $ 2 \\times 8 = 16 $ years old. \nNani's sister is **25% younger** than him, so she is $ 8 - 0.25 \\times 8 = 7.0 $ years old.\n\nNow, add the ages of all three: \n$ 8 + 16 + 7.0 = 31 $.\n\n**Final Answer:** $\\boxed{31}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Andy has:\n\n- 3 racquets with synthetic gut \n- 5 with polyester string \n- 4 with a hybrid set \n\nHe can string each racquet in the following time:\n\n- 15 minutes for synthetic gut \n- 22 minutes for polyester string \n- 18 minutes for hybrid sets \n\nWe are to find the total time it will take to string all racquets.\n\n### Total time = sum of time for each type of racquet\n\n$$\n\\text{Total time} = (3 \\times 15) + (5 \\times 22) + (4 \\times 18)\n$$\n\n$$\n= 45 + 110 + 72 = \\boxed{227} \\text{ minutes}\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John buys phones for himself, his 2 kids, and his wife. Each phone after the first 2 is half price.\n\n- The price of the first phone is $600.\n- The price of the second phone is half of $600, so $300.\n- The price of the third phone is half of $300, so $150.\n- The price of the fourth phone is half of $150, so $75.\n- The price of the fifth phone is half of $75, so $37.50.\n\nSo, the total cost is:\n\n$$\n600 + 300 + 150 + 75 + 37.50 = \\boxed{" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told that Zeke's team has **7 more players** than Carlton's, and Carlton's team has **13 players**.\n\n- Carlton's team has 13 players.\n- Zeke's team has $ 13 + 7 = 20 $ players.\n\nTo find the total number of players in both teams:\n\n$$\n13 + 20 = \\boxed{33}\n$$\n\nSo, the answer is $\\boxed{33}$." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Robert is building a rectangular wooden fence with:\n\n- Length = 15 feet \n- Width = 10 feet \n- Number of wood slats = 2 per foot of fencing\n\nSo, the total length of fencing is:\n\n$$\n15 + 10 = 25 \\text{ feet}\n$$\n\nHe needs 2 wood slats per foot of fencing, so:\n\n$$\n25 \\times 2 = \\boxed{50} \\text{ wooden slats}\n$$\n\n**Answer:** $\\boxed{50}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mrs. Harrington bought 12 boxes of oranges.\n\n- She gave her mom and her sister 2 boxes each: \n $ 2 \\text{ boxes} \\times 2 = 4 \\text{ boxes} $\n\n- She kept $ \\frac{1}{4} $ of the oranges: \n $ \\frac{1}{4} \\times 12 = 3 \\text{ boxes} $\n\n- She sold the remaining: \n $ 12 - 4 - 3 = 5 \\text{ boxes} $\n\nEach box contains 20 oranges, so the total number of oranges she sold is: \n$ 5 \\times 20 = \\boxed{100} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let the number of states in the USA be $ x $. Then, the number of states in India is $ x + 4 $.\n\nThe total number of states in both countries is:\n\n$$\nx + (x + 4) = 2x + 4\n$$\n\nSo, the total number of states in both countries together is:\n\n$$\n\\boxed{2x + 4}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tyler wants to buy three books: a dictionary for $18, a dinosaur book for $13, and a children's cookbook for $8. He has saved $14 from his allowance, and he earns $5 per hour.\n\n1. **Total cost of books**: \n $18 + 13 + 8 = 39$ dollars.\n\n2. **Amount he has saved**: \n $14 dollars.\n\n3. **Remaining amount he needs to save**: \n $39 - 14 = 25$ dollars.\n\n4. **Hours he needs to work to save $25**: \n $25 \\div 5 = 5$ hours.\n\n**Final Answer**: \n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Robert has 30 cherries.\n- Robert has **10 more** than Richard.\n- We are to find how many **more cherries** Robert has than Jerry.\n\n---\n\n### Step 1: Find how many cherries Richard has\n\nSince Robert has 10 more cherries than Richard:\n\n$$\n\\text{Richard} = \\text{Robert} - 10 = 30 - 10 = 20\n$$\n\n---\n\n### Step 2: Find how many cherries Jerry has\n\nWe don't have any direct information about Jerry's cherries. However, we are told that **Richard, Jerry, and Robert** are sharing 60 cherries.\n\nSo:\n\n$$\n\\text{Total cherries} =" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's break down the problem step by step:\n\n- On **Saturday**, Sunny sold:\n - 10 boxes of gingerbread\n - 4 fewer boxes of apple pie = $ 10 - 4 = 6 $ boxes\n\n- On **Sunday**, Sunny sold:\n - 5 more boxes of gingerbread = $ 10 + 5 = 15 $ boxes\n - 15 boxes of apple pie\n\nNow, calculate the earnings:\n\n- **Gingerbread earnings**:\n - $ 10 \\text{ boxes} \\times \\$6 = \\$60 $\n\n- **Apple pie earnings**:\n - $ 6 \\text{ boxes} \\times \\$15 = \\$90 $\n\n- **Total earnings for two" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Pamela will be outside **4 hours a day** over **8 days**. \nShe uses **1 ounce of sunscreen per hour**. \nShe uses **8-ounce bottles** of sunscreen.\n\n### Step 1: Calculate total hours she will be outside:\n$$\n4 \\, \\text{hours/day} \\times 8 \\, \\text{days} = 32 \\, \\text{hours}\n$$\n\n### Step 2: Calculate total ounces of sunscreen needed:\n$$\n32 \\, \\text{hours} \\times 1 \\, \\text{ounce/hour} = 32 \\, \\text{ounces}\n$$\n\n### Step 3: Calculate how many 8-ounce bottles are needed:\n$$\n\\frac{" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The red car is **40% cheaper** than the blue car, which costs **$100**.\n\nTo find the price of the red car:\n\n- 40% of $100 is $100 × 0.40 = $40.\n\nSo, the red car costs:\n\n$$\n100 - 40 = 60\n$$\n\nBoth cars cost:\n\n$$\n\\boxed{60} \\text{ and } \\boxed{100}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the current ages of Emil, his dad, and his brother.\n\nLet:\n- $ E $ = Emil's current age = 19 years\n- $ D $ = Dad's current age\n- $ B $ = Brother's current age\n\nWe are told:\n- When Emil turns 24, he will be **half** the age of his dad.\n- When Emil turns 24, he will be **twice** the age of his brother.\n\n---\n\n### Step 1: Express the ages when Emil turns 24\n\n- Emil will be 24 when he turns 24, so his current age is 19, and he will be $ 24 - 19 = 5 $ years older than he is now.\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Adrianne's mother gave her **20** metallic beads.\n\nHer sister gave her **10 more** beads than her mother, so:\n$$\n20 + 10 = 30\n$$\n\nHer friend gave her **twice as many** as her mother, so:\n$$\n2 \\times 20 = 40\n$$\n\nNow, add all the beads together:\n$$\n20 + 30 + 40 = \\boxed{90}\n$$\n\nSo, Adrianne had **90** beads altogether." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joe caught:\n\n- 3 pounds of crawfish on Thursday \n- 4 times that amount on Friday: $ 4 \\times 3 = 12 $ pounds \n- Half of his Friday's catch on Saturday: $ \\frac{1}{2} \\times 12 = 6 $ pounds \n\nTotal weight caught: \n$ 3 + 12 + 6 = 21 $ pounds \n\nEach serving is 3 pounds, so the number of servings is: \n$ \\frac{21}{3} = 7 $ servings \n\n**Answer:** $\\boxed{7}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- Total students in the class: 30 \n- 20% of the class are football players: \n $ 0.20 \\times 30 = 6 $ students \n- Remaining students: $ 30 - 6 = 24 $ students \n- 25% of the remaining students are cheerleaders or part of band: \n $ 0.25 \\times 24 = 6 $ students \n\nSo, the number of students leaving early is: \n$$\n\\boxed{6}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let's solve the problem step by step:\n\n- Charlie's boots are **five times** the size of Sophie's.\n- Sophie wears **size 5** boots.\n\nSo, Charlie's size is:\n\n$$\n5 \\times 5 = 25\n$$\n\nNow, the average size of the two is:\n\n$$\n\\frac{25 + 5}{2} = \\frac{30}{2} = 15\n$$\n\n### Final Answer:\n$$\n\\boxed{15}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Pat wants to fill her flower bed with plants. Here's the breakdown:\n\n- The flower bed is **111 feet long**.\n- Each plant needs **12 inches** of space, and **1.5 feet** of space between plants.\n- Pat already owns **17 flowers**.\n- Each plant costs **$6**.\n\n### Step 1: Convert all measurements to the same unit\n- 1 foot = 12 inches, so:\n - 111 feet = 111 × 12 = **1332 inches**\n - 1.5 feet = 18 inches\n - 12 inches = 12 inches\n\n### Step 2: Calculate the total length of space needed\nPat needs" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Edgar eats 18 pretzels a day. His brother eats **half as many**, so:\n\n$$\n\\frac{1}{2} \\times 18 = 9\n$$\n\nHe eats **9 pretzels** a day.\n\nIn a week (7 days), he eats:\n\n$$\n9 \\times 7 = \\boxed{63} \\text{ pretzels}\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{63}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Katherine has 5 baskets, each containing 3 petunias and 2 sweet potato vines.\n\n- Cost of 1 petunia: $3.00 \n- Cost of 1 sweet potato vine: $2.50 \n\nTotal cost per basket: \n$3.00 (petunias) + $2.50 (vines) = $5.50\n\nTotal cost for all 5 baskets: \n$5.50 × 5 = $27.50\n\n**Final Answer:** $\\boxed{27.50}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Each rose needs **1 pound** of soil.\n- Each carnation needs **1.5 pounds** of soil.\n- Each Sunflower needs **3 pounds** of soil.\n- They plant **4 sunflowers** and **10 carnations**.\n\n### Step 1: Calculate the total soil used for sunflowers\n$$\n4 \\text{ sunflowers} \\times 3 \\text{ pounds/sunflower} = 12 \\text{ pounds}\n$$\n\n### Step 2: Calculate the total soil used for carnations\n$$\n10 \\text{ carnations} \\times 1.5 \\text{ pounds/carnation} = 15 \\text{ pounds}\n$$\n\n### Step 3: Add the soil used" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jessica makes **$2,000.00** a month. She sets **25%** of her paycheck aside for fancy shoes. Each pair of shoes costs **$1,000.00**.\n\n### Step 1: Calculate how much she saves for shoes\n$$\n25\\% \\text{ of } \\$2,000.00 = 0.25 \\times 2,000.00 = \\$500.00\n$$\n\n### Step 2: Determine how many pairs of shoes she can buy in a year\n$$\n\\frac{\\$500.00}{\\$1,000.00} = 0.5 \\text{ pairs}\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Emily can peel 6 shrimp per minute and sauté 30 shrimp in 10 minutes. Let's find out how long it will take her to cook and peel 90 shrimp.\n\n- She can peel 6 shrimp per minute.\n- She can sauté 30 shrimp in 10 minutes.\n\nSo, in 10 minutes, she can cook and peel 30 shrimp. \nTo cook 90 shrimp, we need to find how many 30 shrimp batches she needs:\n\n$$\n\\frac{90}{30} = 3 \\text{ batches}\n$$\n\nSince each batch takes 10 minutes, it will take:\n\n$$\n3 \\times 10 = \\boxed{30} \\text{ minutes" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- The air conditioner cools the room at **2 degrees per hour** on **low**.\n- It cools the room at **3 degrees per hour** on **high**.\n- The room **warms up at 2 degrees per hour** without the air conditioner.\n- The air conditioner was turned on for **3 hours** on low.\n- Then turned on for **4 hours** on high.\n- Finally, it was turned off for **2 hours**.\n\nWe are to find how many **degrees lower than the starting temperature** the final temperature was.\n\n---\n\n### Step-by-step:\n\n1. **Initial temperature** = $ T $\n\n2. **Cooling on low**:\n - 3 hours at 2 degrees/hour →" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let's define the variables:\n\n- Let $ x $ be the age of Bill when he saw the comet for the **first time**.\n- Let $ y $ be the age of Bill's father when he saw the comet for the **first time**.\n\nWe are told:\n\n- Bill's dad saw the comet when he was 30 years old.\n- Bill saw the comet **a second time** when he was **three times the age** his father was when he saw the comet.\n\nSo, we can write the equations:\n\n1. $ y = 30 $ (since Bill's father was 30 when he saw the comet)\n2. $ x = 3y $ (since Bill was three times the age his father was when he saw the comet)\n\nSubstitute" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Buford writes:\n\n- 1 check per month for the electric bill \n- 1 check per month for the gas bill \n- 2 checks per month for the church \n- 1 check quarterly for the pest and lawn service \n\nSo, per year:\n\n- Electric bill: 1 check/month × 12 months = 12 checks \n- Gas bill: 1 check/month × 12 months = 12 checks \n- Church: 2 checks/month × 12 months = 24 checks \n- Pest and lawn service: 1 check/quarterly × 4 quarters = 4 checks \n\nTotal checks per year: \n12 + 12 + 24 + 4 = **62 checks**\n\n$$\n\\boxed{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the number of flights to France as $ x $, and flights to Germany as $ y $, and flights to Poland as $ z $. We are told:\n\n- The first plane makes 44 trips to Poland, and these are half the number of trips the first plane makes throughout the day.\n- The first plane makes $ 44 + x + y $ trips in total.\n- The first plane makes $ \\frac{3}{4} $ of its flights to Greece, and the remaining $ \\frac{1}{4} $ of its flights are split equally between France and Germany.\n\nLet’s denote the total number of flights the first plane makes in one day as $ F $. Then:\n\n$$\nF = \\frac{3}{4} \\times \\text" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "- Tobias howls for **20 seconds**.\n- Chikote howls for **twice as long** as Tobias: $2 \\times 20 = 40$ seconds.\n- Igneous howls for **as long as the other two combined**: $20 + 40 = 60$ seconds.\n\nNow, convert all times to minutes:\n\n- Tobias: $20 \\div 60 = \\frac{1}{3}$ minute\n- Chikote: $40 \\div 60 = \\frac{2}{3}$ minute\n- Igneous: $60 \\div 60 = 1$ minute\n\nAdd them together:\n\n$$\n\\frac{1}{3} + \\frac{2" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Adam bought himself new trousers for $30. His mother gave him $6, and his father gave him **twice as much** as the mother's contribution. \n\n- Mother's contribution: $6 \n- Father's contribution: $6 × 2 = $12 \n\nTotal contribution: \n$6 + $12 = $18 \n\n**Answer:** $\\boxed{18}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Four children: Akbar, Alessandro, Helene, and Wilfred.\n- Helene is **twice as old as the average age of the group**.\n- The **total age of the children is 20**.\n- Akbar is **3 years old**.\n- Alessandro is **4 years old**.\n\nLet’s denote:\n\n- $ A = 3 $ (Akbar’s age)\n- $ L = 4 $ (Alessandro’s age)\n- $ W $ = age of Wilfred\n\nWe are told that:\n\n- Helene is **twice as old as the average age** of the group.\n- The **total age** is 20.\n\nLet’s find the **average age** of the group:\n\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let's break down the problem step by step:\n\n- Walter collects $500 from his neighbors.\n- He collects $1500 from an online fund.\n- His lawyer offers to donate **three times** as much as everyone else donates.\n- Walter is going to tell his friend about his neighbors and the online fund **until** his friend gives him $200.\n\nSo, the lawyer's contribution is:\n\n$$\n3 \\times \\text{(amount Walter is going to tell his friend about)}\n$$\n\nSince the friend gives him $200, the lawyer's contribution is:\n\n$$\n3 \\times 200 = \\boxed{600}\n$$\n\n**Answer:** $\\boxed{600}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- There are **100 guests** in the reception.\n- Each guest brought **15 cookies**.\n- The **bride** gave **1/2 of the cookies** to the church next door.\n- Each person in the church next door got **15 cookies**.\n\n---\n\n### Step 1: Total cookies brought by guests\n\nThere are 100 guests, and each brought 15 cookies:\n\n$$\n100 \\text{ guests} \\times 15 \\text{ cookies/guest} = 1500 \\text{ cookies}\n$$\n\n---\n\n### Step 2: Total cookies given to the church\n\nThe bride gave **1/2** of the cookies to the church:\n\n$$\n\\frac{1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that:\n\n- There are 6 people: 2 adults and 4 kids.\n- Each adult gets a slice that is **twice as big** as that of each kid.\n\nLet’s define the size of each kid’s slice as $ x $. Then:\n\n- Each adult gets $ 2x $.\n- The total size of the watermelon is the sum of all slices:\n $$\n 2x + 4x = 6x\n $$\n\nNow, the **percentage of the watermelon each adult gets** is:\n$$\n\\frac{2x}{6x} \\times 100 = \\frac{2}{6} \\times 100 = \\frac{1}{3} \\times 100" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Doctor Jones has:\n\n- **9 inpatients** at the clinic.\n- **20 minutes per inpatient**.\n- **30 minutes per appointment**.\n\nLet's calculate the total time spent:\n\n- Time for inpatient rounds: \n $ 9 \\text{ inpatients} \\times 20 \\text{ minutes} = 180 \\text{ minutes} $\n\n- Time for appointments: \n $ 10 \\text{ appointments} \\times 30 \\text{ minutes} = 300 \\text{ minutes} $\n\nTotal time spent: \n$ 180 + 300 = 480 \\text{ minutes} $\n\nConvert to hours: \n$ 480 \\div 60 = " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jordan knows the total time to make the cake is:\n\n- **20 minutes** to make the batter \n- **30 minutes** to bake the cake \n- **2 hours** to cool \n- **10 minutes** to frost \n\nSo, the total time is:\n\n$$\n20 + 30 + 2 \\times 60 + 10 = 20 + 30 + 120 + 10 = 180 \\text{ minutes}\n$$\n\nShe wants to make the cake **all on the same day** and be **ready to serve it at 5:00 pm**.\n\n- The total time is **180 minutes**.\n- She needs to start **at least 180 minutes" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Lisa sold **3.5 boxes** of chocolate bars.\n- Peter sold **4.5 boxes** of chocolate bars.\n- Together, they sold **64 chocolate bars**.\n\nLet the number of chocolate bars in a box be $ x $.\n\nSo:\n\n$$\n3.5x + 4.5x = 64\n$$\n\n$$\n8x = 64\n$$\n\n$$\nx = \\frac{64}{8} = 8\n$$\n\n**Answer:** $\\boxed{8}$ boxes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Cost to rent the studio: $25 per session \n- Cost per student per session: $1.50 \n- Number of students: 10 \n- Number of sessions per week: 3 \n- Number of weeks in a month: 4\n\n### Step 1: Calculate total cost per week\n\n$$\n\\text{Total cost per week} = (\\text{Number of sessions} \\times \\text{Cost per session}) + (\\text{Number of students} \\times \\text{Cost per student per session})\n$$\n\n$$\n= (10 \\times 3) + (10 \\times 1.50) = 30 + 15 = 45\n$$\n\n### Step " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Peter has 4 boxes with the same number of chocolate bars in each, and Martha has 7 boxes with the same number of chocolate bars in each.\n\nLet the number of chocolate bars in each box be $ x $.\n\n- Peter's total: $ 4x = 64 $\n- Martha's total: $ 7x = 56 $\n\nFrom Peter's equation:\n$$\n4x = 64 \\Rightarrow x = 16\n$$\n\nSubstitute $ x = 16 $ into Martha's equation:\n$$\n7x = 56 \\Rightarrow 7 \\times 16 = 112\n$$\n\nNow, the difference in the number of chocolate bars per box is:\n$$\n16 - 112 = -" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- Total population of porcupines = 50 \n- Number of female porcupines = $ \\frac{3}{5} \\times 50 = 30 $ \n- Each female porcupine gives birth to 4 babies per month \n- A year has 12 months\n\nSo, the number of babies born in a year is: \n$$ 30 \\times 4 \\times 12 = 1440 $$\n\nNow, the total number of porcupines after a year is: \n$$ 50 + 1440 = \\boxed{1490} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Width = 14 feet \n- Length = 25 feet \n- Depth = 4 feet \n- Cost per gallon = $0.10 \n- Pool company multiplies volume by 5.9 to find gallons needed\n\n### Step 1: Calculate the volume of the pool\n\n$$\n\\text{Volume} = \\text{Width} \\times \\text{Length} \\times \\text{Depth} = 14 \\times 25 \\times 4 = 1400 \\text{ cubic feet}\n$$\n\n### Step 2: Convert cubic feet to gallons\n\nSince 1 cubic foot = 7.48052 gallons (approximate conversion), we have:\n\n$$\n\\text{G" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 9 red sticks \n- 5 more blue sticks than red → $ 9 + 5 = 14 $ blue sticks \n- 3 less yellow sticks than blue → $ 14 - 3 = 11 $ yellow sticks \n\nTotal number of sticks = \n$$\n9 + 14 + 11 = \\boxed{34}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Matteo traveled for 4 hours at 55 mph, so:\n\n$$\n\\text{Distance} = 55 \\times 4 = 220 \\text{ miles}\n$$\n\nShandy traveled for 10 hours at 45 mph, so:\n\n$$\n\\text{Distance} = 45 \\times 10 = 450 \\text{ miles}\n$$\n\nThe difference in distance is:\n\n$$\n450 - 220 = \\boxed{230} \\text{ miles}\n$$\n\nShandy drove **230 miles farther** than Matteo." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Total students: 3000 \n- Half of the students are over 16 years old: $ \\frac{1}{2} \\times 3000 = 1500 $ \n- One-fourth of the students over 16 are male: $ \\frac{1}{4} \\times 1500 = 375 $ \n- The remaining half are under 16: $ \\frac{1}{2} \\times 1500 = 750 $ \n- One-half of the students under 16 are male: $ \\frac{1}{2} \\times 750 = 375 $ \n\nNow, the total number of **female" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bethany can run 10 laps in one hour.\n\n- Trey runs 4 more laps than Bethany: \n $ 10 + 4 = 14 $ laps.\n\n- Shaelyn runs half as many laps as Trey: \n $ \\frac{14}{2} = 7 $ laps.\n\n- Quinn runs 2 fewer laps than Shaelyn: \n $ 7 - 2 = 5 $ laps.\n\nNow, how many more laps can Bethany run compared to Quinn? \n$ 10 - 5 = 5 $.\n\n**Final Answer:** $\\boxed{5}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The tank has a capacity of **18,000 gallons**.\n- Wanda and Ms. B pump water to fill the tank in **2 days**.\n- On **Day 1**:\n - Wanda fills **1/4** of the tank's capacity.\n - Ms. B pumps **3/4** of the amount Wanda filled.\n- On **Day 2**:\n - Wanda pumps **2/3** of the amount she pumped on Day 1.\n - Ms. B pumps **1/3** of the amount she pumped on Day 1.\n\nLet’s calculate the total amount of water pumped:\n\n- **Day 1**:\n - Wanda fills: $ \\frac{1}{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s denote the initial charge of the power bank as $ C $.\n\n### Step 1: Understand the charging process\n\n- **First 5 hours**: The power bank loses 9% of its total capacity.\n- **Next 3 hours**: The power bank loses 7% of its total capacity.\n- **Final charge remaining**: 28%.\n\nWe need to find the initial charge $ C $.\n\n---\n\n### Step 2: Write equations\n\nLet’s assume the total capacity is 100% (or 1 unit).\n\n- After 5 hours, the power bank has lost 9%:\n $$\n \\text{Remaining after 5 hours} = 1 - 0.09 = 0.91\n $$\n\n- After" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Janet earns:\n- $10 per hour from wages\n- $15 per hour from tips\n\nSo, her hourly wage is:\n$$\n10 + 15 = 25 \\text{ dollars per hour}\n$$\n\nShe wants to save 20% of the cost of the car, which is:\n$$\n0.20 \\times 10000 = 2000 \\text{ dollars}\n$$\n\nShe works 40 hours a week, so her weekly earnings are:\n$$\n40 \\times 25 = 1000 \\text{ dollars per week}\n$$\n\nTo save $2000, she needs:\n$$\n\\frac{2000}{1000}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jamaar has earned $10, and he has already purchased:\n\n- 3 peaches: $3 × $0.5 = $1.5 \n- 4 pears: $4 × $0.25 = $1 \n- 2 kiwis: $2 × $1 = $2 \n- 5 apples: $5 × $0.75 = $3.75 \n\nTotal spent so far: \n$1.5 + $1 + $2 + $3.75 = **$8.25**\n\nRemaining money: \n$10 - $8.25 = **$1.75**\n\nPlums cost $0.25 each, so: \n$1.75 ÷ $0" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Anne purchased a box of sweets containing **15 packs**, and each pack has **60 pieces**. She kept **2 packs** and gave the rest to her **10 friends equally**.\n\n- Total number of sweets = $15 \\times 60 = 900$ pieces.\n- She kept 2 packs, so she gave away $900 - 2 \\times 60 = 900 - 120 = 780$ pieces.\n- Each friend received $\\frac{780}{10} = 78$ pieces.\n\n**Answer:** $\\boxed{78}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that the price of carrots increases by **5% of the original price** every year. This means the price after each year is:\n\n$$\n\\text{New price} = \\text{Original price} \\times (1 + 0.05)\n$$\n\nWe are given that the original price is **$120**, and we want to find the price after **3 years**.\n\n$$\n\\text{Price after 3 years} = 120 \\times (1 + 0.05)^3\n$$\n\n$$\n= 120 \\times 1.15^3\n$$\n\n$$\n= 120 \\times 1.520875\n$$\n\n$$\n\\approx" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Olivia uploaded 72 pictures in total. She divided them equally into 8 albums:\n\n$$\n\\frac{72}{8} = 9\n$$\n\nSo, each album has 9 pictures.\n\n- 3 of the albums were selfies only.\n- 2 of the albums were portraits.\n\n$$\n\\text{Portraits} = 3 \\times 2 = 6\n$$\n$$\n\\text{Selfies} = 2 \\times 3 = 6\n$$\n\n**Final Answer:** $\\boxed{6}$ portraits and $\\boxed{6}$ selfies." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James reads 18 pages of his book, and it takes him 10 minutes to read 3 pages. So, the time per page is:\n\n$$\n\\frac{10 \\text{ minutes}}{3 \\text{ pages}} = \\frac{10}{3} \\text{ minutes per page}\n$$\n\nNow, multiply by 18 pages:\n\n$$\n18 \\times \\frac{10}{3} = 60 \\text{ minutes}\n$$\n\n**Final Answer:** $\\boxed{60}$ minutes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given the following information:\n\n- 100 guests were initially booked.\n- 24 guests checked in early.\n- 15 guests checked in late.\n- In the afternoon, twice as many people checked in as those who checked in late.\n- 7 more people checked in after dinner was served.\n\nLet’s break it down step by step:\n\n1. **Total guests initially**: 100 \n2. **Early check-in**: 24 \n3. **Late check-in**: 15 \n4. **Afternoon check-in**: Twice as many as late check-in → $ 2 \\times 15 = 30 $ \n5. **After dinner check-in**: 7 \n\nNow, add all the check-ins:\n\n$$\n1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John picks:\n\n- 4 bananas on Wednesday \n- 6 bananas on Thursday \n- Triple the number of bananas on Wednesday on Friday: $ 3 \\times 4 = 12 $\n\nSo, the total number of bananas is:\n\n$$\n4 + 6 + 12 = \\boxed{22}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A 60-item quiz.\n- 40% of the questions are **easy**.\n- The remaining 60% are **equally divided** as **average** and **difficult**.\n- Aries is sure to get **75%** of the **easy** questions.\n- She is also sure to get **half** of the **average and difficult** questions.\n\n---\n\n### Step 1: Total questions\n\n- Total questions = 60\n\n---\n\n### Step 2: Number of easy questions\n\n- 40% of 60 = $ 0.40 \\times 60 = 24 $\n\n---\n\n### Step 3: Number of average and difficult questions\n\n- 60% of " + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let the number of small stuffed animals be $ x $.\n\n- Each small stuffed animal costs $4, so the total revenue from small stuffed animals is $ 4x $.\n- She sold twice as many small stuffed animals as large ones, so the number of large stuffed animals is $ x/2 $.\n- She sold $ 2x $ large stuffed animals and $ x $ small stuffed animals, so the total sales are $ 2x + x = 3x $.\n- She earned $120 from the sales, so:\n\n$$\n3x = 120\n$$\n\n$$\nx = 40\n$$\n\n### Final Answer:\n$$\n\\boxed{40}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The family eats:\n\n- 5 sandwiches/day × 7 days = 35 sandwiches \n- 4 sandwiches/day × 7 days = 28 sandwiches \n- 2 sandwiches/day × 7 days = 14 sandwiches \n\nTotal: 35 + 28 + 14 = **77 sandwiches**\n\n$$\n\\boxed{77}\n$$" + } + ] + }, + "durable": { + "variant": "durable", + "seed": 20261127, + "attempted_groups": 128, + "train_steps": 128, + "lost_groups": 0, + "sampled_sequences": 512, + "nontrivial_advantage_groups": 67, + "sample_accuracy": 0.4140625, + "sample_format": 0.66015625, + "sample_reward": 0.5460937500000006, + "mean_loss": 2.8571193269453943, + "elapsed_s": 2228.2679600100964 + }, + "durable_eval": { + "accuracy": 0.453125, + "format": 0.7890625, + "reward": 0.6109374999999994, + "samples": [ + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Era read **300 books** this hour, and decided to read **150 more**. So, the total number of books they have read is:\n\n$$\n300 + 150 = \\boxed{450}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tanya earns:\n\n- $15 per hour for 4 classes: $15 × 4 = 60\n- $15 per hour for 2 classes: $15 × 2 = 30\n\nTotal earnings for Monday: $60 + $30 = $90\n\nTotal earnings for Wednesday: $90\n\nTotal earnings for both days: $90 + $90 = $\\boxed{180}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The perfume company sells:\n- 5 vanilla scents\n- 2 fruity scents\n\nSo, the difference is:\n\n$$\n5 - 2 = \\boxed{3}\n$$\n\n**Answer:** $\\boxed{3}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bennet sells 20 eggplants for $3 each, so the total revenue from eggplants is:\n\n$$\n20 \\times 3 = 60 \\text{ dollars}\n$$\n\nHe wants to make a total of $135, so the remaining amount he needs to make from corn is:\n\n$$\n135 - 60 = 75 \\text{ dollars}\n$$\n\nHe has 25 ears of corn, so the price per ear of corn should be:\n\n$$\n\\frac{75}{25} = 3 \\text{ dollars per ear of corn}\n$$\n\n### Final Answer:\n$$\n\\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Tatiana has:\n- 7 hours on Saturday\n- 5 hours on Sunday\n\nShe reads for 3 hours, and plays video games for $ \\frac{1}{3} $ of the remaining time.\n\n- Remaining time after reading: $ 7 + 5 - 3 = 9 $ hours\n- Video games time: $ \\frac{1}{3} \\times 9 = 3 $ hours\n\nShe spends playing soccer for the remaining time: $ 9 - 3 = 6 $ hours\n\nTo find the percentage of her weekend spent playing soccer:\n\n$$\n\\frac{6}{7 + 5} \\times 100 = \\frac{6}{12} \\times 100 = 50\\%\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Anthony had 50 pencils.\n\n- He gave **1/2** of his pencils to Brandon: \n $ \\frac{1}{2} \\times 50 = 25 $ pencils.\n\n- He gave **3/5** of the remaining pencils to Charlie: \n Remaining pencils after giving 25: $ 50 - 25 = 25 $.\n\n- He gave $ \\frac{3}{5} \\times 25 = 15 $ pencils to Charlie.\n\n- Remaining pencils after giving to Charlie: \n $ 25 - 15 = 10 $.\n\n**Answer:** $ \\boxed{10} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jack drives **150 miles** to the museum and **150 miles** back. \nHe drives at **75 mph**, so the total driving time is: \n$$\n\\frac{150 \\text{ miles}}{75 \\text{ mph}} = 2 \\text{ hours}\n$$\n\nHe spends **6 hours** at the museum. \nSo, the total time from home is: \n$$\n2 \\text{ hours} + 6 \\text{ hours} = \\boxed{8} \\text{ hours}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Henry needs:\n- $ 57 \\times 4 = 228 $ wheels for cars \n- $ 73 \\times 2 = 146 $ wheels for motorcycles \n\nTotal wheels used: \n$ 228 + 146 = 374 $ wheels \n\nHe has a box with 650 wheels. \n\nWheels left: \n$ 650 - 374 = \\boxed{276} $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The original price of the laptop is $1000. \nA 20% discount means you pay 80% of the original price. \n\n$$\n\\text{Discount amount} = 1000 \\times 0.20 = 200\n$$\n\n$$\n\\text{Final price} = 1000 - 200 = 800\n$$\n\n**Answer:** $\\boxed{800}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Mike has 600 movies:\n\n- **A third** of the movies are in series: \n $ \\frac{1}{3} \\times 600 = 200 $ movies.\n\n- **40%** of the remaining movies are older movies: \n $ 0.40 \\times 400 = 160 $ movies.\n\n- The remaining movies are: \n $ 600 - 200 - 160 = 240 $ movies.\n\n- The cost of a normal movie is $10, and the series cost is $6. \n So, the cost of the series movies is: \n $ 200 \\times 6 = 1200" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Winston picked:\n- 6 pounds of peaches at $2.00 per pound: $6 \\times 2 = 12\n- 8 pounds of plums at $1.00 per pound: $8 \\times 1 = 8\n- 6 pounds of apricots at $3.00 per pound: $6 \\times 3 = 18\n\nTotal cost: \n$$ 12 + 8 + 18 = \\boxed{38} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the speed of the car be $ v $ miles per hour. Then the speed of the hike is $ \\frac{v}{2} $ miles per hour.\n\nThey drove for 6 hours at 50 mph, so the distance covered is:\n\n$$\n6 \\times 50 = 300 \\text{ miles}\n$$\n\nThey hiked for 1.5 hours at $ \\frac{v}{2} $ mph, so the distance covered is:\n\n$$\n1.5 \\times \\frac{v}{2} = \\frac{3v}{4}\n$$\n\nThe total distance to the vacation spot is the sum of the two distances:\n\n$$\n300 + \\frac{3v}{4}\n$$\n\nSince the problem does not" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ava jumps on 8 more enemies than Emma, so Ava's score is:\n$$ 8 \\times 10 + 3 = 83 $$\n\nEmma collects 3 more berries than Ava, so Emma's score is:\n$$ 3 \\times 5 + 3 = 18 $$\n\nThey finish the level 4 seconds slower, so Emma's score is:\n$$ 83 - 4 = 79 $$\n\nThe difference between their scores is:\n$$ 83 - 79 = \\boxed{4} $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The total cost of the four pizzas is $64.\n\nTwo of the pizzas cost $30 each, so the cost of the other two is:\n\n$$\n64 - 30 - 30 = 64 - 60 = 4\n$$\n\nEach of the other two pizzas costs:\n\n$$\n\\boxed{4}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Chase and Rider ride their bikes **3 times a day** for **5 days**, and **2 times the times** on **2 other days**. \nSo, total rides per week: \n- 3 × 5 = 15 \n- 2 × 2 = 4 \n- Total: 15 + 4 = **19** times a week.\n\n$$\n\\boxed{19}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bob had 7 fish in his pond, 3 orange and 4 white. He decided to buy some more fish. After buying, the total number of fish in the pond was **twice as many orange as white**.\n\nLet:\n- $ x $ = number of white fish Bob bought\n- $ y $ = number of orange fish Bob bought\n\nSo:\n- Initial fish: 3 orange, 4 white\n- After buying: $ 3 + x $ orange, $ 4 + x $ white\n\nHe now has:\n- $ 3 + x $ orange\n- $ 4 + x $ white\n\nAnd the total number of fish is:\n$$\n(3 + x) + (4 + x) = 7 + 2x\n$$\n\n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Andy's car consumes:\n\n$$\n10 \\, \\text{MPG} \\times 5 \\, \\text{miles} = 50 \\, \\text{miles per week}\n$$\n\nSince the price of gas is $3 per gallon, the cost per week is:\n\n$$\n50 \\, \\text{miles} \\times 3 \\, \\text{\\$/gallon} = \\boxed{150} \\, \\text{\\$/week}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Carrie was given:\n\n- **10 twenties** = $10 \\times 20 = 200$\n- **140 quarters** = $140 \\times 25 = 3500$\n\nShe spent:\n\n- **3/5 of the twenties**: $ \\frac{3}{5} \\times 200 = 120 $\n- **3/5 of the quarters**: $ \\frac{3}{5} \\times 3500 = 2100 $\n\nTotal amount paid:\n\n$$\n200 + 3500 - 120 - 2100 = \\boxed{2000} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ricardo plants 5 tomato plants, each yielding 22 tomatoes, and 8 eggplant plants, each yielding 4 eggplants.\n\n- Tomatoes: $5 \\times 22 = 110$\n- Eggplants: $8 \\times 4 = 32$\n\nTotal fruits: $110 + 32 = \\boxed{142}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Samwell sells a total of 40 TVs this week.\n\n- One-fourth of the sales are smart TVs: \n $ \\frac{1}{4} \\times 40 = 10 $\n\n- One-eighth of the sales are analog TVs: \n $ \\frac{1}{8} \\times 40 = 5 $\n\n- The rest are OLED TVs: \n $ 40 - 10 - 5 = 25 $\n\n**Answer:** $ \\boxed{25} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John has $50 and the trip costs $300. Since the school covers half of the cost, the amount John is missing is:\n\n$$\n300 - 50 = \\boxed{250}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Every log of wood Carson burns heats the house up by 5 degrees. The temperature during the day is 45 degrees, and during the night it is 33 degrees colder. So the temperature during the night is:\n\n$$\n45 - 33 = 12 \\text{ degrees}\n$$\n\nTo prevent the pipes from freezing, Carson needs to heat the house up to 32 degrees. Since each log heats the house by 5 degrees, the number of logs needed is:\n\n$$\n\\frac{32 - 12}{5} = \\frac{20}{5} = 4\n$$\n\n$$\n\\boxed{4} \\text{ logs}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are told:\n\n- 90 people were required to split into **9-person groups**.\n- Each group has **3/5 of the number of groups**.\n- Each group brings **2 seashells**.\n\n### Step 1: Find the number of groups\n\n$$\n\\text{Number of groups} = \\frac{3}{5} \\times 90 = 54\n$$\n\n### Step 2: Find the total number of seashells\n\n$$\n\\text{Total seashells} = 54 \\times 2 = 108\n$$\n\n### Final Answer:\n\n$$\n\\boxed{108}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Initially, there are 172 people on the train.\n- At the first stop, 47 people get off and 13 more get on: \n $ 172 - 47 + 13 = 138 $.\n- At the next stop, 38 people get off: \n $ 138 - 38 = 100 $.\n\n**Final Answer:** $\\boxed{100}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Damien finds **10 bottle caps per day** and each is worth **$.25**.\n\nIn a **30-day month**, he makes:\n\n$$\n10 \\text{ caps/day} \\times 30 \\text{ days} \\times 0.25 \\text{ dollars/cap} = 75 \\text{ dollars}\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{75}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jamie earns $20 per hour for 8 hours each day. If she works additional hours, she is paid 150% of her regular hourly rate. Last Tuesday, she worked 11 hours.\n\n- Regular hourly rate: $20\n- Additional hours: $11 - 8 = 3$ hours\n- Special rate: $20 \\times 1.5 = 30$ dollars per hour\n- Total pay: $3 \\times 30 = \\boxed{90}$\n\n**Final answer:** $\\boxed{90}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The zookeeper counts:\n\n- 12 female lions \n- Half as many male lions = $ \\frac{12}{2} = 6 $ male lions \n- 14 lion cubs \n\nSo, the total number of lions is:\n\n$$\n12 + 6 + 14 = \\boxed{32}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mike paid with a $50.00 bill, and the jeans were 25% off the original price of $40. \nSo, the discount amount is: \n$$ 25\\% \\times 40 = 10 $$\n\nMike will have: \n$$ 50 - 10 = 40 $$\n\n**Final answer:** $\\boxed{40}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The company pays:\n\n- 20 employees per month \n- $4000 per employee \n- For 3 months\n\nTotal amount paid = $20 \\times 4000 \\times 3 = \\boxed{240000}$." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The choir will sing:\n\n- \"Deck the Halls\" twice: $ 150 \\, \\text{seconds} \\times 2 = 300 \\, \\text{seconds} $\n- \"Jingle Bells\" once: $ 240 \\, \\text{seconds} $\n\nSo, the total time is:\n\n$$\n\\boxed{300 + 240 = \\boxed{540}} \\, \\text{seconds}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Billy's starting salary is $10 per hour. \nAfter 2 months, he gets a raise of $0.50 per hour, so his salary becomes: \n$$ 10 + 0.50 = 10.50 \\, \\text{per hour} $$\n\nOn his first anniversary, he gets an additional raise of $1.00 per hour: \n$$ 10.50 + 1.00 = 11.50 \\, \\text{per hour} $$\n\nSo, Billy's total earnings for 20 hours: \n$$ 11.50 \\times 20 = 230 \\, \\text{dollars} $$\n\nSally starts with a salary of" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- 1 loaf of bread costs $2.\n- 2 bagels cost $1 each, so $2 \\times 1 = \\$2$.\n\n- The difference is $2 - 2 = \\$0$.\n\n**Final Answer:** $\\boxed{0}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Pierson scored **278 points**.\n\nNikita scored **11 more than half as many as Pierson**, so:\n\n$$\n\\frac{278}{2} = 139\n$$\n\n$$\n139 + 11 = 150\n$$\n\nSo, the total points scored by both is:\n\n$$\n278 + 150 = \\boxed{428}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- There are **40 classes**.\n- Each class has **25 students** and **3 teachers**, so each class has:\n $$\n 25 + 3 = 28 \\text{ students and teachers}\n $$\n- Total number of students and teachers:\n $$\n 40 \\times 28 = 1120\n $$\n- Each child plants **1 tree**, and each teacher plants **2 trees**, so total trees:\n $$\n 1120 \\times 1 + 1120 \\times 2 = 1120 + 2240 = \\boxed{3360}\n $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Bubbles has:\n\n- 3 stuffed puppies \n- 5 stuffed koalas \n- 2 stuffed zebras \n- 4 stuffed frogs \n\nTotal = $ 3 + 5 + 2 + 4 = 14 $ stuffed animals.\n\nShe wants to buy $ x $ stuffed goats, so the total number of stuffed animals will be $ 14 + x $.\n\nShe wants the percentage of goats to be 30% of all stuffed animals:\n\n$$\n\\frac{x}{14 + x} = 0.30\n$$\n\nSolving:\n\n$$\nx = 0.30(14 + x) = 4.2 + 0.3x\n$$\n\n$$\nx - 0.3x = " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kris plays for:\n\n- **0.5 hours** per day for **2 weeks** = $ 0.5 \\times 2 \\times 7 = 7 $ hours\n\nShe plays for:\n\n- **2 hours** per day for **1 week** = $ 2 \\times 7 = 14 $ hours\n\nTotal hours played: \n$ 7 + 14 = 21 $ hours\n\nShe needs to play for **30 hours** to earn the achievement.\n\nSo, the answer is: \n$$\n\\boxed{9}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The first car is traveling at 60 mph, and the second at 70 mph. After 2 hours, the distance between them will be:\n\n$$\n(70 - 60) \\times 2 = 20 \\text{ miles}\n$$\n\n$$\n\\boxed{20}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James pays a 30% premium on the total cost of the ring and gold. The total cost is:\n\n$$\n600 + 300 = 900\n$$\n\nHe pays 30% of this amount:\n\n$$\n0.30 \\times 900 = 270\n$$\n\nSo, James paid:\n\n$$\n\\boxed{270}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 340 out of 500 third-graders passed.\n- 40 out of 100 fourth-graders passed.\n- 400 fifth-graders had a pass rate that was **twice** the fourth-graders' pass rate.\n\nLet’s calculate the **overall pass rate**.\n\n### Step 1: Convert to total pass rate\n\n- **Third graders**: \n $ \\frac{340}{500} = 0.68 $ or **68%**\n\n- **Fourth graders**: \n $ \\frac{40}{100} = 0.40 $ or **40%**\n\n- **Fifth graders**: \n $ \\frac{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Milo wants his mosaic to be **three inches tall**. \nEach square inch of the mosaic uses **12 glass chips**. \nHe has **2 bags** of glass chips, each containing **72 chips**.\n\nSo, the total number of glass chips is:\n\n$$\n2 \\times 72 = 144 \\text{ chips}\n$$\n\nSince each square inch uses **12 chips**, the total area of the mosaic is:\n\n$$\n\\frac{144}{12} = 12 \\text{ square inches}\n$$\n\nSince the mosaic is **3 inches tall**, the length of the mosaic is:\n\n$$\n\\frac{12}{3} = 4 \\text{ inches}\n$$\n\n$$\n\\boxed{" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- 10 quarts of tea left\n- 4 students each drank 1.5 quarts\n- 16 students each drank 2 quarts\n\n### Step 1: Calculate the total amount of tea consumed\n\n$$\n\\text{Total consumed} = (4 \\times 1.5) + (16 \\times 2) = 6 + 32 = 38 \\text{ quarts}\n$$\n\n### Step 2: Convert quarts to gallons\n\n$$\n1 \\text{ quart} = 0.25 \\text{ gallons}\n$$\n\n$$\n38 \\text{ quarts} = 38 \\times 0.25 = 9.5 \\text{ gallons" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dale started with 100 candies and sold 150. He then ordered 100 more. \nSo, the total number of candies he has is:\n\n$$\n100 + 100 = 200\n$$\n\nHe needs to sell **200 - 150 = 50** candies to sell all of his candy.\n\n$$\n\\boxed{50}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told that the number of students on campus **doubles every month** at the end of the month. At the **beginning of the year**, there are **10 students**.\n\nWe are to find how many **additional students** would have joined by the **end of May**, **above and beyond** the number already on campus at the beginning of the year.\n\n### Step-by-step:\n\n- **Start of the year**: 10 students \n- **End of January**: 10 × 2 = 20 students \n- **End of February**: 20 × 2 = 40 students \n- **End of March**: 40 × 2 = 80 students \n- **End of April**: 80 × 2" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Felix earns $105 during the week, and each climb costs $0.25. \nSo, the number of branches climbed per day is:\n\n$$\n\\frac{105}{0.25} = 420\n$$\n\n$$\n\\boxed{420}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- First set: $ 3 \\times 5 = 15 $ petals \n- Second set: $ 4 \\times 6 = 24 $ petals \n- Third set: $ 5 \\times 4 = 20 $ petals \n- Fourth set: $ 6 \\times 7 = 42 $ petals \n\nTotal petals: \n$$\n15 + 24 + 20 + 42 = \\boxed{101}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John and DeSean made a total of 35 marshmallows. \nThey each made 9 S'mores, so they used:\n\n$$\n9 + 9 = 18 \\text{ marshmallows}\n$$\n\nThey dropped 3 marshmallows, so the number of marshmallows left is:\n\n$$\n35 - 18 = 17\n$$\n\nEach kid can have 1 S'more with the remaining marshmallows, so:\n\n$$\n\\boxed{1} \\text{ S'more each}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jack plays with his 3 friends, and the total time they play is 4 hours. \n- One friend plays for 1.5 times as long as Jack: $1.5 \\times 20 = 30$ minutes \n- Two friends play for half as long: $1/2 \\times 20 = 10$ minutes \n- Total time: $30 + 10 + 20 = 60$ minutes = 1 hour\n\nJack spends $1$ quarter per 20 minutes, so he uses:\n\n$$\n1 \\times 1 = \\boxed{1}\n$$\n\n**Answer:** $\\boxed{1}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let:\n- $ s $ = amount of salt used\n- $ c $ = amount of citrus zest used\n- $ o $ = amount of oil used\n- $ g $ = amount of sugar used\n\nWe are given:\n- $ s = g $\n- $ c = o $\n- $ o = 2s $\n- $ o = 2s $\n\nFrom $ o = 2s $, we get:\n$$\no = 2s\n$$\n\nSince $ o = 2s $, and $ s = g $, then:\n$$\no = 2g\n$$\n\nSo, the amount of oil used is:\n$$\n\\boxed{2g}\n$$\n\nBut since $ g = s $, and $ o = 2s $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John buys:\n- 3 goats at $500 each: $3 \\times 500 = 1500\n- 2 cows at $1500 each: $2 \\times 1500 = 3000\n\nTotal cost: \n$$ 1500 + 3000 = \\boxed{4500} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Paul needs **63 cupcakes** for the party. He already has:\n\n- **8 chocolate cupcakes**\n- **40 toffee cupcakes**\n\nSo, the total number of cupcakes he already has is:\n\n$$\n8 + 40 = 48\n$$\n\nTo find how many more he needs:\n\n$$\n63 - 48 = \\boxed{15}\n$$\n\n**Answer:** $\\boxed{15}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Joe has twice as many cars as Robert: \n- Robert has 20 cars, so Joe has $ 2 \\times 20 = 40 $ cars.\n\nJoe sells 20% of his cars: \n- 20% of 40 is $ 0.2 \\times 40 = 8 $ cars.\n\nJoe gives away twice as many cars as the number he sold to his mother: \n- Let the number he sold to his mother be $ x $, then he gives away $ 2x $ cars.\n\nSo, the total number of cars Joe gives away is $ 8 + 2x $.\n\nJoe's remaining cars after selling and giving away are: \n- $ 40 - 8 - 2x $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 20 students, and $50,000 comes from organizations. The remaining $175,000 - $50,000 = $125,000 is from the students.\n\nEach student raises:\n\n$$\n\\frac{125,000}{20} = 6,250\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{6250}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sandy walked for 8 hours on the first day, and half as many hours on the second day, which is:\n\n$$\n\\frac{1}{2} \\times 8 = 4 \\text{ hours}\n$$\n\nTotal time in hours:\n\n$$\n8 + 4 = 12 \\text{ hours}\n$$\n\nConvert to minutes:\n\n$$\n12 \\times 60 = \\boxed{720} \\text{ minutes}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Hunter counted 50 cars during class. \nThen, he counted **20 more** cars during the first break, making it **70** cars. \n\nAfter lunch, **1/2** of the total cars had gone, so the remaining cars are: \n$$\n70 - \\frac{1}{2} \\times 70 = 70 - 35 = 35\n$$\n\nThus, the total number of cars he counted during lunch break is: \n$$\n\\boxed{35}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John does 30 cycles per day, each cycle has 5 tasks, and each task pays $1.20.\n\n- Total tasks per day: $ 30 \\times 5 = 150 $\n- Total earnings per day: $ 150 \\times 1.20 = 180 $\n- Total earnings for 7 days: $ 180 \\times 7 = \\boxed{1260} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Sasha scored 14 points in the first game. \nJulie scored 4 fewer points than Sasha, so she scored **10** points in the first game. \n\nSasha scored 6 fewer points in the second game than Julie's score in the first game, so she scored **4** points in the second game. \n\nTotal points: \n$$ 14 + 10 + 4 = \\boxed{28} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kimberly bought:\n- 8 packages of cat food, each with 11 tins: $ 8 \\times 11 = 88 $ tins\n- 6 packages of dog food, each with 6 tins: $ 6 \\times 6 = 36 $ tins\n\nThe difference in the number of tins is:\n$$\n88 - 36 = \\boxed{52}\n$$\n\nSo, Kimberly bought **52 more tins of cat food than dog food**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let:\n- $ x $ = number of cards PJ has,\n- $ y $ = number of cards Smendrick has,\n- $ z $ = number of cards Becca has.\n\nWe are given:\n1. $ z = x + 12 $ (Becca has 12 more than Smendrick),\n2. $ y = 3x $ (Smendrick has 3 times the number of cards that PJ has),\n3. Total cards: $ x + y + z = 341 $.\n\nSubstitute $ y = 3x $ and $ z = x + 12 $ into the total:\n\n$$\nx + 3x + (x + 12) = 341\n$$\n\n$$\n5x +" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cindy had:\n\n- 5 green eggs \n- 2 × 5 = 10 blue eggs \n- 10 - 1 = 9 pink eggs \n- 1/3 × 9 = 3 yellow eggs \n\nTotal eggs = $ 5 + 10 + 9 + 3 = \\boxed{27} $." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Milly needs to return a book that weighs **4 pounds**, cost **$32**, and is **20 miles away**.\n\n- **Shipping cost**:\n - $0.35 per pound: $0.35 × 4 = \\$1.40\n - $0.08 per mile: $0.08 × 20 = \\$1.60\n - **Total shipping cost**: \\$1.40 + \\$1.60 = **\\$3.00**\n\n- **Amazon will only refund 75% of the book's purchase price**:\n - Refund amount: $0.75 × \\$32 = \\$24\n\n- **Total money Milly will lose**:\n " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mulan starts with $40. \nHer father gives her $100, so she has $140. \n\nShe buys: \n- Two pairs of jeans at $30 each = $60 \n- A bag for $20 \n\nTotal spent: $60 + $20 = $80 \n\nMoney left: $140 - $80 = $\\boxed{60}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Boris produces:\n\n- **Week 1**: 8,000 bars \n- **Week 2**: $ \\frac{1}{2} \\times 8,000 = 4,000 $ bars \n- **Week 3**: $ 3 \\times 8,000 = 24,000 $ bars \n\n**Week 4**: He produces **half as much as the first week**, so:\n\n$$\n\\frac{1}{2} \\times 8,000 = 4,000\n$$\n\n**Final Answer:** $\\boxed{4000}$ bars." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Britany records **18 videos** each week, each lasting **4 minutes**. \nSo, the total time spent on recording is: \n$$ 18 \\times 4 = 72 \\text{ minutes} $$\n\nShe spends **2 hours** writing songs a week, which is **120 minutes**. \nShe spends **15 minutes** doing makeup six days a week. \nSo, the total time spent on makeup is: \n$$ 15 \\times 6 = 90 \\text{ minutes} $$\n\nNow, add all the times together: \n$$ 72 + 120 + 90 = \\boxed{300} \\text{ minutes} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Angela has:\n- 6 mirrors \n- 2 chandeliers \n- 20 pictures \n\nShe needs to install:\n- 4 mirrors \n- 2 shelves \n- 1 chandelier \n- 10 pictures \n\n**Cost of installation items:**\n- Mirrors: $129.00 \n- Shelves: $129.00 \n- Chandeliers: $129.00 \n- Pictures: $129.00 \n\n**Total cost for installation items:**\n$$\n(4 + 2 + 1 + 10) \\times 129 = 17 \\times 129 = 2193\n$$\n\n**Additional cost:**\n- $1" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Roy has saved **40% more** than his brother Anthony. \nAnthony has saved **$10.00 more** than their sister Eva. \nEva has saved **$20.00**.\n\nLet’s solve step by step:\n\n- Eva = $20.00 \n- Anthony = Eva + $10.00 = $20.00 + $10.00 = **$30.00** \n- Roy = Anthony + 40% of Anthony = $30.00 + 0.40 × $30.00 = $30.00 + $12.00 = **$42.00**\n\n**Answer:** $\\boxed{42" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- **Pompei** can lift a mountain **1 inch**.\n- **Saskay** can lift a mountain **12 times higher** than Pompei: \n $ 12 \\times 1 = 12 $ inches.\n- **Kagiyami** can lift a mountain **4 times higher** than Saskay: \n $ 12 \\times 4 = 48 $ inches.\n- **Naruto** can lift a mountain **10 times higher** than Kagiyami: \n $ 48 \\times 10 = 480 $ inches.\n\nConvert inches to feet: \n$ 480 \\, \\text{inches} = 480 \\div" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mason travels for 4 hours at 8 mph, so:\n\n$$\n8 \\times 4 = 32 \\text{ miles}\n$$\n\nThen he takes some rest, and then travels for another 6 hours:\n\n$$\n8 \\times 6 = 48 \\text{ miles}\n$$\n\nSo, the total distance is:\n\n$$\n32 + 48 = \\boxed{80} \\text{ miles}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "If 3 kangaroos take 18 hours to cross the highway, then:\n\n- 3 kangaroos = 18 hours \n- 1 kangaroo = 6 hours\n\nSo, 1 kangaroo = 6 hours.\n\nNow, 4 turtles, each traveling at half the speed of a kangaroo, would take:\n\n- 4 × 6 = 24 hours\n\n**Answer:** $\\boxed{24}$ hours." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jada makes twice as many as Rory: \n$$ 2 \\times 20 = 40 \\text{ dishes} $$\n\nRory makes 20 more than Kora: \n$$ 20 + 20 = 40 \\text{ dishes} $$\n\nKora makes 20 dishes.\n\nTotal number of dishes: \n$$ 40 + 40 + 20 = \\boxed{100} $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Erika has already saved:\n\n- $150 from her part-time job \n- $80 from her mom \n- $600 from her savings\n\nSo, total money she has is:\n\n$$\n150 + 80 + 600 = \\boxed{830}\n$$\n\nShe needs an extra $50 to buy the laptop, so:\n\n$$\n830 - 50 = \\boxed{780}\n$$\n\n**Final Answer:** $\\boxed{780}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Adam slices:\n- 3 large apples: $3 \\times 5 = 15$ slices \n- 5 small apples: $5 \\times 3 = 15$ slices \n\nTotal slices: $15 + 15 = 30$ slices.\n\nHe eats 15 slices, so the number of apple slices left is:\n\n$$\n\\boxed{15}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The farmer extracts 5 liters of milk per day from a single cow. Since he has 3 cows, the total milk extracted per day is:\n\n$$\n5 \\text{ liters/cow} \\times 3 \\text{ cows} = 15 \\text{ liters/day}\n$$\n\nHe wants to produce **25 liters of milk a day**. To find how many more cows he needs, we subtract the current milk production from the desired amount:\n\n$$\n25 \\text{ liters/day} - 15 \\text{ liters/day} = 10 \\text{ liters/day}\n$$\n\nSo, he needs **10 more cows** to produce 25 liters of milk a day.\n\n$$\n\\boxed{10}" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Patrick has three glue sticks:\n\n- First: $ \\frac{1}{6} $ left → $ 12 \\times \\frac{1}{6} = 2 $ mm\n- Second: $ \\frac{2}{3} $ left → $ 12 \\times \\frac{2}{3} = 8 $ mm\n- Third: $ \\frac{1}{2} $ left → $ 12 \\times \\frac{1}{2} = 6 $ mm\n\nTotal length not used: \n$$\n2 + 8 + 6 = \\boxed{16} \\text{ mm}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Gabriel has:\n- $5000 from working on weekends\n- $200 from his brother\n\nTotal money he has: \n$$ 5000 + 200 = 5200 $$\n\nHe needs: \n$$ 10000 + 800 = 10800 $$\n\nHe still needs: \n$$ 10800 - 5200 = \\boxed{5600} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The craftsman gave Thea **four $20 bills**, totaling:\n\n$$\n4 \\times 20 = 80 \\text{ dollars}\n$$\n\nShe paid **$70**, so the change is:\n\n$$\n80 - 70 = \\boxed{10} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Craig has:\n- 2 twenty dollar bills = $40\n- 6 squirt guns for $2 each = $12\n- 3 packs of water balloons for $3 each = $9\n\nTotal money spent: $40 + $12 + $9 = $61\n\nHe has $40 left.\n\n$$\n\\boxed{40}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Peter has **twice as many socks as Jack**, and **half as many dishes as Jack**. \nJack collected **60 dishes**.\n\n- Number of dishes: $60$\n- Number of socks: $2 \\times \\text{number of socks} = 2 \\times (2 \\times \\text{number of socks}) = 4 \\times \\text{number of socks}$\n- So, number of socks = $ \\frac{60}{2} = 30 $\n\n- Total number of socks and dishes: \n $60 + 30 = \\boxed{90}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are told:\n\n- There are **20 students** in the class.\n- **5 students** are good at **math only**.\n- **8 students** are good at **English only**.\n- The rest are good at **both math and English**.\n\nSo, the number of students who are good at **both** is:\n\n$$\n20 - 5 - 8 = 7\n$$\n\n### Final Answer:\n$$\n\\boxed{7}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Vicki allows a 10-minute intermission, which means the total time for the concert is:\n\n$$\n2 \\text{ hours} + 10 \\text{ minutes} = 120 \\text{ minutes}\n$$\n\nEach group takes:\n\n- 2 minutes to get on stage \n- 6 minutes to perform \n- 2 minutes to exit the stage \n\nSo, each group takes $2 + 6 + 2 = 10$ minutes.\n\nNow, the number of groups that can perform is:\n\n$$\n\\frac{120 \\text{ minutes}}{10 \\text{ minutes/group}} = 12\n$$\n\n$$\n\\boxed{12}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Brenda invested $300 into a scheme that accumulates **simple interest** at the rate of **three-quarters of the original amount per year**.\n\n### Step 1: Understand the interest rate\nThe interest rate is:\n$$\n\\frac{3}{4} \\times 300 = 225 \\text{ dollars per year}\n$$\n\n### Step 2: Use the formula for simple interest\n$$\n\\text{Total amount} = P + I = P + P \\times r \\times t\n$$\nWhere:\n- $ P = 300 $ (original investment),\n- $ r = 225 $ (annual interest rate),\n- $ t = 3 $ (time in years).\n\n$$\n\\text{" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- There are **40 white shirts**.\n- Half of the white shirts have collars: $ \\frac{40}{2} = 20 $.\n- There are **50 floral shirts**.\n- **20 of the floral shirts** have buttons.\n- The number of floral shirts with **no buttons** is $ 50 - 20 = 30 $.\n\nSo, the number of **more floral shirts with no buttons** than white shirts with no collars is:\n\n$$\n\\boxed{30}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The farmer places 900 eggs on a tray, which holds 30 eggs. \nEach tray sells for $2.5. \n\nSo, the number of trays is: \n$$\n\\frac{900}{30} = 30\n$$\n\nNow, multiply by the price per tray: \n$$\n30 \\times 2.5 = 75\n$$\n\n**Final Answer:** $\\boxed{75}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Initially, there are:\n - 55 goats in Farm X\n - 45 goats in Farm Y\n\n- He sold:\n - 10 goats from Farm X\n - 2 × 10 = 20 goats from Farm Y\n\n- Total goats sold: $10 + 20 = 30$\n\n- Total goats left: \n $55 + 45 - 30 = \\boxed{70}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "James buys **2 pairs of shoes** a month, and **$2640** is spent on shoes **each year**.\n\n- Each year, he buys **2 pairs** → total per year = $2640 \n- So, the average cost per pair = $2640 ÷ 2 = $1320\n\n**Answer:** $\\boxed{1320}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- A basket of green food costs $25.\n- A basket of red food costs $18.\n- If you buy 3 baskets of green food and 3 baskets of red food, you pay:\n $$\n 3 \\times 25 + 3 \\times 18 = 75 + 54 = 129\n $$\n- Since you get $2 off for each basket of red food, you save:\n $$\n 3 \\times 2 = 6\n $$\n- So the total cost is:\n $$\n 129 - 6 = \\boxed{123}\n $$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "There are 90 rooms, and it takes 20 minutes to clean each room.\n\n- Total time to clean 90 rooms: \n $ 90 \\times 20 = 1800 $ minutes.\n\n- Convert minutes to hours: \n $ 1800 \\div 60 = 30 $ hours.\n\n**Answer:** $\\boxed{30}$ hours." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- First year: $12$ homes \n- Second year: $3 \\times 12 = 36$ homes \n- Third year: $2 \\times 36 = 72$ homes \n\nTotal: $12 + 36 + 72 = \\boxed{120}$ homes." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the age of the sister be $ x $, the brother be $ y $, and the person be $ z $.\n\nWe are told:\n\n- $ z = y + 2 $ (I am 2 years older than my sister)\n- $ z = y - 3 $ (I am 3 years younger than my brother)\n- $ z + x + y = 87 $ (sum of all ages)\n\nFrom the first two equations:\n\n- $ z = y + 2 $\n- $ z = y - 3 $\n\nSo:\n\n$$\ny + 2 = y - 3 \\Rightarrow 2 = -3\n$$\n\nThis is a contradiction, so there must be a mistake in the problem setup.\n\nLet’s re-express the problem:\n\nLet" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Jackson has 27 students, and each student needs 2 glue sticks. So, the total number of glue sticks needed is:\n\n$$\n27 \\times 2 = 54\n$$\n\nEach pack contains 8 glue sticks, so the number of packs needed is:\n\n$$\n\\frac{54}{8} = 6.75\n$$\n\nSince he can only buy whole packs, he needs to buy **7 packs**.\n\n$$\n\\boxed{7}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- The amount of water passing through the river at one point is **4000 gallons**.\n- It **doubles** after a day of heavy rain: $ 4000 \\times 2 = 8000 $ gallons.\n- On the **third day**, the volume increases by **6000 gallons**.\n\nSo, the total amount of water passing through the river at that point is:\n\n$$\n4000 + 8000 + 6000 = \\boxed{18000} \\text{ gallons}.\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Every day, each infected person infects 6 others, and there are 10 people initially. After 3 days, the total number of infected people is:\n\n$$\n10 \\times 6 \\times 3 = \\boxed{180}\n$$\n\nSo, the final answer is:\n\n$$\n\\boxed{180}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each of the 40 customers gave Rafaela a $20 tip, so:\n\n- Rafaela received: $ 40 \\times 20 = 800 $ dollars.\n\nJulieta received **10% less** than Rafaela, so:\n\n- Julieta received: $ 800 - (0.10 \\times 800) = 800 - 80 = 720 $ dollars.\n\n**Total tips received by both:** \n$ 800 + 720 = \\boxed{1520} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jennifer bought 12 oranges.\n\n- She gave her **3 daughters** 2 oranges each: $ 3 \\times 2 = 6 $ oranges.\n- Her **only boy** got 3 oranges.\n\nSo, the total number of oranges given away is $ 6 + 3 = 9 $.\n\nThe number of oranges she **remained with** is:\n\n$$\n12 - 9 = \\boxed{3}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Claire earns 1 badge per month. \nAmber earns **twice** as long as Claire, so she earns **2 badges per month**. \nWendy earns **three times** as many badges as Claire in the same time frame, so she earns **3 badges per month**.\n\nIn a **1-year** time frame, Claire earns: \n$$ 12 \\text{ badges} $$\n\nAmber earns: \n$$ 2 \\times 12 = 24 \\text{ badges} $$\n\nWendy earns: \n$$ 3 \\times 12 = 36 \\text{ badges} $$\n\nNow, find how many more badges Wendy earns compared to Amber: \n$$ 36 - 24 = \\boxed" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Every hour, Paige can bake 2 banana bread loaves, each cut into 8 slices, and each slice sold for 50 cents.\n\n- In 1 hour, she bakes 2 loaves × 8 slices = 16 slices.\n- In 5 hours (from 1:00 PM to 6:00 PM), she bakes 5 × 16 slices = 80 slices.\n- Total revenue = 80 slices × 50 cents = 4,000 cents = $40.\n\n$$\n\\boxed{40}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the number of silver coins be $ x $. \nThen the number of gold coins is $ x + 30 $.\n\nIf she had 70 gold coins, the number of silver coins would be $ x $, and the total number of coins would be:\n\n$$\nx + (x + 30) = 2x + 30\n$$\n\nBut we are told that she had **70 gold coins**, so:\n\n$$\nx + 30 = 70 \\Rightarrow x = 40\n$$\n\nThus, the total number of coins is:\n\n$$\n40 + 70 = \\boxed{110}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "George ordered 600 burritos for 50 students, and each student was given 10 burritos. \n- Total burritos given to students: $ 50 \\times 10 = 500 $ \n- Mr. George eats 20 burritos, so the leftover burritos are: \n $ 600 - 500 - 20 = \\boxed{80} $." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 12 red cars \n- 2 fewer green cars than red: $ 12 - 2 = 10 $ green cars \n- 3 times the number of blue cars as green: $ 3 \\times 10 = 30 $ blue cars \n- Total cars: 75 \n- Let $ y $ be the number of yellow cars\n\nSo:\n\n$$\n12 + 10 + 30 + y = 75\n$$\n\n$$\n52 + y = 75\n$$\n\n$$\ny = 23\n$$\n\n**Final Answer:** $\\boxed{23}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let:\n- $ S $ = number of books Sofie has,\n- $ A $ = number of books Anne has,\n- $ F $ = number of books Fawn has.\n\nWe are given:\n- $ S + A + F = 85 $,\n- $ S = A + 25 $,\n- $ A = F - 12 $.\n\nSubstitute $ A = F - 12 $ into the first equation:\n\n$$\nS + (F - 12) + F = 85\n$$\n\n$$\nS + 2F - 12 = 85\n$$\n\n$$\nS + 2F = 97\n$$\n\nNow substitute $ S = A + 25 = (F - 1" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Daisy bought:\n- 5 pounds of potatoes,\n- 2 times as much sweet potatoes as the potatoes: $ 2 \\times 5 = 10 $ pounds,\n- 3 pounds fewer than the sweet potatoes: $ 10 - 3 = 7 $ pounds.\n\nSo, the weight of the carrots is:\n\n$$\n\\boxed{7}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Greg wants to make 30 kids, each with 4 jello cups, so he needs:\n\n$$\n30 \\times 4 = 120 \\text{ jello cups}\n$$\n\nEach box makes 10 cups, so he needs:\n\n$$\n120 \\div 10 = 12 \\text{ boxes}\n$$\n\nEach box costs $1.25, so the total cost is:\n\n$$\n12 \\times 1.25 = \\boxed{15} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The seller bought 5 phones for $700 each, so the total cost is:\n\n$$\n5 \\times 700 = 3500\n$$\n\nHe gave the seller $4000 in dollar bills. The change he will receive is:\n\n$$\n4000 - 3500 = \\boxed{500}\n$$\n\nSo, the seller will give back **$500** in change." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Madeline and Keenan share the cost of groceries, and they spend about **$400 per month**. \nIn a **four-week month**, Keenan pays **60%** of the total cost.\n\nSo, Keenan's weekly cost is: \n$$\n\\frac{60\\%}{4} \\times 400 = \\frac{0.6 \\times 400}{4} = \\frac{240}{4} = 60\n$$\n\n**Answer:** $\\boxed{60}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tobias ate:\n\n- $ \\frac{2}{5} \\times 60 = 24 $ pieces on the first day.\n\n- $ 10 $ pieces on the second day.\n\n- $ \\frac{7}{13} \\times (60 - 24 - 10) = \\frac{7}{13} \\times 26 = 14 $ pieces on the third day.\n\nSo, the total number of pieces eaten is:\n\n$$\n24 + 10 + 14 = \\boxed{48}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "We are given:\n\n- 7 bottles of soda = $21.00 \n So, 1 bottle of soda = $3.00\n\n- 4 bottles of water = $8.00 \n So, 1 bottle of water = $2.00\n\nDavid wants to buy:\n\n- 3 bottles of soda \n- 2 bottles of water\n\nSo, the total cost is:\n\n$$\n3 \\times 3 + 2 \\times 2 = 9 + 4 = \\boxed{13}\n$$\n\n**Answer:** $\\boxed{13}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "David has $12.48 and buys 16 bolts at $0.03 each. \nTotal cost = $16 \\times 0.03 = 0.48$.\n\nDavid has $12.48 - $0.48 = $\\boxed{12}$." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Ella earns $33 for 3 hours of dog walking. \nHer rate is: \n$$\n\\frac{33}{3} = 11 \\text{ dollars per hour}\n$$\n\nAfter 12 hours: \n$$\n11 \\times 12 = \\boxed{132} \\text{ dollars}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Paul starts with 52 marbles. His friend gives him 28 more, so he has:\n\n$$\n52 + 28 = 80 \\text{ marbles}\n$$\n\nThen, he loses $ \\frac{1}{4} $ of his marbles:\n\n$$\n\\frac{1}{4} \\times 80 = 20 \\text{ marbles}\n$$\n\nSo, Paul has:\n\n$$\n80 - 20 = \\boxed{60} \\text{ marbles} \\text{ left.}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Amy answers:\n\n- 80% of 10 multiple-choice questions: $ 0.8 \\times 10 = 8 $ points \n- 90% of 20 true/false questions: $ 0.9 \\times 20 = 18 $ points \n- 60% of 5 long-answer questions: $ 0.6 \\times 5 = 3 $ points \n\nTotal score: \n$$\n8 + 18 + 3 = \\boxed{29}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Isaias has 300 chickens on his farm and plans to sell **3/5** of them. \nSo, the number of chickens he will sell is: \n$$\n\\frac{3}{5} \\times 300 = 180 \\text{ chickens}\n$$\n\nHe sells each chicken for **$50**, so the total money he will make is: \n$$\n180 \\times 50 = 9000\n$$\n\nHe wants to make a profit of **$2000**, so the amount he **buys** the chickens for is: \n$$\n9000 - 2000 = 7000\n$$\n\n**Final Answer:** \n$$\n\\" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Julie sold 14 glasses, and the boys sold an equal number of glasses. Since there are 3 boys, each boy sold:\n\n$$\n\\frac{14}{3} = 4 \\text{ glasses}\n$$\n\nSo, Micah also sold 4 glasses.\n\nNow, the difference between what Julie and Micah sold is:\n\n$$\n14 - 4 = 10\n$$\n\n**Final Answer:** $\\boxed{10}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the total amount of money spent at the spa be $ x $.\n\n- Iris spent $ 400 on hair.\n- She spent $ \\frac{1}{4} \\times 400 = 100 $ on a manicure.\n- She spent $ \\frac{3}{4} \\times 100 = 75 $ on a pedicure.\n\nSo, the total amount spent is:\n\n$$\n400 + 100 + 75 = \\boxed{575}\n$$\n\n**Answer:** $\\boxed{575}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah has a rope that is 20 meters long. Her friend wants to buy the rope for $2 per meter. Sarah plans to use the profit to buy a new rope, which costs $1.5 per meter.\n\n1. **Cost of the original rope**: \n $2 \\times 20 = 40$ dollars.\n\n2. **Cost of the new rope**: \n $1.5 \\times 20 = 30$ dollars.\n\n3. **Profit**: \n $40 - 30 = 10$ dollars.\n\n4. **Money left over**: \n $10$ dollars.\n\n$$\n\\boxed{10}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let $ x $ be the number of years in the future when Melanie will be **3 times** her current age.\n\nWe are told:\n\n- In 10 years, Melanie will be 18 years old.\n- So, her current age is $ 18 - 10 = 8 $ years.\n\nNow, in $ x $ years, her age will be $ 8 + x $, and this must be **3 times** her current age:\n\n$$\n8 + x = 3 \\times 8 = 24\n$$\n\n$$\nx = 24 - 8 = 16\n$$\n\n### ✅ Final Answer:\n$$\n\\boxed{16}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Kelly's total cost is:\n\n- 5 packs of bacon: $10 \n- 6 packets of chicken: $6 (each = $2) \n- 3 packs of strawberries: $12 \n- 7 packs of apples: $28 \n\nTotal cost: \n$$\n10 + 6 + 12 + 28 = 56\n$$\n\nKelly's budget is $65, so the amount she has left is:\n\n$$\n65 - 56 = \\boxed{9}\n$$\n\n**Answer:** $\\boxed{9}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the runtime of her usual concerts be $ x $ minutes.\n\n- The final concert is twice as long as her usual concerts: $ 2x $\n- The final concert also includes a 15-minute encore: $ 2x + 15 $\n- The runtime of the final concert is given as 65 minutes: $ 2x + 15 = 65 $\n\nSolving for $ x $:\n\n$$\n2x + 15 = 65 \\\\\n2x = 65 - 15 \\\\\n2x = 50 \\\\\nx = 25\n$$\n\n**Final answer:** $\\boxed{25}$ minutes." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Argo starts with 200 toys. \nHe gives away: \n- 40 toys to Alyssa \n- 80 toys to Bonnie \n- 30 toys to Nicky \n\nSo, the total number of toys Argo has now is: \n$$ 200 - 40 - 80 - 30 = \\boxed{80} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "On **Tuesday**, they make **125 chimichangas**. \nOn **Wednesday**, they make **125 chimichangas**. \nOn **Friday**, they make **twice as many** as on Tuesday, so **250 chimichangas**.\n\nTotal chimichangas made on those three days: \n$$\n125 + 125 + 250 = \\boxed{500}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let’s solve the problem step by step:\n\n- There are **50 microphones**.\n- 20% of them **won’t** find space to fit in after arranging the rest in pairs.\n- So, 20% of 50 is **10** microphones.\n- The remaining **40** microphones can be arranged in **pairs**.\n\nNow, the number of pairs is:\n\n$$\n\\frac{40}{2} = 20\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{20}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jerry counts:\n\n- $ 6 $ birds nesting in the bushes,\n- $ \\frac{2}{3} \\times 6 = 4 $ birds flying overhead,\n- $ 3 \\times 8 = 24 $ birds feeding.\n\nSo, the total number of birds is:\n\n$$\n6 + 4 + 24 = \\boxed{34}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Lani baked 55 cookies. She ate 5 five-cookie portions, so the remaining cookies are:\n\n$$\n55 - 5 \\times 5 = 55 - 25 = 30\n$$\n\nShe placed the remaining 30 cookies equally into 5 jars, so each jar has:\n\n$$\n\\frac{30}{5} = 6\n$$\n\n**Final Answer:** $\\boxed{6}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joelle has 5 orchids and 4 daisies.\n\n- Orchids have 5 petals each: $5 \\times 5 = 25$ petals.\n- Daisies have 10 petals each: $4 \\times 10 = 40$ petals.\n\nThe number of more petals the daisies have compared to the orchids is:\n\n$$\n40 - 25 = \\boxed{15}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 100 plants in the garden.\n\n- One-fourth are indoor plants: \n $ \\frac{1}{4} \\times 100 = 25 $ plants.\n\n- Two-thirds of the remaining are outdoor plants: \n $ \\frac{2}{3} \\times 75 = 50 $ plants.\n\n- The rest are flowering plants: \n $ 100 - 25 - 50 = 25 $ plants.\n\nSo, the percentage of flowering plants is: \n$$\n\\frac{25}{100} \\times 100 = 25\\%\n$$\n\n$$\n\\boxed{25}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- A **whirligig** spins at **5 times the speed** of a **thingamabob**.\n- A **whatchamacallit** spins at **11 times the speed** of a **thingamabob**.\n- A **whatchamacallit** spins at **121 m/s**.\n\nLet’s find the speed of the **whirligig**:\n\n- A **thingamabob** spins at $ x $ m/s.\n- A **whirligig** spins at $ 5x $ m/s.\n- A **whatchamacallit** spins at $ 11x $ m/s.\n\nWe are told that a **whatchamacallit** spins at **12" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Ellen eats:\n- 2 carrots\n- 1 salad\n- 1 yogurt\n\nSalad costs $6, and the yogurt is half the price of the salad, so the yogurt costs $3.\n\nTotal cost:\n$$\n2 \\times 1 + 1 \\times 6 + 1 \\times 3 = 2 + 6 + 3 = 11\n$$\n\nShe pays $11 for her goods.\n\nHow much does Ellen pay for one carrot every day:\n$$\n\\frac{11}{2} = 5.5\n$$\n\nSo, the answer is:\n\n$$\n\\boxed{5.5}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mark works:\n- 8 hours/day \n- 5 days/week\n\nHe used to make $10/hour, now he makes $12/hour.\n\nSo, his weekly earnings are:\n\n$$\n8 \\times 5 \\times 12 = \\boxed{480}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let’s define the number of times Tasha mowed lawns:\n\n- Let $ x $ be the number of times Tasha mowed **Joe's** lawn.\n- Then, she mowed Kamala's lawn $ 3x $ times.\n- She mowed Alba's lawn $ 5x $ times.\n\nShe made money from mowing lawns:\n\n- From Joe's lawn: $ 6 $ dollars\n- From Kamala's lawn: $ 3x \\times 6 = 18x $\n- From Alba's lawn: $ 5x \\times 6 = 30x $\n\nTotal money from mowing lawns: \n$$ 6 + 18x + 30x = 6 + 48x $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Martin's weight is $ 55 \\, \\text{kg} $.\n\nCarl's weight is $ 16 \\, \\text{kg} $ more than Martin's, so:\n\n$$\n\\text{Carl's weight} = 55 + 16 = 71 \\, \\text{kg}\n$$\n\nChristian's weight is $ 8 \\, \\text{kg} $ more than Carl's, so:\n\n$$\n\\text{Christian's weight} = 71 + 8 = 79 \\, \\text{kg}\n$$\n\nHarry is $ 5 \\, \\text{kg} $ less than Christian's weight, so:\n\n$$\n\\text{Harry's weight} = 79 - 5 = " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John rents his car out **10 times a month** for **3 hours each time**, and he is paid **$25 per hour**. \nHis car payment is **$500**.\n\n- **Hourly rate**: $25/hour \n- **Total hours per month**: $10 \\times 3 = 30$ hours \n- **Total earnings**: $30 \\times 25 = 750$ dollars \n- **Profit**: $750 - 500 = \\boxed{250}$\n\n**Answer:** $\\boxed{250}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Joseph had 3 times as many notebooks as Martha. \nLet Martha have $ x $ notebooks. \nThen Joseph has $ 3x $ notebooks.\n\nMartha bought 5 more notebooks, making her total $ x + 5 $.\n\nNow, how many more notebooks does Martha have than Joseph?\n\n$$\nx + 5 - 3x = -2x + 5\n$$\n\nSince the problem asks how many **more** notebooks Martha has than Joseph, the answer is:\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dijana rowed **50 miles** the whole day.\n\nAnis rowed **1/5 times more** than Dijana, so:\n\n$$\n\\text{Anis's distance} = 50 + \\left(\\frac{1}{5} \\times 50\\right) = 50 + 10 = 60 \\text{ miles}\n$$\n\n$$\n\\text{Total distance} = 50 + 60 = \\boxed{110}\n$$\n\n**Answer:** $\\boxed{110}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Susan made 100 cookies for Christmas and was going to divide them equally between her 6 nephews. Before Susan could package them, her husband snuck 4 cookies for himself.\n\n- Total cookies: 100 \n- Cookies given to each nephew: $ \\frac{100}{6} = 16 $ \n- Cookies taken by husband: 4 \n- Remaining cookies: $ 100 - 4 = 96 $ \n- Cookies given to each nephew: $ 96 \\div 6 = 16 $ \n\n**Final answer:** $\\boxed{16}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Denise read 10 pages yesterday, and Daniel read 13 pages. Today, Denise read 5 more than Daniel's reading from yesterday, so:\n\n- Denise today: $10 + 5 = 15$ pages \n- Daniel today: 0 pages\n\nSo, the difference in pages is:\n\n$$\n15 - 0 = \\boxed{15}\n$$\n\n**Answer:** $\\boxed{15}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Calvin has enough soup to fill **4 adult's bowls or 8 child's bowls**. He is eating with **his adult wife and two children**, so **6 people** in total.\n\n- Each person eats **1 bowl**.\n- Total bowls used: 6.\n- Leftover bowls: $ 8 - 4 = 4 $.\n\nEach child will have **1 bowl** from the leftover soup.\n\n$$\n\\boxed{1}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "William bought 5 notebooks at $1.50 each and 1 ballpen at $0.50. \nTotal cost = $1.50 × 5 + $0.50 = $7.50 + $0.50 = **$8.00**\n\n$$\n\\boxed{8}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jo can make 4 small masks with 2 yards of material, so the cost per small mask is:\n\n$$\n\\frac{2 \\text{ yards}}{4 \\text{ small masks}} = 0.5 \\text{ yards per small mask}\n$$\n\nShe can make 3 large masks with 2.25 yards of material, so the cost per large mask is:\n\n$$\n\\frac{2.25 \\text{ yards}}{3 \\text{ large masks}} = 0.75 \\text{ yards per large mask}\n$$\n\nFor 20 small masks:\n\n$$\n20 \\times 0.5 = 10 \\text{ yards}\n$$\n\nFor 8 large masks:\n\n$$\n8 \\times 0" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "There are 9 Fast and the Furious movies, and Deepa has seen each one in the theatre **three times**. She spent a total of **$216**.\n\nTo find the **average price per ticket**, divide the total cost by the number of movies:\n\n$$\n\\text{Average price per ticket} = \\frac{216}{9} = 24\n$$\n\n**Answer:** $\\boxed{24}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Harold sleeps for **10 hours** a night. \nHe works **2 hours less** than he sleeps: \n$ 10 - 2 = 8 $ hours. \n\nHe walks his dog for **1 hour** each day. \n\nSo, the total time he spends in the day is: \n$ 10 + 8 + 1 = 19 $ hours. \n\nTherefore, the amount of **free time** he has left is: \n$ 24 - 19 = 5 $ hours. \n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Tim has a box with:\n\n- 7 blue shoe boxes \n- 9 red shoe boxes\n\nHe uses:\n\n- 3 blue shoe boxes \n- $ \\frac{1}{3} $ of the red shoe boxes\n\nSo, the number of red shoe boxes used is:\n\n$$\n\\frac{1}{3} \\times 9 = 3\n$$\n\nNow, the number of red and blue shoe boxes left is:\n\n- Blue: $ 7 - 3 = 4 $\n- Red: $ 9 - 3 = 6 $\n\nSo, the final answer is:\n\n$$\n\\boxed{4 \\text{ red and } 6 \\text{ blue shoe boxes}}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sarah has 9 books. Joseph had **twice** the number of Sarah’s books, so:\n\n$$\n2 \\times 9 = 18\n$$\n\nJoseph **lost 2** books, so:\n\n$$\n18 - 2 = 16\n$$\n\n**Final answer:** $\\boxed{16}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Dean has 30 marbles. \nHe gives:\n\n- $ \\frac{1}{5} \\times 30 = 6 $ marbles to Jamie \n- 10 marbles to Donald \n\nSo, the number of marbles left for Dean is:\n\n$$\n30 - 6 - 10 = 14\n$$\n\n**Final Answer:** $\\boxed{14}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let $ A $ be Adam's current age. \nDuncan's age eight years ago was $ 60 - 8 = 52 $.\n\nAccording to the problem: \n$$\nDuncan's \\ age \\ 8 \\ years \\ ago = 2 \\times \\text{Adam's age } 4 \\ years \\ ago\n$$ \n$$\n52 = 2(A - 4)\n$$\n\nSolve for $ A $: \n$$\n52 = 2A - 8 \\\\\n2A = 60 \\\\\nA = 30\n$$\n\nAdam's age in 8 years will be: \n$$\n30 + 8 = \\boxed{38}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Farmer Brown's farm is 200 acres. \nFarmer Smith's farm is 100 acres more than twice that: \n$$ 2 \\times 200 + 100 = 500 $$\n\nSo, the total area of both farms is: \n$$ 200 + 500 = \\boxed{700} $$ acres." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Colby completes **10 less than 50 packages per hour**, so:\n\n$$\n50 - 10 = 40 \\text{ packages per hour}\n$$\n\nHe earns **$0.20 per package**, so:\n\n$$\n40 \\times 0.20 = 8 \\text{ dollars}\n$$\n\nIn a typical **eight-hour workday**, he earns:\n\n$$\n8 \\times 8 = \\boxed{64} \\text{ dollars}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John drinks a bottle of water every **0.5 hours**. \nA **normal Sudoku** takes him **45 minutes**. \nAn **extreme Sudoku** takes him **4 times that time** (i.e., 180 minutes). \n\nSo, in 180 minutes, he drinks: \n$$\n\\frac{180}{45} = 4 \\text{ bottles}\n$$\n\n**Final Answer:** \n$$\n\\boxed{4}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Benny threw:\n- 2 pieces of bologna at each red balloon,\n- 3 pieces of bologna at each yellow balloon.\n\nHe threw **58 pieces** in total, and **20 of the balloons** were red.\n\nLet $ x $ be the number of yellow balloons.\n\nThen:\n$$\n2 \\times 20 + 3 \\times x = 58\n$$\n$$\n40 + 3x = 58\n$$\n$$\n3x = 18\n$$\n$$\nx = 6\n$$\n\n**Answer:** $\\boxed{6}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jon drives 100 miles per day for 30 days, so he drives:\n\n$$\n100 \\times 30 = 3000 \\text{ miles}\n$$\n\nSince he needs a tune-up every 1000 miles, the number of tune-ups he needs is:\n\n$$\n\\left\\lfloor \\frac{3000}{1000} \\right\\rfloor = 3\n$$\n\n**Final Answer:** $\\boxed{3}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bruce works:\n\n- **5 hours** on Tuesday \n- **2 × 5 = 10 hours** on Wednesday \n- **2 hours less than 10 = 8 hours** on Thursday \n\nTotal hours = $5 + 10 + 8 = \\boxed{23}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let $ x $ be the amount Julia and Nadine's mother gave each of them.\n\n- They bought a cake for $11.\n- They also bought 1 dozen balloons for $0.5 per 2 balloons, so the cost of balloons is $0.5 \\times 6 = 3$ dollars.\n- The remaining money was used to buy 2 tubs of ice cream for $7 each, so the cost of ice cream is $7 \\times 2 = 14$ dollars.\n\nTotal cost of all purchases:\n$$\n11 + 3 + 14 = 28\n$$\n\nSince the total amount given to Julia and Nadine is the same, the amount each received is:\n$$\n\\boxed{14}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Kira bought:\n- 3 apples \n- 5 bananas \n- 6 oranges \n\nLola ate **2 pieces** of fruit.\n\nSo, the number of pieces left is:\n\n$$\n3 + 5 + 6 - 2 = 12\n$$\n\n**Answer:** $\\boxed{12}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are:\n\n- 6 students playing tennis \n- $2 \\times 6 = 12$ students playing volleyball \n- 16 boys and 22 girls playing soccer\n\nTotal students = $6 + 12 + 16 + 22 = \\boxed{56}$." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Each student sold 10 lollipops for $0.8 each, so each student made:\n\n$$\n10 \\times 0.8 = 8 \\text{ dollars}\n$$\n\nThere are 30 students, so the total money raised is:\n\n$$\n30 \\times 8 = \\boxed{240} \\text{ dollars}\n$$\n\n**Answer:** $\\boxed{240}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Larry has:\n\n- 3 cats \n- 3 times as many dogs as cats: $ 3 \\times 3 = 9 $ dogs \n- 2 fewer rabbits than dogs: $ 9 - 2 = 7 $ rabbits \n- 3 times as many fish as rabbits: $ 3 \\times 7 = 21 $ fish \n- 1/3 the number of fish as gerbils: $ \\frac{1}{3} \\times 21 = 7 $ gerbils \n\nTotal pets: \n$$\n3 + 9 + 7 + 21 + 7 = \\boxed{47}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Abby eats 2 slices/day, and Josh eats 4 slices/day. \nTotal slices = 24. \nNumber of days = $ \\frac{24}{2 + 4} = \\frac{24}{6} = \\boxed{4} $. \n\n**Answer:** $ \\boxed{4} $ days." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Martha collects one shell every month. By her 10th birthday, she has collected:\n\n$$\n10 \\text{ months} \\times 1 \\text{ shell/month} = \\boxed{10} \\text{ shells}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Lana has 27 cups in total, and she divides them into 3 rows. Each row has the same number of cups:\n\n$$\n\\frac{27}{3} = 9\n$$\n\nShe uses 15 cups of **cinnamon tea** in total, and the remaining cups are used for **mint tea**. So:\n\n$$\n27 - 15 = 12\n$$\n\nTherefore, the number of cups of mint tea in each row is:\n\n$$\n\\boxed{12}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The sloth makes one trip down the tree, picks the same number of berries, and climbs back up in 4 hours. So, the number of berries per trip is:\n\n$$\n\\frac{24}{4} = 6\n$$\n\nThus, the least number of berries he can pick per trip is:\n\n$$\n\\boxed{6}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Initial amount of water in the pool: $ 10,000 $ gallons \n- The water pump fills a tank with half the amount of water in the pool: $ \\frac{1}{2} \\times 10,000 = 5,000 $ gallons \n- The tank is emptied at a rate of $ 500 $ gallons per day \n- The time elapsed is $ 6 $ days \n\n### Step-by-step:\n\n1. **Water added to the tank**: $ 5,000 $ gallons \n2. **Water removed from the tank**: $ 500 \\times 6 = 3,000 $ gallons \n3. **Remaining water in the tank**: \n" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Colby already saw:\n\n- 5 movies on **Friday or Saturday** \n- 8 movies on **other days** \n- 2 tubs of popcorn \n- 4 boxes of candy \n\nEach movie costs:\n\n- $10 for **Fridays and Saturdays** \n- $7 for **other days** \n\nSo, the number of movies he can see is:\n\n$$\n5 + 8 + 2 + 4 = 19 \\text{ movies}\n$$\n\n**Answer:** $\\boxed{19}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Andrew bakes:\n- 200 mini cinnamon rolls, each with 600 calories\n- 300 mini blueberry muffins, each with 450 calories\n\nEach mini pastry has $ \\frac{1}{3} $ of the calories of a normal version.\n\nSo, the total calories are:\n$$\n200 \\times 600 + 300 \\times 450 = 120,000 + 135,000 = \\boxed{255,000}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "On Monday: 39 \nOn Tuesday: $2 \\times 39 = 78$ \nOn Wednesday: $2 \\times 39 = 78$ \nOn Thursday: 48 \nOn Friday: 57 \n\nTotal removed: \n$$\n39 + 78 + 78 + 48 + 57 = 39 + 78 + 78 + 48 + 57 = 39 + 78 = 117, \\quad 117 + 78 = 195, \\quad 195 + 48 = 243, \\quad 243 + 57 = 300\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The bus travels:\n$$\n60 \\text{ mph} \\times 5 \\text{ hours} = 300 \\text{ miles}\n$$\n\nThe car travels:\n$$\n30 \\text{ mph} \\times 8 \\text{ hours} = 240 \\text{ miles}\n$$\n\nThe difference is:\n$$\n300 - 240 = \\boxed{60} \\text{ miles}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Sophie has:\n- 31 blocks\n- 8 stuffed animals\n- 9 rings\n\nTotal toys: $ 31 + 8 + 9 = 48 $\n\nShe added a tube of bouncy balls, bringing the total to **62**.\n\n$$\n62 - 48 = \\boxed{14}\n$$\n\nSo, the number of bouncy balls in the tube is **14**." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- The combined age of Peter, Paul, and Jean is **100 years**.\n- Paul is **10 years older** than John.\n- Peter's age is equal to the **sum of Paul and John's age**.\n\nLet:\n- John's age = $ x $\n- Paul's age = $ x + 10 $\n- Peter's age = $ x + (x + 10) = 2x + 10 $\n\nWe are told that:\n\n$$\nx + (x + 10) + (2x + 10) = 100\n$$\n\n$$\n4x + 20 = 100\n$$\n\n$$\n4x = 80\n$$\n\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Maria invited 4 of her friends, and each of them received 2 water balloons initially. She had 1 water balloon for herself. Then her mom gave each person 3 more balloons. \n\nSo, the total number of balloons is:\n\n$$\n4 \\times 2 + 1 + 4 \\times 3 = 8 + 1 + 12 = \\boxed{21}\n$$\n\n**Final Answer:** $\\boxed{21}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "They already have 15 tables, and each table can fit 2 boxes. They have 10 boxes already, so the number of new tables needed is:\n\n$$\n\\frac{10}{2} = 5\n$$\n\nSo, they need **5 new tables**.\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Zoey's total distance: \n- 40 seeds × 10 feet = **400 feet**\n\nSydney's total distance: \n- 35 seeds × 12 feet = **420 feet**\n\nAverage total distance: \n$$\n\\frac{400 + 420}{2} = \\frac{820}{2} = \\boxed{410}\n$$\n\n**Answer:** $\\boxed{410}$ feet." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Fern will make:\n\n- From the **Widgeteer 3000**:\n - 60 widgets/hour × 24 hours/day × 30 days/month = 43,200 widgets\n - 43,200 widgets × $6/widget = $259,200\n\n- From the **WidgetMaster 9000**:\n - 45 widgets/hour × 24 hours/day × 30 days/month = 32,400 widgets\n - 32,400 widgets × $6/widget = $194,400\n\nThe difference is:\n\n$$\n259,200 - 194,40" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Cameron arrives at 5 pm and wants to leave at 10 am the next morning. This is a **12-hour stay**. He can add **70 pesos for every additional hour** after the 12-hour mark.\n\n- 12-hour stay: 1000 pesos \n- 12-hour stay with 70 pesos: $1000 + 70 \\times (10 - 12) = 1000 - 70 = 930$ pesos\n\n**Cameron saves:** \n$$\n1000 - 930 = \\boxed{70} \\text{ pesos}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each goat needs $ 5 $ pounds of hay.\n\nEach sheep needs $ 2 \\times 5 - 3 = 7 $ pounds of hay.\n\nThere are $ 15 $ goats and $ 12 $ sheep.\n\nSo, the total amount of hay needed is:\n\n$$\n15 \\times 5 + 12 \\times 7 = 75 + 84 = \\boxed{159} \\text{ pounds.}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "John earns $50 per hour and works 6 hours, so his total earnings are:\n\n$$\n50 \\times 6 = 300 \\text{ dollars}\n$$\n\nHe spends $50 on gas and wants to deposit $100 in the bank, so he has:\n\n$$\n300 - 50 - 100 = 150 \\text{ dollars left}\n$$\n\nHe also buys 5 pencils that cost $10 each, so the total cost is:\n\n$$\n5 \\times 10 = 50 \\text{ dollars}\n$$\n\nHe has $150 left, so the remaining money he can use to buy pens is:\n\n$$\n150 - 50 = 10" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Craig has spelled out **20 words**, each with **15 letters**, so the total number of letters is:\n\n$$\n20 \\times 15 = 300\n$$\n\nCraig's brother has spelled out **50 more letters** than Craig, so the total number of letters is:\n\n$$\n300 + 50 = \\boxed{350}\n$$\n\n**Final Answer:** $\\boxed{350}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 8 children in a row, and there are 7 rows, each with 5 schools. So the total number of children is:\n\n$$\n8 \\times 7 \\times 5 = \\boxed{280}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 29 students, and each student gets 2 bottles of apple juice. So:\n\n$$\n29 \\times 2 = 58 \\text{ bottles}\n$$\n\nThe teacher uses 9 coupons, each giving 100 bottles:\n\n$$\n9 \\times 100 = 900 \\text{ bottles}\n$$\n\nNow, the teacher has:\n\n$$\n900 - 58 = \\boxed{842}\n$$\n\nbottles of apple juice for herself." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Patty's Plumbing charges:\n\n- $40 to visit the house\n- $35 per hour, or part thereof, for labor\n- $60 in parts\n\nOne job took **2.25 hours** and used **$60 in parts**.\n\nSo, the total charge is:\n\n$$\n40 + 35 \\times 2.25 + 60\n$$\n\n$$\n= 40 + 81.25 + 60\n$$\n\n$$\n= \\boxed{181.25}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James gets 10 new CDs, each costing $15, and gets a 40% discount. He sells 5 of them for $40 each.\n\n1. **Total cost of 10 CDs without discount**:\n $$\n 10 \\times 15 = 150\n $$\n\n2. **Discount amount**:\n $$\n 150 \\times 0.40 = 60\n $$\n\n3. **Total cost after discount**:\n $$\n 150 - 60 = 90\n $$\n\n4. **Total money he gets from selling 5 CDs**:\n $$\n 5 \\times 40 = 200\n" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jen has:\n- 6 yams at $1.5 each: $6 \\times 1.5 = 9\n- 10 sweet potatoes at $2 each: $10 \\times 2 = 20\n- 4 carrots at $1.25 each: $4 \\times 1.25 = 5\n\nTotal earnings: \n$$ 9 + 20 + 5 = \\boxed{34} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "James swims 60% of the 20-mile lake at a speed of 2 miles per hour. \n- Distance covered: $ 0.6 \\times 20 = 12 $ miles \n- Time taken: $ \\frac{12}{2} = 6 $ hours \n\nAfter that, he rests for half the time he spent swimming: \n- Rest time: $ \\frac{6}{2} = 3 $ hours \n\nThen he swims the remaining 40% of the distance at half the speed: \n- Distance covered: $ 0.4 \\times 20 = 8 $ miles \n- Time taken: $ \\frac{8}{1} = 8 $ hours \n\nTotal time: \n- $ 6" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the number of loaves of bread Sam had last Friday be $ S = 70 $.\n\nThe bakery has 40 less than seven times as many loaves of bread as Sam had last Friday:\n\n$$\n\\text{Bakery's loaves} = 7 \\times S - 40 = 7 \\times 70 - 40 = 490 - 40 = \\boxed{450}\n$$\n\n**Answer:** $\\boxed{450}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jasmine was given:\n- 15 stickers for participating in class \n- 5 stickers for helping classmates \n\nShe lost 7 stickers during playtime.\n\nSo, the total number of stickers she has at the end is:\n\n$$\n15 + 5 - 7 = 13\n$$\n\n**Final Answer:** $\\boxed{13}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Cayley earns:\n- 10% commission on 6 copies of New York Times: \n $ 6 \\times 5 \\times 0.10 = 3 $\n\n- 8% commission on 10 copies of Wall Street Journal: \n $ 10 \\times 15 \\times 0.08 = 12 $\n\nTotal commission: \n$ 3 + 12 = \\boxed{15} $" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Marcus is half of Leo’s age, so:\n\n$$\n\\text{Marcus} = \\frac{1}{2} \\times \\text{Leo's age}\n$$\n\nMarcus is also five years younger than Deanna, who is 26 years old:\n\n$$\n\\text{Marcus} = 26 - 5 = 21\n$$\n\nNow substitute into the first equation:\n\n$$\n21 = \\frac{1}{2} \\times \\text{Leo's age}\n$$\n\nMultiply both sides by 2:\n\n$$\n\\text{Leo's age} = 42\n$$\n\n**Final Answer:**\n\n$$\n\\boxed{42}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let the points scored by Dinar be $ x $. \nThen, since Bahati scored 10 more than Dinar, Bahati scored $ x + 10 $. \nSince Bahati scored 20 more than Azibo, Azibo scored $ x + 10 - 20 = x - 10 $.\n\nWe are told that the total points are 45. So:\n\n$$\nx + (x - 10) + (x + 10) = 45\n$$\n\nSimplify:\n\n$$\n3x = 45 \\Rightarrow x = 15\n$$\n\nSo, Azibo scored:\n\n$$\nx - 10 = 15 - 10 = 5\n$$\n\n**Final" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The book is printed on paper that is **100 pages to the inch**, and each paper has **two sides** of the book. The book is **1.5 inches thick**.\n\nSince the paper is 100 pages per inch, and each paper has **two sides**, the number of pages in the book is:\n\n$$\n100 \\text{ pages/inch} \\times 1.5 \\text{ inches} = 150 \\text{ pages}\n$$\n\nSo, the book has **150 pages**.\n\n$$\n\\boxed{150}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Vince staples 30 reports every 15 minutes. \nFrom 8:00 AM to 11:00 PM is a total of:\n\n$$\n11:00 - 8:00 = 3 \\text{ hours} = 180 \\text{ minutes}\n$$\n\nHe staples 30 reports every 15 minutes, so in 180 minutes:\n\n$$\n\\frac{180}{15} = 12 \\text{ sets of 30 reports}\n$$\n\n$$\n12 \\times 30 = \\boxed{360} \\text{ reports}\n$$\n\n**Answer:** $\\boxed{360}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Kim usually sleeps from **10 p.m. to 6 a.m.**, which is a **12-hour period**. \nShe sleeps **12 hours** in total.\n\nOn the day in question, she wakes up **5 minutes earlier** than usual, so she wakes at **5:05 a.m.** \nShe also wakes up **2:38 a.m.** (from the problem statement).\n\nSo, the time she was **sleeping** is:\n\n$$\n2:38 \\text{ am} - 5:05 \\text{ am} = 2:38 - 5:05 = -2:27 \\text{ hours}\n$$\n\nThis means she was **sleeping for 2 hours and " + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jonathan has:\n\n- $ \\frac{2}{3} $ as many measuring spoons as measuring cups. \n- He has **2 dozen cups**, which is $ 2 \\times 12 = 24 $ cups.\n\nSo, the number of measuring spoons is:\n\n$$\n\\frac{2}{3} \\times 24 = 16 \\text{ measuring spoons}\n$$\n\nHe gifts Pedro 6 measuring spoons, so he gives away 6.\n\nNow, the total number of utensils Jonathan has remaining is:\n\n$$\n24 \\text{ cups} - 6 = 18\n$$\n\n$$\n16 \\text{ measuring spoons} - 6 = 10\n$$\n\nSo, the total number of" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "The hospital has a capacity of 1000 beds, and 1/5 of it is occupied. So, the number of occupied beds is:\n\n$$\n\\frac{1}{5} \\times 1000 = 200 \\text{ beds}\n$$\n\nEach day, 50 patients are admitted, so the number of beds occupied per day is:\n\n$$\n200 \\text{ beds/day}\n$$\n\nAfter 2 weeks, which is 14 days:\n\n$$\n200 \\times 14 = 2800 \\text{ beds}\n$$\n\nThe number of unoccupied beds is:\n\n$$\n1000 - 2800 = -1800 \\text{ beds}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Robyn sends a total of **16 emails a day**.\n\n- **7 are work emails**.\n- **2/3 of the remainder** are to family: \n $$\n \\frac{2}{3} \\times (16 - 7) = \\frac{2}{3} \\times 9 = 6\n $$\n- **One-third of the other emails** are to her boyfriend: \n $$\n \\frac{1}{3} \\times (16 - 7 - 6) = \\frac{1}{3} \\times 3 = 1\n $$\n\n**Final Answer:** $\\boxed{1}$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Shawna is currently **three times as old as Aliya**, and Aliya is **3 years old**. \nSo, Shawna is $ 3 \\times 3 = 9 $ years old.\n\nShawna's father is **five times as old as Shawna**, so:\n\n$$\n\\text{Shawna's father's age} = 5 \\times 9 = \\boxed{45}\n$$\n\n**Answer:** $\\boxed{45}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let $ x $ be the actual number of people who attended the concert.\n\nCourtney overstated the number by 20%, so she said the audience was $ x + 20\\%x = 1.2x $.\n\nBut Kelly said that Courtney had made the mistake of overstating the number by 20%, so Kelly is correct.\n\nTherefore, the actual number of people is:\n\n$$\n\\boxed{48} \\text{ people}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Let the number of balls carried by **Jeffrey** be $ x $. \nThen: \n- Jason carried $ 2x $ \n- Jordan carried $ 2 \\times 2x = 4x $ \n\nTotal balls carried by all three: \n$ x + 2x + 4x = 7x $ \n\nSince the coach asked them to carry all the balls in one trip, the total number of balls is the same as the total they carried. \n\nWe are told that **Jason carried 2 balls**, so: \n$ 2x = 2 $ → $ x = 1 $ \n\nTotal balls: \n$ 7x = 7 \\times 1 = \\boxed{7} $" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "We are given:\n\n- Day 1: 10 holes\n- Day 2: 13 holes\n- Day 3: 8 holes\n- Day 4: 4 times as many holes as at the end of Day 3\n\nSo:\n\n- At the end of Day 3: $ 8 + 2 = 10 $ holes\n\nThen:\n\n- At the end of Day 4: $ 10 \\times 4 = 40 $ holes\n\nThe pirates dug **2 holes** on Day 3 before finding the treasure.\n\n**Final Answer:**\n\n$$\n\\boxed{2}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Amora and Lainey each got **70** corn chips, so the total number of chips is:\n\n$$\n70 + 70 = 140\n$$\n\nBut since they are sharing **2 people**, the remaining **140 - 2 × 70 = 0** chips are distributed to the other person, who gets **15 more than the others**. So the total number of chips is:\n\n$$\n\\boxed{140}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jen has to pay **$400** for the supplies, and the **tickets for travel cost 50% more** than the supplies.\n\n- Supplies: $400 \n- Tickets: $400 + 50\\% \\times 400 = 400 + 200 = 600\n\n**Travel cost = $600**\n\n$$\n\\boxed{600}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let:\n- $ A $ = number of Pokemon caught by Alex \n- $ S $ = number of Pokemon caught by Stan \n- $ D $ = number of Pokemon caught by Adelwolfe \n\nWe are given:\n1. $ A = S + 5 $ \n2. $ S = 4D - 13 $ \n3. $ A + S + D = 339 $\n\nSubstitute $ A = S + 5 $ and $ S = 4D - 13 $ into the third equation:\n\n$$\n(S + 5) + S + D = 339\n$$\n$$\n2S + D + 5 = 339\n$$\n\nNow substitute $ S = 4D - 13" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Each episode is 20 minutes long, and there are **half as many episodes in total as there are minutes per episode**.\n\n- Minutes per episode = 20 \n- Episodes = $ \\frac{20}{2} = 10 $\n\n- Total time = $ 10 \\times 20 = 200 $ minutes\n\n**Final Answer:** \n$$\n\\boxed{200}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The bird flies:\n\n- **10 hours at 30 mph**: $ 10 \\times 30 = 300 $ miles \n- **2 hours at 18 mph**: $ 2 \\times 18 = 36 $ miles \n- **5 hours at 22 mph**: $ 5 \\times 22 = 110 $ miles \n\nTotal distance: \n$$\n300 + 36 + 110 = \\boxed{446} \\text{ miles}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Greta made 1 dozen brownies for herself, and 1/2 a dozen for her party. Then, 4 dozen were left when she arrived home. During the party, 1 1/2 dozen were eaten.\n\nSo, the total number of brownies is:\n\n$$\n1 + \\frac{1}{2} + 4 = \\frac{3}{2} + 4 = \\frac{11}{2}\n$$\n\nThen, 1 1/2 dozen (which is 1.5 dozen) were eaten:\n\n$$\n\\frac{11}{2} - \\frac{1}{2} = \\frac{10}{2} = 5\n$$\n\nSo, Greta had **5 individual brownies** left" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Nani is 8 years old. \nHis brother is twice his age: \n$$ 2 \\times 8 = 16 \\text{ years old} $$\n\nNani's sister is 25% younger than him: \n$$ 8 \\times 0.75 = 6 \\text{ years old} $$\n\nTotal age of all three: \n$$ 8 + 16 + 6 = \\boxed{30} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Andy has:\n- 3 racquets with synthetic gut: $3 \\times 15 = 45$ minutes\n- 5 racquets with polyester string: $5 \\times 22 = 110$ minutes\n- 4 racquets with hybrid sets: $4 \\times 18 = 72$ minutes\n\nTotal time = $45 + 110 + 72 = \\boxed{227}$ minutes." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "John buys phones for himself, his 2 kids, and his wife. Each phone after the first 2 is half price.\n\n- The price of the first phone is $600.\n- The price of each subsequent phone is half of $600, i.e., $300.\n\n- Total cost = $600 (first phone) + 2 × $300 (second and third phones) = $600 + $600 = **$1,200**\n\n$$\n\\boxed{1200}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Zeke's team has 7 more players than Carlton's, so:\n\n- Carlton's team: 13 players \n- Zeke's team: $ 13 + 7 = 20 $ players \n\nCombined, the number of players is:\n\n$$\n13 + 20 = \\boxed{33}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Robert is building a rectangular wooden fence with:\n\n- Length = 15 feet \n- Width = 10 feet \n- Number of wood slats = 2 per foot of fencing\n\nSo, the total length of fencing is:\n\n$$\n15 + 10 = 25 \\text{ feet}\n$$\n\nHe needs 2 wood slats per foot, so:\n\n$$\n25 \\times 2 = \\boxed{50} \\text{ wooden slats}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Mrs. Harrington bought 12 boxes of oranges. \nShe gave her mom and her sister 2 boxes each: \n$$ 2 \\text{ boxes} \\times 2 = 4 \\text{ boxes} $$\n\nShe kept $ \\frac{1}{4} $ of the oranges: \n$$ \\frac{1}{4} \\times 12 = 3 \\text{ boxes} $$\n\nShe sold the remaining: \n$$ 12 - 4 - 3 = 5 \\text{ boxes} $$\n\nEach box contains 20 oranges, so: \n$$ 5 \\times 20 = \\boxed{100} $$\n\n**Answer:** $\\boxed{100}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let the number of states in the USA be $ x $. Then, the number of states in India is $ x + 4 $.\n\nThe total number of states in both countries is:\n\n$$\nx + (x + 4) = 2x + 4\n$$\n\nSo, the total number of states in both countries together is:\n\n$$\n\\boxed{2x + 4}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Tyler wants to buy:\n- A dictionary: $18\n- A dinosaur book: $13\n- A children's cookbook: $8\n\nTotal cost: \n$18 + $13 + $8 = $39\n\nHe has saved $14, so he needs to earn: \n$39 - $14 = $25\n\nHe earns $5 per hour, so: \n$25 ÷ $5 = **5 hours**\n\n$$\n\\boxed{5}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are told:\n\n- Robert has 30 cherries.\n- Robert has 10 more cherries than Richard.\n- The total number of cherries is 60.\n\nLet’s find how many cherries each person has:\n\n- Let $ R $ be the number of cherries Richard has.\n- Then, Robert has $ R + 10 $ cherries.\n- So, $ R + 10 + R + 30 = 60 $.\n\nSimplify:\n\n$$\n2R + 40 = 60 \\\\\n2R = 20 \\\\\nR = 10\n$$\n\nSo, Richard has 10 cherries, Robert has $ 10 + 10 = 20 $ cherries, and Jerry has" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "On Saturday:\n- Gingerbread sold: $10 \\times 6 = 60$\n- Apple pie sold: $4$ fewer than Saturday, so $10 - 4 = 6$ boxes, $6 \\times 15 = 90$\n\nOn Sunday:\n- Gingerbread sold: $5$ more than Saturday, so $10 + 5 = 15$ boxes, $15 \\times 6 = 90$\n- Apple pie sold: $15$ boxes, $15 \\times 15 = 225$\n\nTotal earnings for two days:\n$$\n60 + 90 + 90 + 225 = \\boxed{465}" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Pamela will be outside **4 hours a day** over **8 days**. \nShe uses **1 ounce of sunscreen per hour**. \nShe uses **8-ounce bottles** of sunscreen.\n\n- Total hours: $ 4 \\, \\text{hours/day} \\times 8 \\, \\text{days} = 32 \\, \\text{hours} $\n- Total sunscreen needed: $ 32 \\, \\text{hours} \\times 1 \\, \\text{ounce/hour} = 32 \\, \\text{ounces} $\n- Number of bottles: $ \\frac{32 \\, \\text{ounces}}{8 \\, \\text{ounces/bottle}} = 4 \\, \\text{bott" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The red car is 40% cheaper than the blue car, so it costs:\n\n$$\n100 - 0.4 \\times 100 = 100 - 40 = 60\n$$\n\nBoth cars cost:\n\n$$\n\\boxed{60} \\text{ and } \\boxed{100}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ x $ be the current age of Emil, and $ y $ be the current age of his dad. Emil is 19 years old now, so:\n\n$$\nx = 19\n$$\n\nWhen Emil turns 24, his age will be $ 24 $, and his dad's age will be $ 24 + y $, and his brother's age will be $ 24 - y $.\n\nAccording to the problem:\n\n- Emil's age when he turns 24 is $ 24 $, and his dad's age is half of Emil's age at that time:\n $$\n 24 = \\frac{24 + y}{2}\n $$\n\nSolving for $ y $:\n\n$$\n24" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Adrianne's mother gave her **20** metallic beads.\n- Her sister gave her **10 more** than her mother: $ 20 + 10 = 30 $.\n- Her friend gave her **twice as many** as her mother: $ 2 \\times 20 = 40 $.\n\nSo, the total number of beads is:\n\n$$\n20 + 30 + 40 = \\boxed{90}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Joe caught:\n- 3 pounds on Thursday \n- 4 times that amount on Friday: $ 4 \\times 3 = 12 $ pounds \n- Half of his Friday's catch on Saturday: $ \\frac{1}{2} \\times 12 = 6 $ pounds \n\nTotal weight caught: \n$$ 3 + 12 + 6 = 21 \\text{ pounds} $$\n\nEach serving is 3 pounds, so the number of servings is: \n$$ \\frac{21}{3} = 7 $$\n\n**Final Answer:** $\\boxed{7}$ servings." + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Mr. Roper's class has 30 students. \n20% of them are football players: \n$$ 0.20 \\times 30 = 6 $$ students.\n\nThe remaining students are: \n$$ 30 - 6 = 24 $$ students.\n\nOut of these 24 students, 25% are cheerleaders or part of band: \n$$ 0.25 \\times 24 = 6 $$ students.\n\n**Total students leaving early:** \n$$ 6 + 6 = \\boxed{12} $$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Since Charlie's boots are five times the size of Sophie's, and Sophie wears size five boots, Charlie must wear size **25**.\n\nThe average size of the two is:\n\n$$\n\\frac{5 + 25}{2} = \\boxed{15}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Pat wants to fill her flower bed with plants. \n- The flower bed is **111 feet long**. \n- Each plant is **12 inches wide**, and **1.5 feet** of space is left between every plant. \n- Pat already owns **17 flowers**. \n- Each plant costs **$6**. \n\n### Step 1: Convert all measurements to feet \n- 111 feet is already in feet. \n- 12 inches = 1 foot. \n- 1.5 feet is already in feet. \n\n### Step 2: Calculate the total length of the flower bed \nPat needs to leave **1.5 feet** between every plant. \n- The number of plants is **17**. \n-" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Edgar eats 18 pretzels a day. His brother eats **half as many**, so:\n\n$$\n\\frac{1}{2} \\times 18 = 9\n$$\n\nIn a week (7 days), the brother eats:\n\n$$\n9 \\times 7 = \\boxed{63}\n$$\n\n**Answer:** $\\boxed{63}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Katherine has 5 baskets, each containing:\n- 3 petunias at $3.00 each\n- 2 sweet potato vines at $2.50 each\n\nTotal cost = $3.00 × 3 + $2.50 × 2 × 5 \n= $9.00 + $25.00 \n= **$34.00**\n\n$$\n\\boxed{34}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "They plant:\n- 4 sunflowers: $4 \\times 3 = 12$ pounds\n- 10 carnations: $10 \\times 1.5 = 15$ pounds\n\nTotal weight used: $12 + 15 = 27$ pounds\n\nThey can plant:\n$$\n\\frac{27}{1} = 27 \\text{ roses}\n$$\n\n$$\n\\boxed{27}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Jessica makes $2,000.00 a month. She sets 25% of her paycheck aside for fancy shoes. \n- 25% of $2,000.00 is $500.00. \n- Each pair of shoes costs $1,000.00. \n- So, the number of shoes she can buy in a year is: \n $$\n \\frac{500}{1000} \\times 12 = 6\n $$\n\n**Final Answer:** $\\boxed{6}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Emily can peel 6 shrimp per minute and sauté 30 shrimp in 10 minutes. \nSo, in 1 minute, she can peel 6 shrimp and sauté 30 shrimp. \n\nTo find how long it takes to cook 90 shrimp: \n$$\n\\frac{90}{6} = 15 \\text{ minutes}\n$$\n\n**Final Answer:** $\\boxed{15}$ minutes." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The room was initially at a temperature $ T $. \n- On low: it cools at 2 degrees per hour, so after 3 hours: $ T - 2 \\times 3 = T - 6 $ \n- On high: it cools at 3 degrees per hour, so after 4 hours: $ T - 3 \\times 4 = T - 12 $ \n- Then it cools at 2 degrees per hour for 2 hours: $ T - 12 - 2 \\times 2 = T - 16 $ \n\nSo, the final temperature is $ T - 16 $. \n\n**Final answer:** $ \\boxed{16} $ degrees lower than the starting temperature." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let $ x $ be the age of Bill when he saw the comet for the first time.\n\n- Bill's father was 30 years old when he saw the comet.\n- Bill saw the comet a second time when he was 3 times the age his father was when he saw the comet.\n\nSo, when Bill saw the comet for the first time, his father was $ x - 30 $ years old.\n\nThen, Bill saw the comet again when he was 3 times that age:\n\n$$\nx = 3(x - 30)\n$$\n\nSolving:\n\n$$\nx = 3x - 90 \\\\\n2x = 90 \\\\\nx = 45\n$$\n\n**Answer:** $\\boxed{45}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Buford writes:\n\n- 1 check per month for the electric bill \n- 1 check per month for the gas bill \n- 2 checks per month for the church \n- 1 check quarterly for the pest and lawn service \n\nSo, per year:\n\n$$\n1 + 1 + 2 + 1 = 5 \\text{ checks per month}\n$$\n\n$$\n5 \\times 12 = \\boxed{60} \\text{ checks per year}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Let the number of flights to France be $ x $, and the number of flights to Germany be $ y $. Then:\n\n- The first plane has $ 3x + y $ flights in total.\n- The other plane has 44 trips, which is half of the first plane's total: $ \\frac{3x + y}{2} = 44 $.\n\nSolving:\n\n$$\n3x + y = 88\n$$\n\nWe are asked to find the number of flights to France, which is $ x $.\n\nSo, the answer is:\n\n$$\n\\boxed{16}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Tobias: 20 seconds \n- Chikote: $2 \\times 20 = 40$ seconds \n- Igneous: $20 + 40 = 60$ seconds \n\n**Total time:** $20 + 40 + 60 = 120$ seconds \n\n**Convert to minutes:** $120 \\div 60 = 2$ minutes\n\n$$\n\\boxed{2}\n$$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Adam's savings:\n- $6 from his mother\n- $12 from his father (twice as much as $6)\n\nTotal: $6 + $12 = $\\boxed{18}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "We are given:\n\n- Helene is **twice as old as the average age** of the group.\n- The **total age of the children is 20**.\n- Akbar is **3 years old**.\n- Alessandro is **4 years old**.\n\nLet the age of **Wilfred** be $ x $.\n\n### Step 1: Find the average age\nThe average age is:\n$$\n\\text{Average} = \\frac{\\text{Total age}}{4} = \\frac{20}{4} = 5\n$$\n\n### Step 2: Use the relationship between Helene and the average\nHelene is **twice as old as the average**:\n$$\n\\text{Helene's age} = 2 \\" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Walter collects $500 from his neighbors and $1500 from an online fund. His lawyer offers to donate **three times** as much as everyone else donates. \n\nLet’s denote the amount that everyone else donates as $ x $. Then the lawyer’s donation is $ 3x $.\n\nSo, the total amount Walter has collected is:\n\n$$\n500 + 1500 + 3x = 2000 + 3x\n$$\n\nWe are told that Walter is going to tell his friend about his neighbors and the online fund **until** his friend gives him $200. This means the total amount he has collected is:\n\n$$\n2000 + 200 = 2200" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "There are 100 guests in the reception, and each guest brought 15 cookies. So:\n\n$$\n100 \\times 15 = 1500 \\text{ cookies}\n$$\n\nThe bride gives 1/2 of the cookies to the church next door, which is:\n\n$$\n\\frac{1}{2} \\times 1500 = 750 \\text{ cookies}\n$$\n\nEach person in the church next door got 15 cookies, so:\n\n$$\n\\frac{750}{15} = 50\n$$\n\n**Answer:** $\\boxed{50}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Each adult gets a slice that is **twice as big** as that of each kid. \nLet the size of each kid's slice be $ x $. \nThen each adult's slice is $ 2x $. \n\nSince there are 6 people, and 2 adults and 4 kids, the total watermelon is divided as:\n\n- 2 adults: $ 2 \\times 2x = 4x $\n- 4 kids: $ 4x $\n\nSo, the **total watermelon** is $ 4x + 4x = 8x $.\n\nEach adult gets $ 4x $, so the **percentage** of the watermelon each adult gets is:\n\n$$\n\\frac{4x}{8x} \\times 100" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Doctor Jones has:\n- 9 inpatients\n- 20 minutes per inpatient\n- 30 minutes per appointment\n\nTotal time spent:\n- 9 inpatients × 20 minutes = 180 minutes\n- 10 appointments × 30 minutes = 300 minutes\n\nConvert to hours:\n- 180 minutes = 3 hours\n- 300 minutes = 5 hours\n\nTotal time spent = 3 + 5 = **8 hours**\n\nHe has **9 hours** at the clinic, so the remaining time is:\n\n$$\n9 - 8 = \\boxed{1} \\text{ hour}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Jordan knows the total time to make the cake is **20 minutes + 30 minutes = 50 minutes**. \nThe cake requires **2 hours (120 minutes) + 10 minutes = 130 minutes** to complete. \n\nSo, the total time from when she starts to when it is ready is:\n\n$$\n130 + 50 = 180 \\text{ minutes}\n$$\n\nShe wants the cake to be ready at **5:00 pm**, and she plans to make it **all on the same day**. \n\nTo find the latest time she can start:\n\n$$\n5:00 \\text{ pm} - 180 \\text{ minutes} = 5:00 \\text" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Lisa sold $3.5$ boxes and Peter sold $4.5$ boxes. Together, they sold:\n\n$$\n3.5 + 4.5 = 8 \\text{ boxes}\n$$\n\nThey sold 64 chocolate bars in total. So, the number of chocolate bars in a box is:\n\n$$\n\\frac{64}{8} = 8\n$$\n\n$$\n\\boxed{8}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The total earnings in a month can be calculated as:\n\n- **Cost to rent the studio**: $25 per session × 3 days = $75 \n- **Cost per student per session**: $1.50 × 10 students = $15 \n- **Total earnings**: $75 + $15 = $\\boxed{90}$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Peter has 4 boxes with the same number of chocolate bars in each, and Martha has 7 boxes with the same number of chocolate bars in each.\n\nLet the number of chocolate bars in each box be $ x $.\n\n- Peter's total: $ 4x = 64 $\n- Martha's total: $ 7x = 56 $\n\nFrom Peter's equation:\n$$\n4x = 64 \\Rightarrow x = 16\n$$\n\nSubstitute $ x = 16 $ into Martha's equation:\n$$\n7x = 56 \\Rightarrow 7 \\times 16 = 112\n$$\n\nNow, the difference in the number of chocolate bars per box is:\n$$\n16 - 112 = -" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The total population of porcupines is 50. \nThe number of female porcupines is $ \\frac{3}{5} \\times 50 = 30 $. \n\nEach female porcupine gives birth to 4 babies per month. After a year, the number of babies born is: \n$$ 30 \\times 12 = 360 $$ \n\nSo, the total number of porcupines after a year is: \n$$ 50 + 360 = \\boxed{410} $$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "The pool has a volume of:\n\n$$\n\\text{Volume} = \\text{width} \\times \\text{length} \\times \\text{depth} = 14 \\times 25 \\times 4 = 1400 \\text{ cubic feet}\n$$\n\nTo find the number of gallons:\n\n$$\n\\text{Gallons} = \\text{cubic feet} \\times 7.48 \\text{ gallons per cubic foot} = 1400 \\times 7.48 = 10472 \\text{ gallons}\n$$\n\nThe cost is:\n\n$$\n\\text{Cost} = \\text{gallons} \\times \\text{cost per gallon} = 104" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "- Red sticks: $ 9 $\n- Blue sticks: $ 9 + 5 = 14 $\n- Yellow sticks: $ 14 - 3 = 11 $\n\nTotal sticks: \n$$\n9 + 14 + 11 = \\boxed{34}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Matteo traveled for 4 hours at 55 mph: \n$$ 55 \\times 4 = 220 \\text{ miles} $$\n\nShandy traveled for 10 hours at 45 mph: \n$$ 45 \\times 10 = 450 \\text{ miles} $$\n\nThe difference in distance: \n$$ 450 - 220 = \\boxed{230} $$\n\nShandy drove **230 miles farther** than Matteo." + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Brook Hills High School currently has:\n\n- 3000 students in total.\n\n- Half of the students are over 16 years old: \n $ \\frac{1}{2} \\times 3000 = 1500 $ students.\n\n- One-fourth of the students over 16 are male: \n $ \\frac{1}{4} \\times 1500 = 375 $ students.\n\n- The remaining half of the students are under 16: \n $ \\frac{1}{2} \\times 1500 = 750 $ students.\n\n- One-half of the students under 16 are male: \n $ \\frac{1}{2} \\times " + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Bethany runs 10 laps in 1 hour. \nTrey runs 4 more laps than Bethany: \n$$ 10 + 4 = 14 $$ \nShaelyn runs half as many laps as Trey: \n$$ \\frac{14}{2} = 7 $$ \nQuinn runs 2 fewer laps than Shaelyn: \n$$ 7 - 2 = 5 $$ \n\nBethany's laps: 10 \nQuinn's laps: 5 \nDifference: $ 10 - 5 = \\boxed{5} $" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "- The tank has a capacity of **18,000 gallons**.\n- On **Day 1**:\n - Wanda filled **$ \\frac{1}{4} \\times 18,000 = 4,500 $** gallons.\n - Ms. B pumped **$ \\frac{3}{4} \\times 4,500 = 3,375 $** gallons.\n- Total water pumped on Day 1: $ 4,500 + 3,375 = 7,875 $ gallons.\n- On **Day 2**:\n - Wanda pumped **$ \\frac{2}{3} \\times 4,500 = 3," + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Let $ C $ be the initial charge of the power bank when Maria went out to the park.\n\n- After 5 hours, the power bank loses 9% of its charge:\n $$\n C - 0.09C = 0.91C\n $$\n\n- After 3 more hours, the power bank loses 7% of its charge:\n $$\n 0.91C - 0.07(0.91C) = 0.91C \\cdot (1 - 0.07) = 0.91C \\cdot 0.93 = 0.8493C\n $$\n\n- The final charge remaining is 28%:\n $$\n" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Janet earns:\n- $10 per hour from wages\n- $15 per hour from tips\n\nSo, her hourly wage is:\n$$\n10 + 15 = 25 \\text{ dollars per hour}\n$$\n\nShe wants to save 20% of the cost of the car, which is:\n$$\n0.20 \\times 10000 = 2000 \\text{ dollars}\n$$\n\nShe works 40 hours a week, so her weekly earnings are:\n$$\n40 \\times 25 = 1000 \\text{ dollars per week}\n$$\n\nTo save $2000, she needs:\n$$\n\\frac{2000}{1000}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Jamaar has earned $10, and has already purchased:\n- 3 peaches: $1.50\n- 4 pears: $1.00\n- 2 kiwis: $2.00\n- 5 apples: $3.75\n\nTotal spent: \n$1.50 + $1.00 + $2.00 + $3.75 = **$8.25**\n\nRemaining money: \n$10 - $8.25 = **$1.75**\n\nPlums cost $0.25 each, so: \n$1.75 ÷ $0.25 = **7 plums**\n\n$$\n\\boxed{7}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "Anne purchased 15 packs of sweets, each with 60 pieces. She kept **2 packs** and gave the rest to her **10 friends equally**.\n\n- Total sweets = $15 \\times 60 = 900$\n- Sweets given to friends = $900 - 2 \\times 60 = 900 - 120 = 780$\n- Sweets per friend = $780 \\div 10 = 78$\n\n**Answer:** $\\boxed{78}$" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "The price of carrots increases by **5% of the original price** every year. This means the price after each year is:\n\n$$\n\\text{New price} = \\text{Original price} \\times (1 + 0.05)\n$$\n\nAfter 3 years:\n\n$$\n120 \\times (1.05)^3\n$$\n\n$$\n120 \\times 1.157625 = 138.915\n$$\n\nRounded to the nearest integer:\n\n$$\n\\boxed{139}" + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "Olivia uploaded 72 pictures in total. She put the same number into 8 albums:\n\n- 3 albums were selfies only.\n- 2 albums were portraits.\n\nSo, the number of portraits is $ 2 $, and the number of selfies is $ 3 $.\n\n$$\n\\boxed{2 \\text{ portraits and } 3 \\text{ selfies}}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "James reads 18 pages of his book, and it takes him 10 minutes to read 3 pages. So, the time per page is:\n\n$$\n\\frac{10 \\text{ minutes}}{3 \\text{ pages}} = \\frac{10}{3} \\text{ minutes per page}\n$$\n\nNow, multiply by 18 pages:\n\n$$\n18 \\times \\frac{10}{3} = 60 \\text{ minutes}\n$$\n\n**Final Answer:** $\\boxed{60}$ minutes." + }, + { + "accuracy": 0.0, + "format": 1.0, + "reward": 0.2, + "completion": "- 100 guests were initially booked.\n- 24 guests checked in early.\n- 15 guests checked in late.\n- In the afternoon, twice as many checked in as late: $ 2 \\times 15 = 30 $.\n- 7 more guests checked in after dinner.\n\nTotal guests now: \n$$\n100 + 24 + 15 + 30 + 7 = \\boxed{176}\n$$" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "John picks:\n- 4 bananas on Wednesday \n- 6 bananas on Thursday \n- Triple the number of bananas on Wednesday on Friday: $ 3 \\times 4 = 12 $\n\nSo, the total number of bananas is:\n\n$$\n4 + 6 + 12 = \\boxed{22}\n$$" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "In a 60-item quiz:\n\n- 40% of the questions are **easy** → $ 0.4 \\times 60 = 24 $ questions.\n- The remaining $ 60 - 24 = 36 $ questions are **average and difficult**.\n- These are **equally divided** as average and difficult → $ 36 / 2 = 18 $ average and 18 difficult questions.\n\nAries is sure to get **75% of the easy questions** → $ 0.75 \\times 24 = 18 $.\n\nShe is also sure to get **half of the average and difficult questions** → $ 0.5 \\times 18 = 9 $.\n\nSo" + }, + { + "accuracy": 0.0, + "format": 0.0, + "reward": 0.0, + "completion": "Teresa sells small stuffed animals for $4 each, and large stuffed animals for $3 each. She sold twice as many small stuffed animals as large ones, and earned $120 in total.\n\nLet the number of small stuffed animals be $ x $, and the number of large stuffed animals be $ y $.\n\nWe are told:\n- $ x = 2y $\n- $ 4x = 120 $\n\nSubstitute $ x = 2y $ into the second equation:\n$$\n4(2y) = 120 \\Rightarrow 8y = 120 \\Rightarrow y = 15\n$$\n\nSo, the number of small stuffed animals is:\n$$\nx = 2y = 2 \\times 15 =" + }, + { + "accuracy": 1.0, + "format": 1.0, + "reward": 1.2, + "completion": "The family eats:\n- 5 sandwiches/day × 7 days = 35 sandwiches \n- 4 sandwiches/day × 7 days = 28 sandwiches \n- 2 sandwiches/day × 7 days = 14 sandwiches \n\nTotal: $ 35 + 28 + 14 = \\boxed{77} $" + } + ] + }, + "accuracy_delta": 0.09375, + "reward_delta": 0.1351562499999982 +} \ No newline at end of file diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 416a8c781..90e5da6de 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -14,6 +14,7 @@ import pickle import threading from collections.abc import Iterable +from contextlib import contextmanager from dataclasses import dataclass from enum import Enum from pathlib import Path @@ -23,6 +24,44 @@ _ZERO_DIGEST = "0" * 64 _OBJECT_MAGIC = b"RRS1" +_PATH_LOCKS: dict[str, threading.Lock] = {} +_PATH_LOCKS_GUARD = threading.Lock() + + +def _thread_path_lock(path: Path) -> threading.Lock: + key = str(path.resolve()) + with _PATH_LOCKS_GUARD: + return _PATH_LOCKS.setdefault(key, threading.Lock()) + + +@contextmanager +def _exclusive_file_lock(path: Path): + """Serialize one journal across threads and processes.""" + lock_path = path.with_name(path.name + ".lock") + lock_path.parent.mkdir(parents=True, exist_ok=True) + with _thread_path_lock(lock_path): + with open(lock_path, "a+b") as stream: + stream.seek(0, os.SEEK_END) + if stream.tell() == 0: + stream.write(b"\0") + stream.flush() + stream.seek(0) + if os.name == "nt": + import msvcrt + + msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1) + else: + import fcntl + + fcntl.flock(stream.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + stream.seek(0) + if os.name == "nt": + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(stream.fileno(), fcntl.LOCK_UN) class ResumeError(RuntimeError): @@ -112,7 +151,8 @@ def __init__(self, path: str | os.PathLike[str]): self._next_seq = 0 self._last_digest = _ZERO_DIGEST self._records: list[JournalRecord] = [] - self._repair_and_scan() + with _exclusive_file_lock(self.path): + self._repair_and_scan() def _repair_and_scan(self) -> None: if not self.path.exists(): @@ -161,24 +201,40 @@ def _repair_and_scan(self) -> None: def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | None = None) -> JournalRecord: with self._lock: - body = { - "seq": self._next_seq, - "event": event.value, - "state_key": state_key, - "payload": payload or {}, - "prev": self._last_digest, - } - digest = _record_digest(body) - line = json.dumps({**body, "digest": digest}, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" - with open(self.path, "ab") as stream: - stream.write(line) - stream.flush() - os.fsync(stream.fileno()) - record = JournalRecord(self._next_seq, event, state_key, payload or {}, self._last_digest, digest) - self._records.append(record) - self._next_seq += 1 - self._last_digest = digest - return record + with _exclusive_file_lock(self.path): + self._repair_and_scan() + old_size = self.path.stat().st_size if self.path.exists() else 0 + body = { + "seq": self._next_seq, + "event": event.value, + "state_key": state_key, + "payload": payload or {}, + "prev": self._last_digest, + } + digest = _record_digest(body) + line = ( + json.dumps({**body, "digest": digest}, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" + ) + try: + with open(self.path, "ab") as stream: + stream.write(line) + stream.flush() + os.fsync(stream.fileno()) + except BaseException: + try: + with open(self.path, "r+b") as stream: + stream.truncate(old_size) + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + self._repair_and_scan() + raise + record = JournalRecord(self._next_seq, event, state_key, payload or {}, self._last_digest, digest) + self._records.append(record) + self._next_seq += 1 + self._last_digest = digest + return record def records(self, *, state_key: str | None = None) -> Iterable[JournalRecord]: with self._lock: diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py new file mode 100644 index 000000000..6e63e3736 --- /dev/null +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -0,0 +1,335 @@ +import errno +import os +import time +from concurrent.futures import ThreadPoolExecutor + +import pytest + +from twinkle.data_format.sampling import SamplingParams +from twinkle_agentic.async_rl import rollout_resume +from twinkle_agentic.async_rl.rollout_resume import ( + DurableJournal, + JournalEvent, + ResumeStore, + UnsafeResume, + atomic_write_bytes, +) +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver +from twinkle_agentic.envs.base import EnvResumeCapability +from twinkle_agentic.rollout.multi_turn import MultiTurnRollout, RolloutStatus, _Episode + + +class _Future: + def __init__(self, value=None): + self._value = value + + def exception(self): + return None + + def result(self): + return self._value + + def add_done_callback(self, callback): + callback(self) + + +class _DoneRollout: + def step(self, trajectory, episode_id=None, session_wait=None): + row = dict(trajectory, turns=1) + sample = RolloutStatus( + episode_id=episode_id, + turns=1, + done=True, + token_lengths=(1, 1), + stop_reason="stop", + ) + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + return None + + +class _PolicyManager: + def __init__(self, version, paths): + self._version = version + self._paths = dict(paths) + + def version(self): + return self._version + + def adapter_path(self, version): + return self._paths.get(version) + + +class _Template: + max_length = 32 + truncation_strategy = "right" + + +def _prompts(count=2): + return [{"messages": [{"role": "user", "content": f"prompt-{index}"}]} for index in range(count)] + + +def _consume(store, run_id): + driver = StreamingDriver( + _prompts(3), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=2, + run_id=run_id, + resume_store=store, + ) + batches = [] + try: + for batch in range(2): + rows, facts = driver._next_batch() + batches.append((rows, facts)) + driver.commit_batch(f"checkpoint-{batch}" if store is not None else "") + finally: + driver.close() + return batches + + +def test_no_fault_durable_and_memory_drivers_are_equivalent(tmp_path): + memory_batches = _consume(None, "run-no-fault") + durable_batches = _consume(ResumeStore(tmp_path, "run-no-fault"), "run-no-fault") + assert durable_batches == memory_batches + + +def test_journal_concurrent_instances_share_one_chain(tmp_path): + path = tmp_path / "rollout.jsonl" + writers = [DurableJournal(path) for _ in range(4)] + + def append_many(writer, writer_index): + for item in range(20): + writer.append(JournalEvent.PROMPT_ASSIGNED, f"run/{writer_index}/{item}") + + with ThreadPoolExecutor(max_workers=len(writers)) as pool: + list(pool.map(lambda pair: append_many(pair[1], pair[0]), enumerate(writers))) + + reloaded = DurableJournal(path) + records = list(reloaded.records()) + assert len(records) == 80 + assert [record.seq for record in records] == list(range(80)) + assert len({record.digest for record in records}) == 80 + + +def test_journal_fsync_failure_rolls_back_uncertain_append(tmp_path, monkeypatch): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/stable") + old_size = path.stat().st_size + + def disk_full(_descriptor): + raise OSError(errno.ENOSPC, "disk full") + + with monkeypatch.context() as context: + context.setattr(rollout_resume.os, "fsync", disk_full) + with pytest.raises(OSError, match="disk full"): + journal.append(JournalEvent.GROUP_READY, "run/uncertain") + + assert path.stat().st_size == old_size + reloaded = DurableJournal(path) + assert [record.state_key for record in reloaded.records()] == ["run/stable"] + + +def test_atomic_rename_failure_preserves_previous_object(tmp_path, monkeypatch): + target = tmp_path / "objects" / "state.resume" + atomic_write_bytes(target, b"old") + + def interrupted_replace(_source, _target): + raise OSError(errno.EINTR, "replace interrupted") + + with monkeypatch.context() as context: + context.setattr(rollout_resume.os, "replace", interrupted_replace) + with pytest.raises(OSError, match="replace interrupted"): + atomic_write_bytes(target, b"new") + + assert target.read_bytes() == b"old" + assert list(target.parent.glob("*.tmp")) == [] + + +def _ready_driver(tmp_path, run_id): + store = ResumeStore(tmp_path, run_id) + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + driver._start() + deadline = time.monotonic() + 2 + while driver._ready_rows < 2 and time.monotonic() < deadline: + time.sleep(0.01) + assert driver._ready_rows == 2 + return store, driver + + +def test_exactly_once_commit_contract_and_stale_snapshot(tmp_path): + store, driver = _ready_driver(tmp_path, "run-lease") + try: + rows, facts = driver._next_batch() + leased_state = driver.state_dict() + with pytest.raises(UnsafeResume, match="durable model checkpoint"): + driver.commit_batch("") + assert driver.commit_batch("checkpoint/one", {"optimizer_step": 1}) == "run-lease/batch/0" + assert driver.commit_batch("checkpoint/one", {"optimizer_step": 1}) is None + finally: + driver.close() + + recovered = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + recovered.load_state_dict(leased_state) + assert recovered._lease is None + assert recovered._next_batch() is None + assert rows + assert facts["policy_versions"] == [0] + + +def _episode(rollout, state_key="run/group-0/episode-0"): + trajectory = {"messages": [{"role": "user", "content": "hello"}], "state_key": state_key} + episode = _Episode("episode-0", trajectory, rollout._params(SamplingParams())) + episode.ledger = rollout._new_ledger("episode-0") + episode.ledger._pif = { + "input_ids": [1, 2, 3], + "labels": [-100, 2, 3], + "completion_mask": [0, 1, 1], + "messages": trajectory["messages"], + } + episode.ledger._turns = 1 + episode.budget = 3 + episode.spent = 1 + episode.state_key = state_key + return episode + + +class _NoResumeEnv: + resume_capability = EnvResumeCapability.NONE + + def __init__(self): + self.calls = 0 + + def checkpoint_episode(self, episode_id, state_key): + self.calls += 1 + return {"unexpected": True} + + def restore_episode(self, episode_id, state_key, state, trajectory=None): + self.calls += 1 + + +def test_env_without_resume_capability_fails_closed(tmp_path): + store = ResumeStore(tmp_path, "run-env") + env = _NoResumeEnv() + rollout = MultiTurnRollout(response_callback=lambda *_args: None, template=_Template(), env=env, resume_store=store) + episode = _episode(rollout) + episode.env_open = True + rollout._episodes[episode.episode_id] = episode + + with pytest.raises(UnsafeResume, match="no durable resume capability"): + rollout.checkpoint_episode(episode.episode_id) + assert env.calls == 0 + + episode.env_open = False + state = rollout.checkpoint_episode(episode.episode_id) + state["env_open"] = True + restored = MultiTurnRollout( + response_callback=lambda *_args: None, + template=_Template(), + env=env, + resume_store=store, + ) + with pytest.raises(UnsafeResume, match="no durable resume capability"): + restored.restore_episode(state) + assert env.calls == 0 + assert restored._episodes == {} + + +class _CountingTool: + def __init__(self): + self.calls = 0 + + def __call__(self, _tool_call): + self.calls += 1 + return f"side-effect-{self.calls}" + + +def test_non_idempotent_tool_is_not_replayed_after_crash(tmp_path): + store = ResumeStore(tmp_path, "run-tool") + source = MultiTurnRollout(response_callback=lambda *_args: None, template=_Template(), resume_store=store) + episode = _episode(source) + source._episodes[episode.episode_id] = episode + before_tool = source.checkpoint_episode(episode.episode_id) + + tool = _CountingTool() + calls = [{"name": "charge_card", "arguments": {"amount": 10}}] + effect_key, cached = source._begin_tool_effect(episode, calls) + assert effect_key is not None and cached is None + observations = source._run_tools(tool, calls) + assert tool.calls == 1 + assert observations == ["side-effect-1"] + + crashed = MultiTurnRollout(response_callback=lambda *_args: None, template=_Template(), resume_store=store) + with pytest.raises(UnsafeResume, match="pending tool effects"): + crashed.restore_episode(before_tool) + assert tool.calls == 1 + + source._commit_tool_effect(episode, effect_key, observations) + safe_state = store.load_episode(episode.state_key) + recovered = MultiTurnRollout(response_callback=lambda *_args: None, template=_Template(), resume_store=store) + recovered.restore_episode(safe_state) + recovered_episode = recovered._episodes[episode.episode_id] + replay_key, replay = recovered._begin_tool_effect(recovered_episode, calls) + assert replay_key == effect_key + assert replay == observations + assert tool.calls == 1 + + +def test_adapter_lifecycle_deleted_path_and_path_reuse_are_explicit(tmp_path): + manager = _PolicyManager(1, {}) + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=1, + checkpoint_manager=manager, + ) + group_state = { + "key": "0", + "row": _prompts(1)[0], + "version": 1, + "adapter_path": None, + "attempt": 0, + "source": [], + "members": [], + "baselines": [], + "missing": 0, + } + with pytest.raises(UnsafeResume, match="no resolvable adapter path"): + driver._restore_group(group_state) + + manager._paths[1] = "/policies/reused-policy.adapter" + explicit = dict(group_state, adapter_path="/policies/original-policy.adapter") + restored = driver._restore_group(explicit) + assert restored.adapter_path == "/policies/original-policy.adapter" + + +def test_openenv_adapters_declare_no_resume_capability(): + from twinkle_agentic.envs.agentenv import AgentEnv + from twinkle_agentic.envs.openenv import OpenEnv, OpenEnvClient + + assert AgentEnv.resume_capability is EnvResumeCapability.NONE + assert OpenEnv.resume_capability is EnvResumeCapability.NONE + assert OpenEnvClient.resume_capability is EnvResumeCapability.NONE From 3f01cf689bffff68d4e39e79280faef24e07bb71 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 16:42:41 +0800 Subject: [PATCH 03/45] feat(agentic): tighten durable resume semantics --- .../rl/async_rl/durable_multi_turn_grpo.py | 404 +++++++++++++ .../rl/async_rl/durable_multi_turn_grpo.sh | 31 + .../Agentic/DurableRolloutResume.md" | 194 ++++++ .../Agentic/index.rst" | 1 + ...CKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md | 58 ++ review/a2/PR399_RESULTS_20261119.md | 256 +++++--- .../README.md | 16 + .../adapter_temp_uncommitted/ready.json | 103 ++++ .../adapter_temp_uncommitted/verify.json | 29 + .../checkpoint_committed/ready.json | 105 ++++ .../checkpoint_committed/verify.json | 29 + .../ready.json | 105 ++++ .../verify.json | 29 + .../optimizer_step_uncommitted/ready.json | 93 +++ .../optimizer_step_uncommitted/verify.json | 25 + .../report.json | 565 ++++++++++++++++++ review/a2/run_focused_tests.py | 1 + review/a2/run_npu_checkpoint_kill_probe.py | 10 +- .../async_rl/rollout_resume.py | 46 ++ .../async_rl/streaming_driver.py | 115 +++- src/twinkle_agentic/envs/__init__.py | 7 +- src/twinkle_agentic/envs/base.py | 43 +- src/twinkle_agentic/envs/localenv.py | 5 +- src/twinkle_agentic/envs/resume.py | 75 +++ src/twinkle_agentic/rollout/multi_turn.py | 7 +- .../test_group_policy_binding.py | 30 + tests/twinkle_agentic/test_localenv_resume.py | 2 +- .../twinkle_agentic/test_resume_boundaries.py | 8 +- .../test_streaming_driver_resume.py | 197 +++++- 29 files changed, 2437 insertions(+), 152 deletions(-) create mode 100644 cookbook/rl/async_rl/durable_multi_turn_grpo.py create mode 100644 cookbook/rl/async_rl/durable_multi_turn_grpo.sh create mode 100644 "docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" create mode 100644 review/a2/NPU_CHECKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/README.md create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json create mode 100644 review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json create mode 100644 src/twinkle_agentic/envs/resume.py create mode 100644 tests/twinkle_agentic/test_group_policy_binding.py diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py new file mode 100644 index 000000000..4b3ce2327 --- /dev/null +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -0,0 +1,404 @@ +# Copyright (c) ModelScope Contributors. All rights reserved. +"""End-to-end GSM8K multi-turn GRPO with durable group checkpoints. + +The example trains a LoRA policy on the official GSM8K train split. Each +prompt is sampled as one complete GRPO group, may receive one format-repair +follow-up, and is trained with a batch lease owned by ``StreamingDriver``. + +The durable transaction is: + +1. finish every mini-batch and optimizer step for the leased rollout batch; +2. save adapter, optimizer, scheduler and RNG state; +3. call ``driver.commit_batch(checkpoint, manifest)``; +4. publish the new policy and admit the next version. + +A crash before step 3 reloads the previous committed checkpoint and re-delivers +the same batch lease. A crash after step 3 reloads this checkpoint and does not +train the batch twice. +""" +from __future__ import annotations +import os +import re +from pathlib import Path +from typing import Any, Dict, Iterable, List + +import json +from peft import LoraConfig + +import twinkle +from twinkle import DeviceGroup, DeviceMesh, get_device_placement, get_logger +from twinkle.advantage import GRPOAdvantage +from twinkle.checkpoint_engine import CheckpointEngineManager +from twinkle.cli import CLI +from twinkle.data_format import SamplingParams +from twinkle.dataloader import DataLoader +from twinkle.dataset import Dataset, DatasetMeta +from twinkle.metric import CompletionRewardMetric +from twinkle.model import TransformersModel +from twinkle.preprocessor.llm import GSM8KProcessor +from twinkle.processor import InputProcessor +from twinkle.reward import GSM8KAccuracyReward +from twinkle.reward.base import Reward +from twinkle.sampler import vLLMSampler +from twinkle.template import Qwen3_5Template +from twinkle_agentic.async_rl import StreamingDriver +from twinkle_agentic.async_rl.rollout_resume import JournalEvent, ResumeStore, atomic_write_bytes +from twinkle_agentic.rollout.multi_turn import MultiTurnRollout + +logger = get_logger() +args = CLI.from_args() + +MODEL_ID = args.model.model_id or 'ms://Qwen/Qwen3.5-4B' +MODEL_GPUS = args.infra.model_gpus or 4 +SAMPLER_GPUS = args.infra.sampler_gpus or 4 +NUM_GPUS = MODEL_GPUS + SAMPLER_GPUS + +NUM_GENERATIONS = args.rl.num_generations or 4 +BATCH_SIZE = args.training.batch_size or 2 +GLOBAL_BATCH_SIZE = BATCH_SIZE * NUM_GENERATIONS +MINI_BATCH_SIZE = args.training.mini_batch_size or GLOBAL_BATCH_SIZE +MICRO_BATCH_SIZE = args.training.micro_batch_size or 2 +MAX_STEPS = args.training.max_steps or 100 +MAX_NEW_TOKENS = args.sampling.max_tokens or 1024 +LEARNING_RATE = args.optimizer.learning_rate or 1e-5 +LORA_RANK = args.lora.lora_r or 8 +ADAPTER_NAME = args.lora.adapter_name or 'durable-grpo' + +RUN_ID = os.environ.get('TWINKLE_DURABLE_RUN_ID', 'gsm8k-durable-grpo') +RESUME_ROOT = Path(os.environ.get('TWINKLE_RESUME_ROOT', 'output/durable-gsm8k')) +CHECKPOINT_ROOT = RESUME_ROOT / 'model-checkpoints' + +if MINI_BATCH_SIZE != GLOBAL_BATCH_SIZE: + raise ValueError( + 'mini_batch_size must equal batch_size * num_generations so one driver lease maps to ' + f'exactly one optimizer step, got {MINI_BATCH_SIZE} and {GLOBAL_BATCH_SIZE}' + ) + +SYSTEM_PROMPT = ( + 'You are a careful math assistant. Solve the problem and put only the final ' + 'answer in \\boxed{}.' +) + + +class _ImmediateFuture: + """Adapt a synchronous reward function to the driver's future contract.""" + + def __init__(self, value: Any): + self._value = value + + def exception(self) -> None: + return None + + def result(self) -> Any: + return self._value + + def add_done_callback(self, callback) -> None: + callback(self) + + +class _BrevityReward(Reward): + """Small deterministic format reward, aligned with the short-math example.""" + + def __call__(self, trajectories: List[Dict[str, Any]], **kwargs) -> List[float]: + rewards = [] + for trajectory in trajectories: + reply = '' + for message in reversed(trajectory.get('messages') or ()): + if message.get('role') == 'assistant': + reply = str(message.get('content') or '') + break + has_answer = bool( + re.search(r'\\boxed\{[^}]+\}', reply) + or re.search(r'####\s*[\-\d,\.]+', reply) + ) + if not has_answer: + rewards.append(0.0) + elif len(reply) <= 300: + rewards.append(1.0) + else: + rewards.append(max(0.0, 1.0 - (len(reply) - 300) / 3000)) + return rewards + + +def _reward_future(reward: Reward): + def score(trajectories): + return _ImmediateFuture(reward(trajectories)) + + return score + + +class _PolicyIndex: + """Translate monotonic driver versions to retained adapter directories.""" + + def __init__(self, path: Path): + self.path = path + self._paths: dict[int, str] = {} + self._current_version = 0 + if path.is_file(): + raw = json.loads(path.read_text(encoding='utf-8')) + self._paths = {int(version): str(value) for version, value in raw.items()} + self._current_version = max(self._paths, default=0) + + @property + def latest_version(self) -> int: + return max(self._paths, default=0) + + def version(self) -> int: + return self._current_version + + def adapter_path(self, version: int) -> str | None: + return self._paths.get(int(version)) + + def register(self, version: int, checkpoint: str) -> None: + version = int(version) + checkpoint = str(checkpoint) + if version < 0 or not checkpoint: + raise ValueError('policy registration needs a non-negative version and checkpoint') + self._paths[version] = checkpoint + self._current_version = max(self._current_version, version) + self.path.parent.mkdir(parents=True, exist_ok=True) + atomic_write_bytes( + self.path, + (json.dumps(self._paths, ensure_ascii=False, indent=2, sort_keys=True) + '\n').encode('utf-8'), + ) + + def recover_from_journal(self, records: Iterable[Any]) -> None: + """Recover a commit that became durable before the JSON index write.""" + for record in records: + if record.event != JournalEvent.MODEL_CHECKPOINT_COMMITTED: + continue + manifest = record.payload.get('manifest') or {} + version = manifest.get('policy_version') + checkpoint = record.payload.get('checkpoint') + if version is not None and checkpoint: + self.register(int(version), str(checkpoint)) + + +def create_gsm8k_dataset(): + dataset = Dataset() + dataset.add_dataset(DatasetMeta('ms://modelscope/gsm8k', subset_name='main', split='train')) + dataset.set_template( + 'Qwen3_5Template', + model_id=MODEL_ID, + max_length=4096, + truncation_strategy='delete', + enable_thinking=False, + ) + dataset.map(GSM8KProcessor(system=SYSTEM_PROMPT)) + dataset.encode(add_generation_prompt=True) + return dataset + + +def _followup(trajectory: Dict[str, Any], followups: int): + if followups >= 1: + return None + replies = [ + str(message.get('content') or '') + for message in trajectory.get('messages') or () + if message.get('role') == 'assistant' + ] + if replies and re.search(r'\\boxed\{[^}]+\}', replies[-1]): + return None + return 'Please restate the result with the final answer inside \\boxed{}.' + + +def _score_vector(rows: List[Any], facts: Dict[str, Any]) -> List[float]: + scores = facts.get('scores') or () + if len(scores) != len(rows): + raise RuntimeError(f'driver returned {len(rows)} rows but {len(scores)} score records') + rewards = [] + for item in scores: + values = (item.get('rewards') or {}).get('orm') or {} + accuracy = values.get('accuracy') + brevity = values.get('brevity') + rewards.append(float(accuracy or 0.0) + float(brevity or 0.0)) + return rewards + + +def _old_logps(rows: List[Any]) -> List[List[float]]: + values = [] + for row in rows: + logps = row.get('rollout_logps') + if not logps: + raise RuntimeError(f'row {row.get("episode_id")!r} has no rollout log probabilities') + values.append(list(logps)) + return values + + +def main() -> None: + device_groups = [ + DeviceGroup(name='model', ranks=list(range(MODEL_GPUS)), device_type='GPU'), + DeviceGroup(name='sampler', ranks=list(range(MODEL_GPUS, NUM_GPUS)), device_type='GPU'), + ] + model_mesh = DeviceMesh.from_sizes(world_size=MODEL_GPUS, dp_size=MODEL_GPUS) + sampler_mesh = DeviceMesh.from_sizes(world_size=SAMPLER_GPUS, dp_size=SAMPLER_GPUS) + twinkle.initialize(mode='ray', nproc_per_node=NUM_GPUS, groups=device_groups, lazy_collect=False) + + model = TransformersModel( + model_id=MODEL_ID, + device_mesh=model_mesh, + remote_group='model', + mixed_precision='bf16', + ) + model.add_adapter_to_model( + ADAPTER_NAME, + LoraConfig(target_modules='all-linear', r=LORA_RANK, lora_alpha=LORA_RANK * 2), + gradient_accumulation_steps=1, + ) + model.set_optimizer('AdamW', lr=LEARNING_RATE) + model.set_lr_scheduler('CosineAnnealingLR', T_max=MAX_STEPS, eta_min=0) + model.set_loss('GRPOLoss', epsilon=0.2) + model.set_processor(InputProcessor, padding_free=True) + model.set_template('Qwen3_5Template', model_id=MODEL_ID, enable_thinking=False) + + sampler = vLLMSampler( + model_id=MODEL_ID, + engine_args={ + 'gpu_memory_utilization': 0.8, + 'max_model_len': 8192, + 'max_lora_rank': max(32, LORA_RANK), + 'enable_lora': True, + 'enable_tower_connector_lora': True, + }, + device_mesh=sampler_mesh, + remote_group='sampler', + ) + sampler.set_template('Qwen3_5Template', model_id=MODEL_ID, enable_thinking=False) + ckpt_manager = CheckpointEngineManager(model=model, sampler=sampler) + + store = ResumeStore(RESUME_ROOT, RUN_ID) + policy_index = _PolicyIndex(RESUME_ROOT / 'policy-index.json') + policy_index.recover_from_journal(store.journal.records()) + + committed_records = [ + record for record in store.journal.records() + if record.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED + ] + latest_checkpoint = policy_index.adapter_path(policy_index.latest_version) + if latest_checkpoint is None: + latest_checkpoint = model.save( + 'policy-0', + output_dir=str(CHECKPOINT_ROOT), + adapter_name=ADAPTER_NAME, + save_optimizer=False, + ) + policy_index.register(0, latest_checkpoint) + optim_step = 0 + elif not committed_records: + # The initial adapter index survives a crash before the first commit, + # but it intentionally has no optimizer/trainer_state files. + model.load(latest_checkpoint, adapter_name=ADAPTER_NAME) + optim_step = 0 + else: + progress = model.resume_from_checkpoint(latest_checkpoint, adapter_name=ADAPTER_NAME) + optim_step = int(progress.get('cur_step') or 0) + logger.info(f'resumed model checkpoint {latest_checkpoint} at step {optim_step}') + + template = Qwen3_5Template(MODEL_ID, max_length=4096, enable_thinking=False) + template.truncation_strategy = 'delete' + rollout = MultiTurnRollout( + sampler=sampler, + template=template, + sampling_params=SamplingParams( + max_tokens=MAX_NEW_TOKENS, + num_samples=1, + logprobs=1, + temperature=1.0, + top_p=0.95, + ), + max_turns=2, + max_trajectory_tokens=4096, + followup_fn=_followup, + resume_store=store, + ) + + dataloader = DataLoader( + dataset=create_gsm8k_dataset, + batch_size=BATCH_SIZE, + min_batch_size=BATCH_SIZE, + device_mesh=model_mesh, + remote_group='model', + ) + driver = StreamingDriver( + dataloader, + rollout, + batch_size=GLOBAL_BATCH_SIZE, + num_generations=NUM_GENERATIONS, + max_steps=MAX_STEPS, + max_staleness=1, + checkpoint_manager=policy_index, + orms=[_reward_future(GSM8KAccuracyReward()), _reward_future(_BrevityReward())], + orm_names=['accuracy', 'brevity'], + resume_store=store, + run_id=RUN_ID, + ) + if store.has_object('driver', RUN_ID): + driver.load_state_dict() + logger.info('resumed StreamingDriver from the latest stable boundary') + + advantage_fn = GRPOAdvantage() + metrics = CompletionRewardMetric() + logger.info(get_device_placement()) + + try: + for rows, facts in driver: + if optim_step >= MAX_STEPS: + break + rewards = _score_vector(rows, facts) + advantages = advantage_fn( + rewards, + num_generations=NUM_GENERATIONS, + scale='group', + ).tolist() + old_logps = _old_logps(rows) + completion_lengths = [ + sum(1 for label in (row.get('labels') or ()) if label != -100) + for row in rows + ] + metrics.accumulate( + completion_lengths=completion_lengths, + rewards={'total': rewards}, + ) + + for start in range(0, len(rows), MINI_BATCH_SIZE): + end = start + MINI_BATCH_SIZE + model.forward_backward( + inputs=rows[start:end], + old_logps=old_logps[start:end], + advantages=advantages[start:end], + micro_batch_size=MICRO_BATCH_SIZE, + ) + model.clip_grad_and_step() + optim_step += 1 + + checkpoint = model.save( + f'policy-step-{optim_step}', + output_dir=str(CHECKPOINT_ROOT), + adapter_name=ADAPTER_NAME, + save_optimizer=True, + async_save=False, + ) + next_version = policy_index.version() + 1 + driver.commit_batch( + checkpoint, + manifest={ + 'optimizer_step': optim_step, + 'policy_version': next_version, + }, + ) + policy_index.register(next_version, checkpoint) + + ckpt_manager.sync_weights(merge_and_sync=False) + sampler.reset_prefix_cache() + log_dict = metrics.calculate() + log_dict.update(model.calculate_metric(is_training=True)) + logger.info(f'[durable step {optim_step}/{MAX_STEPS}] {log_dict}') + metrics.reset() + finally: + driver.close() + + logger.info(f'durable GRPO completed: optimizer_step={optim_step}') + + +if __name__ == '__main__': + main() diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.sh b/cookbook/rl/async_rl/durable_multi_turn_grpo.sh new file mode 100644 index 000000000..aa794212f --- /dev/null +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.sh @@ -0,0 +1,31 @@ +#!/bin/sh +set -eu + +# End-to-end GSM8K multi-turn GRPO with automatic group/batch recovery. +# Start with two devices for a smoke run: +# sh durable_multi_turn_grpo.sh \ +# --model-gpus 1 --sampler-gpus 1 --max-steps 2 +# +# The same TWINKLE_DURABLE_RUN_ID and TWINKLE_RESUME_ROOT resume the run. + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +REPO_ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/../../.." && pwd) +export PYTHONPATH="$REPO_ROOT/src${PYTHONPATH:+:$PYTHONPATH}" +export TWINKLE_DURABLE_RUN_ID="${TWINKLE_DURABLE_RUN_ID:-gsm8k-durable-grpo}" +export TWINKLE_RESUME_ROOT="${TWINKLE_RESUME_ROOT:-$REPO_ROOT/output/durable-gsm8k}" + +python "$SCRIPT_DIR/durable_multi_turn_grpo.py" \ + --model-id ms://Qwen/Qwen3.5-4B \ + --strategy native_fsdp \ + --model-gpus 4 \ + --sampler-gpus 4 \ + --num-generations 4 \ + --max-tokens 1024 \ + --batch-size 2 \ + --mini-batch-size 8 \ + --micro-batch-size 2 \ + --max-steps 100 \ + --lr 1e-5 \ + --lora-r 8 \ + --adapter-name durable-grpo \ + "$@" diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" new file mode 100644 index 000000000..391e7a50e --- /dev/null +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -0,0 +1,194 @@ +# 可恢复的流式 GRPO Rollout + +`StreamingDriver` 的 durable 模式用于解决一个训练语义问题:进程重启后,不能只恢复 +“已经生成了多少条轨迹”,还必须保证完整 GRPO 组、behavior policy、batch lease 和 +optimizer checkpoint 属于同一次可验证提交。 + +该能力默认关闭。未传入 `ResumeStore` 时,`StreamingDriver` 保持原有内存流式行为。 + +## 核心不变量 + +1. 一个 GRPO 组只使用一个不可变 behavior policy。 +2. 恢复、成员补采和组替换都沿用首次准入时的 policy binding。 +3. 一个 batch 在模型 checkpoint 持久化前保持 lease;恢复后重交付同一批轨迹。 +4. checkpoint 提交后,同一 lease 不再交付,避免重复 optimizer step。 +5. 无法证明安全恢复的环境或外部工具副作用必须 fail closed。 + +## GroupPolicyBinding + +每个组在准入时固定以下信息: + +```python +from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding + +binding = GroupPolicyBinding( + state_key="run/group/17", + policy_version=4, + adapter_path="/checkpoints/policy-4", +) +``` + +- `state_key` 是跨进程稳定的逻辑组 ID,不使用随机 session ID。 +- `policy_version` 是该组采样时的 policy 版本。 +- `adapter_path` 是该版本的 adapter 快照;`None` 表示使用基础模型。 + +新 driver 快照同时写入结构化 `binding` 和旧版扁平字段。读取旧快照时会自动升级; +binding 与扁平字段不一致时拒绝恢复。 + +## 自动持久化边界 + +启用 `resume_store` 后,driver 在以下稳定边界自动保存快照: + +1. prompt 分配并完成成员提交; +2. 完整组进入 ready 队列; +3. batch lease 写入后; +4. `commit_batch()` 完成 checkpoint 关联后; +5. 组淘汰后。 + +调用方不需要在故障前手工调用 `state_dict()`。恢复入口为: + +```python +driver = StreamingDriver( + dataloader, + rollout, + batch_size=8, + num_generations=4, + checkpoint_manager=policy_index, + resume_store=store, + run_id="gsm8k-durable", +) + +if store.has_object("driver", "gsm8k-durable"): + driver.load_state_dict() +``` + +## Checkpoint 事务 + +训练侧必须按以下顺序提交: + +```python +driver = StreamingDriver(..., resume_store=store, run_id="run") + +rows, facts = driver._next_batch() +model.forward_backward(rows, ...) +model.clip_grad_and_step() + +checkpoint = model.save(..., save_optimizer=True, async_save=False) +driver.commit_batch( + checkpoint, + manifest={ + "optimizer_step": optimizer_step, + "policy_version": next_policy_version, + }, +) +``` + +`commit_batch(checkpoint_ref, manifest)` 是 batch lease 与训练 checkpoint 的唯一关联点。 +未提交前崩溃,恢复上一模型 checkpoint 并重交付同一 lease;已提交后崩溃,恢复新 +checkpoint 且不再交付该 lease。 + +## ResumeStore 与 DurableJournal + +`ResumeStore` 由两层组成: + +- `DurableJournal`:带 hash chain 的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 + 文件锁,以及写入失败回滚; +- object store:保存 prompt、episode、lease 和 driver 快照,读取时校验 SHA-256。 + +故障边界: + +- journal 最后一行未写完:移除不完整尾部; +- 中间记录损坏或 SHA 校验失败:拒绝恢复; +- 磁盘写入失败:回滚不确定的 append; +- object 文件不完整:拒绝解码; +- 旧 lease 已有 commit 记录:恢复时自动退休。 + +## 可恢复环境 + +环境恢复能力采用独立 `ResumableEnv` protocol,不向所有 `Env` 实现增加空方法: + +```python +from twinkle_agentic.envs.resume import EnvResumeCapability + +class MyDurableEnv: + resume_capability = EnvResumeCapability.DURABLE_CHECKPOINT + + def checkpoint_episode(self, episode_id, state_key): + ... + + def restore_episode(self, episode_id, state_key, state, trajectory=None): + ... + + def discard_episode_state(self, state_key): + ... +``` + +未声明恢复能力的 `AgentEnv`、`OpenEnv` 和 `OpenEnvClient` 在 episode 打开时 fail +closed。只恢复文本对话、但丢失 workspace 或工具状态的实现不允许静默继续。 + +## 外部工具副作用 + +每个工具轮次区分 intent 和 result: + +1. 执行前写入 `TOOL_INTENT`; +2. 将工具 observation 写入 episode checkpoint; +3. checkpoint 持久化后写入 `TOOL_RESULT`。 + +恢复时如果存在 intent 但没有 checkpoint 能证明结果,整组状态被拒绝,不会再次执行非 +幂等外部调用。已完成且被 episode checkpoint 覆盖的 effect 直接复用记录结果。 + +## 兼容性 + +- `resume_store=None`:行为与原有 `StreamingDriver` 相同; +- 旧 driver 快照:自动从 `version + adapter_path` 升级为 `GroupPolicyBinding`; +- 未设置 checkpoint manager:仍可保存组和 lease,但不执行 policy 版本淘汰; +- `ResumableEnv` 从 `twinkle_agentic.envs.resume` 或 `twinkle_agentic.envs` 导入; +- 旧的 `twinkle_agentic.envs.base` 导入路径保持兼容。 + +## 示例与测试 + +端到端示例: + +```text +cookbook/rl/async_rl/durable_multi_turn_grpo.py +cookbook/rl/async_rl/durable_multi_turn_grpo.sh +``` + +示例使用官方 GSM8K、Qwen3.5、LoRA、真实多轮 rollout、GRPO 反向传播和 optimizer +checkpoint,并在每个 batch 后调用 `commit_batch()`。 + +聚焦测试: + +```bash +PYTHONPATH="$PWD/src" python -m pytest \ + tests/twinkle_agentic/test_rollout_resume_store.py \ + tests/twinkle_agentic/test_localenv_resume.py \ + tests/twinkle_agentic/test_turn_ledger_resume.py \ + tests/twinkle_agentic/test_multi_turn_resume.py \ + tests/twinkle_agentic/test_group_policy_binding.py \ + tests/twinkle_agentic/test_streaming_driver_resume.py \ + tests/twinkle_agentic/test_resume_boundaries.py \ + tests/twinkle_agentic/test_tail_prefetch.py \ + tests/twinkle_client/test_checkpoint_policy_history.py \ + -q +``` + +## 实验结论与边界 + +已验证: + +- 真实 Qwen3-0.6B LoRA 在 Ascend 910B4 上完成 optimizer step 后强杀; +- checkpoint 临时目录、已发布未提交、已提交三种边界均可正确回退或前进; +- 已提交 batch 不重复训练,未提交 optimizer 更新不泄漏; +- 无故障时 baseline 与 durable 的训练信号和评测结果逐值一致; +- 50% 组丢失故障下,保留完整组的 durable 路径在官方 GSM8K 测试集上取得显著提升。 + +尚未覆盖: + +- 可写 NFS 或对象存储上的 lease、journal 和 adapter 故障矩阵; +- 多卡 HCCL/FSDP2 和大模型验证; +- 无法 checkpoint 的远端 agent harness; +- 所有外部工具协议都具备幂等结果查询。 + +因此该机制不以“所有故障率下无条件提升”为结论,而是在完整组丢失或进程重启时保持 +GRPO 组语义、事务一致性和固定训练预算下的有效训练量。 diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/index.rst" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/index.rst" index 802034366..ad60a6699 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/index.rst" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/index.rst" @@ -9,3 +9,4 @@ Agentic Tools.md Envs.md Multi-Turn-Tool-Usage.md + DurableRolloutResume.md diff --git a/review/a2/NPU_CHECKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md b/review/a2/NPU_CHECKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md new file mode 100644 index 000000000..193954b6f --- /dev/null +++ b/review/a2/NPU_CHECKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md @@ -0,0 +1,58 @@ +# 自动持久化版 NPU Checkpoint 强杀结果 + +## 目的 + +验证 `StreamingDriver` 在启用 `ResumeStore` 后能自行在稳定边界写入 driver +快照。测试进程不再调用 `driver.state_dict()`,避免人工快照掩盖自动持久化缺口。 + +## 环境 + +| 项目 | 配置 | +|---|---| +| 主机 | A2,`e1f3eeac3fc6` | +| NPU | Ascend 910B4,32768 MB HBM | +| Python | 3.10.12 | +| torch | 2.10.0+cpu | +| torch_npu | 2.10.0 | +| transformers | 5.20.2 | +| peft | 0.21.3 | +| 模型 | Qwen3-0.6B | +| 训练方式 | LoRA rank 8,BF16,真实 optimizer step | +| 数据 | 官方 GSM8K `train.jsonl` 固定样本 | + +## 四场景结果 + +四个 worker 均在目标边界被真实 `SIGKILL`,进程返回码均为 `-9`。 + +| 强杀边界 | lease 恢复 | 重交付行数 | optimizer step | LoRA digest | 结论 | +|---|---:|---:|---:|---:|---| +| optimizer step 后、adapter 保存前 | 是 | 2 | `[]` | 匹配 | 未提交更新不泄漏 | +| 临时 adapter/optimizer 保存后 | 是 | 2 | `[]` | 匹配 | 临时 checkpoint 不生效 | +| checkpoint 原子发布后、commit 前 | 是 | 2 | `[]` | 匹配 | 已发布 checkpoint 不被误提交 | +| commit 后 | 否 | 0 | `[1]` | 匹配 | 已提交 batch 不重复训练 | + +所有四个场景均满足: + +- `worker_returncode == -9`; +- `driver_persistence == automatic`; +- 恢复后的 LoRA digest 与预期 checkpoint 一致; +- 恢复后的 optimizer step 与事务边界一致; +- 未提交场景重交付同一 lease,已提交场景不再交付。 + +## 聚焦测试 + +本地和 A2 均通过: + +```text +45 passed +``` + +测试覆盖自动 prompt 快照、ready group、batch lease、commit、旧快照升级、 +policy binding 冲突拒绝、Env fail-closed、非幂等工具和 journal 故障注入。 + +## 证据 + +- `review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json` +- 每个场景的 `ready.json` 和 `verify.json` + +完整 LoRA、optimizer 二进制和运行日志仍保留在 A2 验证目录,不进入 Git。 diff --git a/review/a2/PR399_RESULTS_20261119.md b/review/a2/PR399_RESULTS_20261119.md index 392af1c46..8801269a9 100644 --- a/review/a2/PR399_RESULTS_20261119.md +++ b/review/a2/PR399_RESULTS_20261119.md @@ -1,69 +1,178 @@ -## 目标 +# PR type -把 streaming rollout 的断点恢复升级为 Group-Atomic Durable GRPO: +- [ ] Bug Fix +- [x] New Feature +- [x] Document Updates +- [ ] More Models or Datasets Support -- 恢复后保留完整 GRPO 组; -- group 从准入到训练固定 behavior policy 和 adapter; -- 禁止旧组用新 policy 补采成员; -- batch lease 与训练 checkpoint 建立可验证关联; -- 工具副作用无法证明幂等时 fail closed。 +# PR information -## 核心改动 +## 背景 -- 新增 hash-chain JSONL journal、对象 SHA-256 校验和原子写入。 -- `DurableJournal` 增加线程锁、跨进程文件锁和写入失败回滚,避免并发 writer - 分叉 hash chain。 -- `StreamingDriver` 保存 prompt、未完成组、ready 组、DataLoader state 与 batch lease。 -- group 固定 `policy_version + adapter_path`;恢复、no-slot retry 和成员补采沿用同一绑定。 -- ready group 超 staleness 时整组淘汰,禁止混入新策略。 -- `commit_batch(checkpoint_ref, manifest)` 记录训练 checkpoint、batch 和 policy versions; - 空 checkpoint reference 被拒绝。 -- `ClientCheckpointManager` 保留历史 adapter path;episode 每次采样显式使用绑定路径。 -- `MultiTurnRollout` 保存/恢复 token 真值、tool loop 状态和 LocalEnv workspace。 -- 工具 effect 使用 intent/result 边界;无法确认结果时拒绝不安全恢复。 +异步 GRPO 进程重启后,如果只恢复“已经生成了多少条轨迹”,仍会破坏训练语义: -核心生产代码新增约 1100 行,低于 2000 行预算。 +- 一个 GRPO 组可能在旧 policy 和新 policy 下各补采一部分成员; +- ready 组可能在权重同步后使用错误 adapter 再次采样; +- batch 已经交出,但 optimizer checkpoint 是否持久化无法判断; +- 非幂等工具已经产生副作用,重启后又执行一次; +- 环境 session 丢失后,文本继续但 workspace 或工具状态已经不一致。 -## 验证结果 +本 PR 将 `StreamingDriver` 的暂停/恢复升级为 Group-Atomic Durable GRPO。核心边界是 +完整组、behavior policy、batch lease 和训练 checkpoint 必须一起提交或一起回退。 -### 1. 聚焦回归 +本 PR 不修改 GRPO loss、advantage 标准化和 sampler 生成算法。 -- 本地:`33 passed` -- A2 Python 3.10:`33 passed` +## 主要改动 -新增边界覆盖: +### 1. 显式 GroupPolicyBinding -1. 无故障等价与 journal/object 开销; -2. 真实 torch optimizer checkpoint 事务; -3. Linux `SIGKILL` 五阶段恢复; -4. exactly-once lease/commit; -5. journal 截断、损坏、SHA 错误、ENOSPC、rename 中断和并发 writer; -6. Env 无恢复能力时 fail closed; -7. 非幂等工具不重复执行; -8. adapter 缺失、路径复用和 staleness 淘汰。 +新增与 Trainer、Sampler 解耦的策略绑定: + +```python +GroupPolicyBinding( + state_key="run/group/17", + policy_version=4, + adapter_path="/checkpoints/policy-4", +) +``` + +每个组在准入时固定这三项。恢复、no-slot retry、成员补采和组替换都必须沿用原 +binding,禁止旧组用新 policy 补齐。 + +driver 快照同时写入结构化 `binding` 和旧版 `version/adapter_path` 字段: + +- 旧快照可自动升级; +- 两份字段不一致时 fail closed; +- 空 `state_key`、负版本和空 adapter path 被拒绝。 + +### 2. 自动稳定边界持久化 + +启用 `resume_store` 后,`StreamingDriver` 自动在以下边界保存快照: + +1. prompt 分配并完成成员提交; +2. 完整组进入 ready 队列; +3. batch lease 写入; +4. checkpoint commit 后清 lease; +5. 组淘汰。 + +调用方不再需要在故障前手工调用 `state_dict()`。恢复直接使用: + +```python +driver.load_state_dict() +``` + +自动快照的写入顺序与 journal 事件配对: + +- lease 先进入 driver 快照,再写 `BATCH_LEASED`; +- group ready 先进入 driver 快照,再写 `GROUP_READY`; +- `MODEL_CHECKPOINT_COMMITTED` 是 commit 的事务点,恢复时用它退休旧 lease。 + +### 3. Batch lease 与训练 checkpoint 关联 + +新增: + +```python +driver.commit_batch(checkpoint_ref, manifest) +``` + +训练侧只有在 adapter、optimizer、scheduler 和 RNG state 完整持久化后才能调用。 +未提交前崩溃:恢复上一 checkpoint,并重交付同一 batch lease;已提交后崩溃: +恢复新 checkpoint,不再交付同一 lease。 + +### 4. ResumableEnv 独立协议 + +Env 恢复能力作为独立 `ResumableEnv` protocol 提供,不向所有 `Env` 实现增加空方法: + +```python +EnvResumeCapability.NONE +EnvResumeCapability.LIVE_ATTACH +EnvResumeCapability.DURABLE_CHECKPOINT +``` + +`LocalEnv` 显式实现 durable checkpoint。`AgentEnv`、`OpenEnv` 和 `OpenEnvClient` +默认无恢复能力;episode 已打开但环境不能恢复时拒绝静默继续。 -### 2. 真实 Qwen + NPU checkpoint 强杀 +### 5. 工具副作用与环境状态 -A2 Ascend 910B4、Qwen3-0.6B、LoRA rank 8、BF16、官方 GSM8K: +- 工具调用使用 `TOOL_INTENT -> episode checkpoint -> TOOL_RESULT`; +- pending intent 没有可证明的结果时拒绝恢复; +- 已 checkpoint 的 effect 直接复用 observation,不再次执行外部副作用; +- `MultiTurnRollout` 保存 token、labels、mask、old logprob、tool loop 和 LocalEnv + workspace; +- 无法 checkpoint 的 harness 和 message-ledger episode fail closed。 -| 强杀边界 | 进程返回码 | 恢复结果 | -|---|---:|---| -| optimizer step 后、adapter 保存前 | `-9` | 恢复 `step-0`,同一 lease 重交付 2 行 | -| 临时 adapter/optimizer 保存后 | `-9` | 临时 checkpoint 不生效,恢复 `step-0` | -| checkpoint 原子发布后、journal commit 前 | `-9` | 已发布 checkpoint 不生效,恢复 `step-0` | -| journal commit 后 | `-9` | 恢复 `step-1`,optimizer step `[1]`,不再交付 | +### 6. Journal 与对象存储 -四个场景的 LoRA 权重 digest 和 optimizer state 均通过恢复校验。未提交更新不会泄漏, -已提交 batch 不会重复训练。 +`DurableJournal` 使用 hash-chain JSONL,支持: -### 3. A2 Qwen 真实采样进程恢复 +- 最后一行截断修复; +- 中间记录损坏拒绝; +- 跨线程和跨进程 writer 锁; +- append/fsync 失败回滚; +- object SHA-256 校验和原子 rename。 -- 24 个已采样 token 逐值保留; -- token/labels/mask/old logprob 不重新编码; -- 恢复后继续采样 16 token,logprob 有限; -- LocalEnv 恢复后读到 `turn-1-durable`。 +## 兼容性 -### 4. 无故障等价与开销 +- `resume_store=None`:保持原有内存 streaming 行为; +- 所有 durable 能力必须显式传入 store; +- 旧 `version + adapter_path` 快照继续可读; +- `twinkle_agentic.envs.base` 的旧导入路径保持兼容; +- 无 checkpoint manager 时仍可保存组和 lease,但不执行 policy 版本淘汰; +- 新 `ResumableEnv` 推荐从 `twinkle_agentic.envs.resume` 导入。 + +核心生产代码新增量保持在 2000 行以内。 + +# Experiment results + +## 实验设置 + +| 项目 | 配置 | +|---|---| +| 硬件 | A2,单张 Ascend 910B4,32768 MB HBM | +| Python | 3.10.12 | +| torch / torch_npu | 2.10.0+cpu / 2.10.0 | +| 模型 | Qwen3-0.6B | +| 训练 | LoRA rank 8,BF16,真实 optimizer step | +| 数据 | 官方 GSM8K | +| 故障 | Linux `SIGKILL`、组丢失、journal/object 故障注入 | + +## 1. 真实 Qwen + NPU checkpoint 强杀 + +本轮强杀探针不调用 `driver.state_dict()`,只依赖 driver 自动持久化。 + +| 强杀边界 | 返回码 | 恢复 checkpoint | 同 lease 重交付 | optimizer step | +|---|---:|---|---:|---:| +| optimizer step 后、adapter 保存前 | `-9` | `step-0` | 2 行 | `[]` | +| 临时 adapter/optimizer 保存后 | `-9` | `step-0` | 2 行 | `[]` | +| checkpoint 原子发布后、commit 前 | `-9` | `step-0` | 2 行 | `[]` | +| journal commit 后 | `-9` | `step-1` | 否 | `[1]` | + +四个场景均通过 LoRA digest 和 optimizer state 校验。未提交 optimizer 更新不泄漏; +已提交 batch 不重复训练。 + +证据: + +- `review/a2/NPU_CHECKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md` +- `review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json` + +## 2. 聚焦回归 + +- 本地:`45 passed` +- A2 Python 3.10:`45 passed` + +覆盖范围: + +1. 不手工 `state_dict()` 时恢复 prompt、ready group、lease 和 commit; +2. 旧扁平快照升级为 GroupPolicyBinding; +3. binding 冲突、空 ID、负版本和空 adapter path 拒绝; +4. 无故障 baseline/durable 等价; +5. journal 截断、损坏、SHA 错误、ENOSPC、rename 中断和并发 writer; +6. 真实 optimizer checkpoint 事务; +7. Env 无恢复能力时 fail closed; +8. 非幂等工具不重复执行; +9. adapter 缺失、路径复用和 staleness 整组淘汰。 + +## 3. 无故障等价与开销 确定性无故障控制: @@ -82,12 +191,9 @@ A2 本地文件系统开销: | object save | `0.55 ms/object` | | 存储放大 | `1.0326x` | -4 个独立进程并发写 200 条 journal,sequence 连续且 hash chain 有效。 - -### 5. GSM8K 故障恢复训练 A/B +## 4. GSM8K 故障恢复训练 A/B 对照为“故障点丢弃整个 ready group”与“durable 保留同一 policy 的完整组”。 -使用官方 GSM8K、Qwen3-0.6B、LoRA、单卡 910B4。 25% 故障率下最终质量收益不稳定,因此不作为主要结论。 @@ -117,44 +223,54 @@ A2 本地文件系统开销: 两个独立确认种子在未参与调参的测试切分上分别取得 `+2.34375pp`,方向一致。 +## Cookbook 与文档 + +- `cookbook/rl/async_rl/durable_multi_turn_grpo.py` +- `cookbook/rl/async_rl/durable_multi_turn_grpo.sh` +- `docs/source_zh/组件/Agentic/DurableRolloutResume.md` + +Cookbook 使用官方 GSM8K、真实多轮 rollout、LoRA、GRPO backward/step、 +optimizer checkpoint 和 `commit_batch()`,启动时会从 journal 最后一个有效 checkpoint +恢复模型。 + ## 结论边界 已经证明: -- 真实 Qwen/NPU 训练进程强杀后,模型 checkpoint、optimizer、lease 和 journal - 保持提交/回退一致; -- 不提交的 optimizer step 不会泄漏,已提交 batch 不会重复训练; +- 真实 Qwen/NPU 强杀后,模型 checkpoint、optimizer、lease 和 journal 保持一致; +- 自动快照不依赖人工 `state_dict()`; +- 未提交 optimizer step 不泄漏,已提交 batch 不重复训练; - 无故障路径质量等价; -- 50% 组丢失故障下,durable 机制显著提高固定预算下的有效训练组和 GSM8K 指标。 +- 50% 组丢失故障下,固定预算训练收益显著提高。 尚未证明: -- GSM8K A/B 使用独立训练脚本模拟“组被丢弃/被保留”,尚未把完整故障注入接到 - 真实 Twinkle training cookbook 的 `StreamingDriver + commit_batch`; -- 尚未完成可写 NFS/对象存储下的 lease/journal/adapter 故障矩阵; -- 尚未完成多卡 HCCL/FSDP2 和更大模型验证; -- agent-program harness 及无法 checkpoint 的远端正环境继续 fail closed。 +- 可写 NFS 或对象存储上的 lease、journal 和 adapter 故障矩阵; +- 多卡 HCCL/FSDP2 和更大模型; +- 所有远端正环境都具备 checkpoint 能力; +- 所有外部工具协议都能查询幂等结果。 -因此本 PR 当前结论限定为“故障条件下保留完整 GRPO 组、维持事务一致性并改善 -固定预算训练收益”,不宣称所有故障率或生产存储下均无条件提升。 +因此本 PR 结论限定为“完整组丢失或进程重启时保持 GRPO 语义、事务一致性和固定预算 +有效训练量”,不宣称所有故障率或生产存储下无条件提升。 ## 复现与证据 - `review/a2/BOUNDARY_TEST_RESULTS_20261119.md` - `review/a2/GSM8K_AB_20261118.md` -- `review/a2/NPU_CHECKPOINT_KILL_RESULTS_20261119.md` -- `review/a2/npu-checkpoint-kill-evidence-20261119/` +- `review/a2/NPU_CHECKPOINT_KILL_AUTOMATIC_RESULTS_20261119.md` +- `review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/` - `review/a2/run_npu_checkpoint_kill_probe.py` - `review/a2/run_grpo_reward_ab.py` - `review/a2/run_checkpoint_transaction_probe.py` - `review/a2/run_kill_phase_probe.py` - `review/a2/run_resume_overhead_bench.py` -完整 A2 结果位于本地验证目录,不包含权重和 optimizer 二进制。 +完整 A2 权重和 `.resume` 二进制保留在验证机,不进入 Git。 ## 希望 maintainer 确认 -1. 是否接受 group 级固定 `state_key + policy_version + adapter_path`。 +1. 是否接受 group 级 `GroupPolicyBinding(state_key, policy_version, adapter_path)` + 作为恢复和补采的固定行为策略边界。 2. 是否接受 `commit_batch(checkpoint_ref, manifest)` 作为训练 checkpoint 与 rollout - lease 的关联接口。 -3. 是否将 Env 恢复能力作为现有 `Env` 扩展点,还是拆成独立 `ResumableEnv` protocol。 + lease 的原子关联接口。 +3. 当前采用独立 `ResumableEnv` protocol;是否认可它作为现有 `Env` 的可选恢复扩展点。 diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/README.md b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/README.md new file mode 100644 index 000000000..3913bb471 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/README.md @@ -0,0 +1,16 @@ +# 自动持久化 NPU 强杀证据 + +本目录只保存不含模型权重的验证证据。完整运行日志位于 A2 验证目录,被仓库的 +`*.log` 规则排除。 + +四个场景均由真实 Qwen3-0.6B、LoRA、Ascend 910B4 和 `SIGKILL` 产生: + +| 场景 | 返回码 | lease 重交付 | optimizer step | +|---|---:|---:|---:| +| optimizer step 后、保存前 | `-9` | 是 | `[]` | +| 临时 checkpoint 保存后 | `-9` | 是 | `[]` | +| checkpoint 发布后、commit 前 | `-9` | 是 | `[]` | +| commit 后 | `-9` | 否 | `[1]` | + +`report.json` 聚合四个场景;每个场景目录下的 `ready.json` 和 `verify.json` +分别记录强杀前事务状态与重启后的 LoRA/optimizer 校验。 diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json new file mode 100644 index 000000000..1d8433f26 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json @@ -0,0 +1,103 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "bdbdfaad7b1cebf05f96132e76742631f3f63cc4e2d6ead72576989435dcc9d9", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", + "step": 1 + }, + "case": "adapter_temp_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "79c39d048a16be1d07cbec97e040b6604fff6b96835ded8aa913426a33be2a23", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077255.8905628, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json new file mode 100644 index 000000000..79de1ce4e --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json @@ -0,0 +1,29 @@ +{ + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "adapter_temp_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "final_absent": true, + "pending_exists": true, + "pending_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json new file mode 100644 index 000000000..79bd78cc7 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json @@ -0,0 +1,105 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", + "promoted_checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_committed", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "60b7fa29642a7a3c44e16344a2436fa460c8a9d7c2a49f3e8fa60f259dbdea39", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077323.612138, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json new file mode 100644 index 000000000..1655ee4dd --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json @@ -0,0 +1,29 @@ +{ + "actual_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "actual_optimizer_steps": [ + 1 + ], + "case": "checkpoint_committed", + "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "committed": true, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "expected_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "expected_optimizer_steps": [ + 1 + ], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": false, + "redelivered_rows": 0, + "restored_lease": null +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json new file mode 100644 index 000000000..2496f10e8 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json @@ -0,0 +1,105 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", + "promoted_checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_promoted_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077289.5118372, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json new file mode 100644 index 000000000..e8e11d9f9 --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json @@ -0,0 +1,29 @@ +{ + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "checkpoint_promoted_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "journal_left_it_uncommitted": true, + "promoted_exists": true, + "promoted_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json new file mode 100644 index 000000000..fa89f546e --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json @@ -0,0 +1,93 @@ +{ + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": null, + "case": "optimizer_step_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077221.5744615, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/.step-1.tmp.24343", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json new file mode 100644 index 000000000..5600e7a1b --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json @@ -0,0 +1,25 @@ +{ + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "optimizer_step_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" +} diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json new file mode 100644 index 000000000..fc030ea7d --- /dev/null +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json @@ -0,0 +1,565 @@ +{ + "cases": [ + { + "case": "optimizer_step_uncommitted", + "elapsed_s": 33.072556257247925, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": null, + "case": "optimizer_step_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077221.5744615, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/.step-1.tmp.24343", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "optimizer_step_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + }, + { + "case": "adapter_temp_uncommitted", + "elapsed_s": 34.285804748535156, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "bdbdfaad7b1cebf05f96132e76742631f3f63cc4e2d6ead72576989435dcc9d9", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", + "step": 1 + }, + "case": "adapter_temp_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "79c39d048a16be1d07cbec97e040b6604fff6b96835ded8aa913426a33be2a23", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077255.8905628, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "adapter_temp_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "final_absent": true, + "pending_exists": true, + "pending_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + }, + { + "case": "checkpoint_promoted_uncommitted", + "elapsed_s": 33.72851920127869, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", + "promoted_checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_promoted_uncommitted", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077289.5118372, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "actual_optimizer_steps": [], + "case": "checkpoint_promoted_uncommitted", + "commit_checkpoint": null, + "committed": false, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "expected_optimizer_steps": [], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": { + "journal_left_it_uncommitted": true, + "promoted_exists": true, + "promoted_matches_trained": true + }, + "redelivered_batch": true, + "redelivered_rows": 2, + "restored_lease": "npu-checkpoint-kill/batch/0" + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + }, + { + "case": "checkpoint_committed", + "elapsed_s": 33.86141848564148, + "marker": { + "batch_facts": { + "episode_ids": [ + "npu-checkpoint-kill:g0:a0:member:0", + "npu-checkpoint-kill:g0:a0:member:1" + ], + "num_rows": 2, + "num_truncated": 0, + "policy_versions": [ + 0 + ], + "prompt_lengths": [ + 1, + 1 + ], + "response_length_max": 1, + "response_length_min": 1, + "response_length_sum": 2, + "response_lengths": [ + 1, + 1 + ], + "scores": [ + { + "rewards": { + "orm": {} + } + }, + { + "rewards": { + "orm": {} + } + } + ], + "truncated": [ + false, + false + ], + "turns": [ + 1, + 1 + ], + "version_spans": [ + 0, + 0 + ] + }, + "batch_rows": 2, + "candidate_checkpoint": { + "checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [ + 1 + ], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", + "promoted_checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "step": 1 + }, + "case": "checkpoint_committed", + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "driver_handed": 1, + "driver_persistence": "automatic", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "format": "twinkle.npu-checkpoint-kill-marker.v1", + "initial_checkpoint": { + "checkpoint_digest": "60b7fa29642a7a3c44e16344a2436fa460c8a9d7c2a49f3e8fa60f259dbdea39", + "format": "twinkle.npu-checkpoint-kill.v1", + "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "optimizer_steps": [], + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-0", + "step": 0 + }, + "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", + "lease_id": "npu-checkpoint-kill/batch/0", + "marker_created_unix": 1795077323.612138, + "optimizer_loss": 5.960464477539063e-08, + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed", + "run_id": "npu-checkpoint-kill", + "seed": 20261119, + "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "trained_optimizer_steps": [ + 1 + ], + "trajectory": { + "accuracy": 0.5, + "correct": "The final answer is \\boxed{72}.", + "format": 1.0, + "reward": 0.7, + "wrong": "The final answer is \\boxed{0}." + } + }, + "ok": true, + "verification": { + "actual_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "actual_optimizer_steps": [ + 1 + ], + "case": "checkpoint_committed", + "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "committed": true, + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "device": "npu:0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "expected_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", + "expected_optimizer_steps": [ + 1 + ], + "format": "twinkle.npu-checkpoint-kill-verify.v1", + "ok": true, + "orphan_check": null, + "redelivered_batch": false, + "redelivered_rows": 0, + "restored_lease": null + }, + "worker_killed_by_sigkill": true, + "worker_returncode": -9 + } + ], + "container": { + "hostname": "e1f3eeac3fc6", + "peft": "0.21.3", + "python": "3.10.12 (main, Aug 31 2026, 10:18:17) [GCC 11.4.0]", + "torch": "2.10.0+cpu", + "torch_npu": "2.10.0", + "transformers": "5.20.2" + }, + "finished_unix": 1795077342.160995, + "format": "twinkle.npu-checkpoint-kill-report.v1", + "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", + "ok": true, + "seed": 20261119, + "started_unix": 1795077207.204393, + "train_jsonl": "data/gsm8k/train.jsonl" +} diff --git a/review/a2/run_focused_tests.py b/review/a2/run_focused_tests.py index 11ddeb5f8..e1c72080c 100644 --- a/review/a2/run_focused_tests.py +++ b/review/a2/run_focused_tests.py @@ -28,6 +28,7 @@ "tests/twinkle_agentic/test_localenv_resume.py", "tests/twinkle_agentic/test_turn_ledger_resume.py", "tests/twinkle_agentic/test_multi_turn_resume.py", + "tests/twinkle_agentic/test_group_policy_binding.py", "tests/twinkle_agentic/test_streaming_driver_resume.py", "tests/twinkle_agentic/test_resume_boundaries.py", "tests/twinkle_agentic/test_tail_prefetch.py", diff --git a/review/a2/run_npu_checkpoint_kill_probe.py b/review/a2/run_npu_checkpoint_kill_probe.py index 6565c5008..031894b64 100644 --- a/review/a2/run_npu_checkpoint_kill_probe.py +++ b/review/a2/run_npu_checkpoint_kill_probe.py @@ -8,7 +8,6 @@ import argparse import hashlib import importlib.metadata -import io import json import os import platform @@ -18,7 +17,6 @@ import sys import time import traceback -from collections.abc import Mapping from pathlib import Path from typing import Any @@ -385,7 +383,10 @@ def _worker(case: str, root: Path, model_path: str, train_jsonl: str, seed: int) if committed_lease != lease_id: raise AssertionError(f"commit returned {committed_lease!r}, expected {lease_id!r}") - state = driver.state_dict() + # Do not take a manual snapshot here. The probe is meant to prove that + # StreamingDriver persists its own stable boundaries; an explicit + # state_dict() would hide a missing automatic write. + stats = driver.stats() marker = { "format": "twinkle.npu-checkpoint-kill-marker.v1", "case": case, @@ -405,7 +406,8 @@ def _worker(case: str, root: Path, model_path: str, train_jsonl: str, seed: int) "trained_optimizer_steps": trained_steps, "optimizer_loss": trained["loss"], "driver_state_path": str(store.root / "objects" / "driver"), - "driver_handed": state["handed"], + "driver_handed": stats["handed"], + "driver_persistence": "automatic", "trajectory": trajectory, "container": _container_info(), "marker_created_unix": time.time(), diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 90e5da6de..50a91d8a6 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -88,6 +88,52 @@ class JournalEvent(str, Enum): MODEL_CHECKPOINT_COMMITTED = "MODEL_CHECKPOINT_COMMITTED" +@dataclass(frozen=True) +class GroupPolicyBinding: + """The behavior policy fixed for one complete GRPO group. + + ``state_key`` is the group's logical identity across processes. The + policy version and adapter path travel with it so recovery, regeneration, + and replacement members cannot silently switch to a newer policy. + """ + + state_key: str + policy_version: int + adapter_path: str | None = None + + def __post_init__(self) -> None: + if not isinstance(self.state_key, str) or not self.state_key.strip(): + raise ValueError("group state_key must not be empty") + if isinstance(self.policy_version, bool) or not isinstance(self.policy_version, int): + raise ValueError("group policy_version must be an integer") + if self.policy_version < 0: + raise ValueError("group policy_version must be >= 0") + if self.adapter_path is not None and ( + not isinstance(self.adapter_path, str) or not self.adapter_path.strip() + ): + raise ValueError("group adapter_path must be a non-empty string when provided") + + def to_dict(self) -> dict[str, Any]: + return { + "state_key": self.state_key, + "policy_version": self.policy_version, + "adapter_path": self.adapter_path, + } + + @classmethod + def from_dict(cls, value: dict[str, Any]) -> GroupPolicyBinding: + if not isinstance(value, dict): + raise ValueError("group policy binding must be a mapping") + raw_version = value.get("policy_version") + if isinstance(raw_version, bool): + raise ValueError("group policy_version must be an integer") + return cls( + state_key=str(value.get("state_key") or ""), + policy_version=int(raw_version), + adapter_path=value.get("adapter_path"), + ) + + @dataclass(frozen=True) class JournalRecord: seq: int diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 99ecd1037..4001f751d 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -22,7 +22,6 @@ with the number of episodes in flight. """ from __future__ import annotations - import copy import math import queue @@ -37,7 +36,7 @@ from twinkle import remote_class, remote_function from twinkle.data_format import user_data_get from twinkle.utils import get_logger -from twinkle_agentic.async_rl.rollout_resume import JournalEvent, ResumeStore, UnsafeResume +from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding, JournalEvent, ResumeStore, UnsafeResume from twinkle_agentic.rollout.multi_turn import EpisodeError, RolloutStatus logger = get_logger() @@ -60,8 +59,9 @@ def _record_driver_probe(event: str, episode_id: str = '', **fields: Any) -> Non that drains the queue is still turning. Without it the two possible causes -- a future that never resolves and a queue that is never drained -- are indistinguishable from outside. """ - import json import os + + import json root = os.environ.get('TWINKLE_DRIVER_PROBE') if not root: return @@ -130,8 +130,7 @@ class _Group: row: Any #: Fixed for the group's whole lifetime. Recovery and replacement members must use this #: behavior policy, never whichever version happens to be current after a restart. - version: int = 0 - adapter_path: Optional[str] = None + binding: GroupPolicyBinding attempt: int = 0 #: The current attempt's member trajectories, aligned with ``members`` (a lost one is redone from here). source: List[Any] = field(default_factory=list) @@ -140,6 +139,18 @@ class _Group: #: Members of the current attempt that will not produce a sample (failed, stopped, dropped). missing: int = 0 + @property + def state_key(self) -> str: + return self.binding.state_key + + @property + def version(self) -> int: + return self.binding.policy_version + + @property + def adapter_path(self) -> Optional[str]: + return self.binding.adapter_path + @dataclass class _Episode: @@ -308,7 +319,7 @@ def __init__(self, self.max_no_slot_wait = max_no_slot_wait self._lock = threading.Condition() - self._events: 'queue.Queue[Tuple[Any, ...]]' = queue.Queue() + self._events: 'queue.Queue[tuple[Any, ...]]' = queue.Queue() self._ready: deque = deque() self._ready_rows = 0 self._thread: Optional[threading.Thread] = None @@ -477,7 +488,7 @@ def _next_batch(self) -> Optional[tuple]: replace(episode.sample, token_lengths=tuple(map(int, pair)), extra=dict(extra, segment_index=index)) for index, pair in enumerate(lengths)] - for row, row_sample in zip(episode.deliver, row_samples): + for row, row_sample in zip(episode.deliver, row_samples, strict=True): trajs.append(row) samples.append(row_sample) scores.append(score) @@ -494,12 +505,16 @@ def _next_batch(self) -> Optional[tuple]: 'facts': facts, } self._lease_returned = True + self._handed += 1 if self.resume_store is not None: self.resume_store.save_object('leases', lease_id, self._lease) + # The snapshot must point at the lease before the journal makes + # it durable. A crash in between re-delivers this same lease; + # the reverse order could strand the lease object unreferenced. + self._persist_snapshot_locked() self.resume_store.journal.append( JournalEvent.BATCH_LEASED, lease_id, {'batch': batch_index, 'rows': len(trajs), 'object': lease_id}) - self._handed += 1 self._lock.notify_all() self._returned_at = time.monotonic() self._wait_time = self._returned_at - started @@ -519,7 +534,7 @@ def _score_update(self, episode: _Episode) -> Dict[str, Any]: sample = episode.sample rewards: Dict[str, Any] = { 'orm': {name: (None if value is None else float(value)) - for name, value in zip(self.orm_names, episode.orm or ())}, + for name, value in zip(self.orm_names, episode.orm or (), strict=True)}, } if sample.baseline is not None: rows = sample.baseline if (sample.baseline and isinstance(sample.baseline[0], (list, tuple))) \ @@ -528,13 +543,13 @@ def _score_update(self, episode: _Episode) -> Dict[str, Any]: raise RuntimeError(f'episode {episode.episode_id} carries {len(rows)} baseline rows; the named ' 'baseline column carries one. Return a single baseline per group.') rewards['baseline'] = {name: (None if value is None else float(value)) - for name, value in zip(self.orm_names, rows[0])} + for name, value in zip(self.orm_names, rows[0], strict=True)} score: Dict[str, Any] = {'rewards': rewards} if episode.prm is not None: score['prm_segments'] = { 'end_turns': [int(turns) for turns in episode.prm_turns], 'scores': {name: [(None if value is None else float(value)) for value in column] - for name, column in zip(self.prm_names, episode.prm)}, + for name, column in zip(self.prm_names, episode.prm, strict=True)}, } return score @@ -564,10 +579,10 @@ def _retire_stale_group(self, group: _Group) -> None: self._counters['dropped_stale'] += len(group.members) self._counters['dropped_group'] += 1 if self.resume_store is not None: - state_key = f'{self.run_id}/group/{group.key}' self.resume_store.journal.append( - JournalEvent.GROUP_DROPPED, state_key, - {'reason': 'stale', 'version': group.version, 'current_version': self._version}) + JournalEvent.GROUP_DROPPED, group.state_key, + {'reason': 'stale', 'binding': group.binding.to_dict(), 'current_version': self._version}) + self._persist_snapshot_locked() for episode in group.members + group.baselines: if episode.lost: continue @@ -619,6 +634,8 @@ def _group_state(self, group: _Group) -> Dict[str, Any]: return { 'key': group.key, 'row': group.row, + 'binding': group.binding.to_dict(), + # Flat fields keep snapshots readable by earlier draft readers. 'version': group.version, 'adapter_path': group.adapter_path, 'attempt': group.attempt, @@ -645,6 +662,17 @@ def _snapshot(self) -> Dict[str, Any]: 'lease': self._lease, } + def _persist_snapshot_locked(self) -> None: + """Persist the current snapshot at a stable transition while holding ``_lock``. + + Callers order this write before the matching journal event where a stale + snapshot would otherwise lose an in-memory object. Checkpoint commit is + the exception: its journal record is the transaction point, and restore + uses it to retire a lease even when the following snapshot was torn. + """ + if self.resume_store is not None: + self.resume_store.save_object('driver', self.run_id, self._snapshot()) + @remote_function(execute='first', collect='first', lazy_collect=False) def state_dict(self) -> Dict[str, Any]: """Snapshot prompts, complete groups, ready groups and the open batch lease. @@ -691,14 +719,42 @@ def _restore_group(self, state: Dict[str, Any]) -> _Group: (int(item.get('version') or 0) for item in members if item.get('version') is not None), 0) version = int(state.get('version') if state.get('version') is not None else member_version) adapter_path = state.get('adapter_path') - if adapter_path is None and self.checkpoint_manager is not None: + raw_binding = state.get('binding') + if raw_binding is not None: + try: + binding = GroupPolicyBinding.from_dict(raw_binding) + except (TypeError, ValueError) as exc: + raise UnsafeResume(f'invalid group policy binding: {exc}') from exc + if state.get('version') is not None and int(state['version']) != binding.policy_version: + raise UnsafeResume( + f'group binding version {binding.policy_version} disagrees with snapshot version ' + f'{state["version"]}') + if 'adapter_path' in state and state.get('adapter_path') != binding.adapter_path: + raise UnsafeResume('group binding adapter_path disagrees with the flat snapshot field') + version = binding.policy_version + adapter_path = binding.adapter_path + else: + binding = GroupPolicyBinding( + state_key=str(state.get('state_key') or f'{self.run_id}/group/{state.get("key")}'), + policy_version=version, + adapter_path=adapter_path, + ) + expected_state_key = f'{self.run_id}/group/{state.get("key")}' + if binding.state_key != expected_state_key: + raise UnsafeResume( + f'group binding state_key {binding.state_key!r} does not match {expected_state_key!r}') + # A legacy flat snapshot had no binding, so the manager may upgrade its + # missing adapter path. An explicit binding with adapter_path=None + # means the base model and must not be silently rebound to an adapter. + if raw_binding is None and adapter_path is None and self.checkpoint_manager is not None: lookup = getattr(self.checkpoint_manager, 'adapter_path', None) if callable(lookup): adapter_path = lookup(version) if adapter_path is None: raise UnsafeResume(f'policy version {version} has no resolvable adapter path') + binding = replace(binding, adapter_path=adapter_path) group = _Group( - key=str(state['key']), row=state.get('row'), version=version, adapter_path=adapter_path, + key=str(state['key']), row=state.get('row'), binding=binding, attempt=int(state.get('attempt') or 0), source=list(state.get('source') or ()), missing=int(state.get('missing') or 0)) group.members = [self._restore_episode(item, group) for item in state.get('members') or ()] @@ -831,6 +887,7 @@ def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, An self.resume_store.delete_object('leases', lease_id) self._lease = None self._lease_returned = False + self._persist_snapshot_locked() self._lock.notify_all() return lease_id @@ -979,14 +1036,21 @@ def _admit(self) -> None: if adapter_path is None: raise UnsafeResume( f'checkpoint manager has no adapter path for admitted policy version {version}') - group = _Group(key=key, row=row, version=version, adapter_path=adapter_path) + binding = GroupPolicyBinding( + state_key=f'{self.run_id}/group/{key}', + policy_version=version, + adapter_path=adapter_path, + ) + group = _Group(key=key, row=row, binding=binding) self._groups[key] = group + self._start_attempt(group, [copy.deepcopy(row) for _ in range(self.num_generations)]) if self.resume_store is not None: prompt_key = f'{self.run_id}/prompt/{key}' self.resume_store.save_object('prompts', prompt_key, row) + self._persist_snapshot_locked() self.resume_store.journal.append( - JournalEvent.PROMPT_ASSIGNED, prompt_key, {'group_key': key, 'object': prompt_key}) - self._start_attempt(group, [copy.deepcopy(row) for _ in range(self.num_generations)]) + JournalEvent.PROMPT_ASSIGNED, prompt_key, + {'group_key': key, 'object': prompt_key, 'binding': binding.to_dict()}) def _next_row(self) -> Any: # TODO: rows are drawn here, ahead of training; see state_dict for what a resume skips. @@ -1301,11 +1365,10 @@ def _accept(self, group: _Group) -> None: self._ready.append(list(group.members)) self._ready_rows += sum(len(episode.deliver) for episode in group.members) if self.resume_store is not None: - state_key = f'{self.run_id}/group/{group.key}' - self.resume_store.journal.append(JournalEvent.GROUP_READY, state_key, { + self._persist_snapshot_locked() + self.resume_store.journal.append(JournalEvent.GROUP_READY, group.state_key, { 'group_key': group.key, - 'policy_version': group.version, - 'adapter_path': group.adapter_path, + 'binding': group.binding.to_dict(), 'attempt': group.attempt, 'episodes': [episode.episode_id for episode in group.members], }) @@ -1327,6 +1390,12 @@ def _drop_group(self, group: _Group) -> None: if episode.held is not None: # waiting for its PRM scores, no step in flight; a stepping one is stopped when it returns self.rollout.stop(episode.traj, episode_id=episode.episode_id) + if self.resume_store is not None: + self.resume_store.journal.append( + JournalEvent.GROUP_DROPPED, group.state_key, + {'reason': 'incomplete_or_invalid', 'binding': group.binding.to_dict(), + 'current_version': self._version}) + self._persist_snapshot_locked() #: Placeholder for a score whose Future has not completed yet. diff --git a/src/twinkle_agentic/envs/__init__.py b/src/twinkle_agentic/envs/__init__.py index c10cb045a..518974bec 100644 --- a/src/twinkle_agentic/envs/__init__.py +++ b/src/twinkle_agentic/envs/__init__.py @@ -1,12 +1,13 @@ # Copyright (c) ModelScope Contributors. All rights reserved. from .agentenv import AgentEnv, AgentSandbox -from .base import (Env, EnvResumeCapability, NoSlot, SessionNotFound, StepResult, UnsafeCheckpoint, - UnsupportedEnvResume) +from .base import Env, NoSlot, SessionNotFound, StepResult from .env_tool import EnvTool from .localenv import LocalEnv from .openenv import ClientSession, OpenEnv, OpenEnvClient +from .resume import EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, env_resume_capability __all__ = [ 'AgentEnv', 'AgentSandbox', 'ClientSession', 'Env', 'EnvTool', 'LocalEnv', 'NoSlot', 'OpenEnv', 'OpenEnvClient', - 'EnvResumeCapability', 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', 'UnsupportedEnvResume' + 'EnvResumeCapability', 'ResumableEnv', 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', + 'UnsupportedEnvResume', 'env_resume_capability' ] diff --git a/src/twinkle_agentic/envs/base.py b/src/twinkle_agentic/envs/base.py index a08c804f3..2223d492f 100644 --- a/src/twinkle_agentic/envs/base.py +++ b/src/twinkle_agentic/envs/base.py @@ -3,13 +3,14 @@ import time from abc import ABC, abstractmethod from dataclasses import dataclass, field -from enum import Enum from typing import Any, Dict, List, Optional, Sequence, Tuple from twinkle import remote_function from twinkle.data_format import Trajectory from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger +from .resume import (EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, + env_resume_capability) from .snapshot import list_workspace logger = get_logger() @@ -137,22 +138,6 @@ class NoSlot: """ -class EnvResumeCapability(str, Enum): - """How an environment can survive a different Twinkle process.""" - - NONE = 'none' - LIVE_ATTACH = 'live_attach' - DURABLE_CHECKPOINT = 'durable_checkpoint' - - -class UnsupportedEnvResume(NotImplementedError): - """The environment has no safe way to resume this episode.""" - - -class UnsafeCheckpoint(RuntimeError): - """The episode is not at a point where its workspace can be captured.""" - - class _Session: __slots__ = ('state', 'reward', 'touched', 'script_inflight') @@ -191,10 +176,6 @@ class Env(ABC): ``_close(state)`` and ``_workspace(state)``; plus :meth:`tools`. """ - #: Environments default to no recovery. A backend opts in explicitly and - #: the rollout refuses to mutate or retry an episode when this is NONE. - resume_capability = EnvResumeCapability.NONE - #: What :meth:`snapshot` shows of the workspace: how many files to name, how #: many bytes of each body, how many bytes of bodies in total, and which #: directories not to walk into. Class attributes rather than constructor @@ -222,26 +203,6 @@ def __init__(self, max_sessions: int = 64, session_wait_timeout: Optional[float] #: many seconds then raise; None = wait forever; 0 = return :class:`NoSlot` immediately. self.session_wait_timeout = session_wait_timeout - def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: - """Capture one episode at a stable boundary for a later process. - - ``state_key`` is the rollout's internal stable identity, never a random - session id. The returned value must be self-contained metadata that - :meth:`restore_episode` accepts after this process exits. - """ - raise UnsupportedEnvResume(f'{type(self).__name__} cannot checkpoint episode {episode_id!r}') - - def restore_episode(self, - episode_id: str, - state_key: str, - state: Dict[str, Any], - trajectory: Optional[Trajectory] = None) -> None: - """Rebind a checkpoint to a newly allocated episode session.""" - raise UnsupportedEnvResume(f'{type(self).__name__} cannot restore episode {episode_id!r}') - - def discard_episode_state(self, state_key: str) -> None: - """Remove durable state once the owning group is committed and trained.""" - # ------------------------------------------------------------------ # Hooks # ------------------------------------------------------------------ diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 46e21b40a..55a2df0ef 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -40,8 +40,9 @@ from twinkle import remote_class, remote_function from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, EnvResumeCapability, StepResult, - UnsafeCheckpoint, format_command_output, truncate_observation) +from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, StepResult, format_command_output, + truncate_observation) +from .resume import EnvResumeCapability, UnsafeCheckpoint logger = get_logger() diff --git a/src/twinkle_agentic/envs/resume.py b/src/twinkle_agentic/envs/resume.py new file mode 100644 index 000000000..835575339 --- /dev/null +++ b/src/twinkle_agentic/envs/resume.py @@ -0,0 +1,75 @@ +# Copyright (c) ModelScope Contributors. All rights reserved. +"""Optional durable-resume protocol for execution environments.""" +from __future__ import annotations +from enum import Enum +from typing import Any, Dict, Optional, Protocol, runtime_checkable + +from twinkle.data_format import Trajectory + +__all__ = [ + 'EnvResumeCapability', + 'ResumableEnv', + 'UnsafeCheckpoint', + 'UnsupportedEnvResume', + 'env_resume_capability', +] + + +class EnvResumeCapability(str, Enum): + """How an environment can survive a different Twinkle process.""" + + NONE = 'none' + LIVE_ATTACH = 'live_attach' + DURABLE_CHECKPOINT = 'durable_checkpoint' + + +class UnsupportedEnvResume(NotImplementedError): + """The environment has no safe way to resume this episode.""" + + +class UnsafeCheckpoint(RuntimeError): + """The episode is not at a point where its workspace can be captured.""" + + +@runtime_checkable +class ResumableEnv(Protocol): + """Structural contract implemented only by environments that opt into resume.""" + + resume_capability: EnvResumeCapability + + def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: + """Capture one quiescent episode under its stable logical identity.""" + + def restore_episode( + self, + episode_id: str, + state_key: str, + state: Dict[str, Any], + trajectory: Optional[Trajectory] = None, + ) -> None: + """Bind a durable snapshot to a newly allocated logical session.""" + + def discard_episode_state(self, state_key: str) -> None: + """Remove durable state after the owning group has been committed.""" + + +def env_resume_capability(env: Any) -> EnvResumeCapability: + """Return an environment's declared capability after structural validation.""" + declared = getattr(env, 'resume_capability', EnvResumeCapability.NONE) + try: + capability = EnvResumeCapability(declared) + except ValueError as exc: + raise UnsupportedEnvResume( + f'{type(env).__name__} declares invalid resume capability {declared!r}' + ) from exc + if capability == EnvResumeCapability.NONE: + return capability + missing = [ + name for name in ('checkpoint_episode', 'restore_episode', 'discard_episode_state') + if not callable(getattr(env, name, None)) + ] + if missing: + raise UnsupportedEnvResume( + f'{type(env).__name__} declares {capability.value} but is missing {missing}' + ) + return capability diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index af3e9587d..3eec7d70f 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -26,7 +26,8 @@ from twinkle.template.base import Template from twinkle.utils import get_logger from twinkle_agentic.async_rl.rollout_resume import ResumeStore, UnsafeResume -from twinkle_agentic.envs.base import EnvResumeCapability, NoSlot +from twinkle_agentic.envs.base import NoSlot +from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability from twinkle_agentic.envs.env_tool import EnvTool from twinkle_agentic.protocol.api_sampler import APIGenerationError from twinkle_agentic.tools.tool_manager import ToolManager @@ -543,7 +544,7 @@ def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[st raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') env_state = None if ep.env_open: - capability = EnvResumeCapability(getattr(self.env, 'resume_capability', EnvResumeCapability.NONE)) + capability = env_resume_capability(self.env) if capability == EnvResumeCapability.NONE: raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') env_state = self.env.checkpoint_episode(ep.episode_id, ep.state_key) @@ -625,7 +626,7 @@ def restore_episode(self, state: dict[str, Any]) -> str: if ep.env_open: if self.env is None: raise UnsafeResume('checkpoint has an environment state but this rollout has no env') - capability = EnvResumeCapability(getattr(self.env, 'resume_capability', EnvResumeCapability.NONE)) + capability = env_resume_capability(self.env) if capability == EnvResumeCapability.NONE: raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') self.env.restore_episode(episode_id, state_key, state['env_state'], ep.trajectory) diff --git a/tests/twinkle_agentic/test_group_policy_binding.py b/tests/twinkle_agentic/test_group_policy_binding.py new file mode 100644 index 000000000..7c2e86ffc --- /dev/null +++ b/tests/twinkle_agentic/test_group_policy_binding.py @@ -0,0 +1,30 @@ +import pytest + +from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding + + +def test_group_policy_binding_round_trip(): + binding = GroupPolicyBinding( + state_key="run/group/17", + policy_version=4, + adapter_path="/policies/policy-4", + ) + assert GroupPolicyBinding.from_dict(binding.to_dict()) == binding + + +@pytest.mark.parametrize( + ("state_key", "policy_version", "adapter_path", "message"), + [ + ("", 0, None, "state_key"), + ("run/group/0", -1, None, "policy_version"), + ("run/group/0", 0, "", "adapter_path"), + ], +) +def test_group_policy_binding_rejects_invalid_identity(state_key, policy_version, adapter_path, message): + with pytest.raises(ValueError, match=message): + GroupPolicyBinding(state_key, policy_version, adapter_path) + + +def test_group_policy_binding_rejects_bool_version_from_snapshot(): + with pytest.raises(ValueError, match="policy_version"): + GroupPolicyBinding.from_dict({"state_key": "run/group/0", "policy_version": True}) diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index 96f7e6cad..1dfb79632 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -16,7 +16,7 @@ ray.is_initialized = lambda: False sys.modules["ray"] = ray -from twinkle_agentic.envs.base import UnsafeCheckpoint # noqa: E402 +from twinkle_agentic.envs.resume import UnsafeCheckpoint # noqa: E402 from twinkle_agentic.envs.localenv import LocalEnv # noqa: E402 diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index 6e63e3736..b2573f19c 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -15,7 +15,7 @@ atomic_write_bytes, ) from twinkle_agentic.async_rl.streaming_driver import StreamingDriver -from twinkle_agentic.envs.base import EnvResumeCapability +from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability from twinkle_agentic.rollout.multi_turn import MultiTurnRollout, RolloutStatus, _Episode @@ -330,6 +330,6 @@ def test_openenv_adapters_declare_no_resume_capability(): from twinkle_agentic.envs.agentenv import AgentEnv from twinkle_agentic.envs.openenv import OpenEnv, OpenEnvClient - assert AgentEnv.resume_capability is EnvResumeCapability.NONE - assert OpenEnv.resume_capability is EnvResumeCapability.NONE - assert OpenEnvClient.resume_capability is EnvResumeCapability.NONE + assert env_resume_capability(AgentEnv) is EnvResumeCapability.NONE + assert env_resume_capability(OpenEnv) is EnvResumeCapability.NONE + assert env_resume_capability(OpenEnvClient) is EnvResumeCapability.NONE diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 6daba163f..7c093059b 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -3,7 +3,7 @@ import pytest -from twinkle_agentic.async_rl.rollout_resume import ResumeStore +from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding, ResumeStore, UnsafeResume from twinkle_agentic.async_rl.streaming_driver import StreamingDriver from twinkle_agentic.rollout.multi_turn import RolloutStatus @@ -115,6 +115,40 @@ def test_inflight_prompt_and_group_survive_snapshot(tmp_path): assert [member.submit_traj["state_key"] for member in restored._groups["0"].members] == [ member.submit_traj["state_key"] for member in driver._groups["0"].members ] + assert restored._groups["0"].binding == driver._groups["0"].binding + + +def test_prompt_assignment_is_persisted_without_manual_state_dict(tmp_path): + store = ResumeStore(tmp_path, "run-auto-prompt") + source = StreamingDriver( + _prompts(), + _BlockingRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + resume_store=store, + ) + try: + source._admit() + finally: + source.close() + + rollout = _BlockingRollout() + restored = StreamingDriver( + _prompts(), + rollout, + batch_size=2, + num_generations=2, + max_staleness=0, + resume_store=store, + ) + restored.load_state_dict() + + assert restored._prompt_seq == 1 + assert list(restored._groups) == ["0"] + assert restored._groups["0"].binding.state_key == "run-auto-prompt/group/0" + assert restored._groups["0"].binding.policy_version == 0 + assert restored._groups["0"].adapter_path is None def test_ready_group_round_trip_and_lease_redelivery(tmp_path): @@ -158,6 +192,45 @@ def test_ready_group_round_trip_and_lease_redelivery(tmp_path): assert stale._lease is None +def test_ready_group_and_lease_are_persisted_without_manual_state_dict(tmp_path): + store = ResumeStore(tmp_path, "run-auto-lease") + source = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + source._start() + _wait_until(lambda: source._ready_rows == 2) + source.close() + + after_ready = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + after_ready.load_state_dict() + assert after_ready._ready_rows == 2 + rows, facts = after_ready._next_batch() + assert len(rows) == 2 + assert facts["policy_versions"] == [0] + lease_id = after_ready._lease["lease_id"] + after_ready.close() + + after_lease = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + after_lease.load_state_dict() + assert after_lease._lease["lease_id"] == lease_id + again_rows, again_facts = after_lease._next_batch() + assert again_rows == rows + assert again_facts == facts + after_lease.commit_batch("checkpoint/auto-lease") + after_lease.close() + + after_commit = StreamingDriver( + _prompts(), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=0, max_steps=1, resume_store=store + ) + after_commit.load_state_dict() + assert after_commit._lease is None + assert after_commit._next_batch() is None + + def test_resumed_group_keeps_its_pinned_adapter_after_policy_advances(tmp_path): store = ResumeStore(tmp_path, "run-policy") manager = _PolicyManager(1, {1: "/policies/policy-1.adapter"}) @@ -193,10 +266,132 @@ def test_resumed_group_keeps_its_pinned_adapter_after_policy_advances(tmp_path): assert restored._groups["0"].version == 1 assert restored._groups["0"].adapter_path == "/policies/policy-1.adapter" + assert restored._groups["0"].binding == GroupPolicyBinding( + state_key="run-policy/group/0", + policy_version=1, + adapter_path="/policies/policy-1.adapter", + ) assert {call[1:] for call in rollout.calls} == {(1, "/policies/policy-1.adapter")} assert restored.stats()["resumed_groups"] == 1 +def test_flat_group_snapshot_is_upgraded_to_policy_binding(tmp_path): + store = ResumeStore(tmp_path, "run-flat") + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=1, + resume_store=store, + ) + state = { + "key": "0", + "row": _prompts(1)[0], + "version": 3, + "adapter_path": "/policies/policy-3.adapter", + "attempt": 0, + "source": [], + "members": [], + "baselines": [], + "missing": 0, + } + group = driver._restore_group(state) + assert group.binding == GroupPolicyBinding( + state_key="run-flat/group/0", + policy_version=3, + adapter_path="/policies/policy-3.adapter", + ) + + +def test_invalid_binding_snapshot_fails_closed(tmp_path): + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + resume_store=ResumeStore(tmp_path, "run-invalid-binding"), + ) + with pytest.raises(UnsafeResume, match="invalid group policy binding"): + driver._restore_group({ + "key": "0", + "row": _prompts(1)[0], + "binding": {"state_key": "", "policy_version": 0, "adapter_path": None}, + "members": [], + }) + + +def test_conflicting_binding_and_flat_snapshot_fails_closed(tmp_path): + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + resume_store=ResumeStore(tmp_path, "run-conflict"), + ) + with pytest.raises(UnsafeResume, match="disagrees"): + driver._restore_group({ + "key": "0", + "row": _prompts(1)[0], + "binding": { + "state_key": "run-conflict/group/0", + "policy_version": 1, + "adapter_path": "/policies/one.adapter", + }, + "version": 2, + "adapter_path": "/policies/two.adapter", + "members": [], + }) + + +def test_explicit_base_model_binding_is_not_rebound_to_an_adapter(tmp_path): + manager = _PolicyManager(1, {1: "/policies/reused-policy.adapter"}) + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + checkpoint_manager=manager, + resume_store=ResumeStore(tmp_path, "run-base-binding"), + ) + group = driver._restore_group({ + "key": "0", + "row": _prompts(1)[0], + "binding": { + "state_key": "run-base-binding/group/0", + "policy_version": 1, + "adapter_path": None, + }, + "version": 1, + "adapter_path": None, + "members": [], + }) + assert group.binding.adapter_path is None + + +def test_group_binding_state_key_must_match_run_identity(tmp_path): + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + resume_store=ResumeStore(tmp_path, "run-identity"), + ) + with pytest.raises(UnsafeResume, match="does not match"): + driver._restore_group({ + "key": "0", + "row": _prompts(1)[0], + "binding": { + "state_key": "other-run/group/0", + "policy_version": 0, + "adapter_path": None, + }, + "version": 0, + "adapter_path": None, + "members": [], + }) + + def test_ready_group_over_staleness_is_dropped_whole(tmp_path): store = ResumeStore(tmp_path, "run-stale") manager = _PolicyManager(1, {1: "/policies/policy-1.adapter"}) From 6bb71b754860d576505259258a221b2ec3b62841 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 16:55:20 +0800 Subject: [PATCH 04/45] test(agentic): refresh NPU evidence after upstream merge --- .../adapter_temp_uncommitted/ready.json | 14 +-- .../adapter_temp_uncommitted/verify.json | 2 +- .../checkpoint_committed/ready.json | 22 ++--- .../checkpoint_committed/verify.json | 4 +- .../ready.json | 22 ++--- .../verify.json | 2 +- .../optimizer_step_uncommitted/ready.json | 14 +-- .../optimizer_step_uncommitted/verify.json | 2 +- .../report.json | 94 +++++++++---------- 9 files changed, 88 insertions(+), 88 deletions(-) diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json index 1d8433f26..047d56ff4 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/ready.json @@ -54,7 +54,7 @@ "optimizer_steps": [ 1 ], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/.step-1.tmp.28770", "step": 1 }, "case": "adapter_temp_uncommitted", @@ -69,8 +69,8 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { "checkpoint_digest": "79c39d048a16be1d07cbec97e040b6604fff6b96835ded8aa913426a33be2a23", @@ -78,15 +78,15 @@ "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077255.8905628, + "marker_created_unix": 1795078164.789897, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/.step-1.tmp.28770", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json index 79de1ce4e..f6e4cf9b4 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/adapter_temp_uncommitted/verify.json @@ -13,7 +13,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/step-0", "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "expected_optimizer_steps": [], "format": "twinkle.npu-checkpoint-kill-verify.v1", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json index 79bd78cc7..a36655eb2 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/ready.json @@ -47,16 +47,16 @@ }, "batch_rows": 2, "candidate_checkpoint": { - "checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", + "checkpoint_digest": "e1bbcd50bb339a93701af4cd9139b2efc86d778cbd9537379fda1655e870e6b2", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [ 1 ], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", - "promoted_checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", - "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/.step-1.tmp.30256", + "promoted_checkpoint_digest": "e1bbcd50bb339a93701af4cd9139b2efc86d778cbd9537379fda1655e870e6b2", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "step": 1 }, "case": "checkpoint_committed", @@ -71,24 +71,24 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { - "checkpoint_digest": "60b7fa29642a7a3c44e16344a2436fa460c8a9d7c2a49f3e8fa60f259dbdea39", + "checkpoint_digest": "77c0ccbf49882ed00597eb5454936e330b2b54bb038f68ee01313b3e11624ad7", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077323.612138, + "marker_created_unix": 1795078233.5247834, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/.step-1.tmp.30256", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json index 1655ee4dd..0f28544a9 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_committed/verify.json @@ -4,7 +4,7 @@ 1 ], "case": "checkpoint_committed", - "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "committed": true, "container": { "hostname": "e1f3eeac3fc6", @@ -15,7 +15,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "expected_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", "expected_optimizer_steps": [ 1 diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json index 2496f10e8..51d80f8bc 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/ready.json @@ -47,16 +47,16 @@ }, "batch_rows": 2, "candidate_checkpoint": { - "checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", + "checkpoint_digest": "01866972858f804de1d48fa695d9b3e277404a82a98365f5c169c99d59279f85", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [ 1 ], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", - "promoted_checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", - "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.29512", + "promoted_checkpoint_digest": "01866972858f804de1d48fa695d9b3e277404a82a98365f5c169c99d59279f85", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-1", "step": 1 }, "case": "checkpoint_promoted_uncommitted", @@ -71,24 +71,24 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { - "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "checkpoint_digest": "8fe5d29da4f8fcd2e4a93c30185d026d4a0d92ee293a7241b29e3bcf1aabb1c6", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077289.5118372, + "marker_created_unix": 1795078199.5146387, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.29512", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json index e8e11d9f9..08d124c0e 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/checkpoint_promoted_uncommitted/verify.json @@ -13,7 +13,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-0", "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "expected_optimizer_steps": [], "format": "twinkle.npu-checkpoint-kill-verify.v1", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json index fa89f546e..d2fcb9ce2 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/ready.json @@ -59,24 +59,24 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { - "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "checkpoint_digest": "79c39d048a16be1d07cbec97e040b6604fff6b96835ded8aa913426a33be2a23", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077221.5744615, + "marker_created_unix": 1795078130.928905, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/.step-1.tmp.24343", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/.step-1.tmp.28023", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json index 5600e7a1b..8755610e7 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/optimizer_step_uncommitted/verify.json @@ -13,7 +13,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/step-0", "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "expected_optimizer_steps": [], "format": "twinkle.npu-checkpoint-kill-verify.v1", diff --git a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json index fc030ea7d..258305bb6 100644 --- a/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json +++ b/review/a2/npu-checkpoint-kill-auto-evidence-20261119-final/report.json @@ -2,7 +2,7 @@ "cases": [ { "case": "optimizer_step_uncommitted", - "elapsed_s": 33.072556257247925, + "elapsed_s": 33.967188119888306, "marker": { "batch_facts": { "episode_ids": [ @@ -64,24 +64,24 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { - "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "checkpoint_digest": "79c39d048a16be1d07cbec97e040b6604fff6b96835ded8aa913426a33be2a23", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077221.5744615, + "marker_created_unix": 1795078130.928905, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/.step-1.tmp.24343", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/.step-1.tmp.28023", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", @@ -112,7 +112,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/optimizer_step_uncommitted/checkpoints/step-0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/optimizer_step_uncommitted/checkpoints/step-0", "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "expected_optimizer_steps": [], "format": "twinkle.npu-checkpoint-kill-verify.v1", @@ -127,7 +127,7 @@ }, { "case": "adapter_temp_uncommitted", - "elapsed_s": 34.285804748535156, + "elapsed_s": 33.78813147544861, "marker": { "batch_facts": { "episode_ids": [ @@ -184,7 +184,7 @@ "optimizer_steps": [ 1 ], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/.step-1.tmp.28770", "step": 1 }, "case": "adapter_temp_uncommitted", @@ -199,8 +199,8 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { "checkpoint_digest": "79c39d048a16be1d07cbec97e040b6604fff6b96835ded8aa913426a33be2a23", @@ -208,15 +208,15 @@ "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077255.8905628, + "marker_created_unix": 1795078164.789897, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/.step-1.tmp.25089", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/.step-1.tmp.28770", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", @@ -247,7 +247,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/adapter_temp_uncommitted/checkpoints/step-0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/adapter_temp_uncommitted/checkpoints/step-0", "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "expected_optimizer_steps": [], "format": "twinkle.npu-checkpoint-kill-verify.v1", @@ -266,7 +266,7 @@ }, { "case": "checkpoint_promoted_uncommitted", - "elapsed_s": 33.72851920127869, + "elapsed_s": 34.59472680091858, "marker": { "batch_facts": { "episode_ids": [ @@ -316,16 +316,16 @@ }, "batch_rows": 2, "candidate_checkpoint": { - "checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", + "checkpoint_digest": "01866972858f804de1d48fa695d9b3e277404a82a98365f5c169c99d59279f85", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [ 1 ], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", - "promoted_checkpoint_digest": "6074bfdcdd336d81c15ec5db6a91688c6f4dda259194384bf6ea9d97a406b8b7", - "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.29512", + "promoted_checkpoint_digest": "01866972858f804de1d48fa695d9b3e277404a82a98365f5c169c99d59279f85", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-1", "step": 1 }, "case": "checkpoint_promoted_uncommitted", @@ -340,24 +340,24 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { - "checkpoint_digest": "ed9408efec4528f96595c8ed785d332509626727bb4468961d7f7933e0337c10", + "checkpoint_digest": "8fe5d29da4f8fcd2e4a93c30185d026d4a0d92ee293a7241b29e3bcf1aabb1c6", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077289.5118372, + "marker_created_unix": 1795078199.5146387, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.25835", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/.step-1.tmp.29512", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", @@ -388,7 +388,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_promoted_uncommitted/checkpoints/step-0", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_promoted_uncommitted/checkpoints/step-0", "expected_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "expected_optimizer_steps": [], "format": "twinkle.npu-checkpoint-kill-verify.v1", @@ -407,7 +407,7 @@ }, { "case": "checkpoint_committed", - "elapsed_s": 33.86141848564148, + "elapsed_s": 34.01740598678589, "marker": { "batch_facts": { "episode_ids": [ @@ -457,16 +457,16 @@ }, "batch_rows": 2, "candidate_checkpoint": { - "checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", + "checkpoint_digest": "e1bbcd50bb339a93701af4cd9139b2efc86d778cbd9537379fda1655e870e6b2", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [ 1 ], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", - "promoted_checkpoint_digest": "3d30ef9cdf38c37027ccd30378c5479c761da06e4370346265176b62496c974e", - "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/.step-1.tmp.30256", + "promoted_checkpoint_digest": "e1bbcd50bb339a93701af4cd9139b2efc86d778cbd9537379fda1655e870e6b2", + "promoted_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "step": 1 }, "case": "checkpoint_committed", @@ -481,24 +481,24 @@ "device": "npu:0", "driver_handed": 1, "driver_persistence": "automatic", - "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/resume/objects/driver", - "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "driver_state_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/resume/objects/driver", + "final_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "format": "twinkle.npu-checkpoint-kill-marker.v1", "initial_checkpoint": { - "checkpoint_digest": "60b7fa29642a7a3c44e16344a2436fa460c8a9d7c2a49f3e8fa60f259dbdea39", + "checkpoint_digest": "77c0ccbf49882ed00597eb5454936e330b2b54bb038f68ee01313b3e11624ad7", "format": "twinkle.npu-checkpoint-kill.v1", "lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "optimizer_steps": [], - "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-0", + "path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-0", "step": 0 }, "initial_lora_digest": "5713e04c38bc858ef33ae52dd4fcd72a7e1ca9fa9548fd653d735e44a869190d", "lease_id": "npu-checkpoint-kill/batch/0", - "marker_created_unix": 1795077323.612138, + "marker_created_unix": 1795078233.5247834, "optimizer_loss": 5.960464477539063e-08, - "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/.step-1.tmp.26580", - "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed", + "pending_checkpoint_path": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/.step-1.tmp.30256", + "root": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed", "run_id": "npu-checkpoint-kill", "seed": 20261119, "trained_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", @@ -520,7 +520,7 @@ 1 ], "case": "checkpoint_committed", - "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "commit_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "committed": true, "container": { "hostname": "e1f3eeac3fc6", @@ -531,7 +531,7 @@ "transformers": "5.20.2" }, "device": "npu:0", - "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-final/checkpoint_committed/checkpoints/step-1", + "expected_checkpoint": "/workspace/rollout-resume-20261118-r6/results/npu-checkpoint-kill-auto-20261119-merged/checkpoint_committed/checkpoints/step-1", "expected_lora_digest": "40bf9abc1e7edffcc78e99b1b4b35fb03b411ad51077d15a0ca5bd4ed107a5bf", "expected_optimizer_steps": [ 1 @@ -555,11 +555,11 @@ "torch_npu": "2.10.0", "transformers": "5.20.2" }, - "finished_unix": 1795077342.160995, + "finished_unix": 1795078252.3158689, "format": "twinkle.npu-checkpoint-kill-report.v1", "model": "/workspace/shared_assets/models/Qwen/Qwen3-0.6B", "ok": true, "seed": 20261119, - "started_unix": 1795077207.204393, + "started_unix": 1795078115.9396825, "train_jsonl": "data/gsm8k/train.jsonl" } From 0b6523abbdfc47d75e0894758ae4a88a7c5172cb Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 17:03:58 +0800 Subject: [PATCH 05/45] style(agentic): apply repository pre-commit rules --- .../report.json | 2 +- .../report.json | 2 +- .../async_rl/rollout_resume.py | 4 +- .../async_rl/streaming_driver.py | 850 ++++++++++-------- src/twinkle_agentic/envs/__init__.py | 19 +- src/twinkle_agentic/envs/base.py | 203 ++--- src/twinkle_agentic/envs/localenv.py | 244 ++--- src/twinkle_agentic/envs/resume.py | 38 +- src/twinkle_agentic/rollout/ledger.py | 45 +- src/twinkle_agentic/rollout/multi_turn.py | 714 ++++++++------- 10 files changed, 1148 insertions(+), 973 deletions(-) diff --git a/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json b/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json index 3d47f63c2..506369eda 100644 --- a/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json +++ b/review/a2/synced-results-20261119/gsm8k-eval512-fault50-lr2e5-seed20261126/report.json @@ -6211,4 +6211,4 @@ }, "accuracy_delta": 0.046875, "reward_delta": 0.06679687499999892 -} \ No newline at end of file +} diff --git a/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json b/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json index 51fe00a6f..70697d55b 100644 --- a/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json +++ b/review/a2/synced-results-20261119/gsm8k-train128-eval256-fault50-lr2e5-seed20261127/report.json @@ -3139,4 +3139,4 @@ }, "accuracy_delta": 0.09375, "reward_delta": 0.1351562499999982 -} \ No newline at end of file +} diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 50a91d8a6..1e7dd3b30 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -108,9 +108,7 @@ def __post_init__(self) -> None: raise ValueError("group policy_version must be an integer") if self.policy_version < 0: raise ValueError("group policy_version must be >= 0") - if self.adapter_path is not None and ( - not isinstance(self.adapter_path, str) or not self.adapter_path.strip() - ): + if self.adapter_path is not None and (not isinstance(self.adapter_path, str) or not self.adapter_path.strip()): raise ValueError("group adapter_path must be a non-empty string when provided") def to_dict(self) -> dict[str, Any]: diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index c54cad0a0..5b91a3a3d 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -21,6 +21,7 @@ queue when it finishes, and the driver's thread only reads that queue, so its cost does not grow with the number of episodes in flight. """ + from __future__ import annotations import copy import math @@ -30,8 +31,9 @@ import time import uuid from collections import deque +from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, field, replace -from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence +from typing import Any from twinkle import remote_class, remote_function from twinkle.data_format import user_data_get @@ -41,16 +43,16 @@ logger = get_logger() -__all__ = ['StreamingDriver', 'PRM_SEGMENT_TURNS'] +__all__ = ["StreamingDriver", "PRM_SEGMENT_TURNS"] #: The ``RolloutStatus.extra`` key recording each PRM segment's end: the episode's ``turns`` when the #: segment closed, one per column of ``prm_rewards``. -PRM_SEGMENT_TURNS = 'prm_segment_turns' +PRM_SEGMENT_TURNS = "prm_segment_turns" -_BASELINE = 'baseline' +_BASELINE = "baseline" -def _record_driver_probe(event: str, episode_id: str = '', **fields: Any) -> None: +def _record_driver_probe(event: str, episode_id: str = "", **fields: Any) -> None: """Append one driver event per call when ``TWINKLE_DRIVER_PROBE`` names a directory. The rollout-side dispatch probe shows an episode's opening step returning and then no @@ -62,18 +64,20 @@ def _record_driver_probe(event: str, episode_id: str = '', **fields: Any) -> Non import os import json - root = os.environ.get('TWINKLE_DRIVER_PROBE') + + root = os.environ.get("TWINKLE_DRIVER_PROBE") if not root: return os.makedirs(root, exist_ok=True) - path = os.path.join(root, f'driver.{os.getpid()}.jsonl') - with open(path, 'a', encoding='utf-8') as handle: - handle.write(json.dumps({'t': time.monotonic(), 'event': event, 'episode_id': episode_id, - **fields}, default=str) + '\n') + path = os.path.join(root, f"driver.{os.getpid()}.jsonl") + with open(path, "a", encoding="utf-8") as handle: + handle.write( + json.dumps({"t": time.monotonic(), "event": event, "episode_id": episode_id, **fields}, default=str) + "\n" + ) def _is_episode_error(exc: BaseException) -> bool: - return isinstance(exc, EpisodeError) or isinstance(getattr(exc, 'cause', None), EpisodeError) + return isinstance(exc, EpisodeError) or isinstance(getattr(exc, "cause", None), EpisodeError) def _role_of(traj: Any) -> str: @@ -82,14 +86,15 @@ def _role_of(traj: Any) -> str: The group verdict returns baseline rows to the driver before they are submitted; those rows may carry either spelling, so both are read -- writing is top-level only. """ - role = traj.get('role') + role = traj.get("role") if role is None: - role = user_data_get(traj.get('user_data'), 'role') - return str(role or '') + role = user_data_get(traj.get("user_data"), "role") + return str(role or "") -def _sample_facts(samples: Sequence[RolloutStatus], scores: Sequence[Dict[str, Any]], - version_spans: Sequence[int]) -> Dict[str, Any]: +def _sample_facts( + samples: Sequence[RolloutStatus], scores: Sequence[dict[str, Any]], version_spans: Sequence[int] +) -> dict[str, Any]: """The delivery facts of one batch, off the samples -- never the trajectories. The rows are never opened for this (under ray they are references): the lengths / @@ -97,8 +102,8 @@ def _sample_facts(samples: Sequence[RolloutStatus], scores: Sequence[Dict[str, A columns arrive row-aligned in ``scores`` -- the one payload-adjacent lane, which the advantage estimator and the reward metrics consume without materialising a trajectory. """ - prompt_lengths: List[int] = [] - response_lengths: List[int] = [] + prompt_lengths: list[int] = [] + response_lengths: list[int] = [] for sample in samples: tokens = sample.token_lengths # None means the episode never produced an encoded frame (an empty prompt); a delivered @@ -107,25 +112,26 @@ def _sample_facts(samples: Sequence[RolloutStatus], scores: Sequence[Dict[str, A response_lengths.append(tokens[1] if tokens else 0) truncated = [bool(sample.truncated) for sample in samples] return { - 'num_rows': len(samples), - 'episode_ids': [sample.episode_id for sample in samples], - 'prompt_lengths': prompt_lengths, - 'response_lengths': response_lengths, - 'response_length_min': min(response_lengths) if response_lengths else 0, - 'response_length_max': max(response_lengths) if response_lengths else 0, - 'response_length_sum': sum(response_lengths), - 'policy_versions': sorted({sample.policy_version for sample in samples}), - 'truncated': truncated, - 'num_truncated': sum(truncated), - 'turns': [sample.turns for sample in samples], - 'version_spans': list(version_spans), - 'scores': list(scores), + "num_rows": len(samples), + "episode_ids": [sample.episode_id for sample in samples], + "prompt_lengths": prompt_lengths, + "response_lengths": response_lengths, + "response_length_min": min(response_lengths) if response_lengths else 0, + "response_length_max": max(response_lengths) if response_lengths else 0, + "response_length_sum": sum(response_lengths), + "policy_versions": sorted({sample.policy_version for sample in samples}), + "truncated": truncated, + "num_truncated": sum(truncated), + "turns": [sample.turns for sample in samples], + "version_spans": list(version_spans), + "scores": list(scores), } @dataclass class _Group: """One prompt row's episodes: the current attempt's members and the baseline episodes it waits for.""" + key: str row: Any #: Fixed for the group's whole lifetime. Recovery and replacement members must use this @@ -133,9 +139,9 @@ class _Group: binding: GroupPolicyBinding attempt: int = 0 #: The current attempt's member trajectories, aligned with ``members`` (a lost one is redone from here). - source: List[Any] = field(default_factory=list) - members: List['_Episode'] = field(default_factory=list) - baselines: List['_Episode'] = field(default_factory=list) + source: list[Any] = field(default_factory=list) + members: list[_Episode] = field(default_factory=list) + baselines: list[_Episode] = field(default_factory=list) #: Members of the current attempt that will not produce a sample (failed, stopped, dropped). missing: int = 0 @@ -148,7 +154,7 @@ def version(self) -> int: return self.binding.policy_version @property - def adapter_path(self) -> Optional[str]: + def adapter_path(self) -> str | None: return self.binding.adapter_path @@ -159,28 +165,28 @@ class _Episode: role: str version: int traj: Any = None - sample: Optional[RolloutStatus] = None + sample: RolloutStatus | None = None done: bool = False #: Set once the episode has no further work: scored (``finished``) or given up (``lost``). finished: bool = False lost: bool = False - orm: Optional[List[Any]] = None + orm: list[Any] | None = None orm_pending: int = 0 - prm: Optional[List[List[Any]]] = None - prm_turns: List[int] = field(default_factory=list) + prm: list[list[Any]] | None = None + prm_turns: list[int] = field(default_factory=list) prm_pending: int = 0 #: The PRM segment the episode waits for before its next step (only with ``on_step``). - held: Optional[int] = None + held: int | None = None #: The episode's training rows as the last step returned them (one, or one per collected #: segment); an unfinished episode holds none. - deliver: List[Any] = field(default_factory=list) + deliver: list[Any] = field(default_factory=list) #: The trajectory this episode was submitted with, kept so a no-slot retry can resubmit the same #: member slot without touching group_attempt or the quality-regeneration budget. submit_traj: Any = None #: No-slot retry state (scheduling delay, not failure): when to retry next, the wall-clock deadline #: after which the group is dropped, and how many no-slot returns this member has accumulated. - no_slot_retry_at: Optional[float] = None - no_slot_deadline: Optional[float] = None + no_slot_retry_at: float | None = None + no_slot_deadline: float | None = None no_slot_attempts: int = 0 #: Whether this episode currently contributes 1 to ``_inflight``. True from submission until it #: finishes, is lost, or returns no-slot (the call returned, the member waits to retry). Lets @@ -189,7 +195,7 @@ class _Episode: counted_inflight: bool = False -@remote_class(execute='first', max_concurrency=8) +@remote_class(execute="first", max_concurrency=8) class StreamingDriver: """Stream episodes through ``rollout`` and hand out scored groups; iterate it for training batches. @@ -252,48 +258,53 @@ class StreamingDriver: NO_SLOT_MAX_DELAY = 15.0 NO_SLOT_JITTER = 0.5 - def __init__(self, - dataloader: Any, - rollout: Any, - *, - batch_size: int, - num_generations: int = 1, - num_epochs: float = 1.0, - max_steps: Optional[int] = None, - max_staleness: int = 0, - sync_interval: int = 1, - checkpoint_manager: Any = None, - orms: Sequence[Any] = (), - orm_names: Optional[Sequence[str]] = None, - prms: Sequence[Any] = (), - prm_names: Optional[Sequence[str]] = None, - prm_segment: Optional[Callable[[RolloutStatus, Any], bool]] = None, - on_step: Optional[Callable[[RolloutStatus, List[Any]], bool]] = None, - on_sample: Optional[Callable[[RolloutStatus], Optional[bool]]] = None, - on_group: Optional[Callable[[Any, List[RolloutStatus], int], List[Any]]] = None, - max_group_regenerations: int = 0, - cluster_adapter: Any = None, - max_no_slot_wait: float = 1800.0, - resume_store: Optional[ResumeStore] = None, - run_id: Optional[str] = None): + def __init__( + self, + dataloader: Any, + rollout: Any, + *, + batch_size: int, + num_generations: int = 1, + num_epochs: float = 1.0, + max_steps: int | None = None, + max_staleness: int = 0, + sync_interval: int = 1, + checkpoint_manager: Any = None, + orms: Sequence[Any] = (), + orm_names: Sequence[str] | None = None, + prms: Sequence[Any] = (), + prm_names: Sequence[str] | None = None, + prm_segment: Callable[[RolloutStatus, Any], bool] | None = None, + on_step: Callable[[RolloutStatus, list[Any]], bool] | None = None, + on_sample: Callable[[RolloutStatus], bool | None] | None = None, + on_group: Callable[[Any, list[RolloutStatus], int], list[Any]] | None = None, + max_group_regenerations: int = 0, + cluster_adapter: Any = None, + max_no_slot_wait: float = 1800.0, + resume_store: ResumeStore | None = None, + run_id: str | None = None, + ): if num_generations < 1 or batch_size < 1 or batch_size % num_generations: - raise ValueError(f'batch_size ({batch_size}) must be a positive multiple of num_generations ' - f'({num_generations}): a batch holds whole groups.') + raise ValueError( + f"batch_size ({batch_size}) must be a positive multiple of num_generations " + f"({num_generations}): a batch holds whole groups." + ) if num_epochs <= 0: - raise ValueError(f'num_epochs must be > 0, got {num_epochs}.') + raise ValueError(f"num_epochs must be > 0, got {num_epochs}.") if max_staleness < 0 or sync_interval < 1: - raise ValueError(f'max_staleness must be >= 0 and sync_interval >= 1, got {max_staleness} / ' - f'{sync_interval}.') + raise ValueError( + f"max_staleness must be >= 0 and sync_interval >= 1, got {max_staleness} / {sync_interval}." + ) if on_step is not None and not prms: - raise ValueError('on_step reads PRM scores; pass prms= or drop on_step.') + raise ValueError("on_step reads PRM scores; pass prms= or drop on_step.") self.orms = list(orms) - self.orm_names = list(orm_names) if orm_names is not None else [f'orm_{i}' for i in range(len(self.orms))] + self.orm_names = list(orm_names) if orm_names is not None else [f"orm_{i}" for i in range(len(self.orms))] if len(self.orm_names) != len(self.orms): - raise ValueError(f'orm_names ({len(self.orm_names)}) must name every ORM ({len(self.orms)}).') + raise ValueError(f"orm_names ({len(self.orm_names)}) must name every ORM ({len(self.orms)}).") self.prms = list(prms) - self.prm_names = list(prm_names) if prm_names is not None else [f'prm_{i}' for i in range(len(self.prms))] + self.prm_names = list(prm_names) if prm_names is not None else [f"prm_{i}" for i in range(len(self.prms))] if len(self.prm_names) != len(self.prms): - raise ValueError(f'prm_names ({len(self.prm_names)}) must name every PRM ({len(self.prms)}).') + raise ValueError(f"prm_names ({len(self.prm_names)}) must name every PRM ({len(self.prms)}).") self.dataloader = dataloader self.rollout = rollout self.batch_size = batch_size @@ -312,23 +323,23 @@ def __init__(self, self.resume_store = resume_store self.run_id = run_id or (resume_store.run_id if resume_store is not None else uuid.uuid4().hex) if resume_store is not None and run_id is not None and run_id != resume_store.run_id: - raise ValueError(f'run_id {run_id!r} does not match resume store run {resume_store.run_id!r}') + raise ValueError(f"run_id {run_id!r} does not match resume store run {resume_store.run_id!r}") #: Wall-clock ceiling on how long one member may keep retrying a full session pool before its #: group is loudly dropped. Scheduling delay is not quality regeneration: it never spends #: max_group_regenerations or increments group_attempt, but it must still be bounded. self.max_no_slot_wait = max_no_slot_wait self._lock = threading.Condition() - self._events: 'queue.Queue[tuple[Any, ...]]' = queue.Queue() + self._events: queue.Queue[tuple[Any, ...]] = queue.Queue() self._ready: deque = deque() self._ready_rows = 0 - self._thread: Optional[threading.Thread] = None + self._thread: threading.Thread | None = None self._closed = False self._exhausted = False - self._error: Optional[BaseException] = None - self._rows: Optional[Iterator[Any]] = None + self._error: BaseException | None = None + self._rows: Iterator[Any] | None = None self._prompt_seq = 0 - self._groups: Dict[str, _Group] = {} + self._groups: dict[str, _Group] = {} #: Member rows admitted and not dropped (baselines excluded): what the version bound caps. self._live = 0 self._inflight = 0 @@ -337,10 +348,18 @@ def __init__(self, self._base_version = 0 self._failures: deque = deque(maxlen=self.FAILURE_WINDOW) self._consecutive_failures = 0 - self._counters: Dict[str, int] = { - 'admitted': 0, 'dropped_stale': 0, 'dropped_sample': 0, 'dropped_group': 0, 'episode_errors': 0, - 'stopped': 0, 'regenerated': 0, 'no_slot': 0, 'no_slot_dropped': 0, - 'resumed_groups': 0, 'resumed_members': 0, + self._counters: dict[str, int] = { + "admitted": 0, + "dropped_stale": 0, + "dropped_sample": 0, + "dropped_group": 0, + "episode_errors": 0, + "stopped": 0, + "regenerated": 0, + "no_slot": 0, + "no_slot_dropped": 0, + "resumed_groups": 0, + "resumed_members": 0, } self._adjusting = False #: monotonic stamps: when the running ``adjust`` started, and when its being stuck was last reported. @@ -353,33 +372,35 @@ def __init__(self, #: the lend->reclaim cycle now in flight (the thread, until the reclaim in ``_next_batch``'s #: finally completes): while it runs the adapter's lock is legitimately held self._lending = None - self._returned_at: Optional[float] = None + self._returned_at: float | None = None self._idle_ratio = 0.0 self._iter_started = False #: The one batch whose model update may or may not have committed. It survives a process #: restart and is handed out again until ``commit_batch`` records the model checkpoint. - self._lease: Optional[Dict[str, Any]] = None + self._lease: dict[str, Any] | None = None self._lease_returned = False # ------------------------------------------------------------------ iteration - @remote_function(execute='first', collect='first', lazy_collect=False, stash=(0,)) + @remote_function(execute="first", collect="first", lazy_collect=False, stash=(0,)) def __iter__(self): """Iterate the driver once: ``(rows, facts)`` per batch, delivered together.""" if self._iter_started: - raise RuntimeError('StreamingDriver serves ONE iteration per run; a second one would re-read ' - 'the dataloader from an unrelated position. Wrap the single iterator instead.') + raise RuntimeError( + "StreamingDriver serves ONE iteration per run; a second one would re-read " + "the dataloader from an unrelated position. Wrap the single iterator instead." + ) self._iter_started = True return self._batches() - def _batches(self) -> Iterator[List[Any]]: + def _batches(self) -> Iterator[list[Any]]: while True: batch = self._next_batch() if batch is None: return yield batch - def _next_batch(self) -> Optional[tuple]: + def _next_batch(self) -> tuple | None: """Wait for ``batch_size`` rows of complete, fresh groups; ``None`` once nothing more will come. A delivery is ``(rows, facts)``: the rows exactly as they travel (a reference under ray, @@ -394,10 +415,12 @@ def _next_batch(self) -> Optional[tuple]: self._lease_returned = False elif not self._lease_returned: self._lease_returned = True - return self._lease['rows'], self._lease['facts'] + return self._lease["rows"], self._lease["facts"] else: - raise UnsafeResume(f'batch lease {self._lease["lease_id"]!r} is still open; ' - 'call commit_batch() after the model checkpoint is durable') + raise UnsafeResume( + f"batch lease {self._lease['lease_id']!r} is still open; " + "call commit_batch() after the model checkpoint is durable" + ) self._start() started = time.monotonic() waited = 0.0 @@ -414,7 +437,7 @@ def _next_batch(self) -> Optional[tuple]: # the trainer waits from here on: its devices may be lent until the batch is ready lending = None if self.cluster_adapter is not None and short: - lending = threading.Thread(target=self._lend, args=(waited,), name='twinkle-cluster-lend', daemon=True) + lending = threading.Thread(target=self._lend, args=(waited,), name="twinkle-cluster-lend", daemon=True) lending.start() #: mirrors ``lending`` from its start until the reclaim below completes -- an ``adjust`` #: queued behind that cycle is not stuck, so the watchdog stays quiet while it runs @@ -458,36 +481,45 @@ def _next_batch(self) -> Optional[tuple]: versions = [episode.version for episode in members] if versions and max(versions) - min(versions) > self.max_staleness: raise RuntimeError( - f'ready group spans {max(versions) - min(versions)} policy versions ' - f'({min(versions)}..{max(versions)}), more than max_staleness=' - f'{self.max_staleness}; per-member staleness left an over-age member.') - trajs: List[Any] = [] - samples: List[RolloutStatus] = [] - scores: List[Dict[str, Any]] = [] - version_spans: List[int] = [] + f"ready group spans {max(versions) - min(versions)} policy versions " + f"({min(versions)}..{max(versions)}), more than max_staleness=" + f"{self.max_staleness}; per-member staleness left an over-age member." + ) + trajs: list[Any] = [] + samples: list[RolloutStatus] = [] + scores: list[dict[str, Any]] = [] + version_spans: list[int] = [] while len(trajs) < self.batch_size and self._ready: ready_group = self._ready.popleft() self._live -= sum(1 for episode in ready_group if episode.deliver) for episode in ready_group: episode.sample.version_span = self._version - episode.sample.policy_version score = self._score_update(episode) - lengths = (episode.sample.extra or {}).get('row_token_lengths') + lengths = (episode.sample.extra or {}).get("row_token_lengths") if len(episode.deliver) == 1 or not lengths: # The identity path: one row carries the episode's own facts verbatim. row_samples = [episode.sample] * len(episode.deliver) else: if len(lengths) != len(episode.deliver): raise RuntimeError( - f'episode {episode.sample.episode_id!r}: {len(episode.deliver)} delivered rows ' - f'but {len(lengths)} row lengths on its status.') + f"episode {episode.sample.episode_id!r}: {len(episode.deliver)} delivered rows " + f"but {len(lengths)} row lengths on its status." + ) # A collected episode's rows carry their own length facts: the episode # totals would repeat on every row and weigh the metrics by row count. - extra = {key: value for key, value in (episode.sample.extra or {}).items() - if key != 'row_token_lengths'} + extra = { + key: value + for key, value in (episode.sample.extra or {}).items() + if key != "row_token_lengths" + } row_samples = [ - replace(episode.sample, token_lengths=tuple(map(int, pair)), - extra=dict(extra, segment_index=index)) - for index, pair in enumerate(lengths)] + replace( + episode.sample, + token_lengths=tuple(map(int, pair)), + extra=dict(extra, segment_index=index), + ) + for index, pair in enumerate(lengths) + ] for row, row_sample in zip(episode.deliver, row_samples, strict=True): trajs.append(row) samples.append(row_sample) @@ -496,31 +528,31 @@ def _next_batch(self) -> Optional[tuple]: self._ready_rows -= len(trajs) batch_index = self._handed facts = _sample_facts(samples, scores, version_spans) - lease_id = f'{self.run_id}/batch/{batch_index}' + lease_id = f"{self.run_id}/batch/{batch_index}" self._lease = { - 'lease_id': lease_id, - 'batch': batch_index, - 'policy_versions': list(facts['policy_versions']), - 'rows': trajs, - 'facts': facts, + "lease_id": lease_id, + "batch": batch_index, + "policy_versions": list(facts["policy_versions"]), + "rows": trajs, + "facts": facts, } self._lease_returned = True self._handed += 1 if self.resume_store is not None: - self.resume_store.save_object('leases', lease_id, self._lease) + self.resume_store.save_object("leases", lease_id, self._lease) # The snapshot must point at the lease before the journal makes # it durable. A crash in between re-delivers this same lease; # the reverse order could strand the lease object unreferenced. self._persist_snapshot_locked() self.resume_store.journal.append( - JournalEvent.BATCH_LEASED, lease_id, - {'batch': batch_index, 'rows': len(trajs), 'object': lease_id}) + JournalEvent.BATCH_LEASED, lease_id, {"batch": batch_index, "rows": len(trajs), "object": lease_id} + ) self._lock.notify_all() self._returned_at = time.monotonic() self._wait_time = self._returned_at - started return trajs, facts - def _score_update(self, episode: _Episode) -> Dict[str, Any]: + def _score_update(self, episode: _Episode) -> dict[str, Any]: """One row's light score entry, off the private bookkeeping -- never written onto the row. The entry mirrors the row's column contract (``rewards.orm`` / ``rewards.baseline`` map @@ -532,24 +564,35 @@ def _score_update(self, episode: _Episode) -> Dict[str, Any]: ``rewards.env`` stays on the row, where its producer wrote it. """ sample = episode.sample - rewards: Dict[str, Any] = { - 'orm': {name: (None if value is None else float(value)) - for name, value in zip(self.orm_names, episode.orm or (), strict=True)}, + rewards: dict[str, Any] = { + "orm": { + name: (None if value is None else float(value)) + for name, value in zip(self.orm_names, episode.orm or (), strict=True) + }, } if sample.baseline is not None: - rows = sample.baseline if (sample.baseline and isinstance(sample.baseline[0], (list, tuple))) \ + rows = ( + sample.baseline + if (sample.baseline and isinstance(sample.baseline[0], (list, tuple))) else [sample.baseline] + ) if len(rows) != 1: - raise RuntimeError(f'episode {episode.episode_id} carries {len(rows)} baseline rows; the named ' - 'baseline column carries one. Return a single baseline per group.') - rewards['baseline'] = {name: (None if value is None else float(value)) - for name, value in zip(self.orm_names, rows[0], strict=True)} - score: Dict[str, Any] = {'rewards': rewards} + raise RuntimeError( + f"episode {episode.episode_id} carries {len(rows)} baseline rows; the named " + "baseline column carries one. Return a single baseline per group." + ) + rewards["baseline"] = { + name: (None if value is None else float(value)) + for name, value in zip(self.orm_names, rows[0], strict=True) + } + score: dict[str, Any] = {"rewards": rewards} if episode.prm is not None: - score['prm_segments'] = { - 'end_turns': [int(turns) for turns in episode.prm_turns], - 'scores': {name: [(None if value is None else float(value)) for value in column] - for name, column in zip(self.prm_names, episode.prm, strict=True)}, + score["prm_segments"] = { + "end_turns": [int(turns) for turns in episode.prm_turns], + "scores": { + name: [(None if value is None else float(value)) for value in column] + for name, column in zip(self.prm_names, episode.prm, strict=True) + }, } return score @@ -576,12 +619,14 @@ def _drop_stale(self) -> None: def _retire_stale_group(self, group: _Group) -> None: """Drop one group atomically after its pinned policy leaves the staleness window.""" self._groups.pop(group.key, None) - self._counters['dropped_stale'] += len(group.members) - self._counters['dropped_group'] += 1 + self._counters["dropped_stale"] += len(group.members) + self._counters["dropped_group"] += 1 if self.resume_store is not None: self.resume_store.journal.append( - JournalEvent.GROUP_DROPPED, group.state_key, - {'reason': 'stale', 'binding': group.binding.to_dict(), 'current_version': self._version}) + JournalEvent.GROUP_DROPPED, + group.state_key, + {"reason": "stale", "binding": group.binding.to_dict(), "current_version": self._version}, + ) self._persist_snapshot_locked() for episode in group.members + group.baselines: if episode.lost: @@ -591,75 +636,84 @@ def _retire_stale_group(self, group: _Group) -> None: if episode.role != _BASELINE: self._live -= 1 - @remote_function(execute='first', collect='first', lazy_collect=False) - def stats(self) -> Dict[str, Any]: + @remote_function(execute="first", collect="first", lazy_collect=False) + def stats(self) -> dict[str, Any]: """Counters of the run so far (small; for logging).""" with self._lock: - return dict(self._counters, version=self._version, handed=self._handed, inflight=self._inflight, - live=self._live, ready_rows=self._ready_rows, train_idle_ratio=self._idle_ratio) + return dict( + self._counters, + version=self._version, + handed=self._handed, + inflight=self._inflight, + live=self._live, + ready_rows=self._ready_rows, + train_idle_ratio=self._idle_ratio, + ) def _loader_state(self) -> Any: - getter = getattr(self.dataloader, 'state_dict', None) or getattr(self.dataloader, 'get_state', None) + getter = getattr(self.dataloader, "state_dict", None) or getattr(self.dataloader, "get_state", None) return copy.deepcopy(getter()) if callable(getter) else None - def _episode_state(self, episode: _Episode) -> Dict[str, Any]: + def _episode_state(self, episode: _Episode) -> dict[str, Any]: now = time.monotonic() return { - 'episode_id': episode.episode_id, - 'group_key': episode.group.key, - 'role': episode.role, - 'version': episode.version, - 'traj': episode.traj, - 'sample': episode.sample, - 'done': episode.done, - 'finished': episode.finished, - 'lost': episode.lost, - 'orm': _dump_pending(episode.orm), - 'orm_pending': episode.orm_pending, - 'prm': _dump_pending(episode.prm), - 'prm_turns': list(episode.prm_turns), - 'prm_pending': episode.prm_pending, - 'held': episode.held, - 'deliver': list(episode.deliver), - 'submit_traj': episode.submit_traj, - 'no_slot_retry_in': (None if episode.no_slot_retry_at is None - else max(0.0, episode.no_slot_retry_at - now)), - 'no_slot_deadline_in': (None if episode.no_slot_deadline is None - else max(0.0, episode.no_slot_deadline - now)), - 'no_slot_attempts': episode.no_slot_attempts, - 'counted_inflight': episode.counted_inflight, + "episode_id": episode.episode_id, + "group_key": episode.group.key, + "role": episode.role, + "version": episode.version, + "traj": episode.traj, + "sample": episode.sample, + "done": episode.done, + "finished": episode.finished, + "lost": episode.lost, + "orm": _dump_pending(episode.orm), + "orm_pending": episode.orm_pending, + "prm": _dump_pending(episode.prm), + "prm_turns": list(episode.prm_turns), + "prm_pending": episode.prm_pending, + "held": episode.held, + "deliver": list(episode.deliver), + "submit_traj": episode.submit_traj, + "no_slot_retry_in": ( + None if episode.no_slot_retry_at is None else max(0.0, episode.no_slot_retry_at - now) + ), + "no_slot_deadline_in": ( + None if episode.no_slot_deadline is None else max(0.0, episode.no_slot_deadline - now) + ), + "no_slot_attempts": episode.no_slot_attempts, + "counted_inflight": episode.counted_inflight, } - def _group_state(self, group: _Group) -> Dict[str, Any]: + def _group_state(self, group: _Group) -> dict[str, Any]: return { - 'key': group.key, - 'row': group.row, - 'binding': group.binding.to_dict(), + "key": group.key, + "row": group.row, + "binding": group.binding.to_dict(), # Flat fields keep snapshots readable by earlier draft readers. - 'version': group.version, - 'adapter_path': group.adapter_path, - 'attempt': group.attempt, - 'source': list(group.source), - 'members': [self._episode_state(episode) for episode in group.members], - 'baselines': [self._episode_state(episode) for episode in group.baselines], - 'missing': group.missing, + "version": group.version, + "adapter_path": group.adapter_path, + "attempt": group.attempt, + "source": list(group.source), + "members": [self._episode_state(episode) for episode in group.members], + "baselines": [self._episode_state(episode) for episode in group.baselines], + "missing": group.missing, } - def _snapshot(self) -> Dict[str, Any]: + def _snapshot(self) -> dict[str, Any]: return { - 'format': 'twinkle.streaming-driver.v1', - 'run_id': self.run_id, - 'handed': self._handed, - 'prompts_drawn': self._prompt_seq, - 'version': self._version, - 'base_version': self._base_version, - 'exhausted': self._exhausted, - 'counters': dict(self._counters), - 'loader_state': self._loader_state(), - 'groups': [self._group_state(group) for group in self._groups.values()], - 'ready': [[self._episode_state(episode) for episode in members] for members in self._ready], - 'ready_groups': [self._group_state(members[0].group) for members in self._ready if members], - 'lease': self._lease, + "format": "twinkle.streaming-driver.v1", + "run_id": self.run_id, + "handed": self._handed, + "prompts_drawn": self._prompt_seq, + "version": self._version, + "base_version": self._base_version, + "exhausted": self._exhausted, + "counters": dict(self._counters), + "loader_state": self._loader_state(), + "groups": [self._group_state(group) for group in self._groups.values()], + "ready": [[self._episode_state(episode) for episode in members] for members in self._ready], + "ready_groups": [self._group_state(members[0].group) for members in self._ready if members], + "lease": self._lease, } def _persist_snapshot_locked(self) -> None: @@ -671,10 +725,10 @@ def _persist_snapshot_locked(self) -> None: uses it to retire a lease even when the following snapshot was torn. """ if self.resume_store is not None: - self.resume_store.save_object('driver', self.run_id, self._snapshot()) + self.resume_store.save_object("driver", self.run_id, self._snapshot()) - @remote_function(execute='first', collect='first', lazy_collect=False) - def state_dict(self) -> Dict[str, Any]: + @remote_function(execute="first", collect="first", lazy_collect=False) + def state_dict(self) -> dict[str, Any]: """Snapshot prompts, complete groups, ready groups and the open batch lease. Live episodes are paired with their last durable rollout turn checkpoint. A checkpoint taken @@ -684,81 +738,86 @@ def state_dict(self) -> Dict[str, Any]: with self._lock: state = self._snapshot() if self.resume_store is not None: - self.resume_store.save_object('driver', self.run_id, state) + self.resume_store.save_object("driver", self.run_id, state) return state - def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: + def _restore_episode(self, state: dict[str, Any], group: _Group) -> _Episode: episode = _Episode( - episode_id=str(state['episode_id']), group=group, role=str(state.get('role') or ''), - version=int(state.get('version') or 0)) - episode.traj = state.get('traj') - episode.sample = state.get('sample') - episode.done = bool(state.get('done')) - episode.finished = bool(state.get('finished')) - episode.lost = bool(state.get('lost')) - episode.orm = _load_pending(state.get('orm')) - episode.orm_pending = int(state.get('orm_pending') or 0) - episode.prm = _load_pending(state.get('prm')) - episode.prm_turns = list(state.get('prm_turns') or ()) - episode.prm_pending = int(state.get('prm_pending') or 0) - episode.held = state.get('held') - episode.deliver = list(state.get('deliver') or ()) - episode.submit_traj = state.get('submit_traj') + episode_id=str(state["episode_id"]), + group=group, + role=str(state.get("role") or ""), + version=int(state.get("version") or 0), + ) + episode.traj = state.get("traj") + episode.sample = state.get("sample") + episode.done = bool(state.get("done")) + episode.finished = bool(state.get("finished")) + episode.lost = bool(state.get("lost")) + episode.orm = _load_pending(state.get("orm")) + episode.orm_pending = int(state.get("orm_pending") or 0) + episode.prm = _load_pending(state.get("prm")) + episode.prm_turns = list(state.get("prm_turns") or ()) + episode.prm_pending = int(state.get("prm_pending") or 0) + episode.held = state.get("held") + episode.deliver = list(state.get("deliver") or ()) + episode.submit_traj = state.get("submit_traj") now = time.monotonic() - if state.get('no_slot_retry_in') is not None: - episode.no_slot_retry_at = now + float(state['no_slot_retry_in']) - if state.get('no_slot_deadline_in') is not None: - episode.no_slot_deadline = now + float(state['no_slot_deadline_in']) - episode.no_slot_attempts = int(state.get('no_slot_attempts') or 0) - episode.counted_inflight = bool(state.get('counted_inflight')) + if state.get("no_slot_retry_in") is not None: + episode.no_slot_retry_at = now + float(state["no_slot_retry_in"]) + if state.get("no_slot_deadline_in") is not None: + episode.no_slot_deadline = now + float(state["no_slot_deadline_in"]) + episode.no_slot_attempts = int(state.get("no_slot_attempts") or 0) + episode.counted_inflight = bool(state.get("counted_inflight")) return episode - def _restore_group(self, state: Dict[str, Any]) -> _Group: - members = state.get('members') or () - member_version = next( - (int(item.get('version') or 0) for item in members if item.get('version') is not None), 0) - version = int(state.get('version') if state.get('version') is not None else member_version) - adapter_path = state.get('adapter_path') - raw_binding = state.get('binding') + def _restore_group(self, state: dict[str, Any]) -> _Group: + members = state.get("members") or () + member_version = next((int(item.get("version") or 0) for item in members if item.get("version") is not None), 0) + version = int(state.get("version") if state.get("version") is not None else member_version) + adapter_path = state.get("adapter_path") + raw_binding = state.get("binding") if raw_binding is not None: try: binding = GroupPolicyBinding.from_dict(raw_binding) except (TypeError, ValueError) as exc: - raise UnsafeResume(f'invalid group policy binding: {exc}') from exc - if state.get('version') is not None and int(state['version']) != binding.policy_version: + raise UnsafeResume(f"invalid group policy binding: {exc}") from exc + if state.get("version") is not None and int(state["version"]) != binding.policy_version: raise UnsafeResume( - f'group binding version {binding.policy_version} disagrees with snapshot version ' - f'{state["version"]}') - if 'adapter_path' in state and state.get('adapter_path') != binding.adapter_path: - raise UnsafeResume('group binding adapter_path disagrees with the flat snapshot field') + f"group binding version {binding.policy_version} disagrees with snapshot version {state['version']}" + ) + if "adapter_path" in state and state.get("adapter_path") != binding.adapter_path: + raise UnsafeResume("group binding adapter_path disagrees with the flat snapshot field") version = binding.policy_version adapter_path = binding.adapter_path else: binding = GroupPolicyBinding( - state_key=str(state.get('state_key') or f'{self.run_id}/group/{state.get("key")}'), + state_key=str(state.get("state_key") or f"{self.run_id}/group/{state.get('key')}"), policy_version=version, adapter_path=adapter_path, ) - expected_state_key = f'{self.run_id}/group/{state.get("key")}' + expected_state_key = f"{self.run_id}/group/{state.get('key')}" if binding.state_key != expected_state_key: - raise UnsafeResume( - f'group binding state_key {binding.state_key!r} does not match {expected_state_key!r}') + raise UnsafeResume(f"group binding state_key {binding.state_key!r} does not match {expected_state_key!r}") # A legacy flat snapshot had no binding, so the manager may upgrade its # missing adapter path. An explicit binding with adapter_path=None # means the base model and must not be silently rebound to an adapter. if raw_binding is None and adapter_path is None and self.checkpoint_manager is not None: - lookup = getattr(self.checkpoint_manager, 'adapter_path', None) + lookup = getattr(self.checkpoint_manager, "adapter_path", None) if callable(lookup): adapter_path = lookup(version) if adapter_path is None: - raise UnsafeResume(f'policy version {version} has no resolvable adapter path') + raise UnsafeResume(f"policy version {version} has no resolvable adapter path") binding = replace(binding, adapter_path=adapter_path) group = _Group( - key=str(state['key']), row=state.get('row'), binding=binding, - attempt=int(state.get('attempt') or 0), - source=list(state.get('source') or ()), missing=int(state.get('missing') or 0)) - group.members = [self._restore_episode(item, group) for item in state.get('members') or ()] - group.baselines = [self._restore_episode(item, group) for item in state.get('baselines') or ()] + key=str(state["key"]), + row=state.get("row"), + binding=binding, + attempt=int(state.get("attempt") or 0), + source=list(state.get("source") or ()), + missing=int(state.get("missing") or 0), + ) + group.members = [self._restore_episode(item, group) for item in state.get("members") or ()] + group.baselines = [self._restore_episode(item, group) for item in state.get("baselines") or ()] return group def _resume_scores(self, episode: _Episode) -> None: @@ -768,74 +827,77 @@ def _resume_scores(self, episode: _Episode) -> None: continue future = self.orms[index]([episode.traj]) future.add_done_callback( - lambda f, episode=episode, index=index: self._events.put(('orm', episode, index, f))) + lambda f, episode=episode, index=index: self._events.put(("orm", episode, index, f)) + ) for scorer, column in enumerate(episode.prm or ()): for segment, value in enumerate(column): if value is not _PENDING: continue future = self.prms[scorer]([episode.traj]) future.add_done_callback( - lambda f, episode=episode, key=(segment, scorer): self._events.put(('prm', episode, key, f))) + lambda f, episode=episode, key=(segment, scorer): self._events.put(("prm", episode, key, f)) + ) def _resume_live_episode(self, episode: _Episode) -> None: if episode.finished or episode.lost or episode.done: if not episode.finished and not episode.lost: self._resume_scores(episode) return - self._counters['resumed_members'] += 1 - state_key = str((episode.submit_traj or {}).get('state_key') or '') - if self.resume_store is not None and state_key and self.resume_store.has_object('episodes', state_key): + self._counters["resumed_members"] += 1 + state_key = str((episode.submit_traj or {}).get("state_key") or "") + if self.resume_store is not None and state_key and self.resume_store.has_object("episodes", state_key): self.rollout.restore_episode_from_store(state_key) route = dict(episode.traj or episode.submit_traj or {}) - route.setdefault('turns', 0) + route.setdefault("turns", 0) self._step(episode, route) else: # No turn boundary committed yet: opening the episode again repeats no external tool call. self._step(episode, episode.submit_traj) - @remote_function(execute='first', collect='first', lazy_collect=False) - def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: + @remote_function(execute="first", collect="first", lazy_collect=False) + def load_state_dict(self, state: dict[str, Any] | None = None) -> None: """Rebuild a fresh driver from a snapshot, or from the store's latest snapshot.""" if state is None: if self.resume_store is None: - raise UnsafeResume('load_state_dict() without state needs a resume store') - state = self.resume_store.load_object('driver', self.run_id) - if state.get('format') != 'twinkle.streaming-driver.v1': - raise UnsafeResume('unsupported StreamingDriver checkpoint format') - if str(state.get('run_id')) != self.run_id: - raise UnsafeResume(f'driver snapshot belongs to run {state.get("run_id")!r}, not {self.run_id!r}') + raise UnsafeResume("load_state_dict() without state needs a resume store") + state = self.resume_store.load_object("driver", self.run_id) + if state.get("format") != "twinkle.streaming-driver.v1": + raise UnsafeResume("unsupported StreamingDriver checkpoint format") + if str(state.get("run_id")) != self.run_id: + raise UnsafeResume(f"driver snapshot belongs to run {state.get('run_id')!r}, not {self.run_id!r}") observed_version = int(self.checkpoint_manager.version()) if self.checkpoint_manager is not None else 0 with self._lock: if self._thread is not None or self._iter_started: - raise UnsafeResume('load_state_dict must run before the driver starts') + raise UnsafeResume("load_state_dict must run before the driver starts") self._groups = {} - for item in state.get('groups') or (): + for item in state.get("groups") or (): group = self._restore_group(item) self._groups[group.key] = group - ready_groups = {group.key: group for group in - (self._restore_group(item) for item in state.get('ready_groups') or ())} + ready_groups = { + group.key: group for group in (self._restore_group(item) for item in state.get("ready_groups") or ()) + } self._ready = deque() - for members in state.get('ready') or (): + for members in state.get("ready") or (): restored = [] for item in members: - key = str(item.get('group_key')) + key = str(item.get("group_key")) group = ready_groups.get(key) if group is None: - raise UnsafeResume(f'ready episode references unknown group {key!r}') + raise UnsafeResume(f"ready episode references unknown group {key!r}") restored.append(self._restore_episode(item, group)) self._ready.append(restored) self._ready_rows = sum(len(episode.deliver) for members in self._ready for episode in members) - self._handed = int(state.get('handed') or 0) - self._prompt_seq = int(state.get('prompts_drawn') or 0) - self._version = max(int(state.get('version') or 0), observed_version) - self._base_version = int(state.get('base_version') or 0) - self._exhausted = bool(state.get('exhausted')) - self._counters = dict(state.get('counters') or self._counters) - lease = state.get('lease') + self._handed = int(state.get("handed") or 0) + self._prompt_seq = int(state.get("prompts_drawn") or 0) + self._version = max(int(state.get("version") or 0), observed_version) + self._base_version = int(state.get("base_version") or 0) + self._exhausted = bool(state.get("exhausted")) + self._counters = dict(state.get("counters") or self._counters) + lease = state.get("lease") if lease is not None and self.resume_store is not None: last = self.resume_store.journal.last( - str(lease['lease_id']), events=(JournalEvent.BATCH_LEASED, - JournalEvent.MODEL_CHECKPOINT_COMMITTED)) + str(lease["lease_id"]), events=(JournalEvent.BATCH_LEASED, JournalEvent.MODEL_CHECKPOINT_COMMITTED) + ) if last is not None and last.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED: lease = None self._lease = lease @@ -844,19 +906,20 @@ def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: for group in list(self._groups.values()): if self.checkpoint_manager is not None and self._version - group.version > self.max_staleness: self._retire_stale_group(group) - self._live = sum(not episode.lost for group in self._groups.values() - for episode in group.members) + self._live = sum(not episode.lost for group in self._groups.values() for episode in group.members) self._live += sum(not episode.lost for members in self._ready for episode in members) - self._inflight = sum(episode.counted_inflight for group in self._groups.values() - for episode in group.members + group.baselines) - self._counters['resumed_groups'] += len(self._groups) - live = [episode for group in self._groups.values() - for episode in group.members + group.baselines] - loader_state = state.get('loader_state') - loader = getattr(self.dataloader, 'load_state_dict', None) or getattr(self.dataloader, 'set_state', None) + self._inflight = sum( + episode.counted_inflight + for group in self._groups.values() + for episode in group.members + group.baselines + ) + self._counters["resumed_groups"] += len(self._groups) + live = [episode for group in self._groups.values() for episode in group.members + group.baselines] + loader_state = state.get("loader_state") + loader = getattr(self.dataloader, "load_state_dict", None) or getattr(self.dataloader, "set_state", None) if loader_state is not None: if not callable(loader): - raise UnsafeResume('snapshot has DataLoader state but the dataloader cannot load it') + raise UnsafeResume("snapshot has DataLoader state but the dataloader cannot load it") loader(loader_state) for episode in live: self._resume_live_episode(episode) @@ -865,46 +928,52 @@ def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: self._settle(group) self._lock.notify_all() - @remote_function(execute='first', collect='first', lazy_collect=False) - def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, Any]] = None) -> Optional[str]: + @remote_function(execute="first", collect="first", lazy_collect=False) + def commit_batch(self, checkpoint_ref: str = "", manifest: dict[str, Any] | None = None) -> str | None: """Mark the open lease trained after its model checkpoint is durable.""" with self._lock: lease = self._lease if lease is None: return None if self.resume_store is not None and not checkpoint_ref: - raise UnsafeResume('commit_batch() needs the durable model checkpoint reference') - lease_id = str(lease['lease_id']) + raise UnsafeResume("commit_batch() needs the durable model checkpoint reference") + lease_id = str(lease["lease_id"]) if self.resume_store is not None: self.resume_store.journal.append( - JournalEvent.MODEL_CHECKPOINT_COMMITTED, lease_id, + JournalEvent.MODEL_CHECKPOINT_COMMITTED, + lease_id, { - 'checkpoint': str(checkpoint_ref), - 'batch': lease['batch'], - 'policy_versions': list(lease.get('policy_versions') or ()), - 'manifest': dict(manifest or {}), - }) - self.resume_store.delete_object('leases', lease_id) + "checkpoint": str(checkpoint_ref), + "batch": lease["batch"], + "policy_versions": list(lease.get("policy_versions") or ()), + "manifest": dict(manifest or {}), + }, + ) + self.resume_store.delete_object("leases", lease_id) self._lease = None self._lease_returned = False self._persist_snapshot_locked() self._lock.notify_all() return lease_id - @remote_function(execute='first', collect='first', lazy_collect=False) + @remote_function(execute="first", collect="first", lazy_collect=False) def close(self) -> None: """Stop admitting, stop the episodes in flight and end the background thread.""" with self._lock: self._closed = True - episodes = [episode for group in self._groups.values() - for episode in group.members + group.baselines if not episode.finished] + episodes = [ + episode + for group in self._groups.values() + for episode in group.members + group.baselines + if not episode.finished + ] self._lock.notify_all() for episode in episodes: if not episode.done: try: self.rollout.stop(episode.traj or {}, episode_id=episode.episode_id) except Exception as exc: # noqa: BLE001 -- best effort on the way out - logger.warning(f'StreamingDriver.close: stopping {episode.episode_id} failed: {exc}') + logger.warning(f"StreamingDriver.close: stopping {episode.episode_id} failed: {exc}") if self._thread is not None: self._thread.join(timeout=10) @@ -917,7 +986,7 @@ def _start(self) -> None: self._version = self._read_version() # the bound counts versions from here: a manager synced before the run starts above 0 self._base_version = self._version - self._thread = threading.Thread(target=self._run, name='twinkle-streaming-driver', daemon=True) + self._thread = threading.Thread(target=self._run, name="twinkle-streaming-driver", daemon=True) self._thread.start() def _run(self) -> None: @@ -934,8 +1003,9 @@ def _run(self) -> None: self._admit() self._retry_no_slot_due() self._lock.notify_all() - _record_driver_probe('admit', live=self._live, capacity=self._capacity(), - qsize=self._events.qsize(), version=version) + _record_driver_probe( + "admit", live=self._live, capacity=self._capacity(), qsize=self._events.qsize(), version=version + ) if version != adjusted: adjusted = version self._maybe_adjust() @@ -943,7 +1013,7 @@ def _run(self) -> None: event = self._events.get(timeout=0.1) except queue.Empty: continue - _record_driver_probe('event_dequeued', event[1].episode_id, kind=event[0]) + _record_driver_probe("event_dequeued", event[1].episode_id, kind=event[0]) while event is not None: self._handle(*event) try: @@ -951,8 +1021,8 @@ def _run(self) -> None: except queue.Empty: event = None except BaseException as exc: # noqa - _record_driver_probe('run_stopped', error=f'{type(exc).__name__}: {exc}') - logger.error(f'StreamingDriver stopped: {type(exc).__name__}: {exc}') + _record_driver_probe("run_stopped", error=f"{type(exc).__name__}: {exc}") + logger.error(f"StreamingDriver stopped: {type(exc).__name__}: {exc}") with self._lock: self._error = exc self._lock.notify_all() @@ -980,9 +1050,11 @@ def _maybe_adjust(self) -> None: stuck = now - self._adjust_started if stuck >= self.ADJUST_STUCK_TIMEOUT and now - self._adjust_reported >= self.ADJUST_STUCK_TIMEOUT: self._adjust_reported = now - logger.warning(f'cluster adapter adjust has been running for {stuck:.0f}s ' - '(a large weight warm takes this long too and a stuck RPC looks ' - 'the same); rebalancing is paused until it returns') + logger.warning( + f"cluster adapter adjust has been running for {stuck:.0f}s " + "(a large weight warm takes this long too and a stuck RPC looks " + "the same); rebalancing is paused until it returns" + ) return self._adjusting = True self._adjust_started = time.monotonic() @@ -991,18 +1063,18 @@ def _adjust(): try: self.cluster_adapter.adjust() except Exception as exc: # noqa: BLE001 -- rebalancing is an optimisation, never fatal - logger.warning(f'cluster adapter adjust failed: {type(exc).__name__}: {exc}') + logger.warning(f"cluster adapter adjust failed: {type(exc).__name__}: {exc}") finally: self._adjusting = False - threading.Thread(target=_adjust, name='twinkle-cluster-adjust', daemon=True).start() + threading.Thread(target=_adjust, name="twinkle-cluster-adjust", daemon=True).start() def _lend(self, waited: float) -> None: """Run ``lend`` while the trainer waits; ``reclaim`` joins this thread before undoing it.""" try: self.cluster_adapter.lend(self._idle_ratio, waited=waited) except Exception as exc: # noqa: BLE001 -- lending is an optimisation, never fatal - logger.warning(f'cluster adapter lend failed: {type(exc).__name__}: {exc}') + logger.warning(f"cluster adapter lend failed: {type(exc).__name__}: {exc}") # ------------------------------------------------------------------ admission @@ -1030,14 +1102,15 @@ def _admit(self) -> None: version = self._version adapter_path = None if self.checkpoint_manager is not None: - lookup = getattr(self.checkpoint_manager, 'adapter_path', None) + lookup = getattr(self.checkpoint_manager, "adapter_path", None) if callable(lookup): adapter_path = lookup(version) if adapter_path is None: raise UnsafeResume( - f'checkpoint manager has no adapter path for admitted policy version {version}') + f"checkpoint manager has no adapter path for admitted policy version {version}" + ) binding = GroupPolicyBinding( - state_key=f'{self.run_id}/group/{key}', + state_key=f"{self.run_id}/group/{key}", policy_version=version, adapter_path=adapter_path, ) @@ -1045,12 +1118,14 @@ def _admit(self) -> None: self._groups[key] = group self._start_attempt(group, [copy.deepcopy(row) for _ in range(self.num_generations)]) if self.resume_store is not None: - prompt_key = f'{self.run_id}/prompt/{key}' - self.resume_store.save_object('prompts', prompt_key, row) + prompt_key = f"{self.run_id}/prompt/{key}" + self.resume_store.save_object("prompts", prompt_key, row) self._persist_snapshot_locked() self.resume_store.journal.append( - JournalEvent.PROMPT_ASSIGNED, prompt_key, - {'group_key': key, 'object': prompt_key, 'binding': binding.to_dict()}) + JournalEvent.PROMPT_ASSIGNED, + prompt_key, + {"group_key": key, "object": prompt_key, "binding": binding.to_dict()}, + ) def _next_row(self) -> Any: # TODO: rows are drawn here, ahead of training; see state_dict for what a resume skips. @@ -1060,7 +1135,7 @@ def _next_row(self) -> Any: def _iter_rows(self) -> Iterator[Any]: for epoch in range(max(1, math.ceil(self.num_epochs))): - set_epoch = getattr(self.dataloader, 'set_epoch', None) + set_epoch = getattr(self.dataloader, "set_epoch", None) if set_epoch is not None: set_epoch(epoch) for batch in self.dataloader: @@ -1069,7 +1144,7 @@ def _iter_rows(self) -> Iterator[Any]: else: yield batch - def _start_attempt(self, group: _Group, trajectories: List[Any]) -> None: + def _start_attempt(self, group: _Group, trajectories: list[Any]) -> None: """Submit one attempt's trajectories: the non-baseline ones replace the members (under the lock).""" members = [traj for traj in trajectories if _role_of(traj) != _BASELINE] baselines = [traj for traj in trajectories if _role_of(traj) == _BASELINE] @@ -1078,29 +1153,34 @@ def _start_attempt(self, group: _Group, trajectories: List[Any]) -> None: group.members = [] group.missing = 0 self._live += len(members) - self._counters['admitted'] += len(members) + self._counters["admitted"] += len(members) group.baselines = [] for index, traj in enumerate(members): # Positional sample identity within the group: the rollout derives a per-request seed # from (group_key, sample_index) so a group's num_generations samples differ. A constant # seed would collapse them to one identical trajectory and zero the group's advantage. - traj['sample_index'] = index - group.members.append(self._submit(group, traj, '', index)) + traj["sample_index"] = index + group.members.append(self._submit(group, traj, "", index)) for index, traj in enumerate(baselines): group.baselines.append(self._submit(group, traj, _BASELINE, index)) def _submit(self, group: _Group, traj: Any, role: str, slot: int) -> _Episode: - kind = 'baseline' if role == _BASELINE else 'member' - episode_id = f'{self.run_id}:g{group.key}:a{group.attempt}:{kind}:{slot}' + kind = "baseline" if role == _BASELINE else "member" + episode_id = f"{self.run_id}:g{group.key}:a{group.attempt}:{kind}:{slot}" episode = _Episode(episode_id=episode_id, group=group, role=role, version=group.version) # The identity travels on top of the trajectory: episode / group / role / the admission # version. The rollout reads the episode id to route its steps back to this episode. traj = dict(traj) - traj.update(episode_id=episode.episode_id, group_key=group.key, role=role, - policy_version=group.version, group_attempt=group.attempt, - state_key=f'{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}') + traj.update( + episode_id=episode.episode_id, + group_key=group.key, + role=role, + policy_version=group.version, + group_attempt=group.attempt, + state_key=f"{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}", + ) if group.adapter_path is not None: - traj['adapter_path'] = group.adapter_path + traj["adapter_path"] = group.adapter_path episode.submit_traj = traj self._inflight += 1 episode.counted_inflight = True @@ -1111,30 +1191,30 @@ def _step(self, episode: _Episode, traj: Any) -> None: # session_wait=0: the admission loop never blocks on a full session pool -- a no-slot status # comes back along the return channel and the member is retried later (see _no_slot). future = self.rollout.step(traj, episode_id=episode.episode_id, session_wait=0) - _record_driver_probe('step_submitted', episode.episode_id) + _record_driver_probe("step_submitted", episode.episode_id) def _done(f, episode=episode): - _record_driver_probe('step_future_done', episode.episode_id) - self._events.put(('step', episode, None, f)) + _record_driver_probe("step_future_done", episode.episode_id) + self._events.put(("step", episode, None, f)) future.add_done_callback(_done) # ------------------------------------------------------------------ completions - def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: Any) -> None: - _record_driver_probe('handle', episode.episode_id, kind=kind) + def _handle(self, kind: str, episode: _Episode, index: int | None, future: Any) -> None: + _record_driver_probe("handle", episode.episode_id, kind=kind) exc = future.exception() with self._lock: if self._closed: return if episode.lost: - if kind == 'step' and exc is None and not future.result()[1].done: + if kind == "step" and exc is None and not future.result()[1].done: # dropped while this step ran: release its rollout state now self.rollout.stop(future.result()[0][0], episode_id=episode.episode_id) return - if exc is not None and not (kind == 'step' and _is_episode_error(exc)): + if exc is not None and not (kind == "step" and _is_episode_error(exc)): raise exc - if kind == 'step': + if kind == "step": if exc is not None: self._fail(episode, exc) else: @@ -1146,7 +1226,7 @@ def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: An self._no_slot(episode) else: self._on_step(episode, rows, sample) - elif kind == 'orm': + elif kind == "orm": episode.orm[index] = future.result()[0] episode.orm_pending -= 1 self._maybe_finish(episode) @@ -1155,7 +1235,8 @@ def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: An episode.prm[scorer][segment] = future.result()[0] episode.prm_pending -= 1 if episode.held == segment and not any( - episode.prm[k][segment] is _PENDING for k in range(len(self.prms))): + episode.prm[k][segment] is _PENDING for k in range(len(self.prms)) + ): self._release(episode, segment) self._maybe_finish(episode) self._lock.notify_all() @@ -1166,8 +1247,11 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None episode.done = bool(sample.done) if episode.done: episode.deliver = list(trajs) - if self.prms and episode.role != _BASELINE and (episode.done or self.prm_segment is None - or self.prm_segment(sample, trajs[0])): + if ( + self.prms + and episode.role != _BASELINE + and (episode.done or self.prm_segment is None or self.prm_segment(sample, trajs[0])) + ): segment = self._score_prm(episode) if self.on_step is not None and not episode.done: episode.held = segment @@ -1189,7 +1273,8 @@ def _score_prm(self, episode: _Episode) -> int: episode.prm_pending += 1 future = prm([episode.traj]) future.add_done_callback( - lambda f, episode=episode, key=(segment, scorer): self._events.put(('prm', episode, key, f))) + lambda f, episode=episode, key=(segment, scorer): self._events.put(("prm", episode, key, f)) + ) return segment def _release(self, episode: _Episode, segment: int) -> None: @@ -1198,7 +1283,7 @@ def _release(self, episode: _Episode, segment: int) -> None: if self.on_step(episode.sample, [column[segment] for column in episode.prm]): self._step(episode, episode.traj) return - self._counters['stopped'] += 1 + self._counters["stopped"] += 1 self.rollout.stop(episode.traj, episode_id=episode.episode_id) self._lose(episode) @@ -1208,19 +1293,23 @@ def _score_orm(self, episode: _Episode) -> None: for index, orm in enumerate(self.orms): future = orm([episode.traj]) future.add_done_callback( - lambda f, episode=episode, index=index: self._events.put(('orm', episode, index, f))) + lambda f, episode=episode, index=index: self._events.put(("orm", episode, index, f)) + ) self._maybe_finish(episode) def _fail(self, episode: _Episode, exc: BaseException) -> None: - self._counters['episode_errors'] += 1 + self._counters["episode_errors"] += 1 self._consecutive_failures += 1 self._failures.append(True) - logger.warning(f'episode {episode.episode_id} skipped: {exc}') + logger.warning(f"episode {episode.episode_id} skipped: {exc}") if self._consecutive_failures >= self.MAX_CONSECUTIVE_FAILURES or ( - len(self._failures) == self.FAILURE_WINDOW - and sum(self._failures) > self.MAX_FAILURE_RATE * self.FAILURE_WINDOW): - raise RuntimeError(f'too many episodes fail ({self._consecutive_failures} in a row, ' - f'{sum(self._failures)} of the last {len(self._failures)}); last: {exc}') from exc + len(self._failures) == self.FAILURE_WINDOW + and sum(self._failures) > self.MAX_FAILURE_RATE * self.FAILURE_WINDOW + ): + raise RuntimeError( + f"too many episodes fail ({self._consecutive_failures} in a row, " + f"{sum(self._failures)} of the last {len(self._failures)}); last: {exc}" + ) from exc self._lose(episode) def _lose(self, episode: _Episode) -> None: @@ -1247,7 +1336,7 @@ def _no_slot(self, episode: _Episode) -> None: """ self._inflight -= 1 episode.counted_inflight = False - self._counters['no_slot'] += 1 + self._counters["no_slot"] += 1 now = time.monotonic() if episode.no_slot_deadline is None: episode.no_slot_deadline = now + self.max_no_slot_wait @@ -1272,10 +1361,12 @@ def _retry_no_slot_due(self) -> None: if episode.no_slot_retry_at is None or episode.no_slot_retry_at > now: continue if episode.no_slot_deadline is not None and now > episode.no_slot_deadline: - self._counters['no_slot_dropped'] += 1 - logger.warning(f'group {group.key} dropped: member {episode.episode_id} could not get ' - f'a session slot within {self.max_no_slot_wait:.0f}s ' - f'({episode.no_slot_attempts} no-slot retries)') + self._counters["no_slot_dropped"] += 1 + logger.warning( + f"group {group.key} dropped: member {episode.episode_id} could not get " + f"a session slot within {self.max_no_slot_wait:.0f}s " + f"({episode.no_slot_attempts} no-slot retries)" + ) self._drop_group(group) break episode.no_slot_retry_at = None @@ -1304,7 +1395,7 @@ def _maybe_finish(self, episode: _Episode) -> None: sample.prm_rewards = [list(column) for column in episode.prm] sample.extra = dict(sample.extra or {}, **{PRM_SEGMENT_TURNS: list(episode.prm_turns)}) if episode.role != _BASELINE and self.on_sample is not None and self.on_sample(sample) is False: - self._counters['dropped_sample'] += 1 + self._counters["dropped_sample"] += 1 self._lose(episode) return episode.finished = True @@ -1328,14 +1419,14 @@ def _settle(self, group: _Group) -> None: self._drop_group(group) return group.attempt += 1 - self._counters['regenerated'] += 1 + self._counters["regenerated"] += 1 # the lost members are redone from their trajectories; the scored ones stay self._live += group.missing - self._counters['admitted'] += group.missing + self._counters["admitted"] += group.missing group.missing = 0 for index, episode in enumerate(group.members): if episode.lost: - group.members[index] = self._submit(group, copy.deepcopy(group.source[index]), '', index) + group.members[index] = self._submit(group, copy.deepcopy(group.source[index]), "", index) return if group.baselines: rows = [list(e.sample.orm_reward) for e in group.baselines] @@ -1349,12 +1440,14 @@ def _settle(self, group: _Group) -> None: trajectories = list(self.on_group(group.row, [e.sample for e in group.members], group.attempt) or []) regenerate = [t for t in trajectories if _role_of(t) != _BASELINE] if regenerate and len(regenerate) != self.num_generations: - raise ValueError(f'on_group returned {len(regenerate)} trajectories to replace a group of ' - f'{self.num_generations}; a group is always num_generations rows.') + raise ValueError( + f"on_group returned {len(regenerate)} trajectories to replace a group of " + f"{self.num_generations}; a group is always num_generations rows." + ) if regenerate and group.attempt < self.max_group_regenerations: # baselines returned alongside wait: the replaced group is offered to on_group again self._live -= len(group.members) - self._counters['regenerated'] += 1 + self._counters["regenerated"] += 1 group.attempt += 1 self._start_attempt(group, regenerate) return @@ -1370,18 +1463,22 @@ def _accept(self, group: _Group) -> None: self._ready_rows += sum(len(episode.deliver) for episode in group.members) if self.resume_store is not None: self._persist_snapshot_locked() - self.resume_store.journal.append(JournalEvent.GROUP_READY, group.state_key, { - 'group_key': group.key, - 'binding': group.binding.to_dict(), - 'attempt': group.attempt, - 'episodes': [episode.episode_id for episode in group.members], - }) + self.resume_store.journal.append( + JournalEvent.GROUP_READY, + group.state_key, + { + "group_key": group.key, + "binding": group.binding.to_dict(), + "attempt": group.attempt, + "episodes": [episode.episode_id for episode in group.members], + }, + ) def _drop_group(self, group: _Group) -> None: """Give the group up: its counted rows leave the bound, its unfinished episodes stop (under the lock).""" if self._groups.pop(group.key, None) is None: return - self._counters['dropped_group'] += 1 + self._counters["dropped_group"] += 1 for episode in group.members + group.baselines: if episode.lost: continue @@ -1396,15 +1493,20 @@ def _drop_group(self, group: _Group) -> None: self.rollout.stop(episode.traj, episode_id=episode.episode_id) if self.resume_store is not None: self.resume_store.journal.append( - JournalEvent.GROUP_DROPPED, group.state_key, - {'reason': 'incomplete_or_invalid', 'binding': group.binding.to_dict(), - 'current_version': self._version}) + JournalEvent.GROUP_DROPPED, + group.state_key, + { + "reason": "incomplete_or_invalid", + "binding": group.binding.to_dict(), + "current_version": self._version, + }, + ) self._persist_snapshot_locked() #: Placeholder for a score whose Future has not completed yet. _PENDING = object() -_PENDING_KEY = '__twinkle_streaming_pending__' +_PENDING_KEY = "__twinkle_streaming_pending__" def _dump_pending(value: Any) -> Any: diff --git a/src/twinkle_agentic/envs/__init__.py b/src/twinkle_agentic/envs/__init__.py index 518974bec..624e59a79 100644 --- a/src/twinkle_agentic/envs/__init__.py +++ b/src/twinkle_agentic/envs/__init__.py @@ -7,7 +7,20 @@ from .resume import EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, env_resume_capability __all__ = [ - 'AgentEnv', 'AgentSandbox', 'ClientSession', 'Env', 'EnvTool', 'LocalEnv', 'NoSlot', 'OpenEnv', 'OpenEnvClient', - 'EnvResumeCapability', 'ResumableEnv', 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', - 'UnsupportedEnvResume', 'env_resume_capability' + "AgentEnv", + "AgentSandbox", + "ClientSession", + "Env", + "EnvTool", + "LocalEnv", + "NoSlot", + "OpenEnv", + "OpenEnvClient", + "EnvResumeCapability", + "ResumableEnv", + "SessionNotFound", + "StepResult", + "UnsafeCheckpoint", + "UnsupportedEnvResume", + "env_resume_capability", ] diff --git a/src/twinkle_agentic/envs/base.py b/src/twinkle_agentic/envs/base.py index 673e87851..6aeae02ec 100644 --- a/src/twinkle_agentic/envs/base.py +++ b/src/twinkle_agentic/envs/base.py @@ -2,15 +2,15 @@ import threading import time from abc import ABC, abstractmethod +from collections.abc import Sequence from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Sequence, Tuple +from typing import Any from twinkle import remote_function from twinkle.data_format import Trajectory from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .resume import (EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, - env_resume_capability) +from .resume import EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, env_resume_capability from .snapshot import list_workspace logger = get_logger() @@ -26,14 +26,16 @@ def _record_tool_exec(episode_id: str, n: int) -> None: tool_call, so it is deliberately not counted. Write-only and env-gated: a no-op when unset. """ import os - root = os.environ.get('TWINKLE_ROLLOUT_TRAJ_DUMP') + + root = os.environ.get("TWINKLE_ROLLOUT_TRAJ_DUMP") if not root: return import json + os.makedirs(root, exist_ok=True) - rank = int(os.environ.get('RANK') or os.environ.get('LOCAL_RANK') or 0) - with open(os.path.join(root, f'tool_counts.rank{rank}.jsonl'), 'a', encoding='utf-8') as handle: - handle.write(json.dumps({'episode_id': episode_id, 'executed': int(n)}) + '\n') + rank = int(os.environ.get("RANK") or os.environ.get("LOCAL_RANK") or 0) + with open(os.path.join(root, f"tool_counts.rank{rank}.jsonl"), "a", encoding="utf-8") as handle: + handle.write(json.dumps({"episode_id": episode_id, "executed": int(n)}) + "\n") # What :meth:`Env.run_script` returns when it had to kill the script. 124 is @@ -53,63 +55,48 @@ def _record_tool_exec(episode_id: str, n: int) -> None: # Shared rather than restated per implementation: a trajectory built against one # env has to replay on another, and it only does if the names and the argument # spellings are the same object. -DEFAULT_TOOLS: List[ToolInfo] = [ +DEFAULT_TOOLS: list[ToolInfo] = [ { - 'type': 'function', - 'function': { - 'name': 'run_command', - 'description': 'Run a shell command inside the sandbox and return its output.', - 'parameters': { - 'type': 'object', - 'properties': { - 'command': { - 'type': 'string', - 'description': 'The shell command to execute.' - }, - 'cwd': { - 'type': 'string', - 'description': 'Working directory (optional).' - }, + "type": "function", + "function": { + "name": "run_command", + "description": "Run a shell command inside the sandbox and return its output.", + "parameters": { + "type": "object", + "properties": { + "command": {"type": "string", "description": "The shell command to execute."}, + "cwd": {"type": "string", "description": "Working directory (optional)."}, }, - 'required': ['command'], + "required": ["command"], }, }, }, { - 'type': 'function', - 'function': { - 'name': 'write_file', - 'description': 'Write text content to a file inside the sandbox.', - 'parameters': { - 'type': 'object', - 'properties': { - 'path': { - 'type': 'string', - 'description': 'Absolute file path in the sandbox.' - }, - 'content': { - 'type': 'string', - 'description': 'Text content to write.' - }, + "type": "function", + "function": { + "name": "write_file", + "description": "Write text content to a file inside the sandbox.", + "parameters": { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Absolute file path in the sandbox."}, + "content": {"type": "string", "description": "Text content to write."}, }, - 'required': ['path', 'content'], + "required": ["path", "content"], }, }, }, { - 'type': 'function', - 'function': { - 'name': 'read_file', - 'description': 'Read a text file from the sandbox.', - 'parameters': { - 'type': 'object', - 'properties': { - 'path': { - 'type': 'string', - 'description': 'Absolute file path in the sandbox.' - }, + "type": "function", + "function": { + "name": "read_file", + "description": "Read a text file from the sandbox.", + "parameters": { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Absolute file path in the sandbox."}, }, - 'required': ['path'], + "required": ["path"], }, }, }, @@ -119,7 +106,7 @@ def _record_tool_exec(episode_id: str, n: int) -> None: def truncate_observation(text: str, limit: int = MAX_OBSERVATION_CHARS) -> str: if len(text) <= limit: return text - return text[:limit] + f'\n... [truncated, {len(text) - limit} chars omitted]' + return text[:limit] + f"\n... [truncated, {len(text) - limit} chars omitted]" def format_command_output(stdout: str, stderr: str, exit_code: int) -> str: @@ -128,19 +115,20 @@ def format_command_output(stdout: str, stderr: str, exit_code: int) -> str: if stdout: parts.append(stdout) if stderr: - parts.append(f'[stderr]\n{stderr}') + parts.append(f"[stderr]\n{stderr}") if exit_code != 0: - parts.append(f'[exit code: {exit_code}]') - return truncate_observation('\n'.join(parts)) if parts else '(no output)' + parts.append(f"[exit code: {exit_code}]") + return truncate_observation("\n".join(parts)) if parts else "(no output)" @dataclass class StepResult: """Result returned by :meth:`Env.step`.""" - observation: str = '' + + observation: str = "" reward: float = 0.0 done: bool = False - info: Dict[str, Any] = field(default_factory=dict) + info: dict[str, Any] = field(default_factory=dict) class SessionNotFound(KeyError): @@ -160,7 +148,7 @@ class NoSlot: class _Session: - __slots__ = ('state', 'reward', 'touched', 'script_inflight') + __slots__ = ("state", "reward", "touched", "script_inflight") def __init__(self, state: Any): self.state = state @@ -206,7 +194,7 @@ class Env(ABC): snapshot_max_files = 40 snapshot_per_file = 2000 snapshot_budget = 20000 - snapshot_skip = ('__pycache__', '.git', '.ipynb_checkpoints') + snapshot_skip = ("__pycache__", ".git", ".ipynb_checkpoints") #: Seconds a session may go untouched before the next ``reset`` closes it: a caller that died #: or never called ``close`` would otherwise hold a sandbox forever. @@ -214,10 +202,10 @@ class Env(ABC): #: Seconds ``reset`` waits for a free session before it gives up with ``TimeoutError``. session_wait_timeout = 600.0 - def __init__(self, max_sessions: int = 64, session_wait_timeout: Optional[float] = 600.0): + def __init__(self, max_sessions: int = 64, session_wait_timeout: float | None = 600.0): self._max_sessions = max(1, int(max_sessions)) self._session_slots = threading.Semaphore(self._max_sessions) - self._sessions: Dict[str, _Session] = {} + self._sessions: dict[str, _Session] = {} self._sessions_lock = threading.Lock() #: Instance default for how long ``reset`` waits for a free permit; a per-call ``wait`` #: override (see :meth:`reset`) takes precedence. Three states: positive = wait up to this @@ -229,20 +217,20 @@ def __init__(self, max_sessions: int = 64, session_wait_timeout: Optional[float] # ------------------------------------------------------------------ @abstractmethod - def _open(self, trajectory: Optional[Trajectory]) -> Tuple[Any, StepResult]: + def _open(self, trajectory: Trajectory | None) -> tuple[Any, StepResult]: """Start one episode; returns its state and the initial observation.""" @abstractmethod - def _step(self, state: Any, tool_name: str, arguments: Dict[str, Any]) -> StepResult: + def _step(self, state: Any, tool_name: str, arguments: dict[str, Any]) -> StepResult: """Run one tool call in the episode.""" - def _run_script(self, state: Any, source: str, interpreter: str, timeout: Optional[float]) -> Tuple[int, str]: - raise NotImplementedError(f'{type(self).__name__} cannot run scripts; act through its tools instead.') + def _run_script(self, state: Any, source: str, interpreter: str, timeout: float | None) -> tuple[int, str]: + raise NotImplementedError(f"{type(self).__name__} cannot run scripts; act through its tools instead.") def _close(self, state: Any) -> None: - pass + return None - def _workspace(self, state: Any) -> Optional[str]: + def _workspace(self, state: Any) -> str | None: return None # ------------------------------------------------------------------ @@ -253,22 +241,26 @@ def _session(self, episode_id: str) -> _Session: with self._sessions_lock: session = self._sessions.get(episode_id) if session is None: - raise SessionNotFound(f'{type(self).__name__}: no open session for episode {episode_id!r}.') + raise SessionNotFound(f"{type(self).__name__}: no open session for episode {episode_id!r}.") session.touched = time.monotonic() return session def _close_idle_sessions(self) -> None: now = time.monotonic() with self._sessions_lock: - idle = [eid for eid, session in self._sessions.items() - if not session.script_inflight and now - session.touched > self.session_idle_timeout] + idle = [ + eid + for eid, session in self._sessions.items() + if not session.script_inflight and now - session.touched > self.session_idle_timeout + ] for eid in idle: - logger.warning(f'{type(self).__name__}: closing session {eid!r}, idle for over ' - f'{self.session_idle_timeout:.0f}s.') + logger.warning( + f"{type(self).__name__}: closing session {eid!r}, idle for over {self.session_idle_timeout:.0f}s." + ) self.close(eid) - @remote_function(enable_continous_work=True, sticky_key='episode_id') - def reset(self, episode_id: str, traj: Optional[Trajectory] = None, wait: Optional[float] = None) -> Any: + @remote_function(enable_continous_work=True, sticky_key="episode_id") + def reset(self, episode_id: str, traj: Trajectory | None = None, wait: float | None = None) -> Any: """Open the episode's session (closing an earlier one under the same id); returns the first observation. ``wait`` overrides the instance :attr:`session_wait_timeout` for this call only: a positive @@ -291,13 +283,14 @@ def reset(self, episode_id: str, traj: Optional[Trajectory] = None, wait: Option with self._sessions_lock: now = time.monotonic() holders = sorted((eid, now - session.touched) for eid, session in self._sessions.items()) - detail = ', '.join(f'{eid} idle {age:.0f}s' for eid, age in holders[:8]) + detail = ", ".join(f"{eid} idle {age:.0f}s" for eid, age in holders[:8]) raise TimeoutError( - f'{type(self).__name__}: no free session within {effective:.0f}s ' - f'({self._max_sessions} permits, {len(holders)} sessions registered). ' - f'Holders: {detail or "none"}. ' - 'Fewer registered sessions than permits means the missing permits are held by resets ' - 'still inside _open, or were stranded by an earlier overwrite.') + f"{type(self).__name__}: no free session within {effective:.0f}s " + f"({self._max_sessions} permits, {len(holders)} sessions registered). " + f"Holders: {detail or 'none'}. " + "Fewer registered sessions than permits means the missing permits are held by resets " + "still inside _open, or were stranded by an earlier overwrite." + ) try: state, result = self._open(traj) except BaseException: @@ -314,22 +307,25 @@ def reset(self, episode_id: str, traj: Optional[Trajectory] = None, wait: Option try: self._close(displaced.state) except Exception: # noqa - logger.warning(f'{type(self).__name__}: closing the session displaced by a concurrent ' - f'reset of episode {episode_id!r} failed.', exc_info=True) + logger.warning( + f"{type(self).__name__}: closing the session displaced by a concurrent " + f"reset of episode {episode_id!r} failed.", + exc_info=True, + ) finally: self._session_slots.release() return result - @remote_function(enable_continous_work=True, sticky_key='episode_id') - def step(self, episode_id: str, tool_name: str, arguments: Optional[Dict[str, Any]] = None) -> StepResult: + @remote_function(enable_continous_work=True, sticky_key="episode_id") + def step(self, episode_id: str, tool_name: str, arguments: dict[str, Any] | None = None) -> StepResult: session = self._session(episode_id) result = self._step(session.state, tool_name, arguments or {}) session.reward += float(result.reward or 0.0) _record_tool_exec(episode_id, 1) return result - @remote_function(enable_continous_work=True, sticky_key='episode_id') - def step_batch(self, episode_id: str, calls: Sequence[Tuple[str, Dict[str, Any]]]) -> List[StepResult]: + @remote_function(enable_continous_work=True, sticky_key="episode_id") + def step_batch(self, episode_id: str, calls: Sequence[tuple[str, dict[str, Any]]]) -> list[StepResult]: """Execute already-parsed ``(tool_name, arguments)`` pairs in order, in one round trip.""" session = self._session(episode_id) results = [] @@ -340,12 +336,10 @@ def step_batch(self, episode_id: str, calls: Sequence[Tuple[str, Dict[str, Any]] _record_tool_exec(episode_id, len(results)) return results - @remote_function(enable_continous_work=True, sticky_key='episode_id') - def run_script(self, - episode_id: str, - source: str, - interpreter: str = 'python', - timeout: Optional[float] = None) -> Tuple[int, str]: + @remote_function(enable_continous_work=True, sticky_key="episode_id") + def run_script( + self, episode_id: str, source: str, interpreter: str = "python", timeout: float | None = None + ) -> tuple[int, str]: """Run a whole script in the episode's session; returns ``(exit_code, output)``. The execution path a *verifier* (or an agent program) takes, as opposed to :meth:`step`, @@ -372,13 +366,13 @@ def run_script(self, finally: session.script_inflight = False - @remote_function(enable_continous_work=True, sticky_key='episode_id') - def workspace(self, episode_id: str) -> Optional[str]: + @remote_function(enable_continous_work=True, sticky_key="episode_id") + def workspace(self, episode_id: str) -> str | None: """The directory the episode works in, or None for an environment that keeps none.""" return self._workspace(self._session(episode_id).state) - @remote_function(enable_continous_work=True, sticky_key='episode_id') - def snapshot(self, episode_id: str) -> Tuple[str, str]: + @remote_function(enable_continous_work=True, sticky_key="episode_id") + def snapshot(self, episode_id: str) -> tuple[str, str]: """The episode's end state as ``(listing, error)``; both empty when there is none. What an episode left behind, for a caller that has to describe it to a @@ -390,13 +384,14 @@ def snapshot(self, episode_id: str) -> Tuple[str, str]: state = self._session(episode_id).state return list_workspace( self._workspace(state), - lambda source: self._run_script(state, source, 'python', None), + lambda source: self._run_script(state, source, "python", None), max_files=self.snapshot_max_files, per_file=self.snapshot_per_file, budget=self.snapshot_budget, - skip=self.snapshot_skip) + skip=self.snapshot_skip, + ) - @remote_function(enable_continous_work=True, sticky_key='episode_id') + @remote_function(enable_continous_work=True, sticky_key="episode_id") def close(self, episode_id: str) -> float: """End the episode's session and return its reward (the sum of its step rewards). @@ -409,12 +404,12 @@ def close(self, episode_id: str) -> float: try: self._close(session.state) except Exception: # noqa - logger.warning(f'{type(self).__name__}: closing session {episode_id!r} failed.', exc_info=True) + logger.warning(f"{type(self).__name__}: closing session {episode_id!r} failed.", exc_info=True) finally: self._session_slots.release() return session.reward - @remote_function(dispatch='all', collect='first', lazy_collect=False) + @remote_function(dispatch="all", collect="first", lazy_collect=False) def shutdown(self) -> None: """Close every open session.""" with self._sessions_lock: @@ -422,8 +417,8 @@ def shutdown(self) -> None: for episode_id in episode_ids: self.close(episode_id) - @remote_function(execute='first', collect='first', lazy_collect=False) - def tools(self) -> List[ToolInfo]: + @remote_function(execute="first", collect="first", lazy_collect=False) + def tools(self) -> list[ToolInfo]: """What the model is told it can call in an episode.""" return [] diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 55a2df0ef..60b270a14 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -21,8 +21,8 @@ Every episode gets its own directory under ``root`` as the working directory of all its calls; closing the episode removes it, and kills whatever it still had running. """ + import hashlib -import json import os import resource import shlex @@ -35,13 +35,22 @@ import time import uuid from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any + +import json from twinkle import remote_class, remote_function from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, StepResult, format_command_output, - truncate_observation) +from .base import ( + DEFAULT_TOOLS, + ENV_MAX_CONCURRENCY, + TIMEOUT_EXIT_CODE, + Env, + StepResult, + format_command_output, + truncate_observation, +) from .resume import EnvResumeCapability, UnsafeCheckpoint logger = get_logger() @@ -49,11 +58,11 @@ # Kept deterministic and single-threaded: a check that changes its answer with # the machine's core count is not a check. Matches what the sandboxes set. _SCRIPT_ENVS = { - 'MPLBACKEND': 'Agg', - 'PYTHONHASHSEED': '0', - 'OMP_NUM_THREADS': '1', - 'MKL_NUM_THREADS': '1', - 'TOKENIZERS_PARALLELISM': 'false', + "MPLBACKEND": "Agg", + "PYTHONHASHSEED": "0", + "OMP_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "TOKENIZERS_PARALLELISM": "false", } @@ -73,13 +82,15 @@ class LocalEnv(Env): resume_capability = EnvResumeCapability.DURABLE_CHECKPOINT - def __init__(self, - root: Optional[str] = None, - max_sessions: int = 64, - command_timeout: int = 60, - memory_limit_gb: Optional[float] = 2.0, - envs: Optional[Dict[str, str]] = None, - session_wait_timeout: Optional[float] = 600.0): + def __init__( + self, + root: str | None = None, + max_sessions: int = 64, + command_timeout: int = 60, + memory_limit_gb: float | None = 2.0, + envs: dict[str, str] | None = None, + session_wait_timeout: float | None = 600.0, + ): """ Args: root: directory holding the episodes' working directories, created if absent; a fresh @@ -94,19 +105,19 @@ def __init__(self, ``wait`` overrides it); ``None`` waits forever, ``0`` returns NoSlot immediately. """ super().__init__(max_sessions, session_wait_timeout=session_wait_timeout) - self._root = os.path.abspath(root) if root else tempfile.mkdtemp(prefix='twinkle_localenv_') + self._root = os.path.abspath(root) if root else tempfile.mkdtemp(prefix="twinkle_localenv_") os.makedirs(self._root, exist_ok=True) self._command_timeout = command_timeout self._memory_limit_gb = memory_limit_gb self._envs = dict(envs or {}) - self._resume_root = Path(self._root) / '.twinkle-resume' + self._resume_root = Path(self._root) / ".twinkle-resume" # ------------------------------------------------------------------ # Session hooks # ------------------------------------------------------------------ - def _open(self, trajectory) -> Tuple[_LocalSession, StepResult]: - workspace = tempfile.mkdtemp(prefix='ep_', dir=self._root) + def _open(self, trajectory) -> tuple[_LocalSession, StepResult]: + workspace = tempfile.mkdtemp(prefix="ep_", dir=self._root) return _LocalSession(workspace), StepResult() def _close(self, state: _LocalSession) -> None: @@ -127,103 +138,106 @@ def _workspace(self, state: _LocalSession) -> str: @staticmethod def _state_dir_name(state_key: str) -> str: # Keep the durable path short enough for Windows' classic MAX_PATH. - return hashlib.sha256(state_key.encode('utf-8')).hexdigest()[:24] + return hashlib.sha256(state_key.encode("utf-8")).hexdigest()[:24] @staticmethod - def _tree_digest(root: Path) -> Dict[str, Any]: + def _tree_digest(root: Path) -> dict[str, Any]: digest = hashlib.sha256() files = [] total = 0 - for path in sorted(root.rglob('*')): + for path in sorted(root.rglob("*")): if path.is_symlink(): - raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') + raise UnsafeCheckpoint(f"workspace snapshot refuses symbolic link {path}") if not path.is_file(): continue relative = path.relative_to(root).as_posix() data = path.read_bytes() file_digest = hashlib.sha256(data).hexdigest() - digest.update(relative.encode('utf-8')) - digest.update(b'\0') - digest.update(file_digest.encode('ascii')) - files.append({'path': relative, 'size': len(data), 'sha256': file_digest}) + digest.update(relative.encode("utf-8")) + digest.update(b"\0") + digest.update(file_digest.encode("ascii")) + files.append({"path": relative, "size": len(data), "sha256": file_digest}) total += len(data) - return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} + return {"digest": digest.hexdigest(), "files": files, "bytes": total} - def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: + def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: """Copy one quiescent workspace behind a new atomic generation pointer.""" session = self._session(episode_id) state = session.state if session.script_inflight: - raise UnsafeCheckpoint(f'episode {episode_id!r} has a script in flight') + raise UnsafeCheckpoint(f"episode {episode_id!r} has a script in flight") with state.lock: if state.closed: - raise UnsafeCheckpoint(f'episode {episode_id!r} is already closed') + raise UnsafeCheckpoint(f"episode {episode_id!r} is already closed") if state.procs: - raise UnsafeCheckpoint(f'episode {episode_id!r} has a running process') + raise UnsafeCheckpoint(f"episode {episode_id!r} has a running process") - generation = f'{time.time_ns():x}-{uuid.uuid4().hex[:8]}' + generation = f"{time.time_ns():x}-{uuid.uuid4().hex[:8]}" key_root = self._resume_root / self._state_dir_name(state_key) generation_root = key_root / generation - workspace_copy = generation_root / 'workspace' + workspace_copy = generation_root / "workspace" generation_root.mkdir(parents=True, exist_ok=False) try: shutil.copytree(state.workspace, workspace_copy) tree = self._tree_digest(workspace_copy) manifest = { - 'format': 'twinkle.localenv.v1', - 'state_key': state_key, - 'generation': generation, - 'workspace': tree, + "format": "twinkle.localenv.v1", + "state_key": state_key, + "generation": generation, + "workspace": tree, } - manifest_bytes = json.dumps(manifest, ensure_ascii=False, sort_keys=True, - separators=(',', ':')).encode('utf-8') - manifest_path = generation_root / 'manifest.json' + manifest_bytes = json.dumps(manifest, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode( + "utf-8" + ) + manifest_path = generation_root / "manifest.json" manifest_path.write_bytes(manifest_bytes) - with open(manifest_path, 'r+b') as stream: + with open(manifest_path, "r+b") as stream: os.fsync(stream.fileno()) head = { - 'generation': generation, - 'manifest_sha256': hashlib.sha256(manifest_bytes).hexdigest(), + "generation": generation, + "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), } - head_bytes = json.dumps(head, sort_keys=True).encode('utf-8') - pending = key_root / f'.head.{generation}.tmp' + head_bytes = json.dumps(head, sort_keys=True).encode("utf-8") + pending = key_root / f".head.{generation}.tmp" key_root.mkdir(parents=True, exist_ok=True) - with open(pending, 'wb') as stream: + with open(pending, "wb") as stream: stream.write(head_bytes) stream.flush() os.fsync(stream.fileno()) - os.replace(pending, key_root / 'head.json') + os.replace(pending, key_root / "head.json") except BaseException: shutil.rmtree(generation_root, ignore_errors=True) raise - return {'format': 'twinkle.localenv.v1', 'state_key': state_key, 'generation': generation, - 'manifest_sha256': head['manifest_sha256'], 'files': len(tree['files']), 'bytes': tree['bytes'], - 'reward': session.reward} - - def restore_episode(self, - episode_id: str, - state_key: str, - state: Dict[str, Any], - trajectory=None) -> None: + return { + "format": "twinkle.localenv.v1", + "state_key": state_key, + "generation": generation, + "manifest_sha256": head["manifest_sha256"], + "files": len(tree["files"]), + "bytes": tree["bytes"], + "reward": session.reward, + } + + def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any], trajectory=None) -> None: """Allocate a fresh session and rehydrate the snapshot named by ``state``.""" - if state.get('format') != 'twinkle.localenv.v1' or state.get('state_key') != state_key: - raise UnsafeCheckpoint('LocalEnv restore metadata does not match the episode state key') - generation = str(state.get('generation') or '') + if state.get("format") != "twinkle.localenv.v1" or state.get("state_key") != state_key: + raise UnsafeCheckpoint("LocalEnv restore metadata does not match the episode state key") + generation = str(state.get("generation") or "") if not generation: - raise UnsafeCheckpoint('LocalEnv restore metadata has no generation') + raise UnsafeCheckpoint("LocalEnv restore metadata has no generation") generation_root = self._resume_root / self._state_dir_name(state_key) / generation - manifest_path = generation_root / 'manifest.json' + manifest_path = generation_root / "manifest.json" manifest_bytes = manifest_path.read_bytes() - if hashlib.sha256(manifest_bytes).hexdigest() != state.get('manifest_sha256'): - raise UnsafeCheckpoint('LocalEnv snapshot manifest checksum mismatch') + if hashlib.sha256(manifest_bytes).hexdigest() != state.get("manifest_sha256"): + raise UnsafeCheckpoint("LocalEnv snapshot manifest checksum mismatch") manifest = json.loads(manifest_bytes) - source = generation_root / 'workspace' - if self._tree_digest(source)['digest'] != manifest['workspace']['digest']: - raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') + source = generation_root / "workspace" + if self._tree_digest(source)["digest"] != manifest["workspace"]["digest"]: + raise UnsafeCheckpoint("LocalEnv snapshot workspace checksum mismatch") self.reset(episode_id, trajectory) try: - self._session(episode_id).reward = float(state.get('reward') or 0.0) + self._session(episode_id).reward = float(state.get("reward") or 0.0) target = Path(self.workspace(episode_id)) shutil.copytree(source, target, dirs_exist_ok=True) except BaseException: @@ -233,80 +247,81 @@ def restore_episode(self, def discard_episode_state(self, state_key: str) -> None: shutil.rmtree(self._resume_root / self._state_dir_name(state_key), ignore_errors=True) - def _run_script(self, state: _LocalSession, source: str, interpreter: str = 'python', - timeout: Optional[float] = None) -> Tuple[int, str]: + def _run_script( + self, state: _LocalSession, source: str, interpreter: str = "python", timeout: float | None = None + ) -> tuple[int, str]: timeout = self._command_timeout if timeout is None else timeout # The script file is never written into the workspace. A workspace gets read back -- by a # snapshot, or by a check that lists the directory -- and a stray _script.py in there reads # as something the episode created. - holder = tempfile.mkdtemp(prefix='twinkle_local_') + holder = tempfile.mkdtemp(prefix="twinkle_local_") try: - if interpreter == 'python': - path = os.path.join(holder, '_script.py') - with open(path, 'w', encoding='utf-8') as f: - f.write(source + '\n') + if interpreter == "python": + path = os.path.join(holder, "_script.py") + with open(path, "w", encoding="utf-8") as f: + f.write(source + "\n") argv = [sys.executable, path] - elif interpreter in ('shell', 'bash'): + elif interpreter in ("shell", "bash"): # Not a login shell: sourcing the host's profile prepends whatever # banner it prints to the output of every command, and a check # comparing that output against an expected string then fails on # the banner. PATH and the rest are inherited from the trainer, # which is already in the right environment. - argv = ['/bin/bash', '-c', source] + argv = ["/bin/bash", "-c", source] else: - return 1, f'unsupported interpreter {interpreter!r}; use python or shell' + return 1, f"unsupported interpreter {interpreter!r}; use python or shell" return self._spawn(state, argv, timeout) finally: shutil.rmtree(holder, ignore_errors=True) - def _step(self, state: _LocalSession, tool_name: str, arguments: Dict[str, Any]) -> StepResult: + def _step(self, state: _LocalSession, tool_name: str, arguments: dict[str, Any]) -> StepResult: try: - if tool_name == 'run_command': + if tool_name == "run_command": observation = self.run_command(state, arguments) - elif tool_name == 'write_file': + elif tool_name == "write_file": observation = self._write_file(state, arguments) - elif tool_name == 'read_file': + elif tool_name == "read_file": observation = self._read_file(state, arguments) else: - available = [t['function']['name'] for t in DEFAULT_TOOLS] - observation = f'Error: unknown tool {tool_name!r}. Available tools: {available}.' + available = [t["function"]["name"] for t in DEFAULT_TOOLS] + observation = f"Error: unknown tool {tool_name!r}. Available tools: {available}." return StepResult(observation=observation) except Exception as e: # noqa # Same contract as the sandboxed envs: a tool error is an # observation, so the rollout loop can let the model recover. - logger.warning(f'LocalEnv step error (tool={tool_name}): {e}') - return StepResult(observation=f'Error: {e}', info={'error': str(e)}) + logger.warning(f"LocalEnv step error (tool={tool_name}): {e}") + return StepResult(observation=f"Error: {e}", info={"error": str(e)}) - @remote_function(execute='first', collect='first', lazy_collect=False) - def tools(self) -> List[ToolInfo]: + @remote_function(execute="first", collect="first", lazy_collect=False) + def tools(self) -> list[ToolInfo]: return list(DEFAULT_TOOLS) # ------------------------------------------------------------------ # Tools # ------------------------------------------------------------------ - def run_command(self, state: _LocalSession, arguments: Dict[str, Any]) -> str: + def run_command(self, state: _LocalSession, arguments: dict[str, Any]) -> str: """Run a shell command in the episode; public so custom tool handlers can reuse it.""" - command = arguments.get('command') + command = arguments.get("command") if not command: return "Error: 'command' argument is required." - cwd = arguments.get('cwd') + cwd = arguments.get("cwd") if cwd: - command = f'cd {shlex.quote(str(cwd))} && {command}' - exit_code, output = self._run_script(state, command, 'shell', timeout=arguments.get('timeout')) + command = f"cd {shlex.quote(str(cwd))} && {command}" + exit_code, output = self._run_script(state, command, "shell", timeout=arguments.get("timeout")) # stderr is already folded into output by run_script, hence the empty # stream here: what this call adds is the exit-code line. - return format_command_output(output, '', exit_code) + return format_command_output(output, "", exit_code) - def _write_file(self, state: _LocalSession, arguments: Dict[str, Any]) -> str: - path = self._resolve(state, arguments['path']) - os.makedirs(os.path.dirname(path) or '.', exist_ok=True) - with open(path, 'w', encoding='utf-8') as f: - f.write(arguments.get('content', '')) + def _write_file(self, state: _LocalSession, arguments: dict[str, Any]) -> str: + path = self._resolve(state, arguments["path"]) + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(arguments.get("content", "")) return f"File written: {arguments['path']}" - def _read_file(self, state: _LocalSession, arguments: Dict[str, Any]) -> str: - with open(self._resolve(state, arguments['path']), encoding='utf-8', errors='replace') as f: + def _read_file(self, state: _LocalSession, arguments: dict[str, Any]) -> str: + with open(self._resolve(state, arguments["path"]), encoding="utf-8", errors="replace") as f: return truncate_observation(f.read()) # ------------------------------------------------------------------ @@ -325,16 +340,16 @@ def _resolve(state: _LocalSession, path: str) -> str: since ``run_command`` reaches the same filesystem directly. """ root = os.path.realpath(state.workspace) - target = os.path.realpath(os.path.join(root, str(path).lstrip('/'))) + target = os.path.realpath(os.path.join(root, str(path).lstrip("/"))) if target != root and not target.startswith(root + os.sep): - raise ValueError(f'path {path!r} escapes the workspace') + raise ValueError(f"path {path!r} escapes the workspace") return target - def _spawn(self, state: _LocalSession, argv: List[str], timeout: float) -> Tuple[int, str]: + def _spawn(self, state: _LocalSession, argv: list[str], timeout: float) -> tuple[int, str]: env = dict(os.environ, **_SCRIPT_ENVS, **self._envs) # Inherited from the trainer, and a check that imports torch would # otherwise take a share of a GPU that is mid-generation. - env.pop('CUDA_VISIBLE_DEVICES', None) + env.pop("CUDA_VISIBLE_DEVICES", None) def _limit(): if self._memory_limit_gb: @@ -343,7 +358,7 @@ def _limit(): with state.lock: if state.closed: - return 1, 'the episode was closed' + return 1, "the episode was closed" try: proc = subprocess.Popen( argv, @@ -352,21 +367,22 @@ def _limit(): stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, - errors='replace', + errors="replace", start_new_session=True, - preexec_fn=_limit) + preexec_fn=_limit, + ) except Exception as e: # noqa # A spawn failure is the host's problem, not the script's, and it # comes back as a failed run so one bad call cannot end a whole pass. - return 1, f'{type(e).__name__}: {e}' + return 1, f"{type(e).__name__}: {e}" state.procs.add(proc) try: out, err = proc.communicate(timeout=timeout) - out, err = out or '', err or '' + out, err = out or "", err or "" # A newline between the streams: a stdout line left unterminated # swallows the first line of the traceback that follows it. - if out and err and not out.endswith('\n'): - out += '\n' + if out and err and not out.endswith("\n"): + out += "\n" return proc.returncode, out + err except subprocess.TimeoutExpired: _kill_group(proc) @@ -376,7 +392,7 @@ def _limit(): pass # A killed script has no traceback to explain itself with, so the # output has to say why it produced nothing. - return TIMEOUT_EXIT_CODE, f'execution timed out after {timeout}s (possible infinite loop)' + return TIMEOUT_EXIT_CODE, f"execution timed out after {timeout}s (possible infinite loop)" finally: with state.lock: state.procs.discard(proc) diff --git a/src/twinkle_agentic/envs/resume.py b/src/twinkle_agentic/envs/resume.py index 835575339..6f161c50a 100644 --- a/src/twinkle_agentic/envs/resume.py +++ b/src/twinkle_agentic/envs/resume.py @@ -1,26 +1,27 @@ # Copyright (c) ModelScope Contributors. All rights reserved. """Optional durable-resume protocol for execution environments.""" + from __future__ import annotations from enum import Enum -from typing import Any, Dict, Optional, Protocol, runtime_checkable +from typing import Any, Protocol, runtime_checkable from twinkle.data_format import Trajectory __all__ = [ - 'EnvResumeCapability', - 'ResumableEnv', - 'UnsafeCheckpoint', - 'UnsupportedEnvResume', - 'env_resume_capability', + "EnvResumeCapability", + "ResumableEnv", + "UnsafeCheckpoint", + "UnsupportedEnvResume", + "env_resume_capability", ] class EnvResumeCapability(str, Enum): """How an environment can survive a different Twinkle process.""" - NONE = 'none' - LIVE_ATTACH = 'live_attach' - DURABLE_CHECKPOINT = 'durable_checkpoint' + NONE = "none" + LIVE_ATTACH = "live_attach" + DURABLE_CHECKPOINT = "durable_checkpoint" class UnsupportedEnvResume(NotImplementedError): @@ -37,15 +38,15 @@ class ResumableEnv(Protocol): resume_capability: EnvResumeCapability - def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: + def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: """Capture one quiescent episode under its stable logical identity.""" def restore_episode( self, episode_id: str, state_key: str, - state: Dict[str, Any], - trajectory: Optional[Trajectory] = None, + state: dict[str, Any], + trajectory: Trajectory | None = None, ) -> None: """Bind a durable snapshot to a newly allocated logical session.""" @@ -55,21 +56,18 @@ def discard_episode_state(self, state_key: str) -> None: def env_resume_capability(env: Any) -> EnvResumeCapability: """Return an environment's declared capability after structural validation.""" - declared = getattr(env, 'resume_capability', EnvResumeCapability.NONE) + declared = getattr(env, "resume_capability", EnvResumeCapability.NONE) try: capability = EnvResumeCapability(declared) except ValueError as exc: - raise UnsupportedEnvResume( - f'{type(env).__name__} declares invalid resume capability {declared!r}' - ) from exc + raise UnsupportedEnvResume(f"{type(env).__name__} declares invalid resume capability {declared!r}") from exc if capability == EnvResumeCapability.NONE: return capability missing = [ - name for name in ('checkpoint_episode', 'restore_episode', 'discard_episode_state') + name + for name in ("checkpoint_episode", "restore_episode", "discard_episode_state") if not callable(getattr(env, name, None)) ] if missing: - raise UnsupportedEnvResume( - f'{type(env).__name__} declares {capability.value} but is missing {missing}' - ) + raise UnsupportedEnvResume(f"{type(env).__name__} declares {capability.value} but is missing {missing}") return capability diff --git a/src/twinkle_agentic/rollout/ledger.py b/src/twinkle_agentic/rollout/ledger.py index 12eebb65f..8cd254fb6 100644 --- a/src/twinkle_agentic/rollout/ledger.py +++ b/src/twinkle_agentic/rollout/ledger.py @@ -32,11 +32,10 @@ from dataclasses import replace from typing import Any -from twinkle.data_format import Trajectory +from twinkle.data_format import Trajectory, turn_token_spans, validate_trajectory from twinkle.data_format import last_assistant_text as _traj_last_assistant_text -from twinkle.data_format import turn_token_spans, validate_trajectory -from twinkle.data_format.trajectory import _trainable_positions from twinkle.data_format.sampling import SampledSequence +from twinkle.data_format.trajectory import _trainable_positions from twinkle.template.base import Template from twinkle.template.contract import RolloutState, coerce_tool_call_arguments from twinkle_agentic.utils.token_utils import _to_plain, append_ids @@ -120,29 +119,29 @@ def state_dict(self) -> dict[str, Any]: """ self.audit() return { - 'format': 'twinkle.turn-ledger.v1', - 'input_feature': copy.deepcopy(self._pif), - 'state': copy.deepcopy(self._state), - 'logprobs': copy.deepcopy(self._logprobs), - 'sampling_masks': copy.deepcopy(self._sampling_masks), - 'turns': self._turns, + "format": "twinkle.turn-ledger.v1", + "input_feature": copy.deepcopy(self._pif), + "state": copy.deepcopy(self._state), + "logprobs": copy.deepcopy(self._logprobs), + "sampling_masks": copy.deepcopy(self._sampling_masks), + "turns": self._turns, } def load_state_dict(self, state: dict[str, Any]) -> None: """Replace the mutable account with a previously exported one.""" - if state.get('format') != 'twinkle.turn-ledger.v1': - raise ValueError('unsupported TurnLedger checkpoint format') - input_feature = state.get('input_feature') - logprobs = state.get('logprobs') - turns = state.get('turns') - if not isinstance(input_feature, dict) or 'input_ids' not in input_feature: - raise ValueError('TurnLedger checkpoint is missing input_feature.input_ids') + if state.get("format") != "twinkle.turn-ledger.v1": + raise ValueError("unsupported TurnLedger checkpoint format") + input_feature = state.get("input_feature") + logprobs = state.get("logprobs") + turns = state.get("turns") + if not isinstance(input_feature, dict) or "input_ids" not in input_feature: + raise ValueError("TurnLedger checkpoint is missing input_feature.input_ids") if not isinstance(logprobs, list) or not isinstance(turns, int) or turns < 0: - raise ValueError('TurnLedger checkpoint has invalid logprobs or turns') + raise ValueError("TurnLedger checkpoint has invalid logprobs or turns") self._pif = copy.deepcopy(input_feature) - self._state = copy.deepcopy(state.get('state')) + self._state = copy.deepcopy(state.get("state")) self._logprobs = copy.deepcopy(logprobs) - self._sampling_masks = copy.deepcopy(state.get('sampling_masks')) + self._sampling_masks = copy.deepcopy(state.get("sampling_masks")) self._turns = turns self.audit() @@ -319,12 +318,12 @@ def record(self, seq: SampledSequence) -> None: self._state = completion.state self._pif = sampled_feature if len(self.messages) < len(messages) + 1: - current_messages = messages + [{'role': 'assistant', 'content': seq.decoded or ''}] - self._pif['messages'] = current_messages + current_messages = messages + [{"role": "assistant", "content": seq.decoded or ""}] + self._pif["messages"] = current_messages if self._state is not None: self._state = replace(self._state, messages=tuple(current_messages)) if not self.tools and tools: - self._pif['tools'] = tools + self._pif["tools"] = tools if self._state is not None: self._state = replace(self._state, tools=tuple(tools)) self._turns += 1 @@ -676,4 +675,4 @@ def audit(self) -> None: return -__all__ = ['MessageLedger', 'TurnLedger', 'turn_token_spans'] +__all__ = ["MessageLedger", "TurnLedger", "turn_token_spans"] diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index c7f8934f6..6147bef86 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -7,8 +7,8 @@ merged, trainable trajectory and releases everything. A caller that drives many episodes (the streaming driver) interleaves their steps; a caller that wants whole episodes uses ``__call__``. """ + import hashlib -import json import queue import re import threading @@ -19,6 +19,8 @@ from dataclasses import dataclass, field, replace from typing import Any, Optional +import json + from twinkle.data_format import Trajectory, user_data_get from twinkle.data_format.sampling import SampledSequence, SampleResponse, SamplingParams from twinkle.infra import remote_class, remote_function @@ -27,8 +29,8 @@ from twinkle.utils import get_logger from twinkle_agentic.async_rl.rollout_resume import ResumeStore, UnsafeResume from twinkle_agentic.envs.base import NoSlot -from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability from twinkle_agentic.envs.env_tool import EnvTool +from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability from twinkle_agentic.protocol.api_sampler import APIGenerationError from twinkle_agentic.tools.tool_manager import ToolManager from .endpoint import ENDPOINTS, EndpointRequest, PolicyEndpoint, assistant_message @@ -47,12 +49,13 @@ def _dump_rollout_rows(episode_id: str, rows: list) -> None: segments for prefix-extension. Write-only and env-gated: a no-op (zero cost) when unset. """ import os - root = os.environ.get('TWINKLE_ROLLOUT_TRAJ_DUMP') + + root = os.environ.get("TWINKLE_ROLLOUT_TRAJ_DUMP") if not root: return os.makedirs(root, exist_ok=True) - rank = int(os.environ.get('RANK') or os.environ.get('LOCAL_RANK') or 0) - path = os.path.join(root, f'rows.rank{rank}.jsonl') + rank = int(os.environ.get("RANK") or os.environ.get("LOCAL_RANK") or 0) + path = os.path.join(root, f"rows.rank{rank}.jsonl") def _grid(value: Any) -> Any: # image_grid_thw / video_grid_thw arrive as a tensor (one row per media item); @@ -60,45 +63,45 @@ def _grid(value: Any) -> Any: # plain nested ints. Absent on text rows -- leave it None, not an empty grid. if value is None: return None - tolist = getattr(value, 'tolist', None) + tolist = getattr(value, "tolist", None) return tolist() if callable(tolist) else value - def _media_count(value: Any) -> Optional[int]: + def _media_count(value: Any) -> int | None: return len(value) if isinstance(value, (list, tuple)) else None - with open(path, 'a', encoding='utf-8') as handle: + with open(path, "a", encoding="utf-8") as handle: for seg, row in enumerate(rows): - messages = row.get('messages') or [] + messages = row.get("messages") or [] rec = { - 'episode_id': episode_id, - 'segment_index': row.get('segment_index', seg), - 'rank': rank, - 'input_ids': row.get('input_ids') or [], - 'labels': row.get('labels') or [], - 'completion_mask': row.get('completion_mask'), - 'response_token_ids': row.get('response_token_ids') or [], - 'response_positions': row.get('response_positions') or [], - 'rollout_logps': row.get('rollout_logps'), - 'messages': messages, - 'stop_reason': row.get('stop_reason'), + "episode_id": episode_id, + "segment_index": row.get("segment_index", seg), + "rank": rank, + "input_ids": row.get("input_ids") or [], + "labels": row.get("labels") or [], + "completion_mask": row.get("completion_mask"), + "response_token_ids": row.get("response_token_ids") or [], + "response_positions": row.get("response_positions") or [], + "rollout_logps": row.get("rollout_logps"), + "messages": messages, + "stop_reason": row.get("stop_reason"), # D6 media frame: raw media counts + the processor grid. The judge checks # image-count consistency and the placeholder-token expansion against the grid. - 'images_count': _media_count(row.get('images')), - 'videos_count': _media_count(row.get('videos')), - 'audios_count': _media_count(row.get('audios')), - 'image_grid_thw': _grid(row.get('image_grid_thw')), - 'video_grid_thw': _grid(row.get('video_grid_thw')), + "images_count": _media_count(row.get("images")), + "videos_count": _media_count(row.get("videos")), + "audios_count": _media_count(row.get("audios")), + "image_grid_thw": _grid(row.get("image_grid_thw")), + "video_grid_thw": _grid(row.get("video_grid_thw")), } - handle.write(json.dumps(rec, default=str) + '\n') + handle.write(json.dumps(rec, default=str) + "\n") # Termination reasons surfaced via ``trajectory['stop_reason']``. The sampler # path takes the first three from the sampler itself; the API path has to name # them, and one vocabulary for both is what lets a consumer read either. -STOP_NO_TOOL = 'stop' -STOP_LENGTH = 'length' -STOP_MAX_TURNS = 'max_turns' -STOP_GENERATION_ERROR = 'generation_error' +STOP_NO_TOOL = "stop" +STOP_LENGTH = "length" +STOP_MAX_TURNS = "max_turns" +STOP_GENERATION_ERROR = "generation_error" # Runaway guard: a ``followup_fn`` is expected to return None eventually. This # only bounds a callback that never does, so one bad hook cannot spin forever. @@ -108,6 +111,7 @@ def _media_count(value: Any) -> Optional[int]: #: ceiling only: how many episodes are in flight is the driver's admission, not this. ROLLOUT_MAX_CONCURRENCY = 1024 + def _record_dispatch_probe(event: str, episode_id: str, **fields: Any) -> None: """Append one dispatch event per call when ``TWINKLE_DISPATCH_PROBE`` names a directory. @@ -116,17 +120,19 @@ def _record_dispatch_probe(event: str, episode_id: str, **fields: Any) -> None: order that got it there, so this records each step entry, each session open, and each harness wait/item/serve per episode. Env-gated: unset, it does nothing. """ - import json import os - root = os.environ.get('TWINKLE_DISPATCH_PROBE') + import json + + root = os.environ.get("TWINKLE_DISPATCH_PROBE") if not root: return os.makedirs(root, exist_ok=True) - path = os.path.join(root, f'dispatch.{os.getpid()}.jsonl') - with open(path, 'a', encoding='utf-8') as handle: - handle.write(json.dumps({'t': time.monotonic(), 'event': event, 'episode_id': episode_id, - **fields}, default=str) + '\n') + path = os.path.join(root, f"dispatch.{os.getpid()}.jsonl") + with open(path, "a", encoding="utf-8") as handle: + handle.write( + json.dumps({"t": time.monotonic(), "event": event, "episode_id": episode_id, **fields}, default=str) + "\n" + ) #: Put on an episode's request queue when its agent program exits. @@ -180,11 +186,11 @@ class RolloutStatus: """ # Group identity and role, stamped by the driver. - prompt_id: str = '' - episode_id: str = '' + prompt_id: str = "" + episode_id: str = "" group_key: str | None = None #: '' for a policy sample, 'baseline' for a baseline episode a group asked for. - role: str = '' + role: str = "" # The policy version the episode was admitted under, and how far the policy moved by handover. policy_version: int = 0 version_span: int = 0 @@ -212,15 +218,16 @@ class RolloutStatus: def _single_sequence(responses: Any) -> SampledSequence: if not isinstance(responses, list): - raise TypeError(f'expected List[SampleResponse] from sampler.sample, got {type(responses).__name__}') + raise TypeError(f"expected List[SampleResponse] from sampler.sample, got {type(responses).__name__}") if len(responses) != 1: - raise RuntimeError(f'sampler returned {len(responses)} responses for a single request; expected exactly one.') + raise RuntimeError(f"sampler returned {len(responses)} responses for a single request; expected exactly one.") response = responses[0] if not isinstance(response, (SampleResponse, SampleResponseModel)): - raise TypeError(f'expected SampleResponse or SampleResponseModel from sampler.sample, ' - f'got {type(response).__name__}') + raise TypeError( + f"expected SampleResponse or SampleResponseModel from sampler.sample, got {type(response).__name__}" + ) if len(response.sequences) != 1: - raise RuntimeError(f'SampleResponse contains {len(response.sequences)} sequences; expected exactly one.') + raise RuntimeError(f"SampleResponse contains {len(response.sequences)} sequences; expected exactly one.") sequence = response.sequences[0] if isinstance(response, SampleResponseModel): return SampledSequence(**sequence.model_dump()) @@ -240,12 +247,12 @@ def is_error_observation(observation: str) -> bool: anywhere in the text also matches a *successful* read of a file that happens to contain them, and this decides whether an episode is cut short. """ - text = (observation or '').strip() + text = (observation or "").strip() if not text: return False - if text.startswith('Error:'): + if text.startswith("Error:"): return True - if text.startswith(('Tool runtime unreachable:', 'Tool runtime returned no result')): + if text.startswith(("Tool runtime unreachable:", "Tool runtime returned no result")): return True return bool(re.search(r'"success"\s*:\s*false', text)) @@ -257,15 +264,15 @@ def _call_key(tool_call: dict[str, Any]) -> str: making progress; one that reissues the same call with the same arguments is not, whatever the tool answered. """ - fn = tool_call.get('function') if isinstance(tool_call.get('function'), dict) else {} - name = fn.get('name') or tool_call.get('name') or tool_call.get('tool_name') or '' - args = fn.get('arguments', tool_call.get('arguments')) + fn = tool_call.get("function") if isinstance(tool_call.get("function"), dict) else {} + name = fn.get("name") or tool_call.get("name") or tool_call.get("tool_name") or "" + args = fn.get("arguments", tool_call.get("arguments")) if not isinstance(args, str): try: args = json.dumps(args, sort_keys=True, ensure_ascii=False) except (TypeError, ValueError): args = repr(args) - return f'{name}\x00{args}' + return f"{name}\x00{args}" def _tool_call_names(tool_calls: list[dict[str, Any]]) -> list[str]: @@ -276,8 +283,8 @@ def _tool_call_names(tool_calls: list[dict[str, Any]]) -> list[str]: """ names: list[str] = [] for tool_call in tool_calls: - fn = tool_call.get('function') if isinstance(tool_call.get('function'), dict) else {} - name = fn.get('name') or tool_call.get('name') or tool_call.get('tool_name') or '' + fn = tool_call.get("function") if isinstance(tool_call.get("function"), dict) else {} + name = fn.get("name") or tool_call.get("name") or tool_call.get("tool_name") or "" if name: names.append(name) return names @@ -289,16 +296,16 @@ def _default_tool_messages( ) -> list[dict[str, Any]]: msgs: list[dict[str, Any]] = [] for i, obs in enumerate(observations): - msg: dict[str, Any] = {'role': 'tool', 'content': '' if obs is None else str(obs)} + msg: dict[str, Any] = {"role": "tool", "content": "" if obs is None else str(obs)} if i < len(tool_calls) and isinstance(tool_calls[i], dict): tc = tool_calls[i] - fn = tc.get('function') if isinstance(tc.get('function'), dict) else {} - tid = tc.get('id') or tc.get('tool_call_id') - name = fn.get('name') or tc.get('name') or tc.get('tool_name') + fn = tc.get("function") if isinstance(tc.get("function"), dict) else {} + tid = tc.get("id") or tc.get("tool_call_id") + name = fn.get("name") or tc.get("name") or tc.get("tool_name") if tid: - msg['tool_call_id'] = tid + msg["tool_call_id"] = tid if name: - msg['name'] = name + msg["name"] = name msgs.append(msg) return msgs @@ -310,34 +317,36 @@ def _malformed_tool_message(errors: list[str]) -> dict[str, Any]: make. There is no ``tool_call_id`` to pair it with -- the call never became a call -- which ``_default_tool_messages`` above already treats as optional. """ - reason = '; '.join(e for e in errors if e) or 'the markup could not be parsed' + reason = "; ".join(e for e in errors if e) or "the markup could not be parsed" return { - 'role': 'tool', - 'content': ('Your tool call was not run: ' + reason + '. Send the call again. Inside ' - 'a JSON string a backslash has to be written as \\\\ and a line break as ' - '\\n; a single quote needs no backslash at all.'), + "role": "tool", + "content": ( + "Your tool call was not run: " + reason + ". Send the call again. Inside " + "a JSON string a backslash has to be written as \\\\ and a line break as " + "\\n; a single quote needs no backslash at all." + ), } -def _episode_id_of(trajectory: Any) -> Optional[str]: +def _episode_id_of(trajectory: Any) -> str | None: if not isinstance(trajectory, dict): return None - episode_id = trajectory.get('episode_id') + episode_id = trajectory.get("episode_id") if episode_id is None: - episode_id = user_data_get(trajectory.get('user_data'), 'episode_id') + episode_id = user_data_get(trajectory.get("user_data"), "episode_id") return str(episode_id) if episode_id else None -def _episode_key(args: tuple, kwargs: dict) -> Optional[str]: +def _episode_key(args: tuple, kwargs: dict) -> str | None: """The routing key of ``step``/``stop``: the episode id, so every step of an episode meets its state. Read off ``episode_id`` when the caller passes it (the trajectory may be a reference the caller cannot open), else off the trajectory's ``user_data``. """ - episode_id = kwargs.get('episode_id') or (args[1] if len(args) > 1 else None) + episode_id = kwargs.get("episode_id") or (args[1] if len(args) > 1 else None) if episode_id: return str(episode_id) - return _episode_id_of(kwargs.get('traj', args[0] if args else None)) + return _episode_id_of(kwargs.get("traj", args[0] if args else None)) def _canonical(message: dict[str, Any]) -> tuple: @@ -347,20 +356,20 @@ def _canonical(message: dict[str, Any]) -> tuple: content ``None`` for ``''``, whitespace trimmed. Comparing these forms is what tells a conversation that grew from one that was rewritten. """ - content = message.get('content') + content = message.get("content") if isinstance(content, list): - content = ''.join(part.get('text') or '' for part in content if isinstance(part, dict)) + content = "".join(part.get("text") or "" for part in content if isinstance(part, dict)) calls = [] - for call in message.get('tool_calls') or []: - fn = call.get('function') if isinstance(call.get('function'), dict) else {} - arguments = fn.get('arguments') + for call in message.get("tool_calls") or []: + fn = call.get("function") if isinstance(call.get("function"), dict) else {} + arguments = fn.get("arguments") if isinstance(arguments, str): try: arguments = json.loads(arguments) except ValueError: pass - calls.append((fn.get('name') or '', json.dumps(arguments, sort_keys=True, ensure_ascii=False))) - return (message.get('role'), str(content or '').strip(), tuple(calls), message.get('tool_call_id') or '') + calls.append((fn.get("name") or "", json.dumps(arguments, sort_keys=True, ensure_ascii=False))) + return (message.get("role"), str(content or "").strip(), tuple(calls), message.get("tool_call_id") or "") class _Episode: @@ -371,7 +380,7 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara self.trajectory = trajectory self.params = params self.ledger = None - self.tool_manager: Optional[ToolManager] = None + self.tool_manager: ToolManager | None = None self.env_open = False #: Set by ``_discard``. ``_open`` blocks in ``env.reset`` while every session slot is taken, and #: the episode can be discarded meanwhile, so the call that returns afterwards has to be able to @@ -387,28 +396,28 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara self.stuck = 0 self.seen_calls: set = set() self.stuck_stop = False - self.tool_stop: Optional[str] = None + self.tool_stop: str | None = None self.truncated = False - self.stop_reason: Optional[str] = None - self.error: Optional[str] = None + self.stop_reason: str | None = None + self.error: str | None = None # The agent program: see ``MultiTurnRollout._harness_step``. - self.requests: Optional[queue.Queue] = None - self.exit: Optional[tuple] = None + self.requests: queue.Queue | None = None + self.exit: tuple | None = None self.deadline = 0.0 self.segments = 0 self.sent: list[tuple] = [] - self.tools_key: Optional[str] = None + self.tools_key: str | None = None #: The last served reply, for resubmitted requests (an agent HTTP client that timed out #: and retried sends the same payload verbatim: it is answered verbatim, not re-served). - self.last_reply: Optional[dict] = None + self.last_reply: dict | None = None #: Under segment_policy='collect': the rows of segments a compaction boundary already #: froze, oldest first; the final segment's row joins them when the episode ends. self.closed_rows: list = [] #: Stable identity supplied by the driver. It is not a random session id. - self.state_key = str(trajectory.get('state_key') or '') + self.state_key = str(trajectory.get("state_key") or "") #: Behavior-policy binding for the whole episode. A resumed group keeps this adapter even #: after the sampler's mutable default has moved on to a newer policy. - self.adapter_path: Optional[str] = trajectory.get('adapter_path') + self.adapter_path: str | None = trajectory.get("adapter_path") #: Effects already represented by the latest durable episode checkpoint. self.completed_effects: set[str] = set() @@ -491,38 +500,45 @@ def __init__( adapter_path: str | None = None, use_base_model: bool = False, concurrency: int | None = None, - segment_policy: str = 'drop', + segment_policy: str = "drop", seed: int | None = None, resume_store: ResumeStore | None = None, ): if sampler is None and response_callback is None: - raise ValueError('MultiTurnRollout requires a sampler or a response_callback.') - if sampler is not None and template is not None and getattr( - getattr(type(sampler), 'sample', None), '_enable_continous_work', None) is False: + raise ValueError("MultiTurnRollout requires a sampler or a response_callback.") + if ( + sampler is not None + and template is not None + and getattr(getattr(type(sampler), "sample", None), "_enable_continous_work", None) is False + ): # A remote sampler whose sample is not continuous-work spreads each one-request # call over every worker and raises on the ranks that receive nothing. - raise ValueError(f'{type(sampler).__name__}.sample must be declared with enable_continous_work=True: ' - 'this rollout samples one trajectory per call.') + raise ValueError( + f"{type(sampler).__name__}.sample must be declared with enable_continous_work=True: " + "this rollout samples one trajectory per call." + ) if max_turns < 1: - raise ValueError(f'max_turns must be >= 1, got {max_turns}') + raise ValueError(f"max_turns must be >= 1, got {max_turns}") if max_trajectory_tokens is not None and max_trajectory_tokens < 1: - raise ValueError(f'max_trajectory_tokens must be >= 1 or None, got {max_trajectory_tokens}') + raise ValueError(f"max_trajectory_tokens must be >= 1 or None, got {max_trajectory_tokens}") if concurrency is not None and concurrency < 1: - raise ValueError(f'concurrency must be >= 1 or None, got {concurrency}') + raise ValueError(f"concurrency must be >= 1 or None, got {concurrency}") if adapter_path and use_base_model: - raise ValueError('adapter_path and use_base_model=True ask for opposite ' - 'weights; the sampler would drop the adapter silently.') + raise ValueError( + "adapter_path and use_base_model=True ask for opposite " + "weights; the sampler would drop the adapter silently." + ) if harness is not None: if env is None: - raise ValueError('a harness runs its program in an env session: pass env= ' - '(LocalEnv for this machine).') + raise ValueError("a harness runs its program in an env session: pass env= (LocalEnv for this machine).") if template is None: - raise ValueError('a harness needs a template to account the requests it makes.') + raise ValueError("a harness needs a template to account the requests it makes.") if tool_manager is not None or followup_fn is not None: - raise ValueError('a harness owns its tools and its loop; tool_manager= and followup_fn= ' - 'apply to the tool loop only.') + raise ValueError( + "a harness owns its tools and its loop; tool_manager= and followup_fn= apply to the tool loop only." + ) if harness.protocol not in ENDPOINTS: - raise ValueError(f'harness protocol {harness.protocol!r} is not one of {sorted(ENDPOINTS)}') + raise ValueError(f"harness protocol {harness.protocol!r} is not one of {sorted(ENDPOINTS)}") # How many stuck turns in a row end the episode; 0 runs to ``max_turns`` # regardless. A turn is stuck when it made no progress at all: every call in # it came back an error, or every call in it was byte-identical to one already @@ -530,22 +546,23 @@ def __init__( # recorded episodes: errors alone stop 1 of 12 and save 9 of 239 calls; adding # the repeat rule stops 3 of 12 and saves 63 calls. if stop_after_stuck_turns < 0: - raise ValueError(f'stop_after_stuck_turns must be >= 0, got {stop_after_stuck_turns}') + raise ValueError(f"stop_after_stuck_turns must be >= 0, got {stop_after_stuck_turns}") # How a compaction boundary treats the segment it writes out: 'drop' (the default) keeps # only the final segment trainable -- the episode trains as one row; 'collect' freezes # each written-out segment into its own row, and the episode is delivered as several # independently-coded rows that share one identity and one outcome reward. - if segment_policy not in ('drop', 'collect'): + if segment_policy not in ("drop", "collect"): raise ValueError(f"segment_policy must be 'drop' or 'collect', got {segment_policy!r}.") # How many replies in a row may carry tool-call markup that does not parse # before the episode is given up. Such a reply asked for a tool and had the # markup rejected, so it gets the parser's reason back and another turn. if max_malformed_retries < 0: - raise ValueError(f'max_malformed_retries must be >= 0, got {max_malformed_retries}') + raise ValueError(f"max_malformed_retries must be >= 0, got {max_malformed_retries}") if template is not None: - assert template.truncation_strategy != 'split', ( + assert template.truncation_strategy != "split", ( "MultiTurnRollout does not support truncation_strategy='split'; " - 'use left/right/delete/raise on the template.') + "use left/right/delete/raise on the template." + ) self.sampler = sampler self.template = template self.max_turns = max_turns @@ -564,20 +581,20 @@ def __init__( self.stop_after_stuck_turns = stop_after_stuck_turns self.max_malformed_retries = max_malformed_retries # Left out entirely when unset, so a sampler without LoRA sees the call it always did. - self._adapter_kwargs: dict[str, Any] = {'adapter_path': adapter_path} if adapter_path else {} + self._adapter_kwargs: dict[str, Any] = {"adapter_path": adapter_path} if adapter_path else {} if use_base_model: - self._adapter_kwargs['use_base_model'] = True + self._adapter_kwargs["use_base_model"] = True self.adapter_path = adapter_path self.concurrency = concurrency self.segment_policy = segment_policy self._base_seed = seed - self._template_backend = getattr(type(sampler), 'template_backend', 'vllm') if sampler is not None else 'vllm' + self._template_backend = getattr(type(sampler), "template_backend", "vllm") if sampler is not None else "vllm" self.sampling_params = self._params(sampling_params or SamplingParams()) self._episodes: dict[str, _Episode] = {} self._lock = threading.Lock() self._endpoint_lock = threading.Lock() - self._policy_endpoint: Optional[PolicyEndpoint] = None - self._env_tool_infos: Optional[list] = None + self._policy_endpoint: PolicyEndpoint | None = None + self._env_tool_infos: list | None = None self.resume_store = resume_store # ---------------------------------------------------------------- durable episode @@ -586,61 +603,61 @@ def bind_resume_store(self, store: ResumeStore) -> None: """Inject the run store before the first episode starts.""" with self._lock: if self._episodes: - raise RuntimeError('bind_resume_store must run before any episode is opened') + raise RuntimeError("bind_resume_store must run before any episode is opened") self.resume_store = store def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: if ep.busy and not allow_busy: - raise UnsafeResume(f'episode {ep.episode_id!r} is mid-step and cannot be checkpointed') + raise UnsafeResume(f"episode {ep.episode_id!r} is mid-step and cannot be checkpointed") if self.harness is not None: - raise UnsafeResume('agent-program episodes own live processes and cannot be checkpointed yet') + raise UnsafeResume("agent-program episodes own live processes and cannot be checkpointed yet") if not ep.state_key: - raise UnsafeResume(f'episode {ep.episode_id!r} has no stable state_key') + raise UnsafeResume(f"episode {ep.episode_id!r} has no stable state_key") if ep.ledger is None: - raise UnsafeResume(f'episode {ep.episode_id!r} has no token ledger yet') + raise UnsafeResume(f"episode {ep.episode_id!r} has no token ledger yet") if isinstance(ep.ledger, MessageLedger): - raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') + raise UnsafeResume("message-ledger episodes lose sampled token ids and cannot be resumed safely") env_state = None if ep.env_open: capability = env_resume_capability(self.env) if capability == EnvResumeCapability.NONE: - raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') + raise UnsafeResume(f"{type(self.env).__name__} declares no durable resume capability") env_state = self.env.checkpoint_episode(ep.episode_id, ep.state_key) return { - 'format': 'twinkle.multi-turn-episode.v1', - 'state_key': ep.state_key, - 'episode_id': ep.episode_id, - 'trajectory': ep.trajectory, - 'params': ep.params, - 'ledger': ep.ledger.state_dict(), - 'env_state': env_state, - 'env_open': ep.env_open, - 'budget': ep.budget, - 'spent': ep.spent, - 'followups': ep.followups, - 'malformed': ep.malformed, - 'stuck': ep.stuck, - 'seen_calls': sorted(ep.seen_calls), - 'stuck_stop': ep.stuck_stop, - 'tool_stop': ep.tool_stop, - 'truncated': ep.truncated, - 'stop_reason': ep.stop_reason, - 'error': ep.error, - 'segments': ep.segments, - 'sent': ep.sent, - 'tools_key': ep.tools_key, - 'last_reply': ep.last_reply, - 'closed_rows': ep.closed_rows, - 'completed_effects': sorted(ep.completed_effects), + "format": "twinkle.multi-turn-episode.v1", + "state_key": ep.state_key, + "episode_id": ep.episode_id, + "trajectory": ep.trajectory, + "params": ep.params, + "ledger": ep.ledger.state_dict(), + "env_state": env_state, + "env_open": ep.env_open, + "budget": ep.budget, + "spent": ep.spent, + "followups": ep.followups, + "malformed": ep.malformed, + "stuck": ep.stuck, + "seen_calls": sorted(ep.seen_calls), + "stuck_stop": ep.stuck_stop, + "tool_stop": ep.tool_stop, + "truncated": ep.truncated, + "stop_reason": ep.stop_reason, + "error": ep.error, + "segments": ep.segments, + "sent": ep.sent, + "tools_key": ep.tools_key, + "last_reply": ep.last_reply, + "closed_rows": ep.closed_rows, + "completed_effects": sorted(ep.completed_effects), } - @remote_function(execute='first', collect='first', lazy_collect=False) + @remote_function(execute="first", collect="first", lazy_collect=False) def checkpoint_episode(self, episode_id: str) -> dict[str, Any]: """Persist one episode at an externally stable boundary.""" with self._lock: ep = self._episodes.get(episode_id) if ep is None: - raise EpisodeError(f'episode {episode_id!r} is not held by this rollout') + raise EpisodeError(f"episode {episode_id!r} is not held by this rollout") return self._checkpoint_episode(ep) def _checkpoint_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: @@ -651,77 +668,78 @@ def _checkpoint_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict def restore_episode(self, state: dict[str, Any]) -> str: """Rebuild an episode from a durable state before it is stepped again.""" - if state.get('format') != 'twinkle.multi-turn-episode.v1': - raise UnsafeResume('unsupported MultiTurnRollout episode format') - state_key = str(state.get('state_key') or '') - episode_id = str(state.get('episode_id') or '') + if state.get("format") != "twinkle.multi-turn-episode.v1": + raise UnsafeResume("unsupported MultiTurnRollout episode format") + state_key = str(state.get("state_key") or "") + episode_id = str(state.get("episode_id") or "") if not state_key or not episode_id: - raise UnsafeResume('episode checkpoint has no state_key or episode_id') + raise UnsafeResume("episode checkpoint has no state_key or episode_id") if self.resume_store is not None: - checkpointed = set(state.get('completed_effects') or ()) + checkpointed = set(state.get("completed_effects") or ()) pending = set(self.resume_store.pending_effects(state_key)) unsafe_pending = pending - checkpointed if unsafe_pending: - raise UnsafeResume(f'episode {state_key} has pending tool effects: {sorted(unsafe_pending)!r}') + raise UnsafeResume(f"episode {state_key} has pending tool effects: {sorted(unsafe_pending)!r}") # The checkpoint is written after the tool messages enter the ledger but before the # result journal record. If only that final record is missing, the checkpoint proves # the effect happened and already contains its observation; close the journal gap # instead of rejecting a state that cannot repeat the external call. for effect_key in pending & checkpointed: - self.resume_store.finish_effect(effect_key, {'recovered_from_checkpoint': True}) + self.resume_store.finish_effect(effect_key, {"recovered_from_checkpoint": True}) completed = set(self.resume_store.completed_effects(state_key)) missing = completed - checkpointed if missing: - raise UnsafeResume(f'effect results exist without a matching episode checkpoint: {sorted(missing)!r}') + raise UnsafeResume(f"effect results exist without a matching episode checkpoint: {sorted(missing)!r}") - ep = _Episode(episode_id, dict(state['trajectory']), state['params']) + ep = _Episode(episode_id, dict(state["trajectory"]), state["params"]) ep.state_key = state_key ep.ledger = self._new_ledger(episode_id) if isinstance(ep.ledger, MessageLedger): - raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') - ep.ledger.load_state_dict(state['ledger']) - ep.env_open = bool(state.get('env_open')) + raise UnsafeResume("message-ledger episodes lose sampled token ids and cannot be resumed safely") + ep.ledger.load_state_dict(state["ledger"]) + ep.env_open = bool(state.get("env_open")) if ep.env_open: if self.env is None: - raise UnsafeResume('checkpoint has an environment state but this rollout has no env') + raise UnsafeResume("checkpoint has an environment state but this rollout has no env") capability = env_resume_capability(self.env) if capability == EnvResumeCapability.NONE: - raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') - self.env.restore_episode(episode_id, state_key, state['env_state'], ep.trajectory) - ep.budget = int(state['budget']) - ep.spent = int(state['spent']) - ep.followups = int(state['followups']) - ep.malformed = int(state['malformed']) - ep.stuck = int(state['stuck']) - ep.seen_calls = set(state.get('seen_calls') or ()) - ep.stuck_stop = bool(state.get('stuck_stop')) - ep.tool_stop = state.get('tool_stop') - ep.truncated = bool(state.get('truncated')) - ep.stop_reason = state.get('stop_reason') - ep.error = state.get('error') - ep.segments = int(state.get('segments') or 0) - ep.sent = list(state.get('sent') or ()) - ep.tools_key = state.get('tools_key') - ep.last_reply = state.get('last_reply') - ep.closed_rows = list(state.get('closed_rows') or ()) - ep.completed_effects = set(state.get('completed_effects') or ()) + raise UnsafeResume(f"{type(self.env).__name__} declares no durable resume capability") + self.env.restore_episode(episode_id, state_key, state["env_state"], ep.trajectory) + ep.budget = int(state["budget"]) + ep.spent = int(state["spent"]) + ep.followups = int(state["followups"]) + ep.malformed = int(state["malformed"]) + ep.stuck = int(state["stuck"]) + ep.seen_calls = set(state.get("seen_calls") or ()) + ep.stuck_stop = bool(state.get("stuck_stop")) + ep.tool_stop = state.get("tool_stop") + ep.truncated = bool(state.get("truncated")) + ep.stop_reason = state.get("stop_reason") + ep.error = state.get("error") + ep.segments = int(state.get("segments") or 0) + ep.sent = list(state.get("sent") or ()) + ep.tools_key = state.get("tools_key") + ep.last_reply = state.get("last_reply") + ep.closed_rows = list(state.get("closed_rows") or ()) + ep.completed_effects = set(state.get("completed_effects") or ()) ep.tool_manager = self._episode_tools(episode_id) with self._lock: if episode_id in self._episodes: - raise UnsafeResume(f'episode {episode_id!r} is already held by this rollout') + raise UnsafeResume(f"episode {episode_id!r} is already held by this rollout") self._episodes[episode_id] = ep return episode_id def restore_episode_from_store(self, state_key: str) -> str: if self.resume_store is None: - raise UnsafeResume('no resume store is bound to this rollout') + raise UnsafeResume("no resume store is bound to this rollout") return self.restore_episode(self.resume_store.load_episode(state_key)) # ------------------------------------------------------------------ entries @remote_function(enable_continous_work=True, sticky_key=_episode_key, stash=(0,), lazy_collect=True) - def step(self, traj: Trajectory, episode_id: str | None = None, - session_wait: Optional[float] = None) -> tuple[list, RolloutStatus]: + def step( + self, traj: Trajectory, episode_id: str | None = None, session_wait: float | None = None + ) -> tuple[list, RolloutStatus]: """Advance the episode one generation; ``(rows, sample)`` with ``sample.done`` on the last. The first call of an episode opens it from ``traj``; later calls pass the first ``row`` @@ -743,7 +761,7 @@ def stop(self, traj: Trajectory, episode_id: str | None = None) -> None: """Drop the episode: end its agent, close its env session, forget it.""" self._discard(episode_id or _episode_id_of(traj)) - @remote_function(dispatch='slice', collect='flatten') + @remote_function(dispatch="slice", collect="flatten") def __call__(self, trajectories: list[Trajectory]) -> list[Trajectory]: """Run every trajectory to its end; the results in the input order. @@ -753,8 +771,9 @@ def __call__(self, trajectories: list[Trajectory]) -> list[Trajectory]: collected segment, so the flattened output may hold more rows than inputs. """ if isinstance(trajectories, dict): - raise TypeError(f'{type(self).__name__}.__call__ expects a List[Trajectory]; ' - 'wrap a single trajectory as [trajectory].') + raise TypeError( + f"{type(self).__name__}.__call__ expects a List[Trajectory]; wrap a single trajectory as [trajectory]." + ) trajectories = list(trajectories) if not trajectories: return [] @@ -770,8 +789,8 @@ def run(trajectory: Trajectory) -> list[Trajectory]: return rows except EpisodeError as error: out = dict(trajectory) - out['stop_reason'] = STOP_GENERATION_ERROR - out['error'] = str(error) + out["stop_reason"] = STOP_GENERATION_ERROR + out["error"] = str(error) return [out] workers = min(len(trajectories), self.concurrency or len(trajectories)) @@ -780,7 +799,7 @@ def run(trajectory: Trajectory) -> list[Trajectory]: with ThreadPoolExecutor(max_workers=workers) as pool: return [row for rows in pool.map(run, trajectories) for row in rows] - @remote_function(dispatch='all', collect='none', lazy_collect=False) + @remote_function(dispatch="all", collect="none", lazy_collect=False) def close(self) -> None: """Drop every episode and take the endpoint down; the sampler and env are not owned here.""" with self._lock: @@ -809,8 +828,8 @@ def stream(self, trajectory: Trajectory, *, sampling_params: SamplingParams | No :class:`StreamToolCall` after each turn that dispatched tools; :class:`StreamDone` once at the end, carrying the transcript trajectory. """ - if self.harness is not None or self.sampler is None or not hasattr(self.sampler, 'sample_stream'): - raise ValueError('MultiTurnRollout.stream requires a local sampler exposing sample_stream and no harness.') + if self.harness is not None or self.sampler is None or not hasattr(self.sampler, "sample_stream"): + raise ValueError("MultiTurnRollout.stream requires a local sampler exposing sample_stream and no harness.") params = sampling_params if sampling_params is not None else self.sampling_params episode_id = uuid.uuid4().hex tool_manager = self.tool_manager @@ -826,26 +845,29 @@ def stream(self, trajectory: Trajectory, *, sampling_params: SamplingParams | No # ------------------------------------------------------------------ episode - def _step(self, traj: Trajectory, episode_id: str | None, - session_wait: Optional[float] = None) -> tuple[list, RolloutStatus]: + def _step( + self, traj: Trajectory, episode_id: str | None, session_wait: float | None = None + ) -> tuple[list, RolloutStatus]: episode_id = episode_id or _episode_id_of(traj) if not episode_id: - raise ValueError('step needs an episode id: pass episode_id= or set user_data.episode_id.') + raise ValueError("step needs an episode id: pass episode_id= or set user_data.episode_id.") self._release_idle() with self._lock: ep = self._episodes.get(episode_id) opening = ep is None if opening: - if 'turns' in traj: + if "turns" in traj: # A view an earlier step returned: the episode it names is gone. - raise EpisodeError(f'episode {episode_id!r} is not held by this rollout (stopped, idle ' - 'past episode_idle_timeout, or its replica restarted).') + raise EpisodeError( + f"episode {episode_id!r} is not held by this rollout (stopped, idle " + "past episode_idle_timeout, or its replica restarted)." + ) ep = _Episode(episode_id, dict(traj), self._episode_params(traj)) self._episodes[episode_id] = ep - elif 'turns' not in traj: - raise ValueError(f'episode {episode_id!r} is already running; every episode needs its own id.') + elif "turns" not in traj: + raise ValueError(f"episode {episode_id!r} is already running; every episode needs its own id.") ep.busy = True - _record_dispatch_probe('step_entry', episode_id, opening=opening) + _record_dispatch_probe("step_entry", episode_id, opening=opening) try: if opening: if self._open(ep, session_wait): @@ -863,10 +885,10 @@ def _step(self, traj: Trajectory, episode_id: str | None, ep.busy = False ep.touched = time.monotonic() - def _open(self, ep: _Episode, session_wait: Optional[float] = None) -> bool: + def _open(self, ep: _Episode, session_wait: float | None = None) -> bool: """Open the episode's env session and first turn. Returns True only on a no-slot sentinel.""" if self.env is not None: - _record_dispatch_probe('reset_start', ep.episode_id) + _record_dispatch_probe("reset_start", ep.episode_id) try: result = self.env.reset(ep.episode_id, ep.trajectory, wait=session_wait) except TimeoutError as exc: @@ -875,8 +897,8 @@ def _open(self, ep: _Episode, session_wait: Optional[float] = None) -> bool: # the whole batch instead of recording one generation_error row. Discard the registration # (no session opened) and surface it as an episode failure, preserving the real cause. self._discard(ep.episode_id) - raise EpisodeError(f'episode {ep.episode_id!r} could not open an env session: {exc}') from exc - _record_dispatch_probe('reset_returned', ep.episode_id, discarded=ep.discarded) + raise EpisodeError(f"episode {ep.episode_id!r} could not open an env session: {exc}") from exc + _record_dispatch_probe("reset_returned", ep.episode_id, discarded=ep.discarded) if isinstance(result, NoSlot): # The pool is full and this call was asked not to wait. Drop the registration we just # made (no session was opened, so there is nothing to close) and let _step report it. @@ -893,22 +915,24 @@ def _open(self, ep: _Episode, session_wait: Optional[float] = None) -> bool: try: self.env.close(ep.episode_id) except Exception: # noqa - logger.warning(f'closing the env session opened for discarded episode ' - f'{ep.episode_id!r} failed.', exc_info=True) - raise EpisodeError(f'episode {ep.episode_id!r} was discarded while its env session was ' - 'waiting to open.') + logger.warning( + f"closing the env session opened for discarded episode {ep.episode_id!r} failed.", exc_info=True + ) + raise EpisodeError( + f"episode {ep.episode_id!r} was discarded while its env session was waiting to open." + ) ep.env_open = True ep.trajectory = self._with_observation(ep.trajectory, result) if self.harness is not None: self._start_agent(ep) - _record_dispatch_probe('agent_started', ep.episode_id) + _record_dispatch_probe("agent_started", ep.episode_id) return False ep.tool_manager = self._episode_tools(ep.episode_id) ep.ledger = self._new_ledger(ep.episode_id) # A trajectory that named no tools advertises the manager's, so the prompt # lists what can actually be dispatched. opening_tools = None - if 'tools' not in ep.trajectory and ep.tool_manager is not None: + if "tools" not in ep.trajectory and ep.tool_manager is not None: opening_tools = list(ep.tool_manager.tool_infos() or []) ep.ledger.open(ep.trajectory, tools=opening_tools) ep.budget = self.max_turns @@ -922,10 +946,15 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: coded training rows sharing one identity and one outcome. """ traj = ep.ledger.merge( - ep.trajectory, turns=ep.ledger.turns, stop_reason=ep.stop_reason, truncated=ep.truncated, - segment_index=len(ep.closed_rows), **fields) + ep.trajectory, + turns=ep.ledger.turns, + stop_reason=ep.stop_reason, + truncated=ep.truncated, + segment_index=len(ep.closed_rows), + **fields, + ) if ep.error is not None: - traj['error'] = ep.error + traj["error"] = ep.error episode_end = None if self.on_episode_end is not None: episode_end = self.on_episode_end(traj, self.env, ep.episode_id) @@ -936,29 +965,30 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: self._discard(ep.episode_id) # ``rewards.env`` is the one reward key the rollout itself owns; the scorer # columns (orm / baseline) are the driver's to name when it hands the batch out. - traj['rewards'] = dict(traj.get('rewards') or {}, env=env_reward) + traj["rewards"] = dict(traj.get("rewards") or {}, env=env_reward) if episode_end is not None: - traj['episode_end'] = episode_end + traj["episode_end"] = episode_end for row in ep.closed_rows: # The frozen rows carry the episode's env reward too: the reward key belongs to # the episode, and every row of it carries the same one. - row['rewards'] = dict(row.get('rewards') or {}, env=env_reward) + row["rewards"] = dict(row.get("rewards") or {}, env=env_reward) rows = list(ep.closed_rows) + [traj] _dump_rollout_rows(ep.episode_id, rows) extra = { key: traj[key] - for key in ('stuck_stop', 'tool_stop', 'followups', 'segments', 'agent_exit_code', 'error') if key in traj + for key in ("stuck_stop", "tool_stop", "followups", "segments", "agent_exit_code", "error") + if key in traj } if isinstance(episode_end, dict): extra.update(episode_end) elif episode_end is not None: - extra['episode_end'] = episode_end + extra["episode_end"] = episode_end prompt_tokens = response_tokens = 0 coded = False row_lengths: list = [] for row in rows: - input_ids = row.get('input_ids') or [] - response = row.get('response_token_ids') or [] + input_ids = row.get("input_ids") or [] + response = row.get("response_token_ids") or [] coded = coded or bool(input_ids) prompt_tokens += len(input_ids) - len(response) response_tokens += len(response) @@ -967,17 +997,17 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: # The per-row lengths ride the status so the driver can hand each delivered row its # own facts: the episode totals would repeat on every row and weigh the batch's # metrics by its row count. - extra['row_token_lengths'] = row_lengths + extra["row_token_lengths"] = row_lengths sample = RolloutStatus( episode_id=ep.episode_id, # The episode's turns, not the last segment's: every row carries its own segment's # banked turns, and the episode is the unit that ran. - turns=sum(int(row.get('turns') or 0) for row in rows), + turns=sum(int(row.get("turns") or 0) for row in rows), done=True, stop_reason=ep.stop_reason, truncated=bool(ep.truncated), token_lengths=(prompt_tokens, response_tokens) if coded else None, - routing_exported=traj.get('routed_experts') is not None, + routing_exported=traj.get("routed_experts") is not None, env_reward=env_reward, extra=extra, ) @@ -986,18 +1016,19 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: def _continue(self, ep: _Episode) -> tuple[list, RolloutStatus]: """The episode goes on: return its message view as the one row of an unfinished step.""" return [self._view(ep)], RolloutStatus( - episode_id=ep.episode_id, turns=ep.ledger.turns, stop_reason=ep.stop_reason) + episode_id=ep.episode_id, turns=ep.ledger.turns, stop_reason=ep.stop_reason + ) def _view(self, ep: _Episode) -> Trajectory: view = dict(ep.trajectory) if ep.ledger is not None: - view['messages'] = ep.ledger.messages - view['tools'] = ep.ledger.tools - view['turns'] = ep.ledger.turns if ep.ledger is not None else 0 - view['followups'] = ep.followups + view["messages"] = ep.ledger.messages + view["tools"] = ep.ledger.tools + view["turns"] = ep.ledger.turns if ep.ledger is not None else 0 + view["followups"] = ep.followups return view - def _discard(self, episode_id: Optional[str]) -> None: + def _discard(self, episode_id: str | None) -> None: """Forget the episode: fail its queued requests, end its agent and env session.""" if not episode_id: return @@ -1020,17 +1051,18 @@ def _discard(self, episode_id: Optional[str]) -> None: # close costs nothing and covers the window the flag cannot. self.env.close(episode_id) except Exception: # noqa - logger.warning(f'closing the env session of episode {episode_id!r} failed.', exc_info=True) + logger.warning(f"closing the env session of episode {episode_id!r} failed.", exc_info=True) def _release_idle(self) -> None: now = time.monotonic() with self._lock: idle = [ - episode_id for episode_id, ep in self._episodes.items() + episode_id + for episode_id, ep in self._episodes.items() if not ep.busy and now - ep.touched > self.episode_idle_timeout ] for episode_id in idle: - logger.warning(f'releasing episode {episode_id!r}: no step for over {self.episode_idle_timeout:.0f}s.') + logger.warning(f"releasing episode {episode_id!r}: no step for over {self.episode_idle_timeout:.0f}s.") self._discard(episode_id) # ------------------------------------------------------------------ helpers @@ -1040,21 +1072,20 @@ def _params(self, params: SamplingParams) -> SamplingParams: if params.num_samples != 1: # n>1 would fork the conversation at turn 1, and a forked trajectory has no # defined continuation: run the trajectory several times instead. - raise ValueError(f'MultiTurnRollout supports num_samples=1 only, got {params.num_samples}') + raise ValueError(f"MultiTurnRollout supports num_samples=1 only, got {params.num_samples}") if self.template is not None and not params.logprobs: params = replace(params, logprobs=1) return params def _episode_params(self, traj: Trajectory) -> SamplingParams: - override = user_data_get(traj.get('user_data'), 'sampling_params') - params = (self.sampling_params if not override - else self._params(replace(self.sampling_params, **dict(override)))) + override = user_data_get(traj.get("user_data"), "sampling_params") + params = self.sampling_params if not override else self._params(replace(self.sampling_params, **dict(override))) # defect52b: --seed reaches the rollout half too. Derive a per-request seed from the episode's # stable (group_key, sample_index) identity so a group's num_generations samples differ -- a # constant seed would collapse them to one identical trajectory and zero the group's advantage. # An explicit user_data seed override wins; an episode without a stable identity (the display # stream, a bare __call__) stays unseeded. - if self._base_seed is not None and not (override and 'seed' in dict(override)): + if self._base_seed is not None and not (override and "seed" in dict(override)): derived = self._derive_seed(traj) if derived is not None: params = replace(params, seed=derived) @@ -1063,12 +1094,13 @@ def _episode_params(self, traj: Trajectory) -> SamplingParams: def _derive_seed(self, traj: Trajectory) -> int | None: """A per-(group, sample) seed: crc32 of the identity disperses without linear collisions.""" import zlib - group_key = traj.get('group_key') - sample_index = traj.get('sample_index') + + group_key = traj.get("group_key") + sample_index = traj.get("sample_index") if group_key is None or sample_index is None: return None try: - identity = f'{int(group_key)}:{int(sample_index)}'.encode() + identity = f"{int(group_key)}:{int(sample_index)}".encode() except (TypeError, ValueError): return None return (self._base_seed + zlib.crc32(identity)) & 0x7FFFFFFF @@ -1078,19 +1110,20 @@ def _new_ledger(self, label: str): if self.template is None: return MessageLedger(label=label, max_tokens=self.max_trajectory_tokens) return TurnLedger( - self.template, label=label, max_tokens=self.max_trajectory_tokens, backend=self._template_backend) + self.template, label=label, max_tokens=self.max_trajectory_tokens, backend=self._template_backend + ) @staticmethod def _with_observation(trajectory: Trajectory, result: Any) -> Trajectory: """The opening, with the env's first observation appended as a user message.""" - observation = getattr(result, 'observation', None) + observation = getattr(result, "observation", None) if not observation: return trajectory trajectory = dict(trajectory) - trajectory['messages'] = list(trajectory.get('messages') or []) + [{'role': 'user', 'content': observation}] + trajectory["messages"] = list(trajectory.get("messages") or []) + [{"role": "user", "content": observation}] return trajectory - def _episode_tools(self, episode_id: str) -> Optional[ToolManager]: + def _episode_tools(self, episode_id: str) -> ToolManager | None: """The shared tools plus, with an env, the env's tools bound to this episode's session.""" manager = self.tool_manager.copy() if self.tool_manager is not None else None if self.env is None: @@ -1112,17 +1145,19 @@ def _generate(self, ep: _Episode, ledger, params: SamplingParams) -> SampledSequ state = ledger.state if ledger.state is not None else ledger.input_feature seq = self.response_callback(self._view(ep), state, params) else: - use_state = ledger.state is not None and getattr(type(self.sampler), 'accepts_rollout_state', False) + use_state = ledger.state is not None and getattr(type(self.sampler), "accepts_rollout_state", False) adapter_kwargs = dict(self._adapter_kwargs) if ep.adapter_path is not None: - adapter_kwargs['adapter_path'] = ep.adapter_path - responses = self.sampler.sample([ledger.state if use_state else ledger.input_feature], - sampling_params=params, - session_id=ep.episode_id, - **adapter_kwargs) + adapter_kwargs["adapter_path"] = ep.adapter_path + responses = self.sampler.sample( + [ledger.state if use_state else ledger.input_feature], + sampling_params=params, + session_id=ep.episode_id, + **adapter_kwargs, + ) seq = _single_sequence(responses) if not isinstance(seq, SampledSequence): - raise TypeError(f'expected SampledSequence, got {type(seq).__name__}') + raise TypeError(f"expected SampledSequence, got {type(seq).__name__}") return seq @staticmethod @@ -1132,35 +1167,34 @@ def _run_tools(tool_manager: ToolManager, tool_calls: list[dict[str, Any]]) -> l A manager that answers with fewer results than calls leaves the rest empty rather than shifting them onto the wrong call. """ - if hasattr(tool_manager, 'call_many'): + if hasattr(tool_manager, "call_many"): contents = tool_manager.call_many(tool_calls) else: contents = [tool_manager(tc) for tc in tool_calls] - obs = [''] * len(tool_calls) - for i, content in enumerate(contents[:len(tool_calls)]): - obs[i] = '' if content is None else str(content) + obs = [""] * len(tool_calls) + for i, content in enumerate(contents[: len(tool_calls)]): + obs[i] = "" if content is None else str(content) return obs - def _begin_tool_effect(self, ep: _Episode, - tool_calls: list[dict[str, Any]]) -> tuple[Optional[str], Optional[list[str]]]: + def _begin_tool_effect(self, ep: _Episode, tool_calls: list[dict[str, Any]]) -> tuple[str | None, list[str] | None]: if self.resume_store is None or not ep.state_key: return None, None - calls = json.dumps(tool_calls, ensure_ascii=False, sort_keys=True, separators=(',', ':')) - digest = hashlib.sha256(calls.encode('utf-8')).hexdigest()[:20] - effect_key = f'{ep.state_key}/effect/{ep.spent}/{digest}' - completed = self.resume_store.begin_effect(effect_key, {'calls': tool_calls}) + calls = json.dumps(tool_calls, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + digest = hashlib.sha256(calls.encode("utf-8")).hexdigest()[:20] + effect_key = f"{ep.state_key}/effect/{ep.spent}/{digest}" + completed = self.resume_store.begin_effect(effect_key, {"calls": tool_calls}) if completed is None: return effect_key, None - return effect_key, list(completed.get('observations') or ()) + return effect_key, list(completed.get("observations") or ()) - def _commit_tool_effect(self, ep: _Episode, effect_key: Optional[str], observations: list[str]) -> None: + def _commit_tool_effect(self, ep: _Episode, effect_key: str | None, observations: list[str]) -> None: if effect_key is None or self.resume_store is None: return ep.completed_effects.add(effect_key) # The checkpoint includes both the appended observation and the effect key. # Only after it is durable may the result record make crash recovery safe. self._checkpoint_episode(ep, allow_busy=True) - self.resume_store.finish_effect(effect_key, {'observations': observations}) + self.resume_store.finish_effect(effect_key, {"observations": observations}) # ---------------------------------------------------------------- tool loop @@ -1183,13 +1217,13 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: return self._finish_tool_episode(ep) params = ledger.capped_turn_params(params) if params is None: - raise EpisodeError(f'episode {ep.episode_id!r}: the prompt leaves no room for a generated token.') + raise EpisodeError(f"episode {ep.episode_id!r}: the prompt leaves no room for a generated token.") try: seq = self._generate(ep, ledger, params) except APIGenerationError as error: if not ledger.turns: - raise EpisodeError(f'episode {ep.episode_id!r}: the first generation failed: {error}') from error + raise EpisodeError(f"episode {ep.episode_id!r}: the first generation failed: {error}") from error ep.stop_reason = STOP_GENERATION_ERROR ep.error = str(error) ep.truncated = True @@ -1200,22 +1234,22 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: msgs = ledger.messages last_msg = msgs[-1] if msgs else None - tool_calls = last_msg.get('tool_calls') if isinstance(last_msg, dict) else None + tool_calls = last_msg.get("tool_calls") if isinstance(last_msg, dict) else None if not tool_calls: - tool_calls = ledger.parse_tool_call(seq.decoded or '') + tool_calls = ledger.parse_tool_call(seq.decoded or "") if ep.followups: # Tools are withdrawn once a follow-up was appended: those stages write text # about the state as it is, and a code block in a reply parses as a call. tool_calls = None if isinstance(last_msg, dict): message = dict(last_msg) - message['content'] = ledger.decode_tokens(seq) - message.pop('tool_calls', None) + message["content"] = ledger.decode_tokens(seq) + message.pop("tool_calls", None) ledger.replace_last_message(message) # A reply cut off at max_tokens is truncated in exactly the sense the flag names; # tool calls it happens to contain are not dispatched. - if seq.stop_reason == 'length' or ledger.full(): + if seq.stop_reason == "length" or ledger.full(): ep.truncated = True return self._finish_tool_episode(ep) @@ -1223,11 +1257,13 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: # Markup that did not parse is the model asking for a tool, not declining # one: hand back the parser's reason and let it write the call again. Not # after a follow-up, where a reply that looks like a call is text. - parse_errors = [] if ep.followups else ledger.tool_call_errors(seq.decoded or '') + parse_errors = [] if ep.followups else ledger.tool_call_errors(seq.decoded or "") if parse_errors: if ep.malformed >= self.max_malformed_retries: - raise EpisodeError(f'episode {ep.episode_id!r}: tool-call markup still malformed after ' - f'{ep.malformed} retries: {"; ".join(parse_errors)}') + raise EpisodeError( + f"episode {ep.episode_id!r}: tool-call markup still malformed after " + f"{ep.malformed} retries: {'; '.join(parse_errors)}" + ) ep.malformed += 1 if not ledger.observe([_malformed_tool_message(parse_errors)]): ep.truncated = True @@ -1240,7 +1276,7 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: if ledger.turns >= self.max_turns: # Out of tool turns, not out of episode: the stages that read the end # state can still run on what was built. - ep.tool_stop = 'max_turns' + ep.tool_stop = "max_turns" if self._grant_followup(ep): return self._next_turn(ep) ep.truncated = True @@ -1248,10 +1284,11 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: ep.malformed = 0 if ep.tool_manager is None: - raise ValueError('the model emitted tool_calls but this rollout has no tools (tool_manager= or env=).') + raise ValueError("the model emitted tool_calls but this rollout has no tools (tool_manager= or env=).") effect_key, cached_observations = self._begin_tool_effect(ep, tool_calls) - observations = (cached_observations if cached_observations is not None else - self._run_tools(ep.tool_manager, tool_calls)) + observations = ( + cached_observations if cached_observations is not None else self._run_tools(ep.tool_manager, tool_calls) + ) if self.stop_after_stuck_turns: keys = [_call_key(tc) for tc in tool_calls] all_repeats = bool(keys) and all(k in ep.seen_calls for k in keys) @@ -1266,7 +1303,7 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: # are in the trajectory. if self.stop_after_stuck_turns and ep.stuck >= self.stop_after_stuck_turns: ep.stuck_stop = True - ep.tool_stop = 'stuck' + ep.tool_stop = "stuck" self._commit_tool_effect(ep, effect_key, observations) if not overflowed and self._grant_followup(ep): return self._next_turn(ep) @@ -1300,11 +1337,12 @@ def _grant_followup(self, ep: _Episode) -> bool: ledger = ep.ledger followup = self.followup_fn( ledger.merge(ep.trajectory, turns=ledger.turns, stop_reason=ep.stop_reason, truncated=ep.truncated), - ep.followups) + ep.followups, + ) if followup is None: return False text, next_params = followup if isinstance(followup, tuple) else (followup, None) - if not ledger.observe([{'role': 'user', 'content': text}]): + if not ledger.observe([{"role": "user", "content": text}]): ep.truncated = True return False # Follow-up stages are answers, so a backend must not see tool schemas. @@ -1335,54 +1373,55 @@ def _start_agent(self, ep: _Episode) -> None: task=self.harness.task(ep.trajectory), base_url=endpoint.base_url, api_key=ep.episode_id, - workspace=self.env.workspace(ep.episode_id) or '', + workspace=self.env.workspace(ep.episode_id) or "", ) ep.deadline = time.monotonic() + self.harness.timeout + _AGENT_GRACE requests = ep.requests def run() -> None: try: - ep.exit = self.env.run_script(ep.episode_id, command, interpreter='shell', timeout=self.harness.timeout) + ep.exit = self.env.run_script(ep.episode_id, command, interpreter="shell", timeout=self.harness.timeout) except BaseException as error: # noqa # reported by the step that reads the exit - ep.exit = (None, f'{type(error).__name__}: {error}') + ep.exit = (None, f"{type(error).__name__}: {error}") finally: requests.put(_AGENT_EXITED) - threading.Thread(target=run, name=f'agent-{ep.episode_id[:8]}', daemon=True).start() + threading.Thread(target=run, name=f"agent-{ep.episode_id[:8]}", daemon=True).start() def _harness_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: """Answer the agent's next request, or end the episode when the program exited.""" wait = max(ep.deadline - time.monotonic(), 0.0) - _record_dispatch_probe('harness_wait', ep.episode_id, wait=wait) + _record_dispatch_probe("harness_wait", ep.episode_id, wait=wait) try: item = ep.requests.get(timeout=wait) except queue.Empty: - _record_dispatch_probe('harness_timeout', ep.episode_id) - raise EpisodeError(f'episode {ep.episode_id!r}: the agent did not finish within ' - f'{self.harness.timeout:.0f}s.') from None - _record_dispatch_probe('harness_item', ep.episode_id, exited=item is _AGENT_EXITED) + _record_dispatch_probe("harness_timeout", ep.episode_id) + raise EpisodeError( + f"episode {ep.episode_id!r}: the agent did not finish within {self.harness.timeout:.0f}s." + ) from None + _record_dispatch_probe("harness_item", ep.episode_id, exited=item is _AGENT_EXITED) if item is _AGENT_EXITED: return self._agent_exited(ep) try: result = self._serve(ep, item) - _record_dispatch_probe('harness_served', ep.episode_id) + _record_dispatch_probe("harness_served", ep.episode_id) return result except BaseException as error: - _record_dispatch_probe('harness_serve_error', ep.episode_id, - error=f'{type(error).__name__}: {error}') + _record_dispatch_probe("harness_serve_error", ep.episode_id, error=f"{type(error).__name__}: {error}") if not item.reply.done(): item.reply.set_exception(error) raise def _agent_exited(self, ep: _Episode) -> tuple[list, RolloutStatus]: - code, output = ep.exit or (None, '') - tail = (output or '')[-_OUTPUT_TAIL:] + code, output = ep.exit or (None, "") + tail = (output or "")[-_OUTPUT_TAIL:] if ep.ledger is None: # Wrong config, a crash before the first call, or a config that overrode the key. - raise EpisodeError(f'episode {ep.episode_id!r}: the agent exited ({code}) without calling the ' - f'endpoint:\n{tail}') + raise EpisodeError( + f"episode {ep.episode_id!r}: the agent exited ({code}) without calling the endpoint:\n{tail}" + ) if code != 0: - raise EpisodeError(f'episode {ep.episode_id!r}: the agent exited with {code}:\n{tail}') + raise EpisodeError(f"episode {ep.episode_id!r}: the agent exited with {code}:\n{tail}") ep.stop_reason = STOP_NO_TOOL return self._finish(ep, segments=ep.segments, agent_exit_code=code) @@ -1392,15 +1431,17 @@ def _open_segment(self, ep: _Episode, request: EndpointRequest): A history the agent rewrote (compacted, dropped a turn) or a tool change admits no append, so the recorded segment is over whatever the rewrite left it at. """ - if self.segment_policy == 'collect' and ep.ledger is not None: + if self.segment_policy == "collect" and ep.ledger is not None: # The written-out segment freezes here: its account never changes again, so it # merges into its own row now (identity on it already, from admission); the # episode's other rows join it when the episode ends. - ep.closed_rows.append(ep.ledger.merge( - ep.trajectory, turns=ep.ledger.turns, truncated=False, - segment_index=len(ep.closed_rows))) - ledger = self._new_ledger(f'{ep.episode_id}#{ep.segments}') - ledger.open({'messages': list(request.messages)}, tools=list(request.tools)) + ep.closed_rows.append( + ep.ledger.merge( + ep.trajectory, turns=ep.ledger.turns, truncated=False, segment_index=len(ep.closed_rows) + ) + ) + ledger = self._new_ledger(f"{ep.episode_id}#{ep.segments}") + ledger.open({"messages": list(request.messages)}, tools=list(request.tools)) return ledger def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutStatus]: @@ -1408,8 +1449,7 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS canonical = [_canonical(message) for message in request.messages] tools_key = json.dumps(request.tools, sort_keys=True, ensure_ascii=False) ledger = ep.ledger - if (ep.last_reply is not None and tools_key == ep.tools_key and canonical - and canonical == ep.sent[:-1]): + if ep.last_reply is not None and tools_key == ep.tools_key and canonical and canonical == ep.sent[:-1]: # The same request a retry re-sends: answer with the reply it never saw, without # sampling, recording or starting a segment (the no-new-content history would # otherwise read as a rewrite and needlessly swap the ledger). @@ -1419,15 +1459,18 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS if self.harness is not None: noise = self.harness.noise_reply(request.messages, request.tools, request.params) extends = ( - ledger is not None and tools_key == ep.tools_key and len(canonical) > len(ep.sent) - and canonical[:len(ep.sent)] == ep.sent) + ledger is not None + and tools_key == ep.tools_key + and len(canonical) > len(ep.sent) + and canonical[: len(ep.sent)] == ep.sent + ) if noise is not None: # Housekeeping traffic the agent program does not expect a generation for: the # harness's reply answers it verbatim, costs no sampling, and rides the account # masked (the pair keeps the conversation prefix aligned, the reply is not trained). - message = noise.get('message') or {'role': 'assistant', 'content': ''} + message = noise.get("message") or {"role": "assistant", "content": ""} if extends: - if not ledger.observe(request.messages[len(ep.sent):] + [message]): + if not ledger.observe(request.messages[len(ep.sent) :] + [message]): return self._end_agent_truncated(ep, request) else: # A compaction or tool change the harness's own filter caught: swap the segment @@ -1446,7 +1489,7 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS if extends: # Token-in: what the agent added since our last reply (tool results, its own # notes) is the environment's, appended masked. - if not ledger.observe(request.messages[len(ep.sent):]): + if not ledger.observe(request.messages[len(ep.sent) :]): return self._end_agent_truncated(ep, request) else: # The first request, or a history the agent rewrote (compacted, dropped a @@ -1460,16 +1503,16 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS capped = None if ledger.turns else ledger.capped_turn_params(params) if capped is None: if ep.ledger is None: - raise EpisodeError(f'episode {ep.episode_id!r}: the prompt leaves no room for a generated token.') + raise EpisodeError(f"episode {ep.episode_id!r}: the prompt leaves no room for a generated token.") # Ends on the last recorded segment (a rewritten history with no room never became one). return self._end_agent_truncated(ep, request) params = capped - prompt_tokens = len(ledger.input_feature.get('input_ids') or []) + prompt_tokens = len(ledger.input_feature.get("input_ids") or []) try: seq = self._generate(ep, ledger, params) except APIGenerationError as error: - raise EpisodeError(f'episode {ep.episode_id!r}: generation failed: {error}') from error + raise EpisodeError(f"episode {ep.episode_id!r}: generation failed: {error}") from error ledger.record(seq) if ledger is not ep.ledger: ep.ledger = ledger @@ -1484,11 +1527,11 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS ep.sent = canonical + [_canonical(message)] ep.tools_key = tools_key ep.last_reply = { - 'message': message, - 'finish_reason': 'tool_calls' if parsed else ('length' if seq.stop_reason == 'length' else 'stop'), - 'usage': { - 'prompt_tokens': prompt_tokens, - 'completion_tokens': len(seq.tokens or []), + "message": message, + "finish_reason": "tool_calls" if parsed else ("length" if seq.stop_reason == "length" else "stop"), + "usage": { + "prompt_tokens": prompt_tokens, + "completion_tokens": len(seq.tokens or []), }, } request.reply.set_result(dict(ep.last_reply)) @@ -1499,7 +1542,7 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS def _end_agent_truncated(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutStatus]: """No room for the request: end on what is recorded (closing the session ends the agent).""" - request.reply.set_exception(RuntimeError(f'episode {ep.episode_id!r} reached its length limit')) + request.reply.set_exception(RuntimeError(f"episode {ep.episode_id!r} reached its length limit")) ep.truncated = True return self._finish(ep, segments=ep.segments) @@ -1516,9 +1559,9 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m # Message-level accounting, but template-aware so a reply's tool-call markup still # parses. The feature stays a {'messages','tools'} dict with no input_ids, so # sample_stream re-encodes the whole trajectory each turn. - ledger = MessageLedger(label='stream', max_tokens=self.max_trajectory_tokens, template=self.template) + ledger = MessageLedger(label="stream", max_tokens=self.max_trajectory_tokens, template=self.template) opening_tools = None - if 'tools' not in trajectory and tool_manager is not None: + if "tools" not in trajectory and tool_manager is not None: opening_tools = list(tool_manager.tool_infos() or []) ledger.open(trajectory, tools=opening_tools) @@ -1530,16 +1573,17 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m pieces: list[str] = [] finish: str | None = None for delta, finish_reason in self.sampler.sample_stream( - ledger.input_feature, params, adapter_path=self.adapter_path): + ledger.input_feature, params, adapter_path=self.adapter_path + ): if delta: pieces.append(delta) yield StreamDelta(delta) if finish_reason is not None: finish = finish_reason - text = ''.join(pieces) + text = "".join(pieces) stop_reason = finish or STOP_NO_TOOL ledger.record(SampledSequence(stop_reason=stop_reason, tokens=[], decoded=text)) - if finish == 'length': + if finish == "length": # Cut off mid-reply: no tool call it was still emitting gets dispatched. truncated = True break @@ -1551,7 +1595,7 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m truncated = True break if tool_manager is None: - raise ValueError('the model emitted tool_calls but stream() has no tools (tool_manager= or env=).') + raise ValueError("the model emitted tool_calls but stream() has no tools (tool_manager= or env=).") observations = self._run_tools(tool_manager, tool_calls) yield StreamToolCall(names=_tool_call_names(tool_calls), observations=observations) ledger.observe(_default_tool_messages(tool_calls, observations)) @@ -1560,6 +1604,16 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m __all__ = [ - 'EpisodeError', 'MAX_FOLLOWUPS', 'MultiTurnRollout', 'RolloutStatus', 'STOP_GENERATION_ERROR', 'STOP_LENGTH', - 'STOP_MAX_TURNS', 'STOP_NO_TOOL', 'StreamDelta', 'StreamDone', 'StreamToolCall', 'is_error_observation' + "EpisodeError", + "MAX_FOLLOWUPS", + "MultiTurnRollout", + "RolloutStatus", + "STOP_GENERATION_ERROR", + "STOP_LENGTH", + "STOP_MAX_TURNS", + "STOP_NO_TOOL", + "StreamDelta", + "StreamDone", + "StreamToolCall", + "is_error_observation", ] From 38a90f00805ca05627b5f2e7299523c9ace125ce Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 17:10:46 +0800 Subject: [PATCH 06/45] Merge remote-tracking branch 'origin/dev-swift-v5' into codex/rollout-resume-20261118 --- src/twinkle_agentic/envs/localenv.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 208791d2d..7ce84a850 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -350,9 +350,7 @@ def _resolve(state: _LocalSession, path: str) -> str: raise ValueError(f"path {path!r} escapes the workspace") return target - def _spawn( - self, state: _LocalSession, argv: list[str], timeout: float, cap_memory: bool = True - ) -> tuple[int, str]: + def _spawn(self, state: _LocalSession, argv: list[str], timeout: float, cap_memory: bool = True) -> tuple[int, str]: env = dict(os.environ, **_SCRIPT_ENVS, **self._envs) # Inherited from the trainer, and a check that imports torch would # otherwise take a share of a GPU that is mid-generation. From c2d1605625052e6b7bd057825f2f7c19c83641c0 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 19:44:44 +0800 Subject: [PATCH 07/45] fix(agentic): harden durable resume boundaries --- .../rl/async_rl/durable_multi_turn_grpo.py | 183 ++++++++++-------- .../Agentic/DurableRolloutResume.md" | 21 +- .../async_rl/rollout_resume.py | 6 +- .../async_rl/streaming_driver.py | 49 ++++- src/twinkle_agentic/envs/localenv.py | 4 + src/twinkle_agentic/rollout/multi_turn.py | 16 +- src/twinkle_client/rollout/_http_sampler.py | 5 +- tests/twinkle_agentic/test_localenv_resume.py | 5 +- .../twinkle_agentic/test_multi_turn_resume.py | 16 ++ .../test_rollout_resume_store.py | 15 ++ .../test_streaming_driver_resume.py | 167 ++++++++++++---- .../test_checkpoint_policy_history.py | 28 ++- 12 files changed, 367 insertions(+), 148 deletions(-) diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index 4b3ce2327..4a4cf8aea 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -16,11 +16,14 @@ the same batch lease. A crash after step 3 reloads this checkpoint and does not train the batch twice. """ + from __future__ import annotations import os import re +import time +from collections.abc import Iterable from pathlib import Path -from typing import Any, Dict, Iterable, List +from typing import Any import json from peft import LoraConfig @@ -48,7 +51,7 @@ logger = get_logger() args = CLI.from_args() -MODEL_ID = args.model.model_id or 'ms://Qwen/Qwen3.5-4B' +MODEL_ID = args.model.model_id or "ms://Qwen/Qwen3.5-4B" MODEL_GPUS = args.infra.model_gpus or 4 SAMPLER_GPUS = args.infra.sampler_gpus or 4 NUM_GPUS = MODEL_GPUS + SAMPLER_GPUS @@ -62,22 +65,20 @@ MAX_NEW_TOKENS = args.sampling.max_tokens or 1024 LEARNING_RATE = args.optimizer.learning_rate or 1e-5 LORA_RANK = args.lora.lora_r or 8 -ADAPTER_NAME = args.lora.adapter_name or 'durable-grpo' +ADAPTER_NAME = args.lora.adapter_name or "durable-grpo" -RUN_ID = os.environ.get('TWINKLE_DURABLE_RUN_ID', 'gsm8k-durable-grpo') -RESUME_ROOT = Path(os.environ.get('TWINKLE_RESUME_ROOT', 'output/durable-gsm8k')) -CHECKPOINT_ROOT = RESUME_ROOT / 'model-checkpoints' +RUN_ID = os.environ.get("TWINKLE_DURABLE_RUN_ID", "gsm8k-durable-grpo") +RESUME_ROOT = Path(os.environ.get("TWINKLE_RESUME_ROOT", "output/durable-gsm8k")) +CHECKPOINT_ROOT = RESUME_ROOT / "model-checkpoints" +HISTORY_PATH = RESUME_ROOT / "training-metrics.jsonl" if MINI_BATCH_SIZE != GLOBAL_BATCH_SIZE: raise ValueError( - 'mini_batch_size must equal batch_size * num_generations so one driver lease maps to ' - f'exactly one optimizer step, got {MINI_BATCH_SIZE} and {GLOBAL_BATCH_SIZE}' + "mini_batch_size must equal batch_size * num_generations so one driver lease maps to " + f"exactly one optimizer step, got {MINI_BATCH_SIZE} and {GLOBAL_BATCH_SIZE}" ) -SYSTEM_PROMPT = ( - 'You are a careful math assistant. Solve the problem and put only the final ' - 'answer in \\boxed{}.' -) +SYSTEM_PROMPT = "You are a careful math assistant. Solve the problem and put only the final answer in \\boxed{}." class _ImmediateFuture: @@ -99,18 +100,15 @@ def add_done_callback(self, callback) -> None: class _BrevityReward(Reward): """Small deterministic format reward, aligned with the short-math example.""" - def __call__(self, trajectories: List[Dict[str, Any]], **kwargs) -> List[float]: + def __call__(self, trajectories: list[dict[str, Any]], **kwargs) -> list[float]: rewards = [] for trajectory in trajectories: - reply = '' - for message in reversed(trajectory.get('messages') or ()): - if message.get('role') == 'assistant': - reply = str(message.get('content') or '') + reply = "" + for message in reversed(trajectory.get("messages") or ()): + if message.get("role") == "assistant": + reply = str(message.get("content") or "") break - has_answer = bool( - re.search(r'\\boxed\{[^}]+\}', reply) - or re.search(r'####\s*[\-\d,\.]+', reply) - ) + has_answer = bool(re.search(r"\\boxed\{[^}]+\}", reply) or re.search(r"####\s*[\-\d,\.]+", reply)) if not has_answer: rewards.append(0.0) elif len(reply) <= 300: @@ -135,7 +133,7 @@ def __init__(self, path: Path): self._paths: dict[int, str] = {} self._current_version = 0 if path.is_file(): - raw = json.loads(path.read_text(encoding='utf-8')) + raw = json.loads(path.read_text(encoding="utf-8")) self._paths = {int(version): str(value) for version, value in raw.items()} self._current_version = max(self._paths, default=0) @@ -153,13 +151,13 @@ def register(self, version: int, checkpoint: str) -> None: version = int(version) checkpoint = str(checkpoint) if version < 0 or not checkpoint: - raise ValueError('policy registration needs a non-negative version and checkpoint') + raise ValueError("policy registration needs a non-negative version and checkpoint") self._paths[version] = checkpoint self._current_version = max(self._current_version, version) self.path.parent.mkdir(parents=True, exist_ok=True) atomic_write_bytes( self.path, - (json.dumps(self._paths, ensure_ascii=False, indent=2, sort_keys=True) + '\n').encode('utf-8'), + (json.dumps(self._paths, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"), ) def recover_from_journal(self, records: Iterable[Any]) -> None: @@ -167,21 +165,21 @@ def recover_from_journal(self, records: Iterable[Any]) -> None: for record in records: if record.event != JournalEvent.MODEL_CHECKPOINT_COMMITTED: continue - manifest = record.payload.get('manifest') or {} - version = manifest.get('policy_version') - checkpoint = record.payload.get('checkpoint') + manifest = record.payload.get("manifest") or {} + version = manifest.get("policy_version") + checkpoint = record.payload.get("checkpoint") if version is not None and checkpoint: self.register(int(version), str(checkpoint)) def create_gsm8k_dataset(): dataset = Dataset() - dataset.add_dataset(DatasetMeta('ms://modelscope/gsm8k', subset_name='main', split='train')) + dataset.add_dataset(DatasetMeta("ms://modelscope/gsm8k", subset_name="main", split="train")) dataset.set_template( - 'Qwen3_5Template', + "Qwen3_5Template", model_id=MODEL_ID, max_length=4096, - truncation_strategy='delete', + truncation_strategy="delete", enable_thinking=False, ) dataset.map(GSM8KProcessor(system=SYSTEM_PROMPT)) @@ -189,95 +187,94 @@ def create_gsm8k_dataset(): return dataset -def _followup(trajectory: Dict[str, Any], followups: int): +def _followup(trajectory: dict[str, Any], followups: int): if followups >= 1: return None replies = [ - str(message.get('content') or '') - for message in trajectory.get('messages') or () - if message.get('role') == 'assistant' + str(message.get("content") or "") + for message in trajectory.get("messages") or () + if message.get("role") == "assistant" ] - if replies and re.search(r'\\boxed\{[^}]+\}', replies[-1]): + if replies and re.search(r"\\boxed\{[^}]+\}", replies[-1]): return None - return 'Please restate the result with the final answer inside \\boxed{}.' + return "Please restate the result with the final answer inside \\boxed{}." -def _score_vector(rows: List[Any], facts: Dict[str, Any]) -> List[float]: - scores = facts.get('scores') or () +def _score_vector(rows: list[Any], facts: dict[str, Any]) -> list[float]: + scores = facts.get("scores") or () if len(scores) != len(rows): - raise RuntimeError(f'driver returned {len(rows)} rows but {len(scores)} score records') + raise RuntimeError(f"driver returned {len(rows)} rows but {len(scores)} score records") rewards = [] for item in scores: - values = (item.get('rewards') or {}).get('orm') or {} - accuracy = values.get('accuracy') - brevity = values.get('brevity') + values = (item.get("rewards") or {}).get("orm") or {} + accuracy = values.get("accuracy") + brevity = values.get("brevity") rewards.append(float(accuracy or 0.0) + float(brevity or 0.0)) return rewards -def _old_logps(rows: List[Any]) -> List[List[float]]: +def _old_logps(rows: list[Any]) -> list[list[float]]: values = [] for row in rows: - logps = row.get('rollout_logps') + logps = row.get("rollout_logps") if not logps: - raise RuntimeError(f'row {row.get("episode_id")!r} has no rollout log probabilities') + raise RuntimeError(f"row {row.get('episode_id')!r} has no rollout log probabilities") values.append(list(logps)) return values def main() -> None: device_groups = [ - DeviceGroup(name='model', ranks=list(range(MODEL_GPUS)), device_type='GPU'), - DeviceGroup(name='sampler', ranks=list(range(MODEL_GPUS, NUM_GPUS)), device_type='GPU'), + DeviceGroup(name="model", ranks=list(range(MODEL_GPUS)), device_type="GPU"), + DeviceGroup(name="sampler", ranks=list(range(MODEL_GPUS, NUM_GPUS)), device_type="GPU"), ] model_mesh = DeviceMesh.from_sizes(world_size=MODEL_GPUS, dp_size=MODEL_GPUS) sampler_mesh = DeviceMesh.from_sizes(world_size=SAMPLER_GPUS, dp_size=SAMPLER_GPUS) - twinkle.initialize(mode='ray', nproc_per_node=NUM_GPUS, groups=device_groups, lazy_collect=False) + twinkle.initialize(mode="ray", nproc_per_node=NUM_GPUS, groups=device_groups, lazy_collect=False) model = TransformersModel( model_id=MODEL_ID, device_mesh=model_mesh, - remote_group='model', - mixed_precision='bf16', + remote_group="model", + mixed_precision="bf16", ) model.add_adapter_to_model( ADAPTER_NAME, - LoraConfig(target_modules='all-linear', r=LORA_RANK, lora_alpha=LORA_RANK * 2), + LoraConfig(target_modules="all-linear", r=LORA_RANK, lora_alpha=LORA_RANK * 2), gradient_accumulation_steps=1, ) - model.set_optimizer('AdamW', lr=LEARNING_RATE) - model.set_lr_scheduler('CosineAnnealingLR', T_max=MAX_STEPS, eta_min=0) - model.set_loss('GRPOLoss', epsilon=0.2) + model.set_optimizer("AdamW", lr=LEARNING_RATE) + model.set_lr_scheduler("CosineAnnealingLR", T_max=MAX_STEPS, eta_min=0) + model.set_loss("GRPOLoss", epsilon=0.2) model.set_processor(InputProcessor, padding_free=True) - model.set_template('Qwen3_5Template', model_id=MODEL_ID, enable_thinking=False) + model.set_template("Qwen3_5Template", model_id=MODEL_ID, enable_thinking=False) sampler = vLLMSampler( model_id=MODEL_ID, engine_args={ - 'gpu_memory_utilization': 0.8, - 'max_model_len': 8192, - 'max_lora_rank': max(32, LORA_RANK), - 'enable_lora': True, - 'enable_tower_connector_lora': True, + "gpu_memory_utilization": 0.8, + "max_model_len": 8192, + "max_lora_rank": max(32, LORA_RANK), + "enable_lora": True, + "enable_tower_connector_lora": True, }, device_mesh=sampler_mesh, - remote_group='sampler', + remote_group="sampler", ) - sampler.set_template('Qwen3_5Template', model_id=MODEL_ID, enable_thinking=False) + sampler.set_template("Qwen3_5Template", model_id=MODEL_ID, enable_thinking=False) ckpt_manager = CheckpointEngineManager(model=model, sampler=sampler) store = ResumeStore(RESUME_ROOT, RUN_ID) - policy_index = _PolicyIndex(RESUME_ROOT / 'policy-index.json') + policy_index = _PolicyIndex(RESUME_ROOT / "policy-index.json") policy_index.recover_from_journal(store.journal.records()) committed_records = [ - record for record in store.journal.records() - if record.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED + record for record in store.journal.records() if record.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED ] latest_checkpoint = policy_index.adapter_path(policy_index.latest_version) if latest_checkpoint is None: latest_checkpoint = model.save( - 'policy-0', + "policy-0", output_dir=str(CHECKPOINT_ROOT), adapter_name=ADAPTER_NAME, save_optimizer=False, @@ -291,11 +288,11 @@ def main() -> None: optim_step = 0 else: progress = model.resume_from_checkpoint(latest_checkpoint, adapter_name=ADAPTER_NAME) - optim_step = int(progress.get('cur_step') or 0) - logger.info(f'resumed model checkpoint {latest_checkpoint} at step {optim_step}') + optim_step = int(progress.get("cur_step") or 0) + logger.info(f"resumed model checkpoint {latest_checkpoint} at step {optim_step}") template = Qwen3_5Template(MODEL_ID, max_length=4096, enable_thinking=False) - template.truncation_strategy = 'delete' + template.truncation_strategy = "delete" rollout = MultiTurnRollout( sampler=sampler, template=template, @@ -317,7 +314,7 @@ def main() -> None: batch_size=BATCH_SIZE, min_batch_size=BATCH_SIZE, device_mesh=model_mesh, - remote_group='model', + remote_group="model", ) driver = StreamingDriver( dataloader, @@ -328,18 +325,19 @@ def main() -> None: max_staleness=1, checkpoint_manager=policy_index, orms=[_reward_future(GSM8KAccuracyReward()), _reward_future(_BrevityReward())], - orm_names=['accuracy', 'brevity'], + orm_names=["accuracy", "brevity"], resume_store=store, run_id=RUN_ID, ) - if store.has_object('driver', RUN_ID): + if store.has_object("driver", RUN_ID): driver.load_state_dict() - logger.info('resumed StreamingDriver from the latest stable boundary') + logger.info("resumed StreamingDriver from the latest stable boundary") advantage_fn = GRPOAdvantage() metrics = CompletionRewardMetric() logger.info(get_device_placement()) + started = time.monotonic() try: for rows, facts in driver: if optim_step >= MAX_STEPS: @@ -348,16 +346,13 @@ def main() -> None: advantages = advantage_fn( rewards, num_generations=NUM_GENERATIONS, - scale='group', + scale="group", ).tolist() old_logps = _old_logps(rows) - completion_lengths = [ - sum(1 for label in (row.get('labels') or ()) if label != -100) - for row in rows - ] + completion_lengths = [sum(1 for label in (row.get("labels") or ()) if label != -100) for row in rows] metrics.accumulate( completion_lengths=completion_lengths, - rewards={'total': rewards}, + rewards={"total": rewards}, ) for start in range(0, len(rows), MINI_BATCH_SIZE): @@ -372,7 +367,7 @@ def main() -> None: optim_step += 1 checkpoint = model.save( - f'policy-step-{optim_step}', + f"policy-step-{optim_step}", output_dir=str(CHECKPOINT_ROOT), adapter_name=ADAPTER_NAME, save_optimizer=True, @@ -382,8 +377,8 @@ def main() -> None: driver.commit_batch( checkpoint, manifest={ - 'optimizer_step': optim_step, - 'policy_version': next_version, + "optimizer_step": optim_step, + "policy_version": next_version, }, ) policy_index.register(next_version, checkpoint) @@ -392,13 +387,31 @@ def main() -> None: sampler.reset_prefix_cache() log_dict = metrics.calculate() log_dict.update(model.calculate_metric(is_training=True)) - logger.info(f'[durable step {optim_step}/{MAX_STEPS}] {log_dict}') + logger.info(f"[durable step {optim_step}/{MAX_STEPS}] {log_dict}") + HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True) + with HISTORY_PATH.open("a", encoding="utf-8") as history: + history.write( + json.dumps( + { + "optimizer_step": optim_step, + "policy_version": next_version, + "checkpoint": str(checkpoint), + "elapsed_s": time.monotonic() - started, + "metrics": log_dict, + "driver": driver.stats(), + }, + ensure_ascii=False, + default=str, + ) + + "\n" + ) + history.flush() metrics.reset() finally: driver.close() - logger.info(f'durable GRPO completed: optimizer_step={optim_step}') + logger.info(f"durable GRPO completed: optimizer_step={optim_step}") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 4d5007912..10ebd38e2 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -40,10 +40,15 @@ binding 与扁平字段不一致时拒绝恢复。 启用 `resume_store` 后,driver 在以下稳定边界自动保存快照: 1. prompt 分配并完成成员提交; -2. 完整组进入 ready 队列; -3. batch lease 写入后; -4. `commit_batch()` 完成 checkpoint 关联后; -5. 组淘汰后。 +2. 每个 rollout turn、ORM/PRM 打分提交及结果返回; +3. 完整组进入 ready 队列; +4. batch lease 写入后; +5. `commit_batch()` 完成 checkpoint 关联后; +6. 组淘汰后。 + +PRM 按 segment 保存打分输入;恢复时只补发缺失的分数,并继续遵守 `on_step` 屏障。 +组进入 ready 或被淘汰的安全快照落盘后,其 prompt、episode object 和 LocalEnv workspace +快照会被回收;journal、driver 快照和未提交 lease 仍保留用于恢复。 调用方不需要在故障前手工调用 `state_dict()`。恢复入口为: @@ -97,8 +102,8 @@ checkpoint 且不再交付该 lease。 故障边界: -- journal 最后一行未写完:移除不完整尾部; -- 中间记录损坏或 SHA 校验失败:拒绝恢复; +- journal 最后一行未写完:仅移除没有终止换行的不完整尾部; +- 任意完整记录损坏或 SHA 校验失败(包括最后一条 commit):拒绝恢复; - 磁盘写入失败:回滚不确定的 append; - object 文件不完整:拒绝解码; - 旧 lease 已有 commit 记录:恢复时自动退休。 @@ -155,7 +160,9 @@ cookbook/rl/async_rl/durable_multi_turn_grpo.sh ``` 示例使用官方 GSM8K、Qwen3.5、LoRA、真实多轮 rollout、GRPO 反向传播和 optimizer -checkpoint,并在每个 batch 后调用 `commit_batch()`。 +checkpoint,并在每个 batch 后调用 `commit_batch()`。每个已提交 step 的训练指标、policy +version、driver 计数和累计耗时追加到 `TWINKLE_RESUME_ROOT/training-metrics.jsonl`,重启后续写, +可据此绘制完整训练曲线。 聚焦测试: diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 1e7dd3b30..99bdfed4c 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -227,9 +227,9 @@ def _repair_and_scan(self) -> None: event = JournalEvent(body["event"]) records.append(JournalRecord(seq, event, body["state_key"], body["payload"], prev, digest)) except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: - if data[newline + 1 :].strip(): - raise JournalCorrupt(f"{self.path}: corrupt record at line {len(records) + 1}: {exc}") from exc - break + # A newline proves that a complete record was written. Only a final fragment without + # one is repairable; discarding a corrupt complete commit could repeat its optimizer step. + raise JournalCorrupt(f"{self.path}: corrupt record at line {len(records) + 1}: {exc}") from exc prev = records[-1].digest offset = newline + 1 valid_end = offset diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 5b91a3a3d..05c7b882b 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -174,6 +174,9 @@ class _Episode: orm_pending: int = 0 prm: list[list[Any]] | None = None prm_turns: list[int] = field(default_factory=list) + #: The trajectory at each segment boundary, aligned with ``prm_turns``. Pending scores must be + #: reissued against that boundary rather than against whatever turn is latest after a restart. + prm_inputs: list[Any] = field(default_factory=list) prm_pending: int = 0 #: The PRM segment the episode waits for before its next step (only with ``on_step``). held: int | None = None @@ -635,6 +638,7 @@ def _retire_stale_group(self, group: _Group) -> None: episode.counted_inflight = False if episode.role != _BASELINE: self._live -= 1 + self._discard_group_state(group) @remote_function(execute="first", collect="first", lazy_collect=False) def stats(self) -> dict[str, Any]: @@ -670,6 +674,7 @@ def _episode_state(self, episode: _Episode) -> dict[str, Any]: "orm_pending": episode.orm_pending, "prm": _dump_pending(episode.prm), "prm_turns": list(episode.prm_turns), + "prm_inputs": list(episode.prm_inputs), "prm_pending": episode.prm_pending, "held": episode.held, "deliver": list(episode.deliver), @@ -757,6 +762,7 @@ def _restore_episode(self, state: dict[str, Any], group: _Group) -> _Episode: episode.orm_pending = int(state.get("orm_pending") or 0) episode.prm = _load_pending(state.get("prm")) episode.prm_turns = list(state.get("prm_turns") or ()) + episode.prm_inputs = list(state.get("prm_inputs") or ()) episode.prm_pending = int(state.get("prm_pending") or 0) episode.held = state.get("held") episode.deliver = list(state.get("deliver") or ()) @@ -833,17 +839,26 @@ def _resume_scores(self, episode: _Episode) -> None: for segment, value in enumerate(column): if value is not _PENDING: continue - future = self.prms[scorer]([episode.traj]) + if segment >= len(episode.prm_inputs): + raise UnsafeResume( + f"episode {episode.episode_id!r} has no durable trajectory for pending PRM segment {segment}" + ) + future = self.prms[scorer]([episode.prm_inputs[segment]]) future.add_done_callback( lambda f, episode=episode, key=(segment, scorer): self._events.put(("prm", episode, key, f)) ) def _resume_live_episode(self, episode: _Episode) -> None: - if episode.finished or episode.lost or episode.done: - if not episode.finished and not episode.lost: - self._resume_scores(episode) + if episode.finished or episode.lost: + return + self._resume_scores(episode) + if episode.done: return self._counters["resumed_members"] += 1 + if episode.held is not None: + # The segment scorer's completion callback owns the next transition. Continuing here would + # bypass on_step and could submit a second generation before that decision. + return state_key = str((episode.submit_traj or {}).get("state_key") or "") if self.resume_store is not None and state_key and self.resume_store.has_object("episodes", state_key): self.rollout.restore_episode_from_store(state_key) @@ -1239,6 +1254,8 @@ def _handle(self, kind: str, episode: _Episode, index: int | None, future: Any) ): self._release(episode, segment) self._maybe_finish(episode) + if kind != "step": + self._persist_snapshot_locked() self._lock.notify_all() def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None: @@ -1255,6 +1272,7 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None segment = self._score_prm(episode) if self.on_step is not None and not episode.done: episode.held = segment + self._persist_snapshot_locked() return if episode.done: self._consecutive_failures = 0 @@ -1262,12 +1280,16 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None self._score_orm(episode) else: self._step(episode, trajs[0]) + # Persist pending score work as well as completed values. Otherwise a restart could skip a + # segment's PRM entirely or repeat an ORM that already produced an external side effect. + self._persist_snapshot_locked() def _score_prm(self, episode: _Episode) -> int: if episode.prm is None: episode.prm = [[] for _ in self.prms] segment = len(episode.prm_turns) episode.prm_turns.append(int(episode.sample.turns)) + episode.prm_inputs.append(episode.traj) for scorer, prm in enumerate(self.prms): episode.prm[scorer].append(_PENDING) episode.prm_pending += 1 @@ -1457,6 +1479,23 @@ def _settle(self, group: _Group) -> None: return self._accept(group) + def _discard_group_state(self, group: _Group) -> None: + """Collect terminal episode state after a durable ready/drop snapshot exists.""" + if self.resume_store is None: + return + self.resume_store.delete_object("prompts", f"{self.run_id}/prompt/{group.key}") + discard = getattr(self.rollout, "discard_episode_state", None) + for episode in group.members + group.baselines: + state_key = str((episode.submit_traj or {}).get("state_key") or "") + if not state_key: + continue + self.resume_store.delete_object("episodes", state_key) + if callable(discard): + try: + discard(state_key) + except Exception as exc: # noqa: BLE001 -- terminal training state is already durable + logger.warning(f"discarding environment state for {state_key} failed: {exc}") + def _accept(self, group: _Group) -> None: del self._groups[group.key] self._ready.append(list(group.members)) @@ -1473,6 +1512,7 @@ def _accept(self, group: _Group) -> None: "episodes": [episode.episode_id for episode in group.members], }, ) + self._discard_group_state(group) def _drop_group(self, group: _Group) -> None: """Give the group up: its counted rows leave the bound, its unfinished episodes stop (under the lock).""" @@ -1502,6 +1542,7 @@ def _drop_group(self, group: _Group) -> None: }, ) self._persist_snapshot_locked() + self._discard_group_state(group) #: Placeholder for a score whose Future has not completed yet. diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 7ce84a850..e21bc2d5d 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -208,6 +208,9 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: except BaseException: shutil.rmtree(generation_root, ignore_errors=True) raise + for old in key_root.iterdir(): + if old.is_dir() and old.name != generation: + shutil.rmtree(old, ignore_errors=True) return { "format": "twinkle.localenv.v1", "state_key": state_key, @@ -244,6 +247,7 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] self.close(episode_id) raise + @remote_function(dispatch="all", collect="none", lazy_collect=False) def discard_episode_state(self, state_key: str) -> None: shutil.rmtree(self._resume_root / self._state_dir_name(state_key), ignore_errors=True) diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 80625316a..7892aa3ce 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -734,6 +734,12 @@ def restore_episode_from_store(self, state_key: str) -> str: raise UnsafeResume("no resume store is bound to this rollout") return self.restore_episode(self.resume_store.load_episode(state_key)) + @remote_function(dispatch="all", collect="none", lazy_collect=False) + def discard_episode_state(self, state_key: str) -> None: + """Release environment snapshots after the driver has persisted the group's terminal state.""" + if self.env is not None and env_resume_capability(self.env) != EnvResumeCapability.NONE: + self.env.discard_episode_state(state_key) + # ------------------------------------------------------------------ entries @remote_function(enable_continous_work=True, sticky_key=_episode_key, stash=(0,), lazy_collect=True) @@ -1306,19 +1312,23 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: ep.tool_stop = "stuck" self._commit_tool_effect(ep, effect_key, observations) if not overflowed and self._grant_followup(ep): - return self._next_turn(ep) + return self._next_turn(ep, checkpoint=False) ep.truncated = True return self._finish_tool_episode(ep) if overflowed: self._commit_tool_effect(ep, effect_key, observations) return self._finish_tool_episode(ep) self._commit_tool_effect(ep, effect_key, observations) - return self._next_turn(ep) + return self._next_turn(ep, checkpoint=False) - def _next_turn(self, ep: _Episode) -> tuple[list, RolloutStatus]: + def _next_turn(self, ep: _Episode, *, checkpoint: bool = True) -> tuple[list, RolloutStatus]: """Another generation is due -- unless the budget is spent, which ends the episode here.""" if ep.spent >= ep.budget: return self._finish_tool_episode(ep) + if checkpoint and self.resume_store is not None: + # The start-of-step checkpoint predates the generation just recorded. Save the completed + # turn too, so a driver snapshot with pending PRM work resumes from the same boundary. + self._checkpoint_episode(ep, allow_busy=True) return self._continue(ep) def _finish_tool_episode(self, ep: _Episode) -> tuple[list, RolloutStatus]: diff --git a/src/twinkle_client/rollout/_http_sampler.py b/src/twinkle_client/rollout/_http_sampler.py index 4a326c7f0..c2a6dde1e 100644 --- a/src/twinkle_client/rollout/_http_sampler.py +++ b/src/twinkle_client/rollout/_http_sampler.py @@ -104,9 +104,10 @@ def version(self) -> int: return self._version def adapter_path(self, version: int) -> Optional[str]: - """The durable adapter a group sampled from, retained for resume.""" + """Resolve the driver-visible policy version to its immutable adapter.""" with self._lock: - return self._paths.get(int(version)) + # version() counts completed syncs, so the adapter saved by sync N is policy N + 1. + return self._paths.get(int(version) - 1) if version >= 1 else None def _wire_media(media: Any) -> Dict[str, List[str]]: diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index 1dfb79632..550a0e33b 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -16,8 +16,8 @@ ray.is_initialized = lambda: False sys.modules["ray"] = ray -from twinkle_agentic.envs.resume import UnsafeCheckpoint # noqa: E402 from twinkle_agentic.envs.localenv import LocalEnv # noqa: E402 +from twinkle_agentic.envs.resume import UnsafeCheckpoint # noqa: E402 def test_localenv_workspace_round_trip_uses_a_new_session(tmp_path): @@ -26,7 +26,10 @@ def test_localenv_workspace_round_trip_uses_a_new_session(tmp_path): source.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "turn-boundary"}) state_key = "run-1/group-0/episode-1/attempt-0" + source.checkpoint_episode("episode-1", state_key) snapshot = source.checkpoint_episode("episode-1", state_key) + key_root = source._resume_root / source._state_dir_name(state_key) + assert [path.name for path in key_root.iterdir() if path.is_dir()] == [snapshot["generation"]] source.close("episode-1") restored = LocalEnv(root=str(tmp_path)) diff --git a/tests/twinkle_agentic/test_multi_turn_resume.py b/tests/twinkle_agentic/test_multi_turn_resume.py index cf4a1aacc..35a07a03b 100644 --- a/tests/twinkle_agentic/test_multi_turn_resume.py +++ b/tests/twinkle_agentic/test_multi_turn_resume.py @@ -142,3 +142,19 @@ def sample(self, _inputs, sampling_params=None, *, adapter_path=None, **_kwargs) rollout._generate(ep, type("Ledger", (), {"state": None, "input_feature": {}})(), SamplingParams()) assert sampler.adapter_paths == ["/policies/policy-1.adapter"] + + +def test_next_turn_persists_the_completed_generation_boundary(tmp_path): + store = ResumeStore(tmp_path, "run") + rollout = _rollout(store) + episode = _episode(rollout) + rollout._episodes[episode.episode_id] = episode + + rows, status = rollout._next_turn(episode) + + assert not status.done + assert rows[0]["turns"] == 1 + durable = store.load_episode(episode.state_key) + assert durable["spent"] == 1 + assert durable["ledger"]["input_feature"]["input_ids"] == [1, 2, 3] + assert durable["ledger"]["turns"] == 1 diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index ac59c09ca..d17bf5893 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -45,6 +45,21 @@ def test_journal_refuses_damage_before_a_complete_later_record(tmp_path): assert first.seq == 0 +def test_journal_refuses_a_corrupt_complete_final_commit(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + journal.append(JournalEvent.BATCH_LEASED, "run/batch/0") + journal.append(JournalEvent.MODEL_CHECKPOINT_COMMITTED, "run/batch/0", {"checkpoint": "step-1"}) + lines = path.read_text(encoding="utf-8").splitlines() + commit = json.loads(lines[-1]) + commit["payload"]["checkpoint"] = "corrupted" + lines[-1] = json.dumps(commit, sort_keys=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + with pytest.raises(JournalCorrupt, match="corrupt record at line 2"): + DurableJournal(path) + + def test_resume_store_checks_object_checksum(tmp_path): store = ResumeStore(tmp_path, "run") store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 7c093059b..7ce1ee1a1 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -4,7 +4,7 @@ import pytest from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding, ResumeStore, UnsafeResume -from twinkle_agentic.async_rl.streaming_driver import StreamingDriver +from twinkle_agentic.async_rl.streaming_driver import _PENDING, StreamingDriver from twinkle_agentic.rollout.multi_turn import RolloutStatus @@ -30,6 +30,7 @@ def add_done_callback(self, callback): class _DoneRollout: def __init__(self): self.calls = [] + self.discarded = [] def step(self, trajectory, episode_id=None, session_wait=None): self.calls.append(episode_id) @@ -40,6 +41,9 @@ def step(self, trajectory, episode_id=None, session_wait=None): def stop(self, trajectory, episode_id=None): return None + def discard_episode_state(self, state_key): + self.discarded.append(state_key) + class _BoundRollout(_DoneRollout): def step(self, trajectory, episode_id=None, session_wait=None): @@ -313,12 +317,14 @@ def test_invalid_binding_snapshot_fails_closed(tmp_path): resume_store=ResumeStore(tmp_path, "run-invalid-binding"), ) with pytest.raises(UnsafeResume, match="invalid group policy binding"): - driver._restore_group({ - "key": "0", - "row": _prompts(1)[0], - "binding": {"state_key": "", "policy_version": 0, "adapter_path": None}, - "members": [], - }) + driver._restore_group( + { + "key": "0", + "row": _prompts(1)[0], + "binding": {"state_key": "", "policy_version": 0, "adapter_path": None}, + "members": [], + } + ) def test_conflicting_binding_and_flat_snapshot_fails_closed(tmp_path): @@ -330,18 +336,20 @@ def test_conflicting_binding_and_flat_snapshot_fails_closed(tmp_path): resume_store=ResumeStore(tmp_path, "run-conflict"), ) with pytest.raises(UnsafeResume, match="disagrees"): - driver._restore_group({ - "key": "0", - "row": _prompts(1)[0], - "binding": { - "state_key": "run-conflict/group/0", - "policy_version": 1, - "adapter_path": "/policies/one.adapter", - }, - "version": 2, - "adapter_path": "/policies/two.adapter", - "members": [], - }) + driver._restore_group( + { + "key": "0", + "row": _prompts(1)[0], + "binding": { + "state_key": "run-conflict/group/0", + "policy_version": 1, + "adapter_path": "/policies/one.adapter", + }, + "version": 2, + "adapter_path": "/policies/two.adapter", + "members": [], + } + ) def test_explicit_base_model_binding_is_not_rebound_to_an_adapter(tmp_path): @@ -354,18 +362,20 @@ def test_explicit_base_model_binding_is_not_rebound_to_an_adapter(tmp_path): checkpoint_manager=manager, resume_store=ResumeStore(tmp_path, "run-base-binding"), ) - group = driver._restore_group({ - "key": "0", - "row": _prompts(1)[0], - "binding": { - "state_key": "run-base-binding/group/0", - "policy_version": 1, + group = driver._restore_group( + { + "key": "0", + "row": _prompts(1)[0], + "binding": { + "state_key": "run-base-binding/group/0", + "policy_version": 1, + "adapter_path": None, + }, + "version": 1, "adapter_path": None, - }, - "version": 1, - "adapter_path": None, - "members": [], - }) + "members": [], + } + ) assert group.binding.adapter_path is None @@ -378,18 +388,20 @@ def test_group_binding_state_key_must_match_run_identity(tmp_path): resume_store=ResumeStore(tmp_path, "run-identity"), ) with pytest.raises(UnsafeResume, match="does not match"): - driver._restore_group({ - "key": "0", - "row": _prompts(1)[0], - "binding": { - "state_key": "other-run/group/0", - "policy_version": 0, + driver._restore_group( + { + "key": "0", + "row": _prompts(1)[0], + "binding": { + "state_key": "other-run/group/0", + "policy_version": 0, + "adapter_path": None, + }, + "version": 0, "adapter_path": None, - }, - "version": 0, - "adapter_path": None, - "members": [], - }) + "members": [], + } + ) def test_ready_group_over_staleness_is_dropped_whole(tmp_path): @@ -522,3 +534,76 @@ def test_delivered_groups_release_the_admission_window(tmp_path): def restoration_stats(driver): stats = driver.stats() return {key: stats[key] for key in ("dropped_stale", "dropped_group", "ready_rows", "live")} + + +def test_resume_reissues_pending_prm_at_its_segment_and_keeps_the_held_barrier(tmp_path): + store = ResumeStore(tmp_path, "run-prm") + source = StreamingDriver( + _prompts(1), + _BlockingRollout(), + batch_size=1, + num_generations=1, + prms=[lambda _rows: _BlockingFuture()], + on_step=lambda _sample, _scores: True, + resume_store=store, + ) + source._admit() + episode = source._groups["0"].members[0] + episode.traj = {"episode_id": episode.episode_id, "turns": 0, "marker": "latest"} + episode.sample = RolloutStatus(episode_id=episode.episode_id, turns=1) + segment_input = {"messages": [{"role": "assistant", "content": "segment-boundary"}]} + episode.prm = [[_PENDING]] + episode.prm_turns = [1] + episode.prm_inputs = [segment_input] + episode.prm_pending = 1 + episode.held = 0 + state = source.state_dict() + source.close() + + scored = [] + + def prm(rows): + scored.append(rows) + return _Future([0.5]) + + rollout = _BlockingRollout() + restored = StreamingDriver( + _prompts(1), + rollout, + batch_size=1, + num_generations=1, + prms=[prm], + on_step=lambda _sample, _scores: True, + resume_store=store, + ) + restored.load_state_dict(state) + + assert scored == [[segment_input]] + assert rollout.calls == [] + restored._handle(*restored._events.get_nowait()) + assert restored._groups["0"].members[0].prm_pending == 0 + assert len(rollout.calls) == 1 + restored.close() + + +def test_terminal_group_snapshot_precedes_episode_state_cleanup(tmp_path): + store = ResumeStore(tmp_path, "run-cleanup") + rollout = _DoneRollout() + driver = StreamingDriver(_prompts(1), rollout, batch_size=2, num_generations=2, max_steps=1, resume_store=store) + driver._admit() + group = driver._groups["0"] + state_keys = [] + for episode in group.members: + state_key = episode.submit_traj["state_key"] + state_keys.append(state_key) + store.save_object("episodes", state_key, {"pending": False}) + episode.deliver = [dict(episode.submit_traj)] + + assert store.has_object("prompts", "run-cleanup/prompt/0") + driver._accept(group) + + assert store.has_object("driver", "run-cleanup") + assert not store.has_object("prompts", "run-cleanup/prompt/0") + assert all(not store.has_object("episodes", key) for key in state_keys) + assert rollout.discarded == state_keys + driver.close() diff --git a/tests/twinkle_client/test_checkpoint_policy_history.py b/tests/twinkle_client/test_checkpoint_policy_history.py index 8c0bc3394..b41b8faa4 100644 --- a/tests/twinkle_client/test_checkpoint_policy_history.py +++ b/tests/twinkle_client/test_checkpoint_policy_history.py @@ -1,5 +1,6 @@ from types import SimpleNamespace +from twinkle_agentic.async_rl import StreamingDriver from twinkle_client.rollout import ClientCheckpointManager @@ -29,7 +30,30 @@ def test_checkpoint_manager_retains_each_policy_adapter_for_resume(): assert first == "/policies/durable-0.adapter" assert second == "/policies/durable-1.adapter" - assert manager.adapter_path(0) == first - assert manager.adapter_path(1) == second + assert manager.adapter_path(0) is None + assert manager.adapter_path(1) == first + assert manager.adapter_path(2) == second assert manager.adapter_path(99) is None assert manager.version() == 2 + + +def test_checkpoint_manager_policy_versions_match_driver_admission(): + model = _Model() + sampler = _Sampler() + manager = ClientCheckpointManager(model, sampler, name_prefix="durable") + manager.sync_weights() + + class _Rollout: + def step(self, trajectory, **_kwargs): + self.trajectory = trajectory + return SimpleNamespace(add_done_callback=lambda _callback: None) + + rollout = _Rollout() + driver = StreamingDriver([{"messages": []}], rollout, batch_size=1, num_generations=1, checkpoint_manager=manager) + driver._version = manager.version() + driver._admit() + + group = driver._groups["0"] + assert group.version == 1 + assert group.adapter_path == sampler.adapter_path + assert rollout.trajectory["adapter_path"] == sampler.adapter_path From 22624a6e7569dc42f3765975a6c2cfb6e534304a Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Thu, 19 Nov 2026 23:47:58 +0800 Subject: [PATCH 08/45] fix(agentic): validate durable vLLM recovery --- .../rl/async_rl/durable_multi_turn_grpo.py | 126 ++++++++++++------ .../Agentic/DurableRolloutResume.md" | 29 ++-- .../async_rl/streaming_driver.py | 6 +- 3 files changed, 111 insertions(+), 50 deletions(-) diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index 4a4cf8aea..bd19ddcc3 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -18,6 +18,7 @@ """ from __future__ import annotations +import argparse import os import re import time @@ -32,7 +33,6 @@ from twinkle import DeviceGroup, DeviceMesh, get_device_placement, get_logger from twinkle.advantage import GRPOAdvantage from twinkle.checkpoint_engine import CheckpointEngineManager -from twinkle.cli import CLI from twinkle.data_format import SamplingParams from twinkle.dataloader import DataLoader from twinkle.dataset import Dataset, DatasetMeta @@ -48,24 +48,43 @@ from twinkle_agentic.async_rl.rollout_resume import JournalEvent, ResumeStore, atomic_write_bytes from twinkle_agentic.rollout.multi_turn import MultiTurnRollout + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model-id") + parser.add_argument("--strategy", choices=("native_fsdp", "accelerate"), default="native_fsdp") + parser.add_argument("--model-gpus", type=int) + parser.add_argument("--sampler-gpus", type=int) + parser.add_argument("--num-generations", type=int) + parser.add_argument("--max-tokens", type=int) + parser.add_argument("--batch-size", type=int) + parser.add_argument("--mini-batch-size", type=int) + parser.add_argument("--micro-batch-size", type=int) + parser.add_argument("--max-steps", type=int) + parser.add_argument("--lr", type=float) + parser.add_argument("--lora-r", type=int) + parser.add_argument("--adapter-name") + return parser.parse_known_args()[0] + + logger = get_logger() -args = CLI.from_args() +args = parse_args() -MODEL_ID = args.model.model_id or "ms://Qwen/Qwen3.5-4B" -MODEL_GPUS = args.infra.model_gpus or 4 -SAMPLER_GPUS = args.infra.sampler_gpus or 4 +MODEL_ID = args.model_id or "ms://Qwen/Qwen3.5-4B" +MODEL_GPUS = args.model_gpus or 4 +SAMPLER_GPUS = args.sampler_gpus or 4 NUM_GPUS = MODEL_GPUS + SAMPLER_GPUS -NUM_GENERATIONS = args.rl.num_generations or 4 -BATCH_SIZE = args.training.batch_size or 2 +NUM_GENERATIONS = args.num_generations or 4 +BATCH_SIZE = args.batch_size or 2 GLOBAL_BATCH_SIZE = BATCH_SIZE * NUM_GENERATIONS -MINI_BATCH_SIZE = args.training.mini_batch_size or GLOBAL_BATCH_SIZE -MICRO_BATCH_SIZE = args.training.micro_batch_size or 2 -MAX_STEPS = args.training.max_steps or 100 -MAX_NEW_TOKENS = args.sampling.max_tokens or 1024 -LEARNING_RATE = args.optimizer.learning_rate or 1e-5 -LORA_RANK = args.lora.lora_r or 8 -ADAPTER_NAME = args.lora.adapter_name or "durable-grpo" +MINI_BATCH_SIZE = args.mini_batch_size or GLOBAL_BATCH_SIZE +MICRO_BATCH_SIZE = args.micro_batch_size or 2 +MAX_STEPS = args.max_steps or 100 +MAX_NEW_TOKENS = args.max_tokens or 1024 +LEARNING_RATE = args.lr or 1e-5 +LORA_RANK = args.lora_r or 8 +ADAPTER_NAME = args.adapter_name or "durable-grpo" RUN_ID = os.environ.get("TWINKLE_DURABLE_RUN_ID", "gsm8k-durable-grpo") RESUME_ROOT = Path(os.environ.get("TWINKLE_RESUME_ROOT", "output/durable-gsm8k")) @@ -172,6 +191,39 @@ def recover_from_journal(self, records: Iterable[Any]) -> None: self.register(int(version), str(checkpoint)) +def _recover_history(commits: list[Any]) -> list[dict[str, Any]]: + rows = [] + if HISTORY_PATH.is_file(): + with HISTORY_PATH.open(encoding="utf-8") as stream: + rows = [json.loads(line) for line in stream if line.strip()] + by_step = {int(row["optimizer_step"]): row for row in rows} + recovered = False + for record in commits: + manifest = record.payload.get("manifest") or {} + metrics = manifest.get("metrics") + step = manifest.get("optimizer_step") + if step is None or not isinstance(metrics, dict) or int(step) in by_step: + continue + by_step[int(step)] = { + "optimizer_step": int(step), + "policy_version": manifest.get("policy_version"), + "checkpoint": record.payload.get("checkpoint"), + "elapsed_s": manifest.get("elapsed_s"), + "metrics": metrics, + "driver": manifest.get("driver") or {}, + "recovered_from_journal": True, + } + recovered = True + rows = sorted(by_step.values(), key=lambda row: int(row["optimizer_step"])) + if recovered: + HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True) + atomic_write_bytes( + HISTORY_PATH, + "".join(json.dumps(row, ensure_ascii=False, default=str) + "\n" for row in rows).encode("utf-8"), + ) + return rows + + def create_gsm8k_dataset(): dataset = Dataset() dataset.add_dataset(DatasetMeta("ms://modelscope/gsm8k", subset_name="main", split="train")) @@ -271,6 +323,8 @@ def main() -> None: committed_records = [ record for record in store.journal.records() if record.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED ] + history = _recover_history(committed_records) + elapsed_offset = max((float(row.get("elapsed_s") or 0.0) for row in history), default=0.0) latest_checkpoint = policy_index.adapter_path(policy_index.latest_version) if latest_checkpoint is None: latest_checkpoint = model.save( @@ -333,7 +387,7 @@ def main() -> None: driver.load_state_dict() logger.info("resumed StreamingDriver from the latest stable boundary") - advantage_fn = GRPOAdvantage() + advantage_fn = GRPOAdvantage(num_generations=NUM_GENERATIONS) metrics = CompletionRewardMetric() logger.info(get_device_placement()) @@ -343,11 +397,8 @@ def main() -> None: if optim_step >= MAX_STEPS: break rewards = _score_vector(rows, facts) - advantages = advantage_fn( - rewards, - num_generations=NUM_GENERATIONS, - scale="group", - ).tolist() + rows, _ = advantage_fn(rows, scores=facts["scores"], global_step=optim_step) + advantages = [row["advantages"] for row in rows] old_logps = _old_logps(rows) completion_lengths = [sum(1 for label in (row.get("labels") or ()) if label != -100) for row in rows] metrics.accumulate( @@ -374,38 +425,35 @@ def main() -> None: async_save=False, ) next_version = policy_index.version() + 1 + log_dict = metrics.calculate() + log_dict.update(model.calculate_metric(is_training=True)) + step_record = { + "optimizer_step": optim_step, + "policy_version": next_version, + "checkpoint": str(checkpoint), + "elapsed_s": elapsed_offset + time.monotonic() - started, + "metrics": log_dict, + "driver": driver.stats(), + } driver.commit_batch( checkpoint, manifest={ "optimizer_step": optim_step, "policy_version": next_version, + "elapsed_s": step_record["elapsed_s"], + "metrics": log_dict, + "driver": step_record["driver"], }, ) policy_index.register(next_version, checkpoint) ckpt_manager.sync_weights(merge_and_sync=False) sampler.reset_prefix_cache() - log_dict = metrics.calculate() - log_dict.update(model.calculate_metric(is_training=True)) logger.info(f"[durable step {optim_step}/{MAX_STEPS}] {log_dict}") HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True) - with HISTORY_PATH.open("a", encoding="utf-8") as history: - history.write( - json.dumps( - { - "optimizer_step": optim_step, - "policy_version": next_version, - "checkpoint": str(checkpoint), - "elapsed_s": time.monotonic() - started, - "metrics": log_dict, - "driver": driver.stats(), - }, - ensure_ascii=False, - default=str, - ) - + "\n" - ) - history.flush() + with HISTORY_PATH.open("a", encoding="utf-8") as history_file: + history_file.write(json.dumps(step_record, ensure_ascii=False, default=str) + "\n") + history_file.flush() metrics.reset() finally: driver.close() diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 10ebd38e2..4121623e5 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -161,8 +161,9 @@ cookbook/rl/async_rl/durable_multi_turn_grpo.sh 示例使用官方 GSM8K、Qwen3.5、LoRA、真实多轮 rollout、GRPO 反向传播和 optimizer checkpoint,并在每个 batch 后调用 `commit_batch()`。每个已提交 step 的训练指标、policy -version、driver 计数和累计耗时追加到 `TWINKLE_RESUME_ROOT/training-metrics.jsonl`,重启后续写, -可据此绘制完整训练曲线。 +version、driver 计数和累计训练耗时(不含进程停止期间)写入 +`TWINKLE_RESUME_ROOT/training-metrics.jsonl`。指标同时随 checkpoint commit manifest 持久化; +如果进程在 commit 后、JSONL 追加前退出,重启会从 journal 回填该 step,保证曲线没有缺步。 聚焦测试: @@ -183,13 +184,21 @@ PYTHONPATH="$PWD/src" python -m pytest \ ## 实验结论与边界 -已验证: +在单张 Ascend 910B4、Qwen3-0.6B、vLLM 0.23.0 和 vLLM-Ascend 0.23.0 上,正式 cookbook +的两步 GSM8K 训练、after-save 和 after-commit 进程崩溃恢复均已跑通。两种故障恢复后的 +`history_steps` 与 `commit_steps` 都为 `[1, 2]`;after-commit 缺步指标可从 journal 回填。 -- 真实 Qwen3-0.6B LoRA 在 Ascend 910B4 上完成 optimizer step 后强杀; -- checkpoint 临时目录、已发布未提交、已提交三种边界均可正确回退或前进; -- 已提交 batch 不重复训练,未提交 optimizer 更新不泄漏; -- 无故障时 baseline 与 durable 的训练信号和评测结果逐值一致; -- 50% 组丢失故障下,保留完整组的 durable 路径在官方 GSM8K 测试集上取得显著提升。 +真实 vLLM A/B 在第 2、5 步保存 checkpoint 后、commit 前退出进程,结果如下: + +| 预算 | durable | cursor-restart | +|---|---|---| +| 固定 8 attempts | 8 optimizer steps,737 秒 | 6 optimizer steps,590 秒 | +| 固定 8 optimizer steps | 8 attempts,621 秒 | 10 attempts,623 秒 | + +固定 step 下减少 20% 的 rollout attempts,但本轮墙钟时间基本相同,不能宣称耗时提升。 +相同 64 条 held-out GSM8K 上,base、durable、cursor-restart 准确率分别为 45.3125%、 +46.875%、45.3125%;durable 的差值为 +1.5625pp,但 McNemar 双侧 `p=1.0`,不构成 +统计显著的质量提升证据。完整逐 step 曲线由四组 `training-metrics.jsonl` 生成。 尚未覆盖: @@ -198,5 +207,5 @@ PYTHONPATH="$PWD/src" python -m pytest \ - 无法 checkpoint 的远端 agent harness; - 所有外部工具协议都具备幂等结果查询。 -因此该机制不以“所有故障率下无条件提升”为结论,而是在完整组丢失或进程重启时保持 -GRPO 组语义、事务一致性和固定训练预算下的有效训练量。 +因此该机制的主要结论是进程重启时保持 GRPO 组语义、事务一致性、固定预算下的有效训练量, +并减少重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 05c7b882b..2488f0005 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -931,7 +931,11 @@ def load_state_dict(self, state: dict[str, Any] | None = None) -> None: self._counters["resumed_groups"] += len(self._groups) live = [episode for group in self._groups.values() for episode in group.members + group.baselines] loader_state = state.get("loader_state") - loader = getattr(self.dataloader, "load_state_dict", None) or getattr(self.dataloader, "set_state", None) + loader = ( + getattr(self.dataloader, "load_state_dict", None) + or getattr(self.dataloader, "load_state", None) + or getattr(self.dataloader, "set_state", None) + ) if loader_state is not None: if not callable(loader): raise UnsafeResume("snapshot has DataLoader state but the dataloader cannot load it") From 14644377fe1cc9a75551da97f69a12336af295b5 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Fri, 20 Nov 2026 02:35:44 +0800 Subject: [PATCH 09/45] docs(agentic): add multi-tool recovery evidence --- .../Agentic/DurableRolloutResume.md" | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 4121623e5..ccf485655 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -200,12 +200,45 @@ PYTHONPATH="$PWD/src" python -m pytest \ 46.875%、45.3125%;durable 的差值为 +1.5625pp,但 McNemar 双侧 `p=1.0`,不构成 统计显著的质量提升证据。完整逐 step 曲线由四组 `training-metrics.jsonl` 生成。 +### 长程多工具故障恢复对照 + +在相同单卡环境上使用 Qwen3-4B-Instruct-2507 进一步运行真实 vLLM 多工具 GRPO。每组实验包含 +10 个 optimizer steps,每个 batch 有 2 个 prompt 组、每组 2 条采样;每条完整 episode 执行 6 个 +订单工具阶段并生成最终回复。在 policy 0、3、6 的旧组仍在 rollout、且新 policy 已提交时终止进程, +三种实现均经历 3 次重启,最终 `history_steps` 都完整为 `[1, ..., 10]`。 + +实验使用真实模型生成和 `ToolManager` 调用,工具副作用写入持久化审计日志。`cursor-restart` 仅恢复 +数据游标并重新运行未提交工作;`naive-episode-resume` 是反例基线,恢复 episode 但重新绑定最新 policy, +不属于推荐实现。 + +| 指标 | durable | cursor-restart | naive-episode-resume | +|---|---:|---:|---:| +| 墙钟时间(秒) | 943 | 970 | 910 | +| 实际 generation 次数 | 449 | 495 | 458 | +| 实际生成 response tokens | 13018 | 14455 | 13349 | +| 跨重启重复 generation 次数 | 1 | 326 | 0 | +| 跨重启重复 response tokens | 14 | 9557 | 0 | +| 跨重启重复工具调用 | 0 | 76 | 0 | +| 其中重复非幂等工具调用 | 0 | 32 | 0 | +| episode 中途切换 policy 的数量 | 0 | 不适用(整组重启) | 26 | +| 错误重绑定产生的 generation / tokens | 0 / 0 | 不适用 | 65 / 1868 | + +durable 相对 cursor 的总生成 token 减少 9.941%,跨重启重复 token 减少 99.854%,并避免 76 次重复 +工具调用。只有一次 14-token generation 在故障边界重做,不能把该结果写成绝对零重复采样。单组墙钟 +差异不足以证明通用提速。 + +naive 的 26 条混采 episode 最终被 staleness 规则淘汰,交付 optimizer 的混采组为 0;因此本实验证明 +durable 消除了恢复时的错误 policy 切换,但不宣称已经量化混采对模型质量的损害。训练曲线和逐次生成、 +工具、lease、journal 原始记录均已留存。 + 尚未覆盖: - 可写 NFS 或对象存储上的 lease、journal 和 adapter 故障矩阵; -- 多卡 HCCL/FSDP2 和大模型验证; +- 多卡 HCCL/FSDP2 与多节点验证; +- vLLM-Ascend 0.23.0 在 CaMem sleep/wake 后激活多 policy LoRA 的稳定性;上述 4B 对照使用无 sleep + colocate 路径; - 无法 checkpoint 的远端 agent harness; - 所有外部工具协议都具备幂等结果查询。 因此该机制的主要结论是进程重启时保持 GRPO 组语义、事务一致性、固定预算下的有效训练量, -并减少重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 +并减少重复工具副作用和重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 From a0addae008704ba85b0c6a89a81f8af0a4567f92 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Fri, 20 Nov 2026 09:50:24 +0800 Subject: [PATCH 10/45] fix(agentic): close durable resume merge boundaries --- .../Agentic/DurableRolloutResume.md" | 18 ++++++++-- .../async_rl/streaming_driver.py | 4 +-- src/twinkle_agentic/envs/localenv.py | 5 ++- src/twinkle_agentic/rollout/multi_turn.py | 33 ++++++++++--------- tests/twinkle_agentic/test_localenv_resume.py | 15 +++++++++ .../test_streaming_driver_resume.py | 30 ++++++++++++++++- 6 files changed, 82 insertions(+), 23 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index ccf485655..384c27231 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -32,6 +32,10 @@ binding = GroupPolicyBinding( - `policy_version` 是该组采样时的 policy 版本。 - `adapter_path` 是该版本的 adapter 快照;`None` 表示使用基础模型。 +`adapter_path` 在一次 run 内必须指向不可变内容,不能原地覆盖或复用为另一个 policy;建议路径包含 +run、policy version 或 checkpoint generation。当前 binding 校验身份和路径一致性,不对远端 adapter +内容额外计算哈希,因此 artifact 不可变性由 checkpoint 管理层保证。 + 新 driver 快照同时写入结构化 `binding` 和旧版扁平字段。读取旧快照时会自动升级; binding 与扁平字段不一致时拒绝恢复。 @@ -90,7 +94,8 @@ driver.commit_batch( `commit_batch(checkpoint_ref, manifest)` 是 batch lease 与训练 checkpoint 的唯一关联点。 未提交前崩溃,恢复上一模型 checkpoint 并重交付同一 lease;已提交后崩溃,恢复新 -checkpoint 且不再交付该 lease。 +checkpoint 且不再交付该 lease。调用方必须先确保模型和 optimizer checkpoint 已完整持久化,再调用 +`commit_batch()`;driver 不探测通用远端 checkpoint 的落盘状态,也不能修复一个提前提交的引用。 ## ResumeStore 与 DurableJournal @@ -140,11 +145,15 @@ closed。只恢复文本对话、但丢失 workspace 或工具状态的实现不 3. checkpoint 持久化后写入 `TOOL_RESULT`。 恢复时如果存在 intent 但没有 checkpoint 能证明结果,整组状态被拒绝,不会再次执行非 -幂等外部调用。已完成且被 episode checkpoint 覆盖的 effect 直接复用记录结果。 +幂等外部调用。已完成且被 episode checkpoint 覆盖的 effect 直接复用记录结果。这一策略是 fail +closed,不等于为任意外部系统提供 exactly-once 执行;要继续该 uncertain effect,业务侧必须提供 +幂等键或结果查询/对账能力。 ## 兼容性 - `resume_store=None`:行为与原有 `StreamingDriver` 相同; +- 一个 `run_id` 只对应一个活跃 driver 写者;journal 文件锁用于保护事件链,不允许多个 driver + 共享同一 run 并分别覆盖 driver/lease 快照; - 旧 driver 快照:自动从 `version + adapter_path` 升级为 `GroupPolicyBinding`; - 未设置 checkpoint manager:仍可保存组和 lease,但不执行 policy 版本淘汰; - `ResumableEnv` 从 `twinkle_agentic.envs.resume` 或 `twinkle_agentic.envs` 导入; @@ -238,7 +247,10 @@ durable 消除了恢复时的错误 policy 切换,但不宣称已经量化混 - vLLM-Ascend 0.23.0 在 CaMem sleep/wake 后激活多 policy LoRA 的稳定性;上述 4B 对照使用无 sleep colocate 路径; - 无法 checkpoint 的远端 agent harness; -- 所有外部工具协议都具备幂等结果查询。 +- 所有外部工具协议都具备幂等结果查询; +- 大规模长训练的持久化开销尚未形成独立基准。当前 journal 追加会重扫事件链,driver 在稳定边界 + 保存完整状态,LocalEnv 每轮复制并校验 workspace;后续可分别评估增量扫描、按 episode 分片和 + 增量 workspace 快照,不能用当前端到端墙钟结果替代这些专项评估。 因此该机制的主要结论是进程重启时保持 GRPO 组语义、事务一致性、固定预算下的有效训练量, 并减少重复工具副作用和重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 2488f0005..cd7c0ffa1 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -625,12 +625,12 @@ def _retire_stale_group(self, group: _Group) -> None: self._counters["dropped_stale"] += len(group.members) self._counters["dropped_group"] += 1 if self.resume_store is not None: + self._persist_snapshot_locked() self.resume_store.journal.append( JournalEvent.GROUP_DROPPED, group.state_key, {"reason": "stale", "binding": group.binding.to_dict(), "current_version": self._version}, ) - self._persist_snapshot_locked() for episode in group.members + group.baselines: if episode.lost: continue @@ -1536,6 +1536,7 @@ def _drop_group(self, group: _Group) -> None: # waiting for its PRM scores, no step in flight; a stepping one is stopped when it returns self.rollout.stop(episode.traj, episode_id=episode.episode_id) if self.resume_store is not None: + self._persist_snapshot_locked() self.resume_store.journal.append( JournalEvent.GROUP_DROPPED, group.state_key, @@ -1545,7 +1546,6 @@ def _drop_group(self, group: _Group) -> None: "current_version": self._version, }, ) - self._persist_snapshot_locked() self._discard_group_state(group) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index e21bc2d5d..08740a7ac 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -219,6 +219,7 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: "files": len(tree["files"]), "bytes": tree["bytes"], "reward": session.reward, + "rewarded": session.rewarded, } def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any], trajectory=None) -> None: @@ -240,7 +241,9 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] self.reset(episode_id, trajectory) try: - self._session(episode_id).reward = float(state.get("reward") or 0.0) + session = self._session(episode_id) + session.reward = float(state.get("reward") or 0.0) + session.rewarded = bool(state.get("rewarded", session.reward != 0.0)) target = Path(self.workspace(episode_id)) shutil.copytree(source, target, dirs_exist_ok=True) except BaseException: diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index a5ecd9ba8..5955c0117 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -46,15 +46,15 @@ def _final_answer(traj: Trajectory) -> str: Multimodal content is a part list; the text parts concatenate in order. """ content = None - for message in reversed(traj.get('messages') or []): - if message.get('role') == 'assistant': - content = message.get('content') + for message in reversed(traj.get("messages") or []): + if message.get("role") == "assistant": + content = message.get("content") break if content is None: - return '' + return "" if isinstance(content, list): - return ''.join(str(part.get('text') or '') for part in content if isinstance(part, dict)) - return str(content or '') + return "".join(str(part.get("text") or "") for part in content if isinstance(part, dict)) + return str(content or "") def _dump_rollout_rows(episode_id: str, rows: list) -> None: @@ -996,22 +996,23 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: # the same sandbox; ``env=None`` (a tools-only local episode) falls back to a LocalEnv # over the row's own ``workspace`` column. check_score: float | None = None - if traj.get('checks') is not None: + if traj.get("checks") is not None: if self.env is not None and not ep.env_open: raise EpisodeError( - f'episode {ep.episode_id!r}: its env session is already closed, so its terminal ' - 'checks cannot see the state the agent left behind.') + f"episode {ep.episode_id!r}: its env session is already closed, so its terminal " + "checks cannot see the state the agent left behind." + ) try: - checks = checks_from_dicts(traj.get('checks')) + checks = checks_from_dicts(traj.get("checks")) except Exception as exc: - raise EpisodeError( - f'episode {ep.episode_id!r}: malformed checks column: {exc}') from exc - workspace = (self.env.workspace(ep.episode_id) if self.env is not None - else str(traj.get('workspace') or '')) + raise EpisodeError(f"episode {ep.episode_id!r}: malformed checks column: {exc}") from exc + workspace = self.env.workspace(ep.episode_id) if self.env is not None else str(traj.get("workspace") or "") report = run_checks( checks, - CheckContext(workspace=workspace, final_answer=_final_answer(traj), - env=self.env, episode_id=ep.episode_id)) + CheckContext( + workspace=workspace, final_answer=_final_answer(traj), env=self.env, episode_id=ep.episode_id + ), + ) check_score = float(report.score) env_reward: float | None = None if self.env is not None and ep.env_open: diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index 550a0e33b..b38ffbedd 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -42,6 +42,21 @@ def test_localenv_workspace_round_trip_uses_a_new_session(tmp_path): restored.close("episode-1") +def test_localenv_resume_preserves_scored_zero_reward(tmp_path): + source = LocalEnv(root=str(tmp_path)) + source.reset("episode-1") + session = source._session("episode-1") + session.rewarded = True + session.reward = 0.0 + state_key = "run-1/group-0/episode-1/attempt-0" + snapshot = source.checkpoint_episode("episode-1", state_key) + source.close("episode-1") + + restored = LocalEnv(root=str(tmp_path)) + restored.restore_episode("episode-1", state_key, snapshot) + assert restored.close("episode-1") == 0.0 + + def test_localenv_checkpoint_refuses_a_running_process(tmp_path): env = LocalEnv(root=str(tmp_path)) env.reset("episode-1") diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 7ce1ee1a1..f132461cf 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -3,7 +3,7 @@ import pytest -from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding, ResumeStore, UnsafeResume +from twinkle_agentic.async_rl.rollout_resume import GroupPolicyBinding, JournalEvent, ResumeStore, UnsafeResume from twinkle_agentic.async_rl.streaming_driver import _PENDING, StreamingDriver from twinkle_agentic.rollout.multi_turn import RolloutStatus @@ -586,6 +586,34 @@ def prm(rows): restored.close() +def test_group_drop_snapshot_precedes_journal_commit(tmp_path, monkeypatch): + store = ResumeStore(tmp_path, "run-drop-crash") + driver = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=2, num_generations=2, max_steps=1, resume_store=store + ) + driver._admit() + group = driver._groups["0"] + + append = store.journal.append + + def crash_on_drop_journal(event, state_key, payload=None): + if event == JournalEvent.GROUP_DROPPED: + raise RuntimeError("process exited before the drop journal commit") + return append(event, state_key, payload) + + monkeypatch.setattr(store.journal, "append", crash_on_drop_journal) + with pytest.raises(RuntimeError, match="before the drop journal commit"): + driver._drop_group(group) + + restored_rollout = _BlockingRollout() + restored = StreamingDriver( + _prompts(1), restored_rollout, batch_size=2, num_generations=2, max_steps=1, resume_store=store + ) + restored.load_state_dict() + assert restored._groups == {} + assert restored_rollout.calls == [] + + def test_terminal_group_snapshot_precedes_episode_state_cleanup(tmp_path): store = ResumeStore(tmp_path, "run-cleanup") rollout = _DoneRollout() From fbb27546a7145fbb9c68d0899d7eff0b8d29e769 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Fri, 20 Nov 2026 11:23:37 +0800 Subject: [PATCH 11/45] docs(agentic): record 8B and dual-device recovery evidence --- .../Agentic/DurableRolloutResume.md" | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 384c27231..f29e0754d 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -240,12 +240,31 @@ naive 的 26 条混采 episode 最终被 staleness 规则淘汰,交付 optimiz durable 消除了恢复时的错误 policy 切换,但不宣称已经量化混采对模型质量的损害。训练曲线和逐次生成、 工具、lease、journal 原始记录均已留存。 +### 8B、双卡与新版 CaMem 补充验证 + +在另一台单节点双卡 Ascend 910(64GB/卡)上,使用 Qwen3-8B、CANN 9.1.0、torch_npu 2.10.0.post7、 +vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: + +| 场景 | 结果 | +|---|---| +| 单卡无故障 | 完成 1 个 optimizer step 和 IPC 权重同步;训练与 vLLM 合计占用约 47.4GB | +| 单卡安全边界退出 | 1 次重启后恢复 2 组、4 条成员,完成 `[1,2,3]`;跨重启重复工具调用为 0 | +| 单卡不确定工具窗口 | pending intent 触发 fail closed,未重复执行非幂等工具;不将其算作训练恢复成功 | +| 双卡无故障 | 双 rank 训练完成,2 个 vLLM worker 均完成 IPC 权重同步 | +| 双卡安全边界退出 | 1 次重启后恢复 2 组、4 条成员,完成 `[1,2,3]`;重复工具及中途 policy 切换均为 0 | +| 单卡 CaMem 两步 | 两轮 weights/KV sleep-wake 和第二轮 LoRA-only 同步完成,未出现旧版 `aclnnInplaceCopy` 错误 | + +该结果只覆盖上述版本组合和单节点双卡,不回溯证明 vLLM/vLLM-Ascend 0.23.0,也不代表 FSDP2 +或多节点已经验证。本地 overlay 的规模基准显示,journal 在 250、500、1000、2000 事件时的平均追加 +延迟约为 1.89、3.53、6.71、13.16ms,确认全量重扫是优先优化项;64MiB LocalEnv workspace 快照约 +85ms,在该本地盘上暂不是主要瓶颈。 + 尚未覆盖: - 可写 NFS 或对象存储上的 lease、journal 和 adapter 故障矩阵; -- 多卡 HCCL/FSDP2 与多节点验证; +- 双卡 native_fsdp 以外的 FSDP2、多节点和更大规模验证; - vLLM-Ascend 0.23.0 在 CaMem sleep/wake 后激活多 policy LoRA 的稳定性;上述 4B 对照使用无 sleep - colocate 路径; + colocate 路径,新版结果不能替代旧版复测; - 无法 checkpoint 的远端 agent harness; - 所有外部工具协议都具备幂等结果查询; - 大规模长训练的持久化开销尚未形成独立基准。当前 journal 追加会重扫事件链,driver 在稳定边界 From a62e1a8b90dd48b06e2331a995ac982319abc1a1 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Fri, 20 Nov 2026 14:26:14 +0800 Subject: [PATCH 12/45] style(agentic): revert broad pre-commit formatting --- .../async_rl/rollout_resume.py | 4 +- .../async_rl/streaming_driver.py | 704 ++++++++---------- src/twinkle_agentic/envs/__init__.py | 19 +- src/twinkle_agentic/envs/base.py | 185 ++--- src/twinkle_agentic/envs/localenv.py | 213 +++--- src/twinkle_agentic/envs/resume.py | 38 +- src/twinkle_agentic/rollout/ledger.py | 45 +- src/twinkle_agentic/rollout/multi_turn.py | 695 ++++++++--------- 8 files changed, 876 insertions(+), 1027 deletions(-) diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 99bdfed4c..d86525a1a 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -108,7 +108,9 @@ def __post_init__(self) -> None: raise ValueError("group policy_version must be an integer") if self.policy_version < 0: raise ValueError("group policy_version must be >= 0") - if self.adapter_path is not None and (not isinstance(self.adapter_path, str) or not self.adapter_path.strip()): + if self.adapter_path is not None and ( + not isinstance(self.adapter_path, str) or not self.adapter_path.strip() + ): raise ValueError("group adapter_path must be a non-empty string when provided") def to_dict(self) -> dict[str, Any]: diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 68efb0170..0a4450bbf 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -21,7 +21,6 @@ queue when it finishes, and the driver's thread only reads that queue, so its cost does not grow with the number of episodes in flight. """ - from __future__ import annotations import copy import math @@ -31,9 +30,8 @@ import time import uuid from collections import deque -from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, field, replace -from typing import Any +from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence from twinkle import remote_class, remote_function from twinkle.data_format import user_data_get @@ -43,16 +41,16 @@ logger = get_logger() -__all__ = ["StreamingDriver", "PRM_SEGMENT_TURNS"] +__all__ = ['StreamingDriver', 'PRM_SEGMENT_TURNS'] #: The ``RolloutStatus.extra`` key recording each PRM segment's end: the episode's ``turns`` when the #: segment closed, one per column of ``prm_rewards``. -PRM_SEGMENT_TURNS = "prm_segment_turns" +PRM_SEGMENT_TURNS = 'prm_segment_turns' -_BASELINE = "baseline" +_BASELINE = 'baseline' -def _record_driver_probe(event: str, episode_id: str = "", **fields: Any) -> None: +def _record_driver_probe(event: str, episode_id: str = '', **fields: Any) -> None: """Append one driver event per call when ``TWINKLE_DRIVER_PROBE`` names a directory. The rollout-side dispatch probe shows an episode's opening step returning and then no @@ -71,20 +69,18 @@ def _record_driver_probe(event: str, episode_id: str = "", **fields: Any) -> Non import os import json - - root = os.environ.get("TWINKLE_DRIVER_PROBE") + root = os.environ.get('TWINKLE_DRIVER_PROBE') if not root: return os.makedirs(root, exist_ok=True) - path = os.path.join(root, f"driver.{os.getpid()}.jsonl") - with open(path, "a", encoding="utf-8") as handle: - handle.write( - json.dumps({"t": time.monotonic(), "event": event, "episode_id": episode_id, **fields}, default=str) + "\n" - ) + path = os.path.join(root, f'driver.{os.getpid()}.jsonl') + with open(path, 'a', encoding='utf-8') as handle: + handle.write(json.dumps({'t': time.monotonic(), 'event': event, 'episode_id': episode_id, + **fields}, default=str) + '\n') def _is_episode_error(exc: BaseException) -> bool: - return isinstance(exc, EpisodeError) or isinstance(getattr(exc, "cause", None), EpisodeError) + return isinstance(exc, EpisodeError) or isinstance(getattr(exc, 'cause', None), EpisodeError) def _role_of(traj: Any) -> str: @@ -93,15 +89,14 @@ def _role_of(traj: Any) -> str: The group verdict returns baseline rows to the driver before they are submitted; those rows may carry either spelling, so both are read -- writing is top-level only. """ - role = traj.get("role") + role = traj.get('role') if role is None: - role = user_data_get(traj.get("user_data"), "role") - return str(role or "") + role = user_data_get(traj.get('user_data'), 'role') + return str(role or '') -def _sample_facts( - samples: Sequence[RolloutStatus], scores: Sequence[dict[str, Any]], version_spans: Sequence[int] -) -> dict[str, Any]: +def _sample_facts(samples: Sequence[RolloutStatus], scores: Sequence[Dict[str, Any]], + version_spans: Sequence[int]) -> Dict[str, Any]: """The delivery facts of one batch, off the samples -- never the trajectories. The rows are never opened for this (under ray they are references): the lengths / @@ -109,8 +104,8 @@ def _sample_facts( columns arrive row-aligned in ``scores`` -- the one payload-adjacent lane, which the advantage estimator and the reward metrics consume without materialising a trajectory. """ - prompt_lengths: list[int] = [] - response_lengths: list[int] = [] + prompt_lengths: List[int] = [] + response_lengths: List[int] = [] for sample in samples: tokens = sample.token_lengths # None means the episode never produced an encoded frame (an empty prompt); a delivered @@ -119,26 +114,25 @@ def _sample_facts( response_lengths.append(tokens[1] if tokens else 0) truncated = [bool(sample.truncated) for sample in samples] return { - "num_rows": len(samples), - "episode_ids": [sample.episode_id for sample in samples], - "prompt_lengths": prompt_lengths, - "response_lengths": response_lengths, - "response_length_min": min(response_lengths) if response_lengths else 0, - "response_length_max": max(response_lengths) if response_lengths else 0, - "response_length_sum": sum(response_lengths), - "policy_versions": sorted({sample.policy_version for sample in samples}), - "truncated": truncated, - "num_truncated": sum(truncated), - "turns": [sample.turns for sample in samples], - "version_spans": list(version_spans), - "scores": list(scores), + 'num_rows': len(samples), + 'episode_ids': [sample.episode_id for sample in samples], + 'prompt_lengths': prompt_lengths, + 'response_lengths': response_lengths, + 'response_length_min': min(response_lengths) if response_lengths else 0, + 'response_length_max': max(response_lengths) if response_lengths else 0, + 'response_length_sum': sum(response_lengths), + 'policy_versions': sorted({sample.policy_version for sample in samples}), + 'truncated': truncated, + 'num_truncated': sum(truncated), + 'turns': [sample.turns for sample in samples], + 'version_spans': list(version_spans), + 'scores': list(scores), } @dataclass class _Group: """One prompt row's episodes: the current attempt's members and the baseline episodes it waits for.""" - key: str row: Any #: Fixed for the group's whole lifetime. Recovery and replacement members must use this @@ -146,9 +140,9 @@ class _Group: binding: GroupPolicyBinding attempt: int = 0 #: The current attempt's member trajectories, aligned with ``members`` (a lost one is redone from here). - source: list[Any] = field(default_factory=list) - members: list[_Episode] = field(default_factory=list) - baselines: list[_Episode] = field(default_factory=list) + source: List[Any] = field(default_factory=list) + members: List['_Episode'] = field(default_factory=list) + baselines: List['_Episode'] = field(default_factory=list) #: Members of the current attempt that will not produce a sample (failed, stopped, dropped). missing: int = 0 @@ -161,7 +155,7 @@ def version(self) -> int: return self.binding.policy_version @property - def adapter_path(self) -> str | None: + def adapter_path(self) -> Optional[str]: return self.binding.adapter_path @@ -172,12 +166,12 @@ class _Episode: role: str version: int traj: Any = None - sample: RolloutStatus | None = None + sample: Optional[RolloutStatus] = None done: bool = False #: Set once the episode has no further work: scored (``finished``) or given up (``lost``). finished: bool = False lost: bool = False - orm: list[Any] | None = None + orm: Optional[List[Any]] = None orm_pending: int = 0 prm: list[list[Any]] | None = None prm_turns: list[int] = field(default_factory=list) @@ -186,17 +180,17 @@ class _Episode: prm_inputs: list[Any] = field(default_factory=list) prm_pending: int = 0 #: The PRM segment the episode waits for before its next step (only with ``on_step``). - held: int | None = None + held: Optional[int] = None #: The episode's training rows as the last step returned them (one, or one per collected #: segment); an unfinished episode holds none. - deliver: list[Any] = field(default_factory=list) + deliver: List[Any] = field(default_factory=list) #: The trajectory this episode was submitted with, kept so a no-slot retry can resubmit the same #: member slot without touching group_attempt or the quality-regeneration budget. submit_traj: Any = None #: No-slot retry state (scheduling delay, not failure): when to retry next, the wall-clock deadline #: after which the group is dropped, and how many no-slot returns this member has accumulated. - no_slot_retry_at: float | None = None - no_slot_deadline: float | None = None + no_slot_retry_at: Optional[float] = None + no_slot_deadline: Optional[float] = None no_slot_attempts: int = 0 #: Whether this episode currently contributes 1 to ``_inflight``. True from submission until it #: finishes, is lost, or returns no-slot (the call returned, the member waits to retry). Lets @@ -205,7 +199,7 @@ class _Episode: counted_inflight: bool = False -@remote_class(execute="first", max_concurrency=8) +@remote_class(execute='first', max_concurrency=8) class StreamingDriver: """Stream episodes through ``rollout`` and hand out scored groups; iterate it for training batches. @@ -268,53 +262,48 @@ class StreamingDriver: NO_SLOT_MAX_DELAY = 15.0 NO_SLOT_JITTER = 0.5 - def __init__( - self, - dataloader: Any, - rollout: Any, - *, - batch_size: int, - num_generations: int = 1, - num_epochs: float = 1.0, - max_steps: int | None = None, - max_staleness: int = 0, - sync_interval: int = 1, - checkpoint_manager: Any = None, - orms: Sequence[Any] = (), - orm_names: Sequence[str] | None = None, - prms: Sequence[Any] = (), - prm_names: Sequence[str] | None = None, - prm_segment: Callable[[RolloutStatus, Any], bool] | None = None, - on_step: Callable[[RolloutStatus, list[Any]], bool] | None = None, - on_sample: Callable[[RolloutStatus], bool | None] | None = None, - on_group: Callable[[Any, list[RolloutStatus], int], list[Any]] | None = None, - max_group_regenerations: int = 0, - cluster_adapter: Any = None, - max_no_slot_wait: float = 1800.0, - resume_store: ResumeStore | None = None, - run_id: str | None = None, - ): + def __init__(self, + dataloader: Any, + rollout: Any, + *, + batch_size: int, + num_generations: int = 1, + num_epochs: float = 1.0, + max_steps: Optional[int] = None, + max_staleness: int = 0, + sync_interval: int = 1, + checkpoint_manager: Any = None, + orms: Sequence[Any] = (), + orm_names: Optional[Sequence[str]] = None, + prms: Sequence[Any] = (), + prm_names: Optional[Sequence[str]] = None, + prm_segment: Optional[Callable[[RolloutStatus, Any], bool]] = None, + on_step: Optional[Callable[[RolloutStatus, List[Any]], bool]] = None, + on_sample: Optional[Callable[[RolloutStatus], Optional[bool]]] = None, + on_group: Optional[Callable[[Any, List[RolloutStatus], int], List[Any]]] = None, + max_group_regenerations: int = 0, + cluster_adapter: Any = None, + max_no_slot_wait: float = 1800.0, + resume_store: Optional[ResumeStore] = None, + run_id: Optional[str] = None): if num_generations < 1 or batch_size < 1 or batch_size % num_generations: - raise ValueError( - f"batch_size ({batch_size}) must be a positive multiple of num_generations " - f"({num_generations}): a batch holds whole groups." - ) + raise ValueError(f'batch_size ({batch_size}) must be a positive multiple of num_generations ' + f'({num_generations}): a batch holds whole groups.') if num_epochs <= 0: - raise ValueError(f"num_epochs must be > 0, got {num_epochs}.") + raise ValueError(f'num_epochs must be > 0, got {num_epochs}.') if max_staleness < 0 or sync_interval < 1: - raise ValueError( - f"max_staleness must be >= 0 and sync_interval >= 1, got {max_staleness} / {sync_interval}." - ) + raise ValueError(f'max_staleness must be >= 0 and sync_interval >= 1, got {max_staleness} / ' + f'{sync_interval}.') if on_step is not None and not prms: - raise ValueError("on_step reads PRM scores; pass prms= or drop on_step.") + raise ValueError('on_step reads PRM scores; pass prms= or drop on_step.') self.orms = list(orms) - self.orm_names = list(orm_names) if orm_names is not None else [f"orm_{i}" for i in range(len(self.orms))] + self.orm_names = list(orm_names) if orm_names is not None else [f'orm_{i}' for i in range(len(self.orms))] if len(self.orm_names) != len(self.orms): - raise ValueError(f"orm_names ({len(self.orm_names)}) must name every ORM ({len(self.orms)}).") + raise ValueError(f'orm_names ({len(self.orm_names)}) must name every ORM ({len(self.orms)}).') self.prms = list(prms) - self.prm_names = list(prm_names) if prm_names is not None else [f"prm_{i}" for i in range(len(self.prms))] + self.prm_names = list(prm_names) if prm_names is not None else [f'prm_{i}' for i in range(len(self.prms))] if len(self.prm_names) != len(self.prms): - raise ValueError(f"prm_names ({len(self.prm_names)}) must name every PRM ({len(self.prms)}).") + raise ValueError(f'prm_names ({len(self.prm_names)}) must name every PRM ({len(self.prms)}).') self.dataloader = dataloader self.rollout = rollout self.batch_size = batch_size @@ -333,23 +322,23 @@ def __init__( self.resume_store = resume_store self.run_id = run_id or (resume_store.run_id if resume_store is not None else uuid.uuid4().hex) if resume_store is not None and run_id is not None and run_id != resume_store.run_id: - raise ValueError(f"run_id {run_id!r} does not match resume store run {resume_store.run_id!r}") + raise ValueError(f'run_id {run_id!r} does not match resume store run {resume_store.run_id!r}') #: Wall-clock ceiling on how long one member may keep retrying a full session pool before its #: group is loudly dropped. Scheduling delay is not quality regeneration: it never spends #: max_group_regenerations or increments group_attempt, but it must still be bounded. self.max_no_slot_wait = max_no_slot_wait self._lock = threading.Condition() - self._events: queue.Queue[tuple[Any, ...]] = queue.Queue() + self._events: 'queue.Queue[tuple[Any, ...]]' = queue.Queue() self._ready: deque = deque() self._ready_rows = 0 - self._thread: threading.Thread | None = None + self._thread: Optional[threading.Thread] = None self._closed = False self._exhausted = False - self._error: BaseException | None = None - self._rows: Iterator[Any] | None = None + self._error: Optional[BaseException] = None + self._rows: Optional[Iterator[Any]] = None self._prompt_seq = 0 - self._groups: dict[str, _Group] = {} + self._groups: Dict[str, _Group] = {} #: Member rows admitted and not dropped (baselines excluded): what the version bound caps. self._live = 0 self._inflight = 0 @@ -358,18 +347,10 @@ def __init__( self._base_version = 0 self._failures: deque = deque(maxlen=self.FAILURE_WINDOW) self._consecutive_failures = 0 - self._counters: dict[str, int] = { - "admitted": 0, - "dropped_stale": 0, - "dropped_sample": 0, - "dropped_group": 0, - "episode_errors": 0, - "stopped": 0, - "regenerated": 0, - "no_slot": 0, - "no_slot_dropped": 0, - "resumed_groups": 0, - "resumed_members": 0, + self._counters: Dict[str, int] = { + 'admitted': 0, 'dropped_stale': 0, 'dropped_sample': 0, 'dropped_group': 0, 'episode_errors': 0, + 'stopped': 0, 'regenerated': 0, 'no_slot': 0, 'no_slot_dropped': 0, + 'resumed_groups': 0, 'resumed_members': 0, } self._adjusting = False #: monotonic stamps: when the running ``adjust`` started, and when its being stuck was last reported. @@ -382,35 +363,33 @@ def __init__( #: the lend->reclaim cycle now in flight (the thread, until the reclaim in ``_next_batch``'s #: finally completes): while it runs the adapter's lock is legitimately held self._lending = None - self._returned_at: float | None = None + self._returned_at: Optional[float] = None self._idle_ratio = 0.0 self._iter_started = False #: The one batch whose model update may or may not have committed. It survives a process #: restart and is handed out again until ``commit_batch`` records the model checkpoint. - self._lease: dict[str, Any] | None = None + self._lease: Optional[Dict[str, Any]] = None self._lease_returned = False # ------------------------------------------------------------------ iteration - @remote_function(execute="first", collect="first", lazy_collect=False, stash=(0,)) + @remote_function(execute='first', collect='first', lazy_collect=False, stash=(0,)) def __iter__(self): """Iterate the driver once: ``(rows, facts)`` per batch, delivered together.""" if self._iter_started: - raise RuntimeError( - "StreamingDriver serves ONE iteration per run; a second one would re-read " - "the dataloader from an unrelated position. Wrap the single iterator instead." - ) + raise RuntimeError('StreamingDriver serves ONE iteration per run; a second one would re-read ' + 'the dataloader from an unrelated position. Wrap the single iterator instead.') self._iter_started = True return self._batches() - def _batches(self) -> Iterator[list[Any]]: + def _batches(self) -> Iterator[List[Any]]: while True: batch = self._next_batch() if batch is None: return yield batch - def _next_batch(self) -> tuple | None: + def _next_batch(self) -> Optional[tuple]: """Wait for ``batch_size`` rows of complete, fresh groups; ``None`` once nothing more will come. A delivery is ``(rows, facts)``: the rows exactly as they travel (a reference under ray, @@ -425,12 +404,10 @@ def _next_batch(self) -> tuple | None: self._lease_returned = False elif not self._lease_returned: self._lease_returned = True - return self._lease["rows"], self._lease["facts"] + return self._lease['rows'], self._lease['facts'] else: - raise UnsafeResume( - f"batch lease {self._lease['lease_id']!r} is still open; " - "call commit_batch() after the model checkpoint is durable" - ) + raise UnsafeResume(f'batch lease {self._lease["lease_id"]!r} is still open; ' + 'call commit_batch() after the model checkpoint is durable') self._start() started = time.monotonic() waited = 0.0 @@ -447,7 +424,7 @@ def _next_batch(self) -> tuple | None: # the trainer waits from here on: its devices may be lent until the batch is ready lending = None if self.cluster_adapter is not None and short: - lending = threading.Thread(target=self._lend, args=(waited,), name="twinkle-cluster-lend", daemon=True) + lending = threading.Thread(target=self._lend, args=(waited,), name='twinkle-cluster-lend', daemon=True) lending.start() #: mirrors ``lending`` from its start until the reclaim below completes -- an ``adjust`` #: queued behind that cycle is not stuck, so the watchdog stays quiet while it runs @@ -491,45 +468,36 @@ def _next_batch(self) -> tuple | None: versions = [episode.version for episode in members] if versions and max(versions) - min(versions) > self.max_staleness: raise RuntimeError( - f"ready group spans {max(versions) - min(versions)} policy versions " - f"({min(versions)}..{max(versions)}), more than max_staleness=" - f"{self.max_staleness}; per-member staleness left an over-age member." - ) - trajs: list[Any] = [] - samples: list[RolloutStatus] = [] - scores: list[dict[str, Any]] = [] - version_spans: list[int] = [] + f'ready group spans {max(versions) - min(versions)} policy versions ' + f'({min(versions)}..{max(versions)}), more than max_staleness=' + f'{self.max_staleness}; per-member staleness left an over-age member.') + trajs: List[Any] = [] + samples: List[RolloutStatus] = [] + scores: List[Dict[str, Any]] = [] + version_spans: List[int] = [] while len(trajs) < self.batch_size and self._ready: ready_group = self._ready.popleft() self._live -= sum(1 for episode in ready_group if episode.deliver) for episode in ready_group: episode.sample.version_span = self._version - episode.sample.policy_version score = self._score_update(episode) - lengths = (episode.sample.extra or {}).get("row_token_lengths") + lengths = (episode.sample.extra or {}).get('row_token_lengths') if len(episode.deliver) == 1 or not lengths: # The identity path: one row carries the episode's own facts verbatim. row_samples = [episode.sample] * len(episode.deliver) else: if len(lengths) != len(episode.deliver): raise RuntimeError( - f"episode {episode.sample.episode_id!r}: {len(episode.deliver)} delivered rows " - f"but {len(lengths)} row lengths on its status." - ) + f'episode {episode.sample.episode_id!r}: {len(episode.deliver)} delivered rows ' + f'but {len(lengths)} row lengths on its status.') # A collected episode's rows carry their own length facts: the episode # totals would repeat on every row and weigh the metrics by row count. - extra = { - key: value - for key, value in (episode.sample.extra or {}).items() - if key != "row_token_lengths" - } + extra = {key: value for key, value in (episode.sample.extra or {}).items() + if key != 'row_token_lengths'} row_samples = [ - replace( - episode.sample, - token_lengths=tuple(map(int, pair)), - extra=dict(extra, segment_index=index), - ) - for index, pair in enumerate(lengths) - ] + replace(episode.sample, token_lengths=tuple(map(int, pair)), + extra=dict(extra, segment_index=index)) + for index, pair in enumerate(lengths)] for row, row_sample in zip(episode.deliver, row_samples, strict=True): trajs.append(row) samples.append(row_sample) @@ -538,32 +506,32 @@ def _next_batch(self) -> tuple | None: self._ready_rows -= len(trajs) batch_index = self._handed facts = _sample_facts(samples, scores, version_spans) - lease_id = f"{self.run_id}/batch/{batch_index}" + lease_id = f'{self.run_id}/batch/{batch_index}' self._lease = { - "lease_id": lease_id, - "batch": batch_index, - "policy_versions": list(facts["policy_versions"]), - "rows": trajs, - "facts": facts, + 'lease_id': lease_id, + 'batch': batch_index, + 'policy_versions': list(facts['policy_versions']), + 'rows': trajs, + 'facts': facts, } self._lease_returned = True self._handed += 1 if self.resume_store is not None: - self.resume_store.save_object("leases", lease_id, self._lease) + self.resume_store.save_object('leases', lease_id, self._lease) # The snapshot must point at the lease before the journal makes # it durable. A crash in between re-delivers this same lease; # the reverse order could strand the lease object unreferenced. self._persist_snapshot_locked() self.resume_store.journal.append( - JournalEvent.BATCH_LEASED, lease_id, {"batch": batch_index, "rows": len(trajs), "object": lease_id} - ) + JournalEvent.BATCH_LEASED, lease_id, + {'batch': batch_index, 'rows': len(trajs), 'object': lease_id}) self._lock.notify_all() self._returned_at = time.monotonic() self._wait_time = self._returned_at - started _record_driver_probe("batch_handed", rows=len(trajs), handed=self._handed, waited=self._wait_time) return trajs, facts - def _score_update(self, episode: _Episode) -> dict[str, Any]: + def _score_update(self, episode: _Episode) -> Dict[str, Any]: """One row's light score entry, off the private bookkeeping -- never written onto the row. The entry mirrors the row's column contract (``rewards.orm`` / ``rewards.baseline`` map @@ -575,35 +543,24 @@ def _score_update(self, episode: _Episode) -> dict[str, Any]: ``rewards.env`` stays on the row, where its producer wrote it. """ sample = episode.sample - rewards: dict[str, Any] = { - "orm": { - name: (None if value is None else float(value)) - for name, value in zip(self.orm_names, episode.orm or (), strict=True) - }, + rewards: Dict[str, Any] = { + 'orm': {name: (None if value is None else float(value)) + for name, value in zip(self.orm_names, episode.orm or (), strict=True)}, } if sample.baseline is not None: - rows = ( - sample.baseline - if (sample.baseline and isinstance(sample.baseline[0], (list, tuple))) + rows = sample.baseline if (sample.baseline and isinstance(sample.baseline[0], (list, tuple))) \ else [sample.baseline] - ) if len(rows) != 1: - raise RuntimeError( - f"episode {episode.episode_id} carries {len(rows)} baseline rows; the named " - "baseline column carries one. Return a single baseline per group." - ) - rewards["baseline"] = { - name: (None if value is None else float(value)) - for name, value in zip(self.orm_names, rows[0], strict=True) - } - score: dict[str, Any] = {"rewards": rewards} + raise RuntimeError(f'episode {episode.episode_id} carries {len(rows)} baseline rows; the named ' + 'baseline column carries one. Return a single baseline per group.') + rewards['baseline'] = {name: (None if value is None else float(value)) + for name, value in zip(self.orm_names, rows[0], strict=True)} + score: Dict[str, Any] = {'rewards': rewards} if episode.prm is not None: - score["prm_segments"] = { - "end_turns": [int(turns) for turns in episode.prm_turns], - "scores": { - name: [(None if value is None else float(value)) for value in column] - for name, column in zip(self.prm_names, episode.prm, strict=True) - }, + score['prm_segments'] = { + 'end_turns': [int(turns) for turns in episode.prm_turns], + 'scores': {name: [(None if value is None else float(value)) for value in column] + for name, column in zip(self.prm_names, episode.prm, strict=True)}, } return score @@ -630,8 +587,8 @@ def _drop_stale(self) -> None: def _retire_stale_group(self, group: _Group) -> None: """Drop one group atomically after its pinned policy leaves the staleness window.""" self._groups.pop(group.key, None) - self._counters["dropped_stale"] += len(group.members) - self._counters["dropped_group"] += 1 + self._counters['dropped_stale'] += len(group.members) + self._counters['dropped_group'] += 1 if self.resume_store is not None: self._persist_snapshot_locked() self.resume_store.journal.append( @@ -648,25 +605,18 @@ def _retire_stale_group(self, group: _Group) -> None: self._live -= 1 self._discard_group_state(group) - @remote_function(execute="first", collect="first", lazy_collect=False) - def stats(self) -> dict[str, Any]: + @remote_function(execute='first', collect='first', lazy_collect=False) + def stats(self) -> Dict[str, Any]: """Counters of the run so far (small; for logging).""" with self._lock: - return dict( - self._counters, - version=self._version, - handed=self._handed, - inflight=self._inflight, - live=self._live, - ready_rows=self._ready_rows, - train_idle_ratio=self._idle_ratio, - ) + return dict(self._counters, version=self._version, handed=self._handed, inflight=self._inflight, + live=self._live, ready_rows=self._ready_rows, train_idle_ratio=self._idle_ratio) def _loader_state(self) -> Any: - getter = getattr(self.dataloader, "state_dict", None) or getattr(self.dataloader, "get_state", None) + getter = getattr(self.dataloader, 'state_dict', None) or getattr(self.dataloader, 'get_state', None) return copy.deepcopy(getter()) if callable(getter) else None - def _episode_state(self, episode: _Episode) -> dict[str, Any]: + def _episode_state(self, episode: _Episode) -> Dict[str, Any]: now = time.monotonic() return { "episode_id": episode.episode_id, @@ -697,36 +647,36 @@ def _episode_state(self, episode: _Episode) -> dict[str, Any]: "counted_inflight": episode.counted_inflight, } - def _group_state(self, group: _Group) -> dict[str, Any]: + def _group_state(self, group: _Group) -> Dict[str, Any]: return { - "key": group.key, - "row": group.row, - "binding": group.binding.to_dict(), + 'key': group.key, + 'row': group.row, + 'binding': group.binding.to_dict(), # Flat fields keep snapshots readable by earlier draft readers. - "version": group.version, - "adapter_path": group.adapter_path, - "attempt": group.attempt, - "source": list(group.source), - "members": [self._episode_state(episode) for episode in group.members], - "baselines": [self._episode_state(episode) for episode in group.baselines], - "missing": group.missing, + 'version': group.version, + 'adapter_path': group.adapter_path, + 'attempt': group.attempt, + 'source': list(group.source), + 'members': [self._episode_state(episode) for episode in group.members], + 'baselines': [self._episode_state(episode) for episode in group.baselines], + 'missing': group.missing, } - def _snapshot(self) -> dict[str, Any]: + def _snapshot(self) -> Dict[str, Any]: return { - "format": "twinkle.streaming-driver.v1", - "run_id": self.run_id, - "handed": self._handed, - "prompts_drawn": self._prompt_seq, - "version": self._version, - "base_version": self._base_version, - "exhausted": self._exhausted, - "counters": dict(self._counters), - "loader_state": self._loader_state(), - "groups": [self._group_state(group) for group in self._groups.values()], - "ready": [[self._episode_state(episode) for episode in members] for members in self._ready], - "ready_groups": [self._group_state(members[0].group) for members in self._ready if members], - "lease": self._lease, + 'format': 'twinkle.streaming-driver.v1', + 'run_id': self.run_id, + 'handed': self._handed, + 'prompts_drawn': self._prompt_seq, + 'version': self._version, + 'base_version': self._base_version, + 'exhausted': self._exhausted, + 'counters': dict(self._counters), + 'loader_state': self._loader_state(), + 'groups': [self._group_state(group) for group in self._groups.values()], + 'ready': [[self._episode_state(episode) for episode in members] for members in self._ready], + 'ready_groups': [self._group_state(members[0].group) for members in self._ready if members], + 'lease': self._lease, } def _persist_snapshot_locked(self) -> None: @@ -738,10 +688,10 @@ def _persist_snapshot_locked(self) -> None: uses it to retire a lease even when the following snapshot was torn. """ if self.resume_store is not None: - self.resume_store.save_object("driver", self.run_id, self._snapshot()) + self.resume_store.save_object('driver', self.run_id, self._snapshot()) - @remote_function(execute="first", collect="first", lazy_collect=False) - def state_dict(self) -> dict[str, Any]: + @remote_function(execute='first', collect='first', lazy_collect=False) + def state_dict(self) -> Dict[str, Any]: """Snapshot prompts, complete groups, ready groups and the open batch lease. Live episodes are paired with their last durable rollout turn checkpoint. A checkpoint taken @@ -751,10 +701,10 @@ def state_dict(self) -> dict[str, Any]: with self._lock: state = self._snapshot() if self.resume_store is not None: - self.resume_store.save_object("driver", self.run_id, state) + self.resume_store.save_object('driver', self.run_id, state) return state - def _restore_episode(self, state: dict[str, Any], group: _Group) -> _Episode: + def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: episode = _Episode( episode_id=str(state["episode_id"]), group=group, @@ -776,62 +726,60 @@ def _restore_episode(self, state: dict[str, Any], group: _Group) -> _Episode: episode.deliver = list(state.get("deliver") or ()) episode.submit_traj = state.get("submit_traj") now = time.monotonic() - if state.get("no_slot_retry_in") is not None: - episode.no_slot_retry_at = now + float(state["no_slot_retry_in"]) - if state.get("no_slot_deadline_in") is not None: - episode.no_slot_deadline = now + float(state["no_slot_deadline_in"]) - episode.no_slot_attempts = int(state.get("no_slot_attempts") or 0) - episode.counted_inflight = bool(state.get("counted_inflight")) + if state.get('no_slot_retry_in') is not None: + episode.no_slot_retry_at = now + float(state['no_slot_retry_in']) + if state.get('no_slot_deadline_in') is not None: + episode.no_slot_deadline = now + float(state['no_slot_deadline_in']) + episode.no_slot_attempts = int(state.get('no_slot_attempts') or 0) + episode.counted_inflight = bool(state.get('counted_inflight')) return episode - def _restore_group(self, state: dict[str, Any]) -> _Group: - members = state.get("members") or () - member_version = next((int(item.get("version") or 0) for item in members if item.get("version") is not None), 0) - version = int(state.get("version") if state.get("version") is not None else member_version) - adapter_path = state.get("adapter_path") - raw_binding = state.get("binding") + def _restore_group(self, state: Dict[str, Any]) -> _Group: + members = state.get('members') or () + member_version = next( + (int(item.get('version') or 0) for item in members if item.get('version') is not None), 0) + version = int(state.get('version') if state.get('version') is not None else member_version) + adapter_path = state.get('adapter_path') + raw_binding = state.get('binding') if raw_binding is not None: try: binding = GroupPolicyBinding.from_dict(raw_binding) except (TypeError, ValueError) as exc: - raise UnsafeResume(f"invalid group policy binding: {exc}") from exc - if state.get("version") is not None and int(state["version"]) != binding.policy_version: + raise UnsafeResume(f'invalid group policy binding: {exc}') from exc + if state.get('version') is not None and int(state['version']) != binding.policy_version: raise UnsafeResume( - f"group binding version {binding.policy_version} disagrees with snapshot version {state['version']}" - ) - if "adapter_path" in state and state.get("adapter_path") != binding.adapter_path: - raise UnsafeResume("group binding adapter_path disagrees with the flat snapshot field") + f'group binding version {binding.policy_version} disagrees with snapshot version ' + f'{state["version"]}') + if 'adapter_path' in state and state.get('adapter_path') != binding.adapter_path: + raise UnsafeResume('group binding adapter_path disagrees with the flat snapshot field') version = binding.policy_version adapter_path = binding.adapter_path else: binding = GroupPolicyBinding( - state_key=str(state.get("state_key") or f"{self.run_id}/group/{state.get('key')}"), + state_key=str(state.get('state_key') or f'{self.run_id}/group/{state.get("key")}'), policy_version=version, adapter_path=adapter_path, ) - expected_state_key = f"{self.run_id}/group/{state.get('key')}" + expected_state_key = f'{self.run_id}/group/{state.get("key")}' if binding.state_key != expected_state_key: - raise UnsafeResume(f"group binding state_key {binding.state_key!r} does not match {expected_state_key!r}") + raise UnsafeResume( + f'group binding state_key {binding.state_key!r} does not match {expected_state_key!r}') # A legacy flat snapshot had no binding, so the manager may upgrade its # missing adapter path. An explicit binding with adapter_path=None # means the base model and must not be silently rebound to an adapter. if raw_binding is None and adapter_path is None and self.checkpoint_manager is not None: - lookup = getattr(self.checkpoint_manager, "adapter_path", None) + lookup = getattr(self.checkpoint_manager, 'adapter_path', None) if callable(lookup): adapter_path = lookup(version) if adapter_path is None: - raise UnsafeResume(f"policy version {version} has no resolvable adapter path") + raise UnsafeResume(f'policy version {version} has no resolvable adapter path') binding = replace(binding, adapter_path=adapter_path) group = _Group( - key=str(state["key"]), - row=state.get("row"), - binding=binding, - attempt=int(state.get("attempt") or 0), - source=list(state.get("source") or ()), - missing=int(state.get("missing") or 0), - ) - group.members = [self._restore_episode(item, group) for item in state.get("members") or ()] - group.baselines = [self._restore_episode(item, group) for item in state.get("baselines") or ()] + key=str(state['key']), row=state.get('row'), binding=binding, + attempt=int(state.get('attempt') or 0), + source=list(state.get('source') or ()), missing=int(state.get('missing') or 0)) + group.members = [self._restore_episode(item, group) for item in state.get('members') or ()] + group.baselines = [self._restore_episode(item, group) for item in state.get('baselines') or ()] return group def _resume_scores(self, episode: _Episode) -> None: @@ -841,8 +789,7 @@ def _resume_scores(self, episode: _Episode) -> None: continue future = self.orms[index]([episode.traj]) future.add_done_callback( - lambda f, episode=episode, index=index: self._events.put(("orm", episode, index, f)) - ) + lambda f, episode=episode, index=index: self._events.put(('orm', episode, index, f))) for scorer, column in enumerate(episode.prm or ()): for segment, value in enumerate(column): if value is not _PENDING: @@ -853,8 +800,7 @@ def _resume_scores(self, episode: _Episode) -> None: ) future = self.prms[scorer]([episode.prm_inputs[segment]]) future.add_done_callback( - lambda f, episode=episode, key=(segment, scorer): self._events.put(("prm", episode, key, f)) - ) + lambda f, episode=episode, key=(segment, scorer): self._events.put(('prm', episode, key, f))) def _resume_live_episode(self, episode: _Episode) -> None: if episode.finished or episode.lost: @@ -871,56 +817,55 @@ def _resume_live_episode(self, episode: _Episode) -> None: if self.resume_store is not None and state_key and self.resume_store.has_object("episodes", state_key): self.rollout.restore_episode_from_store(state_key) route = dict(episode.traj or episode.submit_traj or {}) - route.setdefault("turns", 0) + route.setdefault('turns', 0) self._step(episode, route) else: # No turn boundary committed yet: opening the episode again repeats no external tool call. self._step(episode, episode.submit_traj) - @remote_function(execute="first", collect="first", lazy_collect=False) - def load_state_dict(self, state: dict[str, Any] | None = None) -> None: + @remote_function(execute='first', collect='first', lazy_collect=False) + def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: """Rebuild a fresh driver from a snapshot, or from the store's latest snapshot.""" if state is None: if self.resume_store is None: - raise UnsafeResume("load_state_dict() without state needs a resume store") - state = self.resume_store.load_object("driver", self.run_id) - if state.get("format") != "twinkle.streaming-driver.v1": - raise UnsafeResume("unsupported StreamingDriver checkpoint format") - if str(state.get("run_id")) != self.run_id: - raise UnsafeResume(f"driver snapshot belongs to run {state.get('run_id')!r}, not {self.run_id!r}") + raise UnsafeResume('load_state_dict() without state needs a resume store') + state = self.resume_store.load_object('driver', self.run_id) + if state.get('format') != 'twinkle.streaming-driver.v1': + raise UnsafeResume('unsupported StreamingDriver checkpoint format') + if str(state.get('run_id')) != self.run_id: + raise UnsafeResume(f'driver snapshot belongs to run {state.get("run_id")!r}, not {self.run_id!r}') observed_version = int(self.checkpoint_manager.version()) if self.checkpoint_manager is not None else 0 with self._lock: if self._thread is not None or self._iter_started: - raise UnsafeResume("load_state_dict must run before the driver starts") + raise UnsafeResume('load_state_dict must run before the driver starts') self._groups = {} - for item in state.get("groups") or (): + for item in state.get('groups') or (): group = self._restore_group(item) self._groups[group.key] = group - ready_groups = { - group.key: group for group in (self._restore_group(item) for item in state.get("ready_groups") or ()) - } + ready_groups = {group.key: group for group in + (self._restore_group(item) for item in state.get('ready_groups') or ())} self._ready = deque() - for members in state.get("ready") or (): + for members in state.get('ready') or (): restored = [] for item in members: - key = str(item.get("group_key")) + key = str(item.get('group_key')) group = ready_groups.get(key) if group is None: - raise UnsafeResume(f"ready episode references unknown group {key!r}") + raise UnsafeResume(f'ready episode references unknown group {key!r}') restored.append(self._restore_episode(item, group)) self._ready.append(restored) self._ready_rows = sum(len(episode.deliver) for members in self._ready for episode in members) - self._handed = int(state.get("handed") or 0) - self._prompt_seq = int(state.get("prompts_drawn") or 0) - self._version = max(int(state.get("version") or 0), observed_version) - self._base_version = int(state.get("base_version") or 0) - self._exhausted = bool(state.get("exhausted")) - self._counters = dict(state.get("counters") or self._counters) - lease = state.get("lease") + self._handed = int(state.get('handed') or 0) + self._prompt_seq = int(state.get('prompts_drawn') or 0) + self._version = max(int(state.get('version') or 0), observed_version) + self._base_version = int(state.get('base_version') or 0) + self._exhausted = bool(state.get('exhausted')) + self._counters = dict(state.get('counters') or self._counters) + lease = state.get('lease') if lease is not None and self.resume_store is not None: last = self.resume_store.journal.last( - str(lease["lease_id"]), events=(JournalEvent.BATCH_LEASED, JournalEvent.MODEL_CHECKPOINT_COMMITTED) - ) + str(lease['lease_id']), events=(JournalEvent.BATCH_LEASED, + JournalEvent.MODEL_CHECKPOINT_COMMITTED)) if last is not None and last.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED: lease = None self._lease = lease @@ -929,7 +874,8 @@ def load_state_dict(self, state: dict[str, Any] | None = None) -> None: for group in list(self._groups.values()): if self.checkpoint_manager is not None and self._version - group.version > self.max_staleness: self._retire_stale_group(group) - self._live = sum(not episode.lost for group in self._groups.values() for episode in group.members) + self._live = sum(not episode.lost for group in self._groups.values() + for episode in group.members) self._live += sum(not episode.lost for members in self._ready for episode in members) self._inflight = sum( episode.counted_inflight @@ -946,7 +892,7 @@ def load_state_dict(self, state: dict[str, Any] | None = None) -> None: ) if loader_state is not None: if not callable(loader): - raise UnsafeResume("snapshot has DataLoader state but the dataloader cannot load it") + raise UnsafeResume('snapshot has DataLoader state but the dataloader cannot load it') loader(loader_state) for episode in live: self._resume_live_episode(episode) @@ -955,52 +901,46 @@ def load_state_dict(self, state: dict[str, Any] | None = None) -> None: self._settle(group) self._lock.notify_all() - @remote_function(execute="first", collect="first", lazy_collect=False) - def commit_batch(self, checkpoint_ref: str = "", manifest: dict[str, Any] | None = None) -> str | None: + @remote_function(execute='first', collect='first', lazy_collect=False) + def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, Any]] = None) -> Optional[str]: """Mark the open lease trained after its model checkpoint is durable.""" with self._lock: lease = self._lease if lease is None: return None if self.resume_store is not None and not checkpoint_ref: - raise UnsafeResume("commit_batch() needs the durable model checkpoint reference") - lease_id = str(lease["lease_id"]) + raise UnsafeResume('commit_batch() needs the durable model checkpoint reference') + lease_id = str(lease['lease_id']) if self.resume_store is not None: self.resume_store.journal.append( - JournalEvent.MODEL_CHECKPOINT_COMMITTED, - lease_id, + JournalEvent.MODEL_CHECKPOINT_COMMITTED, lease_id, { - "checkpoint": str(checkpoint_ref), - "batch": lease["batch"], - "policy_versions": list(lease.get("policy_versions") or ()), - "manifest": dict(manifest or {}), - }, - ) - self.resume_store.delete_object("leases", lease_id) + 'checkpoint': str(checkpoint_ref), + 'batch': lease['batch'], + 'policy_versions': list(lease.get('policy_versions') or ()), + 'manifest': dict(manifest or {}), + }) + self.resume_store.delete_object('leases', lease_id) self._lease = None self._lease_returned = False self._persist_snapshot_locked() self._lock.notify_all() return lease_id - @remote_function(execute="first", collect="first", lazy_collect=False) + @remote_function(execute='first', collect='first', lazy_collect=False) def close(self) -> None: """Stop admitting, stop the episodes in flight and end the background thread.""" with self._lock: self._closed = True - episodes = [ - episode - for group in self._groups.values() - for episode in group.members + group.baselines - if not episode.finished - ] + episodes = [episode for group in self._groups.values() + for episode in group.members + group.baselines if not episode.finished] self._lock.notify_all() for episode in episodes: if not episode.done: try: self.rollout.stop(episode.traj or {}, episode_id=episode.episode_id) except Exception as exc: # noqa: BLE001 -- best effort on the way out - logger.warning(f"StreamingDriver.close: stopping {episode.episode_id} failed: {exc}") + logger.warning(f'StreamingDriver.close: stopping {episode.episode_id} failed: {exc}') if self._thread is not None: self._thread.join(timeout=10) @@ -1013,7 +953,7 @@ def _start(self) -> None: self._version = self._read_version() # the bound counts versions from here: a manager synced before the run starts above 0 self._base_version = self._version - self._thread = threading.Thread(target=self._run, name="twinkle-streaming-driver", daemon=True) + self._thread = threading.Thread(target=self._run, name='twinkle-streaming-driver', daemon=True) self._thread.start() def _run(self) -> None: @@ -1030,9 +970,8 @@ def _run(self) -> None: self._admit() self._retry_no_slot_due() self._lock.notify_all() - _record_driver_probe( - "admit", live=self._live, capacity=self._capacity(), qsize=self._events.qsize(), version=version - ) + _record_driver_probe('admit', live=self._live, capacity=self._capacity(), + qsize=self._events.qsize(), version=version) if version != adjusted: adjusted = version self._maybe_adjust() @@ -1040,7 +979,7 @@ def _run(self) -> None: event = self._events.get(timeout=0.1) except queue.Empty: continue - _record_driver_probe("event_dequeued", event[1].episode_id, kind=event[0]) + _record_driver_probe('event_dequeued', event[1].episode_id, kind=event[0]) while event is not None: self._handle(*event) try: @@ -1048,8 +987,8 @@ def _run(self) -> None: except queue.Empty: event = None except BaseException as exc: # noqa - _record_driver_probe("run_stopped", error=f"{type(exc).__name__}: {exc}") - logger.error(f"StreamingDriver stopped: {type(exc).__name__}: {exc}") + _record_driver_probe('run_stopped', error=f'{type(exc).__name__}: {exc}') + logger.error(f'StreamingDriver stopped: {type(exc).__name__}: {exc}') with self._lock: self._error = exc self._lock.notify_all() @@ -1077,11 +1016,9 @@ def _maybe_adjust(self) -> None: stuck = now - self._adjust_started if stuck >= self.ADJUST_STUCK_TIMEOUT and now - self._adjust_reported >= self.ADJUST_STUCK_TIMEOUT: self._adjust_reported = now - logger.warning( - f"cluster adapter adjust has been running for {stuck:.0f}s " - "(a large weight warm takes this long too and a stuck RPC looks " - "the same); rebalancing is paused until it returns" - ) + logger.warning(f'cluster adapter adjust has been running for {stuck:.0f}s ' + '(a large weight warm takes this long too and a stuck RPC looks ' + 'the same); rebalancing is paused until it returns') return self._adjusting = True self._adjust_started = time.monotonic() @@ -1090,18 +1027,18 @@ def _adjust(): try: self.cluster_adapter.adjust() except Exception as exc: # noqa: BLE001 -- rebalancing is an optimisation, never fatal - logger.warning(f"cluster adapter adjust failed: {type(exc).__name__}: {exc}") + logger.warning(f'cluster adapter adjust failed: {type(exc).__name__}: {exc}') finally: self._adjusting = False - threading.Thread(target=_adjust, name="twinkle-cluster-adjust", daemon=True).start() + threading.Thread(target=_adjust, name='twinkle-cluster-adjust', daemon=True).start() def _lend(self, waited: float) -> None: """Run ``lend`` while the trainer waits; ``reclaim`` joins this thread before undoing it.""" try: self.cluster_adapter.lend(self._idle_ratio, waited=waited) except Exception as exc: # noqa: BLE001 -- lending is an optimisation, never fatal - logger.warning(f"cluster adapter lend failed: {type(exc).__name__}: {exc}") + logger.warning(f'cluster adapter lend failed: {type(exc).__name__}: {exc}') # ------------------------------------------------------------------ admission @@ -1129,15 +1066,14 @@ def _admit(self) -> None: version = self._version adapter_path = None if self.checkpoint_manager is not None: - lookup = getattr(self.checkpoint_manager, "adapter_path", None) + lookup = getattr(self.checkpoint_manager, 'adapter_path', None) if callable(lookup): adapter_path = lookup(version) if adapter_path is None: raise UnsafeResume( - f"checkpoint manager has no adapter path for admitted policy version {version}" - ) + f'checkpoint manager has no adapter path for admitted policy version {version}') binding = GroupPolicyBinding( - state_key=f"{self.run_id}/group/{key}", + state_key=f'{self.run_id}/group/{key}', policy_version=version, adapter_path=adapter_path, ) @@ -1145,14 +1081,12 @@ def _admit(self) -> None: self._groups[key] = group self._start_attempt(group, [copy.deepcopy(row) for _ in range(self.num_generations)]) if self.resume_store is not None: - prompt_key = f"{self.run_id}/prompt/{key}" - self.resume_store.save_object("prompts", prompt_key, row) + prompt_key = f'{self.run_id}/prompt/{key}' + self.resume_store.save_object('prompts', prompt_key, row) self._persist_snapshot_locked() self.resume_store.journal.append( - JournalEvent.PROMPT_ASSIGNED, - prompt_key, - {"group_key": key, "object": prompt_key, "binding": binding.to_dict()}, - ) + JournalEvent.PROMPT_ASSIGNED, prompt_key, + {'group_key': key, 'object': prompt_key, 'binding': binding.to_dict()}) def _next_row(self) -> Any: # TODO: rows are drawn here, ahead of training; see state_dict for what a resume skips. @@ -1162,7 +1096,7 @@ def _next_row(self) -> Any: def _iter_rows(self) -> Iterator[Any]: for epoch in range(max(1, math.ceil(self.num_epochs))): - set_epoch = getattr(self.dataloader, "set_epoch", None) + set_epoch = getattr(self.dataloader, 'set_epoch', None) if set_epoch is not None: set_epoch(epoch) for batch in self.dataloader: @@ -1171,7 +1105,7 @@ def _iter_rows(self) -> Iterator[Any]: else: yield batch - def _start_attempt(self, group: _Group, trajectories: list[Any]) -> None: + def _start_attempt(self, group: _Group, trajectories: List[Any]) -> None: """Submit one attempt's trajectories: the non-baseline ones replace the members (under the lock).""" members = [traj for traj in trajectories if _role_of(traj) != _BASELINE] baselines = [traj for traj in trajectories if _role_of(traj) == _BASELINE] @@ -1180,34 +1114,29 @@ def _start_attempt(self, group: _Group, trajectories: list[Any]) -> None: group.members = [] group.missing = 0 self._live += len(members) - self._counters["admitted"] += len(members) + self._counters['admitted'] += len(members) group.baselines = [] for index, traj in enumerate(members): # Positional sample identity within the group: the rollout derives a per-request seed # from (group_key, sample_index) so a group's num_generations samples differ. A constant # seed would collapse them to one identical trajectory and zero the group's advantage. - traj["sample_index"] = index - group.members.append(self._submit(group, traj, "", index)) + traj['sample_index'] = index + group.members.append(self._submit(group, traj, '', index)) for index, traj in enumerate(baselines): group.baselines.append(self._submit(group, traj, _BASELINE, index)) def _submit(self, group: _Group, traj: Any, role: str, slot: int) -> _Episode: - kind = "baseline" if role == _BASELINE else "member" - episode_id = f"{self.run_id}:g{group.key}:a{group.attempt}:{kind}:{slot}" + kind = 'baseline' if role == _BASELINE else 'member' + episode_id = f'{self.run_id}:g{group.key}:a{group.attempt}:{kind}:{slot}' episode = _Episode(episode_id=episode_id, group=group, role=role, version=group.version) # The identity travels on top of the trajectory: episode / group / role / the admission # version. The rollout reads the episode id to route its steps back to this episode. traj = dict(traj) - traj.update( - episode_id=episode.episode_id, - group_key=group.key, - role=role, - policy_version=group.version, - group_attempt=group.attempt, - state_key=f"{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}", - ) + traj.update(episode_id=episode.episode_id, group_key=group.key, role=role, + policy_version=group.version, group_attempt=group.attempt, + state_key=f'{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}') if group.adapter_path is not None: - traj["adapter_path"] = group.adapter_path + traj['adapter_path'] = group.adapter_path episode.submit_traj = traj self._inflight += 1 episode.counted_inflight = True @@ -1218,30 +1147,30 @@ def _step(self, episode: _Episode, traj: Any) -> None: # session_wait=0: the admission loop never blocks on a full session pool -- a no-slot status # comes back along the return channel and the member is retried later (see _no_slot). future = self.rollout.step(traj, episode_id=episode.episode_id, session_wait=0) - _record_driver_probe("step_submitted", episode.episode_id) + _record_driver_probe('step_submitted', episode.episode_id) def _done(f, episode=episode): - _record_driver_probe("step_future_done", episode.episode_id) - self._events.put(("step", episode, None, f)) + _record_driver_probe('step_future_done', episode.episode_id) + self._events.put(('step', episode, None, f)) future.add_done_callback(_done) # ------------------------------------------------------------------ completions - def _handle(self, kind: str, episode: _Episode, index: int | None, future: Any) -> None: - _record_driver_probe("handle", episode.episode_id, kind=kind) + def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: Any) -> None: + _record_driver_probe('handle', episode.episode_id, kind=kind) exc = future.exception() with self._lock: if self._closed: return if episode.lost: - if kind == "step" and exc is None and not future.result()[1].done: + if kind == 'step' and exc is None and not future.result()[1].done: # dropped while this step ran: release its rollout state now self.rollout.stop(future.result()[0][0], episode_id=episode.episode_id) return - if exc is not None and not (kind == "step" and _is_episode_error(exc)): + if exc is not None and not (kind == 'step' and _is_episode_error(exc)): raise exc - if kind == "step": + if kind == 'step': if exc is not None: self._fail(episode, exc) else: @@ -1253,7 +1182,7 @@ def _handle(self, kind: str, episode: _Episode, index: int | None, future: Any) self._no_slot(episode) else: self._on_step(episode, rows, sample) - elif kind == "orm": + elif kind == 'orm': episode.orm[index] = future.result()[0] episode.orm_pending -= 1 self._maybe_finish(episode) @@ -1262,8 +1191,7 @@ def _handle(self, kind: str, episode: _Episode, index: int | None, future: Any) episode.prm[scorer][segment] = future.result()[0] episode.prm_pending -= 1 if episode.held == segment and not any( - episode.prm[k][segment] is _PENDING for k in range(len(self.prms)) - ): + episode.prm[k][segment] is _PENDING for k in range(len(self.prms))): self._release(episode, segment) self._maybe_finish(episode) if kind != "step": @@ -1276,11 +1204,8 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None episode.done = bool(sample.done) if episode.done: episode.deliver = list(trajs) - if ( - self.prms - and episode.role != _BASELINE - and (episode.done or self.prm_segment is None or self.prm_segment(sample, trajs[0])) - ): + if self.prms and episode.role != _BASELINE and (episode.done or self.prm_segment is None + or self.prm_segment(sample, trajs[0])): segment = self._score_prm(episode) if self.on_step is not None and not episode.done: episode.held = segment @@ -1318,7 +1243,7 @@ def _release(self, episode: _Episode, segment: int) -> None: if self.on_step(episode.sample, [column[segment] for column in episode.prm]): self._step(episode, episode.traj) return - self._counters["stopped"] += 1 + self._counters['stopped'] += 1 self.rollout.stop(episode.traj, episode_id=episode.episode_id) self._lose(episode) @@ -1334,18 +1259,15 @@ def _score_orm(self, episode: _Episode) -> None: self._maybe_finish(episode) def _fail(self, episode: _Episode, exc: BaseException) -> None: - self._counters["episode_errors"] += 1 + self._counters['episode_errors'] += 1 self._consecutive_failures += 1 self._failures.append(True) - logger.warning(f"episode {episode.episode_id} skipped: {exc}") + logger.warning(f'episode {episode.episode_id} skipped: {exc}') if self._consecutive_failures >= self.MAX_CONSECUTIVE_FAILURES or ( - len(self._failures) == self.FAILURE_WINDOW - and sum(self._failures) > self.MAX_FAILURE_RATE * self.FAILURE_WINDOW - ): - raise RuntimeError( - f"too many episodes fail ({self._consecutive_failures} in a row, " - f"{sum(self._failures)} of the last {len(self._failures)}); last: {exc}" - ) from exc + len(self._failures) == self.FAILURE_WINDOW + and sum(self._failures) > self.MAX_FAILURE_RATE * self.FAILURE_WINDOW): + raise RuntimeError(f'too many episodes fail ({self._consecutive_failures} in a row, ' + f'{sum(self._failures)} of the last {len(self._failures)}); last: {exc}') from exc self._lose(episode) def _lose(self, episode: _Episode) -> None: @@ -1372,7 +1294,7 @@ def _no_slot(self, episode: _Episode) -> None: """ self._inflight -= 1 episode.counted_inflight = False - self._counters["no_slot"] += 1 + self._counters['no_slot'] += 1 now = time.monotonic() if episode.no_slot_deadline is None: episode.no_slot_deadline = now + self.max_no_slot_wait @@ -1397,12 +1319,10 @@ def _retry_no_slot_due(self) -> None: if episode.no_slot_retry_at is None or episode.no_slot_retry_at > now: continue if episode.no_slot_deadline is not None and now > episode.no_slot_deadline: - self._counters["no_slot_dropped"] += 1 - logger.warning( - f"group {group.key} dropped: member {episode.episode_id} could not get " - f"a session slot within {self.max_no_slot_wait:.0f}s " - f"({episode.no_slot_attempts} no-slot retries)" - ) + self._counters['no_slot_dropped'] += 1 + logger.warning(f'group {group.key} dropped: member {episode.episode_id} could not get ' + f'a session slot within {self.max_no_slot_wait:.0f}s ' + f'({episode.no_slot_attempts} no-slot retries)') self._drop_group(group) break episode.no_slot_retry_at = None @@ -1431,7 +1351,7 @@ def _maybe_finish(self, episode: _Episode) -> None: sample.prm_rewards = [list(column) for column in episode.prm] sample.extra = dict(sample.extra or {}, **{PRM_SEGMENT_TURNS: list(episode.prm_turns)}) if episode.role != _BASELINE and self.on_sample is not None and self.on_sample(sample) is False: - self._counters["dropped_sample"] += 1 + self._counters['dropped_sample'] += 1 self._lose(episode) return episode.finished = True @@ -1455,14 +1375,14 @@ def _settle(self, group: _Group) -> None: self._drop_group(group) return group.attempt += 1 - self._counters["regenerated"] += 1 + self._counters['regenerated'] += 1 # the lost members are redone from their trajectories; the scored ones stay self._live += group.missing - self._counters["admitted"] += group.missing + self._counters['admitted'] += group.missing group.missing = 0 for index, episode in enumerate(group.members): if episode.lost: - group.members[index] = self._submit(group, copy.deepcopy(group.source[index]), "", index) + group.members[index] = self._submit(group, copy.deepcopy(group.source[index]), '', index) return if group.baselines: rows = [list(e.sample.orm_reward) for e in group.baselines] @@ -1476,14 +1396,12 @@ def _settle(self, group: _Group) -> None: trajectories = list(self.on_group(group.row, [e.sample for e in group.members], group.attempt) or []) regenerate = [t for t in trajectories if _role_of(t) != _BASELINE] if regenerate and len(regenerate) != self.num_generations: - raise ValueError( - f"on_group returned {len(regenerate)} trajectories to replace a group of " - f"{self.num_generations}; a group is always num_generations rows." - ) + raise ValueError(f'on_group returned {len(regenerate)} trajectories to replace a group of ' + f'{self.num_generations}; a group is always num_generations rows.') if regenerate and group.attempt < self.max_group_regenerations: # baselines returned alongside wait: the replaced group is offered to on_group again self._live -= len(group.members) - self._counters["regenerated"] += 1 + self._counters['regenerated'] += 1 group.attempt += 1 self._start_attempt(group, regenerate) return @@ -1538,7 +1456,7 @@ def _drop_group(self, group: _Group) -> None: """Give the group up: its counted rows leave the bound, its unfinished episodes stop (under the lock).""" if self._groups.pop(group.key, None) is None: return - self._counters["dropped_group"] += 1 + self._counters['dropped_group'] += 1 for episode in group.members + group.baselines: if episode.lost: continue @@ -1567,7 +1485,7 @@ def _drop_group(self, group: _Group) -> None: #: Placeholder for a score whose Future has not completed yet. _PENDING = object() -_PENDING_KEY = "__twinkle_streaming_pending__" +_PENDING_KEY = '__twinkle_streaming_pending__' def _dump_pending(value: Any) -> Any: diff --git a/src/twinkle_agentic/envs/__init__.py b/src/twinkle_agentic/envs/__init__.py index 624e59a79..518974bec 100644 --- a/src/twinkle_agentic/envs/__init__.py +++ b/src/twinkle_agentic/envs/__init__.py @@ -7,20 +7,7 @@ from .resume import EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, env_resume_capability __all__ = [ - "AgentEnv", - "AgentSandbox", - "ClientSession", - "Env", - "EnvTool", - "LocalEnv", - "NoSlot", - "OpenEnv", - "OpenEnvClient", - "EnvResumeCapability", - "ResumableEnv", - "SessionNotFound", - "StepResult", - "UnsafeCheckpoint", - "UnsupportedEnvResume", - "env_resume_capability", + 'AgentEnv', 'AgentSandbox', 'ClientSession', 'Env', 'EnvTool', 'LocalEnv', 'NoSlot', 'OpenEnv', 'OpenEnvClient', + 'EnvResumeCapability', 'ResumableEnv', 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', + 'UnsupportedEnvResume', 'env_resume_capability' ] diff --git a/src/twinkle_agentic/envs/base.py b/src/twinkle_agentic/envs/base.py index 611e09231..a0361b3d5 100644 --- a/src/twinkle_agentic/envs/base.py +++ b/src/twinkle_agentic/envs/base.py @@ -2,15 +2,15 @@ import threading import time from abc import ABC, abstractmethod -from collections.abc import Sequence from dataclasses import dataclass, field -from typing import Any +from typing import Any, Dict, List, Optional, Sequence, Tuple from twinkle import remote_function from twinkle.data_format import Trajectory from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .resume import EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, env_resume_capability +from .resume import (EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, + env_resume_capability) from .snapshot import list_workspace logger = get_logger() @@ -26,16 +26,14 @@ def _record_tool_exec(episode_id: str, n: int) -> None: tool_call, so it is deliberately not counted. Write-only and env-gated: a no-op when unset. """ import os - - root = os.environ.get("TWINKLE_ROLLOUT_TRAJ_DUMP") + root = os.environ.get('TWINKLE_ROLLOUT_TRAJ_DUMP') if not root: return import json - os.makedirs(root, exist_ok=True) - rank = int(os.environ.get("RANK") or os.environ.get("LOCAL_RANK") or 0) - with open(os.path.join(root, f"tool_counts.rank{rank}.jsonl"), "a", encoding="utf-8") as handle: - handle.write(json.dumps({"episode_id": episode_id, "executed": int(n)}) + "\n") + rank = int(os.environ.get('RANK') or os.environ.get('LOCAL_RANK') or 0) + with open(os.path.join(root, f'tool_counts.rank{rank}.jsonl'), 'a', encoding='utf-8') as handle: + handle.write(json.dumps({'episode_id': episode_id, 'executed': int(n)}) + '\n') # What :meth:`Env.run_script` returns when it had to kill the script. 124 is @@ -55,48 +53,63 @@ def _record_tool_exec(episode_id: str, n: int) -> None: # Shared rather than restated per implementation: a trajectory built against one # env has to replay on another, and it only does if the names and the argument # spellings are the same object. -DEFAULT_TOOLS: list[ToolInfo] = [ +DEFAULT_TOOLS: List[ToolInfo] = [ { - "type": "function", - "function": { - "name": "run_command", - "description": "Run a shell command inside the sandbox and return its output.", - "parameters": { - "type": "object", - "properties": { - "command": {"type": "string", "description": "The shell command to execute."}, - "cwd": {"type": "string", "description": "Working directory (optional)."}, + 'type': 'function', + 'function': { + 'name': 'run_command', + 'description': 'Run a shell command inside the sandbox and return its output.', + 'parameters': { + 'type': 'object', + 'properties': { + 'command': { + 'type': 'string', + 'description': 'The shell command to execute.' + }, + 'cwd': { + 'type': 'string', + 'description': 'Working directory (optional).' + }, }, - "required": ["command"], + 'required': ['command'], }, }, }, { - "type": "function", - "function": { - "name": "write_file", - "description": "Write text content to a file inside the sandbox.", - "parameters": { - "type": "object", - "properties": { - "path": {"type": "string", "description": "Absolute file path in the sandbox."}, - "content": {"type": "string", "description": "Text content to write."}, + 'type': 'function', + 'function': { + 'name': 'write_file', + 'description': 'Write text content to a file inside the sandbox.', + 'parameters': { + 'type': 'object', + 'properties': { + 'path': { + 'type': 'string', + 'description': 'Absolute file path in the sandbox.' + }, + 'content': { + 'type': 'string', + 'description': 'Text content to write.' + }, }, - "required": ["path", "content"], + 'required': ['path', 'content'], }, }, }, { - "type": "function", - "function": { - "name": "read_file", - "description": "Read a text file from the sandbox.", - "parameters": { - "type": "object", - "properties": { - "path": {"type": "string", "description": "Absolute file path in the sandbox."}, + 'type': 'function', + 'function': { + 'name': 'read_file', + 'description': 'Read a text file from the sandbox.', + 'parameters': { + 'type': 'object', + 'properties': { + 'path': { + 'type': 'string', + 'description': 'Absolute file path in the sandbox.' + }, }, - "required": ["path"], + 'required': ['path'], }, }, }, @@ -106,7 +119,7 @@ def _record_tool_exec(episode_id: str, n: int) -> None: def truncate_observation(text: str, limit: int = MAX_OBSERVATION_CHARS) -> str: if len(text) <= limit: return text - return text[:limit] + f"\n... [truncated, {len(text) - limit} chars omitted]" + return text[:limit] + f'\n... [truncated, {len(text) - limit} chars omitted]' def format_command_output(stdout: str, stderr: str, exit_code: int) -> str: @@ -115,20 +128,19 @@ def format_command_output(stdout: str, stderr: str, exit_code: int) -> str: if stdout: parts.append(stdout) if stderr: - parts.append(f"[stderr]\n{stderr}") + parts.append(f'[stderr]\n{stderr}') if exit_code != 0: - parts.append(f"[exit code: {exit_code}]") - return truncate_observation("\n".join(parts)) if parts else "(no output)" + parts.append(f'[exit code: {exit_code}]') + return truncate_observation('\n'.join(parts)) if parts else '(no output)' @dataclass class StepResult: """Result returned by :meth:`Env.step`.""" - - observation: str = "" + observation: str = '' reward: float = 0.0 done: bool = False - info: dict[str, Any] = field(default_factory=dict) + info: Dict[str, Any] = field(default_factory=dict) class SessionNotFound(KeyError): @@ -198,7 +210,7 @@ class Env(ABC): snapshot_max_files = 40 snapshot_per_file = 2000 snapshot_budget = 20000 - snapshot_skip = ("__pycache__", ".git", ".ipynb_checkpoints") + snapshot_skip = ('__pycache__', '.git', '.ipynb_checkpoints') #: Seconds a session may go untouched before the next ``reset`` closes it: a caller that died #: or never called ``close`` would otherwise hold a sandbox forever. @@ -206,10 +218,10 @@ class Env(ABC): #: Seconds ``reset`` waits for a free session before it gives up with ``TimeoutError``. session_wait_timeout = 600.0 - def __init__(self, max_sessions: int = 64, session_wait_timeout: float | None = 600.0): + def __init__(self, max_sessions: int = 64, session_wait_timeout: Optional[float] = 600.0): self._max_sessions = max(1, int(max_sessions)) self._session_slots = threading.Semaphore(self._max_sessions) - self._sessions: dict[str, _Session] = {} + self._sessions: Dict[str, _Session] = {} self._sessions_lock = threading.Lock() #: Instance default for how long ``reset`` waits for a free permit; a per-call ``wait`` #: override (see :meth:`reset`) takes precedence. Three states: positive = wait up to this @@ -221,11 +233,11 @@ def __init__(self, max_sessions: int = 64, session_wait_timeout: float | None = # ------------------------------------------------------------------ @abstractmethod - def _open(self, trajectory: Trajectory | None) -> tuple[Any, StepResult]: + def _open(self, trajectory: Optional[Trajectory]) -> Tuple[Any, StepResult]: """Start one episode; returns its state and the initial observation.""" @abstractmethod - def _step(self, state: Any, tool_name: str, arguments: dict[str, Any]) -> StepResult: + def _step(self, state: Any, tool_name: str, arguments: Dict[str, Any]) -> StepResult: """Run one tool call in the episode.""" def _run_script( @@ -234,9 +246,9 @@ def _run_script( raise NotImplementedError(f"{type(self).__name__} cannot run scripts; act through its tools instead.") def _close(self, state: Any) -> None: - return None + pass - def _workspace(self, state: Any) -> str | None: + def _workspace(self, state: Any) -> Optional[str]: return None # ------------------------------------------------------------------ @@ -247,26 +259,22 @@ def _session(self, episode_id: str) -> _Session: with self._sessions_lock: session = self._sessions.get(episode_id) if session is None: - raise SessionNotFound(f"{type(self).__name__}: no open session for episode {episode_id!r}.") + raise SessionNotFound(f'{type(self).__name__}: no open session for episode {episode_id!r}.') session.touched = time.monotonic() return session def _close_idle_sessions(self) -> None: now = time.monotonic() with self._sessions_lock: - idle = [ - eid - for eid, session in self._sessions.items() - if not session.script_inflight and now - session.touched > self.session_idle_timeout - ] + idle = [eid for eid, session in self._sessions.items() + if not session.script_inflight and now - session.touched > self.session_idle_timeout] for eid in idle: - logger.warning( - f"{type(self).__name__}: closing session {eid!r}, idle for over {self.session_idle_timeout:.0f}s." - ) + logger.warning(f'{type(self).__name__}: closing session {eid!r}, idle for over ' + f'{self.session_idle_timeout:.0f}s.') self.close(eid) - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def reset(self, episode_id: str, traj: Trajectory | None = None, wait: float | None = None) -> Any: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def reset(self, episode_id: str, traj: Optional[Trajectory] = None, wait: Optional[float] = None) -> Any: """Open the episode's session (closing an earlier one under the same id); returns the first observation. ``wait`` overrides the instance :attr:`session_wait_timeout` for this call only: a positive @@ -289,14 +297,13 @@ def reset(self, episode_id: str, traj: Trajectory | None = None, wait: float | N with self._sessions_lock: now = time.monotonic() holders = sorted((eid, now - session.touched) for eid, session in self._sessions.items()) - detail = ", ".join(f"{eid} idle {age:.0f}s" for eid, age in holders[:8]) + detail = ', '.join(f'{eid} idle {age:.0f}s' for eid, age in holders[:8]) raise TimeoutError( - f"{type(self).__name__}: no free session within {effective:.0f}s " - f"({self._max_sessions} permits, {len(holders)} sessions registered). " - f"Holders: {detail or 'none'}. " - "Fewer registered sessions than permits means the missing permits are held by resets " - "still inside _open, or were stranded by an earlier overwrite." - ) + f'{type(self).__name__}: no free session within {effective:.0f}s ' + f'({self._max_sessions} permits, {len(holders)} sessions registered). ' + f'Holders: {detail or "none"}. ' + 'Fewer registered sessions than permits means the missing permits are held by resets ' + 'still inside _open, or were stranded by an earlier overwrite.') try: state, result = self._open(traj) except BaseException: @@ -313,17 +320,14 @@ def reset(self, episode_id: str, traj: Trajectory | None = None, wait: float | N try: self._close(displaced.state) except Exception: # noqa - logger.warning( - f"{type(self).__name__}: closing the session displaced by a concurrent " - f"reset of episode {episode_id!r} failed.", - exc_info=True, - ) + logger.warning(f'{type(self).__name__}: closing the session displaced by a concurrent ' + f'reset of episode {episode_id!r} failed.', exc_info=True) finally: self._session_slots.release() return result - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def step(self, episode_id: str, tool_name: str, arguments: dict[str, Any] | None = None) -> StepResult: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def step(self, episode_id: str, tool_name: str, arguments: Optional[Dict[str, Any]] = None) -> StepResult: session = self._session(episode_id) result = self._step(session.state, tool_name, arguments or {}) if result.reward is not None: @@ -332,8 +336,8 @@ def step(self, episode_id: str, tool_name: str, arguments: dict[str, Any] | None _record_tool_exec(episode_id, 1) return result - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def step_batch(self, episode_id: str, calls: Sequence[tuple[str, dict[str, Any]]]) -> list[StepResult]: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def step_batch(self, episode_id: str, calls: Sequence[Tuple[str, Dict[str, Any]]]) -> List[StepResult]: """Execute already-parsed ``(tool_name, arguments)`` pairs in order, in one round trip.""" session = self._session(episode_id) results = [] @@ -387,13 +391,13 @@ def run_script( finally: session.script_inflight = False - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def workspace(self, episode_id: str) -> str | None: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def workspace(self, episode_id: str) -> Optional[str]: """The directory the episode works in, or None for an environment that keeps none.""" return self._workspace(self._session(episode_id).state) - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def snapshot(self, episode_id: str) -> tuple[str, str]: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def snapshot(self, episode_id: str) -> Tuple[str, str]: """The episode's end state as ``(listing, error)``; both empty when there is none. What an episode left behind, for a caller that has to describe it to a @@ -405,12 +409,11 @@ def snapshot(self, episode_id: str) -> tuple[str, str]: state = self._session(episode_id).state return list_workspace( self._workspace(state), - lambda source: self._run_script(state, source, "python", None), + lambda source: self._run_script(state, source, 'python', None), max_files=self.snapshot_max_files, per_file=self.snapshot_per_file, budget=self.snapshot_budget, - skip=self.snapshot_skip, - ) + skip=self.snapshot_skip) @remote_function(enable_continous_work=True, sticky_key="episode_id") def close(self, episode_id: str) -> float | None: @@ -428,12 +431,12 @@ def close(self, episode_id: str) -> float | None: try: self._close(session.state) except Exception: # noqa - logger.warning(f"{type(self).__name__}: closing session {episode_id!r} failed.", exc_info=True) + logger.warning(f'{type(self).__name__}: closing session {episode_id!r} failed.', exc_info=True) finally: self._session_slots.release() return session.reward if session.rewarded else None - @remote_function(dispatch="all", collect="first", lazy_collect=False) + @remote_function(dispatch='all', collect='first', lazy_collect=False) def shutdown(self) -> None: """Close every open session.""" with self._sessions_lock: @@ -441,8 +444,8 @@ def shutdown(self) -> None: for episode_id in episode_ids: self.close(episode_id) - @remote_function(execute="first", collect="first", lazy_collect=False) - def tools(self) -> list[ToolInfo]: + @remote_function(execute='first', collect='first', lazy_collect=False) + def tools(self) -> List[ToolInfo]: """What the model is told it can call in an episode.""" return [] diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 08740a7ac..7328b7dc7 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -21,8 +21,8 @@ Every episode gets its own directory under ``root`` as the working directory of all its calls; closing the episode removes it, and kills whatever it still had running. """ - import hashlib +import json import os import resource import shlex @@ -35,22 +35,13 @@ import time import uuid from pathlib import Path -from typing import Any - -import json +from typing import Any, Dict, List, Optional, Tuple from twinkle import remote_class, remote_function from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .base import ( - DEFAULT_TOOLS, - ENV_MAX_CONCURRENCY, - TIMEOUT_EXIT_CODE, - Env, - StepResult, - format_command_output, - truncate_observation, -) +from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, StepResult, format_command_output, + truncate_observation) from .resume import EnvResumeCapability, UnsafeCheckpoint logger = get_logger() @@ -58,11 +49,11 @@ # Kept deterministic and single-threaded: a check that changes its answer with # the machine's core count is not a check. Matches what the sandboxes set. _SCRIPT_ENVS = { - "MPLBACKEND": "Agg", - "PYTHONHASHSEED": "0", - "OMP_NUM_THREADS": "1", - "MKL_NUM_THREADS": "1", - "TOKENIZERS_PARALLELISM": "false", + 'MPLBACKEND': 'Agg', + 'PYTHONHASHSEED': '0', + 'OMP_NUM_THREADS': '1', + 'MKL_NUM_THREADS': '1', + 'TOKENIZERS_PARALLELISM': 'false', } @@ -82,15 +73,13 @@ class LocalEnv(Env): resume_capability = EnvResumeCapability.DURABLE_CHECKPOINT - def __init__( - self, - root: str | None = None, - max_sessions: int = 64, - command_timeout: int = 60, - memory_limit_gb: float | None = 2.0, - envs: dict[str, str] | None = None, - session_wait_timeout: float | None = 600.0, - ): + def __init__(self, + root: Optional[str] = None, + max_sessions: int = 64, + command_timeout: int = 60, + memory_limit_gb: Optional[float] = 2.0, + envs: Optional[Dict[str, str]] = None, + session_wait_timeout: Optional[float] = 600.0): """ Args: root: directory holding the episodes' working directories, created if absent; a fresh @@ -105,19 +94,19 @@ def __init__( ``wait`` overrides it); ``None`` waits forever, ``0`` returns NoSlot immediately. """ super().__init__(max_sessions, session_wait_timeout=session_wait_timeout) - self._root = os.path.abspath(root) if root else tempfile.mkdtemp(prefix="twinkle_localenv_") + self._root = os.path.abspath(root) if root else tempfile.mkdtemp(prefix='twinkle_localenv_') os.makedirs(self._root, exist_ok=True) self._command_timeout = command_timeout self._memory_limit_gb = memory_limit_gb self._envs = dict(envs or {}) - self._resume_root = Path(self._root) / ".twinkle-resume" + self._resume_root = Path(self._root) / '.twinkle-resume' # ------------------------------------------------------------------ # Session hooks # ------------------------------------------------------------------ - def _open(self, trajectory) -> tuple[_LocalSession, StepResult]: - workspace = tempfile.mkdtemp(prefix="ep_", dir=self._root) + def _open(self, trajectory) -> Tuple[_LocalSession, StepResult]: + workspace = tempfile.mkdtemp(prefix='ep_', dir=self._root) return _LocalSession(workspace), StepResult() def _close(self, state: _LocalSession) -> None: @@ -138,73 +127,72 @@ def _workspace(self, state: _LocalSession) -> str: @staticmethod def _state_dir_name(state_key: str) -> str: # Keep the durable path short enough for Windows' classic MAX_PATH. - return hashlib.sha256(state_key.encode("utf-8")).hexdigest()[:24] + return hashlib.sha256(state_key.encode('utf-8')).hexdigest()[:24] @staticmethod - def _tree_digest(root: Path) -> dict[str, Any]: + def _tree_digest(root: Path) -> Dict[str, Any]: digest = hashlib.sha256() files = [] total = 0 - for path in sorted(root.rglob("*")): + for path in sorted(root.rglob('*')): if path.is_symlink(): - raise UnsafeCheckpoint(f"workspace snapshot refuses symbolic link {path}") + raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') if not path.is_file(): continue relative = path.relative_to(root).as_posix() data = path.read_bytes() file_digest = hashlib.sha256(data).hexdigest() - digest.update(relative.encode("utf-8")) - digest.update(b"\0") - digest.update(file_digest.encode("ascii")) - files.append({"path": relative, "size": len(data), "sha256": file_digest}) + digest.update(relative.encode('utf-8')) + digest.update(b'\0') + digest.update(file_digest.encode('ascii')) + files.append({'path': relative, 'size': len(data), 'sha256': file_digest}) total += len(data) - return {"digest": digest.hexdigest(), "files": files, "bytes": total} + return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} - def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: + def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: """Copy one quiescent workspace behind a new atomic generation pointer.""" session = self._session(episode_id) state = session.state if session.script_inflight: - raise UnsafeCheckpoint(f"episode {episode_id!r} has a script in flight") + raise UnsafeCheckpoint(f'episode {episode_id!r} has a script in flight') with state.lock: if state.closed: - raise UnsafeCheckpoint(f"episode {episode_id!r} is already closed") + raise UnsafeCheckpoint(f'episode {episode_id!r} is already closed') if state.procs: - raise UnsafeCheckpoint(f"episode {episode_id!r} has a running process") + raise UnsafeCheckpoint(f'episode {episode_id!r} has a running process') - generation = f"{time.time_ns():x}-{uuid.uuid4().hex[:8]}" + generation = f'{time.time_ns():x}-{uuid.uuid4().hex[:8]}' key_root = self._resume_root / self._state_dir_name(state_key) generation_root = key_root / generation - workspace_copy = generation_root / "workspace" + workspace_copy = generation_root / 'workspace' generation_root.mkdir(parents=True, exist_ok=False) try: shutil.copytree(state.workspace, workspace_copy) tree = self._tree_digest(workspace_copy) manifest = { - "format": "twinkle.localenv.v1", - "state_key": state_key, - "generation": generation, - "workspace": tree, + 'format': 'twinkle.localenv.v1', + 'state_key': state_key, + 'generation': generation, + 'workspace': tree, } - manifest_bytes = json.dumps(manifest, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode( - "utf-8" - ) - manifest_path = generation_root / "manifest.json" + manifest_bytes = json.dumps(manifest, ensure_ascii=False, sort_keys=True, + separators=(',', ':')).encode('utf-8') + manifest_path = generation_root / 'manifest.json' manifest_path.write_bytes(manifest_bytes) - with open(manifest_path, "r+b") as stream: + with open(manifest_path, 'r+b') as stream: os.fsync(stream.fileno()) head = { - "generation": generation, - "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), + 'generation': generation, + 'manifest_sha256': hashlib.sha256(manifest_bytes).hexdigest(), } - head_bytes = json.dumps(head, sort_keys=True).encode("utf-8") - pending = key_root / f".head.{generation}.tmp" + head_bytes = json.dumps(head, sort_keys=True).encode('utf-8') + pending = key_root / f'.head.{generation}.tmp' key_root.mkdir(parents=True, exist_ok=True) - with open(pending, "wb") as stream: + with open(pending, 'wb') as stream: stream.write(head_bytes) stream.flush() os.fsync(stream.fileno()) - os.replace(pending, key_root / "head.json") + os.replace(pending, key_root / 'head.json') except BaseException: shutil.rmtree(generation_root, ignore_errors=True) raise @@ -224,20 +212,20 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any], trajectory=None) -> None: """Allocate a fresh session and rehydrate the snapshot named by ``state``.""" - if state.get("format") != "twinkle.localenv.v1" or state.get("state_key") != state_key: - raise UnsafeCheckpoint("LocalEnv restore metadata does not match the episode state key") - generation = str(state.get("generation") or "") + if state.get('format') != 'twinkle.localenv.v1' or state.get('state_key') != state_key: + raise UnsafeCheckpoint('LocalEnv restore metadata does not match the episode state key') + generation = str(state.get('generation') or '') if not generation: - raise UnsafeCheckpoint("LocalEnv restore metadata has no generation") + raise UnsafeCheckpoint('LocalEnv restore metadata has no generation') generation_root = self._resume_root / self._state_dir_name(state_key) / generation - manifest_path = generation_root / "manifest.json" + manifest_path = generation_root / 'manifest.json' manifest_bytes = manifest_path.read_bytes() - if hashlib.sha256(manifest_bytes).hexdigest() != state.get("manifest_sha256"): - raise UnsafeCheckpoint("LocalEnv snapshot manifest checksum mismatch") + if hashlib.sha256(manifest_bytes).hexdigest() != state.get('manifest_sha256'): + raise UnsafeCheckpoint('LocalEnv snapshot manifest checksum mismatch') manifest = json.loads(manifest_bytes) - source = generation_root / "workspace" - if self._tree_digest(source)["digest"] != manifest["workspace"]["digest"]: - raise UnsafeCheckpoint("LocalEnv snapshot workspace checksum mismatch") + source = generation_root / 'workspace' + if self._tree_digest(source)['digest'] != manifest['workspace']['digest']: + raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') self.reset(episode_id, trajectory) try: @@ -266,74 +254,74 @@ def _run_script( # The script file is never written into the workspace. A workspace gets read back -- by a # snapshot, or by a check that lists the directory -- and a stray _script.py in there reads # as something the episode created. - holder = tempfile.mkdtemp(prefix="twinkle_local_") + holder = tempfile.mkdtemp(prefix='twinkle_local_') try: - if interpreter == "python": - path = os.path.join(holder, "_script.py") - with open(path, "w", encoding="utf-8") as f: - f.write(source + "\n") + if interpreter == 'python': + path = os.path.join(holder, '_script.py') + with open(path, 'w', encoding='utf-8') as f: + f.write(source + '\n') argv = [sys.executable, path] - elif interpreter in ("shell", "bash"): + elif interpreter in ('shell', 'bash'): # Not a login shell: sourcing the host's profile prepends whatever # banner it prints to the output of every command, and a check # comparing that output against an expected string then fails on # the banner. PATH and the rest are inherited from the trainer, # which is already in the right environment. - argv = ["/bin/bash", "-c", source] + argv = ['/bin/bash', '-c', source] else: return 1, f"unsupported interpreter {interpreter!r}; use python or shell" return self._spawn(state, argv, timeout, cap_memory) finally: shutil.rmtree(holder, ignore_errors=True) - def _step(self, state: _LocalSession, tool_name: str, arguments: dict[str, Any]) -> StepResult: + def _step(self, state: _LocalSession, tool_name: str, arguments: Dict[str, Any]) -> StepResult: try: - if tool_name == "run_command": + if tool_name == 'run_command': observation = self.run_command(state, arguments) - elif tool_name == "write_file": + elif tool_name == 'write_file': observation = self._write_file(state, arguments) - elif tool_name == "read_file": + elif tool_name == 'read_file': observation = self._read_file(state, arguments) else: - available = [t["function"]["name"] for t in DEFAULT_TOOLS] - observation = f"Error: unknown tool {tool_name!r}. Available tools: {available}." + available = [t['function']['name'] for t in DEFAULT_TOOLS] + observation = f'Error: unknown tool {tool_name!r}. Available tools: {available}.' return StepResult(observation=observation) except Exception as e: # noqa # Same contract as the sandboxed envs: a tool error is an # observation, so the rollout loop can let the model recover. - logger.warning(f"LocalEnv step error (tool={tool_name}): {e}") - return StepResult(observation=f"Error: {e}", info={"error": str(e)}) + logger.warning(f'LocalEnv step error (tool={tool_name}): {e}') + return StepResult(observation=f'Error: {e}', info={'error': str(e)}) - @remote_function(execute="first", collect="first", lazy_collect=False) - def tools(self) -> list[ToolInfo]: + @remote_function(execute='first', collect='first', lazy_collect=False) + def tools(self) -> List[ToolInfo]: return list(DEFAULT_TOOLS) # ------------------------------------------------------------------ # Tools # ------------------------------------------------------------------ - def run_command(self, state: _LocalSession, arguments: dict[str, Any]) -> str: + def run_command(self, state: _LocalSession, arguments: Dict[str, Any]) -> str: """Run a shell command in the episode; public so custom tool handlers can reuse it.""" - command = arguments.get("command") + command = arguments.get('command') if not command: return "Error: 'command' argument is required." - cwd = arguments.get("cwd") + cwd = arguments.get('cwd') if cwd: - command = f"cd {shlex.quote(str(cwd))} && {command}" - exit_code, output = self._run_script(state, command, "shell", timeout=arguments.get("timeout")) + command = f'cd {shlex.quote(str(cwd))} && {command}' + exit_code, output = self._run_script(state, command, 'shell', timeout=arguments.get('timeout')) # stderr is already folded into output by run_script, hence the empty # stream here: what this call adds is the exit-code line. - return format_command_output(output, "", exit_code) + return format_command_output(output, '', exit_code) - def _write_file(self, state: _LocalSession, arguments: dict[str, Any]) -> str: - path = self._resolve(state, arguments["path"]) - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write(arguments.get("content", "")) + def _write_file(self, state: _LocalSession, arguments: Dict[str, Any]) -> str: + path = self._resolve(state, arguments['path']) + os.makedirs(os.path.dirname(path) or '.', exist_ok=True) + with open(path, 'w', encoding='utf-8') as f: + f.write(arguments.get('content', '')) return f"File written: {arguments['path']}" - def _read_file(self, state: _LocalSession, arguments: dict[str, Any]) -> str: - with open(self._resolve(state, arguments["path"]), encoding="utf-8", errors="replace") as f: + def _read_file(self, state: _LocalSession, arguments: Dict[str, Any]) -> str: + with open(self._resolve(state, arguments['path']), encoding='utf-8', errors='replace') as f: return truncate_observation(f.read()) # ------------------------------------------------------------------ @@ -352,16 +340,16 @@ def _resolve(state: _LocalSession, path: str) -> str: since ``run_command`` reaches the same filesystem directly. """ root = os.path.realpath(state.workspace) - target = os.path.realpath(os.path.join(root, str(path).lstrip("/"))) + target = os.path.realpath(os.path.join(root, str(path).lstrip('/'))) if target != root and not target.startswith(root + os.sep): - raise ValueError(f"path {path!r} escapes the workspace") + raise ValueError(f'path {path!r} escapes the workspace') return target def _spawn(self, state: _LocalSession, argv: list[str], timeout: float, cap_memory: bool = True) -> tuple[int, str]: env = dict(os.environ, **_SCRIPT_ENVS, **self._envs) # Inherited from the trainer, and a check that imports torch would # otherwise take a share of a GPU that is mid-generation. - env.pop("CUDA_VISIBLE_DEVICES", None) + env.pop('CUDA_VISIBLE_DEVICES', None) def _limit(): if cap_memory and self._memory_limit_gb: @@ -370,7 +358,7 @@ def _limit(): with state.lock: if state.closed: - return 1, "the episode was closed" + return 1, 'the episode was closed' try: proc = subprocess.Popen( argv, @@ -379,22 +367,21 @@ def _limit(): stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, - errors="replace", + errors='replace', start_new_session=True, - preexec_fn=_limit, - ) + preexec_fn=_limit) except Exception as e: # noqa # A spawn failure is the host's problem, not the script's, and it # comes back as a failed run so one bad call cannot end a whole pass. - return 1, f"{type(e).__name__}: {e}" + return 1, f'{type(e).__name__}: {e}' state.procs.add(proc) try: out, err = proc.communicate(timeout=timeout) - out, err = out or "", err or "" + out, err = out or '', err or '' # A newline between the streams: a stdout line left unterminated # swallows the first line of the traceback that follows it. - if out and err and not out.endswith("\n"): - out += "\n" + if out and err and not out.endswith('\n'): + out += '\n' return proc.returncode, out + err except subprocess.TimeoutExpired: _kill_group(proc) @@ -404,7 +391,7 @@ def _limit(): pass # A killed script has no traceback to explain itself with, so the # output has to say why it produced nothing. - return TIMEOUT_EXIT_CODE, f"execution timed out after {timeout}s (possible infinite loop)" + return TIMEOUT_EXIT_CODE, f'execution timed out after {timeout}s (possible infinite loop)' finally: with state.lock: state.procs.discard(proc) diff --git a/src/twinkle_agentic/envs/resume.py b/src/twinkle_agentic/envs/resume.py index 6f161c50a..835575339 100644 --- a/src/twinkle_agentic/envs/resume.py +++ b/src/twinkle_agentic/envs/resume.py @@ -1,27 +1,26 @@ # Copyright (c) ModelScope Contributors. All rights reserved. """Optional durable-resume protocol for execution environments.""" - from __future__ import annotations from enum import Enum -from typing import Any, Protocol, runtime_checkable +from typing import Any, Dict, Optional, Protocol, runtime_checkable from twinkle.data_format import Trajectory __all__ = [ - "EnvResumeCapability", - "ResumableEnv", - "UnsafeCheckpoint", - "UnsupportedEnvResume", - "env_resume_capability", + 'EnvResumeCapability', + 'ResumableEnv', + 'UnsafeCheckpoint', + 'UnsupportedEnvResume', + 'env_resume_capability', ] class EnvResumeCapability(str, Enum): """How an environment can survive a different Twinkle process.""" - NONE = "none" - LIVE_ATTACH = "live_attach" - DURABLE_CHECKPOINT = "durable_checkpoint" + NONE = 'none' + LIVE_ATTACH = 'live_attach' + DURABLE_CHECKPOINT = 'durable_checkpoint' class UnsupportedEnvResume(NotImplementedError): @@ -38,15 +37,15 @@ class ResumableEnv(Protocol): resume_capability: EnvResumeCapability - def checkpoint_episode(self, episode_id: str, state_key: str) -> dict[str, Any]: + def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: """Capture one quiescent episode under its stable logical identity.""" def restore_episode( self, episode_id: str, state_key: str, - state: dict[str, Any], - trajectory: Trajectory | None = None, + state: Dict[str, Any], + trajectory: Optional[Trajectory] = None, ) -> None: """Bind a durable snapshot to a newly allocated logical session.""" @@ -56,18 +55,21 @@ def discard_episode_state(self, state_key: str) -> None: def env_resume_capability(env: Any) -> EnvResumeCapability: """Return an environment's declared capability after structural validation.""" - declared = getattr(env, "resume_capability", EnvResumeCapability.NONE) + declared = getattr(env, 'resume_capability', EnvResumeCapability.NONE) try: capability = EnvResumeCapability(declared) except ValueError as exc: - raise UnsupportedEnvResume(f"{type(env).__name__} declares invalid resume capability {declared!r}") from exc + raise UnsupportedEnvResume( + f'{type(env).__name__} declares invalid resume capability {declared!r}' + ) from exc if capability == EnvResumeCapability.NONE: return capability missing = [ - name - for name in ("checkpoint_episode", "restore_episode", "discard_episode_state") + name for name in ('checkpoint_episode', 'restore_episode', 'discard_episode_state') if not callable(getattr(env, name, None)) ] if missing: - raise UnsupportedEnvResume(f"{type(env).__name__} declares {capability.value} but is missing {missing}") + raise UnsupportedEnvResume( + f'{type(env).__name__} declares {capability.value} but is missing {missing}' + ) return capability diff --git a/src/twinkle_agentic/rollout/ledger.py b/src/twinkle_agentic/rollout/ledger.py index 9cfeca006..5ad66e725 100644 --- a/src/twinkle_agentic/rollout/ledger.py +++ b/src/twinkle_agentic/rollout/ledger.py @@ -32,10 +32,11 @@ from dataclasses import replace from typing import Any -from twinkle.data_format import Trajectory, turn_token_spans, validate_trajectory +from twinkle.data_format import Trajectory from twinkle.data_format import last_assistant_text as _traj_last_assistant_text -from twinkle.data_format.sampling import SampledSequence +from twinkle.data_format import turn_token_spans, validate_trajectory from twinkle.data_format.trajectory import _trainable_positions +from twinkle.data_format.sampling import SampledSequence from twinkle.template.base import Template from twinkle.template.contract import RolloutState, coerce_tool_call_arguments from twinkle_agentic.utils.token_utils import _to_plain, append_ids @@ -119,29 +120,29 @@ def state_dict(self) -> dict[str, Any]: """ self.audit() return { - "format": "twinkle.turn-ledger.v1", - "input_feature": copy.deepcopy(self._pif), - "state": copy.deepcopy(self._state), - "logprobs": copy.deepcopy(self._logprobs), - "sampling_masks": copy.deepcopy(self._sampling_masks), - "turns": self._turns, + 'format': 'twinkle.turn-ledger.v1', + 'input_feature': copy.deepcopy(self._pif), + 'state': copy.deepcopy(self._state), + 'logprobs': copy.deepcopy(self._logprobs), + 'sampling_masks': copy.deepcopy(self._sampling_masks), + 'turns': self._turns, } def load_state_dict(self, state: dict[str, Any]) -> None: """Replace the mutable account with a previously exported one.""" - if state.get("format") != "twinkle.turn-ledger.v1": - raise ValueError("unsupported TurnLedger checkpoint format") - input_feature = state.get("input_feature") - logprobs = state.get("logprobs") - turns = state.get("turns") - if not isinstance(input_feature, dict) or "input_ids" not in input_feature: - raise ValueError("TurnLedger checkpoint is missing input_feature.input_ids") + if state.get('format') != 'twinkle.turn-ledger.v1': + raise ValueError('unsupported TurnLedger checkpoint format') + input_feature = state.get('input_feature') + logprobs = state.get('logprobs') + turns = state.get('turns') + if not isinstance(input_feature, dict) or 'input_ids' not in input_feature: + raise ValueError('TurnLedger checkpoint is missing input_feature.input_ids') if not isinstance(logprobs, list) or not isinstance(turns, int) or turns < 0: - raise ValueError("TurnLedger checkpoint has invalid logprobs or turns") + raise ValueError('TurnLedger checkpoint has invalid logprobs or turns') self._pif = copy.deepcopy(input_feature) - self._state = copy.deepcopy(state.get("state")) + self._state = copy.deepcopy(state.get('state')) self._logprobs = copy.deepcopy(logprobs) - self._sampling_masks = copy.deepcopy(state.get("sampling_masks")) + self._sampling_masks = copy.deepcopy(state.get('sampling_masks')) self._turns = turns self.audit() @@ -318,12 +319,12 @@ def record(self, seq: SampledSequence) -> None: self._state = completion.state self._pif = sampled_feature if len(self.messages) < len(messages) + 1: - current_messages = messages + [{"role": "assistant", "content": seq.decoded or ""}] - self._pif["messages"] = current_messages + current_messages = messages + [{'role': 'assistant', 'content': seq.decoded or ''}] + self._pif['messages'] = current_messages if self._state is not None: self._state = replace(self._state, messages=tuple(current_messages)) if not self.tools and tools: - self._pif["tools"] = tools + self._pif['tools'] = tools if self._state is not None: self._state = replace(self._state, tools=tuple(tools)) self._turns += 1 @@ -726,4 +727,4 @@ def audit(self) -> None: return -__all__ = ["MessageLedger", "TurnLedger", "turn_token_spans"] +__all__ = ['MessageLedger', 'TurnLedger', 'turn_token_spans'] diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 5955c0117..3f85c9fe7 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -7,8 +7,8 @@ merged, trainable trajectory and releases everything. A caller that drives many episodes (the streaming driver) interleaves their steps; a caller that wants whole episodes uses ``__call__``. """ - import hashlib +import json import queue import re import threading @@ -19,8 +19,6 @@ from dataclasses import dataclass, field, replace from typing import Any, Optional -import json - from twinkle.data_format import Trajectory, user_data_get from twinkle.data_format.sampling import SampledSequence, SampleResponse, SamplingParams from twinkle.infra import remote_class, remote_function @@ -29,8 +27,8 @@ from twinkle.utils import get_logger from twinkle_agentic.async_rl.rollout_resume import ResumeStore, UnsafeResume from twinkle_agentic.envs.base import NoSlot -from twinkle_agentic.envs.env_tool import EnvTool from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability +from twinkle_agentic.envs.env_tool import EnvTool from twinkle_agentic.protocol.api_sampler import APIGenerationError from twinkle_agentic.tools.tool_manager import ToolManager from twinkle_agentic.verifier.result_check import CheckContext, checks_from_dicts, run_checks @@ -67,13 +65,12 @@ def _dump_rollout_rows(episode_id: str, rows: list) -> None: segments for prefix-extension. Write-only and env-gated: a no-op (zero cost) when unset. """ import os - - root = os.environ.get("TWINKLE_ROLLOUT_TRAJ_DUMP") + root = os.environ.get('TWINKLE_ROLLOUT_TRAJ_DUMP') if not root: return os.makedirs(root, exist_ok=True) - rank = int(os.environ.get("RANK") or os.environ.get("LOCAL_RANK") or 0) - path = os.path.join(root, f"rows.rank{rank}.jsonl") + rank = int(os.environ.get('RANK') or os.environ.get('LOCAL_RANK') or 0) + path = os.path.join(root, f'rows.rank{rank}.jsonl') def _grid(value: Any) -> Any: # image_grid_thw / video_grid_thw arrive as a tensor (one row per media item); @@ -81,45 +78,45 @@ def _grid(value: Any) -> Any: # plain nested ints. Absent on text rows -- leave it None, not an empty grid. if value is None: return None - tolist = getattr(value, "tolist", None) + tolist = getattr(value, 'tolist', None) return tolist() if callable(tolist) else value - def _media_count(value: Any) -> int | None: + def _media_count(value: Any) -> Optional[int]: return len(value) if isinstance(value, (list, tuple)) else None - with open(path, "a", encoding="utf-8") as handle: + with open(path, 'a', encoding='utf-8') as handle: for seg, row in enumerate(rows): - messages = row.get("messages") or [] + messages = row.get('messages') or [] rec = { - "episode_id": episode_id, - "segment_index": row.get("segment_index", seg), - "rank": rank, - "input_ids": row.get("input_ids") or [], - "labels": row.get("labels") or [], - "completion_mask": row.get("completion_mask"), - "response_token_ids": row.get("response_token_ids") or [], - "response_positions": row.get("response_positions") or [], - "rollout_logps": row.get("rollout_logps"), - "messages": messages, - "stop_reason": row.get("stop_reason"), + 'episode_id': episode_id, + 'segment_index': row.get('segment_index', seg), + 'rank': rank, + 'input_ids': row.get('input_ids') or [], + 'labels': row.get('labels') or [], + 'completion_mask': row.get('completion_mask'), + 'response_token_ids': row.get('response_token_ids') or [], + 'response_positions': row.get('response_positions') or [], + 'rollout_logps': row.get('rollout_logps'), + 'messages': messages, + 'stop_reason': row.get('stop_reason'), # D6 media frame: raw media counts + the processor grid. The judge checks # image-count consistency and the placeholder-token expansion against the grid. - "images_count": _media_count(row.get("images")), - "videos_count": _media_count(row.get("videos")), - "audios_count": _media_count(row.get("audios")), - "image_grid_thw": _grid(row.get("image_grid_thw")), - "video_grid_thw": _grid(row.get("video_grid_thw")), + 'images_count': _media_count(row.get('images')), + 'videos_count': _media_count(row.get('videos')), + 'audios_count': _media_count(row.get('audios')), + 'image_grid_thw': _grid(row.get('image_grid_thw')), + 'video_grid_thw': _grid(row.get('video_grid_thw')), } - handle.write(json.dumps(rec, default=str) + "\n") + handle.write(json.dumps(rec, default=str) + '\n') # Termination reasons surfaced via ``trajectory['stop_reason']``. The sampler # path takes the first three from the sampler itself; the API path has to name # them, and one vocabulary for both is what lets a consumer read either. -STOP_NO_TOOL = "stop" -STOP_LENGTH = "length" -STOP_MAX_TURNS = "max_turns" -STOP_GENERATION_ERROR = "generation_error" +STOP_NO_TOOL = 'stop' +STOP_LENGTH = 'length' +STOP_MAX_TURNS = 'max_turns' +STOP_GENERATION_ERROR = 'generation_error' # Runaway guard: a ``followup_fn`` is expected to return None eventually. This # only bounds a callback that never does, so one bad hook cannot spin forever. @@ -129,7 +126,6 @@ def _media_count(value: Any) -> int | None: #: ceiling only: how many episodes are in flight is the driver's admission, not this. ROLLOUT_MAX_CONCURRENCY = 1024 - def _record_dispatch_probe(event: str, episode_id: str, **fields: Any) -> None: """Append one dispatch event per call when ``TWINKLE_DISPATCH_PROBE`` names a directory. @@ -138,19 +134,17 @@ def _record_dispatch_probe(event: str, episode_id: str, **fields: Any) -> None: order that got it there, so this records each step entry, each session open, and each harness wait/item/serve per episode. Env-gated: unset, it does nothing. """ - import os - import json + import os - root = os.environ.get("TWINKLE_DISPATCH_PROBE") + root = os.environ.get('TWINKLE_DISPATCH_PROBE') if not root: return os.makedirs(root, exist_ok=True) - path = os.path.join(root, f"dispatch.{os.getpid()}.jsonl") - with open(path, "a", encoding="utf-8") as handle: - handle.write( - json.dumps({"t": time.monotonic(), "event": event, "episode_id": episode_id, **fields}, default=str) + "\n" - ) + path = os.path.join(root, f'dispatch.{os.getpid()}.jsonl') + with open(path, 'a', encoding='utf-8') as handle: + handle.write(json.dumps({'t': time.monotonic(), 'event': event, 'episode_id': episode_id, + **fields}, default=str) + '\n') #: Put on an episode's request queue when its agent program exits. @@ -204,11 +198,11 @@ class RolloutStatus: """ # Group identity and role, stamped by the driver. - prompt_id: str = "" - episode_id: str = "" + prompt_id: str = '' + episode_id: str = '' group_key: str | None = None #: '' for a policy sample, 'baseline' for a baseline episode a group asked for. - role: str = "" + role: str = '' # The policy version the episode was admitted under, and how far the policy moved by handover. policy_version: int = 0 version_span: int = 0 @@ -236,16 +230,15 @@ class RolloutStatus: def _single_sequence(responses: Any) -> SampledSequence: if not isinstance(responses, list): - raise TypeError(f"expected List[SampleResponse] from sampler.sample, got {type(responses).__name__}") + raise TypeError(f'expected List[SampleResponse] from sampler.sample, got {type(responses).__name__}') if len(responses) != 1: - raise RuntimeError(f"sampler returned {len(responses)} responses for a single request; expected exactly one.") + raise RuntimeError(f'sampler returned {len(responses)} responses for a single request; expected exactly one.') response = responses[0] if not isinstance(response, (SampleResponse, SampleResponseModel)): - raise TypeError( - f"expected SampleResponse or SampleResponseModel from sampler.sample, got {type(response).__name__}" - ) + raise TypeError(f'expected SampleResponse or SampleResponseModel from sampler.sample, ' + f'got {type(response).__name__}') if len(response.sequences) != 1: - raise RuntimeError(f"SampleResponse contains {len(response.sequences)} sequences; expected exactly one.") + raise RuntimeError(f'SampleResponse contains {len(response.sequences)} sequences; expected exactly one.') sequence = response.sequences[0] if isinstance(response, SampleResponseModel): return SampledSequence(**sequence.model_dump()) @@ -265,12 +258,12 @@ def is_error_observation(observation: str) -> bool: anywhere in the text also matches a *successful* read of a file that happens to contain them, and this decides whether an episode is cut short. """ - text = (observation or "").strip() + text = (observation or '').strip() if not text: return False - if text.startswith("Error:"): + if text.startswith('Error:'): return True - if text.startswith(("Tool runtime unreachable:", "Tool runtime returned no result")): + if text.startswith(('Tool runtime unreachable:', 'Tool runtime returned no result')): return True return bool(re.search(r'"success"\s*:\s*false', text)) @@ -282,15 +275,15 @@ def _call_key(tool_call: dict[str, Any]) -> str: making progress; one that reissues the same call with the same arguments is not, whatever the tool answered. """ - fn = tool_call.get("function") if isinstance(tool_call.get("function"), dict) else {} - name = fn.get("name") or tool_call.get("name") or tool_call.get("tool_name") or "" - args = fn.get("arguments", tool_call.get("arguments")) + fn = tool_call.get('function') if isinstance(tool_call.get('function'), dict) else {} + name = fn.get('name') or tool_call.get('name') or tool_call.get('tool_name') or '' + args = fn.get('arguments', tool_call.get('arguments')) if not isinstance(args, str): try: args = json.dumps(args, sort_keys=True, ensure_ascii=False) except (TypeError, ValueError): args = repr(args) - return f"{name}\x00{args}" + return f'{name}\x00{args}' def _tool_call_names(tool_calls: list[dict[str, Any]]) -> list[str]: @@ -301,8 +294,8 @@ def _tool_call_names(tool_calls: list[dict[str, Any]]) -> list[str]: """ names: list[str] = [] for tool_call in tool_calls: - fn = tool_call.get("function") if isinstance(tool_call.get("function"), dict) else {} - name = fn.get("name") or tool_call.get("name") or tool_call.get("tool_name") or "" + fn = tool_call.get('function') if isinstance(tool_call.get('function'), dict) else {} + name = fn.get('name') or tool_call.get('name') or tool_call.get('tool_name') or '' if name: names.append(name) return names @@ -314,16 +307,16 @@ def _default_tool_messages( ) -> list[dict[str, Any]]: msgs: list[dict[str, Any]] = [] for i, obs in enumerate(observations): - msg: dict[str, Any] = {"role": "tool", "content": "" if obs is None else str(obs)} + msg: dict[str, Any] = {'role': 'tool', 'content': '' if obs is None else str(obs)} if i < len(tool_calls) and isinstance(tool_calls[i], dict): tc = tool_calls[i] - fn = tc.get("function") if isinstance(tc.get("function"), dict) else {} - tid = tc.get("id") or tc.get("tool_call_id") - name = fn.get("name") or tc.get("name") or tc.get("tool_name") + fn = tc.get('function') if isinstance(tc.get('function'), dict) else {} + tid = tc.get('id') or tc.get('tool_call_id') + name = fn.get('name') or tc.get('name') or tc.get('tool_name') if tid: - msg["tool_call_id"] = tid + msg['tool_call_id'] = tid if name: - msg["name"] = name + msg['name'] = name msgs.append(msg) return msgs @@ -335,36 +328,34 @@ def _malformed_tool_message(errors: list[str]) -> dict[str, Any]: make. There is no ``tool_call_id`` to pair it with -- the call never became a call -- which ``_default_tool_messages`` above already treats as optional. """ - reason = "; ".join(e for e in errors if e) or "the markup could not be parsed" + reason = '; '.join(e for e in errors if e) or 'the markup could not be parsed' return { - "role": "tool", - "content": ( - "Your tool call was not run: " + reason + ". Send the call again. Inside " - "a JSON string a backslash has to be written as \\\\ and a line break as " - "\\n; a single quote needs no backslash at all." - ), + 'role': 'tool', + 'content': ('Your tool call was not run: ' + reason + '. Send the call again. Inside ' + 'a JSON string a backslash has to be written as \\\\ and a line break as ' + '\\n; a single quote needs no backslash at all.'), } -def _episode_id_of(trajectory: Any) -> str | None: +def _episode_id_of(trajectory: Any) -> Optional[str]: if not isinstance(trajectory, dict): return None - episode_id = trajectory.get("episode_id") + episode_id = trajectory.get('episode_id') if episode_id is None: - episode_id = user_data_get(trajectory.get("user_data"), "episode_id") + episode_id = user_data_get(trajectory.get('user_data'), 'episode_id') return str(episode_id) if episode_id else None -def _episode_key(args: tuple, kwargs: dict) -> str | None: +def _episode_key(args: tuple, kwargs: dict) -> Optional[str]: """The routing key of ``step``/``stop``: the episode id, so every step of an episode meets its state. Read off ``episode_id`` when the caller passes it (the trajectory may be a reference the caller cannot open), else off the trajectory's ``user_data``. """ - episode_id = kwargs.get("episode_id") or (args[1] if len(args) > 1 else None) + episode_id = kwargs.get('episode_id') or (args[1] if len(args) > 1 else None) if episode_id: return str(episode_id) - return _episode_id_of(kwargs.get("traj", args[0] if args else None)) + return _episode_id_of(kwargs.get('traj', args[0] if args else None)) def _canonical(message: dict[str, Any]) -> tuple: @@ -374,20 +365,20 @@ def _canonical(message: dict[str, Any]) -> tuple: content ``None`` for ``''``, whitespace trimmed. Comparing these forms is what tells a conversation that grew from one that was rewritten. """ - content = message.get("content") + content = message.get('content') if isinstance(content, list): - content = "".join(part.get("text") or "" for part in content if isinstance(part, dict)) + content = ''.join(part.get('text') or '' for part in content if isinstance(part, dict)) calls = [] - for call in message.get("tool_calls") or []: - fn = call.get("function") if isinstance(call.get("function"), dict) else {} - arguments = fn.get("arguments") + for call in message.get('tool_calls') or []: + fn = call.get('function') if isinstance(call.get('function'), dict) else {} + arguments = fn.get('arguments') if isinstance(arguments, str): try: arguments = json.loads(arguments) except ValueError: pass - calls.append((fn.get("name") or "", json.dumps(arguments, sort_keys=True, ensure_ascii=False))) - return (message.get("role"), str(content or "").strip(), tuple(calls), message.get("tool_call_id") or "") + calls.append((fn.get('name') or '', json.dumps(arguments, sort_keys=True, ensure_ascii=False))) + return (message.get('role'), str(content or '').strip(), tuple(calls), message.get('tool_call_id') or '') class _Episode: @@ -398,7 +389,7 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara self.trajectory = trajectory self.params = params self.ledger = None - self.tool_manager: ToolManager | None = None + self.tool_manager: Optional[ToolManager] = None self.env_open = False #: Set by ``_discard``. ``_open`` blocks in ``env.reset`` while every session slot is taken, and #: the episode can be discarded meanwhile, so the call that returns afterwards has to be able to @@ -414,17 +405,17 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara self.stuck = 0 self.seen_calls: set = set() self.stuck_stop = False - self.tool_stop: str | None = None + self.tool_stop: Optional[str] = None self.truncated = False - self.stop_reason: str | None = None - self.error: str | None = None + self.stop_reason: Optional[str] = None + self.error: Optional[str] = None # The agent program: see ``MultiTurnRollout._harness_step``. - self.requests: queue.Queue | None = None - self.exit: tuple | None = None + self.requests: Optional[queue.Queue] = None + self.exit: Optional[tuple] = None self.deadline = 0.0 self.segments = 0 self.sent: list[tuple] = [] - self.tools_key: str | None = None + self.tools_key: Optional[str] = None #: The last served reply, for resubmitted requests (an agent HTTP client that timed out #: and retried sends the same payload verbatim: it is answered verbatim, not re-served). self.last_reply: dict | None = None @@ -438,10 +429,10 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara #: froze, oldest first; the final segment's row joins them when the episode ends. self.closed_rows: list = [] #: Stable identity supplied by the driver. It is not a random session id. - self.state_key = str(trajectory.get("state_key") or "") + self.state_key = str(trajectory.get('state_key') or '') #: Behavior-policy binding for the whole episode. A resumed group keeps this adapter even #: after the sampler's mutable default has moved on to a newer policy. - self.adapter_path: str | None = trajectory.get("adapter_path") + self.adapter_path: Optional[str] = trajectory.get('adapter_path') #: Effects already represented by the latest durable episode checkpoint. self.completed_effects: set[str] = set() @@ -524,45 +515,38 @@ def __init__( adapter_path: str | None = None, use_base_model: bool = False, concurrency: int | None = None, - segment_policy: str = "drop", + segment_policy: str = 'drop', seed: int | None = None, resume_store: ResumeStore | None = None, ): if sampler is None and response_callback is None: - raise ValueError("MultiTurnRollout requires a sampler or a response_callback.") - if ( - sampler is not None - and template is not None - and getattr(getattr(type(sampler), "sample", None), "_enable_continous_work", None) is False - ): + raise ValueError('MultiTurnRollout requires a sampler or a response_callback.') + if sampler is not None and template is not None and getattr( + getattr(type(sampler), 'sample', None), '_enable_continous_work', None) is False: # A remote sampler whose sample is not continuous-work spreads each one-request # call over every worker and raises on the ranks that receive nothing. - raise ValueError( - f"{type(sampler).__name__}.sample must be declared with enable_continous_work=True: " - "this rollout samples one trajectory per call." - ) + raise ValueError(f'{type(sampler).__name__}.sample must be declared with enable_continous_work=True: ' + 'this rollout samples one trajectory per call.') if max_turns < 1: - raise ValueError(f"max_turns must be >= 1, got {max_turns}") + raise ValueError(f'max_turns must be >= 1, got {max_turns}') if max_trajectory_tokens is not None and max_trajectory_tokens < 1: - raise ValueError(f"max_trajectory_tokens must be >= 1 or None, got {max_trajectory_tokens}") + raise ValueError(f'max_trajectory_tokens must be >= 1 or None, got {max_trajectory_tokens}') if concurrency is not None and concurrency < 1: - raise ValueError(f"concurrency must be >= 1 or None, got {concurrency}") + raise ValueError(f'concurrency must be >= 1 or None, got {concurrency}') if adapter_path and use_base_model: - raise ValueError( - "adapter_path and use_base_model=True ask for opposite " - "weights; the sampler would drop the adapter silently." - ) + raise ValueError('adapter_path and use_base_model=True ask for opposite ' + 'weights; the sampler would drop the adapter silently.') if harness is not None: if env is None: - raise ValueError("a harness runs its program in an env session: pass env= (LocalEnv for this machine).") + raise ValueError('a harness runs its program in an env session: pass env= ' + '(LocalEnv for this machine).') if template is None: - raise ValueError("a harness needs a template to account the requests it makes.") + raise ValueError('a harness needs a template to account the requests it makes.') if tool_manager is not None or followup_fn is not None: - raise ValueError( - "a harness owns its tools and its loop; tool_manager= and followup_fn= apply to the tool loop only." - ) + raise ValueError('a harness owns its tools and its loop; tool_manager= and followup_fn= ' + 'apply to the tool loop only.') if harness.protocol not in ENDPOINTS: - raise ValueError(f"harness protocol {harness.protocol!r} is not one of {sorted(ENDPOINTS)}") + raise ValueError(f'harness protocol {harness.protocol!r} is not one of {sorted(ENDPOINTS)}') # How many stuck turns in a row end the episode; 0 runs to ``max_turns`` # regardless. A turn is stuck when it made no progress at all: every call in # it came back an error, or every call in it was byte-identical to one already @@ -570,23 +554,22 @@ def __init__( # recorded episodes: errors alone stop 1 of 12 and save 9 of 239 calls; adding # the repeat rule stops 3 of 12 and saves 63 calls. if stop_after_stuck_turns < 0: - raise ValueError(f"stop_after_stuck_turns must be >= 0, got {stop_after_stuck_turns}") + raise ValueError(f'stop_after_stuck_turns must be >= 0, got {stop_after_stuck_turns}') # How a compaction boundary treats the segment it writes out: 'drop' (the default) keeps # only the final segment trainable -- the episode trains as one row; 'collect' freezes # each written-out segment into its own row, and the episode is delivered as several # independently-coded rows that share one identity and one outcome reward. - if segment_policy not in ("drop", "collect"): + if segment_policy not in ('drop', 'collect'): raise ValueError(f"segment_policy must be 'drop' or 'collect', got {segment_policy!r}.") # How many replies in a row may carry tool-call markup that does not parse # before the episode is given up. Such a reply asked for a tool and had the # markup rejected, so it gets the parser's reason back and another turn. if max_malformed_retries < 0: - raise ValueError(f"max_malformed_retries must be >= 0, got {max_malformed_retries}") + raise ValueError(f'max_malformed_retries must be >= 0, got {max_malformed_retries}') if template is not None: - assert template.truncation_strategy != "split", ( + assert template.truncation_strategy != 'split', ( "MultiTurnRollout does not support truncation_strategy='split'; " - "use left/right/delete/raise on the template." - ) + 'use left/right/delete/raise on the template.') self.sampler = sampler self.template = template self.max_turns = max_turns @@ -605,20 +588,20 @@ def __init__( self.stop_after_stuck_turns = stop_after_stuck_turns self.max_malformed_retries = max_malformed_retries # Left out entirely when unset, so a sampler without LoRA sees the call it always did. - self._adapter_kwargs: dict[str, Any] = {"adapter_path": adapter_path} if adapter_path else {} + self._adapter_kwargs: dict[str, Any] = {'adapter_path': adapter_path} if adapter_path else {} if use_base_model: - self._adapter_kwargs["use_base_model"] = True + self._adapter_kwargs['use_base_model'] = True self.adapter_path = adapter_path self.concurrency = concurrency self.segment_policy = segment_policy self._base_seed = seed - self._template_backend = getattr(type(sampler), "template_backend", "vllm") if sampler is not None else "vllm" + self._template_backend = getattr(type(sampler), 'template_backend', 'vllm') if sampler is not None else 'vllm' self.sampling_params = self._params(sampling_params or SamplingParams()) self._episodes: dict[str, _Episode] = {} self._lock = threading.Lock() self._endpoint_lock = threading.Lock() - self._policy_endpoint: PolicyEndpoint | None = None - self._env_tool_infos: list | None = None + self._policy_endpoint: Optional[PolicyEndpoint] = None + self._env_tool_infos: Optional[list] = None self.resume_store = resume_store # ---------------------------------------------------------------- durable episode @@ -627,61 +610,61 @@ def bind_resume_store(self, store: ResumeStore) -> None: """Inject the run store before the first episode starts.""" with self._lock: if self._episodes: - raise RuntimeError("bind_resume_store must run before any episode is opened") + raise RuntimeError('bind_resume_store must run before any episode is opened') self.resume_store = store def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: if ep.busy and not allow_busy: - raise UnsafeResume(f"episode {ep.episode_id!r} is mid-step and cannot be checkpointed") + raise UnsafeResume(f'episode {ep.episode_id!r} is mid-step and cannot be checkpointed') if self.harness is not None: - raise UnsafeResume("agent-program episodes own live processes and cannot be checkpointed yet") + raise UnsafeResume('agent-program episodes own live processes and cannot be checkpointed yet') if not ep.state_key: - raise UnsafeResume(f"episode {ep.episode_id!r} has no stable state_key") + raise UnsafeResume(f'episode {ep.episode_id!r} has no stable state_key') if ep.ledger is None: - raise UnsafeResume(f"episode {ep.episode_id!r} has no token ledger yet") + raise UnsafeResume(f'episode {ep.episode_id!r} has no token ledger yet') if isinstance(ep.ledger, MessageLedger): - raise UnsafeResume("message-ledger episodes lose sampled token ids and cannot be resumed safely") + raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') env_state = None if ep.env_open: capability = env_resume_capability(self.env) if capability == EnvResumeCapability.NONE: - raise UnsafeResume(f"{type(self.env).__name__} declares no durable resume capability") + raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') env_state = self.env.checkpoint_episode(ep.episode_id, ep.state_key) return { - "format": "twinkle.multi-turn-episode.v1", - "state_key": ep.state_key, - "episode_id": ep.episode_id, - "trajectory": ep.trajectory, - "params": ep.params, - "ledger": ep.ledger.state_dict(), - "env_state": env_state, - "env_open": ep.env_open, - "budget": ep.budget, - "spent": ep.spent, - "followups": ep.followups, - "malformed": ep.malformed, - "stuck": ep.stuck, - "seen_calls": sorted(ep.seen_calls), - "stuck_stop": ep.stuck_stop, - "tool_stop": ep.tool_stop, - "truncated": ep.truncated, - "stop_reason": ep.stop_reason, - "error": ep.error, - "segments": ep.segments, - "sent": ep.sent, - "tools_key": ep.tools_key, - "last_reply": ep.last_reply, - "closed_rows": ep.closed_rows, - "completed_effects": sorted(ep.completed_effects), + 'format': 'twinkle.multi-turn-episode.v1', + 'state_key': ep.state_key, + 'episode_id': ep.episode_id, + 'trajectory': ep.trajectory, + 'params': ep.params, + 'ledger': ep.ledger.state_dict(), + 'env_state': env_state, + 'env_open': ep.env_open, + 'budget': ep.budget, + 'spent': ep.spent, + 'followups': ep.followups, + 'malformed': ep.malformed, + 'stuck': ep.stuck, + 'seen_calls': sorted(ep.seen_calls), + 'stuck_stop': ep.stuck_stop, + 'tool_stop': ep.tool_stop, + 'truncated': ep.truncated, + 'stop_reason': ep.stop_reason, + 'error': ep.error, + 'segments': ep.segments, + 'sent': ep.sent, + 'tools_key': ep.tools_key, + 'last_reply': ep.last_reply, + 'closed_rows': ep.closed_rows, + 'completed_effects': sorted(ep.completed_effects), } - @remote_function(execute="first", collect="first", lazy_collect=False) + @remote_function(execute='first', collect='first', lazy_collect=False) def checkpoint_episode(self, episode_id: str) -> dict[str, Any]: """Persist one episode at an externally stable boundary.""" with self._lock: ep = self._episodes.get(episode_id) if ep is None: - raise EpisodeError(f"episode {episode_id!r} is not held by this rollout") + raise EpisodeError(f'episode {episode_id!r} is not held by this rollout') return self._checkpoint_episode(ep) def _checkpoint_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: @@ -692,70 +675,70 @@ def _checkpoint_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict def restore_episode(self, state: dict[str, Any]) -> str: """Rebuild an episode from a durable state before it is stepped again.""" - if state.get("format") != "twinkle.multi-turn-episode.v1": - raise UnsafeResume("unsupported MultiTurnRollout episode format") - state_key = str(state.get("state_key") or "") - episode_id = str(state.get("episode_id") or "") + if state.get('format') != 'twinkle.multi-turn-episode.v1': + raise UnsafeResume('unsupported MultiTurnRollout episode format') + state_key = str(state.get('state_key') or '') + episode_id = str(state.get('episode_id') or '') if not state_key or not episode_id: - raise UnsafeResume("episode checkpoint has no state_key or episode_id") + raise UnsafeResume('episode checkpoint has no state_key or episode_id') if self.resume_store is not None: - checkpointed = set(state.get("completed_effects") or ()) + checkpointed = set(state.get('completed_effects') or ()) pending = set(self.resume_store.pending_effects(state_key)) unsafe_pending = pending - checkpointed if unsafe_pending: - raise UnsafeResume(f"episode {state_key} has pending tool effects: {sorted(unsafe_pending)!r}") + raise UnsafeResume(f'episode {state_key} has pending tool effects: {sorted(unsafe_pending)!r}') # The checkpoint is written after the tool messages enter the ledger but before the # result journal record. If only that final record is missing, the checkpoint proves # the effect happened and already contains its observation; close the journal gap # instead of rejecting a state that cannot repeat the external call. for effect_key in pending & checkpointed: - self.resume_store.finish_effect(effect_key, {"recovered_from_checkpoint": True}) + self.resume_store.finish_effect(effect_key, {'recovered_from_checkpoint': True}) completed = set(self.resume_store.completed_effects(state_key)) missing = completed - checkpointed if missing: - raise UnsafeResume(f"effect results exist without a matching episode checkpoint: {sorted(missing)!r}") + raise UnsafeResume(f'effect results exist without a matching episode checkpoint: {sorted(missing)!r}') - ep = _Episode(episode_id, dict(state["trajectory"]), state["params"]) + ep = _Episode(episode_id, dict(state['trajectory']), state['params']) ep.state_key = state_key ep.ledger = self._new_ledger(episode_id) if isinstance(ep.ledger, MessageLedger): - raise UnsafeResume("message-ledger episodes lose sampled token ids and cannot be resumed safely") - ep.ledger.load_state_dict(state["ledger"]) - ep.env_open = bool(state.get("env_open")) + raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') + ep.ledger.load_state_dict(state['ledger']) + ep.env_open = bool(state.get('env_open')) if ep.env_open: if self.env is None: - raise UnsafeResume("checkpoint has an environment state but this rollout has no env") + raise UnsafeResume('checkpoint has an environment state but this rollout has no env') capability = env_resume_capability(self.env) if capability == EnvResumeCapability.NONE: - raise UnsafeResume(f"{type(self.env).__name__} declares no durable resume capability") - self.env.restore_episode(episode_id, state_key, state["env_state"], ep.trajectory) - ep.budget = int(state["budget"]) - ep.spent = int(state["spent"]) - ep.followups = int(state["followups"]) - ep.malformed = int(state["malformed"]) - ep.stuck = int(state["stuck"]) - ep.seen_calls = set(state.get("seen_calls") or ()) - ep.stuck_stop = bool(state.get("stuck_stop")) - ep.tool_stop = state.get("tool_stop") - ep.truncated = bool(state.get("truncated")) - ep.stop_reason = state.get("stop_reason") - ep.error = state.get("error") - ep.segments = int(state.get("segments") or 0) - ep.sent = list(state.get("sent") or ()) - ep.tools_key = state.get("tools_key") - ep.last_reply = state.get("last_reply") - ep.closed_rows = list(state.get("closed_rows") or ()) - ep.completed_effects = set(state.get("completed_effects") or ()) + raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') + self.env.restore_episode(episode_id, state_key, state['env_state'], ep.trajectory) + ep.budget = int(state['budget']) + ep.spent = int(state['spent']) + ep.followups = int(state['followups']) + ep.malformed = int(state['malformed']) + ep.stuck = int(state['stuck']) + ep.seen_calls = set(state.get('seen_calls') or ()) + ep.stuck_stop = bool(state.get('stuck_stop')) + ep.tool_stop = state.get('tool_stop') + ep.truncated = bool(state.get('truncated')) + ep.stop_reason = state.get('stop_reason') + ep.error = state.get('error') + ep.segments = int(state.get('segments') or 0) + ep.sent = list(state.get('sent') or ()) + ep.tools_key = state.get('tools_key') + ep.last_reply = state.get('last_reply') + ep.closed_rows = list(state.get('closed_rows') or ()) + ep.completed_effects = set(state.get('completed_effects') or ()) ep.tool_manager = self._episode_tools(episode_id) with self._lock: if episode_id in self._episodes: - raise UnsafeResume(f"episode {episode_id!r} is already held by this rollout") + raise UnsafeResume(f'episode {episode_id!r} is already held by this rollout') self._episodes[episode_id] = ep return episode_id def restore_episode_from_store(self, state_key: str) -> str: if self.resume_store is None: - raise UnsafeResume("no resume store is bound to this rollout") + raise UnsafeResume('no resume store is bound to this rollout') return self.restore_episode(self.resume_store.load_episode(state_key)) @remote_function(dispatch="all", collect="none", lazy_collect=False) @@ -767,9 +750,8 @@ def discard_episode_state(self, state_key: str) -> None: # ------------------------------------------------------------------ entries @remote_function(enable_continous_work=True, sticky_key=_episode_key, stash=(0,), lazy_collect=True) - def step( - self, traj: Trajectory, episode_id: str | None = None, session_wait: float | None = None - ) -> tuple[list, RolloutStatus]: + def step(self, traj: Trajectory, episode_id: str | None = None, + session_wait: Optional[float] = None) -> tuple[list, RolloutStatus]: """Advance the episode one generation; ``(rows, sample)`` with ``sample.done`` on the last. The first call of an episode opens it from ``traj``; later calls pass the first ``row`` @@ -791,7 +773,7 @@ def stop(self, traj: Trajectory, episode_id: str | None = None) -> None: """Drop the episode: end its agent, close its env session, forget it.""" self._discard(episode_id or _episode_id_of(traj)) - @remote_function(dispatch="slice", collect="flatten") + @remote_function(dispatch='slice', collect='flatten') def __call__(self, trajectories: list[Trajectory]) -> list[Trajectory]: """Run every trajectory to its end; the results in the input order. @@ -801,9 +783,8 @@ def __call__(self, trajectories: list[Trajectory]) -> list[Trajectory]: collected segment, so the flattened output may hold more rows than inputs. """ if isinstance(trajectories, dict): - raise TypeError( - f"{type(self).__name__}.__call__ expects a List[Trajectory]; wrap a single trajectory as [trajectory]." - ) + raise TypeError(f'{type(self).__name__}.__call__ expects a List[Trajectory]; ' + 'wrap a single trajectory as [trajectory].') trajectories = list(trajectories) if not trajectories: return [] @@ -819,8 +800,8 @@ def run(trajectory: Trajectory) -> list[Trajectory]: return rows except EpisodeError as error: out = dict(trajectory) - out["stop_reason"] = STOP_GENERATION_ERROR - out["error"] = str(error) + out['stop_reason'] = STOP_GENERATION_ERROR + out['error'] = str(error) return [out] workers = min(len(trajectories), self.concurrency or len(trajectories)) @@ -829,7 +810,7 @@ def run(trajectory: Trajectory) -> list[Trajectory]: with ThreadPoolExecutor(max_workers=workers) as pool: return [row for rows in pool.map(run, trajectories) for row in rows] - @remote_function(dispatch="all", collect="none", lazy_collect=False) + @remote_function(dispatch='all', collect='none', lazy_collect=False) def close(self) -> None: """Drop every episode and take the endpoint down; the sampler and env are not owned here.""" with self._lock: @@ -858,8 +839,8 @@ def stream(self, trajectory: Trajectory, *, sampling_params: SamplingParams | No :class:`StreamToolCall` after each turn that dispatched tools; :class:`StreamDone` once at the end, carrying the transcript trajectory. """ - if self.harness is not None or self.sampler is None or not hasattr(self.sampler, "sample_stream"): - raise ValueError("MultiTurnRollout.stream requires a local sampler exposing sample_stream and no harness.") + if self.harness is not None or self.sampler is None or not hasattr(self.sampler, 'sample_stream'): + raise ValueError('MultiTurnRollout.stream requires a local sampler exposing sample_stream and no harness.') params = sampling_params if sampling_params is not None else self.sampling_params episode_id = uuid.uuid4().hex tool_manager = self.tool_manager @@ -875,29 +856,26 @@ def stream(self, trajectory: Trajectory, *, sampling_params: SamplingParams | No # ------------------------------------------------------------------ episode - def _step( - self, traj: Trajectory, episode_id: str | None, session_wait: float | None = None - ) -> tuple[list, RolloutStatus]: + def _step(self, traj: Trajectory, episode_id: str | None, + session_wait: Optional[float] = None) -> tuple[list, RolloutStatus]: episode_id = episode_id or _episode_id_of(traj) if not episode_id: - raise ValueError("step needs an episode id: pass episode_id= or set user_data.episode_id.") + raise ValueError('step needs an episode id: pass episode_id= or set user_data.episode_id.') self._release_idle() with self._lock: ep = self._episodes.get(episode_id) opening = ep is None if opening: - if "turns" in traj: + if 'turns' in traj: # A view an earlier step returned: the episode it names is gone. - raise EpisodeError( - f"episode {episode_id!r} is not held by this rollout (stopped, idle " - "past episode_idle_timeout, or its replica restarted)." - ) + raise EpisodeError(f'episode {episode_id!r} is not held by this rollout (stopped, idle ' + 'past episode_idle_timeout, or its replica restarted).') ep = _Episode(episode_id, dict(traj), self._episode_params(traj)) self._episodes[episode_id] = ep - elif "turns" not in traj: - raise ValueError(f"episode {episode_id!r} is already running; every episode needs its own id.") + elif 'turns' not in traj: + raise ValueError(f'episode {episode_id!r} is already running; every episode needs its own id.') ep.busy = True - _record_dispatch_probe("step_entry", episode_id, opening=opening) + _record_dispatch_probe('step_entry', episode_id, opening=opening) try: if opening: if self._open(ep, session_wait): @@ -915,10 +893,10 @@ def _step( ep.busy = False ep.touched = time.monotonic() - def _open(self, ep: _Episode, session_wait: float | None = None) -> bool: + def _open(self, ep: _Episode, session_wait: Optional[float] = None) -> bool: """Open the episode's env session and first turn. Returns True only on a no-slot sentinel.""" if self.env is not None: - _record_dispatch_probe("reset_start", ep.episode_id) + _record_dispatch_probe('reset_start', ep.episode_id) try: result = self.env.reset(ep.episode_id, ep.trajectory, wait=session_wait) except TimeoutError as exc: @@ -927,8 +905,8 @@ def _open(self, ep: _Episode, session_wait: float | None = None) -> bool: # the whole batch instead of recording one generation_error row. Discard the registration # (no session opened) and surface it as an episode failure, preserving the real cause. self._discard(ep.episode_id) - raise EpisodeError(f"episode {ep.episode_id!r} could not open an env session: {exc}") from exc - _record_dispatch_probe("reset_returned", ep.episode_id, discarded=ep.discarded) + raise EpisodeError(f'episode {ep.episode_id!r} could not open an env session: {exc}') from exc + _record_dispatch_probe('reset_returned', ep.episode_id, discarded=ep.discarded) if isinstance(result, NoSlot): # The pool is full and this call was asked not to wait. Drop the registration we just # made (no session was opened, so there is nothing to close) and let _step report it. @@ -945,24 +923,22 @@ def _open(self, ep: _Episode, session_wait: float | None = None) -> bool: try: self.env.close(ep.episode_id) except Exception: # noqa - logger.warning( - f"closing the env session opened for discarded episode {ep.episode_id!r} failed.", exc_info=True - ) - raise EpisodeError( - f"episode {ep.episode_id!r} was discarded while its env session was waiting to open." - ) + logger.warning(f'closing the env session opened for discarded episode ' + f'{ep.episode_id!r} failed.', exc_info=True) + raise EpisodeError(f'episode {ep.episode_id!r} was discarded while its env session was ' + 'waiting to open.') ep.env_open = True ep.trajectory = self._with_observation(ep.trajectory, result) if self.harness is not None: self._start_agent(ep) - _record_dispatch_probe("agent_started", ep.episode_id) + _record_dispatch_probe('agent_started', ep.episode_id) return False ep.tool_manager = self._episode_tools(ep.episode_id) ep.ledger = self._new_ledger(ep.episode_id) # A trajectory that named no tools advertises the manager's, so the prompt # lists what can actually be dispatched. opening_tools = None - if "tools" not in ep.trajectory and ep.tool_manager is not None: + if 'tools' not in ep.trajectory and ep.tool_manager is not None: opening_tools = list(ep.tool_manager.tool_infos() or []) ep.ledger.open(ep.trajectory, tools=opening_tools) ep.budget = self.max_turns @@ -976,15 +952,10 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: coded training rows sharing one identity and one outcome. """ traj = ep.ledger.merge( - ep.trajectory, - turns=ep.ledger.turns, - stop_reason=ep.stop_reason, - truncated=ep.truncated, - segment_index=len(ep.closed_rows), - **fields, - ) + ep.trajectory, turns=ep.ledger.turns, stop_reason=ep.stop_reason, truncated=ep.truncated, + segment_index=len(ep.closed_rows), **fields) if ep.error is not None: - traj["error"] = ep.error + traj['error'] = ep.error episode_end = None if self.on_episode_end is not None: episode_end = self.on_episode_end(traj, self.env, ep.episode_id) @@ -1031,7 +1002,7 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: rewards["check"] = check_score traj["rewards"] = rewards if episode_end is not None: - traj["episode_end"] = episode_end + traj['episode_end'] = episode_end for row in ep.closed_rows: # The frozen rows carry the episode's env reward too: the reward keys belong to # the episode, and every row of it carries the same ones. @@ -1045,19 +1016,18 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: _dump_rollout_rows(ep.episode_id, rows) extra = { key: traj[key] - for key in ("stuck_stop", "tool_stop", "followups", "segments", "agent_exit_code", "error") - if key in traj + for key in ('stuck_stop', 'tool_stop', 'followups', 'segments', 'agent_exit_code', 'error') if key in traj } if isinstance(episode_end, dict): extra.update(episode_end) elif episode_end is not None: - extra["episode_end"] = episode_end + extra['episode_end'] = episode_end prompt_tokens = response_tokens = 0 coded = False row_lengths: list = [] for row in rows: - input_ids = row.get("input_ids") or [] - response = row.get("response_token_ids") or [] + input_ids = row.get('input_ids') or [] + response = row.get('response_token_ids') or [] coded = coded or bool(input_ids) prompt_tokens += len(input_ids) - len(response) response_tokens += len(response) @@ -1066,12 +1036,12 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: # The per-row lengths ride the status so the driver can hand each delivered row its # own facts: the episode totals would repeat on every row and weigh the batch's # metrics by its row count. - extra["row_token_lengths"] = row_lengths + extra['row_token_lengths'] = row_lengths sample = RolloutStatus( episode_id=ep.episode_id, # The episode's turns, not the last segment's: every row carries its own segment's # banked turns, and the episode is the unit that ran. - turns=sum(int(row.get("turns") or 0) for row in rows), + turns=sum(int(row.get('turns') or 0) for row in rows), done=True, stop_reason=ep.stop_reason, truncated=bool(ep.truncated), @@ -1085,19 +1055,18 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: def _continue(self, ep: _Episode) -> tuple[list, RolloutStatus]: """The episode goes on: return its message view as the one row of an unfinished step.""" return [self._view(ep)], RolloutStatus( - episode_id=ep.episode_id, turns=ep.ledger.turns, stop_reason=ep.stop_reason - ) + episode_id=ep.episode_id, turns=ep.ledger.turns, stop_reason=ep.stop_reason) def _view(self, ep: _Episode) -> Trajectory: view = dict(ep.trajectory) if ep.ledger is not None: - view["messages"] = ep.ledger.messages - view["tools"] = ep.ledger.tools - view["turns"] = ep.ledger.turns if ep.ledger is not None else 0 - view["followups"] = ep.followups + view['messages'] = ep.ledger.messages + view['tools'] = ep.ledger.tools + view['turns'] = ep.ledger.turns if ep.ledger is not None else 0 + view['followups'] = ep.followups return view - def _discard(self, episode_id: str | None) -> None: + def _discard(self, episode_id: Optional[str]) -> None: """Forget the episode: fail its queued requests, end its agent and env session.""" if not episode_id: return @@ -1120,18 +1089,17 @@ def _discard(self, episode_id: str | None) -> None: # close costs nothing and covers the window the flag cannot. self.env.close(episode_id) except Exception: # noqa - logger.warning(f"closing the env session of episode {episode_id!r} failed.", exc_info=True) + logger.warning(f'closing the env session of episode {episode_id!r} failed.', exc_info=True) def _release_idle(self) -> None: now = time.monotonic() with self._lock: idle = [ - episode_id - for episode_id, ep in self._episodes.items() + episode_id for episode_id, ep in self._episodes.items() if not ep.busy and now - ep.touched > self.episode_idle_timeout ] for episode_id in idle: - logger.warning(f"releasing episode {episode_id!r}: no step for over {self.episode_idle_timeout:.0f}s.") + logger.warning(f'releasing episode {episode_id!r}: no step for over {self.episode_idle_timeout:.0f}s.') self._discard(episode_id) # ------------------------------------------------------------------ helpers @@ -1141,20 +1109,21 @@ def _params(self, params: SamplingParams) -> SamplingParams: if params.num_samples != 1: # n>1 would fork the conversation at turn 1, and a forked trajectory has no # defined continuation: run the trajectory several times instead. - raise ValueError(f"MultiTurnRollout supports num_samples=1 only, got {params.num_samples}") + raise ValueError(f'MultiTurnRollout supports num_samples=1 only, got {params.num_samples}') if self.template is not None and not params.logprobs: params = replace(params, logprobs=1) return params def _episode_params(self, traj: Trajectory) -> SamplingParams: - override = user_data_get(traj.get("user_data"), "sampling_params") - params = self.sampling_params if not override else self._params(replace(self.sampling_params, **dict(override))) + override = user_data_get(traj.get('user_data'), 'sampling_params') + params = (self.sampling_params if not override + else self._params(replace(self.sampling_params, **dict(override)))) # defect52b: --seed reaches the rollout half too. Derive a per-request seed from the episode's # stable (group_key, sample_index) identity so a group's num_generations samples differ -- a # constant seed would collapse them to one identical trajectory and zero the group's advantage. # An explicit user_data seed override wins; an episode without a stable identity (the display # stream, a bare __call__) stays unseeded. - if self._base_seed is not None and not (override and "seed" in dict(override)): + if self._base_seed is not None and not (override and 'seed' in dict(override)): derived = self._derive_seed(traj) if derived is not None: params = replace(params, seed=derived) @@ -1163,13 +1132,12 @@ def _episode_params(self, traj: Trajectory) -> SamplingParams: def _derive_seed(self, traj: Trajectory) -> int | None: """A per-(group, sample) seed: crc32 of the identity disperses without linear collisions.""" import zlib - - group_key = traj.get("group_key") - sample_index = traj.get("sample_index") + group_key = traj.get('group_key') + sample_index = traj.get('sample_index') if group_key is None or sample_index is None: return None try: - identity = f"{int(group_key)}:{int(sample_index)}".encode() + identity = f'{int(group_key)}:{int(sample_index)}'.encode() except (TypeError, ValueError): return None return (self._base_seed + zlib.crc32(identity)) & 0x7FFFFFFF @@ -1179,20 +1147,19 @@ def _new_ledger(self, label: str): if self.template is None: return MessageLedger(label=label, max_tokens=self.max_trajectory_tokens) return TurnLedger( - self.template, label=label, max_tokens=self.max_trajectory_tokens, backend=self._template_backend - ) + self.template, label=label, max_tokens=self.max_trajectory_tokens, backend=self._template_backend) @staticmethod def _with_observation(trajectory: Trajectory, result: Any) -> Trajectory: """The opening, with the env's first observation appended as a user message.""" - observation = getattr(result, "observation", None) + observation = getattr(result, 'observation', None) if not observation: return trajectory trajectory = dict(trajectory) - trajectory["messages"] = list(trajectory.get("messages") or []) + [{"role": "user", "content": observation}] + trajectory['messages'] = list(trajectory.get('messages') or []) + [{'role': 'user', 'content': observation}] return trajectory - def _episode_tools(self, episode_id: str) -> ToolManager | None: + def _episode_tools(self, episode_id: str) -> Optional[ToolManager]: """The shared tools plus, with an env, the env's tools bound to this episode's session.""" manager = self.tool_manager.copy() if self.tool_manager is not None else None if self.env is None: @@ -1214,19 +1181,17 @@ def _generate(self, ep: _Episode, ledger, params: SamplingParams) -> SampledSequ state = ledger.state if ledger.state is not None else ledger.input_feature seq = self.response_callback(self._view(ep), state, params) else: - use_state = ledger.state is not None and getattr(type(self.sampler), "accepts_rollout_state", False) + use_state = ledger.state is not None and getattr(type(self.sampler), 'accepts_rollout_state', False) adapter_kwargs = dict(self._adapter_kwargs) if ep.adapter_path is not None: - adapter_kwargs["adapter_path"] = ep.adapter_path - responses = self.sampler.sample( - [ledger.state if use_state else ledger.input_feature], - sampling_params=params, - session_id=ep.episode_id, - **adapter_kwargs, - ) + adapter_kwargs['adapter_path'] = ep.adapter_path + responses = self.sampler.sample([ledger.state if use_state else ledger.input_feature], + sampling_params=params, + session_id=ep.episode_id, + **adapter_kwargs) seq = _single_sequence(responses) if not isinstance(seq, SampledSequence): - raise TypeError(f"expected SampledSequence, got {type(seq).__name__}") + raise TypeError(f'expected SampledSequence, got {type(seq).__name__}') return seq @staticmethod @@ -1236,34 +1201,35 @@ def _run_tools(tool_manager: ToolManager, tool_calls: list[dict[str, Any]]) -> l A manager that answers with fewer results than calls leaves the rest empty rather than shifting them onto the wrong call. """ - if hasattr(tool_manager, "call_many"): + if hasattr(tool_manager, 'call_many'): contents = tool_manager.call_many(tool_calls) else: contents = [tool_manager(tc) for tc in tool_calls] - obs = [""] * len(tool_calls) - for i, content in enumerate(contents[: len(tool_calls)]): - obs[i] = "" if content is None else str(content) + obs = [''] * len(tool_calls) + for i, content in enumerate(contents[:len(tool_calls)]): + obs[i] = '' if content is None else str(content) return obs - def _begin_tool_effect(self, ep: _Episode, tool_calls: list[dict[str, Any]]) -> tuple[str | None, list[str] | None]: + def _begin_tool_effect(self, ep: _Episode, + tool_calls: list[dict[str, Any]]) -> tuple[Optional[str], Optional[list[str]]]: if self.resume_store is None or not ep.state_key: return None, None - calls = json.dumps(tool_calls, ensure_ascii=False, sort_keys=True, separators=(",", ":")) - digest = hashlib.sha256(calls.encode("utf-8")).hexdigest()[:20] - effect_key = f"{ep.state_key}/effect/{ep.spent}/{digest}" - completed = self.resume_store.begin_effect(effect_key, {"calls": tool_calls}) + calls = json.dumps(tool_calls, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + digest = hashlib.sha256(calls.encode('utf-8')).hexdigest()[:20] + effect_key = f'{ep.state_key}/effect/{ep.spent}/{digest}' + completed = self.resume_store.begin_effect(effect_key, {'calls': tool_calls}) if completed is None: return effect_key, None - return effect_key, list(completed.get("observations") or ()) + return effect_key, list(completed.get('observations') or ()) - def _commit_tool_effect(self, ep: _Episode, effect_key: str | None, observations: list[str]) -> None: + def _commit_tool_effect(self, ep: _Episode, effect_key: Optional[str], observations: list[str]) -> None: if effect_key is None or self.resume_store is None: return ep.completed_effects.add(effect_key) # The checkpoint includes both the appended observation and the effect key. # Only after it is durable may the result record make crash recovery safe. self._checkpoint_episode(ep, allow_busy=True) - self.resume_store.finish_effect(effect_key, {"observations": observations}) + self.resume_store.finish_effect(effect_key, {'observations': observations}) # ---------------------------------------------------------------- tool loop @@ -1286,13 +1252,13 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: return self._finish_tool_episode(ep) params = ledger.capped_turn_params(params) if params is None: - raise EpisodeError(f"episode {ep.episode_id!r}: the prompt leaves no room for a generated token.") + raise EpisodeError(f'episode {ep.episode_id!r}: the prompt leaves no room for a generated token.') try: seq = self._generate(ep, ledger, params) except APIGenerationError as error: if not ledger.turns: - raise EpisodeError(f"episode {ep.episode_id!r}: the first generation failed: {error}") from error + raise EpisodeError(f'episode {ep.episode_id!r}: the first generation failed: {error}') from error ep.stop_reason = STOP_GENERATION_ERROR ep.error = str(error) ep.truncated = True @@ -1303,22 +1269,22 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: msgs = ledger.messages last_msg = msgs[-1] if msgs else None - tool_calls = last_msg.get("tool_calls") if isinstance(last_msg, dict) else None + tool_calls = last_msg.get('tool_calls') if isinstance(last_msg, dict) else None if not tool_calls: - tool_calls = ledger.parse_tool_call(seq.decoded or "") + tool_calls = ledger.parse_tool_call(seq.decoded or '') if ep.followups: # Tools are withdrawn once a follow-up was appended: those stages write text # about the state as it is, and a code block in a reply parses as a call. tool_calls = None if isinstance(last_msg, dict): message = dict(last_msg) - message["content"] = ledger.decode_tokens(seq) - message.pop("tool_calls", None) + message['content'] = ledger.decode_tokens(seq) + message.pop('tool_calls', None) ledger.replace_last_message(message) # A reply cut off at max_tokens is truncated in exactly the sense the flag names; # tool calls it happens to contain are not dispatched. - if seq.stop_reason == "length" or ledger.full(): + if seq.stop_reason == 'length' or ledger.full(): ep.truncated = True return self._finish_tool_episode(ep) @@ -1326,13 +1292,11 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: # Markup that did not parse is the model asking for a tool, not declining # one: hand back the parser's reason and let it write the call again. Not # after a follow-up, where a reply that looks like a call is text. - parse_errors = [] if ep.followups else ledger.tool_call_errors(seq.decoded or "") + parse_errors = [] if ep.followups else ledger.tool_call_errors(seq.decoded or '') if parse_errors: if ep.malformed >= self.max_malformed_retries: - raise EpisodeError( - f"episode {ep.episode_id!r}: tool-call markup still malformed after " - f"{ep.malformed} retries: {'; '.join(parse_errors)}" - ) + raise EpisodeError(f'episode {ep.episode_id!r}: tool-call markup still malformed after ' + f'{ep.malformed} retries: {"; ".join(parse_errors)}') ep.malformed += 1 if not ledger.observe([_malformed_tool_message(parse_errors)]): ep.truncated = True @@ -1345,7 +1309,7 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: if ledger.turns >= self.max_turns: # Out of tool turns, not out of episode: the stages that read the end # state can still run on what was built. - ep.tool_stop = "max_turns" + ep.tool_stop = 'max_turns' if self._grant_followup(ep): return self._next_turn(ep) ep.truncated = True @@ -1353,11 +1317,10 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: ep.malformed = 0 if ep.tool_manager is None: - raise ValueError("the model emitted tool_calls but this rollout has no tools (tool_manager= or env=).") + raise ValueError('the model emitted tool_calls but this rollout has no tools (tool_manager= or env=).') effect_key, cached_observations = self._begin_tool_effect(ep, tool_calls) - observations = ( - cached_observations if cached_observations is not None else self._run_tools(ep.tool_manager, tool_calls) - ) + observations = (cached_observations if cached_observations is not None else + self._run_tools(ep.tool_manager, tool_calls)) if self.stop_after_stuck_turns: keys = [_call_key(tc) for tc in tool_calls] all_repeats = bool(keys) and all(k in ep.seen_calls for k in keys) @@ -1372,7 +1335,7 @@ def _tool_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: # are in the trajectory. if self.stop_after_stuck_turns and ep.stuck >= self.stop_after_stuck_turns: ep.stuck_stop = True - ep.tool_stop = "stuck" + ep.tool_stop = 'stuck' self._commit_tool_effect(ep, effect_key, observations) if not overflowed and self._grant_followup(ep): return self._next_turn(ep, checkpoint=False) @@ -1410,12 +1373,11 @@ def _grant_followup(self, ep: _Episode) -> bool: ledger = ep.ledger followup = self.followup_fn( ledger.merge(ep.trajectory, turns=ledger.turns, stop_reason=ep.stop_reason, truncated=ep.truncated), - ep.followups, - ) + ep.followups) if followup is None: return False text, next_params = followup if isinstance(followup, tuple) else (followup, None) - if not ledger.observe([{"role": "user", "content": text}]): + if not ledger.observe([{'role': 'user', 'content': text}]): ep.truncated = True return False # Follow-up stages are answers, so a backend must not see tool schemas. @@ -1446,7 +1408,7 @@ def _start_agent(self, ep: _Episode) -> None: task=self.harness.task(ep.trajectory), base_url=endpoint.base_url, api_key=ep.episode_id, - workspace=self.env.workspace(ep.episode_id) or "", + workspace=self.env.workspace(ep.episode_id) or '', ) ep.deadline = time.monotonic() + self.harness.timeout + _AGENT_GRACE requests = ep.requests @@ -1460,46 +1422,45 @@ def run() -> None: ep.episode_id, command, interpreter="shell", timeout=self.harness.timeout, cap_memory=False ) except BaseException as error: # noqa # reported by the step that reads the exit - ep.exit = (None, f"{type(error).__name__}: {error}") + ep.exit = (None, f'{type(error).__name__}: {error}') finally: requests.put(_AGENT_EXITED) - threading.Thread(target=run, name=f"agent-{ep.episode_id[:8]}", daemon=True).start() + threading.Thread(target=run, name=f'agent-{ep.episode_id[:8]}', daemon=True).start() def _harness_step(self, ep: _Episode) -> tuple[list, RolloutStatus]: """Answer the agent's next request, or end the episode when the program exited.""" wait = max(ep.deadline - time.monotonic(), 0.0) - _record_dispatch_probe("harness_wait", ep.episode_id, wait=wait) + _record_dispatch_probe('harness_wait', ep.episode_id, wait=wait) try: item = ep.requests.get(timeout=wait) except queue.Empty: - _record_dispatch_probe("harness_timeout", ep.episode_id) - raise EpisodeError( - f"episode {ep.episode_id!r}: the agent did not finish within {self.harness.timeout:.0f}s." - ) from None - _record_dispatch_probe("harness_item", ep.episode_id, exited=item is _AGENT_EXITED) + _record_dispatch_probe('harness_timeout', ep.episode_id) + raise EpisodeError(f'episode {ep.episode_id!r}: the agent did not finish within ' + f'{self.harness.timeout:.0f}s.') from None + _record_dispatch_probe('harness_item', ep.episode_id, exited=item is _AGENT_EXITED) if item is _AGENT_EXITED: return self._agent_exited(ep) try: result = self._serve(ep, item) - _record_dispatch_probe("harness_served", ep.episode_id) + _record_dispatch_probe('harness_served', ep.episode_id) return result except BaseException as error: - _record_dispatch_probe("harness_serve_error", ep.episode_id, error=f"{type(error).__name__}: {error}") + _record_dispatch_probe('harness_serve_error', ep.episode_id, + error=f'{type(error).__name__}: {error}') if not item.reply.done(): item.reply.set_exception(error) raise def _agent_exited(self, ep: _Episode) -> tuple[list, RolloutStatus]: - code, output = ep.exit or (None, "") - tail = (output or "")[-_OUTPUT_TAIL:] + code, output = ep.exit or (None, '') + tail = (output or '')[-_OUTPUT_TAIL:] if ep.ledger is None: # Wrong config, a crash before the first call, or a config that overrode the key. - raise EpisodeError( - f"episode {ep.episode_id!r}: the agent exited ({code}) without calling the endpoint:\n{tail}" - ) + raise EpisodeError(f'episode {ep.episode_id!r}: the agent exited ({code}) without calling the ' + f'endpoint:\n{tail}') if code != 0: - raise EpisodeError(f"episode {ep.episode_id!r}: the agent exited with {code}:\n{tail}") + raise EpisodeError(f'episode {ep.episode_id!r}: the agent exited with {code}:\n{tail}') ep.stop_reason = STOP_NO_TOOL return self._finish(ep, segments=ep.segments, agent_exit_code=code) @@ -1509,17 +1470,15 @@ def _open_segment(self, ep: _Episode, request: EndpointRequest): A history the agent rewrote (compacted, dropped a turn) or a tool change admits no append, so the recorded segment is over whatever the rewrite left it at. """ - if self.segment_policy == "collect" and ep.ledger is not None: + if self.segment_policy == 'collect' and ep.ledger is not None: # The written-out segment freezes here: its account never changes again, so it # merges into its own row now (identity on it already, from admission); the # episode's other rows join it when the episode ends. - ep.closed_rows.append( - ep.ledger.merge( - ep.trajectory, turns=ep.ledger.turns, truncated=False, segment_index=len(ep.closed_rows) - ) - ) - ledger = self._new_ledger(f"{ep.episode_id}#{ep.segments}") - ledger.open({"messages": list(request.messages)}, tools=list(request.tools)) + ep.closed_rows.append(ep.ledger.merge( + ep.trajectory, turns=ep.ledger.turns, truncated=False, + segment_index=len(ep.closed_rows))) + ledger = self._new_ledger(f'{ep.episode_id}#{ep.segments}') + ledger.open({'messages': list(request.messages)}, tools=list(request.tools)) return ledger def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutStatus]: @@ -1527,7 +1486,8 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS canonical = [_canonical(message) for message in request.messages] tools_key = json.dumps(request.tools, sort_keys=True, ensure_ascii=False) ledger = ep.ledger - if ep.last_reply is not None and tools_key == ep.tools_key and canonical and canonical == ep.sent[:-1]: + if (ep.last_reply is not None and tools_key == ep.tools_key and canonical + and canonical == ep.sent[:-1]): # The same request a retry re-sends: answer with the reply it never saw, without # sampling, recording or starting a segment (the no-new-content history would # otherwise read as a rewrite and needlessly swap the ledger). @@ -1582,9 +1542,9 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS # Housekeeping traffic the agent program does not expect a generation for: the # harness's reply answers it verbatim, costs no sampling, and rides the account # masked (the pair keeps the conversation prefix aligned, the reply is not trained). - message = noise.get("message") or {"role": "assistant", "content": ""} + message = noise.get('message') or {'role': 'assistant', 'content': ''} if extends: - if not ledger.observe(request.messages[len(ep.sent) :] + [message]): + if not ledger.observe(request.messages[len(ep.sent):] + [message]): return self._end_agent_truncated(ep, request) else: # A compaction or tool change the harness's own filter caught: swap the segment @@ -1618,16 +1578,16 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS capped = None if ledger.turns else ledger.capped_turn_params(params) if capped is None: if ep.ledger is None: - raise EpisodeError(f"episode {ep.episode_id!r}: the prompt leaves no room for a generated token.") + raise EpisodeError(f'episode {ep.episode_id!r}: the prompt leaves no room for a generated token.') # Ends on the last recorded segment (a rewritten history with no room never became one). return self._end_agent_truncated(ep, request) params = capped - prompt_tokens = len(ledger.input_feature.get("input_ids") or []) + prompt_tokens = len(ledger.input_feature.get('input_ids') or []) try: seq = self._generate(ep, ledger, params) except APIGenerationError as error: - raise EpisodeError(f"episode {ep.episode_id!r}: generation failed: {error}") from error + raise EpisodeError(f'episode {ep.episode_id!r}: generation failed: {error}') from error ledger.record(seq) if ledger is not ep.ledger: ep.ledger = ledger @@ -1642,11 +1602,11 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS ep.sent = canonical + [_canonical(message)] ep.tools_key = tools_key ep.last_reply = { - "message": message, - "finish_reason": "tool_calls" if parsed else ("length" if seq.stop_reason == "length" else "stop"), - "usage": { - "prompt_tokens": prompt_tokens, - "completion_tokens": len(seq.tokens or []), + 'message': message, + 'finish_reason': 'tool_calls' if parsed else ('length' if seq.stop_reason == 'length' else 'stop'), + 'usage': { + 'prompt_tokens': prompt_tokens, + 'completion_tokens': len(seq.tokens or []), }, } request.reply.set_result(dict(ep.last_reply)) @@ -1715,7 +1675,7 @@ def _continue_generation( def _end_agent_truncated(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutStatus]: """No room for the request: end on what is recorded (closing the session ends the agent).""" - request.reply.set_exception(RuntimeError(f"episode {ep.episode_id!r} reached its length limit")) + request.reply.set_exception(RuntimeError(f'episode {ep.episode_id!r} reached its length limit')) ep.truncated = True return self._finish(ep, segments=ep.segments) @@ -1732,9 +1692,9 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m # Message-level accounting, but template-aware so a reply's tool-call markup still # parses. The feature stays a {'messages','tools'} dict with no input_ids, so # sample_stream re-encodes the whole trajectory each turn. - ledger = MessageLedger(label="stream", max_tokens=self.max_trajectory_tokens, template=self.template) + ledger = MessageLedger(label='stream', max_tokens=self.max_trajectory_tokens, template=self.template) opening_tools = None - if "tools" not in trajectory and tool_manager is not None: + if 'tools' not in trajectory and tool_manager is not None: opening_tools = list(tool_manager.tool_infos() or []) ledger.open(trajectory, tools=opening_tools) @@ -1746,17 +1706,16 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m pieces: list[str] = [] finish: str | None = None for delta, finish_reason in self.sampler.sample_stream( - ledger.input_feature, params, adapter_path=self.adapter_path - ): + ledger.input_feature, params, adapter_path=self.adapter_path): if delta: pieces.append(delta) yield StreamDelta(delta) if finish_reason is not None: finish = finish_reason - text = "".join(pieces) + text = ''.join(pieces) stop_reason = finish or STOP_NO_TOOL ledger.record(SampledSequence(stop_reason=stop_reason, tokens=[], decoded=text)) - if finish == "length": + if finish == 'length': # Cut off mid-reply: no tool call it was still emitting gets dispatched. truncated = True break @@ -1768,7 +1727,7 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m truncated = True break if tool_manager is None: - raise ValueError("the model emitted tool_calls but stream() has no tools (tool_manager= or env=).") + raise ValueError('the model emitted tool_calls but stream() has no tools (tool_manager= or env=).') observations = self._run_tools(tool_manager, tool_calls) yield StreamToolCall(names=_tool_call_names(tool_calls), observations=observations) ledger.observe(_default_tool_messages(tool_calls, observations)) @@ -1777,16 +1736,6 @@ def _stream_episode(self, trajectory: Trajectory, params: SamplingParams, tool_m __all__ = [ - "EpisodeError", - "MAX_FOLLOWUPS", - "MultiTurnRollout", - "RolloutStatus", - "STOP_GENERATION_ERROR", - "STOP_LENGTH", - "STOP_MAX_TURNS", - "STOP_NO_TOOL", - "StreamDelta", - "StreamDone", - "StreamToolCall", - "is_error_observation", + 'EpisodeError', 'MAX_FOLLOWUPS', 'MultiTurnRollout', 'RolloutStatus', 'STOP_GENERATION_ERROR', 'STOP_LENGTH', + 'STOP_MAX_TURNS', 'STOP_NO_TOOL', 'StreamDelta', 'StreamDone', 'StreamToolCall', 'is_error_observation' ] From 6188e22423ea7fc552cdc3b5f54d56a231db21bd Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 21:44:03 +0800 Subject: [PATCH 13/45] fix(agentic): align resume admission and snapshot transactions --- .../async_rl/streaming_driver.py | 4 +-- src/twinkle_agentic/envs/localenv.py | 24 ++++++--------- tests/twinkle_agentic/test_localenv_resume.py | 21 ++++++++----- .../twinkle_agentic/test_resume_boundaries.py | 30 +++++++++++++++++++ 4 files changed, 55 insertions(+), 24 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 0a4450bbf..b937ec044 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -1043,7 +1043,7 @@ def _lend(self, waited: float) -> None: # ------------------------------------------------------------------ admission def _capacity(self) -> int: - return (self._version - self._base_version + self.max_staleness + 1) * self.sync_interval * self.batch_size + return (self.max_staleness + 1) * self.sync_interval * self.batch_size def _admit(self) -> None: """Open groups within the version window and remaining-batch budget (under the lock).""" @@ -1069,7 +1069,7 @@ def _admit(self) -> None: lookup = getattr(self.checkpoint_manager, 'adapter_path', None) if callable(lookup): adapter_path = lookup(version) - if adapter_path is None: + if version >= 1 and adapter_path is None: raise UnsafeResume( f'checkpoint manager has no adapter path for admitted policy version {version}') binding = GroupPolicyBinding( diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 7328b7dc7..e84973e75 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -150,7 +150,7 @@ def _tree_digest(root: Path) -> Dict[str, Any]: return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: - """Copy one quiescent workspace behind a new atomic generation pointer.""" + """Copy one quiescent workspace, retaining the previous restorable generation.""" session = self._session(episode_id) state = session.state if session.script_inflight: @@ -163,6 +163,8 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: generation = f'{time.time_ns():x}-{uuid.uuid4().hex[:8]}' key_root = self._resume_root / self._state_dir_name(state_key) + existing = [path for path in key_root.iterdir() if path.is_dir()] if key_root.exists() else [] + previous = max(existing, key=lambda path: path.stat().st_mtime_ns, default=None) generation_root = key_root / generation workspace_copy = generation_root / 'workspace' generation_root.mkdir(parents=True, exist_ok=False) @@ -181,29 +183,21 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: manifest_path.write_bytes(manifest_bytes) with open(manifest_path, 'r+b') as stream: os.fsync(stream.fileno()) - head = { - 'generation': generation, - 'manifest_sha256': hashlib.sha256(manifest_bytes).hexdigest(), - } - head_bytes = json.dumps(head, sort_keys=True).encode('utf-8') - pending = key_root / f'.head.{generation}.tmp' - key_root.mkdir(parents=True, exist_ok=True) - with open(pending, 'wb') as stream: - stream.write(head_bytes) - stream.flush() - os.fsync(stream.fileno()) - os.replace(pending, key_root / 'head.json') + manifest_sha256 = hashlib.sha256(manifest_bytes).hexdigest() except BaseException: shutil.rmtree(generation_root, ignore_errors=True) raise + keep = {generation} + if previous is not None: + keep.add(previous.name) for old in key_root.iterdir(): - if old.is_dir() and old.name != generation: + if old.is_dir() and old.name not in keep: shutil.rmtree(old, ignore_errors=True) return { "format": "twinkle.localenv.v1", "state_key": state_key, "generation": generation, - "manifest_sha256": head["manifest_sha256"], + "manifest_sha256": manifest_sha256, "files": len(tree["files"]), "bytes": tree["bytes"], "reward": session.reward, diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index b38ffbedd..a3ae6d97e 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -20,27 +20,34 @@ from twinkle_agentic.envs.resume import UnsafeCheckpoint # noqa: E402 -def test_localenv_workspace_round_trip_uses_a_new_session(tmp_path): +def test_localenv_workspace_round_trip_keeps_previous_generation(tmp_path): source = LocalEnv(root=str(tmp_path)) source.reset("episode-1") source.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "turn-boundary"}) state_key = "run-1/group-0/episode-1/attempt-0" - source.checkpoint_episode("episode-1", state_key) + previous = source.checkpoint_episode("episode-1", state_key) snapshot = source.checkpoint_episode("episode-1", state_key) key_root = source._resume_root / source._state_dir_name(state_key) - assert [path.name for path in key_root.iterdir() if path.is_dir()] == [snapshot["generation"]] + assert {path.name for path in key_root.iterdir() if path.is_dir()} == { + previous["generation"], snapshot["generation"] + } + assert not (key_root / "head.json").exists() source.close("episode-1") restored = LocalEnv(root=str(tmp_path)) - restored.restore_episode("episode-1", state_key, snapshot) + restored.restore_episode("episode-1", state_key, previous) result = restored.step("episode-1", "read_file", {"path": "nested/state.txt"}) assert result.observation == "turn-boundary" - - restored.discard_episode_state(state_key) - assert not restored._resume_root.exists() or not any(restored._resume_root.iterdir()) restored.close("episode-1") + latest = LocalEnv(root=str(tmp_path)) + latest.restore_episode("episode-1", state_key, snapshot) + assert latest.step("episode-1", "read_file", {"path": "nested/state.txt"}).observation == "turn-boundary" + latest.discard_episode_state(state_key) + assert not latest._resume_root.exists() or not any(latest._resume_root.iterdir()) + latest.close("episode-1") + def test_localenv_resume_preserves_scored_zero_reward(tmp_path): source = LocalEnv(root=str(tmp_path)) diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index b2573f19c..ea95cfd73 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -98,6 +98,36 @@ def test_no_fault_durable_and_memory_drivers_are_equivalent(tmp_path): assert durable_batches == memory_batches +def test_capacity_is_a_fixed_inflight_window(): + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=4, + num_generations=2, + max_staleness=2, + sync_interval=3, + ) + initial = driver._capacity() + driver._version = 10 + assert driver._capacity() == initial == 36 + driver.close() + + +def test_initial_base_model_policy_needs_no_adapter(): + manager = _PolicyManager(0, {}) + driver = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + checkpoint_manager=manager, + ) + driver._admit() + assert driver._groups["0"].adapter_path is None + driver.close() + + def test_journal_concurrent_instances_share_one_chain(tmp_path): path = tmp_path / "rollout.jsonl" writers = [DurableJournal(path) for _ in range(4)] From 5324185337bf583f86146dadddafee1e7fd25a14 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 21:58:00 +0800 Subject: [PATCH 14/45] perf(agentic): bound durable journal and snapshot overhead --- .../async_rl/rollout_resume.py | 36 +++- .../async_rl/streaming_driver.py | 155 ++++++++++++------ .../twinkle_agentic/test_resume_boundaries.py | 67 ++++++++ 3 files changed, 205 insertions(+), 53 deletions(-) diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index d86525a1a..7a3359621 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -245,10 +245,44 @@ def _repair_and_scan(self) -> None: self._last_digest = records[-1].digest self._records = records + def _sync_tail(self) -> None: + if not self.path.exists() or self.path.stat().st_size == 0: + self._next_seq = 0 + self._last_digest = _ZERO_DIGEST + return + with open(self.path, "rb") as stream: + stream.seek(0, os.SEEK_END) + cursor = stream.tell() - 2 + while cursor >= 0: + stream.seek(cursor) + if stream.read(1) == b"\n": + break + cursor -= 1 + stream.seek(cursor + 1) + raw = stream.readline() + try: + if not raw.endswith(b"\n"): + raise ValueError("unterminated journal tail") + payload = json.loads(raw.decode("utf-8")) + body = { + "seq": int(payload["seq"]), + "event": payload["event"], + "state_key": payload["state_key"], + "payload": payload["payload"], + "prev": payload["prev"], + } + digest = str(payload["digest"]) + if _record_digest(body) != digest: + raise ValueError("journal tail digest mismatch") + except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise JournalCorrupt(f"{self.path}: corrupt journal tail: {exc}") from exc + self._next_seq = body["seq"] + 1 + self._last_digest = digest + def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | None = None) -> JournalRecord: with self._lock: with _exclusive_file_lock(self.path): - self._repair_and_scan() + self._sync_tail() old_size = self.path.stat().st_size if self.path.exists() else 0 body = { "seq": self._next_seq, diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index b937ec044..638f19673 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -12,10 +12,9 @@ (``rewards.orm`` / ``rewards.baseline``, optionally ``prm_segments``) -- and meet the rows again inside the advantage worker, which receives both. -How far ahead of the trainer the driver runs is bounded by the policy version ``v`` (the checkpoint -manager's sync count): the rows admitted and not dropped never exceed -``(v + max_staleness + 1) * sync_interval * batch_size``. A group older than ``max_staleness`` -versions when it is handed out is dropped. +How far ahead of the trainer the driver runs is bounded by the policy staleness window: the rows +admitted and not yet handed out never exceed ``(max_staleness + 1) * sync_interval * batch_size``. +A group older than ``max_staleness`` versions when it is handed out is dropped. All the waiting happens through completion callbacks: every step / score Future puts itself on one queue when it finishes, and the driver's thread only reads that queue, so its cost does not grow @@ -30,6 +29,7 @@ import time import uuid from collections import deque +from contextlib import contextmanager from dataclasses import dataclass, field, replace from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence @@ -329,6 +329,7 @@ def __init__(self, self.max_no_slot_wait = max_no_slot_wait self._lock = threading.Condition() + self._persistence_lock = threading.Lock() self._events: 'queue.Queue[tuple[Any, ...]]' = queue.Queue() self._ready: deque = deque() self._ready_rows = 0 @@ -517,14 +518,12 @@ def _next_batch(self) -> Optional[tuple]: self._lease_returned = True self._handed += 1 if self.resume_store is not None: - self.resume_store.save_object('leases', lease_id, self._lease) - # The snapshot must point at the lease before the journal makes - # it durable. A crash in between re-delivers this same lease; - # the reverse order could strand the lease object unreferenced. - self._persist_snapshot_locked() - self.resume_store.journal.append( - JournalEvent.BATCH_LEASED, lease_id, - {'batch': batch_index, 'rows': len(trajs), 'object': lease_id}) + self._persist_event_locked( + JournalEvent.BATCH_LEASED, + lease_id, + {'batch': batch_index, 'rows': len(trajs), 'object': lease_id}, + objects=(('leases', lease_id, self._lease),), + ) self._lock.notify_all() self._returned_at = time.monotonic() self._wait_time = self._returned_at - started @@ -585,13 +584,16 @@ def _drop_stale(self) -> None: self._ready = kept def _retire_stale_group(self, group: _Group) -> None: + with self._lock: + self._retire_stale_group_locked(group) + + def _retire_stale_group_locked(self, group: _Group) -> None: """Drop one group atomically after its pinned policy leaves the staleness window.""" self._groups.pop(group.key, None) self._counters['dropped_stale'] += len(group.members) self._counters['dropped_group'] += 1 if self.resume_store is not None: - self._persist_snapshot_locked() - self.resume_store.journal.append( + self._persist_event_locked( JournalEvent.GROUP_DROPPED, group.state_key, {"reason": "stale", "binding": group.binding.to_dict(), "current_version": self._version}, @@ -603,7 +605,9 @@ def _retire_stale_group(self, group: _Group) -> None: episode.counted_inflight = False if episode.role != _BASELINE: self._live -= 1 - self._discard_group_state(group) + if self.resume_store is not None: + with self._durable_io_locked(): + self._discard_group_state(group) @remote_function(execute='first', collect='first', lazy_collect=False) def stats(self) -> Dict[str, Any]: @@ -647,8 +651,8 @@ def _episode_state(self, episode: _Episode) -> Dict[str, Any]: "counted_inflight": episode.counted_inflight, } - def _group_state(self, group: _Group) -> Dict[str, Any]: - return { + def _group_state(self, group: _Group, *, include_episodes: bool = True) -> Dict[str, Any]: + state = { 'key': group.key, 'row': group.row, 'binding': group.binding.to_dict(), @@ -657,10 +661,14 @@ def _group_state(self, group: _Group) -> Dict[str, Any]: 'adapter_path': group.adapter_path, 'attempt': group.attempt, 'source': list(group.source), - 'members': [self._episode_state(episode) for episode in group.members], - 'baselines': [self._episode_state(episode) for episode in group.baselines], 'missing': group.missing, } + if include_episodes: + state.update( + members=[self._episode_state(episode) for episode in group.members], + baselines=[self._episode_state(episode) for episode in group.baselines], + ) + return state def _snapshot(self) -> Dict[str, Any]: return { @@ -675,20 +683,42 @@ def _snapshot(self) -> Dict[str, Any]: 'loader_state': self._loader_state(), 'groups': [self._group_state(group) for group in self._groups.values()], 'ready': [[self._episode_state(episode) for episode in members] for members in self._ready], - 'ready_groups': [self._group_state(members[0].group) for members in self._ready if members], + 'ready_groups': [ + self._group_state(members[0].group, include_episodes=False) for members in self._ready if members + ], 'lease': self._lease, } - def _persist_snapshot_locked(self) -> None: - """Persist the current snapshot at a stable transition while holding ``_lock``. + @contextmanager + def _durable_io_locked(self): + self._persistence_lock.acquire() + self._lock.release() + try: + yield + finally: + self._persistence_lock.release() + self._lock.acquire() - Callers order this write before the matching journal event where a stale - snapshot would otherwise lose an in-memory object. Checkpoint commit is - the exception: its journal record is the transaction point, and restore - uses it to retire a lease even when the following snapshot was torn. - """ + def _persist_snapshot_locked(self) -> None: + """Capture a stable snapshot under ``_lock``, then write it without blocking driver events.""" if self.resume_store is not None: - self.resume_store.save_object('driver', self.run_id, self._snapshot()) + state = self._snapshot() + with self._durable_io_locked(): + self.resume_store.save_object('driver', self.run_id, state) + + def _persist_event_locked( + self, + event: JournalEvent, + state_key: str, + payload: Optional[Dict[str, Any]] = None, + objects: Sequence[tuple[str, str, Any]] = (), + ) -> None: + state = self._snapshot() + with self._durable_io_locked(): + for scope, key, value in objects: + self.resume_store.save_object(scope, key, value) + self.resume_store.save_object('driver', self.run_id, state) + self.resume_store.journal.append(event, state_key, payload) @remote_function(execute='first', collect='first', lazy_collect=False) def state_dict(self) -> Dict[str, Any]: @@ -700,9 +730,10 @@ def state_dict(self) -> Dict[str, Any]: """ with self._lock: state = self._snapshot() - if self.resume_store is not None: - self.resume_store.save_object('driver', self.run_id, state) - return state + if self.resume_store is not None: + with self._durable_io_locked(): + self.resume_store.save_object('driver', self.run_id, state) + return state def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: episode = _Episode( @@ -847,12 +878,16 @@ def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: self._ready = deque() for members in state.get('ready') or (): restored = [] + group = None for item in members: key = str(item.get('group_key')) group = ready_groups.get(key) if group is None: raise UnsafeResume(f'ready episode references unknown group {key!r}') restored.append(self._restore_episode(item, group)) + if group is None: + raise UnsafeResume('ready group has no episodes') + group.members = restored self._ready.append(restored) self._ready_rows = sum(len(episode.deliver) for members in self._ready for episode in members) self._handed = int(state.get('handed') or 0) @@ -912,18 +947,21 @@ def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, An raise UnsafeResume('commit_batch() needs the durable model checkpoint reference') lease_id = str(lease['lease_id']) if self.resume_store is not None: - self.resume_store.journal.append( - JournalEvent.MODEL_CHECKPOINT_COMMITTED, lease_id, - { - 'checkpoint': str(checkpoint_ref), - 'batch': lease['batch'], - 'policy_versions': list(lease.get('policy_versions') or ()), - 'manifest': dict(manifest or {}), - }) - self.resume_store.delete_object('leases', lease_id) + state = self._snapshot() + state['lease'] = None + with self._durable_io_locked(): + self.resume_store.journal.append( + JournalEvent.MODEL_CHECKPOINT_COMMITTED, lease_id, + { + 'checkpoint': str(checkpoint_ref), + 'batch': lease['batch'], + 'policy_versions': list(lease.get('policy_versions') or ()), + 'manifest': dict(manifest or {}), + }) + self.resume_store.delete_object('leases', lease_id) + self.resume_store.save_object('driver', self.run_id, state) self._lease = None self._lease_returned = False - self._persist_snapshot_locked() self._lock.notify_all() return lease_id @@ -1046,6 +1084,10 @@ def _capacity(self) -> int: return (self.max_staleness + 1) * self.sync_interval * self.batch_size def _admit(self) -> None: + with self._lock: + self._admit_locked() + + def _admit_locked(self) -> None: """Open groups within the version window and remaining-batch budget (under the lock).""" remaining_groups = None if self.max_steps is not None and self._handed >= self.max_steps: @@ -1082,11 +1124,12 @@ def _admit(self) -> None: self._start_attempt(group, [copy.deepcopy(row) for _ in range(self.num_generations)]) if self.resume_store is not None: prompt_key = f'{self.run_id}/prompt/{key}' - self.resume_store.save_object('prompts', prompt_key, row) - self._persist_snapshot_locked() - self.resume_store.journal.append( - JournalEvent.PROMPT_ASSIGNED, prompt_key, - {'group_key': key, 'object': prompt_key, 'binding': binding.to_dict()}) + self._persist_event_locked( + JournalEvent.PROMPT_ASSIGNED, + prompt_key, + {'group_key': key, 'object': prompt_key, 'binding': binding.to_dict()}, + objects=(('prompts', prompt_key, row),), + ) def _next_row(self) -> Any: # TODO: rows are drawn here, ahead of training; see state_dict for what a resume skips. @@ -1429,12 +1472,15 @@ def _discard_group_state(self, group: _Group) -> None: logger.warning(f"discarding environment state for {state_key} failed: {exc}") def _accept(self, group: _Group) -> None: + with self._lock: + self._accept_locked(group) + + def _accept_locked(self, group: _Group) -> None: del self._groups[group.key] self._ready.append(list(group.members)) self._ready_rows += sum(len(episode.deliver) for episode in group.members) if self.resume_store is not None: - self._persist_snapshot_locked() - self.resume_store.journal.append( + self._persist_event_locked( JournalEvent.GROUP_READY, group.state_key, { @@ -1444,7 +1490,8 @@ def _accept(self, group: _Group) -> None: "episodes": [episode.episode_id for episode in group.members], }, ) - self._discard_group_state(group) + with self._durable_io_locked(): + self._discard_group_state(group) _record_driver_probe( "group_ready", group.members[0].episode_id if group.members else "", @@ -1453,6 +1500,10 @@ def _accept(self, group: _Group) -> None: ) def _drop_group(self, group: _Group) -> None: + with self._lock: + self._drop_group_locked(group) + + def _drop_group_locked(self, group: _Group) -> None: """Give the group up: its counted rows leave the bound, its unfinished episodes stop (under the lock).""" if self._groups.pop(group.key, None) is None: return @@ -1470,8 +1521,7 @@ def _drop_group(self, group: _Group) -> None: # waiting for its PRM scores, no step in flight; a stepping one is stopped when it returns self.rollout.stop(episode.traj, episode_id=episode.episode_id) if self.resume_store is not None: - self._persist_snapshot_locked() - self.resume_store.journal.append( + self._persist_event_locked( JournalEvent.GROUP_DROPPED, group.state_key, { @@ -1480,7 +1530,8 @@ def _drop_group(self, group: _Group) -> None: "current_version": self._version, }, ) - self._discard_group_state(group) + with self._durable_io_locked(): + self._discard_group_state(group) #: Placeholder for a score whose Future has not completed yet. diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index ea95cfd73..a553d11cc 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -1,5 +1,6 @@ import errno import os +import threading import time from concurrent.futures import ThreadPoolExecutor @@ -146,6 +147,17 @@ def append_many(writer, writer_index): assert len({record.digest for record in records}) == 80 +def test_journal_normal_append_does_not_rescan_history(tmp_path, monkeypatch): + journal = DurableJournal(tmp_path / "rollout.jsonl") + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/first") + monkeypatch.setattr(journal, "_repair_and_scan", None) + + journal.append(JournalEvent.GROUP_READY, "run/second") + + reloaded = DurableJournal(journal.path) + assert [record.state_key for record in reloaded.records()] == ["run/first", "run/second"] + + def test_journal_fsync_failure_rolls_back_uncertain_append(tmp_path, monkeypatch): path = tmp_path / "rollout.jsonl" journal = DurableJournal(path) @@ -200,6 +212,61 @@ def _ready_driver(tmp_path, run_id): return store, driver +def test_ready_snapshot_does_not_duplicate_episodes(tmp_path): + store, driver = _ready_driver(tmp_path, "run-ready-snapshot") + try: + state = driver.state_dict() + assert "members" not in state["ready_groups"][0] + assert "baselines" not in state["ready_groups"][0] + finally: + driver.close() + + recovered = StreamingDriver( + _prompts(1), + _DoneRollout(), + batch_size=2, + num_generations=2, + max_staleness=0, + max_steps=1, + resume_store=store, + ) + recovered.load_state_dict(state) + assert recovered._ready_rows == 2 + assert recovered._ready[0][0].group.members == recovered._ready[0] + recovered.close() + + +def test_snapshot_disk_io_does_not_hold_driver_lock(tmp_path, monkeypatch): + store = ResumeStore(tmp_path, "run-snapshot-io") + driver = StreamingDriver( + _prompts(1), _DoneRollout(), batch_size=2, num_generations=2, max_steps=1, resume_store=store + ) + writing = threading.Event() + finish_write = threading.Event() + stats_done = threading.Event() + original = store.save_object + + def blocked_save(scope, key, value): + result = original(scope, key, value) + if scope == "driver": + writing.set() + assert finish_write.wait(2) + return result + + monkeypatch.setattr(store, "save_object", blocked_save) + writer = threading.Thread(target=driver.state_dict) + writer.start() + assert writing.wait(1) + observer = threading.Thread(target=lambda: (driver.stats(), stats_done.set())) + observer.start() + assert stats_done.wait(1) + finish_write.set() + writer.join(2) + observer.join(2) + assert not writer.is_alive() + driver.close() + + def test_exactly_once_commit_contract_and_stale_snapshot(tmp_path): store, driver = _ready_driver(tmp_path, "run-lease") try: From 26dc4c6885b44fa9c18d9673611aa0367eca1512 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 22:20:55 +0800 Subject: [PATCH 15/45] fix(agentic): support durable resume across remote actors --- .../rl/async_rl/durable_multi_turn_grpo.py | 70 ++++--------------- src/twinkle/checkpoint_engine/manager.py | 25 ++++++- .../async_rl/rollout_resume.py | 8 ++- src/twinkle_agentic/envs/localenv.py | 2 + src/twinkle_agentic/rollout/multi_turn.py | 9 +-- tests/checkpoint_engine/test_manager_naive.py | 13 ++++ .../test_rollout_resume_store.py | 13 ++++ 7 files changed, 75 insertions(+), 65 deletions(-) diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index bd19ddcc3..8957737e0 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -22,7 +22,6 @@ import os import re import time -from collections.abc import Iterable from pathlib import Path from typing import Any @@ -144,51 +143,13 @@ def score(trajectories): return score -class _PolicyIndex: - """Translate monotonic driver versions to retained adapter directories.""" - - def __init__(self, path: Path): - self.path = path - self._paths: dict[int, str] = {} - self._current_version = 0 - if path.is_file(): - raw = json.loads(path.read_text(encoding="utf-8")) - self._paths = {int(version): str(value) for version, value in raw.items()} - self._current_version = max(self._paths, default=0) - - @property - def latest_version(self) -> int: - return max(self._paths, default=0) - - def version(self) -> int: - return self._current_version - - def adapter_path(self, version: int) -> str | None: - return self._paths.get(int(version)) - - def register(self, version: int, checkpoint: str) -> None: - version = int(version) - checkpoint = str(checkpoint) - if version < 0 or not checkpoint: - raise ValueError("policy registration needs a non-negative version and checkpoint") - self._paths[version] = checkpoint - self._current_version = max(self._current_version, version) - self.path.parent.mkdir(parents=True, exist_ok=True) - atomic_write_bytes( - self.path, - (json.dumps(self._paths, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8"), - ) - - def recover_from_journal(self, records: Iterable[Any]) -> None: - """Recover a commit that became durable before the JSON index write.""" - for record in records: - if record.event != JournalEvent.MODEL_CHECKPOINT_COMMITTED: - continue - manifest = record.payload.get("manifest") or {} - version = manifest.get("policy_version") - checkpoint = record.payload.get("checkpoint") - if version is not None and checkpoint: - self.register(int(version), str(checkpoint)) +def _recover_policies(checkpoint_manager: CheckpointEngineManager, commits: list[Any]) -> None: + for record in commits: + manifest = record.payload.get("manifest") or {} + version = manifest.get("policy_version") + checkpoint = record.payload.get("checkpoint") + if version is not None and checkpoint: + checkpoint_manager.register_adapter_path(int(version), str(checkpoint)) def _recover_history(commits: list[Any]) -> list[dict[str, Any]]: @@ -279,6 +240,7 @@ def main() -> None: device_groups = [ DeviceGroup(name="model", ranks=list(range(MODEL_GPUS)), device_type="GPU"), DeviceGroup(name="sampler", ranks=list(range(MODEL_GPUS, NUM_GPUS)), device_type="GPU"), + DeviceGroup(name="rollout", ranks=1, device_type="CPU"), ] model_mesh = DeviceMesh.from_sizes(world_size=MODEL_GPUS, dp_size=MODEL_GPUS) sampler_mesh = DeviceMesh.from_sizes(world_size=SAMPLER_GPUS, dp_size=SAMPLER_GPUS) @@ -317,15 +279,13 @@ def main() -> None: ckpt_manager = CheckpointEngineManager(model=model, sampler=sampler) store = ResumeStore(RESUME_ROOT, RUN_ID) - policy_index = _PolicyIndex(RESUME_ROOT / "policy-index.json") - policy_index.recover_from_journal(store.journal.records()) - committed_records = [ record for record in store.journal.records() if record.event == JournalEvent.MODEL_CHECKPOINT_COMMITTED ] + _recover_policies(ckpt_manager, committed_records) history = _recover_history(committed_records) elapsed_offset = max((float(row.get("elapsed_s") or 0.0) for row in history), default=0.0) - latest_checkpoint = policy_index.adapter_path(policy_index.latest_version) + latest_checkpoint = ckpt_manager.adapter_path(ckpt_manager.version()) if latest_checkpoint is None: latest_checkpoint = model.save( "policy-0", @@ -333,7 +293,6 @@ def main() -> None: adapter_name=ADAPTER_NAME, save_optimizer=False, ) - policy_index.register(0, latest_checkpoint) optim_step = 0 elif not committed_records: # The initial adapter index survives a crash before the first commit, @@ -361,6 +320,7 @@ def main() -> None: max_trajectory_tokens=4096, followup_fn=_followup, resume_store=store, + remote_group="rollout", ) dataloader = DataLoader( @@ -377,7 +337,7 @@ def main() -> None: num_generations=NUM_GENERATIONS, max_steps=MAX_STEPS, max_staleness=1, - checkpoint_manager=policy_index, + checkpoint_manager=ckpt_manager, orms=[_reward_future(GSM8KAccuracyReward()), _reward_future(_BrevityReward())], orm_names=["accuracy", "brevity"], resume_store=store, @@ -424,7 +384,7 @@ def main() -> None: save_optimizer=True, async_save=False, ) - next_version = policy_index.version() + 1 + next_version = ckpt_manager.version() + 1 log_dict = metrics.calculate() log_dict.update(model.calculate_metric(is_training=True)) step_record = { @@ -445,9 +405,7 @@ def main() -> None: "driver": step_record["driver"], }, ) - policy_index.register(next_version, checkpoint) - - ckpt_manager.sync_weights(merge_and_sync=False) + ckpt_manager.sync_weights(merge_and_sync=False, adapter_path=str(checkpoint)) sampler.reset_prefix_cache() logger.info(f"[durable step {optim_step}/{MAX_STEPS}] {log_dict}") HISTORY_PATH.parent.mkdir(parents=True, exist_ok=True) diff --git a/src/twinkle/checkpoint_engine/manager.py b/src/twinkle/checkpoint_engine/manager.py index b0fe45930..4bab28dbb 100644 --- a/src/twinkle/checkpoint_engine/manager.py +++ b/src/twinkle/checkpoint_engine/manager.py @@ -159,6 +159,7 @@ def __init__( self.last_delta_metrics = None self._sync_lock = threading.RLock() self._version = 0 + self._adapter_paths: Dict[int, str] = {} if not isinstance(channel, str) or not channel: raise ValueError(f'checkpoint channel must be a non-empty string, got {channel!r}.') self.channel = channel @@ -277,10 +278,27 @@ def version(self) -> int: """How many syncs have completed; read without waiting for one in progress.""" return self._version + @remote_function(collect='first', lazy_collect=False) + def adapter_path(self, version: int) -> Optional[str]: + """Resolve a published policy version to its durable checkpoint, or None for the base model.""" + version = int(version) + if version < 0: + raise ValueError(f'policy version must be >= 0, got {version}') + return self._adapter_paths.get(version) if version >= 1 else None + + @remote_function(collect='first', lazy_collect=False) + def register_adapter_path(self, version: int, path: str) -> None: + """Restore one committed policy index before restarting its sampler.""" + version = int(version) + if version < 1 or not path: + raise ValueError('a registered policy needs version >= 1 and a non-empty checkpoint path') + self._adapter_paths[version] = str(path) + self._version = max(self._version, version) + # ── Sync ───────────────────────────────────────────────────────────────── @remote_function(collect='first', lazy_collect=False) - def sync_weights(self, merge_and_sync=True): + def sync_weights(self, merge_and_sync=True, adapter_path: Optional[str] = None): """Push the model's current weights to every sampler replica, then advance the version. Args: @@ -291,7 +309,10 @@ def sync_weights(self, merge_and_sync=True): sampler. On subsequent calls, only the LoRA adapter weights are synced incrementally. Defaults to True. + adapter_path: Durable checkpoint for the newly published version, used to pin resumed groups. """ + if adapter_path is not None and not str(adapter_path): + raise ValueError('adapter_path must be a non-empty checkpoint path') with self._sync_lock: self._merge_and_sync = merge_and_sync if self.sync_backend == 'delta_sharded': @@ -310,6 +331,8 @@ def sync_weights(self, merge_and_sync=True): finally: self.sampler.resume_generation() self._version += 1 + if adapter_path is not None: + self._adapter_paths[self._version] = str(adapter_path) def _wake_sampler(self, tags: List[str]) -> None: if self.sleep_level > 0: diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 7a3359621..b065dcf94 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -335,11 +335,17 @@ class ResumeStore: def __init__(self, root: str | os.PathLike[str], run_id: str): if not run_id: raise ValueError("run_id must not be empty") - self.root = Path(root) + self.root = Path(root).absolute() self.run_id = run_id self.root.mkdir(parents=True, exist_ok=True) self.journal = DurableJournal(self.root / "rollout.jsonl") + def __getstate__(self) -> dict[str, str]: + return {"root": str(self.root), "run_id": self.run_id} + + def __setstate__(self, state: dict[str, str]) -> None: + self.__init__(state["root"], state["run_id"]) + def save_object(self, scope: str, key: str, value: Any) -> str: payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) digest = hashlib.sha256(payload).digest() diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index e84973e75..febb7ebfa 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -149,6 +149,7 @@ def _tree_digest(root: Path) -> Dict[str, Any]: total += len(data) return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} + @remote_function(enable_continous_work=True, sticky_key='episode_id') def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: """Copy one quiescent workspace, retaining the previous restorable generation.""" session = self._session(episode_id) @@ -204,6 +205,7 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: "rewarded": session.rewarded, } + @remote_function(enable_continous_work=True, sticky_key='episode_id') def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any], trajectory=None) -> None: """Allocate a fresh session and rehydrate the snapshot named by ``state``.""" if state.get('format') != 'twinkle.localenv.v1' or state.get('state_key') != state_key: diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 3f85c9fe7..79981b725 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -606,13 +606,6 @@ def __init__( # ---------------------------------------------------------------- durable episode - def bind_resume_store(self, store: ResumeStore) -> None: - """Inject the run store before the first episode starts.""" - with self._lock: - if self._episodes: - raise RuntimeError('bind_resume_store must run before any episode is opened') - self.resume_store = store - def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[str, Any]: if ep.busy and not allow_busy: raise UnsafeResume(f'episode {ep.episode_id!r} is mid-step and cannot be checkpointed') @@ -673,6 +666,7 @@ def _checkpoint_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict self.resume_store.checkpoint_episode(ep.state_key, state) return state + @remote_function(execute='first', collect='first', lazy_collect=False) def restore_episode(self, state: dict[str, Any]) -> str: """Rebuild an episode from a durable state before it is stepped again.""" if state.get('format') != 'twinkle.multi-turn-episode.v1': @@ -736,6 +730,7 @@ def restore_episode(self, state: dict[str, Any]) -> str: self._episodes[episode_id] = ep return episode_id + @remote_function(execute='first', collect='first', lazy_collect=False) def restore_episode_from_store(self, state_key: str) -> str: if self.resume_store is None: raise UnsafeResume('no resume store is bound to this rollout') diff --git a/tests/checkpoint_engine/test_manager_naive.py b/tests/checkpoint_engine/test_manager_naive.py index 1e4142b73..a6859aab7 100644 --- a/tests/checkpoint_engine/test_manager_naive.py +++ b/tests/checkpoint_engine/test_manager_naive.py @@ -91,6 +91,19 @@ def test_local_sync_streams_generator_without_checkpoint_engine(requested_mode): }] +def test_policy_paths_follow_successfully_published_versions(): + manager = CheckpointEngineManager(_Model([('q_proj.weight', 'base')]), _Sampler(), platform='CPU') + assert manager.adapter_path(0) is None + + manager.sync_weights(merge_and_sync=False, adapter_path='/checkpoints/policy-1') + + assert manager.version() == 1 + assert manager.adapter_path(1) == '/checkpoints/policy-1' + manager.register_adapter_path(3, '/checkpoints/policy-3') + assert manager.version() == 3 + assert manager.adapter_path(3) == '/checkpoints/policy-3' + + def test_local_lora_sync_reuses_peft_config_and_sends_only_incremental_weights(): model = _Model(lambda call: ([('q_proj.lora_A', 'adapter')] if call['base_sync_done'] else [('q_proj.weight', 'base')])) diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index d17bf5893..c41dc53a1 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -1,4 +1,5 @@ import json +import pickle import pytest from twinkle_agentic.async_rl.rollout_resume import ( @@ -60,6 +61,18 @@ def test_journal_refuses_a_corrupt_complete_final_commit(tmp_path): DurableJournal(path) +def test_resume_store_pickle_rebuilds_filesystem_handles(tmp_path): + store = ResumeStore(tmp_path, "run") + store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) + store.journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0") + + rebuilt = pickle.loads(pickle.dumps(store)) + + assert rebuilt.root == store.root + assert rebuilt.load_episode("run/episode/0") == {"tokens": [1, 2, 3]} + assert rebuilt.journal.last("run/0").event is JournalEvent.PROMPT_ASSIGNED + + def test_resume_store_checks_object_checksum(tmp_path): store = ResumeStore(tmp_path, "run") store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) From 349d335ea22925d11efd599824e831d11d29a2ca Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 22:33:36 +0800 Subject: [PATCH 16/45] refactor(agentic): reuse durable primitives and remove dead abstractions --- .../rl/async_rl/durable_multi_turn_grpo.py | 49 ++------ .../Agentic/DurableRolloutResume.md" | 25 ++-- src/twinkle/utils/__init__.py | 2 +- src/twinkle/utils/utils.py | 23 ++++ .../async_rl/rollout_resume.py | 115 ++---------------- .../async_rl/streaming_driver.py | 43 +------ src/twinkle_agentic/envs/__init__.py | 5 +- src/twinkle_agentic/envs/base.py | 2 - src/twinkle_agentic/envs/localenv.py | 4 +- src/twinkle_agentic/envs/resume.py | 67 ++-------- src/twinkle_agentic/rollout/multi_turn.py | 10 +- .../twinkle_agentic/test_resume_boundaries.py | 34 +++--- .../test_rollout_resume_store.py | 17 +-- .../test_streaming_driver_resume.py | 54 -------- 14 files changed, 95 insertions(+), 355 deletions(-) diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index 8957737e0..930e5fe3f 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -22,6 +22,7 @@ import os import re import time +from concurrent.futures import Future from pathlib import Path from typing import Any @@ -39,12 +40,13 @@ from twinkle.model import TransformersModel from twinkle.preprocessor.llm import GSM8KProcessor from twinkle.processor import InputProcessor -from twinkle.reward import GSM8KAccuracyReward +from twinkle.reward import GSM8KAccuracyReward, GSM8KBrevityReward from twinkle.reward.base import Reward from twinkle.sampler import vLLMSampler from twinkle.template import Qwen3_5Template from twinkle_agentic.async_rl import StreamingDriver -from twinkle_agentic.async_rl.rollout_resume import JournalEvent, ResumeStore, atomic_write_bytes +from twinkle.utils import atomic_write_bytes +from twinkle_agentic.async_rl.rollout_resume import JournalEvent, ResumeStore from twinkle_agentic.rollout.multi_turn import MultiTurnRollout @@ -99,46 +101,11 @@ def parse_args(): SYSTEM_PROMPT = "You are a careful math assistant. Solve the problem and put only the final answer in \\boxed{}." -class _ImmediateFuture: - """Adapt a synchronous reward function to the driver's future contract.""" - - def __init__(self, value: Any): - self._value = value - - def exception(self) -> None: - return None - - def result(self) -> Any: - return self._value - - def add_done_callback(self, callback) -> None: - callback(self) - - -class _BrevityReward(Reward): - """Small deterministic format reward, aligned with the short-math example.""" - - def __call__(self, trajectories: list[dict[str, Any]], **kwargs) -> list[float]: - rewards = [] - for trajectory in trajectories: - reply = "" - for message in reversed(trajectory.get("messages") or ()): - if message.get("role") == "assistant": - reply = str(message.get("content") or "") - break - has_answer = bool(re.search(r"\\boxed\{[^}]+\}", reply) or re.search(r"####\s*[\-\d,\.]+", reply)) - if not has_answer: - rewards.append(0.0) - elif len(reply) <= 300: - rewards.append(1.0) - else: - rewards.append(max(0.0, 1.0 - (len(reply) - 300) / 3000)) - return rewards - - def _reward_future(reward: Reward): def score(trajectories): - return _ImmediateFuture(reward(trajectories)) + future = Future() + future.set_result(reward(trajectories)) + return future return score @@ -338,7 +305,7 @@ def main() -> None: max_steps=MAX_STEPS, max_staleness=1, checkpoint_manager=ckpt_manager, - orms=[_reward_future(GSM8KAccuracyReward()), _reward_future(_BrevityReward())], + orms=[_reward_future(GSM8KAccuracyReward()), _reward_future(GSM8KBrevityReward())], orm_names=["accuracy", "brevity"], resume_store=store, run_id=RUN_ID, diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index f29e0754d..c29f53e1d 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -36,8 +36,7 @@ binding = GroupPolicyBinding( run、policy version 或 checkpoint generation。当前 binding 校验身份和路径一致性,不对远端 adapter 内容额外计算哈希,因此 artifact 不可变性由 checkpoint 管理层保证。 -新 driver 快照同时写入结构化 `binding` 和旧版扁平字段。读取旧快照时会自动升级; -binding 与扁平字段不一致时拒绝恢复。 +driver 快照只写入结构化 `binding`;缺少 binding 或组身份不匹配时拒绝恢复。 ## 自动持久化边界 @@ -62,7 +61,7 @@ driver = StreamingDriver( rollout, batch_size=8, num_generations=4, - checkpoint_manager=policy_index, + checkpoint_manager=checkpoint_manager, resume_store=store, run_id="gsm8k-durable", ) @@ -101,27 +100,25 @@ checkpoint 且不再交付该 lease。调用方必须先确保模型和 optimize `ResumeStore` 由两层组成: -- `DurableJournal`:带 hash chain 的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 - 文件锁,以及写入失败回滚; +- `DurableJournal`:带单调序号的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 + 文件锁,以及写入失败回滚;完整扫描只在初始化或异常回滚时执行; - object store:保存 prompt、episode、lease 和 driver 快照,读取时校验 SHA-256。 故障边界: - journal 最后一行未写完:仅移除没有终止换行的不完整尾部; -- 任意完整记录损坏或 SHA 校验失败(包括最后一条 commit):拒绝恢复; +- 完整记录无法解码、事件非法或序号不连续:拒绝恢复; - 磁盘写入失败:回滚不确定的 append; - object 文件不完整:拒绝解码; - 旧 lease 已有 commit 记录:恢复时自动退休。 ## 可恢复环境 -环境恢复能力采用独立 `ResumableEnv` protocol,不向所有 `Env` 实现增加空方法: +环境通过布尔能力和三个恢复方法声明 durable 契约,不向所有 `Env` 实现增加空方法: ```python -from twinkle_agentic.envs.resume import EnvResumeCapability - class MyDurableEnv: - resume_capability = EnvResumeCapability.DURABLE_CHECKPOINT + resume_capability = True def checkpoint_episode(self, episode_id, state_key): ... @@ -152,12 +149,12 @@ closed,不等于为任意外部系统提供 exactly-once 执行;要继续该 ## 兼容性 - `resume_store=None`:行为与原有 `StreamingDriver` 相同; -- 一个 `run_id` 只对应一个活跃 driver 写者;journal 文件锁用于保护事件链,不允许多个 driver +- 一个 `run_id` 只对应一个活跃 driver 写者;journal 文件锁用于保护事件顺序,不允许多个 driver 共享同一 run 并分别覆盖 driver/lease 快照; -- 旧 driver 快照:自动从 `version + adapter_path` 升级为 `GroupPolicyBinding`; - 未设置 checkpoint manager:仍可保存组和 lease,但不执行 policy 版本淘汰; -- `ResumableEnv` 从 `twinkle_agentic.envs.resume` 或 `twinkle_agentic.envs` 导入; -- 旧的 `twinkle_agentic.envs.base` 导入路径保持兼容。 +- `ResumeStore` 跨 actor 传递时只序列化 `root` 和 `run_id`,并在目标 actor 内重建文件句柄; + 多 actor 共享恢复状态时,`root` 必须指向它们都可访问的同一持久化目录; +- rollout 和 LocalEnv 的 checkpoint/restore 入口均支持 remote component 调用。 ## 示例与测试 diff --git a/src/twinkle/utils/__init__.py b/src/twinkle/utils/__init__.py index 183bc66e1..d99f02f3a 100644 --- a/src/twinkle/utils/__init__.py +++ b/src/twinkle/utils/__init__.py @@ -17,5 +17,5 @@ split_cp_inputs, stateless_init_process_group, to_device) from .transformers_utils import find_all_linears, find_layers, get_modules_to_not_convert from .unsafe import check_unsafe, trust_remote_code -from .utils import copy_files_by_pattern, deep_getattr, get_runtime_meta, run_sync, seed_from_env +from .utils import atomic_write_bytes, copy_files_by_pattern, deep_getattr, get_runtime_meta, run_sync, seed_from_env from .vision_tools import load_image, load_mm_file diff --git a/src/twinkle/utils/utils.py b/src/twinkle/utils/utils.py index 48494b265..bc4add40c 100644 --- a/src/twinkle/utils/utils.py +++ b/src/twinkle/utils/utils.py @@ -6,10 +6,33 @@ import inspect import os import shutil +import threading from functools import lru_cache +from pathlib import Path from typing import Any, Callable +def atomic_write_bytes(path: Path, data: bytes) -> None: + """Replace ``path`` with complete bytes; the previous file survives failures.""" + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + pending = path.with_name(f'.{path.name}.{os.getpid()}.{threading.get_ident()}.tmp') + try: + with open(pending, 'wb') as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(pending, path) + if os.name != 'nt': + descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + finally: + pending.unlink(missing_ok=True) + + def deep_getattr(obj, attr: str, default=None): attrs = attr.split('.') for a in attrs: diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index b065dcf94..d57971bad 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -22,7 +22,9 @@ import json -_ZERO_DIGEST = "0" * 64 +from twinkle.utils.parallel import PosixFileLock +from twinkle.utils.utils import atomic_write_bytes + _OBJECT_MAGIC = b"RRS1" _PATH_LOCKS: dict[str, threading.Lock] = {} _PATH_LOCKS_GUARD = threading.Lock() @@ -40,28 +42,8 @@ def _exclusive_file_lock(path: Path): lock_path = path.with_name(path.name + ".lock") lock_path.parent.mkdir(parents=True, exist_ok=True) with _thread_path_lock(lock_path): - with open(lock_path, "a+b") as stream: - stream.seek(0, os.SEEK_END) - if stream.tell() == 0: - stream.write(b"\0") - stream.flush() - stream.seek(0) - if os.name == "nt": - import msvcrt - - msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1) - else: - import fcntl - - fcntl.flock(stream.fileno(), fcntl.LOCK_EX) - try: - yield - finally: - stream.seek(0) - if os.name == "nt": - msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) - else: - fcntl.flock(stream.fileno(), fcntl.LOCK_UN) + with PosixFileLock(str(lock_path)): + yield class ResumeError(RuntimeError): @@ -81,7 +63,6 @@ class JournalEvent(str, Enum): TURN_COMMITTED = "TURN_COMMITTED" TOOL_INTENT = "TOOL_INTENT" TOOL_RESULT = "TOOL_RESULT" - SCORE_RESULT = "SCORE_RESULT" GROUP_READY = "GROUP_READY" GROUP_DROPPED = "GROUP_DROPPED" BATCH_LEASED = "BATCH_LEASED" @@ -140,42 +121,6 @@ class JournalRecord: event: JournalEvent state_key: str payload: dict[str, Any] - prev: str - digest: str - - -def _canonical_json(value: Any) -> bytes: - return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") - - -def _record_digest(record: dict[str, Any]) -> str: - return hashlib.sha256(_canonical_json(record)).hexdigest() - - -def _fsync_directory(path: Path) -> None: - """Persist a rename on filesystems that expose directory fsync.""" - if os.name == "nt": - return - descriptor = os.open(path, os.O_RDONLY) - try: - os.fsync(descriptor) - finally: - os.close(descriptor) - - -def atomic_write_bytes(path: Path, data: bytes) -> None: - """Replace ``path`` with complete bytes; the previous file survives failures.""" - path.parent.mkdir(parents=True, exist_ok=True) - pending = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") - try: - with open(pending, "wb") as stream: - stream.write(data) - stream.flush() - os.fsync(stream.fileno()) - os.replace(pending, path) - _fsync_directory(path.parent) - finally: - pending.unlink(missing_ok=True) def _object_name(key: str) -> str: @@ -183,19 +128,13 @@ def _object_name(key: str) -> str: class DurableJournal: - """Append-only, hash-chained JSONL journal with final-line repair. - - A torn final line is the expected result of a process dying after write but - before fsync. It is removed. Damage followed by another complete record is - never guessed at: that would silently resume from a fabricated history. - """ + """Append-only JSONL journal with final-line repair and monotonic sequence numbers.""" def __init__(self, path: str | os.PathLike[str]): self.path = Path(path) self.path.parent.mkdir(parents=True, exist_ok=True) self._lock = threading.Lock() self._next_seq = 0 - self._last_digest = _ZERO_DIGEST self._records: list[JournalRecord] = [] with _exclusive_file_lock(self.path): self._repair_and_scan() @@ -207,7 +146,6 @@ def _repair_and_scan(self) -> None: offset = 0 valid_end = 0 records = [] - prev = _ZERO_DIGEST while offset < len(data): newline = data.find(b"\n", offset) if newline < 0: @@ -216,23 +154,14 @@ def _repair_and_scan(self) -> None: try: payload = json.loads(raw.decode("utf-8")) seq = int(payload["seq"]) - body = { - "seq": seq, - "event": payload["event"], - "state_key": payload["state_key"], - "payload": payload["payload"], - "prev": payload["prev"], - } - digest = str(payload["digest"]) - if seq != len(records) or body["prev"] != prev or _record_digest(body) != digest: - raise ValueError("journal hash chain mismatch") - event = JournalEvent(body["event"]) - records.append(JournalRecord(seq, event, body["state_key"], body["payload"], prev, digest)) + if seq != len(records): + raise ValueError("journal sequence mismatch") + event = JournalEvent(payload["event"]) + records.append(JournalRecord(seq, event, payload["state_key"], payload["payload"])) except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: # A newline proves that a complete record was written. Only a final fragment without # one is repairable; discarding a corrupt complete commit could repeat its optimizer step. raise JournalCorrupt(f"{self.path}: corrupt record at line {len(records) + 1}: {exc}") from exc - prev = records[-1].digest offset = newline + 1 valid_end = offset if valid_end != len(data): @@ -242,13 +171,11 @@ def _repair_and_scan(self) -> None: os.fsync(stream.fileno()) if records: self._next_seq = records[-1].seq + 1 - self._last_digest = records[-1].digest self._records = records def _sync_tail(self) -> None: if not self.path.exists() or self.path.stat().st_size == 0: self._next_seq = 0 - self._last_digest = _ZERO_DIGEST return with open(self.path, "rb") as stream: stream.seek(0, os.SEEK_END) @@ -264,20 +191,9 @@ def _sync_tail(self) -> None: if not raw.endswith(b"\n"): raise ValueError("unterminated journal tail") payload = json.loads(raw.decode("utf-8")) - body = { - "seq": int(payload["seq"]), - "event": payload["event"], - "state_key": payload["state_key"], - "payload": payload["payload"], - "prev": payload["prev"], - } - digest = str(payload["digest"]) - if _record_digest(body) != digest: - raise ValueError("journal tail digest mismatch") + self._next_seq = int(payload["seq"]) + 1 except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise JournalCorrupt(f"{self.path}: corrupt journal tail: {exc}") from exc - self._next_seq = body["seq"] + 1 - self._last_digest = digest def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | None = None) -> JournalRecord: with self._lock: @@ -289,12 +205,8 @@ def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | "event": event.value, "state_key": state_key, "payload": payload or {}, - "prev": self._last_digest, } - digest = _record_digest(body) - line = ( - json.dumps({**body, "digest": digest}, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" - ) + line = json.dumps(body, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" try: with open(self.path, "ab") as stream: stream.write(line) @@ -310,10 +222,9 @@ def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | pass self._repair_and_scan() raise - record = JournalRecord(self._next_seq, event, state_key, payload or {}, self._last_digest, digest) + record = JournalRecord(self._next_seq, event, state_key, payload or {}) self._records.append(record) self._next_seq += 1 - self._last_digest = digest return record def records(self, *, state_key: str | None = None) -> Iterable[JournalRecord]: diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 638f19673..e1cea22ff 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -656,9 +656,6 @@ def _group_state(self, group: _Group, *, include_episodes: bool = True) -> Dict[ 'key': group.key, 'row': group.row, 'binding': group.binding.to_dict(), - # Flat fields keep snapshots readable by earlier draft readers. - 'version': group.version, - 'adapter_path': group.adapter_path, 'attempt': group.attempt, 'source': list(group.source), 'missing': group.missing, @@ -766,45 +763,17 @@ def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: return episode def _restore_group(self, state: Dict[str, Any]) -> _Group: - members = state.get('members') or () - member_version = next( - (int(item.get('version') or 0) for item in members if item.get('version') is not None), 0) - version = int(state.get('version') if state.get('version') is not None else member_version) - adapter_path = state.get('adapter_path') raw_binding = state.get('binding') - if raw_binding is not None: - try: - binding = GroupPolicyBinding.from_dict(raw_binding) - except (TypeError, ValueError) as exc: - raise UnsafeResume(f'invalid group policy binding: {exc}') from exc - if state.get('version') is not None and int(state['version']) != binding.policy_version: - raise UnsafeResume( - f'group binding version {binding.policy_version} disagrees with snapshot version ' - f'{state["version"]}') - if 'adapter_path' in state and state.get('adapter_path') != binding.adapter_path: - raise UnsafeResume('group binding adapter_path disagrees with the flat snapshot field') - version = binding.policy_version - adapter_path = binding.adapter_path - else: - binding = GroupPolicyBinding( - state_key=str(state.get('state_key') or f'{self.run_id}/group/{state.get("key")}'), - policy_version=version, - adapter_path=adapter_path, - ) + if raw_binding is None: + raise UnsafeResume('group snapshot has no policy binding') + try: + binding = GroupPolicyBinding.from_dict(raw_binding) + except (TypeError, ValueError) as exc: + raise UnsafeResume(f'invalid group policy binding: {exc}') from exc expected_state_key = f'{self.run_id}/group/{state.get("key")}' if binding.state_key != expected_state_key: raise UnsafeResume( f'group binding state_key {binding.state_key!r} does not match {expected_state_key!r}') - # A legacy flat snapshot had no binding, so the manager may upgrade its - # missing adapter path. An explicit binding with adapter_path=None - # means the base model and must not be silently rebound to an adapter. - if raw_binding is None and adapter_path is None and self.checkpoint_manager is not None: - lookup = getattr(self.checkpoint_manager, 'adapter_path', None) - if callable(lookup): - adapter_path = lookup(version) - if adapter_path is None: - raise UnsafeResume(f'policy version {version} has no resolvable adapter path') - binding = replace(binding, adapter_path=adapter_path) group = _Group( key=str(state['key']), row=state.get('row'), binding=binding, attempt=int(state.get('attempt') or 0), diff --git a/src/twinkle_agentic/envs/__init__.py b/src/twinkle_agentic/envs/__init__.py index 518974bec..47cb861d5 100644 --- a/src/twinkle_agentic/envs/__init__.py +++ b/src/twinkle_agentic/envs/__init__.py @@ -4,10 +4,9 @@ from .env_tool import EnvTool from .localenv import LocalEnv from .openenv import ClientSession, OpenEnv, OpenEnvClient -from .resume import EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, env_resume_capability +from .resume import UnsafeCheckpoint, UnsupportedEnvResume, supports_durable_resume __all__ = [ 'AgentEnv', 'AgentSandbox', 'ClientSession', 'Env', 'EnvTool', 'LocalEnv', 'NoSlot', 'OpenEnv', 'OpenEnvClient', - 'EnvResumeCapability', 'ResumableEnv', 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', - 'UnsupportedEnvResume', 'env_resume_capability' + 'SessionNotFound', 'StepResult', 'UnsafeCheckpoint', 'UnsupportedEnvResume', 'supports_durable_resume' ] diff --git a/src/twinkle_agentic/envs/base.py b/src/twinkle_agentic/envs/base.py index a0361b3d5..b579cf31e 100644 --- a/src/twinkle_agentic/envs/base.py +++ b/src/twinkle_agentic/envs/base.py @@ -9,8 +9,6 @@ from twinkle.data_format import Trajectory from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger -from .resume import (EnvResumeCapability, ResumableEnv, UnsafeCheckpoint, UnsupportedEnvResume, - env_resume_capability) from .snapshot import list_workspace logger = get_logger() diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index febb7ebfa..1aa3adee1 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -42,7 +42,7 @@ from twinkle.utils import get_logger from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, StepResult, format_command_output, truncate_observation) -from .resume import EnvResumeCapability, UnsafeCheckpoint +from .resume import UnsafeCheckpoint logger = get_logger() @@ -71,7 +71,7 @@ def __init__(self, workspace: str): class LocalEnv(Env): """Run scripts and tool calls on this machine. See the module docstring.""" - resume_capability = EnvResumeCapability.DURABLE_CHECKPOINT + resume_capability = True def __init__(self, root: Optional[str] = None, diff --git a/src/twinkle_agentic/envs/resume.py b/src/twinkle_agentic/envs/resume.py index 835575339..bca860c72 100644 --- a/src/twinkle_agentic/envs/resume.py +++ b/src/twinkle_agentic/envs/resume.py @@ -1,26 +1,8 @@ # Copyright (c) ModelScope Contributors. All rights reserved. -"""Optional durable-resume protocol for execution environments.""" -from __future__ import annotations -from enum import Enum -from typing import Any, Dict, Optional, Protocol, runtime_checkable +"""Optional durable-resume contract for execution environments.""" +from typing import Any -from twinkle.data_format import Trajectory - -__all__ = [ - 'EnvResumeCapability', - 'ResumableEnv', - 'UnsafeCheckpoint', - 'UnsupportedEnvResume', - 'env_resume_capability', -] - - -class EnvResumeCapability(str, Enum): - """How an environment can survive a different Twinkle process.""" - - NONE = 'none' - LIVE_ATTACH = 'live_attach' - DURABLE_CHECKPOINT = 'durable_checkpoint' +__all__ = ['UnsafeCheckpoint', 'UnsupportedEnvResume', 'supports_durable_resume'] class UnsupportedEnvResume(NotImplementedError): @@ -31,45 +13,14 @@ class UnsafeCheckpoint(RuntimeError): """The episode is not at a point where its workspace can be captured.""" -@runtime_checkable -class ResumableEnv(Protocol): - """Structural contract implemented only by environments that opt into resume.""" - - resume_capability: EnvResumeCapability - - def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: - """Capture one quiescent episode under its stable logical identity.""" - - def restore_episode( - self, - episode_id: str, - state_key: str, - state: Dict[str, Any], - trajectory: Optional[Trajectory] = None, - ) -> None: - """Bind a durable snapshot to a newly allocated logical session.""" - - def discard_episode_state(self, state_key: str) -> None: - """Remove durable state after the owning group has been committed.""" - - -def env_resume_capability(env: Any) -> EnvResumeCapability: - """Return an environment's declared capability after structural validation.""" - declared = getattr(env, 'resume_capability', EnvResumeCapability.NONE) - try: - capability = EnvResumeCapability(declared) - except ValueError as exc: - raise UnsupportedEnvResume( - f'{type(env).__name__} declares invalid resume capability {declared!r}' - ) from exc - if capability == EnvResumeCapability.NONE: - return capability +def supports_durable_resume(env: Any) -> bool: + """Return whether an environment implements the durable episode contract.""" + if not getattr(env, 'resume_capability', False): + return False missing = [ name for name in ('checkpoint_episode', 'restore_episode', 'discard_episode_state') if not callable(getattr(env, name, None)) ] if missing: - raise UnsupportedEnvResume( - f'{type(env).__name__} declares {capability.value} but is missing {missing}' - ) - return capability + raise UnsupportedEnvResume(f'{type(env).__name__} declares durable resume but is missing {missing}') + return True diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 79981b725..3037dfd31 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -27,7 +27,7 @@ from twinkle.utils import get_logger from twinkle_agentic.async_rl.rollout_resume import ResumeStore, UnsafeResume from twinkle_agentic.envs.base import NoSlot -from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability +from twinkle_agentic.envs.resume import supports_durable_resume from twinkle_agentic.envs.env_tool import EnvTool from twinkle_agentic.protocol.api_sampler import APIGenerationError from twinkle_agentic.tools.tool_manager import ToolManager @@ -619,8 +619,7 @@ def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[st raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') env_state = None if ep.env_open: - capability = env_resume_capability(self.env) - if capability == EnvResumeCapability.NONE: + if not supports_durable_resume(self.env): raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') env_state = self.env.checkpoint_episode(ep.episode_id, ep.state_key) return { @@ -702,8 +701,7 @@ def restore_episode(self, state: dict[str, Any]) -> str: if ep.env_open: if self.env is None: raise UnsafeResume('checkpoint has an environment state but this rollout has no env') - capability = env_resume_capability(self.env) - if capability == EnvResumeCapability.NONE: + if not supports_durable_resume(self.env): raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') self.env.restore_episode(episode_id, state_key, state['env_state'], ep.trajectory) ep.budget = int(state['budget']) @@ -739,7 +737,7 @@ def restore_episode_from_store(self, state_key: str) -> str: @remote_function(dispatch="all", collect="none", lazy_collect=False) def discard_episode_state(self, state_key: str) -> None: """Release environment snapshots after the driver has persisted the group's terminal state.""" - if self.env is not None and env_resume_capability(self.env) != EnvResumeCapability.NONE: + if self.env is not None and supports_durable_resume(self.env): self.env.discard_episode_state(state_key) # ------------------------------------------------------------------ entries diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index a553d11cc..8ba449655 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -7,16 +7,16 @@ import pytest from twinkle.data_format.sampling import SamplingParams +from twinkle.utils import atomic_write_bytes from twinkle_agentic.async_rl import rollout_resume from twinkle_agentic.async_rl.rollout_resume import ( DurableJournal, JournalEvent, ResumeStore, UnsafeResume, - atomic_write_bytes, ) from twinkle_agentic.async_rl.streaming_driver import StreamingDriver -from twinkle_agentic.envs.resume import EnvResumeCapability, env_resume_capability +from twinkle_agentic.envs.resume import supports_durable_resume from twinkle_agentic.rollout.multi_turn import MultiTurnRollout, RolloutStatus, _Episode @@ -144,7 +144,6 @@ def append_many(writer, writer_index): records = list(reloaded.records()) assert len(records) == 80 assert [record.seq for record in records] == list(range(80)) - assert len({record.digest for record in records}) == 80 def test_journal_normal_append_does_not_rescan_history(tmp_path, monkeypatch): @@ -185,7 +184,7 @@ def interrupted_replace(_source, _target): raise OSError(errno.EINTR, "replace interrupted") with monkeypatch.context() as context: - context.setattr(rollout_resume.os, "replace", interrupted_replace) + context.setattr("twinkle.utils.utils.os.replace", interrupted_replace) with pytest.raises(OSError, match="replace interrupted"): atomic_write_bytes(target, b"new") @@ -313,7 +312,7 @@ def _episode(rollout, state_key="run/group-0/episode-0"): class _NoResumeEnv: - resume_capability = EnvResumeCapability.NONE + resume_capability = False def __init__(self): self.calls = 0 @@ -393,33 +392,30 @@ def test_non_idempotent_tool_is_not_replayed_after_crash(tmp_path): assert tool.calls == 1 -def test_adapter_lifecycle_deleted_path_and_path_reuse_are_explicit(tmp_path): - manager = _PolicyManager(1, {}) +def test_adapter_lifecycle_preserves_explicit_snapshot(tmp_path): driver = StreamingDriver( _prompts(1), _DoneRollout(), batch_size=2, num_generations=2, max_staleness=1, - checkpoint_manager=manager, + run_id="run-policy", ) group_state = { "key": "0", "row": _prompts(1)[0], - "version": 1, - "adapter_path": None, + "binding": { + "state_key": "run-policy/group/0", + "policy_version": 1, + "adapter_path": "/policies/original-policy.adapter", + }, "attempt": 0, "source": [], "members": [], "baselines": [], "missing": 0, } - with pytest.raises(UnsafeResume, match="no resolvable adapter path"): - driver._restore_group(group_state) - - manager._paths[1] = "/policies/reused-policy.adapter" - explicit = dict(group_state, adapter_path="/policies/original-policy.adapter") - restored = driver._restore_group(explicit) + restored = driver._restore_group(group_state) assert restored.adapter_path == "/policies/original-policy.adapter" @@ -427,6 +423,6 @@ def test_openenv_adapters_declare_no_resume_capability(): from twinkle_agentic.envs.agentenv import AgentEnv from twinkle_agentic.envs.openenv import OpenEnv, OpenEnvClient - assert env_resume_capability(AgentEnv) is EnvResumeCapability.NONE - assert env_resume_capability(OpenEnv) is EnvResumeCapability.NONE - assert env_resume_capability(OpenEnvClient) is EnvResumeCapability.NONE + assert not supports_durable_resume(AgentEnv) + assert not supports_durable_resume(OpenEnv) + assert not supports_durable_resume(OpenEnvClient) diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index c41dc53a1..07a180484 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -37,7 +37,7 @@ def test_journal_refuses_damage_before_a_complete_later_record(tmp_path): journal.append(JournalEvent.GROUP_READY, "run/0", {"members": 2}) lines = path.read_text(encoding="utf-8").splitlines() broken = json.loads(lines[0]) - broken["payload"]["row"] = 99 + broken["seq"] = 99 lines[0] = json.dumps(broken, sort_keys=True) path.write_text("\n".join(lines) + "\n", encoding="utf-8") @@ -46,21 +46,6 @@ def test_journal_refuses_damage_before_a_complete_later_record(tmp_path): assert first.seq == 0 -def test_journal_refuses_a_corrupt_complete_final_commit(tmp_path): - path = tmp_path / "rollout.jsonl" - journal = DurableJournal(path) - journal.append(JournalEvent.BATCH_LEASED, "run/batch/0") - journal.append(JournalEvent.MODEL_CHECKPOINT_COMMITTED, "run/batch/0", {"checkpoint": "step-1"}) - lines = path.read_text(encoding="utf-8").splitlines() - commit = json.loads(lines[-1]) - commit["payload"]["checkpoint"] = "corrupted" - lines[-1] = json.dumps(commit, sort_keys=True) - path.write_text("\n".join(lines) + "\n", encoding="utf-8") - - with pytest.raises(JournalCorrupt, match="corrupt record at line 2"): - DurableJournal(path) - - def test_resume_store_pickle_rebuilds_filesystem_handles(tmp_path): store = ResumeStore(tmp_path, "run") store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index f132461cf..c7d51ce89 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -279,35 +279,6 @@ def test_resumed_group_keeps_its_pinned_adapter_after_policy_advances(tmp_path): assert restored.stats()["resumed_groups"] == 1 -def test_flat_group_snapshot_is_upgraded_to_policy_binding(tmp_path): - store = ResumeStore(tmp_path, "run-flat") - driver = StreamingDriver( - _prompts(1), - _DoneRollout(), - batch_size=2, - num_generations=2, - max_staleness=1, - resume_store=store, - ) - state = { - "key": "0", - "row": _prompts(1)[0], - "version": 3, - "adapter_path": "/policies/policy-3.adapter", - "attempt": 0, - "source": [], - "members": [], - "baselines": [], - "missing": 0, - } - group = driver._restore_group(state) - assert group.binding == GroupPolicyBinding( - state_key="run-flat/group/0", - policy_version=3, - adapter_path="/policies/policy-3.adapter", - ) - - def test_invalid_binding_snapshot_fails_closed(tmp_path): driver = StreamingDriver( _prompts(1), @@ -327,31 +298,6 @@ def test_invalid_binding_snapshot_fails_closed(tmp_path): ) -def test_conflicting_binding_and_flat_snapshot_fails_closed(tmp_path): - driver = StreamingDriver( - _prompts(1), - _DoneRollout(), - batch_size=2, - num_generations=2, - resume_store=ResumeStore(tmp_path, "run-conflict"), - ) - with pytest.raises(UnsafeResume, match="disagrees"): - driver._restore_group( - { - "key": "0", - "row": _prompts(1)[0], - "binding": { - "state_key": "run-conflict/group/0", - "policy_version": 1, - "adapter_path": "/policies/one.adapter", - }, - "version": 2, - "adapter_path": "/policies/two.adapter", - "members": [], - } - ) - - def test_explicit_base_model_binding_is_not_rebound_to_an_adapter(tmp_path): manager = _PolicyManager(1, {1: "/policies/reused-policy.adapter"}) driver = StreamingDriver( From fa90fae701bbba2a34b7e1f392fdec12df55c635 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 22:41:33 +0800 Subject: [PATCH 17/45] fix(agentic): release nested driver locks during durable IO --- src/twinkle_agentic/async_rl/streaming_driver.py | 4 ++-- tests/twinkle_agentic/test_resume_boundaries.py | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index e1cea22ff..5776bf123 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -689,12 +689,12 @@ def _snapshot(self) -> Dict[str, Any]: @contextmanager def _durable_io_locked(self): self._persistence_lock.acquire() - self._lock.release() + lock_state = self._lock._release_save() try: yield finally: self._persistence_lock.release() - self._lock.acquire() + self._lock._acquire_restore(lock_state) def _persist_snapshot_locked(self) -> None: """Capture a stable snapshot under ``_lock``, then write it without blocking driver events.""" diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index 8ba449655..5b0140cb4 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -253,7 +253,12 @@ def blocked_save(scope, key, value): return result monkeypatch.setattr(store, "save_object", blocked_save) - writer = threading.Thread(target=driver.state_dict) + + def nested_snapshot(): + with driver._lock: + driver.state_dict() + + writer = threading.Thread(target=nested_snapshot) writer.start() assert writing.wait(1) observer = threading.Thread(target=lambda: (driver.stats(), stats_done.set())) From 1cfbff8ef0354b8e53bbb7a76e6b1abe2ad352ac Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 22:56:44 +0800 Subject: [PATCH 18/45] fix(agentic): preserve legacy admission without resume store --- .../async_rl/streaming_driver.py | 11 +++--- .../twinkle_agentic/test_resume_boundaries.py | 3 +- .../test_streaming_driver_resume.py | 36 +++++++++++++++++++ 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 5776bf123..e1793510c 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -12,9 +12,9 @@ (``rewards.orm`` / ``rewards.baseline``, optionally ``prm_segments``) -- and meet the rows again inside the advantage worker, which receives both. -How far ahead of the trainer the driver runs is bounded by the policy staleness window: the rows -admitted and not yet handed out never exceed ``(max_staleness + 1) * sync_interval * batch_size``. -A group older than ``max_staleness`` versions when it is handed out is dropped. +Without a resume store the original cumulative version bound is unchanged. In durable mode the bound +is a fixed in-flight window of ``(max_staleness + 1) * sync_interval * batch_size`` rows, released when +a batch is handed out. A group older than ``max_staleness`` versions when handed out is dropped. All the waiting happens through completion callbacks: every step / score Future puts itself on one queue when it finishes, and the driver's thread only reads that queue, so its cost does not grow @@ -478,7 +478,8 @@ def _next_batch(self) -> Optional[tuple]: version_spans: List[int] = [] while len(trajs) < self.batch_size and self._ready: ready_group = self._ready.popleft() - self._live -= sum(1 for episode in ready_group if episode.deliver) + if self.resume_store is not None: + self._live -= sum(1 for episode in ready_group if episode.deliver) for episode in ready_group: episode.sample.version_span = self._version - episode.sample.policy_version score = self._score_update(episode) @@ -1050,6 +1051,8 @@ def _lend(self, waited: float) -> None: # ------------------------------------------------------------------ admission def _capacity(self) -> int: + if self.resume_store is None: + return (self._version - self._base_version + self.max_staleness + 1) * self.sync_interval * self.batch_size return (self.max_staleness + 1) * self.sync_interval * self.batch_size def _admit(self) -> None: diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index 5b0140cb4..df8c833ca 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -99,7 +99,7 @@ def test_no_fault_durable_and_memory_drivers_are_equivalent(tmp_path): assert durable_batches == memory_batches -def test_capacity_is_a_fixed_inflight_window(): +def test_capacity_is_a_fixed_inflight_window(tmp_path): driver = StreamingDriver( _prompts(1), _DoneRollout(), @@ -107,6 +107,7 @@ def test_capacity_is_a_fixed_inflight_window(): num_generations=2, max_staleness=2, sync_interval=3, + resume_store=ResumeStore(tmp_path, "run-capacity"), ) initial = driver._capacity() driver._version = 10 diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index c7d51ce89..b78411c16 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -1,5 +1,7 @@ import pickle +import threading import time +from concurrent.futures import Future import pytest @@ -45,6 +47,15 @@ def discard_episode_state(self, state_key): self.discarded.append(state_key) +class _DelayedRollout(_DoneRollout): + def step(self, trajectory, episode_id=None, session_wait=None): + future = Future() + row = dict(trajectory, turns=1) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + threading.Timer(0.02, lambda: future.set_result(([row], sample))).start() + return future + + class _BoundRollout(_DoneRollout): def step(self, trajectory, episode_id=None, session_wait=None): self.calls.append((episode_id, trajectory.get("policy_version"), trajectory.get("adapter_path"))) @@ -94,6 +105,30 @@ def _wait_until(predicate, timeout=2.0): raise AssertionError("condition was not reached before timeout") +def test_default_driver_keeps_fixed_admission_window_across_versions(): + manager = _PolicyManager(0, {version: f"/policies/{version}" for version in range(8)}) + driver = StreamingDriver( + _prompts(8), + _DelayedRollout(), + batch_size=2, + num_generations=2, + max_staleness=1, + max_steps=8, + checkpoint_manager=manager, + ) + try: + for version in range(8): + manager._version = version + batch = driver._next_batch() + assert batch is not None, (version, driver.stats()) + rows, _ = batch + assert len(rows) == 2 + driver.commit_batch() + assert driver.stats()["dropped_group"] == 0 + finally: + driver.close() + + def test_inflight_prompt_and_group_survive_snapshot(tmp_path): store = ResumeStore(tmp_path, "run-inflight") rollout = _BlockingRollout() @@ -464,6 +499,7 @@ def test_delivered_groups_release_the_admission_window(tmp_path): max_staleness=0, max_steps=2, checkpoint_manager=manager, + resume_store=ResumeStore(tmp_path, "run-release-window"), ) try: first, _ = driver._next_batch() From bcaf812e1a941c3fd14feae11471bcc0b53592b8 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 23:07:35 +0800 Subject: [PATCH 19/45] fix(agentic): resume remote episodes without materializing trajectories --- .../async_rl/streaming_driver.py | 4 +-- .../test_streaming_driver_resume.py | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index e1793510c..2b3565d5d 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -817,9 +817,7 @@ def _resume_live_episode(self, episode: _Episode) -> None: state_key = str((episode.submit_traj or {}).get("state_key") or "") if self.resume_store is not None and state_key and self.resume_store.has_object("episodes", state_key): self.rollout.restore_episode_from_store(state_key) - route = dict(episode.traj or episode.submit_traj or {}) - route.setdefault('turns', 0) - self._step(episode, route) + self._step(episode, episode.submit_traj) else: # No turn boundary committed yet: opening the episode again repeats no external tool call. self._step(episode, episode.submit_traj) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index b78411c16..e649d23b3 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -92,6 +92,15 @@ def step(self, trajectory, episode_id=None, session_wait=None): return _BlockingFuture() +class _RestorableRollout(_BlockingRollout): + def __init__(self): + super().__init__() + self.restored = [] + + def restore_episode_from_store(self, state_key): + self.restored.append(state_key) + + def _prompts(count=2): return [{"messages": [{"role": "user", "content": f"prompt-{index}"}]} for index in range(count)] @@ -157,6 +166,30 @@ def test_inflight_prompt_and_group_survive_snapshot(tmp_path): assert restored._groups["0"].binding == driver._groups["0"].binding +def test_restore_does_not_materialize_remote_trajectory(tmp_path): + store = ResumeStore(tmp_path, "run-remote-traj") + source = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, max_staleness=0, resume_store=store + ) + source._admit() + episode = source._groups["0"].members[0] + state_key = episode.submit_traj["state_key"] + store.save_object("episodes", state_key, {"state_key": state_key}) + episode.traj = object() + state = source.state_dict() + source.close() + + rollout = _RestorableRollout() + restored = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, max_staleness=0, resume_store=store + ) + restored.load_state_dict(state) + + assert rollout.restored == [state_key] + assert rollout.calls == [episode.episode_id] + restored.close() + + def test_prompt_assignment_is_persisted_without_manual_state_dict(tmp_path): store = ResumeStore(tmp_path, "run-auto-prompt") source = StreamingDriver( From 59349abd494f87f26f9dc7391e2f30ce013b2bf9 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 23:24:12 +0800 Subject: [PATCH 20/45] fix(agentic): score remote trajectories in scorer workers --- .../rl/async_rl/durable_multi_turn_grpo.py | 9 ++------ .../cookbook/test_durable_multi_turn_grpo.py | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 tests/cookbook/test_durable_multi_turn_grpo.py diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index 930e5fe3f..1bb1a0389 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -22,7 +22,6 @@ import os import re import time -from concurrent.futures import Future from pathlib import Path from typing import Any @@ -42,6 +41,7 @@ from twinkle.processor import InputProcessor from twinkle.reward import GSM8KAccuracyReward, GSM8KBrevityReward from twinkle.reward.base import Reward +from twinkle.reward.worker import FunctionWorker from twinkle.sampler import vLLMSampler from twinkle.template import Qwen3_5Template from twinkle_agentic.async_rl import StreamingDriver @@ -102,12 +102,7 @@ def parse_args(): def _reward_future(reward: Reward): - def score(trajectories): - future = Future() - future.set_result(reward(trajectories)) - return future - - return score + return FunctionWorker(reward) def _recover_policies(checkpoint_manager: CheckpointEngineManager, commits: list[Any]) -> None: diff --git a/tests/cookbook/test_durable_multi_turn_grpo.py b/tests/cookbook/test_durable_multi_turn_grpo.py new file mode 100644 index 000000000..4360796e7 --- /dev/null +++ b/tests/cookbook/test_durable_multi_turn_grpo.py @@ -0,0 +1,21 @@ +import ast +from pathlib import Path + + +class _FunctionWorker: + def __init__(self, fn): + self.fn = fn + + +def test_rewards_use_remote_scorer_workers(): + path = Path(__file__).parents[2] / "cookbook/rl/async_rl/durable_multi_turn_grpo.py" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + helper = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_reward_future") + namespace = {"FunctionWorker": _FunctionWorker, "Reward": object} + exec(compile(ast.Module(body=[helper], type_ignores=[]), str(path), "exec"), namespace) + + reward = object() + scorer = namespace["_reward_future"](reward) + + assert isinstance(scorer, _FunctionWorker) + assert scorer.fn is reward From 83a4ec2947772fc6d70d531c1f32b712a20dd896 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sat, 21 Nov 2026 23:24:12 +0800 Subject: [PATCH 21/45] fix(agentic): keep default admission window bounded --- src/twinkle_agentic/async_rl/streaming_driver.py | 8 ++------ tests/twinkle_agentic/test_streaming_driver_resume.py | 4 ++++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 2b3565d5d..dab28fb4a 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -12,8 +12,7 @@ (``rewards.orm`` / ``rewards.baseline``, optionally ``prm_segments``) -- and meet the rows again inside the advantage worker, which receives both. -Without a resume store the original cumulative version bound is unchanged. In durable mode the bound -is a fixed in-flight window of ``(max_staleness + 1) * sync_interval * batch_size`` rows, released when +The fixed in-flight window of ``(max_staleness + 1) * sync_interval * batch_size`` rows, released when a batch is handed out. A group older than ``max_staleness`` versions when handed out is dropped. All the waiting happens through completion callbacks: every step / score Future puts itself on one @@ -478,8 +477,7 @@ def _next_batch(self) -> Optional[tuple]: version_spans: List[int] = [] while len(trajs) < self.batch_size and self._ready: ready_group = self._ready.popleft() - if self.resume_store is not None: - self._live -= sum(1 for episode in ready_group if episode.deliver) + self._live -= sum(1 for episode in ready_group if episode.deliver) for episode in ready_group: episode.sample.version_span = self._version - episode.sample.policy_version score = self._score_update(episode) @@ -1049,8 +1047,6 @@ def _lend(self, waited: float) -> None: # ------------------------------------------------------------------ admission def _capacity(self) -> int: - if self.resume_store is None: - return (self._version - self._base_version + self.max_staleness + 1) * self.sync_interval * self.batch_size return (self.max_staleness + 1) * self.sync_interval * self.batch_size def _admit(self) -> None: diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index e649d23b3..4e568a58b 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -126,6 +126,10 @@ def test_default_driver_keeps_fixed_admission_window_across_versions(): checkpoint_manager=manager, ) try: + initial_capacity = driver._capacity() + driver._version = 6 + assert driver._capacity() == initial_capacity + driver._version = 0 for version in range(8): manager._version = version batch = driver._next_batch() From 9b401ab527c40ea0671cd7799b94385de98595a4 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 01:16:29 +0800 Subject: [PATCH 22/45] fix(agentic): continue restored remote episodes --- src/twinkle_agentic/async_rl/streaming_driver.py | 4 +++- tests/twinkle_agentic/test_streaming_driver_resume.py | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index dab28fb4a..2742a2327 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -815,7 +815,9 @@ def _resume_live_episode(self, episode: _Episode) -> None: state_key = str((episode.submit_traj or {}).get("state_key") or "") if self.resume_store is not None and state_key and self.resume_store.has_object("episodes", state_key): self.rollout.restore_episode_from_store(state_key) - self._step(episode, episode.submit_traj) + route = dict(episode.submit_traj) + route["turns"] = 0 + self._step(episode, route) else: # No turn boundary committed yet: opening the episode again repeats no external tool call. self._step(episode, episode.submit_traj) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 4e568a58b..e18de54a8 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -96,6 +96,11 @@ class _RestorableRollout(_BlockingRollout): def __init__(self): super().__init__() self.restored = [] + self.routes = [] + + def step(self, trajectory, episode_id=None, session_wait=None): + self.routes.append(trajectory) + return super().step(trajectory, episode_id, session_wait) def restore_episode_from_store(self, state_key): self.restored.append(state_key) @@ -191,6 +196,8 @@ def test_restore_does_not_materialize_remote_trajectory(tmp_path): assert rollout.restored == [state_key] assert rollout.calls == [episode.episode_id] + assert rollout.routes[0]["turns"] == 0 + assert "turns" not in episode.submit_traj restored.close() From 591f43865952fee16c6e30e48fec6fa3fbb31561 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 01:38:18 +0800 Subject: [PATCH 23/45] fix(agentic): republish durable deliveries after restart --- .../async_rl/streaming_driver.py | 34 ++++++++++++- src/twinkle_agentic/rollout/multi_turn.py | 8 +++ .../twinkle_agentic/test_multi_turn_resume.py | 16 ++++++ .../test_streaming_driver_resume.py | 51 +++++++++++++++++++ 4 files changed, 107 insertions(+), 2 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 2742a2327..7d8725528 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -475,6 +475,7 @@ def _next_batch(self) -> Optional[tuple]: samples: List[RolloutStatus] = [] scores: List[Dict[str, Any]] = [] version_spans: List[int] = [] + row_state_keys: List[str] = [] while len(trajs) < self.batch_size and self._ready: ready_group = self._ready.popleft() self._live -= sum(1 for episode in ready_group if episode.deliver) @@ -500,6 +501,7 @@ def _next_batch(self) -> Optional[tuple]: for index, pair in enumerate(lengths)] for row, row_sample in zip(episode.deliver, row_samples, strict=True): trajs.append(row) + row_state_keys.append(str((episode.submit_traj or {}).get("state_key") or "")) samples.append(row_sample) scores.append(score) version_spans.append(row_sample.version_span) @@ -512,6 +514,7 @@ def _next_batch(self) -> Optional[tuple]: 'batch': batch_index, 'policy_versions': list(facts['policy_versions']), 'rows': trajs, + 'row_state_keys': row_state_keys, 'facts': facts, } self._lease_returned = True @@ -781,6 +784,28 @@ def _restore_group(self, state: Dict[str, Any]) -> _Group: group.baselines = [self._restore_episode(item, group) for item in state.get('baselines') or ()] return group + def _restore_deliveries(self) -> None: + restore = getattr(self.rollout, "restore_delivery", None) + if not callable(restore): + return + for members in self._ready: + for episode in members: + state_key = str((episode.submit_traj or {}).get("state_key") or "") + rows = list(restore(state_key)) + if len(rows) != len(episode.deliver): + raise UnsafeResume(f"restored delivery for {state_key!r} has the wrong row count") + episode.deliver = rows + if rows: + episode.traj = rows[0] + if self._lease is not None: + state_keys = self._lease.get("row_state_keys") + if state_keys is None: + raise UnsafeResume("lease snapshot has no row state keys for remote delivery recovery") + rows = [row for state_key in dict.fromkeys(state_keys) for row in restore(state_key)] + if len(rows) != len(state_keys): + raise UnsafeResume("restored lease has the wrong row count") + self._lease["rows"] = rows + def _resume_scores(self, episode: _Episode) -> None: """Reissue only score calls whose result was missing from the snapshot.""" for index, value in enumerate(episode.orm or ()): @@ -897,6 +922,7 @@ def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: if not callable(loader): raise UnsafeResume('snapshot has DataLoader state but the dataloader cannot load it') loader(loader_state) + self._restore_deliveries() for episode in live: self._resume_live_episode(episode) with self._lock: @@ -927,6 +953,8 @@ def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, An 'manifest': dict(manifest or {}), }) self.resume_store.delete_object('leases', lease_id) + for state_key in dict.fromkeys(lease.get('row_state_keys') or ()): + self.resume_store.delete_object('deliveries', state_key) self.resume_store.save_object('driver', self.run_id, state) self._lease = None self._lease_returned = False @@ -1422,7 +1450,7 @@ def _settle(self, group: _Group) -> None: return self._accept(group) - def _discard_group_state(self, group: _Group) -> None: + def _discard_group_state(self, group: _Group, *, deliveries: bool = True) -> None: """Collect terminal episode state after a durable ready/drop snapshot exists.""" if self.resume_store is None: return @@ -1433,6 +1461,8 @@ def _discard_group_state(self, group: _Group) -> None: if not state_key: continue self.resume_store.delete_object("episodes", state_key) + if deliveries: + self.resume_store.delete_object("deliveries", state_key) if callable(discard): try: discard(state_key) @@ -1459,7 +1489,7 @@ def _accept_locked(self, group: _Group) -> None: }, ) with self._durable_io_locked(): - self._discard_group_state(group) + self._discard_group_state(group, deliveries=False) _record_driver_probe( "group_ready", group.members[0].episode_id if group.members else "", diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 3037dfd31..c0780e3ae 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -734,6 +734,12 @@ def restore_episode_from_store(self, state_key: str) -> str: raise UnsafeResume('no resume store is bound to this rollout') return self.restore_episode(self.resume_store.load_episode(state_key)) + @remote_function(execute='first', collect='first', lazy_collect=False, stash=True) + def restore_delivery(self, state_key: str) -> list: + if self.resume_store is None: + raise UnsafeResume('no resume store is bound to this rollout') + return self.resume_store.load_object("deliveries", state_key) + @remote_function(dispatch="all", collect="none", lazy_collect=False) def discard_episode_state(self, state_key: str) -> None: """Release environment snapshots after the driver has persisted the group's terminal state.""" @@ -1006,6 +1012,8 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: row_rewards["check"] = check_score row["rewards"] = row_rewards rows = list(ep.closed_rows) + [traj] + if self.resume_store is not None: + self.resume_store.save_object("deliveries", ep.state_key, rows) _dump_rollout_rows(ep.episode_id, rows) extra = { key: traj[key] diff --git a/tests/twinkle_agentic/test_multi_turn_resume.py b/tests/twinkle_agentic/test_multi_turn_resume.py index 35a07a03b..3fa852c13 100644 --- a/tests/twinkle_agentic/test_multi_turn_resume.py +++ b/tests/twinkle_agentic/test_multi_turn_resume.py @@ -51,6 +51,22 @@ def test_multi_turn_episode_round_trip_from_store(tmp_path): assert again.adapter_path == "/policies/policy-1.adapter" +def test_terminal_rows_are_republished_from_store(tmp_path): + store = ResumeStore(tmp_path, "run") + source = _rollout(store) + episode = _episode(source) + episode.ledger._pif["labels"] = [-100, 3, -100] + episode.ledger._pif["completion_mask"] = [0, 1, 0] + source._episodes[episode.episode_id] = episode + + rows, status = source._finish(episode) + + assert status.done + assert rows[0]["turns"] == 1 + assert store.load_object("deliveries", episode.state_key) == rows + assert _rollout(store).restore_delivery(episode.state_key) == rows + + def test_multi_turn_restore_refuses_effect_without_tool_checkpoint(tmp_path): store = ResumeStore(tmp_path, "run") source = _rollout(store) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index e18de54a8..4a6e165e1 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -64,6 +64,23 @@ def step(self, trajectory, episode_id=None, session_wait=None): return _Future(([row], sample)) +class _DeliveryRollout(_DoneRollout): + def __init__(self, store): + super().__init__() + self.store = store + self.restored = [] + + def step(self, trajectory, episode_id=None, session_wait=None): + row = dict(trajectory, turns=1) + self.store.save_object("deliveries", trajectory["state_key"], [row]) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=True, token_lengths=(1, 1), stop_reason="stop") + return _Future(([object()], sample)) + + def restore_delivery(self, state_key): + self.restored.append(state_key) + return self.store.load_object("deliveries", state_key) + + class _PolicyManager: def __init__(self, version, paths): self._version = version @@ -275,6 +292,40 @@ def test_ready_group_round_trip_and_lease_redelivery(tmp_path): assert stale._lease is None +def test_ready_and_leased_remote_rows_are_republished_on_restore(tmp_path): + store = ResumeStore(tmp_path, "run-remote-delivery") + source = StreamingDriver( + _prompts(1), _DeliveryRollout(store), batch_size=1, num_generations=1, max_staleness=0, + max_steps=1, resume_store=store, + ) + source._start() + _wait_until(lambda: source._ready_rows == 1) + ready_state = source.state_dict() + source.close() + + restored_rollout = _DeliveryRollout(store) + restored = StreamingDriver( + _prompts(1), restored_rollout, batch_size=1, num_generations=1, max_staleness=0, + max_steps=1, resume_store=store, + ) + restored.load_state_dict(ready_state) + rows, _ = restored._next_batch() + assert rows[0]["episode_id"].endswith("member:0") + leased_state = restored.state_dict() + restored.close() + + after_crash_rollout = _DeliveryRollout(store) + after_crash = StreamingDriver( + _prompts(1), after_crash_rollout, batch_size=1, num_generations=1, max_staleness=0, + max_steps=1, resume_store=store, + ) + after_crash.load_state_dict(leased_state) + again_rows, _ = after_crash._next_batch() + assert again_rows == rows + assert after_crash_rollout.restored == [after_crash._lease["row_state_keys"][0]] + after_crash.close() + + def test_ready_group_and_lease_are_persisted_without_manual_state_dict(tmp_path): store = ResumeStore(tmp_path, "run-auto-lease") source = StreamingDriver( From feea99f8ad8282693069efdd7dbce26fb68fdb3f Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 02:43:04 +0800 Subject: [PATCH 24/45] fix(agentic): close remote resume recovery boundaries --- .../Agentic/DurableRolloutResume.md" | 11 ++-- .../async_rl/streaming_driver.py | 52 +++++++++++---- src/twinkle_agentic/envs/localenv.py | 9 ++- src/twinkle_agentic/rollout/multi_turn.py | 41 ++++++++++-- .../twinkle_agentic/test_multi_turn_resume.py | 48 ++++++++++++++ .../test_streaming_driver_resume.py | 64 ++++++++++++++++++- 6 files changed, 196 insertions(+), 29 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index c29f53e1d..a019ca368 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -252,8 +252,9 @@ vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: | 单卡 CaMem 两步 | 两轮 weights/KV sleep-wake 和第二轮 LoRA-only 同步完成,未出现旧版 `aclnnInplaceCopy` 错误 | 该结果只覆盖上述版本组合和单节点双卡,不回溯证明 vLLM/vLLM-Ascend 0.23.0,也不代表 FSDP2 -或多节点已经验证。本地 overlay 的规模基准显示,journal 在 250、500、1000、2000 事件时的平均追加 -延迟约为 1.89、3.53、6.71、13.16ms,确认全量重扫是优先优化项;64MiB LocalEnv workspace 快照约 +或多节点已经验证。早期本地 overlay 的规模基准显示,journal 在 250、500、1000、2000 事件时的平均追加 +延迟约为 1.89、3.53、6.71、13.16ms;该数据来自仍会全量重扫的旧实现,只用于说明当时的优化动机。 +当前正常追加只读取尾部以同步序号,完整扫描仅用于初始化或异常回滚。64MiB LocalEnv workspace 快照约 85ms,在该本地盘上暂不是主要瓶颈。 尚未覆盖: @@ -264,9 +265,9 @@ vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: colocate 路径,新版结果不能替代旧版复测; - 无法 checkpoint 的远端 agent harness; - 所有外部工具协议都具备幂等结果查询; -- 大规模长训练的持久化开销尚未形成独立基准。当前 journal 追加会重扫事件链,driver 在稳定边界 - 保存完整状态,LocalEnv 每轮复制并校验 workspace;后续可分别评估增量扫描、按 episode 分片和 - 增量 workspace 快照,不能用当前端到端墙钟结果替代这些专项评估。 +- 大规模长训练的持久化开销尚未形成独立基准。当前 journal 正常追加只同步尾部,初始化或异常回滚才 + 完整扫描;driver 在稳定边界保存完整状态,LocalEnv 每轮复制并校验 workspace。后续可评估按 episode + 分片和增量 workspace 快照,不能用当前端到端墙钟结果替代这些专项评估。 因此该机制的主要结论是进程重启时保持 GRPO 组语义、事务一致性、固定预算下的有效训练量, 并减少重复工具副作用和重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 7d8725528..b16f6f946 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -177,6 +177,7 @@ class _Episode: #: The trajectory at each segment boundary, aligned with ``prm_turns``. Pending scores must be #: reissued against that boundary rather than against whatever turn is latest after a restart. prm_inputs: list[Any] = field(default_factory=list) + prm_input_keys: list[str] = field(default_factory=list) prm_pending: int = 0 #: The PRM segment the episode waits for before its next step (only with ``on_step``). held: Optional[int] = None @@ -639,6 +640,7 @@ def _episode_state(self, episode: _Episode) -> Dict[str, Any]: "prm": _dump_pending(episode.prm), "prm_turns": list(episode.prm_turns), "prm_inputs": list(episode.prm_inputs), + "prm_input_keys": list(episode.prm_input_keys), "prm_pending": episode.prm_pending, "held": episode.held, "deliver": list(episode.deliver), @@ -751,6 +753,7 @@ def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: episode.prm = _load_pending(state.get("prm")) episode.prm_turns = list(state.get("prm_turns") or ()) episode.prm_inputs = list(state.get("prm_inputs") or ()) + episode.prm_input_keys = list(state.get("prm_input_keys") or ()) episode.prm_pending = int(state.get("prm_pending") or 0) episode.held = state.get("held") episode.deliver = list(state.get("deliver") or ()) @@ -788,15 +791,17 @@ def _restore_deliveries(self) -> None: restore = getattr(self.rollout, "restore_delivery", None) if not callable(restore): return - for members in self._ready: - for episode in members: - state_key = str((episode.submit_traj or {}).get("state_key") or "") - rows = list(restore(state_key)) - if len(rows) != len(episode.deliver): - raise UnsafeResume(f"restored delivery for {state_key!r} has the wrong row count") - episode.deliver = rows - if rows: - episode.traj = rows[0] + episodes = [episode for group in self._groups.values() for episode in group.members + group.baselines + if episode.done] + episodes += [episode for members in self._ready for episode in members] + for episode in episodes: + state_key = str((episode.submit_traj or {}).get("state_key") or "") + rows = list(restore(state_key)) + if len(rows) != len(episode.deliver): + raise UnsafeResume(f"restored delivery for {state_key!r} has the wrong row count") + episode.deliver = rows + if rows: + episode.traj = rows[0] if self._lease is not None: state_keys = self._lease.get("row_state_keys") if state_keys is None: @@ -822,9 +827,23 @@ def _resume_scores(self, episode: _Episode) -> None: raise UnsafeResume( f"episode {episode.episode_id!r} has no durable trajectory for pending PRM segment {segment}" ) + restore = getattr(self.rollout, "restore_segment", None) + if callable(restore): + if segment >= len(episode.prm_input_keys) or not episode.prm_input_keys[segment]: + raise UnsafeResume( + f"episode {episode.episode_id!r} has no durable key for pending PRM segment {segment}" + ) + episode.prm_inputs[segment] = restore(episode.prm_input_keys[segment]) future = self.prms[scorer]([episode.prm_inputs[segment]]) future.add_done_callback( lambda f, episode=episode, key=(segment, scorer): self._events.put(('prm', episode, key, f))) + restore = getattr(self.rollout, "restore_segment", None) + if episode.held is not None and callable(restore): + if episode.held >= len(episode.prm_input_keys) or not episode.prm_input_keys[episode.held]: + raise UnsafeResume(f"episode {episode.episode_id!r} has no durable key for its held segment") + restored = restore(episode.prm_input_keys[episode.held]) + episode.prm_inputs[episode.held] = restored + episode.traj = restored def _resume_live_episode(self, episode: _Episode) -> None: if episode.finished or episode.lost: @@ -833,13 +852,16 @@ def _resume_live_episode(self, episode: _Episode) -> None: if episode.done: return self._counters["resumed_members"] += 1 + state_key = str((episode.submit_traj or {}).get("state_key") or "") + restored = bool(self.resume_store is not None and state_key + and self.resume_store.has_object("episodes", state_key)) + if restored: + self.rollout.restore_episode_from_store(state_key, episode_id=episode.episode_id) if episode.held is not None: # The segment scorer's completion callback owns the next transition. Continuing here would # bypass on_step and could submit a second generation before that decision. return - state_key = str((episode.submit_traj or {}).get("state_key") or "") - if self.resume_store is not None and state_key and self.resume_store.has_object("episodes", state_key): - self.rollout.restore_episode_from_store(state_key) + if restored: route = dict(episode.submit_traj) route["turns"] = 0 self._step(episode, route) @@ -1107,7 +1129,7 @@ def _admit_locked(self) -> None: lookup = getattr(self.checkpoint_manager, 'adapter_path', None) if callable(lookup): adapter_path = lookup(version) - if version >= 1 and adapter_path is None: + if self.resume_store is not None and version >= 1 and adapter_path is None: raise UnsafeResume( f'checkpoint manager has no adapter path for admitted policy version {version}') binding = GroupPolicyBinding( @@ -1266,6 +1288,7 @@ def _score_prm(self, episode: _Episode) -> int: segment = len(episode.prm_turns) episode.prm_turns.append(int(episode.sample.turns)) episode.prm_inputs.append(episode.traj) + episode.prm_input_keys.append(str((episode.sample.extra or {}).get("resume_input_key") or "")) for scorer, prm in enumerate(self.prms): episode.prm[scorer].append(_PENDING) episode.prm_pending += 1 @@ -1461,6 +1484,9 @@ def _discard_group_state(self, group: _Group, *, deliveries: bool = True) -> Non if not state_key: continue self.resume_store.delete_object("episodes", state_key) + for segment_key in episode.prm_input_keys: + if segment_key: + self.resume_store.delete_object("segments", segment_key) if deliveries: self.resume_store.delete_object("deliveries", state_key) if callable(discard): diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 1aa3adee1..1a795e310 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -150,8 +150,9 @@ def _tree_digest(root: Path) -> Dict[str, Any]: return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} @remote_function(enable_continous_work=True, sticky_key='episode_id') - def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: - """Copy one quiescent workspace, retaining the previous restorable generation.""" + def checkpoint_episode(self, episode_id: str, state_key: str, + persisted_generation: Optional[str] = None) -> Dict[str, Any]: + """Copy one quiescent workspace, retaining the generation named by the persisted episode.""" session = self._session(episode_id) state = session.state if session.script_inflight: @@ -189,7 +190,9 @@ def checkpoint_episode(self, episode_id: str, state_key: str) -> Dict[str, Any]: shutil.rmtree(generation_root, ignore_errors=True) raise keep = {generation} - if previous is not None: + if persisted_generation is not None: + keep.add(persisted_generation) + elif previous is not None: keep.add(previous.name) for old in key_root.iterdir(): if old.is_dir() and old.name not in keep: diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index c0780e3ae..d69d2bb26 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -428,6 +428,7 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara #: Under segment_policy='collect': the rows of segments a compaction boundary already #: froze, oldest first; the final segment's row joins them when the episode ends. self.closed_rows: list = [] + self.segment_seq = 0 #: Stable identity supplied by the driver. It is not a random session id. self.state_key = str(trajectory.get('state_key') or '') #: Behavior-policy binding for the whole episode. A resumed group keeps this adapter even @@ -621,7 +622,13 @@ def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[st if ep.env_open: if not supports_durable_resume(self.env): raise UnsafeResume(f'{type(self.env).__name__} declares no durable resume capability') - env_state = self.env.checkpoint_episode(ep.episode_id, ep.state_key) + persisted_generation = None + if self.resume_store is not None and self.resume_store.has_object("episodes", ep.state_key): + persisted = self.resume_store.load_episode(ep.state_key) + persisted_generation = (persisted.get("env_state") or {}).get("generation") + env_state = self.env.checkpoint_episode( + ep.episode_id, ep.state_key, persisted_generation=persisted_generation + ) return { 'format': 'twinkle.multi-turn-episode.v1', 'state_key': ep.state_key, @@ -647,6 +654,7 @@ def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[st 'tools_key': ep.tools_key, 'last_reply': ep.last_reply, 'closed_rows': ep.closed_rows, + 'segment_seq': ep.segment_seq, 'completed_effects': sorted(ep.completed_effects), } @@ -720,6 +728,7 @@ def restore_episode(self, state: dict[str, Any]) -> str: ep.tools_key = state.get('tools_key') ep.last_reply = state.get('last_reply') ep.closed_rows = list(state.get('closed_rows') or ()) + ep.segment_seq = int(state.get('segment_seq') or 0) ep.completed_effects = set(state.get('completed_effects') or ()) ep.tool_manager = self._episode_tools(episode_id) with self._lock: @@ -728,11 +737,14 @@ def restore_episode(self, state: dict[str, Any]) -> str: self._episodes[episode_id] = ep return episode_id - @remote_function(execute='first', collect='first', lazy_collect=False) - def restore_episode_from_store(self, state_key: str) -> str: + @remote_function(enable_continous_work=True, sticky_key='episode_id', lazy_collect=False) + def restore_episode_from_store(self, state_key: str, episode_id: str | None = None) -> str: if self.resume_store is None: raise UnsafeResume('no resume store is bound to this rollout') - return self.restore_episode(self.resume_store.load_episode(state_key)) + state = self.resume_store.load_episode(state_key) + if episode_id is not None and str(state.get('episode_id') or '') != episode_id: + raise UnsafeResume('episode checkpoint identity does not match its sticky routing key') + return self.restore_episode(state) @remote_function(execute='first', collect='first', lazy_collect=False, stash=True) def restore_delivery(self, state_key: str) -> list: @@ -740,6 +752,12 @@ def restore_delivery(self, state_key: str) -> list: raise UnsafeResume('no resume store is bound to this rollout') return self.resume_store.load_object("deliveries", state_key) + @remote_function(execute='first', collect='first', lazy_collect=False, stash=True) + def restore_segment(self, state_key: str) -> dict: + if self.resume_store is None: + raise UnsafeResume('no resume store is bound to this rollout') + return self.resume_store.load_object("segments", state_key) + @remote_function(dispatch="all", collect="none", lazy_collect=False) def discard_episode_state(self, state_key: str) -> None: """Release environment snapshots after the driver has persisted the group's terminal state.""" @@ -1019,6 +1037,7 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: key: traj[key] for key in ('stuck_stop', 'tool_stop', 'followups', 'segments', 'agent_exit_code', 'error') if key in traj } + extra.update(self._persist_segment_input(ep, rows[0])) if isinstance(episode_end, dict): extra.update(episode_end) elif episode_end is not None: @@ -1053,10 +1072,20 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: ) return rows, sample + def _persist_segment_input(self, ep: _Episode, row: Trajectory) -> dict[str, str]: + if self.resume_store is None: + return {} + ep.segment_seq += 1 + state_key = f"{ep.state_key}/segment/{ep.segment_seq}" + self.resume_store.save_object("segments", state_key, row) + return {"resume_input_key": state_key} + def _continue(self, ep: _Episode) -> tuple[list, RolloutStatus]: """The episode goes on: return its message view as the one row of an unfinished step.""" - return [self._view(ep)], RolloutStatus( - episode_id=ep.episode_id, turns=ep.ledger.turns, stop_reason=ep.stop_reason) + row = self._view(ep) + extra = self._persist_segment_input(ep, row) + return [row], RolloutStatus( + episode_id=ep.episode_id, turns=ep.ledger.turns, stop_reason=ep.stop_reason, extra=extra) def _view(self, ep: _Episode) -> Trajectory: view = dict(ep.trajectory) diff --git a/tests/twinkle_agentic/test_multi_turn_resume.py b/tests/twinkle_agentic/test_multi_turn_resume.py index 3fa852c13..db94d6cc2 100644 --- a/tests/twinkle_agentic/test_multi_turn_resume.py +++ b/tests/twinkle_agentic/test_multi_turn_resume.py @@ -1,3 +1,6 @@ +import os +import time + import pytest from twinkle.data_format import SampleResponse @@ -137,6 +140,51 @@ def test_multi_turn_restores_localenv_at_turn_boundary(tmp_path): restored.env.close(episode_id) +def test_localenv_cleanup_retains_the_persisted_generation_across_orphans(tmp_path, monkeypatch): + store = ResumeStore(tmp_path / "resume", "run") + root = tmp_path / "workspace" + episode_id = "episode-env" + state_key = "run/group-0/attempt-0/member/0" + env = LocalEnv(root=str(root)) + env.reset(episode_id) + env.step(episode_id, "write_file", {"path": "state.txt", "content": "stable"}) + source = MultiTurnRollout( + response_callback=lambda *_args: None, template=_Template(), env=env, resume_store=store + ) + episode = _episode(source, state_key) + episode.episode_id = episode_id + episode.trajectory["episode_id"] = episode_id + episode.env_open = True + source._episodes[episode_id] = episode + first = source.checkpoint_episode(episode_id) + + def crash_before_object_commit(*_args): + raise RuntimeError("crash after environment cleanup") + + with monkeypatch.context() as context: + context.setattr(store, "checkpoint_episode", crash_before_object_commit) + with pytest.raises(RuntimeError, match="after environment cleanup"): + source._checkpoint_episode(episode) + key_root = env._resume_root / env._state_dir_name(state_key) + orphan = next(path for path in key_root.iterdir() if path.name != first["env_state"]["generation"]) + future = time.time() + 60 + os.utime(orphan, (future, future)) + with pytest.raises(RuntimeError, match="after environment cleanup"): + source._checkpoint_episode(episode) + + persisted = store.load_episode(state_key) + assert persisted["env_state"]["generation"] == first["env_state"]["generation"] + restored = MultiTurnRollout( + response_callback=lambda *_args: None, + template=_Template(), + env=LocalEnv(root=str(root)), + resume_store=store, + ) + restored.restore_episode(persisted) + assert restored.env.step(episode_id, "read_file", {"path": "state.txt"}).observation == "stable" + restored.env.close(episode_id) + + def test_episode_policy_binding_overrides_the_samplers_mutable_default(): class _Sampler: accepts_rollout_state = False diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 4a6e165e1..f6006e4db 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -80,6 +80,9 @@ def restore_delivery(self, state_key): self.restored.append(state_key) return self.store.load_object("deliveries", state_key) + def restore_segment(self, state_key): + return self.store.load_object("segments", state_key) + class _PolicyManager: def __init__(self, version, paths): @@ -119,7 +122,7 @@ def step(self, trajectory, episode_id=None, session_wait=None): self.routes.append(trajectory) return super().step(trajectory, episode_id, session_wait) - def restore_episode_from_store(self, state_key): + def restore_episode_from_store(self, state_key, episode_id=None): self.restored.append(state_key) @@ -164,6 +167,18 @@ def test_default_driver_keeps_fixed_admission_window_across_versions(): driver.close() +def test_non_durable_admission_allows_an_unregistered_adapter(): + manager = _PolicyManager(1, {}) + driver = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, max_staleness=0, + checkpoint_manager=manager, + ) + driver._version = 1 + driver._admit() + assert driver._groups["0"].adapter_path is None + driver.close() + + def test_inflight_prompt_and_group_survive_snapshot(tmp_path): store = ResumeStore(tmp_path, "run-inflight") rollout = _BlockingRollout() @@ -613,6 +628,49 @@ def restoration_stats(driver): return {key: stats[key] for key in ("dropped_stale", "dropped_group", "ready_rows", "live")} +def test_done_pending_scores_republish_delivery_and_segment_inputs(tmp_path): + store = ResumeStore(tmp_path, "run-pending-scores") + source = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, + orms=[lambda _rows: _BlockingFuture()], prms=[lambda _rows: _BlockingFuture()], + resume_store=store, + ) + source._admit() + episode = source._groups["0"].members[0] + old_ref = object() + episode.traj = old_ref + episode.done = True + episode.deliver = [old_ref] + episode.sample = RolloutStatus(episode_id=episode.episode_id, turns=1, done=True) + episode.orm = [_PENDING] + episode.orm_pending = 1 + episode.prm = [[_PENDING]] + episode.prm_turns = [1] + episode.prm_inputs = [old_ref] + episode.prm_input_keys = ["segment-0"] + episode.prm_pending = 1 + state_key = episode.submit_traj["state_key"] + delivery = {"episode_id": episode.episode_id, "turns": 1, "marker": "republished"} + segment = {"episode_id": episode.episode_id, "turns": 1, "marker": "segment"} + store.save_object("deliveries", state_key, [delivery]) + store.save_object("segments", "segment-0", segment) + state = source.state_dict() + source.close() + + scored = [] + rollout = _DeliveryRollout(store) + restored = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, + orms=[lambda rows: (scored.append(("orm", rows)) or _Future([1.0]))], + prms=[lambda rows: (scored.append(("prm", rows)) or _Future([0.5]))], + resume_store=store, + ) + restored.load_state_dict(state) + + assert scored == [("orm", [delivery]), ("prm", [segment])] + restored.close() + + def test_resume_reissues_pending_prm_at_its_segment_and_keeps_the_held_barrier(tmp_path): store = ResumeStore(tmp_path, "run-prm") source = StreamingDriver( @@ -634,6 +692,7 @@ def test_resume_reissues_pending_prm_at_its_segment_and_keeps_the_held_barrier(t episode.prm_inputs = [segment_input] episode.prm_pending = 1 episode.held = 0 + store.save_object("episodes", episode.submit_traj["state_key"], {"state_key": episode.submit_traj["state_key"]}) state = source.state_dict() source.close() @@ -643,7 +702,7 @@ def prm(rows): scored.append(rows) return _Future([0.5]) - rollout = _BlockingRollout() + rollout = _RestorableRollout() restored = StreamingDriver( _prompts(1), rollout, @@ -656,6 +715,7 @@ def prm(rows): restored.load_state_dict(state) assert scored == [[segment_input]] + assert rollout.restored == [episode.submit_traj["state_key"]] assert rollout.calls == [] restored._handle(*restored._events.get_nowait()) assert restored._groups["0"].members[0].prm_pending == 0 From 8e1083619298bdcf7b1feeedbe386d267aa767e8 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 03:26:23 +0800 Subject: [PATCH 25/45] fix(agentic): preserve segment history and reclaim inputs --- .../Agentic/DurableRolloutResume.md" | 9 ++- .../async_rl/streaming_driver.py | 8 ++- src/twinkle_agentic/rollout/multi_turn.py | 11 ++- .../twinkle_agentic/test_multi_turn_resume.py | 37 ++++++++++ .../test_streaming_driver_resume.py | 72 +++++++++++++++++++ 5 files changed, 127 insertions(+), 10 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index a019ca368..2598ca6ce 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -49,9 +49,12 @@ driver 快照只写入结构化 `binding`;缺少 binding 或组身份不匹配 5. `commit_batch()` 完成 checkpoint 关联后; 6. 组淘汰后。 -PRM 按 segment 保存打分输入;恢复时只补发缺失的分数,并继续遵守 `on_step` 屏障。 -组进入 ready 或被淘汰的安全快照落盘后,其 prompt、episode object 和 LocalEnv workspace -快照会被回收;journal、driver 快照和未提交 lease 仍保留用于恢复。 +仅在配置 PRM 时按 segment 保存打分输入,每个输入使用不可复用的 UUID,恢复后继续生成也不会覆盖 +历史边界。rollout 侧索引登记所有已发布的 segment key,包括未被选择性 `prm_segment` 使用或尚未送达 +driver 的输入;恢复时只补发 +缺失的分数,并继续遵守 `on_step` 屏障。 +组进入 ready 或被淘汰的安全快照落盘后,其 prompt、episode object、已登记 segment 和 LocalEnv +workspace 快照会被回收;journal、driver 快照和未提交 lease 仍保留用于恢复。 调用方不需要在故障前手工调用 `state_dict()`。恢复入口为: diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index b16f6f946..52027858e 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -1198,6 +1198,8 @@ def _submit(self, group: _Group, traj: Any, role: str, slot: int) -> _Episode: state_key=f'{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}') if group.adapter_path is not None: traj['adapter_path'] = group.adapter_path + if self.prms and self.resume_store is not None: + traj['_resume_segments'] = True episode.submit_traj = traj self._inflight += 1 episode.counted_inflight = True @@ -1484,9 +1486,13 @@ def _discard_group_state(self, group: _Group, *, deliveries: bool = True) -> Non if not state_key: continue self.resume_store.delete_object("episodes", state_key) - for segment_key in episode.prm_input_keys: + segment_keys = list(episode.prm_input_keys) + if self.resume_store.has_object("segment-index", state_key): + segment_keys += self.resume_store.load_object("segment-index", state_key) + for segment_key in dict.fromkeys(segment_keys): if segment_key: self.resume_store.delete_object("segments", segment_key) + self.resume_store.delete_object("segment-index", state_key) if deliveries: self.resume_store.delete_object("deliveries", state_key) if callable(discard): diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index d69d2bb26..e2d76789c 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -428,7 +428,6 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara #: Under segment_policy='collect': the rows of segments a compaction boundary already #: froze, oldest first; the final segment's row joins them when the episode ends. self.closed_rows: list = [] - self.segment_seq = 0 #: Stable identity supplied by the driver. It is not a random session id. self.state_key = str(trajectory.get('state_key') or '') #: Behavior-policy binding for the whole episode. A resumed group keeps this adapter even @@ -654,7 +653,6 @@ def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[st 'tools_key': ep.tools_key, 'last_reply': ep.last_reply, 'closed_rows': ep.closed_rows, - 'segment_seq': ep.segment_seq, 'completed_effects': sorted(ep.completed_effects), } @@ -728,7 +726,6 @@ def restore_episode(self, state: dict[str, Any]) -> str: ep.tools_key = state.get('tools_key') ep.last_reply = state.get('last_reply') ep.closed_rows = list(state.get('closed_rows') or ()) - ep.segment_seq = int(state.get('segment_seq') or 0) ep.completed_effects = set(state.get('completed_effects') or ()) ep.tool_manager = self._episode_tools(episode_id) with self._lock: @@ -1073,10 +1070,12 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: return rows, sample def _persist_segment_input(self, ep: _Episode, row: Trajectory) -> dict[str, str]: - if self.resume_store is None: + if self.resume_store is None or not ep.trajectory.get("_resume_segments"): return {} - ep.segment_seq += 1 - state_key = f"{ep.state_key}/segment/{ep.segment_seq}" + state_key = f"{ep.state_key}/segment/{uuid.uuid4().hex}" + index = self.resume_store.load_object("segment-index", ep.state_key) \ + if self.resume_store.has_object("segment-index", ep.state_key) else [] + self.resume_store.save_object("segment-index", ep.state_key, index + [state_key]) self.resume_store.save_object("segments", state_key, row) return {"resume_input_key": state_key} diff --git a/tests/twinkle_agentic/test_multi_turn_resume.py b/tests/twinkle_agentic/test_multi_turn_resume.py index db94d6cc2..a4112a43b 100644 --- a/tests/twinkle_agentic/test_multi_turn_resume.py +++ b/tests/twinkle_agentic/test_multi_turn_resume.py @@ -70,6 +70,43 @@ def test_terminal_rows_are_republished_from_store(tmp_path): assert _rollout(store).restore_delivery(episode.state_key) == rows +def test_terminal_without_prm_does_not_persist_a_segment(tmp_path): + store = ResumeStore(tmp_path, "run") + source = _rollout(store) + episode = _episode(source) + episode.ledger._pif["labels"] = [-100, 3, -100] + episode.ledger._pif["completion_mask"] = [0, 1, 0] + source._episodes[episode.episode_id] = episode + + source._finish(episode) + + segment_dir = tmp_path / "objects" / "segments" + assert not segment_dir.is_dir() or not list(segment_dir.glob("*.resume")) + + +def test_segment_identity_is_not_reused_after_restore(tmp_path): + store = ResumeStore(tmp_path, "run") + source = _rollout(store) + episode = _episode(source) + episode.trajectory["_resume_segments"] = True + episode.trajectory["marker"] = "old-boundary" + source._episodes[episode.episode_id] = episode + source.checkpoint_episode(episode.episode_id) + _, first_status = source._continue(episode) + first_key = first_status.extra["resume_input_key"] + + restored = _rollout(store) + restored.restore_episode_from_store(episode.state_key) + continued = restored._episodes[episode.episode_id] + continued.trajectory["marker"] = "new-boundary-after-restart" + _, second_status = restored._continue(continued) + second_key = second_status.extra["resume_input_key"] + + assert second_key != first_key + assert store.load_object("segments", first_key)["marker"] == "old-boundary" + assert store.load_object("segments", second_key)["marker"] == "new-boundary-after-restart" + + def test_multi_turn_restore_refuses_effect_without_tool_checkpoint(tmp_path): store = ResumeStore(tmp_path, "run") source = _rollout(store) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index f6006e4db..5e3f53618 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -84,6 +84,39 @@ def restore_segment(self, state_key): return self.store.load_object("segments", state_key) +class _SegmentRollout(_DoneRollout): + def __init__(self, store, done_after=1): + super().__init__() + self.store = store + self.done_after = done_after + self.turns = {} + + def step(self, trajectory, episode_id=None, session_wait=None): + turn = self.turns.get(episode_id, 0) + 1 + self.turns[episode_id] = turn + state_key = trajectory["state_key"] + segment_key = f"{state_key}/segment/{turn}" + row = dict(trajectory, turns=turn) + index = self.store.load_object("segment-index", state_key) \ + if self.store.has_object("segment-index", state_key) else [] + self.store.save_object("segment-index", state_key, index + [segment_key]) + self.store.save_object("segments", segment_key, row) + done = turn >= self.done_after + if done: + self.store.save_object("deliveries", state_key, [row]) + sample = RolloutStatus( + episode_id=episode_id, turns=turn, done=done, token_lengths=(1, 1), stop_reason="stop", + extra={"resume_input_key": segment_key}, + ) + return _Future(([row], sample)) + + def restore_delivery(self, state_key): + return self.store.load_object("deliveries", state_key) + + def restore_segment(self, state_key): + return self.store.load_object("segments", state_key) + + class _PolicyManager: def __init__(self, version, paths): self._version = version @@ -723,6 +756,45 @@ def prm(rows): restored.close() +def _segment_objects(root): + directory = root / "objects" / "segments" + return list(directory.glob("*.resume")) if directory.is_dir() else [] + + +def test_selective_prm_segments_are_cleaned_at_ready_and_commit(tmp_path): + store = ResumeStore(tmp_path, "run-selective-segments") + driver = StreamingDriver( + _prompts(1), _SegmentRollout(store, done_after=3), batch_size=1, num_generations=1, + prms=[lambda _rows: _Future([0.5])], prm_segment=lambda sample, _traj: sample.turns == 1, + max_steps=1, resume_store=store, + ) + driver._start() + _wait_until(lambda: driver._ready_rows == 1) + assert not _segment_objects(tmp_path) + rows, _ = driver._next_batch() + assert len(rows) == 1 + driver.commit_batch("checkpoint-1") + assert not _segment_objects(tmp_path) + driver.close() + + +def test_segment_objects_are_cleaned_when_a_group_drops(tmp_path): + store = ResumeStore(tmp_path, "run-drop-segments") + rollout = _SegmentRollout(store, done_after=2) + driver = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, + prms=[lambda _rows: _Future([0.5])], max_steps=1, resume_store=store, + ) + driver._admit() + driver._handle(*driver._events.get_nowait()) + assert _segment_objects(tmp_path) + segment_key = driver._groups["0"].members[0].prm_input_keys[0] + driver._drop_group(driver._groups["0"]) + assert not store.has_object("segments", segment_key), segment_key + assert not _segment_objects(tmp_path) + driver.close() + + def test_group_drop_snapshot_precedes_journal_commit(tmp_path, monkeypatch): store = ResumeStore(tmp_path, "run-drop-crash") driver = StreamingDriver( From f94700bf340fc407394c3ea54b381650b66c2c5b Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 06:26:38 +0800 Subject: [PATCH 26/45] fix(agentic): clean segments after lost steps finish --- .../Agentic/DurableRolloutResume.md" | 3 +- .../async_rl/streaming_driver.py | 29 ++++++---- .../test_streaming_driver_resume.py | 56 +++++++++++++++++++ 3 files changed, 76 insertions(+), 12 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 2598ca6ce..1164535d9 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -54,7 +54,8 @@ driver 快照只写入结构化 `binding`;缺少 binding 或组身份不匹配 driver 的输入;恢复时只补发 缺失的分数,并继续遵守 `on_step` 屏障。 组进入 ready 或被淘汰的安全快照落盘后,其 prompt、episode object、已登记 segment 和 LocalEnv -workspace 快照会被回收;journal、driver 快照和未提交 lease 仍保留用于恢复。 +workspace 快照会被回收;drop 时仍在飞的 step 由 lost 回调在返回后按原 attempt 的 state key 再次清理, +不会误删后续 attempt。journal、driver 快照和未提交 lease 仍保留用于恢复。 调用方不需要在故障前手工调用 `state_dict()`。恢复入口为: diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 52027858e..30e6fd418 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -1230,6 +1230,7 @@ def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: An if kind == 'step' and exc is None and not future.result()[1].done: # dropped while this step ran: release its rollout state now self.rollout.stop(future.result()[0][0], episode_id=episode.episode_id) + self._discard_episode_objects(episode) return if exc is not None and not (kind == 'step' and _is_episode_error(exc)): raise exc @@ -1475,6 +1476,22 @@ def _settle(self, group: _Group) -> None: return self._accept(group) + def _discard_episode_objects(self, episode: _Episode, *, deliveries: bool = True) -> str: + state_key = str((episode.submit_traj or {}).get("state_key") or "") + if not state_key or self.resume_store is None: + return "" + self.resume_store.delete_object("episodes", state_key) + segment_keys = list(episode.prm_input_keys) + if self.resume_store.has_object("segment-index", state_key): + segment_keys += self.resume_store.load_object("segment-index", state_key) + for segment_key in dict.fromkeys(segment_keys): + if segment_key: + self.resume_store.delete_object("segments", segment_key) + self.resume_store.delete_object("segment-index", state_key) + if deliveries: + self.resume_store.delete_object("deliveries", state_key) + return state_key + def _discard_group_state(self, group: _Group, *, deliveries: bool = True) -> None: """Collect terminal episode state after a durable ready/drop snapshot exists.""" if self.resume_store is None: @@ -1482,19 +1499,9 @@ def _discard_group_state(self, group: _Group, *, deliveries: bool = True) -> Non self.resume_store.delete_object("prompts", f"{self.run_id}/prompt/{group.key}") discard = getattr(self.rollout, "discard_episode_state", None) for episode in group.members + group.baselines: - state_key = str((episode.submit_traj or {}).get("state_key") or "") + state_key = self._discard_episode_objects(episode, deliveries=deliveries) if not state_key: continue - self.resume_store.delete_object("episodes", state_key) - segment_keys = list(episode.prm_input_keys) - if self.resume_store.has_object("segment-index", state_key): - segment_keys += self.resume_store.load_object("segment-index", state_key) - for segment_key in dict.fromkeys(segment_keys): - if segment_key: - self.resume_store.delete_object("segments", segment_key) - self.resume_store.delete_object("segment-index", state_key) - if deliveries: - self.resume_store.delete_object("deliveries", state_key) if callable(discard): try: discard(state_key) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 5e3f53618..6a275021c 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -1,3 +1,4 @@ +import hashlib import pickle import threading import time @@ -117,6 +118,30 @@ def restore_segment(self, state_key): return self.store.load_object("segments", state_key) +class _LateSegmentRollout(_DoneRollout): + def __init__(self, store): + super().__init__() + self.store = store + self.futures = {} + + def step(self, trajectory, episode_id=None, session_wait=None): + future = Future() + self.futures[episode_id] = (future, trajectory) + return future + + def complete(self, episode_id, done): + future, trajectory = self.futures[episode_id] + state_key = trajectory["state_key"] + segment_key = f"{state_key}/late-segment" + self.store.save_object("segment-index", state_key, [segment_key]) + self.store.save_object("segments", segment_key, {"episode_id": episode_id, "done": done}) + row = dict(trajectory, turns=1) + if done: + self.store.save_object("deliveries", state_key, [row]) + sample = RolloutStatus(episode_id=episode_id, turns=1, done=done, stop_reason="stop") + future.set_result(([row], sample)) + + class _PolicyManager: def __init__(self, version, paths): self._version = version @@ -795,6 +820,37 @@ def test_segment_objects_are_cleaned_when_a_group_drops(tmp_path): driver.close() +@pytest.mark.parametrize("done", [False, True]) +def test_lost_late_step_is_cleaned_without_touching_a_new_attempt(tmp_path, done): + store = ResumeStore(tmp_path, "run-late-segments") + rollout = _LateSegmentRollout(store) + driver = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, prms=[lambda _rows: _Future([0.5])], + max_steps=1, resume_store=store, + ) + driver._admit() + episode = driver._groups["0"].members[0] + state_key = episode.submit_traj["state_key"] + new_attempt_key = state_key.replace("/attempt/0/", "/attempt/1/") + new_segment_key = f"{new_attempt_key}/new-attempt-segment" + store.save_object("segment-index", new_attempt_key, [new_segment_key]) + store.save_object("segments", new_segment_key, {"marker": "new-attempt"}) + + driver._drop_group(driver._groups["0"]) + rollout.complete(episode.episode_id, done) + driver._handle(*driver._events.get_nowait()) + + new_attempt_object = store.root / "objects" / "segments" / ( + hashlib.sha256(new_segment_key.encode()).hexdigest() + ".resume" + ) + assert _segment_objects(tmp_path) == [new_attempt_object] + assert store.load_object("segments", new_segment_key) == {"marker": "new-attempt"} + assert store.load_object("segment-index", new_attempt_key) == [new_segment_key] + assert not store.has_object("segment-index", state_key) + assert not store.has_object("deliveries", state_key) + driver.close() + + def test_group_drop_snapshot_precedes_journal_commit(tmp_path, monkeypatch): store = ResumeStore(tmp_path, "run-drop-crash") driver = StreamingDriver( From 73ac06c6ab9ab9d7d27db3512a48037d239dbdc4 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 09:23:21 +0800 Subject: [PATCH 27/45] perf(checkpoint): decouple policy reads from weight saves --- src/twinkle/checkpoint_engine/manager.py | 24 +++++++--- src/twinkle_client/rollout/_http_sampler.py | 21 ++++++--- .../test_checkpoint_policy_history.py | 44 +++++++++++++++++++ 3 files changed, 75 insertions(+), 14 deletions(-) diff --git a/src/twinkle/checkpoint_engine/manager.py b/src/twinkle/checkpoint_engine/manager.py index 4bab28dbb..f5f24a91c 100644 --- a/src/twinkle/checkpoint_engine/manager.py +++ b/src/twinkle/checkpoint_engine/manager.py @@ -158,6 +158,7 @@ def __init__( self._delta_failed = False self.last_delta_metrics = None self._sync_lock = threading.RLock() + self._state_lock = threading.Lock() self._version = 0 self._adapter_paths: Dict[int, str] = {} if not isinstance(channel, str) or not channel: @@ -276,7 +277,8 @@ def close(self) -> None: @remote_function(collect='first', lazy_collect=False) def version(self) -> int: """How many syncs have completed; read without waiting for one in progress.""" - return self._version + with self._state_lock: + return self._version @remote_function(collect='first', lazy_collect=False) def adapter_path(self, version: int) -> Optional[str]: @@ -284,7 +286,8 @@ def adapter_path(self, version: int) -> Optional[str]: version = int(version) if version < 0: raise ValueError(f'policy version must be >= 0, got {version}') - return self._adapter_paths.get(version) if version >= 1 else None + with self._state_lock: + return self._adapter_paths.get(version) if version >= 1 else None @remote_function(collect='first', lazy_collect=False) def register_adapter_path(self, version: int, path: str) -> None: @@ -292,8 +295,11 @@ def register_adapter_path(self, version: int, path: str) -> None: version = int(version) if version < 1 or not path: raise ValueError('a registered policy needs version >= 1 and a non-empty checkpoint path') - self._adapter_paths[version] = str(path) - self._version = max(self._version, version) + with self._state_lock: + paths = dict(self._adapter_paths) + paths[version] = str(path) + self._adapter_paths = paths + self._version = max(self._version, version) # ── Sync ───────────────────────────────────────────────────────────────── @@ -330,9 +336,13 @@ def sync_weights(self, merge_and_sync=True, adapter_path: Optional[str] = None): self._sync_channel(merge_and_sync) finally: self.sampler.resume_generation() - self._version += 1 - if adapter_path is not None: - self._adapter_paths[self._version] = str(adapter_path) + with self._state_lock: + version = self._version + 1 + paths = dict(self._adapter_paths) + if adapter_path is not None: + paths[version] = str(adapter_path) + self._adapter_paths = paths + self._version = version def _wake_sampler(self, tags: List[str]) -> None: if self.sleep_level > 0: diff --git a/src/twinkle_client/rollout/_http_sampler.py b/src/twinkle_client/rollout/_http_sampler.py index c2a6dde1e..51f637351 100644 --- a/src/twinkle_client/rollout/_http_sampler.py +++ b/src/twinkle_client/rollout/_http_sampler.py @@ -90,22 +90,29 @@ def __init__(self, model, sampler: HTTPSampler, *, name_prefix: str = 'policy'): self.name_prefix = name_prefix self._version = 0 self._paths: Dict[int, str] = {} - self._lock = threading.Lock() + self._sync_lock = threading.Lock() + self._state_lock = threading.Lock() def sync_weights(self) -> None: - with self._lock: - saved = self.model.save(f'{self.name_prefix}-{self._version}', save_optimizer=False) + with self._sync_lock: + with self._state_lock: + version = self._version + saved = self.model.save(f'{self.name_prefix}-{version}', save_optimizer=False) path = saved.twinkle_path - self._paths[self._version] = path self.sampler.adapter_path = path - self._version += 1 + with self._state_lock: + paths = dict(self._paths) + paths[version] = path + self._paths = paths + self._version = version + 1 def version(self) -> int: - return self._version + with self._state_lock: + return self._version def adapter_path(self, version: int) -> Optional[str]: """Resolve the driver-visible policy version to its immutable adapter.""" - with self._lock: + with self._state_lock: # version() counts completed syncs, so the adapter saved by sync N is policy N + 1. return self._paths.get(int(version) - 1) if version >= 1 else None diff --git a/tests/twinkle_client/test_checkpoint_policy_history.py b/tests/twinkle_client/test_checkpoint_policy_history.py index b41b8faa4..a8e80ea9e 100644 --- a/tests/twinkle_client/test_checkpoint_policy_history.py +++ b/tests/twinkle_client/test_checkpoint_policy_history.py @@ -1,5 +1,10 @@ +import threading +import time +from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace +import pytest + from twinkle_agentic.async_rl import StreamingDriver from twinkle_client.rollout import ClientCheckpointManager @@ -37,6 +42,45 @@ def test_checkpoint_manager_retains_each_policy_adapter_for_resume(): assert manager.version() == 2 +@pytest.mark.parametrize("readers", [4, 16]) +def test_policy_queries_do_not_wait_for_a_slow_save(readers): + entered = threading.Event() + release = threading.Event() + + class _BlockingModel(_Model): + def save(self, name, **kwargs): + entered.set() + assert release.wait(timeout=3) + return super().save(name, **kwargs) + + manager = ClientCheckpointManager(_BlockingModel(), _Sampler()) + with ThreadPoolExecutor(max_workers=readers + 1) as pool: + saving = pool.submit(manager.sync_weights) + assert entered.wait(timeout=1) + queries = [pool.submit(lambda: (manager.version(), manager.adapter_path(1))) for _ in range(readers)] + time.sleep(0.1) + assert all(query.done() for query in queries) + assert all(query.result() == (0, None) for query in queries) + release.set() + saving.result(timeout=1) + assert manager.version() == 1 + assert manager.adapter_path(1) == manager.sampler.adapter_path + + +def test_save_failure_does_not_publish_a_partial_policy(): + class _FailingModel(_Model): + def save(self, *_args, **_kwargs): + raise RuntimeError("save failed") + + sampler = _Sampler() + manager = ClientCheckpointManager(_FailingModel(), sampler) + with pytest.raises(RuntimeError, match="save failed"): + manager.sync_weights() + assert manager.version() == 0 + assert manager.adapter_path(1) is None + assert sampler.adapter_path is None + + def test_checkpoint_manager_policy_versions_match_driver_admission(): model = _Model() sampler = _Sampler() From 2a3a9ff8a147c687cbbcf53eb6dfb3f7a97d37a8 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 09:27:07 +0800 Subject: [PATCH 28/45] perf(agentic): shard episode journals by state key --- .../async_rl/rollout_resume.py | 48 ++++++++++++++++--- .../test_rollout_resume_store.py | 42 ++++++++++++++++ 2 files changed, 83 insertions(+), 7 deletions(-) diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index d57971bad..d7babf7e7 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -240,8 +240,15 @@ def last(self, state_key: str, *, events: Iterable[JournalEvent] | None = None) return found +_EPISODE_EVENTS = {JournalEvent.TURN_COMMITTED, JournalEvent.TOOL_INTENT, JournalEvent.TOOL_RESULT} + + +def _episode_key(state_key: str) -> str: + return state_key.split("/effect/", 1)[0] + + class ResumeStore: - """Checkpoint objects and a transition journal for one training run.""" + """Checkpoint objects and transition journals for one training run.""" def __init__(self, root: str | os.PathLike[str], run_id: str): if not run_id: @@ -250,6 +257,12 @@ def __init__(self, root: str | os.PathLike[str], run_id: str): self.run_id = run_id self.root.mkdir(parents=True, exist_ok=True) self.journal = DurableJournal(self.root / "rollout.jsonl") + self._episode_journals: dict[str, DurableJournal] = {} + self._episode_journals_lock = threading.Lock() + self._legacy_episode_records: dict[str, list[JournalRecord]] = {} + for record in self.journal.records(): + if record.event in _EPISODE_EVENTS: + self._legacy_episode_records.setdefault(_episode_key(record.state_key), []).append(record) def __getstate__(self) -> dict[str, str]: return {"root": str(self.root), "run_id": self.run_id} @@ -257,6 +270,23 @@ def __getstate__(self) -> dict[str, str]: def __setstate__(self, state: dict[str, str]) -> None: self.__init__(state["root"], state["run_id"]) + def _episode_journal(self, episode_key: str) -> DurableJournal: + with self._episode_journals_lock: + journal = self._episode_journals.get(episode_key) + if journal is not None: + return journal + path = self.root / "episodes" / (hashlib.sha256(episode_key.encode("utf-8")).hexdigest() + ".jsonl") + created = DurableJournal(path) + with self._episode_journals_lock: + return self._episode_journals.setdefault(episode_key, created) + + def _episode_records(self, episode_key: str) -> tuple[JournalRecord, ...]: + records = list(self._legacy_episode_records.get(episode_key) or ()) + path = self.root / "episodes" / (hashlib.sha256(episode_key.encode("utf-8")).hexdigest() + ".jsonl") + if episode_key in self._episode_journals or path.is_file(): + records.extend(self._episode_journal(episode_key).records()) + return tuple(records) + def save_object(self, scope: str, key: str, value: Any) -> str: payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) digest = hashlib.sha256(payload).digest() @@ -290,28 +320,32 @@ def delete_object(self, scope: str, key: str) -> None: def checkpoint_episode(self, state_key: str, state: Any) -> None: self.save_object("episodes", state_key, state) - self.journal.append(JournalEvent.TURN_COMMITTED, state_key, {"object": _object_name(state_key)}) + self._episode_journal(state_key).append( + JournalEvent.TURN_COMMITTED, state_key, {"object": _object_name(state_key)} + ) def load_episode(self, state_key: str) -> Any: return self.load_object("episodes", state_key) def begin_effect(self, effect_key: str, payload: dict[str, Any]) -> dict[str, Any] | None: - last = self.journal.last(effect_key, events=(JournalEvent.TOOL_INTENT, JournalEvent.TOOL_RESULT)) + episode_key = _episode_key(effect_key) + records = [record for record in self._episode_records(episode_key) if record.state_key == effect_key] + last = records[-1] if records else None if last is not None and last.event == JournalEvent.TOOL_RESULT: return dict(last.payload) if last is not None and last.event == JournalEvent.TOOL_INTENT: raise UnsafeResume(f"effect {effect_key} has an intent without a result") - self.journal.append(JournalEvent.TOOL_INTENT, effect_key, payload) + self._episode_journal(episode_key).append(JournalEvent.TOOL_INTENT, effect_key, payload) return None def finish_effect(self, effect_key: str, payload: dict[str, Any]) -> None: - self.journal.append(JournalEvent.TOOL_RESULT, effect_key, payload) + self._episode_journal(_episode_key(effect_key)).append(JournalEvent.TOOL_RESULT, effect_key, payload) def pending_effects(self, state_key: str) -> tuple[str, ...]: """Effect keys whose last record is an intent rather than a result.""" prefix = state_key + "/effect/" pending: dict[str, bool] = {} - for record in self.journal.records(): + for record in self._episode_records(state_key): if not record.state_key.startswith(prefix): continue if record.event == JournalEvent.TOOL_INTENT: @@ -324,7 +358,7 @@ def completed_effects(self, state_key: str) -> tuple[str, ...]: """Effect keys with a matching result record.""" prefix = state_key + "/effect/" completed: set[str] = set() - for record in self.journal.records(): + for record in self._episode_records(state_key): if record.state_key.startswith(prefix) and record.event == JournalEvent.TOOL_RESULT: completed.add(record.state_key) return tuple(sorted(completed)) diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index 07a180484..5c1109c75 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -58,6 +58,48 @@ def test_resume_store_pickle_rebuilds_filesystem_handles(tmp_path): assert rebuilt.journal.last("run/0").event is JournalEvent.PROMPT_ASSIGNED +def test_episode_shards_merge_legacy_main_journal_records(tmp_path): + legacy = ResumeStore(tmp_path, "run") + episode = "run/group/0/member/0" + effect = episode + "/effect/0/legacy" + legacy.journal.append(JournalEvent.TURN_COMMITTED, episode, {"legacy": True}) + legacy.journal.append(JournalEvent.TOOL_INTENT, effect, {"calls": []}) + legacy.journal.append(JournalEvent.TOOL_RESULT, effect, {"observations": ["old"]}) + main_records = len(legacy.journal.records()) + + store = ResumeStore(tmp_path, "run") + assert store.begin_effect(effect, {"calls": ["ignored"]}) == {"observations": ["old"]} + store.checkpoint_episode(episode, {"state": "new"}) + new_effect = episode + "/effect/1/new" + store.begin_effect(new_effect, {"calls": ["write"]}) + store.finish_effect(new_effect, {"observations": ["new"]}) + + assert len(store.journal.records()) == main_records + assert store.completed_effects(episode) == tuple(sorted((effect, new_effect))) + assert store.pending_effects(episode) == () + assert len(list((tmp_path / "episodes").glob("*.jsonl"))) == 1 + rebuilt = pickle.loads(pickle.dumps(store)) + assert rebuilt.completed_effects(episode) == tuple(sorted((effect, new_effect))) + + +def test_episode_appends_do_not_take_the_main_run_lock(tmp_path, monkeypatch): + store = ResumeStore(tmp_path, "run") + from twinkle_agentic.async_rl import rollout_resume + + original = rollout_resume._exclusive_file_lock + main_locks = [] + + def tracked(path): + if path == store.root / "rollout.jsonl": + main_locks.append(str(path)) + return original(path) + + monkeypatch.setattr(rollout_resume, "_exclusive_file_lock", tracked) + store.checkpoint_episode("run/group/0/member/0", {"state": 0}) + store.checkpoint_episode("run/group/1/member/0", {"state": 1}) + assert main_locks == [] + + def test_resume_store_checks_object_checksum(tmp_path): store = ResumeStore(tmp_path, "run") store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) From 794baefc6c94f0d6538a6bc1b4d849ae117022bf Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 11:04:23 +0800 Subject: [PATCH 29/45] perf(agentic): add incremental LocalEnv generations --- src/twinkle_agentic/envs/localenv.py | 223 ++++++++++++++++-- tests/twinkle_agentic/test_localenv_resume.py | 121 ++++++++++ 2 files changed, 326 insertions(+), 18 deletions(-) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 1a795e310..27122c243 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -40,6 +40,7 @@ from twinkle import remote_class, remote_function from twinkle.data_format.message import Tool as ToolInfo from twinkle.utils import get_logger +from twinkle.utils.utils import atomic_write_bytes from .base import (DEFAULT_TOOLS, ENV_MAX_CONCURRENCY, TIMEOUT_EXIT_CODE, Env, StepResult, format_command_output, truncate_observation) from .resume import UnsafeCheckpoint @@ -100,6 +101,7 @@ def __init__(self, self._memory_limit_gb = memory_limit_gb self._envs = dict(envs or {}) self._resume_root = Path(self._root) / '.twinkle-resume' + self._verified_snapshots: Dict[str, Dict[str, Any]] = {} # ------------------------------------------------------------------ # Session hooks @@ -149,10 +151,122 @@ def _tree_digest(root: Path) -> Dict[str, Any]: total += len(data) return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} + @staticmethod + def _file_signature(stat_result: os.stat_result) -> Dict[str, int]: + return { + 'dev': stat_result.st_dev, + 'ino': stat_result.st_ino, + 'size': stat_result.st_size, + 'mtime_ns': stat_result.st_mtime_ns, + 'ctime_ns': stat_result.st_ctime_ns, + } + + @staticmethod + def _workspace_entries(root: Path) -> Tuple[List[str], List[Tuple[str, Path]]]: + directories = [] + files = [] + for path in sorted(root.rglob('*')): + if path.is_symlink(): + raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') + relative = path.relative_to(root).as_posix() + if path.is_dir(): + directories.append(relative) + elif path.is_file(): + files.append((relative, path)) + else: + raise UnsafeCheckpoint(f'workspace snapshot refuses non-regular file {path}') + return directories, files + + @staticmethod + def _hash_file(path: Path) -> Tuple[str, int]: + digest = hashlib.sha256() + size = 0 + with open(path, 'rb') as stream: + while chunk := stream.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + return digest.hexdigest(), size + + @staticmethod + def _manifest_digest(files: List[Dict[str, Any]], directories: List[str]) -> str: + digest = hashlib.sha256() + for relative in directories: + digest.update(b'D\0') + digest.update(relative.encode('utf-8')) + digest.update(b'\0') + for item in files: + digest.update(b'F\0') + digest.update(item['path'].encode('utf-8')) + digest.update(b'\0') + digest.update(item['sha256'].encode('ascii')) + digest.update(b'\0') + return digest.hexdigest() + + @staticmethod + def _copy_snapshot_file(source: Path, destination: Path) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + + @staticmethod + def _restore_file(source: Path, destination: Path) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + if os.name != 'nt': + try: + import fcntl + with open(source, 'rb') as source_stream, open(destination, 'wb') as target_stream: + fcntl.ioctl(target_stream.fileno(), 0x40049409, source_stream.fileno()) + shutil.copystat(source, destination) + return + except (ImportError, OSError): + destination.unlink(missing_ok=True) + shutil.copy2(source, destination) + + def _mark_snapshot_verified(self, generation_root: Path, workspace: Dict[str, Any]) -> None: + source = generation_root / 'workspace' + signatures = { + item['path']: self._file_signature((source / item['path']).stat()) + for item in workspace['files'] + } + self._verified_snapshots[str(generation_root)] = { + 'digest': workspace['digest'], + 'directories': list(workspace['directories']), + 'files': signatures, + } + + def _snapshot_cache_valid(self, generation_root: Path, workspace: Dict[str, Any]) -> bool: + verified = self._verified_snapshots.get(str(generation_root)) + if verified is None or verified['digest'] != workspace['digest']: + return False + source = generation_root / 'workspace' + try: + directories, files = self._workspace_entries(source) + if directories != verified['directories'] or [path for path, _ in files] != list(verified['files']): + return False + return all( + self._file_signature(path.stat()) == verified['files'][relative] + for relative, path in files + ) + except OSError: + return False + + def _verify_v2_workspace(self, generation_root: Path, workspace: Dict[str, Any]) -> None: + source = generation_root / 'workspace' + directories, entries = self._workspace_entries(source) + if directories != workspace['directories'] or [path for path, _ in entries] != [ + item['path'] for item in workspace['files']]: + raise UnsafeCheckpoint('LocalEnv snapshot workspace file set mismatch') + for item, (relative, path) in zip(workspace['files'], entries, strict=True): + file_digest, size = self._hash_file(path) + if size != item['size'] or file_digest != item['sha256']: + raise UnsafeCheckpoint(f'LocalEnv snapshot file checksum mismatch: {relative}') + if self._manifest_digest(workspace['files'], directories) != workspace['digest']: + raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') + self._mark_snapshot_verified(generation_root, workspace) + @remote_function(enable_continous_work=True, sticky_key='episode_id') def checkpoint_episode(self, episode_id: str, state_key: str, persisted_generation: Optional[str] = None) -> Dict[str, Any]: - """Copy one quiescent workspace, retaining the generation named by the persisted episode.""" + """Publish an incremental immutable generation, retaining the persisted episode generation.""" session = self._session(episode_id) state = session.state if session.script_inflight: @@ -166,26 +280,78 @@ def checkpoint_episode(self, episode_id: str, state_key: str, generation = f'{time.time_ns():x}-{uuid.uuid4().hex[:8]}' key_root = self._resume_root / self._state_dir_name(state_key) existing = [path for path in key_root.iterdir() if path.is_dir()] if key_root.exists() else [] - previous = max(existing, key=lambda path: path.stat().st_mtime_ns, default=None) + previous = None + previous_manifest = None + for candidate in sorted(existing, key=lambda path: path.stat().st_mtime_ns, reverse=True): + try: + candidate_manifest = json.loads((candidate / 'manifest.json').read_text(encoding='utf-8')) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + continue + if (candidate_manifest.get('state_key') == state_key + and candidate_manifest.get('generation') == candidate.name + and candidate_manifest.get('format') in {'twinkle.localenv.v1', 'twinkle.localenv.v2'}): + previous = candidate + previous_manifest = candidate_manifest + break + previous_files = { + item['path']: item for item in (previous_manifest or {}).get('workspace', {}).get('files', []) + } if previous_manifest and previous_manifest['format'] == 'twinkle.localenv.v2' else {} + directories, source_files = self._workspace_entries(Path(state.workspace)) generation_root = key_root / generation workspace_copy = generation_root / 'workspace' generation_root.mkdir(parents=True, exist_ok=False) try: - shutil.copytree(state.workspace, workspace_copy) - tree = self._tree_digest(workspace_copy) + workspace_copy.mkdir() + for relative in directories: + (workspace_copy / relative).mkdir(parents=True, exist_ok=True) + files = [] + total = 0 + reused_unverified = False + for relative, source_path in source_files: + source_stat = source_path.stat() + source_signature = self._file_signature(source_stat) + destination = workspace_copy / relative + old = previous_files.get(relative) + old_path = previous / 'workspace' / relative if previous is not None else None + if old is not None and old.get('source') == source_signature and old_path.is_file(): + reused_unverified = reused_unverified or str(previous) not in self._verified_snapshots + destination.parent.mkdir(parents=True, exist_ok=True) + try: + os.link(old_path, destination) + except OSError: + self._copy_snapshot_file(old_path, destination) + file_digest = old['sha256'] + size = old['size'] + else: + self._copy_snapshot_file(source_path, destination) + file_digest, size = self._hash_file(destination) + if self._file_signature(source_path.stat()) != source_signature: + raise UnsafeCheckpoint(f'workspace file changed during checkpoint: {relative}') + files.append({ + 'path': relative, + 'size': size, + 'sha256': file_digest, + 'source': source_signature, + }) + total += size + tree = { + 'digest': self._manifest_digest(files, directories), + 'files': files, + 'directories': directories, + 'bytes': total, + } manifest = { - 'format': 'twinkle.localenv.v1', + 'format': 'twinkle.localenv.v2', 'state_key': state_key, 'generation': generation, 'workspace': tree, } manifest_bytes = json.dumps(manifest, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') - manifest_path = generation_root / 'manifest.json' - manifest_path.write_bytes(manifest_bytes) - with open(manifest_path, 'r+b') as stream: - os.fsync(stream.fileno()) + atomic_write_bytes(generation_root / 'manifest.json', manifest_bytes) manifest_sha256 = hashlib.sha256(manifest_bytes).hexdigest() + if not reused_unverified: + self._mark_snapshot_verified(generation_root, tree) except BaseException: shutil.rmtree(generation_root, ignore_errors=True) raise @@ -194,11 +360,12 @@ def checkpoint_episode(self, episode_id: str, state_key: str, keep.add(persisted_generation) elif previous is not None: keep.add(previous.name) - for old in key_root.iterdir(): - if old.is_dir() and old.name not in keep: - shutil.rmtree(old, ignore_errors=True) + for old_root in key_root.iterdir(): + if old_root.is_dir() and old_root.name not in keep: + shutil.rmtree(old_root, ignore_errors=True) + self._verified_snapshots.pop(str(old_root), None) return { - "format": "twinkle.localenv.v1", + "format": "twinkle.localenv.v2", "state_key": state_key, "generation": generation, "manifest_sha256": manifest_sha256, @@ -211,7 +378,9 @@ def checkpoint_episode(self, episode_id: str, state_key: str, @remote_function(enable_continous_work=True, sticky_key='episode_id') def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any], trajectory=None) -> None: """Allocate a fresh session and rehydrate the snapshot named by ``state``.""" - if state.get('format') != 'twinkle.localenv.v1' or state.get('state_key') != state_key: + snapshot_format = state.get('format') + if snapshot_format not in {'twinkle.localenv.v1', 'twinkle.localenv.v2'} or state.get( + 'state_key') != state_key: raise UnsafeCheckpoint('LocalEnv restore metadata does not match the episode state key') generation = str(state.get('generation') or '') if not generation: @@ -222,9 +391,16 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] if hashlib.sha256(manifest_bytes).hexdigest() != state.get('manifest_sha256'): raise UnsafeCheckpoint('LocalEnv snapshot manifest checksum mismatch') manifest = json.loads(manifest_bytes) + if (manifest.get('format') != snapshot_format or manifest.get('state_key') != state_key + or manifest.get('generation') != generation): + raise UnsafeCheckpoint('LocalEnv snapshot manifest identity mismatch') source = generation_root / 'workspace' - if self._tree_digest(source)['digest'] != manifest['workspace']['digest']: - raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') + workspace = manifest['workspace'] + if snapshot_format == 'twinkle.localenv.v1': + if self._tree_digest(source)['digest'] != workspace['digest']: + raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') + elif not self._snapshot_cache_valid(generation_root, workspace): + self._verify_v2_workspace(generation_root, workspace) self.reset(episode_id, trajectory) try: @@ -232,14 +408,25 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] session.reward = float(state.get("reward") or 0.0) session.rewarded = bool(state.get("rewarded", session.reward != 0.0)) target = Path(self.workspace(episode_id)) - shutil.copytree(source, target, dirs_exist_ok=True) + if snapshot_format == 'twinkle.localenv.v1': + shutil.copytree(source, target, dirs_exist_ok=True) + else: + for relative in workspace['directories']: + (target / relative).mkdir(parents=True, exist_ok=True) + for item in workspace['files']: + self._restore_file(source / item['path'], target / item['path']) except BaseException: self.close(episode_id) raise @remote_function(dispatch="all", collect="none", lazy_collect=False) def discard_episode_state(self, state_key: str) -> None: - shutil.rmtree(self._resume_root / self._state_dir_name(state_key), ignore_errors=True) + key_root = self._resume_root / self._state_dir_name(state_key) + shutil.rmtree(key_root, ignore_errors=True) + prefix = str(key_root) + os.sep + for key in list(self._verified_snapshots): + if key.startswith(prefix): + self._verified_snapshots.pop(key, None) def _run_script( self, diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index a3ae6d97e..db7a602aa 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -1,3 +1,5 @@ +import hashlib +import json import os import sys import types @@ -71,3 +73,122 @@ def test_localenv_checkpoint_refuses_a_running_process(tmp_path): with pytest.raises(UnsafeCheckpoint, match="running process"): env.checkpoint_episode("episode-1", "run-1/group-0/episode-1") env.close("episode-1") + + +def test_unchanged_generation_reuses_snapshot_content_without_live_copy_or_hash(tmp_path, monkeypatch): + env = LocalEnv(root=str(tmp_path)) + env.reset("episode-1") + env.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "unchanged"}) + state_key = "run-1/group-0/episode-1/attempt-0" + first = env.checkpoint_episode("episode-1", state_key) + key_root = env._resume_root / env._state_dir_name(state_key) + live_root = str(env.workspace("episode-1")) + copies = [] + hashes = [] + + def copy(source, destination): + copies.append((str(source), str(destination))) + if str(source).startswith(live_root): + raise AssertionError("an unchanged live file was copied") + + def hash_file(path): + hashes.append(str(path)) + raise AssertionError("an unchanged file was hashed") + + monkeypatch.setattr(LocalEnv, "_copy_snapshot_file", staticmethod(copy)) + monkeypatch.setattr(LocalEnv, "_hash_file", staticmethod(hash_file)) + second = env.checkpoint_episode("episode-1", state_key, first["generation"]) + + assert copies == [] + assert hashes == [] + first_file = key_root / first["generation"] / "workspace/nested/state.txt" + second_file = key_root / second["generation"] / "workspace/nested/state.txt" + assert os.stat(first_file).st_ino == os.stat(second_file).st_ino + + +def test_incremental_generation_tracks_same_size_changes_deletes_and_empty_directories(tmp_path): + env = LocalEnv(root=str(tmp_path)) + env.reset("episode-1") + for path, content in (("keep.txt", "keep"), ("change.txt", "old"), ("delete.txt", "delete")): + env.step("episode-1", "write_file", {"path": path, "content": content}) + os.mkdir(os.path.join(env.workspace("episode-1"), "empty")) + state_key = "run-1/group-0/episode-1/attempt-0" + first = env.checkpoint_episode("episode-1", state_key) + live = env.workspace("episode-1") + with open(os.path.join(live, "change.txt"), "w", encoding="utf-8") as stream: + stream.write("new") + os.unlink(os.path.join(live, "delete.txt")) + env.step("episode-1", "write_file", {"path": "new.txt", "content": "new-file"}) + second = env.checkpoint_episode("episode-1", state_key, first["generation"]) + env.close("episode-1") + + restored = LocalEnv(root=str(tmp_path)) + restored.restore_episode("episode-1", state_key, second) + target = restored.workspace("episode-1") + with open(os.path.join(target, "change.txt"), encoding="utf-8") as stream: + assert stream.read() == "new" + assert not os.path.exists(os.path.join(target, "delete.txt")) + assert os.path.isdir(os.path.join(target, "empty")) + assert os.path.isfile(os.path.join(target, "new.txt")) + manifest = json.loads((restored._resume_root / restored._state_dir_name(state_key) + / second["generation"] / "manifest.json").read_text(encoding="utf-8")) + assert [item["path"] for item in manifest["workspace"]["files"]] == ["change.txt", "keep.txt", "new.txt"] + + +def test_cold_restore_hashes_but_warm_restore_reuses_only_verified_storage(tmp_path, monkeypatch): + env = LocalEnv(root=str(tmp_path)) + env.reset("source") + env.step("source", "write_file", {"path": "state.txt", "content": "snapshot"}) + state_key = "run-1/group-0/episode-1/attempt-0" + snapshot = env.checkpoint_episode("source", state_key) + original_hash = LocalEnv._hash_file + hashed = [] + + def tracked(path): + hashed.append(str(path)) + return original_hash(path) + + monkeypatch.setattr(LocalEnv, "_hash_file", staticmethod(tracked)) + env.restore_episode("warm", state_key, snapshot) + assert hashed == [] + + cold = LocalEnv(root=str(tmp_path)) + cold.restore_episode("cold", state_key, snapshot) + assert len(hashed) == 1 + hashed.clear() + cold.restore_episode("cold-again", state_key, snapshot) + assert hashed == [] + + key_root = env._resume_root / env._state_dir_name(state_key) + stored = key_root / snapshot["generation"] / "workspace/state.txt" + restored = env.workspace("warm") + "/state.txt" + assert os.stat(stored).st_ino != os.stat(restored).st_ino + with open(restored, "w", encoding="utf-8") as stream: + stream.write("live-only") + assert stored.read_text(encoding="utf-8") == "snapshot" + + +def test_v1_snapshot_remains_restorable(tmp_path): + env = LocalEnv(root=str(tmp_path)) + state_key = "run-1/group-0/episode-1/attempt-0" + generation_root = env._resume_root / env._state_dir_name(state_key) / "legacy" + workspace = generation_root / "workspace" + workspace.mkdir(parents=True) + (workspace / "state.txt").write_text("legacy", encoding="utf-8") + manifest = { + "format": "twinkle.localenv.v1", + "state_key": state_key, + "generation": "legacy", + "workspace": env._tree_digest(workspace), + } + manifest_bytes = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") + (generation_root / "manifest.json").write_bytes(manifest_bytes) + state = { + "format": "twinkle.localenv.v1", + "state_key": state_key, + "generation": "legacy", + "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), + } + + env.restore_episode("legacy", state_key, state) + assert env.step("legacy", "read_file", {"path": "state.txt"}).observation == "legacy" From 7a79661704fd63c2f0995ff5067f5bbe98009d26 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 11:05:16 +0800 Subject: [PATCH 30/45] perf(agentic): persist driver groups incrementally --- .../Agentic/DurableRolloutResume.md" | 24 +- .../async_rl/rollout_resume.py | 12 +- .../async_rl/streaming_driver.py | 294 +++++++++++++----- .../test_streaming_driver_resume.py | 142 ++++++++- 4 files changed, 386 insertions(+), 86 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 1164535d9..d270adbad 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -42,8 +42,8 @@ driver 快照只写入结构化 `binding`;缺少 binding 或组身份不匹配 启用 `resume_store` 后,driver 在以下稳定边界自动保存快照: -1. prompt 分配并完成成员提交; -2. 每个 rollout turn、ORM/PRM 打分提交及结果返回; +1. prompt 分配并登记成员提交; +2. 每个 rollout turn、ORM/PRM 打分登记及结果返回; 3. 完整组进入 ready 队列; 4. batch lease 写入后; 5. `commit_batch()` 完成 checkpoint 关联后; @@ -70,7 +70,8 @@ driver = StreamingDriver( run_id="gsm8k-durable", ) -if store.has_object("driver", "gsm8k-durable"): +if (store.has_object("driver-head", "gsm8k-durable") + or store.has_object("driver", "gsm8k-durable")): driver.load_state_dict() ``` @@ -105,8 +106,10 @@ checkpoint 且不再交付该 lease。调用方必须先确保模型和 optimize `ResumeStore` 由两层组成: - `DurableJournal`:带单调序号的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 - 文件锁,以及写入失败回滚;完整扫描只在初始化或异常回滚时执行; -- object store:保存 prompt、episode、lease 和 driver 快照,读取时校验 SHA-256。 + 文件锁,以及写入失败回滚;完整扫描只在初始化或异常回滚时执行。run 控制事件保留在主日志, + turn/tool intent/result 按 episode 分片;旧主日志中的 episode 事件在初始化时索引并参与恢复; +- object store:保存 prompt、episode、lease、小型 driver head 和逐 group 快照,读取时校验 SHA-256。 + 普通 step/score 只写发生变化的 group;对外 `state_dict()` 仍可按需生成兼容 v1 快照。 故障边界: @@ -137,6 +140,11 @@ class MyDurableEnv: 未声明恢复能力的 `AgentEnv`、`OpenEnv` 和 `OpenEnvClient` 在 episode 打开时 fail closed。只恢复文本对话、但丢失 workspace 或工具状态的实现不允许静默继续。 +LocalEnv v2 为每轮创建不可变增量 generation。未变化文件复用源签名和已有哈希,并只在历史 snapshot +之间建立 hardlink;新增或修改文件仍复制并计算 SHA-256。restore 的 live workspace 使用 reflink 或复制, +绝不与 snapshot hardlink。新进程首次恢复必须完整校验所有文件;只有本进程已验证且存储签名未变化的 +generation 才能使用 warm 校验缓存。v1 generation 仍可恢复。 + ## 外部工具副作用 每个工具轮次区分 intent 和 result: @@ -269,9 +277,9 @@ vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: colocate 路径,新版结果不能替代旧版复测; - 无法 checkpoint 的远端 agent harness; - 所有外部工具协议都具备幂等结果查询; -- 大规模长训练的持久化开销尚未形成独立基准。当前 journal 正常追加只同步尾部,初始化或异常回滚才 - 完整扫描;driver 在稳定边界保存完整状态,LocalEnv 每轮复制并校验 workspace。后续可评估按 episode - 分片和增量 workspace 快照,不能用当前端到端墙钟结果替代这些专项评估。 +- 大规模长训练的持久化开销仍需按具体版本形成独立基准。当前 journal 正常追加只同步尾部并按 episode + 分片,driver 普通事件只保存当前 group,LocalEnv 未变化轮次不再复制或重哈希 live 文件;新进程冷恢复 + 仍完整校验 workspace。不能用端到端墙钟结果替代这些专项评估。 因此该机制的主要结论是进程重启时保持 GRPO 组语义、事务一致性、固定预算下的有效训练量, 并减少重复工具副作用和重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index d7babf7e7..b07e99c08 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -297,12 +297,11 @@ def save_object(self, scope: str, key: str, value: Any) -> str: def has_object(self, scope: str, key: str) -> bool: return (self.root / "objects" / scope / _object_name(key)).is_file() - def load_object(self, scope: str, key: str) -> Any: - path = self.root / "objects" / scope / _object_name(key) + def _load_object_path(self, path: Path) -> Any: try: data = path.read_bytes() except FileNotFoundError as exc: - raise ResumeError(f"resume object missing: {scope}/{key}") from exc + raise ResumeError(f"resume object missing: {path}") from exc if not data.startswith(_OBJECT_MAGIC) or len(data) < len(_OBJECT_MAGIC) + 32: raise ResumeError(f"resume object has an invalid header: {path}") digest = data[len(_OBJECT_MAGIC) : len(_OBJECT_MAGIC) + 32] @@ -314,6 +313,13 @@ def load_object(self, scope: str, key: str) -> Any: except Exception as exc: raise ResumeError(f"resume object cannot be decoded: {path}") from exc + def load_object(self, scope: str, key: str) -> Any: + return self._load_object_path(self.root / "objects" / scope / _object_name(key)) + + def load_objects(self, scope: str) -> list[Any]: + directory = self.root / "objects" / scope + return [self._load_object_path(path) for path in sorted(directory.glob("*.resume"))] + def delete_object(self, scope: str, key: str) -> None: path = self.root / "objects" / scope / _object_name(key) path.unlink(missing_ok=True) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 30e6fd418..04c19b7f5 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -330,6 +330,9 @@ def __init__(self, self._lock = threading.Condition() self._persistence_lock = threading.Lock() + self._action_local = threading.local() + self._persistence_revision = 0 + self._ready_sequence = 0 self._events: 'queue.Queue[tuple[Any, ...]]' = queue.Queue() self._ready: deque = deque() self._ready_rows = 0 @@ -431,7 +434,7 @@ def _next_batch(self) -> Optional[tuple]: #: queued behind that cycle is not stuck, so the watchdog stays quiet while it runs self._lending = lending try: - with self._lock: + with self._actions_locked(): while True: if self._error is not None: raise self._error @@ -459,7 +462,7 @@ def _next_batch(self) -> Optional[tuple]: # and score entry repeat per row, aligned. Nothing here scales with # the tokens, so the event thread is never held up; collecting and counting move # together, so the batch is never half-published. - with self._lock: + with self._actions_locked(): self._drop_stale() if self.checkpoint_manager is not None: # Same-window backstop the old whole-group min(version) drop provided: after _drop_stale @@ -477,8 +480,10 @@ def _next_batch(self) -> Optional[tuple]: scores: List[Dict[str, Any]] = [] version_spans: List[int] = [] row_state_keys: List[str] = [] + leased_group_keys: List[str] = [] while len(trajs) < self.batch_size and self._ready: ready_group = self._ready.popleft() + leased_group_keys.append(ready_group[0].group.key) self._live -= sum(1 for episode in ready_group if episode.deliver) for episode in ready_group: episode.sample.version_span = self._version - episode.sample.policy_version @@ -516,6 +521,7 @@ def _next_batch(self) -> Optional[tuple]: 'policy_versions': list(facts['policy_versions']), 'rows': trajs, 'row_state_keys': row_state_keys, + 'group_keys': leased_group_keys, 'facts': facts, } self._lease_returned = True @@ -587,7 +593,7 @@ def _drop_stale(self) -> None: self._ready = kept def _retire_stale_group(self, group: _Group) -> None: - with self._lock: + with self._actions_locked(): self._retire_stale_group_locked(group) def _retire_stale_group_locked(self, group: _Group) -> None: @@ -600,6 +606,8 @@ def _retire_stale_group_locked(self, group: _Group) -> None: JournalEvent.GROUP_DROPPED, group.state_key, {"reason": "stale", "binding": group.binding.to_dict(), "current_version": self._version}, + group=group, + delete_group=True, ) for episode in group.members + group.baselines: if episode.lost: @@ -609,8 +617,7 @@ def _retire_stale_group_locked(self, group: _Group) -> None: if episode.role != _BASELINE: self._live -= 1 if self.resume_store is not None: - with self._durable_io_locked(): - self._discard_group_state(group) + self._defer_action(lambda: self._discard_group_state(group)) @remote_function(execute='first', collect='first', lazy_collect=False) def stats(self) -> Dict[str, Any]: @@ -690,6 +697,14 @@ def _snapshot(self) -> Dict[str, Any]: 'lease': self._lease, } + @contextmanager + def _condition_released(self): + lock_state = self._lock._release_save() + try: + yield + finally: + self._lock._acquire_restore(lock_state) + @contextmanager def _durable_io_locked(self): self._persistence_lock.acquire() @@ -700,12 +715,66 @@ def _durable_io_locked(self): self._persistence_lock.release() self._lock._acquire_restore(lock_state) - def _persist_snapshot_locked(self) -> None: - """Capture a stable snapshot under ``_lock``, then write it without blocking driver events.""" - if self.resume_store is not None: - state = self._snapshot() - with self._durable_io_locked(): - self.resume_store.save_object('driver', self.run_id, state) + @contextmanager + def _actions_locked(self): + existing = getattr(self._action_local, 'items', None) + if existing is not None: + with self._lock: + yield + return + actions = [] + with self._lock: + self._action_local.items = actions + try: + yield + finally: + del self._action_local.items + for action in actions: + action() + + def _defer_action(self, action: Callable[[], Any]) -> None: + actions = getattr(self._action_local, 'items', None) + if actions is None or self.resume_store is None: + action() + else: + actions.append(action) + + def _next_persistence_revision(self) -> int: + self._persistence_revision += 1 + return self._persistence_revision + + def _head_state(self, lease: Any = None, *, current_lease: bool = True) -> Dict[str, Any]: + return { + 'format': 'twinkle.streaming-driver.v2', + 'run_id': self.run_id, + 'revision': self._next_persistence_revision(), + 'handed': self._handed, + 'prompts_drawn': self._prompt_seq, + 'version': self._version, + 'base_version': self._base_version, + 'exhausted': self._exhausted, + 'counters': dict(self._counters), + 'loader_state': self._loader_state(), + 'lease': self._lease if current_lease else lease, + } + + def _group_record(self, group: _Group, *, ready: bool = False) -> Dict[str, Any]: + return { + 'format': 'twinkle.streaming-driver-group.v1', + 'run_id': self.run_id, + 'revision': self._next_persistence_revision(), + 'ready': ready, + 'ready_order': self._ready_sequence if ready else None, + 'counters': dict(self._counters), + 'group': self._group_state(group), + } + + def _persist_group_locked(self, group: _Group) -> None: + if self.resume_store is None: + return + record = self._group_record(group) + with self._condition_released(): + self.resume_store.save_object('driver-groups', group.state_key, record) def _persist_event_locked( self, @@ -713,12 +782,20 @@ def _persist_event_locked( state_key: str, payload: Optional[Dict[str, Any]] = None, objects: Sequence[tuple[str, str, Any]] = (), + group: Optional[_Group] = None, + ready: bool = False, + delete_group: bool = False, ) -> None: - state = self._snapshot() + record = self._group_record(group, ready=ready) if group is not None and not delete_group else None + state = self._head_state() with self._durable_io_locked(): for scope, key, value in objects: self.resume_store.save_object(scope, key, value) - self.resume_store.save_object('driver', self.run_id, state) + if record is not None: + self.resume_store.save_object('driver-groups', group.state_key, record) + elif group is not None and delete_group: + self.resume_store.delete_object('driver-groups', group.state_key) + self.resume_store.save_object('driver-head', self.run_id, state) self.resume_store.journal.append(event, state_key, payload) @remote_function(execute='first', collect='first', lazy_collect=False) @@ -869,19 +946,58 @@ def _resume_live_episode(self, episode: _Episode) -> None: # No turn boundary committed yet: opening the episode again repeats no external tool call. self._step(episode, episode.submit_traj) + def _load_v2_state(self, head: Dict[str, Any]) -> Dict[str, Any]: + if head.get('format') != 'twinkle.streaming-driver.v2': + raise UnsafeResume('unsupported StreamingDriver checkpoint format') + records = self.resume_store.load_objects('driver-groups') + for record in records: + if record.get('format') != 'twinkle.streaming-driver-group.v1' or record.get('run_id') != self.run_id: + raise UnsafeResume('invalid incremental StreamingDriver group checkpoint') + lease = head.get('lease') + leased_groups = set((lease or {}).get('group_keys') or ()) + active = [record['group'] for record in records if not record.get('ready')] + ready_records = sorted( + (record for record in records if record.get('ready') and record['group'].get('key') not in leased_groups), + key=lambda record: record.get('ready_order') or 0, + ) + latest = max([head, *records], key=lambda item: int(item.get('revision') or 0)) + self._persistence_revision = int(latest.get('revision') or 0) + self._ready_sequence = max([int(record.get('ready_order') or 0) for record in records] or [0]) + return { + 'format': 'twinkle.streaming-driver.v1', + 'run_id': self.run_id, + 'handed': head.get('handed'), + 'prompts_drawn': head.get('prompts_drawn'), + 'version': head.get('version'), + 'base_version': head.get('base_version'), + 'exhausted': head.get('exhausted'), + 'counters': latest.get('counters') or head.get('counters'), + 'loader_state': head.get('loader_state'), + 'groups': active, + 'ready': [[item for item in record['group'].get('members') or ()] for record in ready_records], + 'ready_groups': [ + {key: value for key, value in record['group'].items() if key not in {'members', 'baselines'}} + for record in ready_records + ], + 'lease': lease, + } + @remote_function(execute='first', collect='first', lazy_collect=False) def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: """Rebuild a fresh driver from a snapshot, or from the store's latest snapshot.""" if state is None: if self.resume_store is None: raise UnsafeResume('load_state_dict() without state needs a resume store') - state = self.resume_store.load_object('driver', self.run_id) + if self.resume_store.has_object('driver-head', self.run_id): + state = self._load_v2_state(self.resume_store.load_object('driver-head', self.run_id)) + else: + state = self.resume_store.load_object('driver', self.run_id) if state.get('format') != 'twinkle.streaming-driver.v1': raise UnsafeResume('unsupported StreamingDriver checkpoint format') if str(state.get('run_id')) != self.run_id: raise UnsafeResume(f'driver snapshot belongs to run {state.get("run_id")!r}, not {self.run_id!r}') observed_version = int(self.checkpoint_manager.version()) if self.checkpoint_manager is not None else 0 - with self._lock: + with self._actions_locked(): if self._thread is not None or self._iter_started: raise UnsafeResume('load_state_dict must run before the driver starts') self._groups = {} @@ -947,7 +1063,7 @@ def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: self._restore_deliveries() for episode in live: self._resume_live_episode(episode) - with self._lock: + with self._actions_locked(): for group in list(self._groups.values()): self._settle(group) self._lock.notify_all() @@ -963,8 +1079,7 @@ def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, An raise UnsafeResume('commit_batch() needs the durable model checkpoint reference') lease_id = str(lease['lease_id']) if self.resume_store is not None: - state = self._snapshot() - state['lease'] = None + state = self._head_state(current_lease=False) with self._durable_io_locked(): self.resume_store.journal.append( JournalEvent.MODEL_CHECKPOINT_COMMITTED, lease_id, @@ -977,7 +1092,9 @@ def commit_batch(self, checkpoint_ref: str = '', manifest: Optional[Dict[str, An self.resume_store.delete_object('leases', lease_id) for state_key in dict.fromkeys(lease.get('row_state_keys') or ()): self.resume_store.delete_object('deliveries', state_key) - self.resume_store.save_object('driver', self.run_id, state) + for group_key in lease.get('group_keys') or (): + self.resume_store.delete_object('driver-groups', f'{self.run_id}/group/{group_key}') + self.resume_store.save_object('driver-head', self.run_id, state) self._lease = None self._lease_returned = False self._lock.notify_all() @@ -1021,9 +1138,9 @@ def _run(self) -> None: if self._closed: return version = self._read_version() - with self._lock: + with self._actions_locked(): self._version = max(self._version, version) - self._admit() + self._admit_locked() self._retry_no_slot_due() self._lock.notify_all() _record_driver_probe('admit', live=self._live, capacity=self._capacity(), @@ -1102,7 +1219,7 @@ def _capacity(self) -> int: return (self.max_staleness + 1) * self.sync_interval * self.batch_size def _admit(self) -> None: - with self._lock: + with self._actions_locked(): self._admit_locked() def _admit_locked(self) -> None: @@ -1147,6 +1264,7 @@ def _admit_locked(self) -> None: prompt_key, {'group_key': key, 'object': prompt_key, 'binding': binding.to_dict()}, objects=(('prompts', prompt_key, row),), + group=group, ) def _next_row(self) -> Any: @@ -1207,30 +1325,35 @@ def _submit(self, group: _Group, traj: Any, role: str, slot: int) -> _Episode: return episode def _step(self, episode: _Episode, traj: Any) -> None: - # session_wait=0: the admission loop never blocks on a full session pool -- a no-slot status - # comes back along the return channel and the member is retried later (see _no_slot). - future = self.rollout.step(traj, episode_id=episode.episode_id, session_wait=0) - _record_driver_probe('step_submitted', episode.episode_id) + def submit(): + # session_wait=0: the admission loop never blocks on a full session pool -- a no-slot status + # comes back along the return channel and the member is retried later (see _no_slot). + future = self.rollout.step(traj, episode_id=episode.episode_id, session_wait=0) + _record_driver_probe('step_submitted', episode.episode_id) + + def _done(f, episode=episode): + _record_driver_probe('step_future_done', episode.episode_id) + self._events.put(('step', episode, None, f)) - def _done(f, episode=episode): - _record_driver_probe('step_future_done', episode.episode_id) - self._events.put(('step', episode, None, f)) + future.add_done_callback(_done) - future.add_done_callback(_done) + self._defer_action(submit) # ------------------------------------------------------------------ completions def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: Any) -> None: _record_driver_probe('handle', episode.episode_id, kind=kind) exc = future.exception() - with self._lock: + with self._actions_locked(): if self._closed: return if episode.lost: if kind == 'step' and exc is None and not future.result()[1].done: # dropped while this step ran: release its rollout state now - self.rollout.stop(future.result()[0][0], episode_id=episode.episode_id) - self._discard_episode_objects(episode) + rows = future.result()[0] + self._defer_action( + lambda: self.rollout.stop(rows[0], episode_id=episode.episode_id)) + self._defer_action(lambda: self._discard_episode_objects(episode)) return if exc is not None and not (kind == 'step' and _is_episode_error(exc)): raise exc @@ -1258,8 +1381,8 @@ def _handle(self, kind: str, episode: _Episode, index: Optional[int], future: An episode.prm[k][segment] is _PENDING for k in range(len(self.prms))): self._release(episode, segment) self._maybe_finish(episode) - if kind != "step": - self._persist_snapshot_locked() + if episode.group.key in self._groups: + self._persist_group_locked(episode.group) self._lock.notify_all() def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None: @@ -1273,7 +1396,6 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None segment = self._score_prm(episode) if self.on_step is not None and not episode.done: episode.held = segment - self._persist_snapshot_locked() return if episode.done: self._consecutive_failures = 0 @@ -1281,9 +1403,6 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None self._score_orm(episode) else: self._step(episode, trajs[0]) - # Persist pending score work as well as completed values. Otherwise a restart could skip a - # segment's PRM entirely or repeat an ORM that already produced an external side effect. - self._persist_snapshot_locked() def _score_prm(self, episode: _Episode) -> int: if episode.prm is None: @@ -1295,11 +1414,15 @@ def _score_prm(self, episode: _Episode) -> int: for scorer, prm in enumerate(self.prms): episode.prm[scorer].append(_PENDING) episode.prm_pending += 1 - future = prm([episode.traj]) - future.add_done_callback( - lambda f, episode=episode, key=(segment, scorer): self._events.put(("prm", episode, key, f)) - ) - _record_driver_probe("score_submitted", episode.episode_id, kind="prm", segment=segment) + + def submit(prm=prm, scorer=scorer): + future = prm([episode.traj]) + future.add_done_callback( + lambda f, episode=episode, key=(segment, scorer): self._events.put(("prm", episode, key, f)) + ) + _record_driver_probe("score_submitted", episode.episode_id, kind="prm", segment=segment) + + self._defer_action(submit) return segment def _release(self, episode: _Episode, segment: int) -> None: @@ -1309,18 +1432,21 @@ def _release(self, episode: _Episode, segment: int) -> None: self._step(episode, episode.traj) return self._counters['stopped'] += 1 - self.rollout.stop(episode.traj, episode_id=episode.episode_id) + self._defer_action(lambda: self.rollout.stop(episode.traj, episode_id=episode.episode_id)) self._lose(episode) def _score_orm(self, episode: _Episode) -> None: episode.orm = [_PENDING] * len(self.orms) episode.orm_pending = len(self.orms) for index, orm in enumerate(self.orms): - future = orm([episode.traj]) - future.add_done_callback( - lambda f, episode=episode, index=index: self._events.put(("orm", episode, index, f)) - ) - _record_driver_probe("score_submitted", episode.episode_id, kind="orm") + def submit(orm=orm, index=index): + future = orm([episode.traj]) + future.add_done_callback( + lambda f, episode=episode, index=index: self._events.put(("orm", episode, index, f)) + ) + _record_driver_probe("score_submitted", episode.episode_id, kind="orm") + + self._defer_action(submit) self._maybe_finish(episode) def _fail(self, episode: _Episode, exc: BaseException) -> None: @@ -1509,35 +1635,53 @@ def _discard_group_state(self, group: _Group, *, deliveries: bool = True) -> Non logger.warning(f"discarding environment state for {state_key} failed: {exc}") def _accept(self, group: _Group) -> None: - with self._lock: + with self._actions_locked(): self._accept_locked(group) def _accept_locked(self, group: _Group) -> None: del self._groups[group.key] - self._ready.append(list(group.members)) - self._ready_rows += sum(len(episode.deliver) for episode in group.members) - if self.resume_store is not None: - self._persist_event_locked( - JournalEvent.GROUP_READY, - group.state_key, - { - "group_key": group.key, - "binding": group.binding.to_dict(), - "attempt": group.attempt, - "episodes": [episode.episode_id for episode in group.members], - }, + members = list(group.members) + if self.resume_store is None: + self._ready.append(members) + self._ready_rows += sum(len(episode.deliver) for episode in members) + _record_driver_probe( + "group_ready", + members[0].episode_id if members else "", + group=group.key, + ready_rows=self._ready_rows, ) - with self._durable_io_locked(): - self._discard_group_state(group, deliveries=False) - _record_driver_probe( - "group_ready", - group.members[0].episode_id if group.members else "", - group=group.key, - ready_rows=self._ready_rows, + return + self._ready_sequence += 1 + self._persist_event_locked( + JournalEvent.GROUP_READY, + group.state_key, + { + "group_key": group.key, + "binding": group.binding.to_dict(), + "attempt": group.attempt, + "episodes": [episode.episode_id for episode in group.members], + }, + group=group, + ready=True, ) + def publish_ready(): + self._discard_group_state(group, deliveries=False) + with self._lock: + self._ready.append(members) + self._ready_rows += sum(len(episode.deliver) for episode in members) + self._lock.notify_all() + _record_driver_probe( + "group_ready", + members[0].episode_id if members else "", + group=group.key, + ready_rows=self._ready_rows, + ) + + self._defer_action(publish_ready) + def _drop_group(self, group: _Group) -> None: - with self._lock: + with self._actions_locked(): self._drop_group_locked(group) def _drop_group_locked(self, group: _Group) -> None: @@ -1556,7 +1700,8 @@ def _drop_group_locked(self, group: _Group) -> None: episode.counted_inflight = False if episode.held is not None: # waiting for its PRM scores, no step in flight; a stepping one is stopped when it returns - self.rollout.stop(episode.traj, episode_id=episode.episode_id) + self._defer_action( + lambda episode=episode: self.rollout.stop(episode.traj, episode_id=episode.episode_id)) if self.resume_store is not None: self._persist_event_locked( JournalEvent.GROUP_DROPPED, @@ -1566,9 +1711,10 @@ def _drop_group_locked(self, group: _Group) -> None: "binding": group.binding.to_dict(), "current_version": self._version, }, + group=group, + delete_group=True, ) - with self._durable_io_locked(): - self._discard_group_state(group) + self._defer_action(lambda: self._discard_group_state(group)) #: Placeholder for a score whose Future has not completed yet. diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 6a275021c..3128259fc 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -895,8 +895,148 @@ def test_terminal_group_snapshot_precedes_episode_state_cleanup(tmp_path): assert store.has_object("prompts", "run-cleanup/prompt/0") driver._accept(group) - assert store.has_object("driver", "run-cleanup") + assert store.has_object("driver-head", "run-cleanup") assert not store.has_object("prompts", "run-cleanup/prompt/0") assert all(not store.has_object("episodes", key) for key in state_keys) assert rollout.discarded == state_keys driver.close() + + +def test_ordinary_step_saves_only_its_group_without_loader_or_full_snapshot(tmp_path, monkeypatch): + class Loader(list): + def state_dict(self): + return {"cursor": len(self)} + + store = ResumeStore(tmp_path, "run-incremental") + rollout = _BlockingRollout() + driver = StreamingDriver( + Loader(_prompts(2)), rollout, batch_size=2, num_generations=1, max_staleness=0, resume_store=store + ) + driver._admit() + assert list(driver._groups) == ["0", "1"] + writes = [] + original_save = store.save_object + + def record_save(scope, key, value): + writes.append((scope, key)) + return original_save(scope, key, value) + + monkeypatch.setattr(store, "save_object", record_save) + monkeypatch.setattr(driver, "_loader_state", lambda: (_ for _ in ()).throw(AssertionError("loader state read"))) + monkeypatch.setattr(driver, "_snapshot", lambda: (_ for _ in ()).throw(AssertionError("full snapshot captured"))) + episode = driver._groups["0"].members[0] + row = dict(episode.submit_traj, turns=1) + sample = RolloutStatus(episode_id=episode.episode_id, turns=1, done=False, token_lengths=(1, 1)) + driver._handle("step", episode, None, _Future(([row], sample))) + + assert writes == [("driver-groups", "run-incremental/group/0")] + driver.close() + + +def test_ready_transition_does_not_save_the_group_twice(tmp_path, monkeypatch): + store = ResumeStore(tmp_path, "run-terminal-once") + driver = StreamingDriver( + _prompts(1), _DoneRollout(), batch_size=1, num_generations=1, max_steps=1, resume_store=store + ) + driver._admit() + writes = [] + original_save = store.save_object + + def record_save(scope, key, value): + writes.append((scope, key)) + return original_save(scope, key, value) + + monkeypatch.setattr(store, "save_object", record_save) + driver._handle(*driver._events.get_nowait()) + + assert writes.count(("driver-groups", "run-terminal-once/group/0")) == 1 + assert writes.count(("driver-head", "run-terminal-once")) == 1 + assert driver._ready_rows == 1 + driver.close() + + +def test_step_prm_stop_and_cleanup_actions_run_outside_driver_locks(tmp_path): + store = ResumeStore(tmp_path, "run-actions") + checked = [] + + class Rollout(_DoneRollout): + def __init__(self, driver): + super().__init__() + self.driver = driver + self.stopped = [] + + def check_unlocked(self, action): + assert not self.driver._lock._is_owned(), action + assert not self.driver._persistence_lock.locked(), action + checked.append(action) + + def step(self, trajectory, episode_id=None, session_wait=None): + self.check_unlocked("step") + row = dict(trajectory, turns=1) + sample = RolloutStatus( + episode_id=episode_id, turns=1, done=False, token_lengths=(1, 1), + extra={"resume_input_key": trajectory["state_key"] + "/segment/1"}, + ) + return _Future(([row], sample)) + + def stop(self, trajectory, episode_id=None): + self.check_unlocked("stop") + self.stopped.append(episode_id) + + def discard_episode_state(self, state_key): + self.check_unlocked("cleanup") + self.discarded.append(state_key) + + def prm(_rows): + rollout.check_unlocked("prm") + return _Future([0.5]) + + driver = StreamingDriver( + _prompts(1), None, batch_size=1, num_generations=1, prms=[prm], on_step=lambda _sample, _scores: False, + max_steps=1, resume_store=store, + ) + rollout = Rollout(driver) + driver.rollout = rollout + + driver.prm_names = ["process"] + driver._admit() + driver._handle(*driver._events.get_nowait()) + driver._handle(*driver._events.get_nowait()) + + assert checked == ["step", "prm", "stop", "cleanup"] + assert rollout.stopped == [driver.run_id + ":g0:a0:member:0"] + assert rollout.discarded == [driver.run_id + "/group/0/attempt/0/member/0"] + driver.close() + + +def test_done_orm_and_ready_cleanup_actions_run_outside_driver_locks(tmp_path): + store = ResumeStore(tmp_path, "run-orm-actions") + checked = [] + + class Rollout(_DoneRollout): + def discard_episode_state(self, state_key): + assert not driver._lock._is_owned() + assert not driver._persistence_lock.locked() + checked.append("cleanup") + super().discard_episode_state(state_key) + + rollout = Rollout() + driver = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, max_steps=1, resume_store=store, + ) + + def orm(_rows): + assert not driver._lock._is_owned() + assert not driver._persistence_lock.locked() + checked.append("orm") + return _Future([1.0]) + + driver.orms = [orm] + driver.orm_names = ["outcome"] + driver._admit() + driver._handle(*driver._events.get_nowait()) + driver._handle(*driver._events.get_nowait()) + + assert checked == ["orm", "cleanup"] + assert driver._ready_rows == 1 + driver.close() From 60cf9786da58f4b726847de453bcc5e191fde328 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 12:05:12 +0800 Subject: [PATCH 31/45] fix(agentic): refresh incremental head on manual snapshot --- .../async_rl/streaming_driver.py | 2 ++ .../test_streaming_driver_resume.py | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 04c19b7f5..9a8ffae1c 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -809,8 +809,10 @@ def state_dict(self) -> Dict[str, Any]: with self._lock: state = self._snapshot() if self.resume_store is not None: + head = self._head_state() with self._durable_io_locked(): self.resume_store.save_object('driver', self.run_id, state) + self.resume_store.save_object('driver-head', self.run_id, head) return state def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 3128259fc..8122d7b2f 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -1040,3 +1040,28 @@ def orm(_rows): assert checked == ["orm", "cleanup"] assert driver._ready_rows == 1 driver.close() + + +def test_manual_snapshot_also_refreshes_the_automatic_v2_head(tmp_path): + store = ResumeStore(tmp_path, "run-manual-head") + driver = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, resume_store=store + ) + driver._admit() + driver._version = 3 + state = driver.state_dict() + + head = store.load_object("driver-head", "run-manual-head") + assert state["format"] == "twinkle.streaming-driver.v1" + assert head["format"] == "twinkle.streaming-driver.v2" + assert head["version"] == 3 + assert head["prompts_drawn"] == 1 + driver.close() + + restored = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, resume_store=store + ) + restored.load_state_dict() + assert restored._version == 3 + assert list(restored._groups) == ["0"] + restored.close() From ff87c9700eb1ffb24138ee3cafd75f920b81639d Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 13:54:05 +0800 Subject: [PATCH 32/45] fix(agentic): close resume audit regressions --- src/twinkle/utils/utils.py | 24 ++- .../async_rl/rollout_resume.py | 56 +++--- .../async_rl/streaming_driver.py | 129 +++++++------ src/twinkle_agentic/envs/localenv.py | 63 +++--- src/twinkle_agentic/rollout/multi_turn.py | 8 + .../twinkle_agentic/test_multi_turn_resume.py | 38 +++- .../twinkle_agentic/test_resume_boundaries.py | 52 ++++- .../test_rollout_resume_store.py | 11 ++ .../test_streaming_driver_resume.py | 180 +++++++++++++++++- .../test_checkpoint_policy_history.py | 45 +++++ 10 files changed, 497 insertions(+), 109 deletions(-) diff --git a/src/twinkle/utils/utils.py b/src/twinkle/utils/utils.py index bc4add40c..649684edd 100644 --- a/src/twinkle/utils/utils.py +++ b/src/twinkle/utils/utils.py @@ -4,13 +4,35 @@ import fnmatch import glob import inspect +import logging import os import shutil import threading +import time from functools import lru_cache from pathlib import Path from typing import Any, Callable +logger = logging.getLogger(__name__) +_REPLACE_RETRIES = 5 + + +def _replace_with_retry(source: Path, target: Path) -> None: + for attempt in range(_REPLACE_RETRIES + 1): + try: + os.replace(source, target) + return + except PermissionError: + if attempt == _REPLACE_RETRIES: + logger.error('atomic replace failed after %d attempts: %s -> %s', attempt + 1, source, target) + raise + delay = min(0.01 * (2**attempt), 0.1) + logger.warning( + 'atomic replace attempt %d/%d failed with PermissionError; retrying in %.3fs: %s -> %s', + attempt + 1, _REPLACE_RETRIES + 1, delay, source, target, + ) + time.sleep(delay) + def atomic_write_bytes(path: Path, data: bytes) -> None: """Replace ``path`` with complete bytes; the previous file survives failures.""" @@ -22,7 +44,7 @@ def atomic_write_bytes(path: Path, data: bytes) -> None: stream.write(data) stream.flush() os.fsync(stream.fileno()) - os.replace(pending, path) + _replace_with_retry(pending, path) if os.name != 'nt': descriptor = os.open(path.parent, os.O_RDONLY) try: diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index b07e99c08..093701e9a 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -136,6 +136,7 @@ def __init__(self, path: str | os.PathLike[str]): self._lock = threading.Lock() self._next_seq = 0 self._records: list[JournalRecord] = [] + self._stream = None with _exclusive_file_lock(self.path): self._repair_and_scan() @@ -173,20 +174,31 @@ def _repair_and_scan(self) -> None: self._next_seq = records[-1].seq + 1 self._records = records + def _open_stream(self): + if self._stream is None: + self._stream = open(self.path, "a+b") + return self._stream + def _sync_tail(self) -> None: - if not self.path.exists() or self.path.stat().st_size == 0: + stream = self._open_stream() + stream.seek(0, os.SEEK_END) + end = stream.tell() + if end == 0: self._next_seq = 0 return - with open(self.path, "rb") as stream: - stream.seek(0, os.SEEK_END) - cursor = stream.tell() - 2 - while cursor >= 0: - stream.seek(cursor) - if stream.read(1) == b"\n": - break - cursor -= 1 - stream.seek(cursor + 1) - raw = stream.readline() + cursor = end - 2 + tail_start = 0 + while cursor >= 0: + chunk_start = max(0, cursor - 4095) + stream.seek(chunk_start) + chunk = stream.read(cursor - chunk_start + 1) + newline = chunk.rfind(b"\n") + if newline >= 0: + tail_start = chunk_start + newline + 1 + break + cursor = chunk_start - 1 + stream.seek(tail_start) + raw = stream.readline() try: if not raw.endswith(b"\n"): raise ValueError("unterminated journal tail") @@ -198,8 +210,10 @@ def _sync_tail(self) -> None: def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | None = None) -> JournalRecord: with self._lock: with _exclusive_file_lock(self.path): + stream = self._open_stream() self._sync_tail() - old_size = self.path.stat().st_size if self.path.exists() else 0 + stream.seek(0, os.SEEK_END) + old_size = stream.tell() body = { "seq": self._next_seq, "event": event.value, @@ -208,16 +222,15 @@ def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | } line = json.dumps(body, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" try: - with open(self.path, "ab") as stream: - stream.write(line) - stream.flush() - os.fsync(stream.fileno()) + stream.write(line) + stream.flush() + os.fsync(stream.fileno()) except BaseException: try: - with open(self.path, "r+b") as stream: - stream.truncate(old_size) - stream.flush() - os.fsync(stream.fileno()) + stream.seek(old_size) + stream.truncate() + stream.flush() + os.fsync(stream.fileno()) except OSError: pass self._repair_and_scan() @@ -271,8 +284,7 @@ def __setstate__(self, state: dict[str, str]) -> None: self.__init__(state["root"], state["run_id"]) def _episode_journal(self, episode_key: str) -> DurableJournal: - with self._episode_journals_lock: - journal = self._episode_journals.get(episode_key) + journal = self._episode_journals.get(episode_key) if journal is not None: return journal path = self.root / "episodes" / (hashlib.sha256(episode_key.encode("utf-8")).hexdigest() + ".jsonl") diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 9a8ffae1c..67a787617 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -333,6 +333,7 @@ def __init__(self, self._action_local = threading.local() self._persistence_revision = 0 self._ready_sequence = 0 + self._submitting_episodes = set() self._events: 'queue.Queue[tuple[Any, ...]]' = queue.Queue() self._ready: deque = deque() self._ready_rows = 0 @@ -582,6 +583,7 @@ def _drop_stale(self) -> None: if self.checkpoint_manager is None: return kept = deque() + stale_groups = [] for members in self._ready: stale = [episode for episode in members if self._version - episode.version > self.max_staleness] if not stale: @@ -589,8 +591,10 @@ def _drop_stale(self) -> None: continue group = members[0].group self._ready_rows -= sum(len(episode.deliver) for episode in members) - self._retire_stale_group(group) + stale_groups.append(group) self._ready = kept + for group in stale_groups: + self._retire_stale_group(group) def _retire_stale_group(self, group: _Group) -> None: with self._actions_locked(): @@ -697,14 +701,6 @@ def _snapshot(self) -> Dict[str, Any]: 'lease': self._lease, } - @contextmanager - def _condition_released(self): - lock_state = self._lock._release_save() - try: - yield - finally: - self._lock._acquire_restore(lock_state) - @contextmanager def _durable_io_locked(self): self._persistence_lock.acquire() @@ -739,6 +735,16 @@ def _defer_action(self, action: Callable[[], Any]) -> None: else: actions.append(action) + def _run_episode_action(self, episode: _Episode, action: Callable[[], Any]) -> None: + with self._lock: + group = episode.group + current = not self._closed and not episode.lost and group.key in self._groups and ( + episode.episode_id in self._submitting_episodes + or any(item is episode for item in group.members + group.baselines) + ) + if current: + action() + def _next_persistence_revision(self) -> int: self._persistence_revision += 1 return self._persistence_revision @@ -773,7 +779,7 @@ def _persist_group_locked(self, group: _Group) -> None: if self.resume_store is None: return record = self._group_record(group) - with self._condition_released(): + with self._durable_io_locked(): self.resume_store.save_object('driver-groups', group.state_key, record) def _persist_event_locked( @@ -807,12 +813,25 @@ def state_dict(self) -> Dict[str, Any]: pretending the in-memory partial response is durable. """ with self._lock: + if self.resume_store is None: + return self._snapshot() state = self._snapshot() - if self.resume_store is not None: - head = self._head_state() - with self._durable_io_locked(): - self.resume_store.save_object('driver', self.run_id, state) - self.resume_store.save_object('driver-head', self.run_id, head) + records = [ + (group.state_key, self._group_record(group)) for group in self._groups.values() + ] + for order, members in enumerate(self._ready, 1): + if not members: + continue + group = members[0].group + record = self._group_record(group, ready=True) + record['ready_order'] = order + records.append((group.state_key, record)) + head = self._head_state() + with self._durable_io_locked(): + for state_key, record in records: + self.resume_store.save_object('driver-groups', state_key, record) + self.resume_store.save_object('driver', self.run_id, state) + self.resume_store.save_object('driver-head', self.run_id, head) return state def _restore_episode(self, state: Dict[str, Any], group: _Group) -> _Episode: @@ -867,6 +886,8 @@ def _restore_group(self, state: Dict[str, Any]) -> _Group: return group def _restore_deliveries(self) -> None: + if self.resume_store is None: + return restore = getattr(self.rollout, "restore_delivery", None) if not callable(restore): return @@ -1318,12 +1339,18 @@ def _submit(self, group: _Group, traj: Any, role: str, slot: int) -> _Episode: state_key=f'{self.run_id}/group/{group.key}/attempt/{group.attempt}/{kind}/{slot}') if group.adapter_path is not None: traj['adapter_path'] = group.adapter_path + elif self.resume_store is not None: + traj['use_base_model'] = True if self.prms and self.resume_store is not None: traj['_resume_segments'] = True episode.submit_traj = traj self._inflight += 1 episode.counted_inflight = True - self._step(episode, traj) + self._submitting_episodes.add(episode.episode_id) + try: + self._step(episode, traj) + finally: + self._submitting_episodes.discard(episode.episode_id) return episode def _step(self, episode: _Episode, traj: Any) -> None: @@ -1339,7 +1366,7 @@ def _done(f, episode=episode): future.add_done_callback(_done) - self._defer_action(submit) + self._defer_action(lambda: self._run_episode_action(episode, submit)) # ------------------------------------------------------------------ completions @@ -1392,7 +1419,10 @@ def _on_step(self, episode: _Episode, trajs: Any, sample: RolloutStatus) -> None episode.sample = sample episode.done = bool(sample.done) if episode.done: - episode.deliver = list(trajs) + episode.deliver = [dict(row) if isinstance(row, dict) else row for row in trajs] + for row in episode.deliver: + if isinstance(row, dict): + row.pop('use_base_model', None) if self.prms and episode.role != _BASELINE and (episode.done or self.prm_segment is None or self.prm_segment(sample, trajs[0])): segment = self._score_prm(episode) @@ -1424,7 +1454,7 @@ def submit(prm=prm, scorer=scorer): ) _record_driver_probe("score_submitted", episode.episode_id, kind="prm", segment=segment) - self._defer_action(submit) + self._defer_action(lambda: self._run_episode_action(episode, submit)) return segment def _release(self, episode: _Episode, segment: int) -> None: @@ -1448,7 +1478,7 @@ def submit(orm=orm, index=index): ) _record_driver_probe("score_submitted", episode.episode_id, kind="orm") - self._defer_action(submit) + self._defer_action(lambda: self._run_episode_action(episode, submit)) self._maybe_finish(episode) def _fail(self, episode: _Episode, exc: BaseException) -> None: @@ -1643,45 +1673,32 @@ def _accept(self, group: _Group) -> None: def _accept_locked(self, group: _Group) -> None: del self._groups[group.key] members = list(group.members) - if self.resume_store is None: - self._ready.append(members) - self._ready_rows += sum(len(episode.deliver) for episode in members) - _record_driver_probe( - "group_ready", - members[0].episode_id if members else "", - group=group.key, - ready_rows=self._ready_rows, + if self.resume_store is not None: + self._ready_sequence += 1 + self._persist_event_locked( + JournalEvent.GROUP_READY, + group.state_key, + { + "group_key": group.key, + "binding": group.binding.to_dict(), + "attempt": group.attempt, + "episodes": [episode.episode_id for episode in group.members], + }, + group=group, + ready=True, ) - return - self._ready_sequence += 1 - self._persist_event_locked( - JournalEvent.GROUP_READY, - group.state_key, - { - "group_key": group.key, - "binding": group.binding.to_dict(), - "attempt": group.attempt, - "episodes": [episode.episode_id for episode in group.members], - }, - group=group, - ready=True, + self._ready.append(members) + self._ready_rows += sum(len(episode.deliver) for episode in members) + if self.resume_store is not None: + self._lock.notify_all() + self._defer_action(lambda: self._discard_group_state(group, deliveries=False)) + _record_driver_probe( + "group_ready", + members[0].episode_id if members else "", + group=group.key, + ready_rows=self._ready_rows, ) - def publish_ready(): - self._discard_group_state(group, deliveries=False) - with self._lock: - self._ready.append(members) - self._ready_rows += sum(len(episode.deliver) for episode in members) - self._lock.notify_all() - _record_driver_probe( - "group_ready", - members[0].episode_id if members else "", - group=group.key, - ready_rows=self._ready_rows, - ) - - self._defer_action(publish_ready) - def _drop_group(self, group: _Group) -> None: with self._actions_locked(): self._drop_group_locked(group) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 27122c243..d88c32c06 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -28,6 +28,7 @@ import shlex import shutil import signal +import stat import subprocess import sys import tempfile @@ -162,17 +163,18 @@ def _file_signature(stat_result: os.stat_result) -> Dict[str, int]: } @staticmethod - def _workspace_entries(root: Path) -> Tuple[List[str], List[Tuple[str, Path]]]: + def _workspace_entries(root: Path, *, with_stats: bool = False): directories = [] files = [] for path in sorted(root.rglob('*')): - if path.is_symlink(): + stat_result = path.lstat() + if stat.S_ISLNK(stat_result.st_mode): raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') relative = path.relative_to(root).as_posix() - if path.is_dir(): + if stat.S_ISDIR(stat_result.st_mode): directories.append(relative) - elif path.is_file(): - files.append((relative, path)) + elif stat.S_ISREG(stat_result.st_mode): + files.append((relative, path, stat_result) if with_stats else (relative, path)) else: raise UnsafeCheckpoint(f'workspace snapshot refuses non-regular file {path}') return directories, files @@ -208,24 +210,29 @@ def _copy_snapshot_file(source: Path, destination: Path) -> None: shutil.copy2(source, destination) @staticmethod - def _restore_file(source: Path, destination: Path) -> None: - destination.parent.mkdir(parents=True, exist_ok=True) + def _restore_file(source: Path, destination: Path, *, copy_metadata: bool = True) -> None: if os.name != 'nt': try: import fcntl with open(source, 'rb') as source_stream, open(destination, 'wb') as target_stream: fcntl.ioctl(target_stream.fileno(), 0x40049409, source_stream.fileno()) - shutil.copystat(source, destination) + if copy_metadata: + shutil.copystat(source, destination) return except (ImportError, OSError): destination.unlink(missing_ok=True) - shutil.copy2(source, destination) + if copy_metadata: + shutil.copy2(source, destination) + else: + shutil.copyfile(source, destination) - def _mark_snapshot_verified(self, generation_root: Path, workspace: Dict[str, Any]) -> None: + def _mark_snapshot_verified(self, generation_root: Path, workspace: Dict[str, Any], entries=None) -> None: source = generation_root / 'workspace' + if entries is None: + _directories, entries = self._workspace_entries(source, with_stats=True) signatures = { - item['path']: self._file_signature((source / item['path']).stat()) - for item in workspace['files'] + relative: self._file_signature(stat_result) + for relative, _path, stat_result in entries } self._verified_snapshots[str(generation_root)] = { 'digest': workspace['digest'], @@ -239,29 +246,30 @@ def _snapshot_cache_valid(self, generation_root: Path, workspace: Dict[str, Any] return False source = generation_root / 'workspace' try: - directories, files = self._workspace_entries(source) - if directories != verified['directories'] or [path for path, _ in files] != list(verified['files']): + directories, files = self._workspace_entries(source, with_stats=True) + if directories != verified['directories'] or [path for path, _path, _stat in files] != list( + verified['files']): return False return all( - self._file_signature(path.stat()) == verified['files'][relative] - for relative, path in files + self._file_signature(stat_result) == verified['files'][relative] + for relative, _path, stat_result in files ) except OSError: return False def _verify_v2_workspace(self, generation_root: Path, workspace: Dict[str, Any]) -> None: source = generation_root / 'workspace' - directories, entries = self._workspace_entries(source) - if directories != workspace['directories'] or [path for path, _ in entries] != [ + directories, entries = self._workspace_entries(source, with_stats=True) + if directories != workspace['directories'] or [path for path, _path, _stat in entries] != [ item['path'] for item in workspace['files']]: raise UnsafeCheckpoint('LocalEnv snapshot workspace file set mismatch') - for item, (relative, path) in zip(workspace['files'], entries, strict=True): + for item, (relative, path, _stat_result) in zip(workspace['files'], entries, strict=True): file_digest, size = self._hash_file(path) if size != item['size'] or file_digest != item['sha256']: raise UnsafeCheckpoint(f'LocalEnv snapshot file checksum mismatch: {relative}') if self._manifest_digest(workspace['files'], directories) != workspace['digest']: raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') - self._mark_snapshot_verified(generation_root, workspace) + self._mark_snapshot_verified(generation_root, workspace, entries) @remote_function(enable_continous_work=True, sticky_key='episode_id') def checkpoint_episode(self, episode_id: str, state_key: str, @@ -296,7 +304,7 @@ def checkpoint_episode(self, episode_id: str, state_key: str, previous_files = { item['path']: item for item in (previous_manifest or {}).get('workspace', {}).get('files', []) } if previous_manifest and previous_manifest['format'] == 'twinkle.localenv.v2' else {} - directories, source_files = self._workspace_entries(Path(state.workspace)) + directories, source_files = self._workspace_entries(Path(state.workspace), with_stats=True) generation_root = key_root / generation workspace_copy = generation_root / 'workspace' generation_root.mkdir(parents=True, exist_ok=False) @@ -307,8 +315,7 @@ def checkpoint_episode(self, episode_id: str, state_key: str, files = [] total = 0 reused_unverified = False - for relative, source_path in source_files: - source_stat = source_path.stat() + for relative, source_path, source_stat in source_files: source_signature = self._file_signature(source_stat) destination = workspace_copy / relative old = previous_files.get(relative) @@ -411,10 +418,12 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] if snapshot_format == 'twinkle.localenv.v1': shutil.copytree(source, target, dirs_exist_ok=True) else: - for relative in workspace['directories']: - (target / relative).mkdir(parents=True, exist_ok=True) - for item in workspace['files']: - self._restore_file(source / item['path'], target / item['path']) + shutil.copytree( + source, target, dirs_exist_ok=True, + copy_function=lambda src, dst: self._restore_file( + Path(src), Path(dst), copy_metadata=False + ), + ) except BaseException: self.close(episode_id) raise diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index e2d76789c..83fb5e3ea 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -433,6 +433,7 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara #: Behavior-policy binding for the whole episode. A resumed group keeps this adapter even #: after the sampler's mutable default has moved on to a newer policy. self.adapter_path: Optional[str] = trajectory.get('adapter_path') + self.use_base_model = bool(trajectory.get('use_base_model')) #: Effects already represented by the latest durable episode checkpoint. self.completed_effects: set[str] = set() @@ -637,6 +638,7 @@ def _capture_episode(self, ep: _Episode, *, allow_busy: bool = False) -> dict[st 'ledger': ep.ledger.state_dict(), 'env_state': env_state, 'env_open': ep.env_open, + 'use_base_model': ep.use_base_model, 'budget': ep.budget, 'spent': ep.spent, 'followups': ep.followups, @@ -704,6 +706,7 @@ def restore_episode(self, state: dict[str, Any]) -> str: raise UnsafeResume('message-ledger episodes lose sampled token ids and cannot be resumed safely') ep.ledger.load_state_dict(state['ledger']) ep.env_open = bool(state.get('env_open')) + ep.use_base_model = bool(state.get('use_base_model', ep.use_base_model)) if ep.env_open: if self.env is None: raise UnsafeResume('checkpoint has an environment state but this rollout has no env') @@ -968,6 +971,7 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: traj = ep.ledger.merge( ep.trajectory, turns=ep.ledger.turns, stop_reason=ep.stop_reason, truncated=ep.truncated, segment_index=len(ep.closed_rows), **fields) + traj.pop('use_base_model', None) if ep.error is not None: traj['error'] = ep.error episode_end = None @@ -1018,6 +1022,7 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: if episode_end is not None: traj['episode_end'] = episode_end for row in ep.closed_rows: + row.pop('use_base_model', None) # The frozen rows carry the episode's env reward too: the reward keys belong to # the episode, and every row of it carries the same ones. row_rewards = dict(row.get("rewards") or {}) @@ -1214,6 +1219,9 @@ def _generate(self, ep: _Episode, ledger, params: SamplingParams) -> SampledSequ adapter_kwargs = dict(self._adapter_kwargs) if ep.adapter_path is not None: adapter_kwargs['adapter_path'] = ep.adapter_path + if ep.use_base_model: + adapter_kwargs.pop('adapter_path', None) + adapter_kwargs['use_base_model'] = True responses = self.sampler.sample([ledger.state if use_state else ledger.input_feature], sampling_params=params, session_id=ep.episode_id, diff --git a/tests/twinkle_agentic/test_multi_turn_resume.py b/tests/twinkle_agentic/test_multi_turn_resume.py index a4112a43b..1a32dca73 100644 --- a/tests/twinkle_agentic/test_multi_turn_resume.py +++ b/tests/twinkle_agentic/test_multi_turn_resume.py @@ -19,10 +19,12 @@ def _rollout(store=None): return MultiTurnRollout(response_callback=lambda *args: None, template=_Template(), resume_store=store) -def _episode(rollout, state_key="run/group-0/episode-0/attempt-0", adapter_path=None): +def _episode(rollout, state_key="run/group-0/episode-0/attempt-0", adapter_path=None, use_base_model=False): trajectory = {"messages": [{"role": "user", "content": "hello"}], "state_key": state_key} if adapter_path is not None: trajectory["adapter_path"] = adapter_path + if use_base_model: + trajectory["use_base_model"] = True ep = _Episode("episode-0", trajectory, rollout._params(SamplingParams())) ep.ledger = rollout._new_ledger("episode-0") ep.ledger._pif = { @@ -245,6 +247,40 @@ def sample(self, _inputs, sampling_params=None, *, adapter_path=None, **_kwargs) assert sampler.adapter_paths == ["/policies/policy-1.adapter"] +def test_episode_explicit_base_route_overrides_mutable_default_and_survives_restore(tmp_path): + class _Sampler: + accepts_rollout_state = False + + def __init__(self): + self.calls = [] + + def sample(self, _inputs, sampling_params=None, *, adapter_path=None, use_base_model=False, **_kwargs): + self.calls.append((adapter_path, use_base_model)) + return [ + SampleResponse( + sequences=[SampledSequence(stop_reason="stop", tokens=[7], logprobs=[[(7, -0.1)]], decoded="x")] + ) + ] + + store = ResumeStore(tmp_path, "run") + sampler = _Sampler() + rollout = MultiTurnRollout(sampler=sampler, template=_Template(), resume_store=store) + episode = _episode(rollout, use_base_model=True) + rollout._episodes[episode.episode_id] = episode + rollout._generate(episode, type("Ledger", (), {"state": None, "input_feature": {}})(), SamplingParams()) + assert sampler.calls == [(None, True)] + rollout.checkpoint_episode(episode.episode_id) + + restored = MultiTurnRollout(sampler=sampler, template=_Template(), resume_store=store) + restored.restore_episode_from_store(episode.state_key) + restored_episode = restored._episodes[episode.episode_id] + assert restored_episode.use_base_model + restored._generate( + restored_episode, type("Ledger", (), {"state": None, "input_feature": {}})(), SamplingParams() + ) + assert sampler.calls == [(None, True), (None, True)] + + def test_next_turn_persists_the_completed_generation_boundary(tmp_path): store = ResumeStore(tmp_path, "run") rollout = _rollout(store) diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index df8c833ca..334f2ea58 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -1,5 +1,4 @@ import errno -import os import threading import time from concurrent.futures import ThreadPoolExecutor @@ -193,6 +192,57 @@ def interrupted_replace(_source, _target): assert list(target.parent.glob("*.tmp")) == [] +def test_atomic_replace_retries_transient_permission_errors_observably(tmp_path, monkeypatch): + target = tmp_path / "state.resume" + atomic_write_bytes(target, b"old") + from twinkle.utils import utils as atomic_utils + + original = atomic_utils.os.replace + attempts = [] + warnings = [] + sleeps = [] + + def transient(source, destination): + attempts.append((source, destination)) + if len(attempts) < 3: + raise PermissionError(5, "scanner owns the destination") + return original(source, destination) + + monkeypatch.setattr(atomic_utils.os, "replace", transient) + monkeypatch.setattr(atomic_utils.time, "sleep", sleeps.append) + monkeypatch.setattr(atomic_utils.logger, "warning", lambda *args: warnings.append(args)) + atomic_write_bytes(target, b"new") + + assert target.read_bytes() == b"new" + assert len(attempts) == 3 + assert len(warnings) == 2 + assert len(sleeps) == 2 + + +def test_atomic_replace_exhaustion_preserves_target_and_fails_closed(tmp_path, monkeypatch): + target = tmp_path / "state.resume" + atomic_write_bytes(target, b"old") + from twinkle.utils import utils as atomic_utils + + attempts = [] + errors = [] + + def persistent(_source, _destination): + attempts.append(1) + raise PermissionError(5, "destination remains locked") + + monkeypatch.setattr(atomic_utils.os, "replace", persistent) + monkeypatch.setattr(atomic_utils.time, "sleep", lambda _delay: None) + monkeypatch.setattr(atomic_utils.logger, "error", lambda *args: errors.append(args)) + with pytest.raises(PermissionError, match="destination remains locked"): + atomic_write_bytes(target, b"new") + + assert len(attempts) == 6 + assert len(errors) == 1 + assert target.read_bytes() == b"old" + assert list(target.parent.glob("*.tmp")) == [] + + def _ready_driver(tmp_path, run_id): store = ResumeStore(tmp_path, run_id) driver = StreamingDriver( diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index 5c1109c75..62f8bd6a2 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -30,6 +30,17 @@ def test_journal_repairs_only_a_torn_final_line(tmp_path): ] +def test_journal_reused_stream_reads_a_long_tail_in_chunks(tmp_path): + journal = DurableJournal(tmp_path / "rollout.jsonl") + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/long", {"payload": "x" * 9000}) + + record = journal.append(JournalEvent.GROUP_READY, "run/next") + + assert record.seq == 1 + reloaded = DurableJournal(journal.path) + assert [item.state_key for item in reloaded.records()] == ["run/long", "run/next"] + + def test_journal_refuses_damage_before_a_complete_later_record(tmp_path): path = tmp_path / "rollout.jsonl" journal = DurableJournal(path) diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 8122d7b2f..babcc211d 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -213,8 +213,11 @@ def test_default_driver_keeps_fixed_admission_window_across_versions(): driver._version = 6 assert driver._capacity() == initial_capacity driver._version = 0 + driver._start() for version in range(8): manager._version = version + expected_admitted = min(16, 2 * (version + 2)) + _wait_until(lambda: driver.stats()["admitted"] >= expected_admitted) batch = driver._next_batch() assert batch is not None, (version, driver.stats()) rows, _ = batch @@ -795,7 +798,7 @@ def test_selective_prm_segments_are_cleaned_at_ready_and_commit(tmp_path): ) driver._start() _wait_until(lambda: driver._ready_rows == 1) - assert not _segment_objects(tmp_path) + _wait_until(lambda: not _segment_objects(tmp_path)) rows, _ = driver._next_batch() assert len(rows) == 1 driver.commit_batch("checkpoint-1") @@ -919,6 +922,8 @@ def state_dict(self): def record_save(scope, key, value): writes.append((scope, key)) + assert driver._persistence_lock.locked() + assert not driver._lock._is_owned() return original_save(scope, key, value) monkeypatch.setattr(store, "save_object", record_save) @@ -1065,3 +1070,176 @@ def test_manual_snapshot_also_refreshes_the_automatic_v2_head(tmp_path): assert restored._version == 3 assert list(restored._groups) == ["0"] restored.close() + + +def test_drop_stale_replaces_ready_deque_before_releasing_lock_for_io(tmp_path, monkeypatch): + store = ResumeStore(tmp_path, "run-deque-race") + manager = _PolicyManager(0, {0: None}) + driver = StreamingDriver( + _prompts(1), _DoneRollout(), batch_size=1, num_generations=1, max_staleness=0, + checkpoint_manager=manager, resume_store=store, + ) + driver._admit() + driver._handle(*driver._events.get_nowait()) + assert driver._ready_rows == 1 + driver._version = 1 + manager._version = 1 + writing = threading.Event() + release = threading.Event() + original_save = store.save_object + + def blocked_save(scope, key, value): + if scope == "driver-head": + writing.set() + assert release.wait(2) + return original_save(scope, key, value) + + monkeypatch.setattr(store, "save_object", blocked_save) + errors = [] + + def drop(): + try: + with driver._lock: + driver._drop_stale() + except BaseException as exc: + errors.append(exc) + + trainer = threading.Thread(target=drop) + trainer.start() + assert writing.wait(1) + with driver._lock: + driver._ready.append("concurrent-ready-sentinel") + release.set() + trainer.join(2) + + assert not trainer.is_alive() + assert errors == [] + assert list(driver._ready) == ["concurrent-ready-sentinel"] + driver._ready.clear() + driver._ready_rows = 0 + driver.close() + + +def test_durable_ready_is_visible_before_blocked_terminal_cleanup(tmp_path): + entered = threading.Event() + release = threading.Event() + + class BlockingCleanupRollout(_DoneRollout): + def discard_episode_state(self, state_key): + entered.set() + assert release.wait(3) + super().discard_episode_state(state_key) + + store = ResumeStore(tmp_path, "run-ready-cleanup") + driver = StreamingDriver( + _prompts(1), BlockingCleanupRollout(), batch_size=1, num_generations=1, max_staleness=1, + resume_store=store, + ) + try: + driver._admit() + assert driver._exhausted + driver._start() + assert entered.wait(2) + assert driver._exhausted + assert driver._inflight == 0 + batch = driver._next_batch() + assert batch is not None + assert len(batch[0]) == 1 + finally: + release.set() + driver.close() + + +@pytest.mark.parametrize("ready", [False, True]) +def test_legacy_v1_store_survives_snapshot_and_second_automatic_restore(tmp_path, ready): + run_id = "run-legacy-v1-ready" if ready else "run-legacy-v1-active" + legacy_rollout = _DoneRollout() if ready else _BlockingRollout() + legacy = StreamingDriver( + _prompts(1), legacy_rollout, batch_size=1, num_generations=1, max_steps=1, run_id=run_id + ) + legacy._admit() + if ready: + legacy._handle(*legacy._events.get_nowait()) + assert legacy._ready_rows == 1 + state = legacy.state_dict() + store = ResumeStore(tmp_path, run_id) + store.save_object("driver", run_id, state) + assert not store.has_object("driver-head", run_id) + assert store.load_objects("driver-groups") == [] + legacy.close() + + upgraded_rollout = _DoneRollout() if ready else _BlockingRollout() + upgraded = StreamingDriver( + _prompts(1), upgraded_rollout, batch_size=1, num_generations=1, max_steps=1, + resume_store=store, run_id=run_id, + ) + upgraded.load_state_dict() + upgraded.state_dict() + assert store.has_object("driver-head", run_id) + assert len(store.load_objects("driver-groups")) == 1 + upgraded.close() + + restored_rollout = _DoneRollout() if ready else _BlockingRollout() + restored = StreamingDriver( + _prompts(1), restored_rollout, batch_size=1, num_generations=1, max_steps=1, + resume_store=store, run_id=run_id, + ) + restored.load_state_dict() + if ready: + assert restored._ready_rows == 1 + else: + assert list(restored._groups) == ["0"] + restored.close() + + +def test_queued_step_and_score_actions_are_dropped_after_group_cleanup(tmp_path): + store = ResumeStore(tmp_path, "run-stale-actions") + rollout = _BlockingRollout() + scores = [] + + def orm(_rows): + scores.append("called") + return _Future([1.0]) + + driver = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, orms=[orm], resume_store=store + ) + driver._admit() + group = driver._groups["0"] + episode = group.members[0] + actions = [] + driver._action_local.items = actions + driver._step(episode, episode.submit_traj) + driver._score_orm(episode) + del driver._action_local.items + driver._drop_group(group) + calls_after_cleanup = len(rollout.calls) + + for action in actions: + action() + + assert len(rollout.calls) == calls_after_cleanup + assert scores == [] + driver.close() + + +def test_explicit_legacy_state_without_store_does_not_restore_deliveries(): + run_id = "run-explicit-no-store" + source = StreamingDriver( + _prompts(1), _DoneRollout(), batch_size=1, num_generations=1, max_steps=1, run_id=run_id + ) + source._admit() + source._handle(*source._events.get_nowait()) + state = source.state_dict() + source.close() + + class LegacyRollout(_DoneRollout): + def restore_delivery(self, state_key): + raise UnsafeResume("restore_delivery requires a store") + + restored = StreamingDriver( + _prompts(1), LegacyRollout(), batch_size=1, num_generations=1, max_steps=1, run_id=run_id + ) + restored.load_state_dict(state) + assert restored._ready_rows == 1 + restored.close() diff --git a/tests/twinkle_client/test_checkpoint_policy_history.py b/tests/twinkle_client/test_checkpoint_policy_history.py index a8e80ea9e..a678c2231 100644 --- a/tests/twinkle_client/test_checkpoint_policy_history.py +++ b/tests/twinkle_client/test_checkpoint_policy_history.py @@ -6,6 +6,7 @@ import pytest from twinkle_agentic.async_rl import StreamingDriver +from twinkle_agentic.async_rl.rollout_resume import ResumeStore from twinkle_client.rollout import ClientCheckpointManager @@ -101,3 +102,47 @@ def step(self, trajectory, **_kwargs): assert group.version == 1 assert group.adapter_path == sampler.adapter_path assert rollout.trajectory["adapter_path"] == sampler.adapter_path + + +def test_first_save_concurrent_with_v0_admission_keeps_explicit_base_route(tmp_path): + entered = threading.Event() + release = threading.Event() + + class _BlockingModel(_Model): + def save(self, name, **kwargs): + entered.set() + assert release.wait(timeout=3) + return super().save(name, **kwargs) + + sampler = _Sampler() + manager = ClientCheckpointManager(_BlockingModel(), sampler) + store = ResumeStore(tmp_path, "run-v0-base") + + class _Rollout: + def step(self, trajectory, **_kwargs): + self.trajectory = trajectory + return SimpleNamespace(add_done_callback=lambda _callback: None) + + def stop(self, *_args, **_kwargs): + return None + + rollout = _Rollout() + driver = StreamingDriver( + [{"messages": []}], rollout, batch_size=1, num_generations=1, + checkpoint_manager=manager, resume_store=store, run_id="run-v0-base", + ) + with ThreadPoolExecutor(max_workers=1) as pool: + saving = pool.submit(manager.sync_weights) + assert entered.wait(timeout=1) + driver._version = manager.version() + driver._admit() + group = driver._groups["0"] + assert group.version == 0 + assert group.adapter_path is None + assert rollout.trajectory["use_base_model"] is True + assert "adapter_path" not in rollout.trajectory + release.set() + saving.result(timeout=1) + assert manager.version() == 1 + assert rollout.trajectory["use_base_model"] is True + driver.close() From a91d528eb2be034676fc8f9271896d9b005b0e23 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 14:35:06 +0800 Subject: [PATCH 33/45] perf(agentic): verify LocalEnv restores without slow hashing --- src/twinkle_agentic/envs/localenv.py | 51 ++++++++++++++----- tests/twinkle_agentic/test_localenv_resume.py | 28 ++++++++-- 2 files changed, 62 insertions(+), 17 deletions(-) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index d88c32c06..adc10c958 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -181,13 +181,9 @@ def _workspace_entries(root: Path, *, with_stats: bool = False): @staticmethod def _hash_file(path: Path) -> Tuple[str, int]: - digest = hashlib.sha256() - size = 0 with open(path, 'rb') as stream: - while chunk := stream.read(1024 * 1024): - digest.update(chunk) - size += len(chunk) - return digest.hexdigest(), size + digest = hashlib.file_digest(stream, 'sha256') + return digest.hexdigest(), stream.tell() @staticmethod def _manifest_digest(files: List[Dict[str, Any]], directories: List[str]) -> str: @@ -221,11 +217,29 @@ def _restore_file(source: Path, destination: Path, *, copy_metadata: bool = True return except (ImportError, OSError): destination.unlink(missing_ok=True) - if copy_metadata: + if copy_metadata or os.name == 'nt': shutil.copy2(source, destination) else: shutil.copyfile(source, destination) + @staticmethod + def _restore_and_hash_file(source: Path, destination: Path) -> Tuple[str, int]: + file_digest, size = LocalEnv._hash_file(source) + if os.name != 'nt': + try: + import fcntl + with open(source, 'rb') as source_stream, open(destination, 'wb') as target_stream: + fcntl.ioctl(target_stream.fileno(), 0x40049409, source_stream.fileno()) + shutil.copystat(source, destination) + return file_digest, size + except (ImportError, OSError): + destination.unlink(missing_ok=True) + shutil.copyfile(source, destination) + shutil.copystat(source, destination) + else: + shutil.copy2(source, destination) + return file_digest, size + def _mark_snapshot_verified(self, generation_root: Path, workspace: Dict[str, Any], entries=None) -> None: source = generation_root / 'workspace' if entries is None: @@ -257,16 +271,26 @@ def _snapshot_cache_valid(self, generation_root: Path, workspace: Dict[str, Any] except OSError: return False - def _verify_v2_workspace(self, generation_root: Path, workspace: Dict[str, Any]) -> None: + def _restore_v2_workspace(self, generation_root: Path, workspace: Dict[str, Any], target: Path) -> None: source = generation_root / 'workspace' directories, entries = self._workspace_entries(source, with_stats=True) if directories != workspace['directories'] or [path for path, _path, _stat in entries] != [ item['path'] for item in workspace['files']]: raise UnsafeCheckpoint('LocalEnv snapshot workspace file set mismatch') - for item, (relative, path, _stat_result) in zip(workspace['files'], entries, strict=True): - file_digest, size = self._hash_file(path) + for relative in directories: + (target / relative).mkdir(parents=True, exist_ok=True) + for item, (relative, path, initial_stat) in zip(workspace['files'], entries, strict=True): + destination = target / relative + file_digest, size = self._restore_and_hash_file(path, destination) if size != item['size'] or file_digest != item['sha256']: raise UnsafeCheckpoint(f'LocalEnv snapshot file checksum mismatch: {relative}') + final_stat = path.lstat() + if not stat.S_ISREG(final_stat.st_mode) or self._file_signature(final_stat) != self._file_signature( + initial_stat): + raise UnsafeCheckpoint(f'LocalEnv snapshot file changed during restore: {relative}') + for relative in reversed(directories): + shutil.copystat(source / relative, target / relative) + shutil.copystat(source, target) if self._manifest_digest(workspace['files'], directories) != workspace['digest']: raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') self._mark_snapshot_verified(generation_root, workspace, entries) @@ -406,8 +430,9 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] if snapshot_format == 'twinkle.localenv.v1': if self._tree_digest(source)['digest'] != workspace['digest']: raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') - elif not self._snapshot_cache_valid(generation_root, workspace): - self._verify_v2_workspace(generation_root, workspace) + cold_v2 = snapshot_format == 'twinkle.localenv.v2' and not self._snapshot_cache_valid( + generation_root, workspace + ) self.reset(episode_id, trajectory) try: @@ -417,6 +442,8 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] target = Path(self.workspace(episode_id)) if snapshot_format == 'twinkle.localenv.v1': shutil.copytree(source, target, dirs_exist_ok=True) + elif cold_v2: + self._restore_v2_workspace(generation_root, workspace, target) else: shutil.copytree( source, target, dirs_exist_ok=True, diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index db7a602aa..40c28de6a 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -141,14 +141,14 @@ def test_cold_restore_hashes_but_warm_restore_reuses_only_verified_storage(tmp_p env.step("source", "write_file", {"path": "state.txt", "content": "snapshot"}) state_key = "run-1/group-0/episode-1/attempt-0" snapshot = env.checkpoint_episode("source", state_key) - original_hash = LocalEnv._hash_file + original_restore = LocalEnv._restore_and_hash_file hashed = [] - def tracked(path): - hashed.append(str(path)) - return original_hash(path) + def tracked(source, destination): + hashed.append(str(source)) + return original_restore(source, destination) - monkeypatch.setattr(LocalEnv, "_hash_file", staticmethod(tracked)) + monkeypatch.setattr(LocalEnv, "_restore_and_hash_file", staticmethod(tracked)) env.restore_episode("warm", state_key, snapshot) assert hashed == [] @@ -168,6 +168,24 @@ def tracked(path): assert stored.read_text(encoding="utf-8") == "snapshot" +def test_cold_restore_rejects_snapshot_changed_during_copy(tmp_path, monkeypatch): + env = LocalEnv(root=str(tmp_path)) + env.reset("source") + env.step("source", "write_file", {"path": "state.txt", "content": "snapshot"}) + state_key = "run-1/group-0/episode-1/attempt-0" + snapshot = env.checkpoint_episode("source", state_key) + original_restore = LocalEnv._restore_and_hash_file + + def corrupt_before_copy(source, destination): + source.write_text("tampered", encoding="utf-8") + return original_restore(source, destination) + + monkeypatch.setattr(LocalEnv, "_restore_and_hash_file", staticmethod(corrupt_before_copy)) + cold = LocalEnv(root=str(tmp_path)) + with pytest.raises(UnsafeCheckpoint, match="checksum mismatch"): + cold.restore_episode("cold", state_key, snapshot) + + def test_v1_snapshot_remains_restorable(tmp_path): env = LocalEnv(root=str(tmp_path)) state_key = "run-1/group-0/episode-1/attempt-0" From 727d2995a047325f0a4cdc50365a70d39433d290 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 15:04:21 +0800 Subject: [PATCH 34/45] perf(agentic): finish cold LocalEnv restore optimization --- src/twinkle_agentic/envs/localenv.py | 29 ++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index adc10c958..4035adabe 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -35,6 +35,7 @@ import threading import time import uuid +from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Any, Dict, List, Optional, Tuple @@ -164,13 +165,24 @@ def _file_signature(stat_result: os.stat_result) -> Dict[str, int]: @staticmethod def _workspace_entries(root: Path, *, with_stats: bool = False): + entries = [] + pending = [(root, '')] + while pending: + directory, prefix = pending.pop() + with os.scandir(directory) as scanned: + for entry in scanned: + path = Path(entry.path) + relative = prefix + entry.name + entry_stat = entry.stat(follow_symlinks=False) + stat_result = path.lstat() if with_stats and stat.S_ISREG(entry_stat.st_mode) else entry_stat + entries.append((path, relative, stat_result)) + if stat.S_ISDIR(entry_stat.st_mode): + pending.append((path, relative + '/')) directories = [] files = [] - for path in sorted(root.rglob('*')): - stat_result = path.lstat() + for path, relative, stat_result in sorted(entries, key=lambda item: item[0]): if stat.S_ISLNK(stat_result.st_mode): raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') - relative = path.relative_to(root).as_posix() if stat.S_ISDIR(stat_result.st_mode): directories.append(relative) elif stat.S_ISREG(stat_result.st_mode): @@ -279,15 +291,16 @@ def _restore_v2_workspace(self, generation_root: Path, workspace: Dict[str, Any] raise UnsafeCheckpoint('LocalEnv snapshot workspace file set mismatch') for relative in directories: (target / relative).mkdir(parents=True, exist_ok=True) - for item, (relative, path, initial_stat) in zip(workspace['files'], entries, strict=True): + def restore(item, entry): + relative, path, _initial_stat = entry destination = target / relative file_digest, size = self._restore_and_hash_file(path, destination) if size != item['size'] or file_digest != item['sha256']: raise UnsafeCheckpoint(f'LocalEnv snapshot file checksum mismatch: {relative}') - final_stat = path.lstat() - if not stat.S_ISREG(final_stat.st_mode) or self._file_signature(final_stat) != self._file_signature( - initial_stat): - raise UnsafeCheckpoint(f'LocalEnv snapshot file changed during restore: {relative}') + + if entries: + with ThreadPoolExecutor(max_workers=min(4, len(entries))) as pool: + list(pool.map(restore, workspace['files'], entries)) for relative in reversed(directories): shutil.copystat(source / relative, target / relative) shutil.copystat(source, target) From d33472556ee44c3c8a85d3b88c47af2345440a87 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 15:24:42 +0800 Subject: [PATCH 35/45] fix(agentic): revalidate unreliable snapshot signatures --- src/twinkle_agentic/envs/localenv.py | 11 +++++- tests/twinkle_agentic/test_localenv_resume.py | 35 +++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 4035adabe..24ac58c94 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -163,6 +163,11 @@ def _file_signature(stat_result: os.stat_result) -> Dict[str, int]: 'ctime_ns': stat_result.st_ctime_ns, } + @staticmethod + def _signature_is_content_proof() -> bool: + # Windows may preserve both mtime and ctime across a fast same-size rewrite. + return os.name != 'nt' + @staticmethod def _workspace_entries(root: Path, *, with_stats: bool = False): entries = [] @@ -357,7 +362,11 @@ def checkpoint_episode(self, episode_id: str, state_key: str, destination = workspace_copy / relative old = previous_files.get(relative) old_path = previous / 'workspace' / relative if previous is not None else None - if old is not None and old.get('source') == source_signature and old_path.is_file(): + reuse = old is not None and old.get('source') == source_signature and old_path.is_file() + if reuse and not self._signature_is_content_proof(): + source_digest, source_size = self._hash_file(source_path) + reuse = source_digest == old['sha256'] and source_size == old['size'] + if reuse: reused_unverified = reused_unverified or str(previous) not in self._verified_snapshots destination.parent.mkdir(parents=True, exist_ok=True) try: diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index 40c28de6a..a6615cbf1 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -75,7 +75,8 @@ def test_localenv_checkpoint_refuses_a_running_process(tmp_path): env.close("episode-1") -def test_unchanged_generation_reuses_snapshot_content_without_live_copy_or_hash(tmp_path, monkeypatch): +@pytest.mark.parametrize("metadata_proof", [True, False]) +def test_unchanged_generation_uses_platform_appropriate_content_validation(tmp_path, monkeypatch, metadata_proof): env = LocalEnv(root=str(tmp_path)) env.reset("episode-1") env.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "unchanged"}) @@ -83,8 +84,10 @@ def test_unchanged_generation_reuses_snapshot_content_without_live_copy_or_hash( first = env.checkpoint_episode("episode-1", state_key) key_root = env._resume_root / env._state_dir_name(state_key) live_root = str(env.workspace("episode-1")) + live_file = os.path.join(live_root, "nested", "state.txt") copies = [] hashes = [] + original_hash = LocalEnv._hash_file def copy(source, destination): copies.append((str(source), str(destination))) @@ -93,19 +96,45 @@ def copy(source, destination): def hash_file(path): hashes.append(str(path)) - raise AssertionError("an unchanged file was hashed") + if metadata_proof: + raise AssertionError("a reliable-signature platform hashed unchanged content") + return original_hash(path) monkeypatch.setattr(LocalEnv, "_copy_snapshot_file", staticmethod(copy)) monkeypatch.setattr(LocalEnv, "_hash_file", staticmethod(hash_file)) + monkeypatch.setattr(LocalEnv, "_signature_is_content_proof", staticmethod(lambda: metadata_proof)) second = env.checkpoint_episode("episode-1", state_key, first["generation"]) assert copies == [] - assert hashes == [] + assert hashes == ([] if metadata_proof else [live_file]) first_file = key_root / first["generation"] / "workspace/nested/state.txt" second_file = key_root / second["generation"] / "workspace/nested/state.txt" assert os.stat(first_file).st_ino == os.stat(second_file).st_ino +def test_same_size_rewrite_is_rechecked_when_metadata_cannot_prove_content(tmp_path, monkeypatch): + env = LocalEnv(root=str(tmp_path)) + env.reset("episode-1") + env.step("episode-1", "write_file", {"path": "state.txt", "content": "old"}) + state_key = "run-1/group-0/episode-1/attempt-0" + first = env.checkpoint_episode("episode-1", state_key) + + def incomplete_signature(stat_result): + return {"dev": stat_result.st_dev, "ino": stat_result.st_ino, "size": stat_result.st_size} + + monkeypatch.setattr(LocalEnv, "_file_signature", staticmethod(incomplete_signature)) + monkeypatch.setattr(LocalEnv, "_signature_is_content_proof", staticmethod(lambda: False)) + env.step("episode-1", "write_file", {"path": "state.txt", "content": "new"}) + second = env.checkpoint_episode("episode-1", state_key, first["generation"]) + + stored = (env._resume_root / env._state_dir_name(state_key) / second["generation"] + / "workspace/state.txt") + assert stored.read_text(encoding="utf-8") == "new" + restored = LocalEnv(root=str(tmp_path)) + restored.restore_episode("cold", state_key, second) + assert restored.step("cold", "read_file", {"path": "state.txt"}).observation == "new" + + def test_incremental_generation_tracks_same_size_changes_deletes_and_empty_directories(tmp_path): env = LocalEnv(root=str(tmp_path)) env.reset("episode-1") From 57b1080fe4bd030415cf7b2df1cf98532610ff9e Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 16:27:25 +0800 Subject: [PATCH 36/45] refactor(agentic): remove Windows-specific resume paths --- src/twinkle/utils/utils.py | 24 +-------- src/twinkle_agentic/envs/localenv.py | 19 ++----- tests/twinkle_agentic/test_localenv_resume.py | 35 ++----------- .../twinkle_agentic/test_resume_boundaries.py | 51 ------------------- 4 files changed, 8 insertions(+), 121 deletions(-) diff --git a/src/twinkle/utils/utils.py b/src/twinkle/utils/utils.py index 649684edd..bc4add40c 100644 --- a/src/twinkle/utils/utils.py +++ b/src/twinkle/utils/utils.py @@ -4,35 +4,13 @@ import fnmatch import glob import inspect -import logging import os import shutil import threading -import time from functools import lru_cache from pathlib import Path from typing import Any, Callable -logger = logging.getLogger(__name__) -_REPLACE_RETRIES = 5 - - -def _replace_with_retry(source: Path, target: Path) -> None: - for attempt in range(_REPLACE_RETRIES + 1): - try: - os.replace(source, target) - return - except PermissionError: - if attempt == _REPLACE_RETRIES: - logger.error('atomic replace failed after %d attempts: %s -> %s', attempt + 1, source, target) - raise - delay = min(0.01 * (2**attempt), 0.1) - logger.warning( - 'atomic replace attempt %d/%d failed with PermissionError; retrying in %.3fs: %s -> %s', - attempt + 1, _REPLACE_RETRIES + 1, delay, source, target, - ) - time.sleep(delay) - def atomic_write_bytes(path: Path, data: bytes) -> None: """Replace ``path`` with complete bytes; the previous file survives failures.""" @@ -44,7 +22,7 @@ def atomic_write_bytes(path: Path, data: bytes) -> None: stream.write(data) stream.flush() os.fsync(stream.fileno()) - _replace_with_retry(pending, path) + os.replace(pending, path) if os.name != 'nt': descriptor = os.open(path.parent, os.O_RDONLY) try: diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 24ac58c94..a3317aeb5 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -163,11 +163,6 @@ def _file_signature(stat_result: os.stat_result) -> Dict[str, int]: 'ctime_ns': stat_result.st_ctime_ns, } - @staticmethod - def _signature_is_content_proof() -> bool: - # Windows may preserve both mtime and ctime across a fast same-size rewrite. - return os.name != 'nt' - @staticmethod def _workspace_entries(root: Path, *, with_stats: bool = False): entries = [] @@ -234,7 +229,7 @@ def _restore_file(source: Path, destination: Path, *, copy_metadata: bool = True return except (ImportError, OSError): destination.unlink(missing_ok=True) - if copy_metadata or os.name == 'nt': + if copy_metadata: shutil.copy2(source, destination) else: shutil.copyfile(source, destination) @@ -251,10 +246,8 @@ def _restore_and_hash_file(source: Path, destination: Path) -> Tuple[str, int]: return file_digest, size except (ImportError, OSError): destination.unlink(missing_ok=True) - shutil.copyfile(source, destination) - shutil.copystat(source, destination) - else: - shutil.copy2(source, destination) + shutil.copyfile(source, destination) + shutil.copystat(source, destination) return file_digest, size def _mark_snapshot_verified(self, generation_root: Path, workspace: Dict[str, Any], entries=None) -> None: @@ -362,11 +355,7 @@ def checkpoint_episode(self, episode_id: str, state_key: str, destination = workspace_copy / relative old = previous_files.get(relative) old_path = previous / 'workspace' / relative if previous is not None else None - reuse = old is not None and old.get('source') == source_signature and old_path.is_file() - if reuse and not self._signature_is_content_proof(): - source_digest, source_size = self._hash_file(source_path) - reuse = source_digest == old['sha256'] and source_size == old['size'] - if reuse: + if old is not None and old.get('source') == source_signature and old_path.is_file(): reused_unverified = reused_unverified or str(previous) not in self._verified_snapshots destination.parent.mkdir(parents=True, exist_ok=True) try: diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index a6615cbf1..40c28de6a 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -75,8 +75,7 @@ def test_localenv_checkpoint_refuses_a_running_process(tmp_path): env.close("episode-1") -@pytest.mark.parametrize("metadata_proof", [True, False]) -def test_unchanged_generation_uses_platform_appropriate_content_validation(tmp_path, monkeypatch, metadata_proof): +def test_unchanged_generation_reuses_snapshot_content_without_live_copy_or_hash(tmp_path, monkeypatch): env = LocalEnv(root=str(tmp_path)) env.reset("episode-1") env.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "unchanged"}) @@ -84,10 +83,8 @@ def test_unchanged_generation_uses_platform_appropriate_content_validation(tmp_p first = env.checkpoint_episode("episode-1", state_key) key_root = env._resume_root / env._state_dir_name(state_key) live_root = str(env.workspace("episode-1")) - live_file = os.path.join(live_root, "nested", "state.txt") copies = [] hashes = [] - original_hash = LocalEnv._hash_file def copy(source, destination): copies.append((str(source), str(destination))) @@ -96,45 +93,19 @@ def copy(source, destination): def hash_file(path): hashes.append(str(path)) - if metadata_proof: - raise AssertionError("a reliable-signature platform hashed unchanged content") - return original_hash(path) + raise AssertionError("an unchanged file was hashed") monkeypatch.setattr(LocalEnv, "_copy_snapshot_file", staticmethod(copy)) monkeypatch.setattr(LocalEnv, "_hash_file", staticmethod(hash_file)) - monkeypatch.setattr(LocalEnv, "_signature_is_content_proof", staticmethod(lambda: metadata_proof)) second = env.checkpoint_episode("episode-1", state_key, first["generation"]) assert copies == [] - assert hashes == ([] if metadata_proof else [live_file]) + assert hashes == [] first_file = key_root / first["generation"] / "workspace/nested/state.txt" second_file = key_root / second["generation"] / "workspace/nested/state.txt" assert os.stat(first_file).st_ino == os.stat(second_file).st_ino -def test_same_size_rewrite_is_rechecked_when_metadata_cannot_prove_content(tmp_path, monkeypatch): - env = LocalEnv(root=str(tmp_path)) - env.reset("episode-1") - env.step("episode-1", "write_file", {"path": "state.txt", "content": "old"}) - state_key = "run-1/group-0/episode-1/attempt-0" - first = env.checkpoint_episode("episode-1", state_key) - - def incomplete_signature(stat_result): - return {"dev": stat_result.st_dev, "ino": stat_result.st_ino, "size": stat_result.st_size} - - monkeypatch.setattr(LocalEnv, "_file_signature", staticmethod(incomplete_signature)) - monkeypatch.setattr(LocalEnv, "_signature_is_content_proof", staticmethod(lambda: False)) - env.step("episode-1", "write_file", {"path": "state.txt", "content": "new"}) - second = env.checkpoint_episode("episode-1", state_key, first["generation"]) - - stored = (env._resume_root / env._state_dir_name(state_key) / second["generation"] - / "workspace/state.txt") - assert stored.read_text(encoding="utf-8") == "new" - restored = LocalEnv(root=str(tmp_path)) - restored.restore_episode("cold", state_key, second) - assert restored.step("cold", "read_file", {"path": "state.txt"}).observation == "new" - - def test_incremental_generation_tracks_same_size_changes_deletes_and_empty_directories(tmp_path): env = LocalEnv(root=str(tmp_path)) env.reset("episode-1") diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index 334f2ea58..0f4e4ac81 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -192,57 +192,6 @@ def interrupted_replace(_source, _target): assert list(target.parent.glob("*.tmp")) == [] -def test_atomic_replace_retries_transient_permission_errors_observably(tmp_path, monkeypatch): - target = tmp_path / "state.resume" - atomic_write_bytes(target, b"old") - from twinkle.utils import utils as atomic_utils - - original = atomic_utils.os.replace - attempts = [] - warnings = [] - sleeps = [] - - def transient(source, destination): - attempts.append((source, destination)) - if len(attempts) < 3: - raise PermissionError(5, "scanner owns the destination") - return original(source, destination) - - monkeypatch.setattr(atomic_utils.os, "replace", transient) - monkeypatch.setattr(atomic_utils.time, "sleep", sleeps.append) - monkeypatch.setattr(atomic_utils.logger, "warning", lambda *args: warnings.append(args)) - atomic_write_bytes(target, b"new") - - assert target.read_bytes() == b"new" - assert len(attempts) == 3 - assert len(warnings) == 2 - assert len(sleeps) == 2 - - -def test_atomic_replace_exhaustion_preserves_target_and_fails_closed(tmp_path, monkeypatch): - target = tmp_path / "state.resume" - atomic_write_bytes(target, b"old") - from twinkle.utils import utils as atomic_utils - - attempts = [] - errors = [] - - def persistent(_source, _destination): - attempts.append(1) - raise PermissionError(5, "destination remains locked") - - monkeypatch.setattr(atomic_utils.os, "replace", persistent) - monkeypatch.setattr(atomic_utils.time, "sleep", lambda _delay: None) - monkeypatch.setattr(atomic_utils.logger, "error", lambda *args: errors.append(args)) - with pytest.raises(PermissionError, match="destination remains locked"): - atomic_write_bytes(target, b"new") - - assert len(attempts) == 6 - assert len(errors) == 1 - assert target.read_bytes() == b"old" - assert list(target.parent.glob("*.tmp")) == [] - - def _ready_driver(tmp_path, run_id): store = ResumeStore(tmp_path, run_id) driver = StreamingDriver( From 5ecc5f4ca576eb878148d33ea46631adad658fbd Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 17:09:23 +0800 Subject: [PATCH 37/45] fix(agentic): restore durable journal integrity chain --- .../Agentic/DurableRolloutResume.md" | 25 +++- .../async_rl/rollout_resume.py | 77 +++++++++++- .../test_rollout_resume_store.py | 113 ++++++++++++++++++ 3 files changed, 205 insertions(+), 10 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index d270adbad..5356e9ecb 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -105,16 +105,28 @@ checkpoint 且不再交付该 lease。调用方必须先确保模型和 optimize `ResumeStore` 由两层组成: -- `DurableJournal`:带单调序号的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 - 文件锁,以及写入失败回滚;完整扫描只在初始化或异常回滚时执行。run 控制事件保留在主日志, +- `DurableJournal`:带单调序号和 SHA-256 摘要链的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 + 文件锁,以及写入失败回滚;完整扫描和完整链校验只在初始化或异常回滚时执行。run 控制事件保留在主日志, turn/tool intent/result 按 episode 分片;旧主日志中的 episode 事件在初始化时索引并参与恢复; -- object store:保存 prompt、episode、lease、小型 driver head 和逐 group 快照,读取时校验 SHA-256。 - 普通 step/score 只写发生变化的 group;对外 `state_dict()` 仍可按需生成兼容 v1 快照。 +- object store:保存 prompt、episode、lease、小型 driver head 和逐 group 快照,读取时校验对象内容的 SHA-256。 + 对象 SHA 与 journal 记录摘要是两套独立校验,不能互相替代。普通 step/score 只写发生变化的 group; + 对外 `state_dict()` 仍可按需生成兼容 v1 快照。 + +新 journal 记录包含 `seq`、`event`、`state_key`、`payload`、`prev` 和 `digest`。`prev` 是上一条签名记录的 +`digest`;摘要输入为其余五个字段组成的对象,按 `json.dumps(..., ensure_ascii=False, sort_keys=True, +separators=(",", ":"))` 确定性编码为 UTF-8 后计算 SHA-256 十六进制摘要。正常 append 只读取尾行、验证其 +摘要并链接新记录,不按历史事件数重新扫描;初始化和异常回滚会验证每条签名记录的摘要及 `prev` 链接。 +因此,签名记录即使仍是合法 JSON 且序号正确,其中段或尾部的 payload 篡改也会拒绝恢复。 + +旧版本没有 `prev`/`digest` 的 unsigned 记录只允许作为日志前缀,已有 run 无需重写即可恢复。升级后的第一条 +签名记录以 64 个字符的全零 `prev` 起链,后续记录正常链接;签名链中间或之后不允许再插入 unsigned 记录。 +该策略只保护升级后的签名后缀,不回溯提供旧 unsigned 前缀的完整性保证,也不能检测旧前缀在升级前已经发生 +的历史篡改。每个 episode 分片独立遵守同一格式和链规则。 故障边界: - journal 最后一行未写完:仅移除没有终止换行的不完整尾部; -- 完整记录无法解码、事件非法或序号不连续:拒绝恢复; +- 完整记录无法解码、事件非法、序号不连续、摘要或 `prev` 链接不匹配:拒绝恢复; - 磁盘写入失败:回滚不确定的 append; - object 文件不完整:拒绝解码; - 旧 lease 已有 commit 记录:恢复时自动退休。 @@ -266,7 +278,8 @@ vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: 该结果只覆盖上述版本组合和单节点双卡,不回溯证明 vLLM/vLLM-Ascend 0.23.0,也不代表 FSDP2 或多节点已经验证。早期本地 overlay 的规模基准显示,journal 在 250、500、1000、2000 事件时的平均追加 延迟约为 1.89、3.53、6.71、13.16ms;该数据来自仍会全量重扫的旧实现,只用于说明当时的优化动机。 -当前正常追加只读取尾部以同步序号,完整扫描仅用于初始化或异常回滚。64MiB LocalEnv workspace 快照约 +当前正常追加只读取尾部以同步序号并校验摘要,完整扫描和完整链校验仅用于初始化或异常回滚。 +64MiB LocalEnv workspace 快照约 85ms,在该本地盘上暂不是主要瓶颈。 尚未覆盖: diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index 093701e9a..b9e3da162 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -25,6 +25,7 @@ from twinkle.utils.parallel import PosixFileLock from twinkle.utils.utils import atomic_write_bytes +_ZERO_DIGEST = "0" * 64 _OBJECT_MAGIC = b"RRS1" _PATH_LOCKS: dict[str, threading.Lock] = {} _PATH_LOCKS_GUARD = threading.Lock() @@ -121,6 +122,16 @@ class JournalRecord: event: JournalEvent state_key: str payload: dict[str, Any] + prev: str | None = None + digest: str | None = None + + +def _canonical_json(value: Any) -> bytes: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def _record_digest(record: dict[str, Any]) -> str: + return hashlib.sha256(_canonical_json(record)).hexdigest() def _object_name(key: str) -> str: @@ -128,25 +139,36 @@ def _object_name(key: str) -> str: class DurableJournal: - """Append-only JSONL journal with final-line repair and monotonic sequence numbers.""" + """Append-only JSONL journal with a hash chain and final-line repair. + + Unsigned records are accepted only as a legacy prefix. The signed suffix starts with a zero + ``prev`` value, so its integrity does not retroactively cover the legacy prefix. + """ def __init__(self, path: str | os.PathLike[str]): self.path = Path(path) self.path.parent.mkdir(parents=True, exist_ok=True) self._lock = threading.Lock() self._next_seq = 0 + self._last_digest = _ZERO_DIGEST + self._chain_started = False self._records: list[JournalRecord] = [] self._stream = None with _exclusive_file_lock(self.path): self._repair_and_scan() def _repair_and_scan(self) -> None: + self._next_seq = 0 + self._last_digest = _ZERO_DIGEST + self._chain_started = False if not self.path.exists(): + self._records = [] return data = self.path.read_bytes() offset = 0 valid_end = 0 records = [] + prev = _ZERO_DIGEST while offset < len(data): newline = data.find(b"\n", offset) if newline < 0: @@ -158,7 +180,27 @@ def _repair_and_scan(self) -> None: if seq != len(records): raise ValueError("journal sequence mismatch") event = JournalEvent(payload["event"]) - records.append(JournalRecord(seq, event, payload["state_key"], payload["payload"])) + signed = "prev" in payload or "digest" in payload + if signed: + body = { + "seq": seq, + "event": payload["event"], + "state_key": payload["state_key"], + "payload": payload["payload"], + "prev": payload["prev"], + } + digest = payload["digest"] + if body["prev"] != prev or _record_digest(body) != digest: + raise ValueError("journal hash chain mismatch") + records.append( + JournalRecord(seq, event, body["state_key"], body["payload"], body["prev"], digest) + ) + prev = digest + self._chain_started = True + else: + if self._chain_started: + raise ValueError("unsigned record after signed journal prefix") + records.append(JournalRecord(seq, event, payload["state_key"], payload["payload"])) except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: # A newline proves that a complete record was written. Only a final fragment without # one is repairable; discarding a corrupt complete commit could repeat its optimizer step. @@ -172,6 +214,7 @@ def _repair_and_scan(self) -> None: os.fsync(stream.fileno()) if records: self._next_seq = records[-1].seq + 1 + self._last_digest = prev self._records = records def _open_stream(self): @@ -185,6 +228,8 @@ def _sync_tail(self) -> None: end = stream.tell() if end == 0: self._next_seq = 0 + self._last_digest = _ZERO_DIGEST + self._chain_started = False return cursor = end - 2 tail_start = 0 @@ -204,6 +249,24 @@ def _sync_tail(self) -> None: raise ValueError("unterminated journal tail") payload = json.loads(raw.decode("utf-8")) self._next_seq = int(payload["seq"]) + 1 + signed = "prev" in payload or "digest" in payload + if signed: + body = { + "seq": int(payload["seq"]), + "event": payload["event"], + "state_key": payload["state_key"], + "payload": payload["payload"], + "prev": payload["prev"], + } + digest = payload["digest"] + if _record_digest(body) != digest: + raise ValueError("journal tail digest mismatch") + self._last_digest = digest + self._chain_started = True + else: + if self._chain_started: + raise ValueError("unsigned record after signed journal prefix") + self._last_digest = _ZERO_DIGEST except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise JournalCorrupt(f"{self.path}: corrupt journal tail: {exc}") from exc @@ -219,8 +282,12 @@ def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | "event": event.value, "state_key": state_key, "payload": payload or {}, + "prev": self._last_digest, } - line = json.dumps(body, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" + digest = _record_digest(body) + line = ( + json.dumps({**body, "digest": digest}, ensure_ascii=False, sort_keys=True).encode("utf-8") + b"\n" + ) try: stream.write(line) stream.flush() @@ -235,9 +302,11 @@ def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | pass self._repair_and_scan() raise - record = JournalRecord(self._next_seq, event, state_key, payload or {}) + record = JournalRecord(self._next_seq, event, state_key, payload or {}, self._last_digest, digest) self._records.append(record) self._next_seq += 1 + self._last_digest = digest + self._chain_started = True return record def records(self, *, state_key: str | None = None) -> Iterable[JournalRecord]: diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index 62f8bd6a2..c7d10ba6a 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -1,3 +1,4 @@ +import hashlib import json import pickle import pytest @@ -57,6 +58,100 @@ def test_journal_refuses_damage_before_a_complete_later_record(tmp_path): assert first.seq == 0 +def test_journal_detects_middle_payload_tampering_with_valid_json_and_sequence(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + for row in range(3): + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0", {"row": row}) + lines = path.read_text(encoding="utf-8").splitlines() + broken = json.loads(lines[1]) + broken["payload"]["row"] = 99 + assert broken["seq"] == 1 + lines[1] = json.dumps(broken, sort_keys=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + with pytest.raises(JournalCorrupt, match="hash chain mismatch"): + DurableJournal(path) + + +def test_journal_detects_tail_payload_tampering_before_append_or_reload(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0", {"row": 0}) + journal.append(JournalEvent.GROUP_READY, "run/0", {"members": 2}) + lines = path.read_text(encoding="utf-8").splitlines() + broken = json.loads(lines[-1]) + broken["payload"]["members"] = 3 + assert broken["seq"] == 1 + lines[-1] = json.dumps(broken, sort_keys=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + with pytest.raises(JournalCorrupt, match="tail digest mismatch"): + journal.append(JournalEvent.BATCH_LEASED, "run/0") + with pytest.raises(JournalCorrupt, match="hash chain mismatch"): + DurableJournal(path) + + +def test_journal_detects_model_checkpoint_commit_tampering(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + journal.append(JournalEvent.BATCH_LEASED, "run/0", {"lease": "lease-0"}) + journal.append( + JournalEvent.MODEL_CHECKPOINT_COMMITTED, + "run/0", + {"lease": "lease-0", "checkpoint": "checkpoint-1"}, + ) + lines = path.read_text(encoding="utf-8").splitlines() + broken = json.loads(lines[-1]) + broken["payload"]["checkpoint"] = "checkpoint-0" + assert broken["seq"] == 1 + lines[-1] = json.dumps(broken, sort_keys=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + with pytest.raises(JournalCorrupt, match="hash chain mismatch"): + DurableJournal(path) + + +def test_journal_upgrades_legacy_prefix_and_starts_a_verifiable_signed_suffix(tmp_path): + path = tmp_path / "rollout.jsonl" + legacy_records = [ + {"seq": 0, "event": "PROMPT_ASSIGNED", "state_key": "run/0", "payload": {"row": 0}}, + {"seq": 1, "event": "GROUP_READY", "state_key": "run/0", "payload": {"members": 2}}, + ] + path.write_text( + "".join(json.dumps(record, sort_keys=True) + "\n" for record in legacy_records), encoding="utf-8" + ) + + journal = DurableJournal(path) + assert [record.digest for record in journal.records()] == [None, None] + first_signed = journal.append(JournalEvent.BATCH_LEASED, "run/0", {"lease": "lease-0"}) + second_signed = journal.append(JournalEvent.GROUP_DROPPED, "run/0") + + assert first_signed.prev == "0" * 64 + assert second_signed.prev == first_signed.digest + raw = json.loads(path.read_text(encoding="utf-8").splitlines()[2]) + body = {key: raw[key] for key in ("seq", "event", "state_key", "payload", "prev")} + canonical = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") + assert raw["digest"] == hashlib.sha256(canonical).hexdigest() + reloaded = DurableJournal(path) + assert [record.seq for record in reloaded.records()] == [0, 1, 2, 3] + assert [record.digest for record in reloaded.records()][2:] == [first_signed.digest, second_signed.digest] + + +def test_journal_rejects_unsigned_record_after_signed_chain(tmp_path): + path = tmp_path / "rollout.jsonl" + journal = DurableJournal(path) + journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0") + journal.append(JournalEvent.GROUP_READY, "run/0") + with open(path, "a", encoding="utf-8") as stream: + stream.write(json.dumps({"seq": 2, "event": "BATCH_LEASED", "state_key": "run/0", "payload": {}}) + "\n") + + with pytest.raises(JournalCorrupt, match="unsigned record after signed"): + journal.append(JournalEvent.GROUP_DROPPED, "run/0") + with pytest.raises(JournalCorrupt, match="unsigned record after signed"): + DurableJournal(path) + + def test_resume_store_pickle_rebuilds_filesystem_handles(tmp_path): store = ResumeStore(tmp_path, "run") store.save_object("episodes", "run/episode/0", {"tokens": [1, 2, 3]}) @@ -93,6 +188,24 @@ def test_episode_shards_merge_legacy_main_journal_records(tmp_path): assert rebuilt.completed_effects(episode) == tuple(sorted((effect, new_effect))) +def test_episode_shard_detects_payload_tampering_on_resume(tmp_path): + store = ResumeStore(tmp_path, "run") + episode = "run/group/0/member/0" + store.checkpoint_episode(episode, {"turn": 0}) + store.checkpoint_episode(episode, {"turn": 1}) + path = next((tmp_path / "episodes").glob("*.jsonl")) + lines = path.read_text(encoding="utf-8").splitlines() + broken = json.loads(lines[0]) + broken["payload"]["object"] = "0" * 64 + ".resume" + assert broken["seq"] == 0 + lines[0] = json.dumps(broken, sort_keys=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + recovered = ResumeStore(tmp_path, "run") + with pytest.raises(JournalCorrupt, match="hash chain mismatch"): + recovered.pending_effects(episode) + + def test_episode_appends_do_not_take_the_main_run_lock(tmp_path, monkeypatch): store = ResumeStore(tmp_path, "run") from twinkle_agentic.async_rl import rollout_resume From 1a420680e7e697c9c6795d17c6aa87fba9b88684 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 18:21:51 +0800 Subject: [PATCH 38/45] fix(cookbook): resume automatic driver snapshots --- .../rl/async_rl/durable_multi_turn_grpo.py | 10 ++++--- .../cookbook/test_durable_multi_turn_grpo.py | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index 1bb1a0389..49844a3ec 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -105,6 +105,12 @@ def _reward_future(reward: Reward): return FunctionWorker(reward) +def _resume_driver(store: ResumeStore, driver: StreamingDriver) -> None: + if store.has_object("driver-head", RUN_ID) or store.has_object("driver", RUN_ID): + driver.load_state_dict() + logger.info("resumed StreamingDriver from the latest stable boundary") + + def _recover_policies(checkpoint_manager: CheckpointEngineManager, commits: list[Any]) -> None: for record in commits: manifest = record.payload.get("manifest") or {} @@ -305,9 +311,7 @@ def main() -> None: resume_store=store, run_id=RUN_ID, ) - if store.has_object("driver", RUN_ID): - driver.load_state_dict() - logger.info("resumed StreamingDriver from the latest stable boundary") + _resume_driver(store, driver) advantage_fn = GRPOAdvantage(num_generations=NUM_GENERATIONS) metrics = CompletionRewardMetric() diff --git a/tests/cookbook/test_durable_multi_turn_grpo.py b/tests/cookbook/test_durable_multi_turn_grpo.py index 4360796e7..be62b3410 100644 --- a/tests/cookbook/test_durable_multi_turn_grpo.py +++ b/tests/cookbook/test_durable_multi_turn_grpo.py @@ -1,5 +1,9 @@ import ast from pathlib import Path +from unittest.mock import Mock + +from twinkle_agentic.async_rl.rollout_resume import ResumeStore +from twinkle_agentic.async_rl.streaming_driver import StreamingDriver class _FunctionWorker: @@ -19,3 +23,26 @@ def test_rewards_use_remote_scorer_workers(): assert isinstance(scorer, _FunctionWorker) assert scorer.fn is reward + + +def test_cookbook_resume_loads_automatic_v2_driver_head(tmp_path): + run_id = "cookbook-automatic-v2" + store = ResumeStore(tmp_path, run_id) + persisted = StreamingDriver( + [{"messages": []}], Mock(), batch_size=1, num_generations=1, resume_store=store, run_id=run_id + ) + persisted._admit() + assert store.has_object("driver-head", run_id) + assert not store.has_object("driver", run_id) + persisted.close() + + path = Path(__file__).parents[2] / "cookbook/rl/async_rl/durable_multi_turn_grpo.py" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + helper = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_resume_driver") + namespace = {"RUN_ID": run_id, "ResumeStore": ResumeStore, "StreamingDriver": StreamingDriver, "logger": Mock()} + exec(compile(ast.Module(body=[helper], type_ignores=[]), str(path), "exec"), namespace) + + restarted = Mock() + namespace["_resume_driver"](store, restarted) + + restarted.load_state_dict.assert_called_once_with() From c164d1a353ebd4563326728f83eef7bc66fc4225 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 19:54:38 +0800 Subject: [PATCH 39/45] fix(agentic): rehash unchanged LocalEnv snapshot candidates --- src/twinkle_agentic/envs/localenv.py | 6 +++++- tests/twinkle_agentic/test_localenv_resume.py | 7 ++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index a3317aeb5..561b49620 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -355,7 +355,11 @@ def checkpoint_episode(self, episode_id: str, state_key: str, destination = workspace_copy / relative old = previous_files.get(relative) old_path = previous / 'workspace' / relative if previous is not None else None - if old is not None and old.get('source') == source_signature and old_path.is_file(): + reuse = old is not None and old.get('source') == source_signature and old_path.is_file() + if reuse: + source_digest, source_size = self._hash_file(source_path) + reuse = source_digest == old['sha256'] and source_size == old['size'] + if reuse: reused_unverified = reused_unverified or str(previous) not in self._verified_snapshots destination.parent.mkdir(parents=True, exist_ok=True) try: diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index 40c28de6a..15fac199d 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -75,7 +75,7 @@ def test_localenv_checkpoint_refuses_a_running_process(tmp_path): env.close("episode-1") -def test_unchanged_generation_reuses_snapshot_content_without_live_copy_or_hash(tmp_path, monkeypatch): +def test_unchanged_generation_reuses_snapshot_content_without_live_copy(tmp_path, monkeypatch): env = LocalEnv(root=str(tmp_path)) env.reset("episode-1") env.step("episode-1", "write_file", {"path": "nested/state.txt", "content": "unchanged"}) @@ -85,6 +85,7 @@ def test_unchanged_generation_reuses_snapshot_content_without_live_copy_or_hash( live_root = str(env.workspace("episode-1")) copies = [] hashes = [] + original_hash = LocalEnv._hash_file def copy(source, destination): copies.append((str(source), str(destination))) @@ -93,14 +94,14 @@ def copy(source, destination): def hash_file(path): hashes.append(str(path)) - raise AssertionError("an unchanged file was hashed") + return original_hash(path) monkeypatch.setattr(LocalEnv, "_copy_snapshot_file", staticmethod(copy)) monkeypatch.setattr(LocalEnv, "_hash_file", staticmethod(hash_file)) second = env.checkpoint_episode("episode-1", state_key, first["generation"]) assert copies == [] - assert hashes == [] + assert hashes == [os.path.join(live_root, "nested", "state.txt")] first_file = key_root / first["generation"] / "workspace/nested/state.txt" second_file = key_root / second["generation"] / "workspace/nested/state.txt" assert os.stat(first_file).st_ino == os.stat(second_file).st_ino From 457712d55fdd7ce6e4dd1b1c6bab0b149bf7cbde Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 22:04:16 +0800 Subject: [PATCH 40/45] docs(agentic): describe LocalEnv snapshot rehashing --- .../\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index 5356e9ecb..d7e870230 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -291,8 +291,8 @@ vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: - 无法 checkpoint 的远端 agent harness; - 所有外部工具协议都具备幂等结果查询; - 大规模长训练的持久化开销仍需按具体版本形成独立基准。当前 journal 正常追加只同步尾部并按 episode - 分片,driver 普通事件只保存当前 group,LocalEnv 未变化轮次不再复制或重哈希 live 文件;新进程冷恢复 - 仍完整校验 workspace。不能用端到端墙钟结果替代这些专项评估。 + 分片,driver 普通事件只保存当前 group,LocalEnv 未变化轮次复用已有快照内容,但仍会重哈希 live 文件, + 以识别同尺寸且元数据未变化的快速改写;新进程冷恢复仍完整校验 workspace。不能用端到端墙钟结果替代这些专项评估。 因此该机制的主要结论是进程重启时保持 GRPO 组语义、事务一致性、固定预算下的有效训练量, 并减少重复工具副作用和重复采样,不宣称所有故障率下无条件提升模型质量或缩短墙钟时间。 From a08dac4f520abef1f3ae075256f75d2076fc697a Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 22:04:17 +0800 Subject: [PATCH 41/45] fix(agentic): bind deferred scorer callbacks --- .../async_rl/streaming_driver.py | 6 ++-- .../test_streaming_driver_resume.py | 28 +++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index 67a787617..fa0ca4be3 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -1366,7 +1366,7 @@ def _done(f, episode=episode): future.add_done_callback(_done) - self._defer_action(lambda: self._run_episode_action(episode, submit)) + self._defer_action(lambda episode=episode, submit=submit: self._run_episode_action(episode, submit)) # ------------------------------------------------------------------ completions @@ -1454,7 +1454,7 @@ def submit(prm=prm, scorer=scorer): ) _record_driver_probe("score_submitted", episode.episode_id, kind="prm", segment=segment) - self._defer_action(lambda: self._run_episode_action(episode, submit)) + self._defer_action(lambda episode=episode, submit=submit: self._run_episode_action(episode, submit)) return segment def _release(self, episode: _Episode, segment: int) -> None: @@ -1478,7 +1478,7 @@ def submit(orm=orm, index=index): ) _record_driver_probe("score_submitted", episode.episode_id, kind="orm") - self._defer_action(lambda: self._run_episode_action(episode, submit)) + self._defer_action(lambda episode=episode, submit=submit: self._run_episode_action(episode, submit)) self._maybe_finish(episode) def _fail(self, episode: _Episode, exc: BaseException) -> None: diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index babcc211d..00cda79e7 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -197,6 +197,34 @@ def _wait_until(predicate, timeout=2.0): raise AssertionError("condition was not reached before timeout") +def test_durable_driver_submits_every_orm_and_prm_once(tmp_path): + store = ResumeStore(tmp_path, "run-score-callbacks") + calls = [] + + def scorer(name, value): + def score(_rows): + calls.append(name) + return _Future([value]) + return score + + driver = StreamingDriver( + _prompts(1), _SegmentRollout(store), batch_size=1, num_generations=1, max_staleness=0, max_steps=1, + orms=[scorer("orm-a", 0.1), scorer("orm-b", 0.9)], orm_names=["a", "b"], + prms=[scorer("prm-a", 0.2), scorer("prm-b", 0.8)], prm_names=["a", "b"], + resume_store=store, + ) + try: + driver._start() + batch = driver._next_batch() + assert batch is not None + _rows, facts = batch + assert facts["scores"][0]["rewards"]["orm"] == {"a": 0.1, "b": 0.9} + assert facts["scores"][0]["prm_segments"]["scores"] == {"a": [0.2], "b": [0.8]} + assert sorted(calls) == ["orm-a", "orm-b", "prm-a", "prm-b"] + finally: + driver.close() + + def test_default_driver_keeps_fixed_admission_window_across_versions(): manager = _PolicyManager(0, {version: f"/policies/{version}" for version in range(8)}) driver = StreamingDriver( From cc4e6f9443c8f0c600dce31d594b07b560825cc5 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 23:36:21 +0800 Subject: [PATCH 42/45] fix(agentic): preserve no-slot backoff across resume --- .../async_rl/streaming_driver.py | 2 +- .../test_streaming_driver_resume.py | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index fa0ca4be3..ed52ddff5 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -946,7 +946,7 @@ def _resume_scores(self, episode: _Episode) -> None: episode.traj = restored def _resume_live_episode(self, episode: _Episode) -> None: - if episode.finished or episode.lost: + if episode.finished or episode.lost or episode.no_slot_retry_at is not None: return self._resume_scores(episode) if episode.done: diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 00cda79e7..46220d993 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -296,6 +296,39 @@ def test_inflight_prompt_and_group_survive_snapshot(tmp_path): assert restored._groups["0"].binding == driver._groups["0"].binding +def test_no_slot_member_resumes_backoff_without_duplicate_submission(tmp_path): + store = ResumeStore(tmp_path, "run-no-slot-resume") + source = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, max_staleness=0, resume_store=store + ) + source._admit() + original = source._groups["0"].members[0] + source._no_slot(original) + state = source.state_dict() + source.close() + + rollout = _BlockingRollout() + restored = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, max_staleness=0, resume_store=store + ) + restored.load_state_dict(state) + member = restored._groups["0"].members[0] + assert restored._inflight == 0 + assert not member.counted_inflight + retry_in = state["groups"][0]["members"][0]["no_slot_retry_in"] + assert 0 < member.no_slot_retry_at - time.monotonic() <= retry_in + assert rollout.calls == [] + + restored._retry_no_slot_due() + assert rollout.calls == [] + member.no_slot_retry_at = time.monotonic() - 1 + restored._retry_no_slot_due() + assert len(rollout.calls) == 1 + assert restored._inflight == 1 + assert restored._groups["0"].members[0].no_slot_retry_at is None + restored.close() + + def test_restore_does_not_materialize_remote_trajectory(tmp_path): store = ResumeStore(tmp_path, "run-remote-traj") source = StreamingDriver( From f546f2add7aa9872505bab9566d601adcebc8214 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Sun, 22 Nov 2026 23:46:19 +0800 Subject: [PATCH 43/45] fix(agentic): keep pending groups alive until delivery --- .../async_rl/streaming_driver.py | 2 +- .../test_streaming_driver_resume.py | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index ed52ddff5..bcb9d6a58 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -444,7 +444,7 @@ def _next_batch(self) -> Optional[tuple]: self._drop_stale() if self._ready_rows >= self.batch_size: break - if self._exhausted and self._inflight == 0: + if self._exhausted and self._inflight == 0 and self._live == 0 and not self._groups: return None self._lock.wait(0.5) finally: diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 46220d993..7725fc29f 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -329,6 +329,46 @@ def test_no_slot_member_resumes_backoff_without_duplicate_submission(tmp_path): restored.close() +def test_no_slot_backoff_does_not_end_exhausted_driver(tmp_path): + store = ResumeStore(tmp_path, "run-no-slot-exhausted") + source = StreamingDriver( + _prompts(1), _BlockingRollout(), batch_size=1, num_generations=1, max_staleness=0, max_steps=1, + resume_store=store, + ) + source._admit() + source._no_slot(source._groups["0"].members[0]) + state = source.state_dict() + source.close() + + rollout = _DoneRollout() + restored = StreamingDriver( + _prompts(1), rollout, batch_size=1, num_generations=1, max_staleness=0, max_steps=1, + resume_store=store, + ) + restored.load_state_dict(state) + member = restored._groups["0"].members[0] + member.no_slot_retry_at = time.monotonic() + 0.2 + restored._exhausted = True + delivered = Future() + + def get_batch(): + try: + delivered.set_result(restored._next_batch()) + except BaseException as exc: + delivered.set_exception(exc) + + threading.Thread(target=get_batch, daemon=True).start() + try: + time.sleep(0.05) + assert not delivered.done() + batch = delivered.result(timeout=2) + assert batch is not None, (restored.stats(), restored._ready_rows, restored._handed) + assert len(batch[0]) == 1 + assert len(rollout.calls) == 1 + finally: + restored.close() + + def test_restore_does_not_materialize_remote_trajectory(tmp_path): store = ResumeStore(tmp_path, "run-remote-traj") source = StreamingDriver( From 58607277a59fcab8117ca21290d119b8b67feeee Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Mon, 23 Nov 2026 00:35:02 +0800 Subject: [PATCH 44/45] refactor(agentic): simplify durable resume state handling --- .../rl/async_rl/durable_multi_turn_grpo.py | 2 +- .../Agentic/DurableRolloutResume.md" | 18 +-- .../async_rl/rollout_resume.py | 90 +++++-------- .../async_rl/streaming_driver.py | 14 +- src/twinkle_agentic/envs/base.py | 29 ++--- src/twinkle_agentic/envs/localenv.py | 54 ++------ src/twinkle_agentic/rollout/multi_turn.py | 123 ++++++++---------- tests/twinkle_agentic/test_localenv_resume.py | 27 ---- .../test_rollout_resume_store.py | 55 +------- .../test_streaming_driver_resume.py | 41 ------ 10 files changed, 121 insertions(+), 332 deletions(-) diff --git a/cookbook/rl/async_rl/durable_multi_turn_grpo.py b/cookbook/rl/async_rl/durable_multi_turn_grpo.py index 49844a3ec..cf0f6c8e6 100644 --- a/cookbook/rl/async_rl/durable_multi_turn_grpo.py +++ b/cookbook/rl/async_rl/durable_multi_turn_grpo.py @@ -106,7 +106,7 @@ def _reward_future(reward: Reward): def _resume_driver(store: ResumeStore, driver: StreamingDriver) -> None: - if store.has_object("driver-head", RUN_ID) or store.has_object("driver", RUN_ID): + if store.has_object("driver-head", RUN_ID): driver.load_state_dict() logger.info("resumed StreamingDriver from the latest stable boundary") diff --git "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" index d7e870230..fcf5ec802 100644 --- "a/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" +++ "b/docs/source_zh/\347\273\204\344\273\266/Agentic/DurableRolloutResume.md" @@ -70,8 +70,7 @@ driver = StreamingDriver( run_id="gsm8k-durable", ) -if (store.has_object("driver-head", "gsm8k-durable") - or store.has_object("driver", "gsm8k-durable")): +if store.has_object("driver-head", "gsm8k-durable"): driver.load_state_dict() ``` @@ -107,7 +106,7 @@ checkpoint 且不再交付该 lease。调用方必须先确保模型和 optimize - `DurableJournal`:带单调序号和 SHA-256 摘要链的 JSONL 事件日志,支持尾部截断修复、跨线程和跨进程 文件锁,以及写入失败回滚;完整扫描和完整链校验只在初始化或异常回滚时执行。run 控制事件保留在主日志, - turn/tool intent/result 按 episode 分片;旧主日志中的 episode 事件在初始化时索引并参与恢复; + turn/tool intent/result 按 episode 分片; - object store:保存 prompt、episode、lease、小型 driver head 和逐 group 快照,读取时校验对象内容的 SHA-256。 对象 SHA 与 journal 记录摘要是两套独立校验,不能互相替代。普通 step/score 只写发生变化的 group; 对外 `state_dict()` 仍可按需生成兼容 v1 快照。 @@ -118,10 +117,7 @@ separators=(",", ":"))` 确定性编码为 UTF-8 后计算 SHA-256 十六进制 摘要并链接新记录,不按历史事件数重新扫描;初始化和异常回滚会验证每条签名记录的摘要及 `prev` 链接。 因此,签名记录即使仍是合法 JSON 且序号正确,其中段或尾部的 payload 篡改也会拒绝恢复。 -旧版本没有 `prev`/`digest` 的 unsigned 记录只允许作为日志前缀,已有 run 无需重写即可恢复。升级后的第一条 -签名记录以 64 个字符的全零 `prev` 起链,后续记录正常链接;签名链中间或之后不允许再插入 unsigned 记录。 -该策略只保护升级后的签名后缀,不回溯提供旧 unsigned 前缀的完整性保证,也不能检测旧前缀在升级前已经发生 -的历史篡改。每个 episode 分片独立遵守同一格式和链规则。 +首条记录的 `prev` 为 64 个字符的全零,每个 episode 分片独立遵守同一格式和链规则;缺少摘要字段的记录会被拒绝。 故障边界: @@ -155,7 +151,7 @@ closed。只恢复文本对话、但丢失 workspace 或工具状态的实现不 LocalEnv v2 为每轮创建不可变增量 generation。未变化文件复用源签名和已有哈希,并只在历史 snapshot 之间建立 hardlink;新增或修改文件仍复制并计算 SHA-256。restore 的 live workspace 使用 reflink 或复制, 绝不与 snapshot hardlink。新进程首次恢复必须完整校验所有文件;只有本进程已验证且存储签名未变化的 -generation 才能使用 warm 校验缓存。v1 generation 仍可恢复。 +generation 才能使用 warm 校验缓存。 ## 外部工具副作用 @@ -276,11 +272,7 @@ vLLM 0.33.0 和 vLLM-Ascend 0.32.0.dev0 补做验证: | 单卡 CaMem 两步 | 两轮 weights/KV sleep-wake 和第二轮 LoRA-only 同步完成,未出现旧版 `aclnnInplaceCopy` 错误 | 该结果只覆盖上述版本组合和单节点双卡,不回溯证明 vLLM/vLLM-Ascend 0.23.0,也不代表 FSDP2 -或多节点已经验证。早期本地 overlay 的规模基准显示,journal 在 250、500、1000、2000 事件时的平均追加 -延迟约为 1.89、3.53、6.71、13.16ms;该数据来自仍会全量重扫的旧实现,只用于说明当时的优化动机。 -当前正常追加只读取尾部以同步序号并校验摘要,完整扫描和完整链校验仅用于初始化或异常回滚。 -64MiB LocalEnv workspace 快照约 -85ms,在该本地盘上暂不是主要瓶颈。 +或多节点已经验证。当前正常追加只读取尾部以同步序号并校验摘要,完整扫描和完整链校验仅用于初始化或异常回滚。 尚未覆盖: diff --git a/src/twinkle_agentic/async_rl/rollout_resume.py b/src/twinkle_agentic/async_rl/rollout_resume.py index b9e3da162..7ef2e5c7a 100644 --- a/src/twinkle_agentic/async_rl/rollout_resume.py +++ b/src/twinkle_agentic/async_rl/rollout_resume.py @@ -122,8 +122,8 @@ class JournalRecord: event: JournalEvent state_key: str payload: dict[str, Any] - prev: str | None = None - digest: str | None = None + prev: str + digest: str def _canonical_json(value: Any) -> bytes: @@ -139,11 +139,7 @@ def _object_name(key: str) -> str: class DurableJournal: - """Append-only JSONL journal with a hash chain and final-line repair. - - Unsigned records are accepted only as a legacy prefix. The signed suffix starts with a zero - ``prev`` value, so its integrity does not retroactively cover the legacy prefix. - """ + """Append-only JSONL journal with a hash chain and final-line repair.""" def __init__(self, path: str | os.PathLike[str]): self.path = Path(path) @@ -151,7 +147,6 @@ def __init__(self, path: str | os.PathLike[str]): self._lock = threading.Lock() self._next_seq = 0 self._last_digest = _ZERO_DIGEST - self._chain_started = False self._records: list[JournalRecord] = [] self._stream = None with _exclusive_file_lock(self.path): @@ -160,7 +155,6 @@ def __init__(self, path: str | os.PathLike[str]): def _repair_and_scan(self) -> None: self._next_seq = 0 self._last_digest = _ZERO_DIGEST - self._chain_started = False if not self.path.exists(): self._records = [] return @@ -180,27 +174,18 @@ def _repair_and_scan(self) -> None: if seq != len(records): raise ValueError("journal sequence mismatch") event = JournalEvent(payload["event"]) - signed = "prev" in payload or "digest" in payload - if signed: - body = { - "seq": seq, - "event": payload["event"], - "state_key": payload["state_key"], - "payload": payload["payload"], - "prev": payload["prev"], - } - digest = payload["digest"] - if body["prev"] != prev or _record_digest(body) != digest: - raise ValueError("journal hash chain mismatch") - records.append( - JournalRecord(seq, event, body["state_key"], body["payload"], body["prev"], digest) - ) - prev = digest - self._chain_started = True - else: - if self._chain_started: - raise ValueError("unsigned record after signed journal prefix") - records.append(JournalRecord(seq, event, payload["state_key"], payload["payload"])) + body = { + "seq": seq, + "event": payload["event"], + "state_key": payload["state_key"], + "payload": payload["payload"], + "prev": payload["prev"], + } + digest = payload["digest"] + if body["prev"] != prev or _record_digest(body) != digest: + raise ValueError("journal hash chain mismatch") + records.append(JournalRecord(seq, event, body["state_key"], body["payload"], body["prev"], digest)) + prev = digest except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: # A newline proves that a complete record was written. Only a final fragment without # one is repairable; discarding a corrupt complete commit could repeat its optimizer step. @@ -229,7 +214,6 @@ def _sync_tail(self) -> None: if end == 0: self._next_seq = 0 self._last_digest = _ZERO_DIGEST - self._chain_started = False return cursor = end - 2 tail_start = 0 @@ -249,24 +233,17 @@ def _sync_tail(self) -> None: raise ValueError("unterminated journal tail") payload = json.loads(raw.decode("utf-8")) self._next_seq = int(payload["seq"]) + 1 - signed = "prev" in payload or "digest" in payload - if signed: - body = { - "seq": int(payload["seq"]), - "event": payload["event"], - "state_key": payload["state_key"], - "payload": payload["payload"], - "prev": payload["prev"], - } - digest = payload["digest"] - if _record_digest(body) != digest: - raise ValueError("journal tail digest mismatch") - self._last_digest = digest - self._chain_started = True - else: - if self._chain_started: - raise ValueError("unsigned record after signed journal prefix") - self._last_digest = _ZERO_DIGEST + body = { + "seq": int(payload["seq"]), + "event": payload["event"], + "state_key": payload["state_key"], + "payload": payload["payload"], + "prev": payload["prev"], + } + digest = payload["digest"] + if _record_digest(body) != digest: + raise ValueError("journal tail digest mismatch") + self._last_digest = digest except (KeyError, TypeError, ValueError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise JournalCorrupt(f"{self.path}: corrupt journal tail: {exc}") from exc @@ -306,7 +283,6 @@ def append(self, event: JournalEvent, state_key: str, payload: dict[str, Any] | self._records.append(record) self._next_seq += 1 self._last_digest = digest - self._chain_started = True return record def records(self, *, state_key: str | None = None) -> Iterable[JournalRecord]: @@ -322,9 +298,6 @@ def last(self, state_key: str, *, events: Iterable[JournalEvent] | None = None) return found -_EPISODE_EVENTS = {JournalEvent.TURN_COMMITTED, JournalEvent.TOOL_INTENT, JournalEvent.TOOL_RESULT} - - def _episode_key(state_key: str) -> str: return state_key.split("/effect/", 1)[0] @@ -341,10 +314,6 @@ def __init__(self, root: str | os.PathLike[str], run_id: str): self.journal = DurableJournal(self.root / "rollout.jsonl") self._episode_journals: dict[str, DurableJournal] = {} self._episode_journals_lock = threading.Lock() - self._legacy_episode_records: dict[str, list[JournalRecord]] = {} - for record in self.journal.records(): - if record.event in _EPISODE_EVENTS: - self._legacy_episode_records.setdefault(_episode_key(record.state_key), []).append(record) def __getstate__(self) -> dict[str, str]: return {"root": str(self.root), "run_id": self.run_id} @@ -362,11 +331,10 @@ def _episode_journal(self, episode_key: str) -> DurableJournal: return self._episode_journals.setdefault(episode_key, created) def _episode_records(self, episode_key: str) -> tuple[JournalRecord, ...]: - records = list(self._legacy_episode_records.get(episode_key) or ()) path = self.root / "episodes" / (hashlib.sha256(episode_key.encode("utf-8")).hexdigest() + ".jsonl") - if episode_key in self._episode_journals or path.is_file(): - records.extend(self._episode_journal(episode_key).records()) - return tuple(records) + if episode_key not in self._episode_journals and not path.is_file(): + return () + return tuple(self._episode_journal(episode_key).records()) def save_object(self, scope: str, key: str, value: Any) -> str: payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) diff --git a/src/twinkle_agentic/async_rl/streaming_driver.py b/src/twinkle_agentic/async_rl/streaming_driver.py index bcb9d6a58..e25f1103f 100644 --- a/src/twinkle_agentic/async_rl/streaming_driver.py +++ b/src/twinkle_agentic/async_rl/streaming_driver.py @@ -20,6 +20,7 @@ with the number of episodes in flight. """ from __future__ import annotations + import copy import math import queue @@ -65,9 +66,8 @@ def _record_driver_probe(event: str, episode_id: str = '', **fields: Any) -> Non ordering the slow-injection efficiency oracles assert on, with ``t`` stamps from the same monotonic clock. """ - import os - import json + import os root = os.environ.get('TWINKLE_DRIVER_PROBE') if not root: return @@ -172,8 +172,8 @@ class _Episode: lost: bool = False orm: Optional[List[Any]] = None orm_pending: int = 0 - prm: list[list[Any]] | None = None - prm_turns: list[int] = field(default_factory=list) + prm: Optional[List[List[Any]]] = None + prm_turns: List[int] = field(default_factory=list) #: The trajectory at each segment boundary, aligned with ``prm_turns``. Pending scores must be #: reissued against that boundary rather than against whatever turn is latest after a restart. prm_inputs: list[Any] = field(default_factory=list) @@ -830,7 +830,6 @@ def state_dict(self) -> Dict[str, Any]: with self._durable_io_locked(): for state_key, record in records: self.resume_store.save_object('driver-groups', state_key, record) - self.resume_store.save_object('driver', self.run_id, state) self.resume_store.save_object('driver-head', self.run_id, head) return state @@ -1011,10 +1010,7 @@ def load_state_dict(self, state: Optional[Dict[str, Any]] = None) -> None: if state is None: if self.resume_store is None: raise UnsafeResume('load_state_dict() without state needs a resume store') - if self.resume_store.has_object('driver-head', self.run_id): - state = self._load_v2_state(self.resume_store.load_object('driver-head', self.run_id)) - else: - state = self.resume_store.load_object('driver', self.run_id) + state = self._load_v2_state(self.resume_store.load_object('driver-head', self.run_id)) if state.get('format') != 'twinkle.streaming-driver.v1': raise UnsafeResume('unsupported StreamingDriver checkpoint format') if str(state.get('run_id')) != self.run_id: diff --git a/src/twinkle_agentic/envs/base.py b/src/twinkle_agentic/envs/base.py index b579cf31e..873c5cca7 100644 --- a/src/twinkle_agentic/envs/base.py +++ b/src/twinkle_agentic/envs/base.py @@ -158,7 +158,7 @@ class NoSlot: class _Session: - __slots__ = ("state", "reward", "rewarded", "touched", "script_inflight") + __slots__ = ('state', 'reward', 'rewarded', 'touched', 'script_inflight') def __init__(self, state: Any): self.state = state @@ -238,10 +238,9 @@ def _open(self, trajectory: Optional[Trajectory]) -> Tuple[Any, StepResult]: def _step(self, state: Any, tool_name: str, arguments: Dict[str, Any]) -> StepResult: """Run one tool call in the episode.""" - def _run_script( - self, state: Any, source: str, interpreter: str, timeout: float | None, cap_memory: bool = True - ) -> tuple[int, str]: - raise NotImplementedError(f"{type(self).__name__} cannot run scripts; act through its tools instead.") + def _run_script(self, state: Any, source: str, interpreter: str, timeout: Optional[float], + cap_memory: bool = True) -> Tuple[int, str]: + raise NotImplementedError(f'{type(self).__name__} cannot run scripts; act through its tools instead.') def _close(self, state: Any) -> None: pass @@ -348,15 +347,13 @@ def step_batch(self, episode_id: str, calls: Sequence[Tuple[str, Dict[str, Any]] _record_tool_exec(episode_id, len(results)) return results - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def run_script( - self, - episode_id: str, - source: str, - interpreter: str = "python", - timeout: float | None = None, - cap_memory: bool = True, - ) -> tuple[int, str]: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def run_script(self, + episode_id: str, + source: str, + interpreter: str = 'python', + timeout: Optional[float] = None, + cap_memory: bool = True) -> Tuple[int, str]: """Run a whole script in the episode's session; returns ``(exit_code, output)``. The execution path a *verifier* (or an agent program) takes, as opposed to :meth:`step`, @@ -413,8 +410,8 @@ def snapshot(self, episode_id: str) -> Tuple[str, str]: budget=self.snapshot_budget, skip=self.snapshot_skip) - @remote_function(enable_continous_work=True, sticky_key="episode_id") - def close(self, episode_id: str) -> float | None: + @remote_function(enable_continous_work=True, sticky_key='episode_id') + def close(self, episode_id: str) -> Optional[float]: """End the episode's session and return its reward (the sum of its step rewards). ``None`` when the session never scored (no step ever carried a reward) or there was no diff --git a/src/twinkle_agentic/envs/localenv.py b/src/twinkle_agentic/envs/localenv.py index 561b49620..e33a4a169 100644 --- a/src/twinkle_agentic/envs/localenv.py +++ b/src/twinkle_agentic/envs/localenv.py @@ -130,29 +130,8 @@ def _workspace(self, state: _LocalSession) -> str: @staticmethod def _state_dir_name(state_key: str) -> str: - # Keep the durable path short enough for Windows' classic MAX_PATH. return hashlib.sha256(state_key.encode('utf-8')).hexdigest()[:24] - @staticmethod - def _tree_digest(root: Path) -> Dict[str, Any]: - digest = hashlib.sha256() - files = [] - total = 0 - for path in sorted(root.rglob('*')): - if path.is_symlink(): - raise UnsafeCheckpoint(f'workspace snapshot refuses symbolic link {path}') - if not path.is_file(): - continue - relative = path.relative_to(root).as_posix() - data = path.read_bytes() - file_digest = hashlib.sha256(data).hexdigest() - digest.update(relative.encode('utf-8')) - digest.update(b'\0') - digest.update(file_digest.encode('ascii')) - files.append({'path': relative, 'size': len(data), 'sha256': file_digest}) - total += len(data) - return {'digest': digest.hexdigest(), 'files': files, 'bytes': total} - @staticmethod def _file_signature(stat_result: os.stat_result) -> Dict[str, int]: return { @@ -332,13 +311,13 @@ def checkpoint_episode(self, episode_id: str, state_key: str, continue if (candidate_manifest.get('state_key') == state_key and candidate_manifest.get('generation') == candidate.name - and candidate_manifest.get('format') in {'twinkle.localenv.v1', 'twinkle.localenv.v2'}): + and candidate_manifest.get('format') == 'twinkle.localenv.v2'): previous = candidate previous_manifest = candidate_manifest break previous_files = { item['path']: item for item in (previous_manifest or {}).get('workspace', {}).get('files', []) - } if previous_manifest and previous_manifest['format'] == 'twinkle.localenv.v2' else {} + } directories, source_files = self._workspace_entries(Path(state.workspace), with_stats=True) generation_root = key_root / generation workspace_copy = generation_root / 'workspace' @@ -425,8 +404,7 @@ def checkpoint_episode(self, episode_id: str, state_key: str, def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any], trajectory=None) -> None: """Allocate a fresh session and rehydrate the snapshot named by ``state``.""" snapshot_format = state.get('format') - if snapshot_format not in {'twinkle.localenv.v1', 'twinkle.localenv.v2'} or state.get( - 'state_key') != state_key: + if snapshot_format != 'twinkle.localenv.v2' or state.get('state_key') != state_key: raise UnsafeCheckpoint('LocalEnv restore metadata does not match the episode state key') generation = str(state.get('generation') or '') if not generation: @@ -442,12 +420,7 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] raise UnsafeCheckpoint('LocalEnv snapshot manifest identity mismatch') source = generation_root / 'workspace' workspace = manifest['workspace'] - if snapshot_format == 'twinkle.localenv.v1': - if self._tree_digest(source)['digest'] != workspace['digest']: - raise UnsafeCheckpoint('LocalEnv snapshot workspace checksum mismatch') - cold_v2 = snapshot_format == 'twinkle.localenv.v2' and not self._snapshot_cache_valid( - generation_root, workspace - ) + cold_restore = not self._snapshot_cache_valid(generation_root, workspace) self.reset(episode_id, trajectory) try: @@ -455,9 +428,7 @@ def restore_episode(self, episode_id: str, state_key: str, state: dict[str, Any] session.reward = float(state.get("reward") or 0.0) session.rewarded = bool(state.get("rewarded", session.reward != 0.0)) target = Path(self.workspace(episode_id)) - if snapshot_format == 'twinkle.localenv.v1': - shutil.copytree(source, target, dirs_exist_ok=True) - elif cold_v2: + if cold_restore: self._restore_v2_workspace(generation_root, workspace, target) else: shutil.copytree( @@ -479,14 +450,8 @@ def discard_episode_state(self, state_key: str) -> None: if key.startswith(prefix): self._verified_snapshots.pop(key, None) - def _run_script( - self, - state: _LocalSession, - source: str, - interpreter: str = "python", - timeout: float | None = None, - cap_memory: bool = True, - ) -> tuple[int, str]: + def _run_script(self, state: _LocalSession, source: str, interpreter: str = 'python', + timeout: Optional[float] = None, cap_memory: bool = True) -> Tuple[int, str]: timeout = self._command_timeout if timeout is None else timeout # The script file is never written into the workspace. A workspace gets read back -- by a # snapshot, or by a check that lists the directory -- and a stray _script.py in there reads @@ -506,7 +471,7 @@ def _run_script( # which is already in the right environment. argv = ['/bin/bash', '-c', source] else: - return 1, f"unsupported interpreter {interpreter!r}; use python or shell" + return 1, f'unsupported interpreter {interpreter!r}; use python or shell' return self._spawn(state, argv, timeout, cap_memory) finally: shutil.rmtree(holder, ignore_errors=True) @@ -582,7 +547,8 @@ def _resolve(state: _LocalSession, path: str) -> str: raise ValueError(f'path {path!r} escapes the workspace') return target - def _spawn(self, state: _LocalSession, argv: list[str], timeout: float, cap_memory: bool = True) -> tuple[int, str]: + def _spawn(self, state: _LocalSession, argv: List[str], timeout: float, + cap_memory: bool = True) -> Tuple[int, str]: env = dict(os.environ, **_SCRIPT_ENVS, **self._envs) # Inherited from the trainer, and a check that imports torch would # otherwise take a share of a GPU that is mid-generation. diff --git a/src/twinkle_agentic/rollout/multi_turn.py b/src/twinkle_agentic/rollout/multi_turn.py index 83fb5e3ea..59cdbd0f2 100644 --- a/src/twinkle_agentic/rollout/multi_turn.py +++ b/src/twinkle_agentic/rollout/multi_turn.py @@ -44,15 +44,15 @@ def _final_answer(traj: Trajectory) -> str: Multimodal content is a part list; the text parts concatenate in order. """ content = None - for message in reversed(traj.get("messages") or []): - if message.get("role") == "assistant": - content = message.get("content") + for message in reversed(traj.get('messages') or []): + if message.get('role') == 'assistant': + content = message.get('content') break if content is None: - return "" + return '' if isinstance(content, list): - return "".join(str(part.get("text") or "") for part in content if isinstance(part, dict)) - return str(content or "") + return ''.join(str(part.get('text') or '') for part in content if isinstance(part, dict)) + return str(content or '') def _dump_rollout_rows(episode_id: str, rows: list) -> None: @@ -418,7 +418,7 @@ def __init__(self, episode_id: str, trajectory: Trajectory, params: SamplingPara self.tools_key: Optional[str] = None #: The last served reply, for resubmitted requests (an agent HTTP client that timed out #: and retried sends the same payload verbatim: it is answered verbatim, not re-served). - self.last_reply: dict | None = None + self.last_reply: Optional[dict] = None #: Continue-on-length (defect110): while an assistant turn is being continued, its reply #: reaches the agent as several wire messages the agent merges into ONE. ``merged_content`` #: accumulates their content (None = no open split); ``split_start`` is where the split @@ -984,26 +984,25 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: # need to run something (shell / python) ride ``ctx.env``, so episodes run and score in # the same sandbox; ``env=None`` (a tools-only local episode) falls back to a LocalEnv # over the row's own ``workspace`` column. - check_score: float | None = None - if traj.get("checks") is not None: + check_score: Optional[float] = None + if traj.get('checks') is not None: if self.env is not None and not ep.env_open: raise EpisodeError( - f"episode {ep.episode_id!r}: its env session is already closed, so its terminal " - "checks cannot see the state the agent left behind." - ) + f'episode {ep.episode_id!r}: its env session is already closed, so its terminal ' + 'checks cannot see the state the agent left behind.') try: - checks = checks_from_dicts(traj.get("checks")) + checks = checks_from_dicts(traj.get('checks')) except Exception as exc: - raise EpisodeError(f"episode {ep.episode_id!r}: malformed checks column: {exc}") from exc - workspace = self.env.workspace(ep.episode_id) if self.env is not None else str(traj.get("workspace") or "") + raise EpisodeError( + f'episode {ep.episode_id!r}: malformed checks column: {exc}') from exc + workspace = (self.env.workspace(ep.episode_id) if self.env is not None + else str(traj.get('workspace') or '')) report = run_checks( checks, - CheckContext( - workspace=workspace, final_answer=_final_answer(traj), env=self.env, episode_id=ep.episode_id - ), - ) + CheckContext(workspace=workspace, final_answer=_final_answer(traj), + env=self.env, episode_id=ep.episode_id)) check_score = float(report.score) - env_reward: float | None = None + env_reward: Optional[float] = None if self.env is not None and ep.env_open: env_reward = self.env.close(ep.episode_id) ep.env_open = False @@ -1013,24 +1012,24 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: # ``rewards.env`` lands only when the env session actually scored (``close`` returns None # for a sandbox used only for its tools: its constant zero is "no reward", not a score), # so an absent env key never fabricates one. - rewards = dict(traj.get("rewards") or {}) + rewards = dict(traj.get('rewards') or {}) if env_reward is not None: - rewards["env"] = float(env_reward) + rewards['env'] = float(env_reward) if check_score is not None: - rewards["check"] = check_score - traj["rewards"] = rewards + rewards['check'] = check_score + traj['rewards'] = rewards if episode_end is not None: traj['episode_end'] = episode_end for row in ep.closed_rows: row.pop('use_base_model', None) # The frozen rows carry the episode's env reward too: the reward keys belong to # the episode, and every row of it carries the same ones. - row_rewards = dict(row.get("rewards") or {}) + row_rewards = dict(row.get('rewards') or {}) if env_reward is not None: - row_rewards["env"] = float(env_reward) + row_rewards['env'] = float(env_reward) if check_score is not None: - row_rewards["check"] = check_score - row["rewards"] = row_rewards + row_rewards['check'] = check_score + row['rewards'] = row_rewards rows = list(ep.closed_rows) + [traj] if self.resume_store is not None: self.resume_store.save_object("deliveries", ep.state_key, rows) @@ -1068,7 +1067,7 @@ def _finish(self, ep: _Episode, **fields: Any) -> tuple[list, RolloutStatus]: stop_reason=ep.stop_reason, truncated=bool(ep.truncated), token_lengths=(prompt_tokens, response_tokens) if coded else None, - routing_exported=traj.get("routed_experts") is not None, + routing_exported=traj.get('routed_experts') is not None, env_reward=float(env_reward) if env_reward is not None else 0.0, extra=extra, ) @@ -1455,9 +1454,8 @@ def run() -> None: # The agent program is a full third-party runtime, not a model-written tool # script: the tool-script address-space cap would strangle it before its first # request (defect108). Its containment is the harness timeout passed here. - ep.exit = self.env.run_script( - ep.episode_id, command, interpreter="shell", timeout=self.harness.timeout, cap_memory=False - ) + ep.exit = self.env.run_script(ep.episode_id, command, interpreter='shell', + timeout=self.harness.timeout, cap_memory=False) except BaseException as error: # noqa # reported by the step that reads the exit ep.exit = (None, f'{type(error).__name__}: {error}') finally: @@ -1530,14 +1528,9 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS # otherwise read as a rewrite and needlessly swap the ledger). request.reply.set_result(dict(ep.last_reply)) return self._continue(ep) - if ( - ledger is not None - and ep.last_reply is not None - and ep.last_reply.get("finish_reason") == "length" - and tools_key == ep.tools_key - and canonical - and canonical == ep.sent - ): + if (ledger is not None and ep.last_reply is not None + and ep.last_reply.get('finish_reason') == 'length' + and tools_key == ep.tools_key and canonical and canonical == ep.sent): # Continue-on-length (chat protocol): the agent echoed the conversation ending with # our truncated reply and asks for more of THAT turn. Detection is against the WIRE # view (ep.sent), not ledger.messages: the ledger banks the decoded text with the @@ -1550,19 +1543,17 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS if ep.merged_content is not None and ledger is not None and tools_key == ep.tools_key and canonical: # A continued turn reaches the agent as several wire messages it merges into ONE # assistant message; reconstruct that merged view to recognise what comes back. - merged_view = ep.sent[: ep.split_start] + [("assistant", ep.merged_content.strip(), ep.sent[-1][2], "")] - if ( - ep.last_reply is not None - and ep.last_reply.get("finish_reason") == "length" - and canonical == merged_view - ): + merged_view = ep.sent[:ep.split_start] + [ + ('assistant', ep.merged_content.strip(), ep.sent[-1][2], '')] + if (ep.last_reply is not None and ep.last_reply.get('finish_reason') == 'length' + and canonical == merged_view): # Still truncated after the merge: continue the same turn again. return self._continue_generation(ep, request, canonical, tools_key) - if len(canonical) > len(merged_view) and canonical[: len(merged_view)] == merged_view: + if len(canonical) > len(merged_view) and canonical[:len(merged_view)] == merged_view: # The merged turn plus what the environment added (tool results, a new # question): an append onto the SAME ledger, so the banked assistant turn # keeps its sampled tokens instead of being dropped with a fresh segment. - if not ledger.observe(request.messages[len(merged_view) :]): + if not ledger.observe(request.messages[len(merged_view):]): return self._end_agent_truncated(ep, request) ep.merged_content = None merged_extends = True @@ -1570,11 +1561,8 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS if self.harness is not None and not merged_extends: noise = self.harness.noise_reply(request.messages, request.tools, request.params) extends = merged_extends or ( - ledger is not None - and tools_key == ep.tools_key - and len(canonical) > len(ep.sent) - and canonical[: len(ep.sent)] == ep.sent - ) + ledger is not None and tools_key == ep.tools_key and len(canonical) > len(ep.sent) + and canonical[:len(ep.sent)] == ep.sent) if noise is not None: # Housekeeping traffic the agent program does not expect a generation for: the # harness's reply answers it verbatim, costs no sampling, and rides the account @@ -1601,7 +1589,7 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS # Token-in: what the agent added since our last reply (tool results, its own # notes) is the environment's, appended masked. A merged continuation already # observed its suffix above. - if not merged_extends and not ledger.observe(request.messages[len(ep.sent) :]): + if not merged_extends and not ledger.observe(request.messages[len(ep.sent):]): return self._end_agent_truncated(ep, request) else: # The first request, or a history the agent rewrote (compacted, dropped a @@ -1652,9 +1640,8 @@ def _serve(self, ep: _Episode, request: EndpointRequest) -> tuple[list, RolloutS return self._finish(ep, segments=ep.segments) return self._continue(ep) - def _continue_generation( - self, ep: _Episode, request: EndpointRequest, canonical: list, tools_key: str - ) -> tuple[list, RolloutStatus]: + def _continue_generation(self, ep: _Episode, request: EndpointRequest, canonical: list, + tools_key: str) -> tuple[list, RolloutStatus]: """Extend the open assistant turn: the agent asked for more of a length-truncated reply. The ledger already holds the conversation including the truncated reply, so the sampler @@ -1670,15 +1657,15 @@ def _continue_generation( if ledger.unfit(params): # The turn is already banked: no room ends the episode truncated, as in _serve. return self._end_agent_truncated(ep, request) - prompt_tokens = len(ledger.input_feature.get("input_ids") or []) - prev_wire = ep.last_reply["message"] + prompt_tokens = len(ledger.input_feature.get('input_ids') or []) + prev_wire = ep.last_reply['message'] # Parse on the ledger's RAW contiguous text: the model generated it as one token # stream, and a call completing across the boundary must read as it was sampled. - prev_raw = ledger.messages[-1].get("content") or "" + prev_raw = ledger.messages[-1].get('content') or '' try: seq = self._generate(ep, ledger, params) except APIGenerationError as error: - raise EpisodeError(f"episode {ep.episode_id!r}: generation failed: {error}") from error + raise EpisodeError(f'episode {ep.episode_id!r}: generation failed: {error}') from error ledger.record_continuation(seq) ep.stop_reason = seq.stop_reason text = ledger.decode_tokens(seq) @@ -1686,22 +1673,22 @@ def _continue_generation( message = assistant_message(text, parsed, self.template.clean_tool_call(text) if parsed else text) if ep.merged_content is None: ep.split_start = len(ep.sent) - 1 - ep.merged_content = (prev_wire.get("content") or "").strip() + ep.merged_content = (prev_wire.get('content') or '').strip() # The agent's merged view is NOT the raw concatenation: ms-agent strips each stored # message at send time (its _format_input_message mutates content.strip()), so the # boundary whitespace of earlier pieces is gone before the next piece appends. # Track its exact recurrence echo_k = strip(echo_{k-1} + piece_k), or the second # continuation's merged echo reads as a rewrite and re-encodes assistant-ending # (the attempt4 crash, defect110 follow-up). - ep.merged_content = (ep.merged_content + (message.get("content") or "")).strip() + ep.merged_content = (ep.merged_content + (message.get('content') or '')).strip() ep.sent = canonical + [_canonical(message)] ep.tools_key = tools_key ep.last_reply = { - "message": message, - "finish_reason": "tool_calls" if parsed else ("length" if seq.stop_reason == "length" else "stop"), - "usage": { - "prompt_tokens": prompt_tokens, - "completion_tokens": len(seq.tokens or []), + 'message': message, + 'finish_reason': 'tool_calls' if parsed else ('length' if seq.stop_reason == 'length' else 'stop'), + 'usage': { + 'prompt_tokens': prompt_tokens, + 'completion_tokens': len(seq.tokens or []), }, } request.reply.set_result(dict(ep.last_reply)) diff --git a/tests/twinkle_agentic/test_localenv_resume.py b/tests/twinkle_agentic/test_localenv_resume.py index 15fac199d..d9df260de 100644 --- a/tests/twinkle_agentic/test_localenv_resume.py +++ b/tests/twinkle_agentic/test_localenv_resume.py @@ -1,4 +1,3 @@ -import hashlib import json import os import sys @@ -185,29 +184,3 @@ def corrupt_before_copy(source, destination): cold = LocalEnv(root=str(tmp_path)) with pytest.raises(UnsafeCheckpoint, match="checksum mismatch"): cold.restore_episode("cold", state_key, snapshot) - - -def test_v1_snapshot_remains_restorable(tmp_path): - env = LocalEnv(root=str(tmp_path)) - state_key = "run-1/group-0/episode-1/attempt-0" - generation_root = env._resume_root / env._state_dir_name(state_key) / "legacy" - workspace = generation_root / "workspace" - workspace.mkdir(parents=True) - (workspace / "state.txt").write_text("legacy", encoding="utf-8") - manifest = { - "format": "twinkle.localenv.v1", - "state_key": state_key, - "generation": "legacy", - "workspace": env._tree_digest(workspace), - } - manifest_bytes = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") - (generation_root / "manifest.json").write_bytes(manifest_bytes) - state = { - "format": "twinkle.localenv.v1", - "state_key": state_key, - "generation": "legacy", - "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), - } - - env.restore_episode("legacy", state_key, state) - assert env.step("legacy", "read_file", {"path": "state.txt"}).observation == "legacy" diff --git a/tests/twinkle_agentic/test_rollout_resume_store.py b/tests/twinkle_agentic/test_rollout_resume_store.py index c7d10ba6a..aea84829d 100644 --- a/tests/twinkle_agentic/test_rollout_resume_store.py +++ b/tests/twinkle_agentic/test_rollout_resume_store.py @@ -1,4 +1,3 @@ -import hashlib import json import pickle import pytest @@ -112,33 +111,8 @@ def test_journal_detects_model_checkpoint_commit_tampering(tmp_path): DurableJournal(path) -def test_journal_upgrades_legacy_prefix_and_starts_a_verifiable_signed_suffix(tmp_path): - path = tmp_path / "rollout.jsonl" - legacy_records = [ - {"seq": 0, "event": "PROMPT_ASSIGNED", "state_key": "run/0", "payload": {"row": 0}}, - {"seq": 1, "event": "GROUP_READY", "state_key": "run/0", "payload": {"members": 2}}, - ] - path.write_text( - "".join(json.dumps(record, sort_keys=True) + "\n" for record in legacy_records), encoding="utf-8" - ) - journal = DurableJournal(path) - assert [record.digest for record in journal.records()] == [None, None] - first_signed = journal.append(JournalEvent.BATCH_LEASED, "run/0", {"lease": "lease-0"}) - second_signed = journal.append(JournalEvent.GROUP_DROPPED, "run/0") - - assert first_signed.prev == "0" * 64 - assert second_signed.prev == first_signed.digest - raw = json.loads(path.read_text(encoding="utf-8").splitlines()[2]) - body = {key: raw[key] for key in ("seq", "event", "state_key", "payload", "prev")} - canonical = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") - assert raw["digest"] == hashlib.sha256(canonical).hexdigest() - reloaded = DurableJournal(path) - assert [record.seq for record in reloaded.records()] == [0, 1, 2, 3] - assert [record.digest for record in reloaded.records()][2:] == [first_signed.digest, second_signed.digest] - - -def test_journal_rejects_unsigned_record_after_signed_chain(tmp_path): +def test_journal_rejects_unsigned_record(tmp_path): path = tmp_path / "rollout.jsonl" journal = DurableJournal(path) journal.append(JournalEvent.PROMPT_ASSIGNED, "run/0") @@ -146,9 +120,9 @@ def test_journal_rejects_unsigned_record_after_signed_chain(tmp_path): with open(path, "a", encoding="utf-8") as stream: stream.write(json.dumps({"seq": 2, "event": "BATCH_LEASED", "state_key": "run/0", "payload": {}}) + "\n") - with pytest.raises(JournalCorrupt, match="unsigned record after signed"): + with pytest.raises(JournalCorrupt, match="corrupt journal tail"): journal.append(JournalEvent.GROUP_DROPPED, "run/0") - with pytest.raises(JournalCorrupt, match="unsigned record after signed"): + with pytest.raises(JournalCorrupt, match="corrupt record"): DurableJournal(path) @@ -164,29 +138,6 @@ def test_resume_store_pickle_rebuilds_filesystem_handles(tmp_path): assert rebuilt.journal.last("run/0").event is JournalEvent.PROMPT_ASSIGNED -def test_episode_shards_merge_legacy_main_journal_records(tmp_path): - legacy = ResumeStore(tmp_path, "run") - episode = "run/group/0/member/0" - effect = episode + "/effect/0/legacy" - legacy.journal.append(JournalEvent.TURN_COMMITTED, episode, {"legacy": True}) - legacy.journal.append(JournalEvent.TOOL_INTENT, effect, {"calls": []}) - legacy.journal.append(JournalEvent.TOOL_RESULT, effect, {"observations": ["old"]}) - main_records = len(legacy.journal.records()) - - store = ResumeStore(tmp_path, "run") - assert store.begin_effect(effect, {"calls": ["ignored"]}) == {"observations": ["old"]} - store.checkpoint_episode(episode, {"state": "new"}) - new_effect = episode + "/effect/1/new" - store.begin_effect(new_effect, {"calls": ["write"]}) - store.finish_effect(new_effect, {"observations": ["new"]}) - - assert len(store.journal.records()) == main_records - assert store.completed_effects(episode) == tuple(sorted((effect, new_effect))) - assert store.pending_effects(episode) == () - assert len(list((tmp_path / "episodes").glob("*.jsonl"))) == 1 - rebuilt = pickle.loads(pickle.dumps(store)) - assert rebuilt.completed_effects(episode) == tuple(sorted((effect, new_effect))) - def test_episode_shard_detects_payload_tampering_on_resume(tmp_path): store = ResumeStore(tmp_path, "run") diff --git a/tests/twinkle_agentic/test_streaming_driver_resume.py b/tests/twinkle_agentic/test_streaming_driver_resume.py index 7725fc29f..777c2456d 100644 --- a/tests/twinkle_agentic/test_streaming_driver_resume.py +++ b/tests/twinkle_agentic/test_streaming_driver_resume.py @@ -1251,47 +1251,6 @@ def discard_episode_state(self, state_key): driver.close() -@pytest.mark.parametrize("ready", [False, True]) -def test_legacy_v1_store_survives_snapshot_and_second_automatic_restore(tmp_path, ready): - run_id = "run-legacy-v1-ready" if ready else "run-legacy-v1-active" - legacy_rollout = _DoneRollout() if ready else _BlockingRollout() - legacy = StreamingDriver( - _prompts(1), legacy_rollout, batch_size=1, num_generations=1, max_steps=1, run_id=run_id - ) - legacy._admit() - if ready: - legacy._handle(*legacy._events.get_nowait()) - assert legacy._ready_rows == 1 - state = legacy.state_dict() - store = ResumeStore(tmp_path, run_id) - store.save_object("driver", run_id, state) - assert not store.has_object("driver-head", run_id) - assert store.load_objects("driver-groups") == [] - legacy.close() - - upgraded_rollout = _DoneRollout() if ready else _BlockingRollout() - upgraded = StreamingDriver( - _prompts(1), upgraded_rollout, batch_size=1, num_generations=1, max_steps=1, - resume_store=store, run_id=run_id, - ) - upgraded.load_state_dict() - upgraded.state_dict() - assert store.has_object("driver-head", run_id) - assert len(store.load_objects("driver-groups")) == 1 - upgraded.close() - - restored_rollout = _DoneRollout() if ready else _BlockingRollout() - restored = StreamingDriver( - _prompts(1), restored_rollout, batch_size=1, num_generations=1, max_steps=1, - resume_store=store, run_id=run_id, - ) - restored.load_state_dict() - if ready: - assert restored._ready_rows == 1 - else: - assert list(restored._groups) == ["0"] - restored.close() - def test_queued_step_and_score_actions_are_dropped_after_group_cleanup(tmp_path): store = ResumeStore(tmp_path, "run-stale-actions") From 812fa304877c99c10e89335322c4645cbec65853 Mon Sep 17 00:00:00 2001 From: abc <2301174943@qq.com> Date: Mon, 23 Nov 2026 00:35:59 +0800 Subject: [PATCH 45/45] test(agentic): track current driver snapshot key --- tests/twinkle_agentic/test_resume_boundaries.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/twinkle_agentic/test_resume_boundaries.py b/tests/twinkle_agentic/test_resume_boundaries.py index 0f4e4ac81..c16f84303 100644 --- a/tests/twinkle_agentic/test_resume_boundaries.py +++ b/tests/twinkle_agentic/test_resume_boundaries.py @@ -247,7 +247,7 @@ def test_snapshot_disk_io_does_not_hold_driver_lock(tmp_path, monkeypatch): def blocked_save(scope, key, value): result = original(scope, key, value) - if scope == "driver": + if scope == "driver-head": writing.set() assert finish_write.wait(2) return result