GLM-5.3 · RL

R05 · RL build

Correctness rejected

OpenBuild Qwen3-1.7B online GRPO 2dev · Open Build

—PERFORMANCE RATIO
100TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Tool activity

Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.

Main agentGLM-5.3 · 100 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
34Inspect
14Edit
1Build
25Validate
4Execute
12Profile
10Other

02 / EVENT SEQUENCE

Event timeline

Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.

Show event timelineHide event timeline67 groups · 100 calls

Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.

Main agent

  1. Inspect · Source & workspace

    Requested workspace inspection, file and log inspection and environment setup or inspection related to source & workspace.

    2 calls · #0001–#0002

    echo <val>ls -l -a <path> <n> > <path>head -n <n>envgrep -i <val>ls -l -a <path>
  2. Inspect · Task requirements

    Requested file and log inspection and workspace inspection related to task requirements.

    2 calls · #0003–#0004

    Read <path>cat <path>echo <flag>ls -l -a <path>
  3. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    4 calls · #0005–#0008

    Read <path>
  4. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0009–#0009

    Read <path>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0010–#0011

    Read <path>cd <path><command> <args>cat <val>
  6. Inspect · Task requirements

    Requested workspace inspection and file and log inspection related to task requirements.

    2 calls · #0012–#0013

    cd <path>ls -l -a <path> <val>echo <val>cat <val>
  7. Inspect · Device memory

    Requested runtime inspection, file and log inspection and script or workload execution related to device memory.

    1 call · #0014–#0014

    npu-smi info <n> >& <path>head -n <n>echo <flag>python3 -c <script>
  8. Inspect · Source & workspace

    Requested workspace inspection and file and log inspection related to source & workspace.

    1 call · #0015–#0015

    ls -l -a <path>cat <path>
  9. Execute · Benchmark & validation setup

    Requested workspace file updates, file and log inspection and environment setup or inspection related to benchmark & validation setup.

    1 call · #0016–#0016

    mkdir -p <path>cat > <path> <script>cd <path>env <vars> python3 <script> <n> >& <path>tail -n <n>
  10. Inspect · Source & workspace

    Requested file and log inspection, source searches and script or workload execution related to source & workspace.

    2 calls · #0017–#0018

    cd <path>cat > <path> <script><command> <args>grep -E <val>python3 <script> <n> >& <path>tail -n <n>
  11. Profile · Batching & scheduling

    Requested file and log inspection, environment setup or inspection and source searches related to batching & scheduling.

    1 call · #0019–#0019

    cd <path>cat > <path> <script>env <vars> python3 <script> <n> >& <path>grep -v <val>tail -n <n>
  12. Execute · Benchmark & validation setup

    Requested script or workload execution, environment setup or inspection and source searches related to benchmark & validation setup.

    1 call · #0020–#0020

    cd <path>python3 - <script>env <vars> python3 <script> <n> >& <path>grep -v <val>tail -n <n>
  13. Profile · Source & workspace

    Requested file and log inspection, environment setup or inspection and source searches related to source & workspace.

    1 call · #0021–#0021

    cd <path>cat > <path> <script>env <vars> python3 <script> <n> >& <path>grep -v <val>tail -n <n>
  14. Inspect · Runtime processes

    Requested file and log inspection, environment setup or inspection and source searches related to runtime processes.

    2 calls · #0022–#0023

    cd <path>cat > <path> <script>env <vars> python3 <script> <n> >& <path>grep -v <val>tail<command> <args>
    5 more command sketches
    cat <path>cat <path> <n> > <path>grep <flag> <args>head -n <n>echo <flag>
  15. Inspect · Source & workspace

    Requested file and log inspection, environment setup or inspection and source searches related to source & workspace.

    1 call · #0024–#0024

    cd <path>cat > <path> <script>env <vars> python3 <script> <n> >& <path>grep -v <val>tail -n <n>
  16. Execute · Benchmark & validation setup

    1 tool error

    Requested environment setup or inspection related to benchmark & validation setup.

    1 call · #0025–#0025

    cd <path>env <vars> python3 <script> <n> > <path>
  17. Profile · Source & workspace

    Requested file and log inspection and environment setup or inspection related to source & workspace.

    2 calls · #0026–#0027

    cd <path>cat > <path> <script>env <vars> python3 <script> <n> > <path>head -n <n>env <vars> python3 <script> <n> >& <path>
  18. Edit · Source & workspace

    Requested code edits, environment setup or inspection and file and log inspection related to source & workspace.

    1 call · #0028–#0028

    cd <path>sed -i <path> <path>env <vars> python3 <script> <n> >& <path>sed -n <path>head -n <n>
  19. Inspect · Batching & scheduling

    Requested file and log inspection, environment setup or inspection and source searches related to batching & scheduling.

    1 call · #0029–#0029

    cd <path>cat > <path> <script>env <vars> python3 <script> <n> >& <path>grep -E <val>
  20. Inspect · Source & workspace

    Requested script or workload execution and file and log inspection related to source & workspace.

    1 call · #0030–#0030

    cd <path>timeout <n> <val> <val> <val> <path> <n> >& <path>tail -n <n>
  21. Profile · Batching & scheduling

    Requested file and log inspection and source searches related to batching & scheduling.

    1 call · #0031–#0031

    cd <path>cat > <path> <script><command> <args>grep -E <val>
  22. Inspect · Attention kernels

    Requested file and log inspection, script or workload execution and source searches related to attention kernels.

    1 call · #0032–#0032

    cd <path>cat > <path> <script>timeout <n> <val> <val> <val> <path> <n> >& <path>grep -E <val>echo <flag>df -h <path> <path> <n> > <path>
    2 more command sketches
    <command> <args>tail -n <n>
  23. Inspect · Source & workspace

    Requested script or workload execution, file and log inspection and workspace file updates related to source & workspace.

    2 calls · #0033–#0034

    cd <path>timeout <n> <val> <val> <val> <path> <n> >& <path>tail -n <n>mkdir -p <path>ls -l -a <path>
  24. Edit · Source & workspace

    Requested code edits related to source & workspace.

    9 calls · #0035–#0043

    Write <path>Edit <path>
  25. Execute · Rollout generation

    Requested file and log inspection and workspace inspection related to rollout generation.

    1 call · #0044–#0044

    cd <path>cat > <path> <script>ls -l -a
  26. Build · Reward & policy updates

    Requested file and log inspection, workspace file updates and workspace inspection related to reward & policy updates.

    1 call · #0045–#0045

    cd <path>cat > <path> <script>chmod <val> <path> <path> <path> <path> <path>ls -l -apython3 -c <script>
  27. Profile · Task requirements

    Requested script or workload execution and file and log inspection related to task requirements.

    1 call · #0046–#0046

    cd <path><command> <args><script> <args>python3 -c <script>cat <path>
  28. Profile · Reward & policy updates

    1 tool error

    Requested script or workload execution related to reward & policy updates.

    1 call · #0047–#0047

    cd <path>python3 -c <script>
  29. Other · Reward & policy updates

    1 tool error

    Requested workspace file updates and script or workload execution related to reward & policy updates.

    1 call · #0048–#0048

    cd <path>cp <path> <path>python3 -c <script>
  30. Profile · Reward & policy updates

    Requested script or workload execution, file and log inspection and source searches related to reward & policy updates.

    2 calls · #0049–#0050

    cd <path>python3 -c <script> <n> >& <path>tail -n <n>cat > <path> <script>timeout <n> <val> <val> <path> <val> <path> <n> >& <path>grep -v <val>
  31. Edit · Source & workspace

    Requested code edits, script or workload execution and file and log inspection related to source & workspace.

    2 calls · #0051–#0052

    Edit <path>cd <path>python3 - <script>sed -i <val> <path>sed -n <val> <path>
  32. Inspect · Source & workspace

    Requested script or workload execution, source searches and file and log inspection related to source & workspace.

    3 calls · #0053–#0055

    cd <path>timeout <n> <val> <val> <path> <val> <path> <n> >& <path>grep -v <val>tail -n <n>python3 - <script>grep -n <val> <path>
    1 more command sketches
    head -n <n>
  33. Profile · Reward & policy updates

    Requested file and log inspection, script or workload execution and source searches related to reward & policy updates.

    1 call · #0056–#0056

    cd <path>cat > <path> <script>timeout <n> <val> <val> <path> <val> <path> <n> >& <path>grep -E <val>
  34. Validate · Benchmark & validation setup

    Requested environment setup or inspection, file and log inspection and workspace inspection related to benchmark & validation setup.

    2 calls · #0057–#0058

    cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>env <vars>ls <val> <n> > <path><command> <args>
    5 more command sketches
    head -n <n>xargs <val>echo <val>ls -l -a <val>cat <path> <n> > <path>
  35. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0059–#0059

    Edit <path>
  36. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0060–#0060

    cd <path>timeout <n> <val> <path> <n> >& <path>tail -n <n>echo <val>tail -n <n> <path> <n> > <path>
  37. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0061–#0061

    Edit <path>
  38. Inspect · Source & workspace

    Requested script or workload execution, file and log inspection and source searches related to source & workspace.

    1 call · #0062–#0062

    cd <path>python3 - <script>sed -n <val> <path>grep -n <val> <flag> <args>
  39. Validate · Reward & policy updates

    1 tool error

    Requested file and log inspection, workspace file updates and script or workload execution related to reward & policy updates.

    1 call · #0063–#0063

    cd <path>cat > <path> <script>chmod <val> <path>timeout <n> <path> <val> <n> >& <path>grep -v <val>tail -n <n>
  40. Validate · Benchmark & validation setup

    Requested execution waits, file and log inspection and source searches related to benchmark & validation setup.

    2 calls · #0064–#0065

    cd <path><command> <args>echo <val> >> <path>sleep <n>tail -n <n> <path> <n> > <path>echo <flag>
    3 more command sketches
    grep -v <val> <path>tail -n <n>echo <val>
  41. Validate · Reward & policy updates

    Requested script or workload execution, execution waits and source searches related to reward & policy updates.

    1 call · #0066–#0066

    cd <path>python3 - <script><command> <args>echo <val> >> <path>sleep <n>grep -v <val> <path>
    1 more command sketches
    tail -n <n>
  42. Other · Rollout generation

    Requested script or workload execution and source searches related to rollout generation.

    1 call · #0067–#0067

    cd <path>python3 - <script>grep -n <val> <path>
  43. Validate · Benchmark & validation setup

    Requested execution waits, source searches and file and log inspection related to benchmark & validation setup.

    1 call · #0068–#0068

    cd <path><command> <args>echo <val> >> <path>sleep <n>grep -v <val> <path>tail -n <n>
  44. Validate · Rollout generation

    Requested script or workload execution, source searches and execution waits related to rollout generation.

    1 call · #0069–#0069

    python3 - <script>grep -n <val> <path>cd <path><command> <args>echo <val> >> <path>sleep <n>
    2 more command sketches
    grep -v <val> <path>tail -n <n>
  45. Other · Checkpoints & weight state

    Requested script or workload execution related to checkpoints & weight state.

    1 call · #0070–#0070

    python3 - <script>
  46. Validate · Checkpoints & weight state

    Requested execution waits, source searches and file and log inspection related to checkpoints & weight state.

    1 call · #0071–#0071

    cd <path><command> <args>echo <val> >> <path>sleep <n>grep -v <val> <path>tail -n <n>
  47. Validate · Benchmark & validation setup

    Requested execution waits, source searches and file and log inspection related to benchmark & validation setup.

    1 call · #0072–#0072

    sleep <n>grep -v <val> <path>tail -n <n>echo <val>ls -l -a <path> <n> > <path>cat <path> <n> > <path>
  48. Profile · Checkpoints & weight state

    Requested file and log inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0073–#0073

    cd <path>cat > <path> <script>python3 <script> <path> <path> <val> <path> <n> >& <path>tail -n <n>
  49. Other · Rollout generation

    Requested script or workload execution and file and log inspection related to rollout generation.

    2 calls · #0074–#0075

    cd <path>python3 - <script>sed -n <val> <path>python3 -c <script>
  50. Other · Source & workspace

    Requested script or workload execution and source searches related to source & workspace.

    1 call · #0076–#0076

    python3 - <script>grep -n <val> <path>echo <val>cd <path>python3 -c <script>
  51. Validate · Benchmark & validation setup

    2 tool errors

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    6 calls · #0077–#0082

    cd <path><command> <args>echo <val> >> <path>sleep <n>echo <val>tail -n <n> <path>
    7 more command sketches
    python3 -c <script> <n> >& <path>tail -n <n>python3 -c <script>tail -n <n> <path> <n> > <path>rm -f <path>bash <script> > <path> <n> >& <path>ls -l -a <path> <n> > <path>
  52. Validate · Rollout generation

    Requested script or workload execution, source searches and file and log inspection related to rollout generation.

    1 call · #0083–#0083

    python3 - <script>cd <path><command> <args>echo <val> >> <path>grep -v <val> <path>tail -n <n>
    1 more command sketches
    echo <val>
  53. Other · Rollout generation

    Requested script or workload execution and source searches related to rollout generation.

    1 call · #0084–#0084

    cd <path>python3 - <script>grep -n <val> <flag> <args>
  54. Validate · Benchmark & validation setup

    1 tool error

    Requested source searches, file and log inspection and execution waits related to benchmark & validation setup.

    2 calls · #0085–#0086

    cd <path><command> <args>echo <val> >> <path>grep -v <val> <path>tail -n <n>echo <val>
    1 more command sketches
    sleep <n>
  55. Other · Reward & policy updates

    Requested script or workload execution related to reward & policy updates.

    1 call · #0087–#0087

    cd <path>python3 -c <script>
  56. Other · Source & workspace

    Requested script or workload execution and source searches related to source & workspace.

    1 call · #0088–#0088

    cd <path>python3 - <script>grep -n <val> <path>
  57. Validate · Benchmark & validation setup

    Requested script or workload execution, execution waits and source searches related to benchmark & validation setup.

    1 call · #0089–#0089

    cd <path>nohup <val> <val> <val> <n> <path> <val> > <path> <n> >& <path>sleep <n>grep -v <val> <path>tail -n <n>
  58. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    1 call · #0090–#0090

    grep -v <val> <path>tail -n <n>
  59. Other · Source & workspace

    Requested script or workload execution and source searches related to source & workspace.

    1 call · #0091–#0091

    python3 - <script>grep -n <val> <path>
  60. Validate · Rollout generation

    Requested script or workload execution, execution waits and source searches related to rollout generation.

    2 calls · #0092–#0093

    cd <path>nohup <val> <val> <val> <n> <path> <val> > <path> <n> >& <path>sleep <n>grep -v <val> <path>grep -E <val>python3 -c <script> <n> >& <path>
    2 more command sketches
    tail -n <n>grep -E <val> <path>
  61. Inspect · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0094–#0094

    python3 - <script>python3 -c <script>
  62. Validate · Benchmark & validation setup

    Requested script or workload execution, execution waits and source searches related to benchmark & validation setup.

    1 call · #0095–#0095

    cd <path>nohup <val> <val> <val> <n> <path> <val> > <path> <n> >& <path>sleep <n>grep -E <val> <path>
  63. Inspect · Rollout generation

    Requested execution waits, source searches and script or workload execution related to rollout generation.

    1 call · #0096–#0096

    sleep <n>grep -E <val> <path>python3 -c <script> <n> >& <path>tail -n <n>
  64. Validate · Benchmark & validation setup

    Requested script or workload execution, execution waits and source searches related to benchmark & validation setup.

    1 call · #0097–#0097

    python3 - <script>cd <path>nohup <val> <val> <val> <n> <path> <val> > <path> <n> >& <path>sleep <n>grep -E <val> <path>
  65. Inspect · Rollout generation

    Requested execution waits, source searches and script or workload execution related to rollout generation.

    1 call · #0098–#0098

    sleep <n>grep -E <val> <path>python3 -c <script> <n> >& <path>tail -n <n>
  66. Profile · Checkpoints & weight state

    Requested script or workload execution and source searches related to checkpoints & weight state.

    1 call · #0099–#0099

    cd <path>python3 -c <script> <n> >& <path>grep -v <val>
  67. Inspect · Source & workspace

    1 tool error

    Requested workspace inspection related to source & workspace.

    1 call · #0100–#0100

    cd <path>du <flag> <args>find <path> -type <val>sortecho <flag>find <path> -type <val> <flag> <args>
    1 more command sketches
    <command> <args>

03 / CANDIDATE ARTIFACT

Text patches & binary names

Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.

openbuild_solution · 16 changed files

Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..4fc6f7996deb1dc51e80cbbf9480fc6f3cee052a--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,32 @@+#!/usr/bin/env bash+# Offline bootstrap.  The base runtime already carries every dependency this+# solution needs (torch, torch_npu, transformers, safetensors, numpy), so the+# only work here is to verify that surface and record it.  Nothing is installed+# into, or removed from, the neutral base Python environment.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"++python3 - <<'PY'+import importlib.util+import json+import os+import sys++required = {+    "torch": None,+    "torch_npu": None,+    "transformers": None,+    "safetensors": None,+    "numpy": None,+    "obgrpo": os.environ.get("OPENBUILD_SOLUTION_DIR", ""),+}+missing = []+for name in required:+    if importlib.util.find_spec(name) is None:+        missing.append(name)+if missing:+    raise SystemExit(f"bootstrap: unavailable modules {sorted(missing)}")+print(json.dumps({"bootstrap": "ok", "modules": sorted(required)}))+PYdiff --git a/solution/cleanup.sh b/solution/cleanup.shnew file mode 100755index 0000000000000000000000000000000000000000..81a5be43e148c3a5ba08f9d9a0902445d2579a16--- /dev/null+++ b/solution/cleanup.sh@@ -0,0 +1,25 @@+#!/usr/bin/env bash+# Stop every worker this solution started, release every declared port and leave+# no device work deferred.  Safe to call repeatedly and after success or failure.+set -uo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"++python3 -m obgrpo.cleanup || true+# Belt and braces: make sure nothing from this solution still owns a device.+for pid_file in "${OPENBUILD_STATE_DIR:-/nonexistent}"/worker.json; do+  [ -f "$pid_file" ] || continue+  pgid=$(python3 -c "import json,sys;print(json.load(open(sys.argv[1])).get('pgid',0))" "$pid_file" 2>/dev/null || echo 0)+  case "$pgid" in+    ''|*[!0-9]*) ;;+    *) kill -TERM -- "-$pgid" 2>/dev/null || true+       sleep 1+       kill -KILL -- "-$pgid" 2>/dev/null || true ;;+  esac+done+rm -f "${OPENBUILD_STATE_DIR:-/nonexistent}"/obgrpo.sock \+      "${OPENBUILD_STATE_DIR:-/nonexistent}"/worker.json \+      "${OPENBUILD_STATE_DIR:-/nonexistent}"/ready.json+echo "obgrpo cleanup complete"+exit 0diff --git a/solution/execute.sh b/solution/execute.shnew file mode 100755index 0000000000000000000000000000000000000000..d0baad6ffb1fbf499343ab058860dc9bee8ea3ff--- /dev/null+++ b/solution/execute.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Scored online run: rollout -> task-owned reward -> advantage -> actor update ->+# policy refresh, for every committed update declared by the input manifest.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"++exec python3 -m obgrpo.execute "$@"diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..8e87cf16b0c47131f6ce441cb49329e25193cca3--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,13 @@+{+  "schema_version": 1,+  "kind": "openbuild_rl_solution",+  "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1",+  "model": "Qwen/Qwen3-1.7B",+  "offline_replay": true,+  "framework": "obgrpo (self-contained PyTorch + torch_npu GRPO stack: incremental-decode rollout engine, full-parameter BF16 actor with FP32 AdamW master state)",+  "bootstrap": "bootstrap.sh",+  "prepare": "prepare.sh",+  "execute": "execute.sh",+  "probe": "probe.sh",+  "cleanup": "cleanup.sh"+}diff --git a/solution/obgrpo/__init__.py b/solution/obgrpo/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..6230c677c8dc09047c58c3093f6fd70bae6a81d2--- /dev/null+++ b/solution/obgrpo/__init__.py@@ -0,0 +1,10 @@+"""Offline-replayable online GRPO/RLVR stack for Qwen3-1.7B on Ascend 910B.++Self-contained: PyTorch + torch_npu + transformers only, no external RL+framework, no network access.+"""++__all__ = ["TASK_ID", "MODEL_ID"]++TASK_ID = "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+MODEL_ID = "Qwen/Qwen3-1.7B"diff --git a/solution/obgrpo/algomath.py b/solution/obgrpo/algomath.pynew file mode 100644index 0000000000000000000000000000000000000000..9cef8106d028be6f95bb8d050b5f6278f1757d95--- /dev/null+++ b/solution/obgrpo/algomath.py@@ -0,0 +1,84 @@+"""Published GRPO / AdamW mathematics for this task.++The functions here mirror, in plain Python floats, the formulas published in+`workloads/public_contract.json` and the task-owned algorithm probe schema so+that the probe path and the device path provably use the same mathematics:++* group advantage  : (r - mean) / (sample_std + eps), all zeros when std == 0+* policy loss      : -min(ratio * A, clip(ratio) * A) averaged over tokens+* approx KL        : exp(-log_ratio) + log_ratio - 1        (k3 estimator)+* clip fraction    : fraction of tokens with ratio outside the clip band+"""++from __future__ import annotations++import math+import statistics++GROUP_EPSILON = 1e-6+CLIP_LOW = 0.2+CLIP_HIGH = 0.2+TOKEN_FLOOR = 1e-10+++def group_advantages(rewards: list[float], epsilon: float = GROUP_EPSILON) -> list[float]:+    """Sample-standard-deviation group normalisation of one prompt group."""+    mean = statistics.fmean(rewards)+    std = statistics.stdev(rewards)+    if std == 0.0:+        return [0.0] * len(rewards)+    return [(value - mean) / (std + epsilon) for value in rewards]+++def token_loss(advantage: float, old_logprob: float, current_logprob: float,+               clip_low: float = CLIP_LOW, clip_high: float = CLIP_HIGH) -> tuple[float, float, float, float]:+    """Return (loss, approx_kl, clipped_flag, ratio) for a single token."""+    log_ratio = current_logprob - old_logprob+    ratio = math.exp(log_ratio) if log_ratio < 700.0 else math.inf+    unclipped = ratio * advantage+    clipped_ratio = min(max(ratio, 1.0 - clip_low), 1.0 + clip_high)+    losses = -min(unclipped, clipped_ratio * advantage)+    kls = math.exp(-log_ratio) + log_ratio - 1.0 if log_ratio > -700.0 else math.inf+    clipped = 1.0 if ratio < 1.0 - clip_low or ratio > 1.0 + clip_high else 0.0+    return losses, kls, clipped, ratio+++def aggregate(advantage: float, old_row: list[float], current_row: list[float],+              clip_low: float = CLIP_LOW, clip_high: float = CLIP_HIGH) -> dict[str, list[float]]:+    """Per-token loss / kl / clip contributions for one trajectory."""+    losses: list[float] = []+    kls: list[float] = []+    clipped: list[float] = []+    ratios: list[float] = []+    for old, current in zip(old_row, current_row, strict=True):+        loss, kl, flag, ratio = token_loss(advantage, float(old), float(current), clip_low, clip_high)+        losses.append(loss)+        kls.append(kl)+        clipped.append(flag)+        ratios.append(ratio)+    return {"losses": losses, "kls": kls, "clipped": clipped, "ratios": ratios}+++# --------------------------------------------------------------------------------------+# Optimizer (AdamW) reference used by the checkpoint/probe path.  The device path uses+# torch.optim.AdamW with the identical configuration; this exists so the configuration+# is stated once, in one place.+# --------------------------------------------------------------------------------------+OPTIMIZER_CONFIG = {+    "kind": "adamw",+    "learning_rate": 1e-6,+    "weight_decay": 0.01,+    "betas": (0.9, 0.999),+    "eps": 1e-8,+    "clip_grad": 1.0,+    "state_dtype": "float32",+}++SAMPLING_CONFIG = {+    "responses_per_prompt": 4,+    "temperature": 0.7,+    "top_p": 0.8,+    "top_k": 20,+    "max_response_tokens": 256,+    "enable_thinking": False,+}diff --git a/solution/obgrpo/cleanup.py b/solution/obgrpo/cleanup.pynew file mode 100644index 0000000000000000000000000000000000000000..7ac31f833463cc177edd84aad0e5af8be3b5938e--- /dev/null+++ b/solution/obgrpo/cleanup.py@@ -0,0 +1,8 @@+"""cleanup.sh entrypoint: stop the worker and release every declared port."""++from __future__ import annotations++from .lifecycle import cleanup++if __name__ == "__main__":+    raise SystemExit(cleanup())diff --git a/solution/obgrpo/execute.py b/solution/obgrpo/execute.pynew file mode 100644index 0000000000000000000000000000000000000000..f79d0e2e85cb3a8df4a67bf6e1e83a2d876869cf--- /dev/null+++ b/solution/obgrpo/execute.py@@ -0,0 +1,19 @@+"""execute.sh entrypoint: foreground client that drives the loaded worker."""++from __future__ import annotations++import argparse++from .lifecycle import execute+++def main() -> int:+    parser = argparse.ArgumentParser()+    parser.add_argument("--input-manifest", required=True)+    parser.add_argument("--output-dir", required=True)+    args = parser.parse_args()+    return execute(args.input_manifest, args.output_dir)+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/solution/obgrpo/lifecycle.py b/solution/obgrpo/lifecycle.pynew file mode 100644index 0000000000000000000000000000000000000000..eab14a8d28d1d6be338d75789f94f215114e4c31--- /dev/null+++ b/solution/obgrpo/lifecycle.py@@ -0,0 +1,154 @@+"""prepare / execute / cleanup lifecycle helpers for the shell entrypoints."""++from __future__ import annotations++import json+import os+import signal+import socket+import subprocess+import sys+import time+from pathlib import Path++from . import worker+++def state_dir() -> Path:+    raw = os.environ.get("OPENBUILD_STATE_DIR")+    if not raw:+        raise SystemExit("OPENBUILD_STATE_DIR is not set")+    path = Path(raw)+    path.mkdir(parents=True, exist_ok=True)+    return path+++def solution_dir() -> Path:+    raw = os.environ.get("OPENBUILD_SOLUTION_DIR")+    return Path(raw).resolve() if raw else Path(__file__).resolve().parent.parent+++def stop_worker(grace: float = 25.0) -> dict:+    info_path = worker.worker_info_path()+    info: dict = {}+    if info_path.is_file():+        try:+            info = json.loads(info_path.read_text(encoding="utf-8"))+        except (OSError, ValueError):+            info = {}+    pgid = int(info.get("pgid", 0) or 0)+    pid = int(info.get("pid", 0) or 0)+    stopped = True+    if pgid > 1:+        for sig in (signal.SIGTERM, signal.SIGKILL):+            try:+                os.killpg(pgid, sig)+            except (ProcessLookupError, PermissionError):+                pass+            deadline = time.time() + (grace if sig == signal.SIGTERM else 10.0)+            stopped = not _group_alive(pgid)+            while time.time() < deadline and not stopped:+                time.sleep(0.2)+                stopped = not _group_alive(pgid)+            if stopped:+                break+    elif pid > 1:+        try:+            os.kill(pid, signal.SIGKILL)+        except (ProcessLookupError, PermissionError):+            pass+    worker.socket_path().unlink(missing_ok=True)+    info_path.unlink(missing_ok=True)+    (state_dir() / "ready.json").unlink(missing_ok=True)+    return {"pgid": pgid, "pid": pid, "stopped": stopped}+++def _group_alive(pgid: int) -> bool:+    try:+        os.killpg(pgid, 0)+    except ProcessLookupError:+        return False+    except PermissionError:+        return True+    return True+++def ping_worker(timeout: float = 5.0) -> bool:+    path = worker.socket_path()+    if not path.exists():+        return False+    try:+        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:+            sock.settimeout(timeout)+            sock.connect(str(path))+            sock.sendall((json.dumps({"kind": "ping"}) + "\n").encode())+            payload = worker._recv_line(sock)+            return payload.get("kind") == "pong"+    except (OSError, ValueError):+        return False+++def prepare() -> int:+    root = state_dir()+    stop_worker(grace=15.0)+    environment = dict(os.environ)+    environment["PYTHONPATH"] = os.pathsep.join(+        [str(solution_dir())] + ([environment["PYTHONPATH"]] if environment.get("PYTHONPATH") else [])+    )+    environment["PYTHONDONTWRITEBYTECODE"] = "0"+    log_handle = (root / worker.LOG_NAME).open("ab", buffering=0)+    process = subprocess.Popen(+        [sys.executable, "-m", "obgrpo.worker", "serve"],+        cwd=str(solution_dir()),+        env=environment,+        stdin=subprocess.DEVNULL,+        stdout=log_handle,+        stderr=subprocess.STDOUT,+        start_new_session=True,+    )+    deadline = time.time() + float(os.environ.get("OPENBUILD_PREPARE_BUDGET", "780"))+    ready = False+    while time.time() < deadline:+        if process.poll() is not None:+            break+        if ping_worker():+            ready = True+            break+        time.sleep(1.0)+    if not ready:+        print(f"worker did not become ready (exit={process.poll()})", file=sys.stderr)+        if (root / worker.LOG_NAME).is_file():+            print("--- worker log tail ---", file=sys.stderr)+            print(+                "".join((root / worker.LOG_NAME).read_text(errors="replace").splitlines(keepends=True)[-40:]),+                file=sys.stderr,+            )+        stop_worker()+        return 1+    info = json.loads(worker.worker_info_path().read_text(encoding="utf-8"))+    payload = {+        "status": "ready",+        "process_group_ids": [int(info["pgid"])],+        "ports": [],+        "worker_pid": int(info["pid"]),+        "socket": info["socket"],+        "log": info["log"],+        "device_ids": [int(v) for v in os.environ.get("OPENBUILD_DEVICE_IDS", "0").split(",") if v != ""],+        "model_path": os.environ.get("OPENBUILD_MODEL_PATH", ""),+        "restart_checkpoint": os.environ.get("OPENBUILD_RESTART_CHECKPOINT", ""),+        "framework": "obgrpo",+    }+    (root / "ready.json").write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")+    print(json.dumps({k: payload[k] for k in ("status", "process_group_ids", "ports", "device_ids")}, sort_keys=True))+    return 0+++def execute(input_manifest: str, output_dir: str) -> int:+    Path(output_dir).mkdir(parents=True, exist_ok=True)+    return worker.client(input_manifest, output_dir)+++def cleanup() -> int:+    report = stop_worker()+    print(json.dumps({"status": "clean", **{k: v for k, v in report.items()}}, sort_keys=True))+    return 0diff --git a/solution/obgrpo/online.py b/solution/obgrpo/online.pynew file mode 100644index 0000000000000000000000000000000000000000..a51f204e9084c04f0e5038375c90a248bf2f80f4--- /dev/null+++ b/solution/obgrpo/online.py@@ -0,0 +1,370 @@+"""The online GRPO/RLVR loop: rollout -> task-owned reward -> advantage -> actor update+-> policy refresh, repeated for the declared number of committed updates."""++from __future__ import annotations++import json+import math+import os+import statistics+import time+import urllib.error+import urllib.request+from pathlib import Path++from . import TASK_ID+from .algomath import GROUP_EPSILON, group_advantages+from .policy import ActorPolicy, per_request_uniforms++FRESHNESS_TOKENS = 8+FRESHNESS_ITEMS = 1+CHECK_OLD_LOGPROB_TOKENS = 16+++def seed_for(base: int, update: int, version: int, ordinal: int, response: int) -> int:+    return base + update * 100000 + version * 10000 + ordinal * 4 + response+++def informative_window(item: dict, threshold: float = 0.02) -> int:+    """First response position whose sampled probability is not saturated.++    Positions where the truncated distribution keeps a single token carry no+    evidence about the weights, so the observation windows start at the first+    position with genuine sampling entropy.+    """+    logprobs = item["old_logprobs"]+    for index, value in enumerate(logprobs):+        if abs(float(value)) > threshold:+            return index+    return 0+++class RewardService:+    """Task-owned verifier: POST /score_batch with a bearer token."""++    def __init__(self, url: str, token: str, attempts: int = 6):+        self.url = url.rstrip("/")+        self.token = token+        self.attempts = attempts+        self.calls = 0++    def score(self, items: list[tuple[str, str]]) -> list[float]:+        body = json.dumps(+            {"items": [{"prompt_id": prompt, "response_text": text} for prompt, text in items]}+        ).encode("utf-8")+        last = None+        for attempt in range(self.attempts):+            request = urllib.request.Request(+                f"{self.url}/score_batch",+                data=body,+                method="POST",+                headers={+                    "Content-Type": "application/json",+                    "Authorization": f"Bearer {self.token}",+                },+            )+            try:+                with urllib.request.urlopen(request, timeout=180) as response:+                    payload = json.loads(response.read().decode("utf-8"))+                rewards = [float(value) for value in payload["rewards"]]+                if len(rewards) != len(items):+                    raise ValueError("reward count differs from request size")+                self.calls += 1+                return rewards+            except (urllib.error.URLError, urllib.error.HTTPError, OSError, ValueError) as exc:  # noqa: PERF203+                last = exc+                time.sleep(min(2.0 ** attempt, 15.0))+        raise RuntimeError(f"reward service failed after {self.attempts} attempts: {last}")+++def run_online(+    policy: ActorPolicy,+    online_input: dict,+    output_dir: Path,+    action: str,+    reward: RewardService,+    log=print,+) -> dict:+    started = time.time()+    output_dir.mkdir(parents=True, exist_ok=True)+    base_seed = int(online_input["seed"])+    prompts = online_input["prompts"]+    restart_input = "source_checkpoint_update" in online_input+    if restart_input:+        updates_this_run = 1+    else:+        updates_this_run = int(online_input["committed_updates"])+    first_update = policy.committed_update + 1+    final_update = first_update + updates_this_run - 1++    encoded = {+        prompt["id"]: policy.encode_prompt(prompt["system_prompt"], prompt["question"]) for prompt in prompts+    }+    ordinals = {prompt["id"]: int(prompt["ordinal"]) for prompt in prompts}+    order = [prompt["id"] for prompt in prompts]++    observations: dict = {+        "compute_dtype": policy.compute_dtype_name,+        "optimizer_state_dtypes": ["float32"],+        "logical_parameter_count": policy.logical_parameter_count,+        "parameter_tensor_count": policy.parameter_tensor_count,+        "model_id": "Qwen/Qwen3-1.7B",+        "logical_device_ids": [policy.device_id],+        "updates": {},+        "freshness": [],+        "old_logprob_checks": [],+        "initial": {+            "parameter_projection": policy.parameter_projection(),+            "committed_update": policy.committed_update,+            "policy_version": policy.policy_version,+        },+    }+    if restart_input:+        observations["restart"] = {+            "source_checkpoint_update": int(online_input["source_checkpoint_update"]),+            "parameter_projection": observations["initial"]["parameter_projection"],+        }++    rows: list[dict] = []+    events: list[dict] = []+    consumed = 0+    freshness_updates = sorted({first_update, final_update})++    for update in range(first_update, final_update + 1):+        version = update - 1+        clock = time.time()+        requests: list[dict] = []+        for prompt_id in order:+            for response_ordinal in range(4):+                requests.append(+                    {+                        "prompt_id": prompt_id,+                        "prompt_ordinal": ordinals[prompt_id],+                        "response_ordinal": response_ordinal,+                        "request_seed": seed_for(base_seed, update, version, ordinals[prompt_id], response_ordinal),+                    }+                )+        uniforms = per_request_uniforms([item["request_seed"] for item in requests], policy.max_response_tokens)+        prompts_batch = [encoded[item["prompt_id"]] for item in requests]+        rolled = policy.generate(prompts_batch, uniforms)+        rollout_seconds = time.time() - clock++        clock = time.time()+        texts = [policy.decode(result.token_ids) for result in rolled]+        rewards = reward.score(+            [(item["prompt_id"], text) for item, text in zip(requests, texts, strict=True)]+        )+        reward_seconds = time.time() - clock++        clock = time.time()+        groups: dict[str, list[int]] = {}+        for index, item in enumerate(requests):+            groups.setdefault(item["prompt_id"], []).append(index)+        advantages = [0.0] * len(requests)+        group_report = {}+        for prompt_id, indices in groups.items():+            group_rewards = [rewards[index] for index in indices]+            normalized = group_advantages(group_rewards, GROUP_EPSILON)+            for index, value in zip(indices, normalized, strict=True):+                advantages[index] = value+            group_report[prompt_id] = {+                "rewards": group_rewards,+                "mean": statistics.fmean(group_rewards),+                "sample_std": statistics.stdev(group_rewards),+                "advantages": normalized,+            }+        items = []+        for item, result, reward_value, advantage in zip(+            requests, rolled, rewards, advantages, strict=True+        ):+            items.append(+                {+                    "prompt_ids": result.prompt_ids,+                    "token_ids": result.token_ids,+                    "old_logprobs": result.logprobs,+                    "advantage": float(advantage),+                    "prompt_id": item["prompt_id"],+                    "response_ordinal": item["response_ordinal"],+                }+            )+        advantage_seconds = time.time() - clock++        clock = time.time()+        metrics = policy.apply_update(items)+        actor_seconds = time.time() - clock+        policy.committed_update = update+        policy.policy_version = update++        clock = time.time()+        anchor = informative_window(items[0])+        span = min(CHECK_OLD_LOGPROB_TOKENS, max(1, len(items[0]["token_ids"]) - anchor))+        window = items[0]["token_ids"][anchor : anchor + span]+        if update == first_update:+            actor_side = [float(v) for v in policy.response_logprobs(+                [{"prompt_ids": items[0]["prompt_ids"], "token_ids": items[0]["token_ids"],+                  "report_start": anchor, "report_limit": span}]+            ).cpu().tolist()]+            observations["old_logprob_checks"].append(+                {+                    "update": update,+                    "policy_version": version,+                    "window_start": anchor,+                    "tokens": span,+                    "actor_logprobs": actor_side,+                    "rollout_logprobs": [float(v) for v in items[0]["old_logprobs"][anchor : anchor + span]],+                }+            )+        if update in freshness_updates:+            probe_items = []+            for item in items[:FRESHNESS_ITEMS]:+                probe_items.append(+                    {+                        "prompt_ids": item["prompt_ids"],+                        "token_ids": item["token_ids"],+                        "report_start": anchor,+                        "report_limit": FRESHNESS_TOKENS,+                    }+                )+            replay = [+                {"prompt_ids": item["prompt_ids"], "token_ids": item["token_ids"], "old_logprobs": item["old_logprobs"]}+                for item in items[:FRESHNESS_ITEMS]+            ]+            rollout_side = policy.rollout_logprobs(replay, FRESHNESS_TOKENS, start=anchor)+            actor_side = [float(v) for v in policy.response_logprobs(probe_items).cpu().tolist()]+            delta = max(+                (abs(left - right) for left, right in zip(actor_side, rollout_side, strict=True)), default=0.0+            )+            observations["freshness"].append(+                {+                    "update": update,+                    "policy_version": update,+                    "window_start": anchor,+                    "tokens": len(actor_side),+                    "actor_logprobs": actor_side,+                    "rollout_logprobs": rollout_side,+                    "max_abs_delta": delta,+                }+            )+        freshness_seconds = time.time() - clock++        observations["updates"][str(update)] = {+            "policy_loss": metrics["policy_loss"],+            "approx_kl": metrics["approx_kl"],+            "clip_fraction": metrics["clip_fraction"],+            "global_grad_norm": metrics["global_grad_norm"],+            "parameter_projection": policy.parameter_projection(),+            "mean_ratio": metrics.get("mean_ratio", 0.0),+            "response_tokens": metrics["response_tokens"],+            "optimizer_steps": policy.optimizer_steps,+            "rollout_seconds": rollout_seconds,+            "reward_seconds": reward_seconds,+            "advantage_seconds": advantage_seconds,+            "actor_seconds": actor_seconds,+            "freshness_seconds": freshness_seconds,+            "groups": group_report,+        }+        events.append(+            {+                "update": update,+                "trajectory": version,+                "actor_before": update - 1,+                "actor_after": update,+                "rollout_after_sync": update,+                "lag": 0,+            }+        )+        for item, result, reward_value in zip(items, rolled, rewards, strict=True):+            consumed += len(result.token_ids)+            rows.append(+                {+                    "update": update,+                    "prompt_id": item["prompt_id"],+                    "prompt_ordinal": ordinals[item["prompt_id"]],+                    "response_ordinal": item["response_ordinal"],+                    "request_seed": seed_for(+                        base_seed, update, version, ordinals[item["prompt_id"]], item["response_ordinal"]+                    ),+                    "generating_policy_version": version,+                    "response_token_ids": result.token_ids,+                    "response_text": policy.decode(result.token_ids),+                    "old_logprobs": result.logprobs,+                    "reward": float(reward_value),+                    "advantage": float(item["advantage"]),+                }+            )+        log(+            f"update {update}: tokens={metrics['response_tokens']} loss={metrics['policy_loss']:.6f} "+            f"kl={metrics['approx_kl']:.6f} clip={metrics['clip_fraction']:.4f} "+            f"gnorm={metrics['global_grad_norm']:.4f} reward={sum(rewards):.1f} "+            f"rollout={rollout_seconds:.2f}s actor={actor_seconds:.2f}s"+        )++    checkpoint_manifest_path = None+    checkpoint_root = output_dir / "checkpoint"+    checkpoint = policy.save_checkpoint(checkpoint_root)+    files = checkpoint.pop("files")+    manifest = {+        "schema_version": 1,+        "kind": "openbuild_rl_checkpoint",+        "task_id": TASK_ID,+        "committed_update": policy.committed_update,+        "next_update": policy.committed_update + 1,+        "state_components": [+            "model",+            "optimizer",+            "scheduler",+            "committed_update",+            "policy_version",+            "data_cursor",+        ],+        "files": files,+    }+    (checkpoint_root / "manifest.json").write_text(+        json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"+    )+    files.append("manifest.json")+    manifest["files"] = files+    checkpoint_manifest_path = "checkpoint/manifest.json"++    with (output_dir / "trajectories.jsonl").open("w", encoding="utf-8") as handle:+        for row in rows:+            handle.write(json.dumps(row, allow_nan=False, separators=(",", ":"), sort_keys=True) + "\n")++    result = {+        "schema_version": 1,+        "kind": "openbuild_rl_result",+        "task_id": TASK_ID,+        "status": "completed",+        "action": action,+        "committed_updates": policy.committed_update,+        "accepted_trajectories": len(rows),+        "consumed_response_tokens": consumed,+        "logical_device_ids": [policy.device_id],+        "policy_versions": events,+        "trajectory_path": "trajectories.jsonl",+        "observation_path": "observations.json",+        "checkpoint_manifest_path": checkpoint_manifest_path,+    }+    observations["wall_time_seconds"] = time.time() - started+    observations["accepted_trajectories"] = len(rows)+    observations["consumed_response_tokens"] = consumed+    observations["sampling"] = policy.sampling+    observations["optimizer"] = {+        "kind": "adamw",+        "learning_rate": 1e-6,+        "weight_decay": 0.01,+        "betas": [0.9, 0.999],+        "clip_grad": 1.0,+        "state_dtype": "float32",+        "steps": policy.optimizer_steps,+    }+    observations["timing"] = {+        "wall_time_seconds": observations["wall_time_seconds"],+    }+    (output_dir / "result.json").write_text(+        json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8"+    )+    (output_dir / "observations.json").write_text(+        json.dumps(observations, indent=2, sort_keys=True) + "\n", encoding="utf-8"+    )+    return resultdiff --git a/solution/obgrpo/policy.py b/solution/obgrpo/policy.pynew file mode 100644index 0000000000000000000000000000000000000000..9cd6cd7ee23bb8b65a63869e1d4443697d3cfa85--- /dev/null+++ b/solution/obgrpo/policy.py@@ -0,0 +1,536 @@+"""Rollout engine + full-parameter actor for the online GRPO loop.++Layout (one Ascend 910B device per engine instance):++  BF16  `model`      - deployed policy used for both rollout and actor compute+  FP32  `masters`    - authoritative full-parameter actor state+  FP32  Adam state   - exp_avg / exp_avg_sq owned by torch.optim.AdamW++Rollout and actor share the same physical weights, so a committed update is+reflected in the rollout policy by construction; the rollout engine still keeps+its own incremental-decode probability path, and the freshness observation+compares that path against the actor's teacher-forced path after every+committed update.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path++import numpy as np+import torch+import torch_npu  # noqa: F401  (registers the npu backend)++from .algomath import (+    CLIP_HIGH,+    CLIP_LOW,+    OPTIMIZER_CONFIG,+    SAMPLING_CONFIG,+    TOKEN_FLOOR,+)++PROJECTION_SEED = 20260828+PROJECTION_DIM = 1 << 21+++def _synchronize() -> None:+    torch.npu.synchronize()+++# --------------------------------------------------------------------------------------+# Sampling distribution: temperature + top-k + top-p, renormalised.  The policy *is* this+# distribution, so both the rollout log probabilities and the actor log probabilities used+# in the clipped ratio are taken from it.+# --------------------------------------------------------------------------------------+def truncated_probs(logits: torch.Tensor, temperature: float, top_k: int, top_p: float):+    """Return (probabilities, token ids) over the truncated support, sorted descending."""+    scaled = logits / temperature+    k = min(int(top_k), scaled.shape[-1])+    top_values, top_ids = torch.topk(scaled, k, dim=-1)+    probs = torch.softmax(top_values.float(), dim=-1)+    cumulative = torch.cumsum(probs, dim=-1)+    keep = (cumulative - probs) < float(top_p)+    keep[..., 0] = True+    kept = probs * keep.to(probs.dtype)+    kept = kept / kept.sum(dim=-1, keepdim=True)+    return kept, top_ids+++def token_logprob(logits: torch.Tensor, tokens: torch.Tensor, cfg: dict) -> torch.Tensor:+    """Log probability of `tokens` under the truncated sampling distribution."""+    probs, top_ids = truncated_probs(logits, cfg["temperature"], cfg["top_k"], cfg["top_p"])+    match = (top_ids == tokens.unsqueeze(-1)).to(probs.dtype)+    picked = (probs * match).sum(dim=-1)+    return torch.log(picked.clamp_min(TOKEN_FLOOR))+++def sample_tokens(logits: torch.Tensor, uniforms: torch.Tensor, cfg: dict):+    """Sample one token per row from the truncated distribution using per-row unit draws."""+    probs, top_ids = truncated_probs(logits, cfg["temperature"], cfg["top_k"], cfg["top_p"])+    cumulative = torch.cumsum(probs, dim=-1)+    pick = (cumulative < uniforms.unsqueeze(-1)).sum(dim=-1).to(torch.long)+    pick = pick.clamp(max=probs.shape[-1] - 1)+    token = top_ids.gather(-1, pick.unsqueeze(-1)).squeeze(-1)+    logprob = torch.log(probs.gather(-1, pick.unsqueeze(-1)).squeeze(-1).clamp_min(TOKEN_FLOOR))+    return token, logprob+++def _as_list(value) -> list:+    if value is None:+        return []+    if isinstance(value, (list, tuple)):+        return list(value)+    return [value]+++@dataclass+class RolloutResult:+    token_ids: list[int]+    logprobs: list[float]+    prompt_ids: list[int]+++class ActorPolicy:+    """Deployed BF16 policy plus its FP32 master / AdamW state."""++    def __init__(self, model_path: str, device_id: int, dtype=torch.bfloat16):+        from transformers import AutoModelForCausalLM, AutoTokenizer++        self.device_id = int(device_id)+        torch.npu.set_device(self.device_id)+        torch.npu.init()+        self.device = torch.device("npu", self.device_id)+        self.dtype = dtype+        self.compute_dtype_name = "bfloat16" if dtype is torch.bfloat16 else str(dtype).replace("torch.", "")+        self.model_path = model_path+        self.tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True, trust_remote_code=True)+        self.model = AutoModelForCausalLM.from_pretrained(+            model_path,+            dtype=dtype,+            local_files_only=True,+            trust_remote_code=True,+            attn_implementation="sdpa",+        )+        self.model.eval().to(self.device)+        self.eos_ids = [int(v) for v in _as_list(self.model.generation_config.eos_token_id)]+        self.pad_id = int(self.model.generation_config.pad_token_id or self.eos_ids[-1])+        self.params = [p for p in self.model.parameters() if p.requires_grad]+        self.masters = [p.detach().to(self.device, torch.float32).clone() for p in self.params]+        for master in self.masters:+            master.requires_grad_(False)+        self.optimizer = self._fresh_optimizer()+        self.sampling = dict(SAMPLING_CONFIG)+        self.max_response_tokens = int(self.sampling["max_response_tokens"])+        self.committed_update = 0+        self.policy_version = 0+        self.optimizer_steps = 0+        self._projection_selector = None+        self._projection_cache = None+        self.logical_parameter_count = int(sum(p.numel() for p in self.params))+        self.parameter_tensor_count = int(len(self.params))++    def _fresh_optimizer(self):+        cfg = OPTIMIZER_CONFIG+        return torch.optim.AdamW(+            self.masters,+            lr=cfg["learning_rate"],+            betas=tuple(cfg["betas"]),+            eps=cfg["eps"],+            weight_decay=cfg["weight_decay"],+        )++    # -- prompt encoding ----------------------------------------------------------------+    def encode_prompt(self, system_prompt: str, question: str) -> list[int]:+        text = self.tokenizer.apply_chat_template(+            [{"role": "system", "content": system_prompt}, {"role": "user", "content": question}],+            tokenize=False,+            add_generation_prompt=True,+            enable_thinking=False,+        )+        return [int(v) for v in self.tokenizer.encode(text, add_special_tokens=False)]++    def decode(self, token_ids: list[int]) -> str:+        return self.tokenizer.decode(token_ids, skip_special_tokens=True)++    # -- parameter projection -----------------------------------------------------------+    def _selector(self):+        if self._projection_selector is None:+            per = max(1, PROJECTION_DIM // max(1, len(self.masters)))+            pieces = []+            for master in self.masters:+                total = master.numel()+                if total == 0:+                    continue+                step = max(1, total // per)+                pieces.append(torch.arange(0, total, step, device=master.device)[:per])+            self._projection_selector = pieces+        return self._projection_selector++    def _projection_direction(self, size: int) -> np.ndarray:+        if self._projection_cache is None:+            gen = np.random.default_rng(PROJECTION_SEED)+            values = gen.standard_normal(PROJECTION_DIM).astype(np.float64)+            self._projection_cache = values+        return self._projection_cache[:size]++    def parameter_projection(self) -> float:+        """Fixed deterministic linear functional of the FP32 actor state."""+        pieces = self._selector()+        picked = [master.reshape(-1)[idx] for master, idx in zip(self.masters, pieces, strict=True)]+        sampled = torch.cat(picked).to(torch.float32).cpu().numpy().astype(np.float64)+        return float(np.dot(self._projection_direction(sampled.shape[0]), sampled))++    # -- rollout ------------------------------------------------------------------------+    @torch.inference_mode()+    def generate(self, prompts: list[list[int]], uniforms: np.ndarray) -> list[RolloutResult]:+        cfg = self.sampling+        batch = len(prompts)+        lengths = [len(p) for p in prompts]+        width = max(lengths)+        span = self.max_response_tokens+        device = self.device+        input_ids = torch.full((batch, width), self.pad_id, dtype=torch.long, device=device)+        for row, prompt in enumerate(prompts):+            input_ids[row, : len(prompt)] = torch.tensor(prompt, dtype=torch.long, device=device)+        mask = torch.zeros((batch, width + span + 1), dtype=torch.long, device=device)+        for row, length in enumerate(lengths):+            mask[row, :length] = 1+        out = self.model(input_ids, attention_mask=mask[:, :width], use_cache=True)+        past = out.past_key_values+        rows = torch.arange(batch, device=device)+        tail = torch.tensor([length - 1 for length in lengths], device=device)+        logits = out.logits[rows, tail].float()+        draws = torch.from_numpy(np.asarray(uniforms, dtype=np.float32)).to(device)+        if draws.dim() != 2 or draws.shape[0] != batch:+            raise ValueError("uniform matrix rows must match the request batch")+        if draws.shape[1] < span:+            pad = torch.from_numpy(+                np.asarray(per_request_uniforms(list(range(batch)), span - draws.shape[1]), dtype=np.float32)+            ).to(device)+            draws = torch.cat([draws, pad], dim=1)+        tokens = torch.full((batch, span), self.pad_id, dtype=torch.long, device=device)+        scores = torch.zeros((batch, span), dtype=torch.float32, device=device)+        done = torch.zeros(batch, dtype=torch.bool, device=device)+        stops = torch.tensor(self.eos_ids, dtype=torch.long, device=device)+        positions = torch.tensor([[length] for length in lengths], dtype=torch.long, device=device)+        taken = 0+        for step in range(span):+            token, logprob = sample_tokens(logits, draws[:, step], cfg)+            token = torch.where(done, torch.full_like(token, self.pad_id), token)+            tokens[:, step] = token+            scores[:, step] = logprob+            done = done | torch.isin(token, stops)+            taken = step + 1+            if bool(done.all()) or step + 1 >= span:+                break+            mask[:, width + step] = 1+            nxt = self.model(+                token.unsqueeze(1),+                past_key_values=past,+                attention_mask=mask[:, : width + step + 1],+                position_ids=positions,+                use_cache=True,+            )+            past = nxt.past_key_values+            logits = nxt.logits[:, -1, :].float()+            positions = positions + 1+        _synchronize()+        token_cpu = tokens.cpu().tolist()+        score_cpu = scores.cpu().tolist()+        del past, out, nxt+        torch.npu.empty_cache()+        results: list[RolloutResult] = []+        for row in range(batch):+            row_ids = [int(v) for v in token_cpu[row][:taken]]+            cut = len(row_ids)+            for index, value in enumerate(row_ids):+                if value in self.eos_ids:+                    cut = index + 1+                    break+            results.append(+                RolloutResult(+                    token_ids=row_ids[:cut],+                    logprobs=[float(v) for v in score_cpu[row][:cut]],+                    prompt_ids=list(prompts[row]),+                )+            )+        return results++    # -- actor teacher-forced log probabilities -----------------------------------------+    def _padded_inputs(self, sequences: list[list[int]]):+        batch = len(sequences)+        lengths = [len(s) for s in sequences]+        width = max(lengths)+        input_ids = torch.full((batch, width), self.pad_id, dtype=torch.long, device=self.device)+        mask = torch.zeros((batch, width), dtype=torch.long, device=self.device)+        for row, sequence in enumerate(sequences):+            input_ids[row, : len(sequence)] = torch.tensor(sequence, dtype=torch.long, device=self.device)+            mask[row, : len(sequence)] = 1+        return input_ids, mask, lengths++    def response_logprobs(self, items: list[dict], chunk: int = 384):+        """Teacher-forced log probabilities for the reported window of each item.++        The input always carries the full prompt + response prefix, because the+        distribution of a response token depends on every token before it;+        `report_start` / `report_limit` only select which positions are returned.+        """+        sequences = [item["prompt_ids"] + item["token_ids"] for item in items]+        prompt_lengths = [len(item["prompt_ids"]) for item in items]+        input_ids, mask, _ = self._padded_inputs(sequences)+        hidden = self.model.model(input_ids=input_ids, attention_mask=mask, use_cache=False).last_hidden_state+        picks = []+        flat: list[int] = []+        for row, item in enumerate(items):+            begin = int(item.get("report_start", 0))+            span = len(item["token_ids"]) - begin+            limit = item.get("report_limit")+            if limit is not None:+                span = min(span, int(limit))+            start = prompt_lengths[row] - 1 + begin+            picks.append(hidden[row, start : start + span])+            flat.extend(int(t) for t in item["token_ids"][begin : begin + span])+        gathered = torch.cat(picks, dim=0)+        flat_tokens = torch.tensor(flat, dtype=torch.long, device=self.device)+        values = []+        for start in range(0, gathered.shape[0], chunk):+            block = gathered[start : start + chunk]+            logits = self.model.lm_head(block).float()+            values.append(token_logprob(logits, flat_tokens[start : start + chunk], self.sampling))+        result = torch.cat(values, dim=0)+        del hidden, gathered, picks, values+        return result++    # -- actor update -------------------------------------------------------------------+    def apply_update(self, items: list[dict], micro_batch: int = 4, capture_first: int = 0):+        """One PPO epoch over `items`, then one full-parameter AdamW step.++        Each item carries `prompt_ids`, `token_ids`, `old_logprobs`, `advantage`.+        Returns per-update metrics plus, when asked, the pre-update actor log+        probabilities of the first `capture_first` tokens of `items[0]`.+        """+        total_tokens = sum(len(item["token_ids"]) for item in items)+        order = sorted(range(len(items)), key=lambda i: -(len(items[i]["prompt_ids"]) + len(items[i]["token_ids"])))+        captured: list[float] = []+        if capture_first:+            with torch.no_grad():+                head = self.response_logprobs([items[0]])+            captured = [float(v) for v in head[:capture_first].cpu().tolist()]+            del head+        loss_sum = 0.0+        kl_sum = 0.0+        clip_sum = 0.0+        for param in self.params:+            param.grad = None+        for start in range(0, len(order), micro_batch):+            chunk_items = [items[i] for i in order[start : start + micro_batch]]+            current = self.response_logprobs(chunk_items)+            old = torch.tensor(+                [float(v) for item in chunk_items for v in item["old_logprobs"]],+                dtype=torch.float32,+                device=self.device,+            )+            advantage = torch.tensor(+                [float(item["advantage"]) for item in chunk_items for _ in item["token_ids"]],+                dtype=torch.float32,+                device=self.device,+            )+            log_ratio = current - old+            ratio = torch.exp(log_ratio)+            unclipped = ratio * advantage+            clipped = torch.clamp(ratio, 1.0 - CLIP_LOW, 1.0 + CLIP_HIGH) * advantage+            per_token = -torch.minimum(unclipped, clipped)+            per_token.sum().div(float(total_tokens)).backward()+            with torch.no_grad():+                loss_sum += float(per_token.sum())+                kl_sum += float((torch.exp(-log_ratio) + log_ratio - 1.0).sum())+                clip_sum += float(((ratio < 1.0 - CLIP_LOW) | (ratio > 1.0 + CLIP_HIGH)).to(torch.float32).sum())+            del current, old, advantage, log_ratio, ratio, unclipped, clipped, per_token+        for param, master in zip(self.params, self.masters, strict=True):+            if param.grad is not None:+                master.grad = param.grad.detach().to(torch.float32)+            else:+                master.grad = torch.zeros_like(master)+            param.grad = None+        grad_norm = torch.nn.utils.clip_grad_norm_(self.masters, OPTIMIZER_CONFIG["clip_grad"])+        self.optimizer.step()+        self.optimizer_steps += 1+        with torch.no_grad():+            for param, master in zip(self.params, self.masters, strict=True):+                param.copy_(master)+            for master in self.masters:+                master.grad = None+        _synchronize()+        return {+            "policy_loss": loss_sum / total_tokens,+            "approx_kl": kl_sum / total_tokens,+            "clip_fraction": clip_sum / total_tokens,+            "global_grad_norm": float(grad_norm),+            "response_tokens": total_tokens,+            "captured_actor_logprobs": captured,+        }++    # -- rollout-path freshness evidence ------------------------------------------------+    @torch.inference_mode()+    def rollout_logprobs(self, items: list[dict], limit: int, start: int = 0) -> list[float]:+        """Re-run the incremental-decode rollout path over recorded responses."""+        cfg = self.sampling+        prompts = [item["prompt_ids"] for item in items]+        batch = len(prompts)+        lengths = [len(p) for p in prompts]+        width = max(lengths)+        device = self.device+        input_ids = torch.full((batch, width), self.pad_id, dtype=torch.long, device=device)+        steps = start + limit+        mask = torch.zeros((batch, width + steps + 1), dtype=torch.long, device=device)+        for row, prompt in enumerate(prompts):+            input_ids[row, : len(prompt)] = torch.tensor(prompt, dtype=torch.long, device=device)+            mask[row, : len(prompt)] = 1+        out = self.model(input_ids, attention_mask=mask[:, :width], use_cache=True)+        past = out.past_key_values+        rows = torch.arange(batch, device=device)+        tail = torch.tensor([length - 1 for length in lengths], device=device)+        logits = out.logits[rows, tail].float()+        positions = torch.tensor([[length] for length in lengths], dtype=torch.long, device=device)+        collected: list[list[float]] = [[] for _ in range(batch)]+        for step in range(steps):+            tokens = torch.tensor(+                [int(item["token_ids"][min(step, len(item["token_ids"]) - 1)]) for item in items],+                dtype=torch.long,+                device=device,+            )+            values = token_logprob(logits, tokens, cfg)+            for row in range(batch):+                if start <= step < len(items[row]["token_ids"]):+                    collected[row].append(float(values[row]))+            if step + 1 >= steps:+                break+            mask[:, width + step] = 1+            nxt = self.model(+                tokens.unsqueeze(1),+                past_key_values=past,+                attention_mask=mask[:, : width + step + 1],+                position_ids=positions,+                use_cache=True,+            )+            past = nxt.past_key_values+            logits = nxt.logits[:, -1, :].float()+            positions = positions + 1+        _synchronize()+        del past, out, nxt+        torch.npu.empty_cache()+        return [value for row in collected for value in row]++    # -- warmup -------------------------------------------------------------------------+    def warmup(self) -> dict:+        """Exercise rollout + actor update kernels, then restore pristine state."""+        snapshot = [master.detach().to("cpu").clone() for master in self.masters]+        before = self.parameter_projection()+        synthetic = [[self.pad_id] * 8, [self.pad_id] * 9]+        uniforms = per_request_uniforms([11, 12], self.max_response_tokens)+        results = self.generate(synthetic, uniforms)+        items = []+        for result in results:+            length = max(1, len(result.token_ids))+            items.append(+                {+                    "prompt_ids": result.prompt_ids,+                    "token_ids": result.token_ids[:length],+                    "old_logprobs": result.logprobs[:length],+                    "advantage": 0.0,+                }+            )+        self.apply_update(items, micro_batch=2)+        self.optimizer = self._fresh_optimizer()+        with torch.no_grad():+            for master, saved in zip(self.masters, snapshot, strict=True):+                master.copy_(saved.to(self.device, torch.float32))+            for param, master in zip(self.params, self.masters, strict=True):+                param.copy_(master)+        self.optimizer_steps = 0+        after = self.parameter_projection()+        _synchronize()+        return {"rollout_steps": len(items), "projection_before": before, "projection_after": after}++    # -- checkpoint ---------------------------------------------------------------------+    def state_summary(self) -> dict:+        return {+            "committed_update": int(self.committed_update),+            "policy_version": int(self.policy_version),+            "optimizer_steps": int(self.optimizer_steps),+            "scheduler": {+                "kind": "constant",+                "learning_rate": OPTIMIZER_CONFIG["learning_rate"],+                "step": int(self.optimizer_steps),+            },+            "data_cursor": {+                "committed_update": int(self.committed_update),+                "next_update": int(self.committed_update) + 1,+            },+        }++    def save_checkpoint(self, root: Path) -> dict:+        from safetensors.torch import save_file++        root.mkdir(parents=True, exist_ok=True)+        files = []+        model_state = {+            f"master.{index}": master.detach().to("cpu").contiguous()+            for index, master in enumerate(self.masters)+        }+        save_file(model_state, str(root / "model.safetensors"))+        files.append("model.safetensors")+        del model_state+        packed = {}+        snapshot = self.optimizer.state_dict()+        for param_index, state in snapshot["state"].items():+            for name, tensor in state.items():+                if torch.is_tensor(tensor):+                    packed[f"{param_index}.{name}"] = tensor.detach().to("cpu").contiguous()+        del snapshot+        save_file(packed, str(root / "optimizer.safetensors"))+        files.append("optimizer.safetensors")+        del packed+        summary = self.state_summary()+        summary["optimizer_config"] = OPTIMIZER_CONFIG+        summary["sampling"] = self.sampling+        summary["logical_parameter_count"] = self.logical_parameter_count+        summary["parameter_tensor_count"] = self.parameter_tensor_count+        (root / "state.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8")+        files.append("state.json")+        return {"files": files, **summary}++    def load_checkpoint(self, root: Path) -> dict:+        from safetensors.torch import load_file++        summary = json.loads((root / "state.json").read_text(encoding="utf-8"))+        model_state = load_file(str(root / "model.safetensors"))+        with torch.no_grad():+            for index, master in enumerate(self.masters):+                master.copy_(model_state[f"master.{index}"].to(self.device, torch.float32))+            for param, master in zip(self.params, self.masters, strict=True):+                param.copy_(master)+        del model_state+        optimizer_state = load_file(str(root / "optimizer.safetensors"))+        snapshot = self.optimizer.state_dict()+        for param_index, entry in snapshot["state"].items():+            for name in list(entry):+                key = f"{param_index}.{name}"+                if key in optimizer_state:+                    entry[name] = optimizer_state[key].to(self.device, torch.float32)+        self.optimizer.load_state_dict(snapshot)+        self.committed_update = int(summary["committed_update"])+        self.policy_version = int(summary["policy_version"])+        self.optimizer_steps = int(summary["optimizer_steps"])+        _synchronize()+        return summary+++def per_request_uniforms(seeds: list[int], width: int) -> np.ndarray:+    """Deterministic per-request unit draws: row i is PCG64(seed_i).random(width)."""+    matrix = np.empty((len(seeds), width), dtype=np.float64)+    for row, seed in enumerate(seeds):+        matrix[row] = np.random.Generator(np.random.PCG64(int(seed))).random(width)+    return matrixdiff --git a/solution/obgrpo/prepare.py b/solution/obgrpo/prepare.pynew file mode 100644index 0000000000000000000000000000000000000000..294a817f73e9928d3c358820d90a7a8ae9ea5323--- /dev/null+++ b/solution/obgrpo/prepare.py@@ -0,0 +1,8 @@+"""prepare.sh entrypoint: start the persistent rollout/training worker."""++from __future__ import annotations++from .lifecycle import prepare++if __name__ == "__main__":+    raise SystemExit(prepare())diff --git a/solution/obgrpo/probe.py b/solution/obgrpo/probe.pynew file mode 100644index 0000000000000000000000000000000000000000..0df6c5c35a4fffe4324de30a1139d5f127277206--- /dev/null+++ b/solution/obgrpo/probe.py@@ -0,0 +1,67 @@+"""Fixed-trajectory algorithm probe: published GRPO + clipped-policy mathematics.++Pure Python floats, mirroring the task-owned reference formulas exactly so the+probe validates the mathematics independently of rollout sampling.+"""++from __future__ import annotations++import argparse+import json+import math+import statistics+from pathlib import Path+++def compute(probe: dict) -> dict:+    epsilon = float(probe["group_normalization_epsilon"])+    low = float(probe["clip_ratio_low"])+    high = float(probe["clip_ratio_high"])+    advantages: list[list[float]] = []+    losses: list[float] = []+    kls: list[float] = []+    clipped: list[float] = []+    for group in probe["groups"]:+        rewards = [float(value) for value in group["rewards"]]+        mean = statistics.fmean(rewards)+        std = statistics.stdev(rewards)+        normalised = [0.0] * len(rewards) if std == 0 else [(v - mean) / (std + epsilon) for v in rewards]+        advantages.append(normalised)+        for advantage, old_row, current_row in zip(+            normalised, group["old_logprobs"], group["current_logprobs"], strict=True+        ):+            if len(old_row) != len(current_row) or not old_row:+                raise ValueError("probe log-probability rows are invalid")+            for old, current in zip(old_row, current_row, strict=True):+                log_ratio = float(current) - float(old)+                ratio = math.exp(log_ratio)+                losses.append(-min(ratio * advantage, min(max(ratio, 1.0 - low), 1.0 + high) * advantage))+                kls.append(math.exp(-log_ratio) + log_ratio - 1.0)+                clipped.append(1.0 if ratio < 1.0 - low or ratio > 1.0 + high else 0.0)+    return {+        "schema_version": 1,+        "kind": "openbuild_rl_algorithm_probe_result",+        "probe_id": probe["probe_id"],+        "advantages": advantages,+        "policy_loss": statistics.fmean(losses),+        "approx_kl": statistics.fmean(kls),+        "clip_fraction": statistics.fmean(clipped),+    }+++def main(argv: list[str] | None = None) -> int:+    parser = argparse.ArgumentParser()+    parser.add_argument("--input-manifest", required=True)+    parser.add_argument("--output", required=True)+    args = parser.parse_args(argv)+    probe = json.loads(Path(args.input_manifest).read_text(encoding="utf-8"))+    result = compute(probe)+    Path(args.output).write_text(+        json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8"+    )+    print(json.dumps({k: v for k, v in result.items() if k != "advantages"}, sort_keys=True))+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/solution/obgrpo/worker.py b/solution/obgrpo/worker.pynew file mode 100644index 0000000000000000000000000000000000000000..69e8600cc229629160b8322ebea9096fb347f4a1--- /dev/null+++ b/solution/obgrpo/worker.py@@ -0,0 +1,231 @@+"""Persistent rollout/training worker plus its foreground client.++`prepare.sh` starts one worker process in its own process group and reports that+process group through `ready.json`; the worker owns the loaded model, so model+loading and warmup stay outside the timed execute interval while every process+remains owned by the task lifecycle and is stopped by `cleanup.sh`.++`execute.sh` is a foreground client: it hands the job to the worker, streams the+worker's progress to its own stdout, and exits with the worker's status.  All+device work therefore happens inside the scored execute process window.+"""++from __future__ import annotations++import json+import os+import signal+import socket+import sys+import time+from pathlib import Path++STATE_DIR = Path(os.environ.get("OPENBUILD_STATE_DIR", "/tmp/obgrpo-state"))+SOCKET_NAME = "obgrpo.sock"+WORKER_NAME = "worker.json"+LOG_NAME = "worker.log"+++def socket_path() -> Path:+    return STATE_DIR / SOCKET_NAME+++def worker_info_path() -> Path:+    return STATE_DIR / WORKER_NAME+++def log_path() -> Path:+    return STATE_DIR / LOG_NAME+++def _send(connection: socket.socket, payload: dict) -> None:+    connection.sendall((json.dumps(payload, default=str) + "\n").encode("utf-8"))+++def _recv_line(connection: socket.socket, limit: int = 1 << 22) -> dict:+    chunks = bytearray()+    while b"\n" not in chunks:+        block = connection.recv(65536)+        if not block:+            break+        chunks += block+        if len(chunks) > limit:+            break+    text = bytes(chunks).split(b"\n", 1)[0].decode("utf-8", "replace")+    return json.loads(text) if text.strip() else {}+++def _stop(signum, frame):  # noqa: ARG001+    raise SystemExit(0)+++def serve() -> int:+    STATE_DIR.mkdir(parents=True, exist_ok=True)+    log_file = log_path().open("a", buffering=1, encoding="utf-8")+    os.dup2(log_file.fileno(), sys.stdout.fileno(), inheritable=True)+    os.dup2(log_file.fileno(), sys.stderr.fileno(), inheritable=True)+    sys.stdout = log_file+    sys.stderr = log_file+    signal.signal(signal.SIGTERM, _stop)+    signal.signal(signal.SIGINT, _stop)++    device_ids = [int(v) for v in os.environ.get("OPENBUILD_DEVICE_IDS", "0").split(",") if v != ""]+    device = device_ids[0] if device_ids else 0+    model_path = os.environ.get("OPENBUILD_MODEL_PATH", "")+    print(f"[worker] boot model={model_path} device={device} pid={os.getpid()}", flush=True)+    from .policy import ActorPolicy++    policy = ActorPolicy(model_path, device)+    print(+        f"[worker] loaded params={policy.logical_parameter_count} tensors={policy.parameter_tensor_count}",+        flush=True,+    )+    restart_checkpoint = os.environ.get("OPENBUILD_RESTART_CHECKPOINT", "")+    if restart_checkpoint:+        summary = policy.load_checkpoint(Path(restart_checkpoint))+        print(f"[worker] resumed checkpoint committed_update={summary['committed_update']}", flush=True)+    else:+        warm = policy.warmup()+        print(+            f"[worker] warmup done projection_before={warm['projection_before']!r} "+            f"projection_after={warm['projection_after']!r}",+            flush=True,+    )+    ready_projection = policy.parameter_projection()+    print(f"[worker] ready committed_update={policy.committed_update}", flush=True)++    path = socket_path()+    path.unlink(missing_ok=True)+    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+    server.bind(str(path))+    server.listen(4)+    worker_info_path().write_text(+        json.dumps(+            {+                "pid": os.getpid(),+                "pgid": os.getpgid(0),+                "socket": str(path),+                "log": str(log_path()),+                "device": device,+                "model": model_path,+            }+        )+        + "\n",+        encoding="utf-8",+    )+    while True:+        try:+            connection, _ = server.accept()+        except OSError:+            continue+        with connection:+            try:+                job = _recv_line(connection)+                if job.get("kind") == "ping":+                    _send(connection, {"kind": "pong", "committed_update": policy.committed_update})+                    continue+                _run_job(connection, job, policy, ready_projection)+            except Exception as exc:  # noqa: BLE001+                import traceback+                print(f"[worker] job failed: {exc!r}", flush=True)+                traceback.print_exc()+                try:+                    _send(connection, {"kind": "result", "status": "error", "reason": repr(exc)})+                except OSError:+                    pass+++def _run_job(connection: socket.socket, job: dict, policy, ready_projection: float) -> None:+    from .online import RewardService, run_online++    started = time.time()+    print(f"[worker] job {job.get('action')} input={job.get('input_manifest')}", flush=True)++    def log(message: str) -> None:+        print(f"[worker] {message}", flush=True)+        try:+            _send(connection, {"kind": "log", "message": message})+        except OSError:+            pass++    online_input = json.loads(Path(job["input_manifest"]).read_text(encoding="utf-8"))+    output_dir = Path(job["output_dir"])+    reward = RewardService(job["reward_url"], job["reward_token"])+    result = run_online(policy, online_input, output_dir, job["action"], reward, log=log)+    _send(+        connection,+        {+            "kind": "result",+            "status": "ok",+            "action": job["action"],+            "committed_updates": result["committed_updates"],+            "accepted_trajectories": result["accepted_trajectories"],+            "consumed_response_tokens": result["consumed_response_tokens"],+            "seconds": time.time() - started,+            "ready_projection": ready_projection,+        },+    )+    print(f"[worker] job done in {time.time() - started:.1f}s", flush=True)+++def client(input_manifest: str, output_dir: str) -> int:+    path = socket_path()+    deadline = time.time() + 120.0+    connection = None+    while time.time() < deadline:+        try:+            candidate = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+            candidate.connect(str(path))+            connection = candidate+            break+        except OSError:+            try:+                candidate.close()+            except OSError:+                pass+            time.sleep(0.5)+    if connection is None:+        info = worker_info_path()+        print(f"obgrpo worker socket unavailable at {path}", file=sys.stderr)+        if info.is_file():+            print(info.read_text(), file=sys.stderr)+        if log_path().is_file():+            print("--- worker log tail ---", file=sys.stderr)+            print("".join(log_path().read_text(encoding="utf-8", errors="replace").splitlines(keepends=True)[-40:]), file=sys.stderr)+        return 2+    with connection:+        _send(+            connection,+            {+                "input_manifest": input_manifest,+                "output_dir": output_dir,+                "action": os.environ.get("OPENBUILD_ACTION", "execute"),+                "reward_url": os.environ.get("OPENBUILD_REWARD_URL", ""),+                "reward_token": os.environ.get("OPENBUILD_REWARD_TOKEN", ""),+            },+        )+        connection.settimeout(7200.0)+        while True:+            try:+                payload = _recv_line(connection)+            except (OSError, json.JSONDecodeError):+                print("obgrpo worker connection lost", file=sys.stderr)+                return 3+            if not payload:+                print("obgrpo worker closed the connection", file=sys.stderr)+                return 3+            if payload.get("kind") == "log":+                print(payload.get("message", ""), flush=True)+                continue+            if payload.get("kind") == "result":+                if payload.get("status") != "ok":+                    print(f"worker reported failure: {payload.get('reason')}", file=sys.stderr)+                    return 1+                print(json.dumps(payload, sort_keys=True), flush=True)+                return 0+            print(json.dumps(payload, sort_keys=True), flush=True)+++if __name__ == "__main__":+    mode = sys.argv[1] if len(sys.argv) > 1 else "serve"+    raise SystemExit(serve() if mode == "serve" else client(sys.argv[2], sys.argv[3]))diff --git a/solution/prepare.sh b/solution/prepare.shnew file mode 100755index 0000000000000000000000000000000000000000..546f043461851579e6a3d1c43156e4181e31ce80--- /dev/null+++ b/solution/prepare.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Load the policy, initialise the rollout/training worker and warm the kernels.+# Writes $OPENBUILD_STATE_DIR/ready.json and returns; scored prompts are never+# read here.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"+export OPENBUILD_SOLUTION_DIR="${SOLUTION_DIR}"++exec python3 -m obgrpo.preparediff --git a/solution/probe.sh b/solution/probe.shnew file mode 100755index 0000000000000000000000000000000000000000..5a5a66031a9a8e2abffb48afb4d658d3c5a238ad--- /dev/null+++ b/solution/probe.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+# Fixed-trajectory algorithm probe: published GRPO / clipped-policy mathematics.+set -euo pipefail++SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)}"+export PYTHONPATH="${SOLUTION_DIR}${PYTHONPATH:+:${PYTHONPATH}}"++exec python3 -m obgrpo.probe "$@"