armnet-runtime 0.3.4__tar.gz → 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/.gitignore +2 -0
  2. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/PKG-INFO +2 -2
  3. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/pyproject.toml +2 -2
  4. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/__init__.py +10 -0
  5. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/context.py +118 -13
  6. armnet_runtime-0.3.5/src/armnet_runtime/evals.py +181 -0
  7. armnet_runtime-0.3.5/src/armnet_runtime/group_ranking.py +137 -0
  8. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/_robot_link.py +52 -0
  9. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_armnet_robots.py +33 -0
  10. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_context_arms.py +22 -0
  11. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_context_camera_mounts.py +9 -3
  12. armnet_runtime-0.3.5/tests/test_eval_session.py +87 -0
  13. armnet_runtime-0.3.5/tests/test_group_ranking_api.py +100 -0
  14. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/LICENSE +0 -0
  15. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/README.md +0 -0
  16. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/proto/rerun.proto +0 -0
  17. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/scripts/gen_proto.sh +0 -0
  18. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/_rerun_pb2.py +0 -0
  19. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/cli.py +0 -0
  20. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/decorator.py +0 -0
  21. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/depth_view.py +0 -0
  22. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/env.py +0 -0
  23. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/leaderboard.py +0 -0
  24. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/__init__.py +0 -0
  25. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/_remote_protocol.py +0 -0
  26. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/import_swap.py +0 -0
  27. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_arx5.py +0 -0
  28. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_camera.py +0 -0
  29. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_feetech.py +0 -0
  30. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_yam.py +0 -0
  31. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/so101.py +0 -0
  32. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/yam.py +0 -0
  33. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/markers.py +0 -0
  34. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/rerun.py +0 -0
  35. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/variation.py +0 -0
  36. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/src/armnet_runtime/volume_sync.py +0 -0
  37. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_cell_instrument.py +0 -0
  38. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_completion.py +0 -0
  39. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_confirm_scene_reset.py +0 -0
  40. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_depth_view.py +0 -0
  41. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_edge_goal_clamp.py +0 -0
  42. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_embodiment.py +0 -0
  43. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_leaderboard.py +0 -0
  44. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_persistent_connection.py +0 -0
  45. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_proxy_method_cache.py +0 -0
  46. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_rail_recovery.py +0 -0
  47. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_rail_reset_restore.py +0 -0
  48. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_remote_yam.py +0 -0
  49. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_robot_telemetry.py +0 -0
  50. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_scene_calibration_context.py +0 -0
  51. {armnet_runtime-0.3.4 → armnet_runtime-0.3.5}/tests/test_variation.py +0 -0
@@ -194,6 +194,8 @@ terraform.tfstate.backup
194
194
 
195
195
  # experimental
196
196
  experimental/*/images/*.png
197
+ # A checkout of github.com/villekuosmanen/vla-vlm-benchmarks
198
+ experimental/vla_vlm_benchmarks/
197
199
  *.p12
198
200
  build_log.txt
199
201
  outputs
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: armnet-runtime
3
- Version: 0.3.4
3
+ Version: 0.3.5
4
4
  Summary: armnet runtime SDK — used by code running inside customer containers on a cell.
5
5
  Project-URL: Homepage, https://armnet.dev
6
6
  Project-URL: Documentation, https://docs.armnet.dev/packages/runtime/
@@ -8,7 +8,7 @@ Author: Ville Kuosmanen
8
8
  License-Expression: Apache-2.0
9
9
  License-File: LICENSE
10
10
  Requires-Python: <3.13,>=3.12
11
- Requires-Dist: armnet-core>=0.3.3
11
+ Requires-Dist: armnet-core>=0.3.4
12
12
  Requires-Dist: protobuf<7,>=5
13
13
  Requires-Dist: pydantic<3,>=2.6
14
14
  Provides-Extra: dev
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  name = "armnet-runtime"
7
7
  # 0.2.0 follows armnet-core: ctx.cell now carries an environment and hands
8
8
  # reset/scoring to it, and CompletionStatus moved to armnet-core.
9
- version = "0.3.4"
9
+ version = "0.3.5"
10
10
  description = "armnet runtime SDK \u2014 used by code running inside customer containers on a cell."
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.12,<3.13"
@@ -15,7 +15,7 @@ license-files = ["LICENSE"]
15
15
  authors = [{ name = "Ville Kuosmanen" }]
16
16
 
17
17
  dependencies = [
18
- "armnet-core>=0.3.3",
18
+ "armnet-core>=0.3.4",
19
19
  "pydantic>=2.6,<3",
20
20
  # Wire format for Rerun visualization packets (armnet_runtime.rerun).
21
21
  "protobuf>=5,<7",
@@ -51,6 +51,8 @@ from armnet_runtime.context import (
51
51
  require_so101_embodiment,
52
52
  )
53
53
  from armnet_runtime.decorator import MainRegistrationError, main
54
+ from armnet_runtime.evals import EvalSession, EvalSlot, EvalTrial, ranks_from_outcomes
55
+ from armnet_runtime.group_ranking import GroupRanking, Match, RankingEntry, matches
54
56
  from armnet_runtime.variation import (
55
57
  DEFAULT_VARIATION_SEED,
56
58
  NothingToVary,
@@ -73,7 +75,15 @@ __all__ = [
73
75
  "require_bimanual_yam_embodiment",
74
76
  "require_so101_embodiment",
75
77
  "Embodiment",
78
+ "EvalSession",
79
+ "EvalSlot",
80
+ "EvalTrial",
81
+ "ranks_from_outcomes",
82
+ "GroupRanking",
76
83
  "Job",
84
+ "Match",
85
+ "RankingEntry",
86
+ "matches",
77
87
  "JobResult",
78
88
  "JobSpec",
79
89
  "JobStatus",
@@ -18,9 +18,12 @@ import tempfile
18
18
  import time
19
19
  from dataclasses import dataclass, field
20
20
  from pathlib import Path
21
- from typing import Any, Iterable, Mapping, Optional
21
+ from typing import TYPE_CHECKING, Any, Iterable, Mapping, Optional, Sequence
22
22
  from urllib.parse import urlparse
23
23
 
24
+ if TYPE_CHECKING: # pragma: no cover
25
+ from armnet_runtime.group_ranking import GroupRanking, RankingEntry
26
+
24
27
  from armnet_core import (
25
28
  BIMANUAL_YAM_EMBODIMENT,
26
29
  CellDeviceConfig,
@@ -972,7 +975,7 @@ class Cell:
972
975
 
973
976
  self._await_operator_reset()
974
977
 
975
- def confirm_scene_reset(self) -> None:
978
+ def confirm_scene_reset(self, *, reset_index: Optional[int] = None) -> None:
976
979
  """Ask the operator to stage the scene and confirm, moving nothing.
977
980
 
978
981
  :meth:`reset` always returns the arm to rest before any operator
@@ -982,15 +985,24 @@ class Cell:
982
985
  could sweep the arm through the objects the operator just placed.
983
986
  Call :meth:`reset` with ``confirm=False`` first, command the start
984
987
  pose, then call this.
988
+
989
+ Each staging prompt shows the next layout of the job's task. Pass
990
+ ``reset_index`` to show that layout instead: a job that runs several
991
+ policies on the same scene stages each of them on the same layout.
985
992
  """
986
993
 
987
994
  self._report_progress("Waiting for workspace reset...")
988
- self._await_operator_reset()
995
+ self._await_operator_reset(reset_index=reset_index)
989
996
 
990
- def _await_operator_reset(self) -> None:
997
+ def _await_operator_reset(self, *, reset_index: Optional[int] = None) -> None:
991
998
  # Operator confirmation on the cell-served operator-call endpoint
992
999
  # (fallback to the dev local-control endpoint).
993
- request = {"op": "reset", "request": {"kind": "manual"}}
1000
+ reset: dict[str, Any] = {"kind": "manual"}
1001
+ if reset_index is not None:
1002
+ if int(reset_index) < 0:
1003
+ raise ValueError("reset_index must be non-negative")
1004
+ reset["reset_index"] = int(reset_index)
1005
+ request = {"op": "reset", "request": reset}
994
1006
  operator_endpoint = self.operator_call_endpoint or self.local_control_endpoint
995
1007
  if operator_endpoint:
996
1008
  response = _connector_request(operator_endpoint, request)
@@ -1127,6 +1139,9 @@ class Cell:
1127
1139
  index: Optional[int] = None,
1128
1140
  total: Optional[int] = None,
1129
1141
  outcome_controls: bool = True,
1142
+ trial: Optional[int] = None,
1143
+ trials: Optional[int] = None,
1144
+ label: Optional[str] = None,
1130
1145
  ) -> list[str]:
1131
1146
  """Tell the platform a rollout/episode in this job's loop has started.
1132
1147
 
@@ -1134,6 +1149,11 @@ class Cell:
1134
1149
  ("rollout N / M") for the live job. Pass ``index`` (1-based) and, when
1135
1150
  known, ``total`` so operators see how far along the loop is.
1136
1151
 
1152
+ A loop that runs its rollouts in groups to be ranked against each other
1153
+ (see :meth:`rank_group`) passes ``trial`` (1-based) and ``trials`` for
1154
+ the group, and the rollout's anonymous ``label`` in it ("A", "B", ...);
1155
+ ``index``/``total`` then count the rollouts within the trial.
1156
+
1137
1157
  ``outcome_controls`` controls whether the FMS also shows operator
1138
1158
  success/fail buttons: keep the default ``True`` for policy evals; pass
1139
1159
  ``False`` for progress-only loops such as teleop data collection, where
@@ -1158,9 +1178,83 @@ class Cell:
1158
1178
  payload["index"] = int(index)
1159
1179
  if total is not None:
1160
1180
  payload["total"] = int(total)
1181
+ if trial is not None:
1182
+ payload["trial"] = int(trial)
1183
+ if trials is not None:
1184
+ payload["trials"] = int(trials)
1185
+ if label is not None:
1186
+ payload["label"] = str(label)
1161
1187
  self._rollout_signal("rollout_begin", **payload)
1162
1188
  return problems
1163
1189
 
1190
+ def rank_group(
1191
+ self,
1192
+ entries: Sequence["RankingEntry"],
1193
+ *,
1194
+ title: Optional[str] = None,
1195
+ timeout_s: Optional[float] = None,
1196
+ ) -> "GroupRanking":
1197
+ """Ask the operator to rank a group of rollouts against each other.
1198
+
1199
+ Run several policies once each on the same staged scene, then call this
1200
+ with one :class:`~armnet_runtime.group_ranking.RankingEntry` per rollout
1201
+ (two to four): an anonymous label, the outcome and the rollout's last
1202
+ top-camera frame. The FMS shows them side by side, and the operator
1203
+ ranks them (1 is best, equal ranks tie, no rank for a rollout that made
1204
+ no progress) or drops the group when none made progress. Labels are
1205
+ all the operator sees, so keep which policy is which in the job and
1206
+ shuffle it between groups.
1207
+
1208
+ Blocks until the operator answers or ``timeout_s`` (the cell's default,
1209
+ 15 minutes, when ``None``) runs out, and returns a
1210
+ :class:`~armnet_runtime.group_ranking.GroupRanking`: its ``status`` is
1211
+ ``"ranked"`` (with one rank per entry), ``"dropped"``, ``"timeout"`` or
1212
+ ``"cancelled"``. :func:`~armnet_runtime.group_ranking.matches` turns a
1213
+ ranking into the pairwise comparisons it implies. With no cell attached
1214
+ (a local dev run) the ranks are typed on this terminal.
1215
+ """
1216
+
1217
+ from armnet_runtime.group_ranking import GroupRanking, parse_ranks, request_entries
1218
+
1219
+ if len(entries) < 2:
1220
+ raise ValueError("a group ranking needs at least two rollouts")
1221
+ endpoint = self.operator_call_endpoint or self.local_control_endpoint
1222
+ if not endpoint:
1223
+ labels = ", ".join(f"{e.label} ({e.outcome or 'no outcome'})" for e in entries)
1224
+ while True:
1225
+ text = input(f"{title or 'Rank the rollouts'}: {labels}. Ranks in order "
1226
+ "(1 best, equal ranks tie, - for no progress; empty to drop): ")
1227
+ try:
1228
+ ranks = parse_ranks(text, len(entries))
1229
+ except ValueError as exc:
1230
+ print(exc)
1231
+ continue
1232
+ return GroupRanking("dropped" if ranks is None else "ranked", ranks)
1233
+ request: dict[str, Any] = {"op": "group_ranking", "title": title, "entries": request_entries(entries)}
1234
+ if timeout_s is not None:
1235
+ request["timeout_s"] = float(timeout_s)
1236
+ response = _connector_request(endpoint, request)
1237
+ if not response.get("ok"):
1238
+ raise RuntimeError(response.get("error", "group ranking failed"))
1239
+ ranks = response.get("ranks")
1240
+ return GroupRanking(str(response.get("status")), list(ranks) if ranks is not None else None)
1241
+
1242
+ def supports_group_ranking(self) -> bool:
1243
+ """Whether this cell can put a group of rollouts to the operator (:meth:`rank_group`).
1244
+
1245
+ A cell running armnet code from before group rankings cannot, and
1246
+ :meth:`rank_group` raises there. Check before the first rollout of a job
1247
+ that ranks, rather than finding out after its first group. Asks the
1248
+ operator nothing. ``True`` with no cell attached, where ranks are typed
1249
+ on the terminal.
1250
+ """
1251
+
1252
+ endpoint = self.operator_call_endpoint or self.local_control_endpoint
1253
+ if not endpoint:
1254
+ return True
1255
+ response = _connector_request(endpoint, {"op": "group_ranking", "probe": True})
1256
+ return bool(response.get("ok")) and bool(response.get("supported"))
1257
+
1164
1258
  def _begin_instrumented_episode(self) -> list[str]:
1165
1259
  if self._instrumented is None:
1166
1260
  return []
@@ -1525,6 +1619,9 @@ class Context:
1525
1619
  volume: Volume = field(default_factory=Volume)
1526
1620
  secrets: dict[str, str] = field(default_factory=dict)
1527
1621
  timeout_seconds: Optional[int] = None
1622
+ # The eval job's side of its results (armnet_runtime.evals.EvalSession);
1623
+ # None unless the job was submitted with an eval declaration.
1624
+ eval: Any = None
1528
1625
  # Lazily created background Rerun streamer (see log_rerun_data). Not part of
1529
1626
  # the constructor or the public/comparable surface.
1530
1627
  _rerun_streamer: Any = field(default=None, init=False, repr=False, compare=False)
@@ -1853,7 +1950,7 @@ def build_context() -> Context:
1853
1950
  )
1854
1951
 
1855
1952
  cell_config = _load_cell_config()
1856
- return Context(
1953
+ ctx = Context(
1857
1954
  job_id=job_id,
1858
1955
  embodiment=embodiment_raw,
1859
1956
  task=task_raw,
@@ -1908,6 +2005,10 @@ def build_context() -> Context:
1908
2005
  secrets=_load_secrets(),
1909
2006
  timeout_seconds=timeout,
1910
2007
  )
2008
+ from armnet_runtime.evals import eval_session_from_env
2009
+
2010
+ ctx.eval = eval_session_from_env(os.environ.get(env_keys.EVAL), ctx.cell)
2011
+ return ctx
1911
2012
 
1912
2013
 
1913
2014
  def _load_secrets() -> dict[str, str]:
@@ -2113,13 +2214,14 @@ def _build_camera_config(config: Any) -> Any:
2113
2214
  return config
2114
2215
 
2115
2216
  camera_type = str(config.get("type", "opencv")).lower()
2116
- # Strip keys that are not OpenCVCameraConfig params. Mount blocks are only
2117
- # used by the edge connector; id_path is the USB port used at provisioning
2118
- # time to create the /dev/video_<name> symlink. A Pi CSI camera is still
2119
- # described to LeRobot as an OpenCV camera — the edge swaps in PiCamera
2120
- # from the cell config's type. use_depth and serial_number tell the edge to
2121
- # open a RealSense; the job camera is still an OpenCV config, and depth is
2122
- # read from the remote camera object rather than from these fields.
2217
+ # Strip keys that are not OpenCVCameraConfig params. Mount blocks and Pi
2218
+ # exposure settings are only used by the edge connector; id_path is the USB
2219
+ # port used at provisioning time to create the /dev/video_<name> symlink. A
2220
+ # Pi CSI camera is still described to LeRobot as an OpenCV camera — the
2221
+ # edge swaps in PiCamera from the cell config's type. use_depth and
2222
+ # serial_number tell the edge to open a RealSense; the job camera is still
2223
+ # an OpenCV config, and depth is read from the remote camera object rather
2224
+ # than from these fields.
2123
2225
  _NON_CAMERA_KEYS = {
2124
2226
  "type",
2125
2227
  "arducam_mount",
@@ -2127,6 +2229,9 @@ def _build_camera_config(config: Any) -> Any:
2127
2229
  "id_path",
2128
2230
  "use_depth",
2129
2231
  "serial_number",
2232
+ "auto_exposure",
2233
+ "exposure_time_us",
2234
+ "analogue_gain",
2130
2235
  }
2131
2236
  _OPENCV_SHAPED = {"opencv", "pi", "picam", "picamera", "picamera2", "csi"}
2132
2237
  kwargs = {key: value for key, value in config.items() if key not in _NON_CAMERA_KEYS}
@@ -0,0 +1,181 @@
1
+ """Eval jobs from the job's side: ``ctx.eval``.
2
+
3
+ A job submitted with an eval declaration (``JobSpec.eval``) gets ``ctx.eval``;
4
+ any other job gets ``None``. The cell records each rollout's outcome itself (the
5
+ operator's verdict) along with the staging layout and the operator's rankings.
6
+ The job adds what only it knows: which policy runs under which label, and per
7
+ rollout where it is in the job's dataset, the milestones it reached and notes.
8
+
9
+ A single-policy eval::
10
+
11
+ ev = ctx.eval
12
+ for trial in ev.plan(): # one trial per episode
13
+ slot = trial.slots[0]
14
+ ctx.cell.confirm_scene_reset(reset_index=trial.layout)
15
+ ctx.cell.rollout_begin(index=trial.number, total=len(...), trial=trial.number, label=slot.label)
16
+ try:
17
+ run_policy(slot.policy) # your control loop
18
+ status = ctx.cell.is_complete(block=True)
19
+ finally:
20
+ ctx.cell.rollout_end()
21
+ ev.record_rollout(dataset_episode=..., notes=...)
22
+
23
+ A ranked eval runs every policy once per trial, then ranks the trial with
24
+ ``ev.rank(trial, entries)``: by the outcomes when one of two rollouts succeeded
25
+ and the other did not, otherwise by asking the operator.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import random
31
+ from dataclasses import dataclass
32
+ from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence
33
+
34
+ from armnet_core import EvalDeclaration
35
+
36
+ if TYPE_CHECKING:
37
+ from armnet_runtime.context import Cell
38
+ from armnet_runtime.group_ranking import GroupRanking, RankingEntry
39
+
40
+ LABELS = "ABCD"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class EvalSlot:
45
+ """A rollout's place in a trial: the label the operator sees, and the policy behind it."""
46
+
47
+ label: str
48
+ policy: str
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class EvalTrial:
53
+ number: int # 1-based
54
+ layout: int # the staging layout every rollout of the trial meets
55
+ slots: tuple[EvalSlot, ...] # in the order they run
56
+
57
+
58
+ def ranks_from_outcomes(outcomes: Sequence[Optional[str]]) -> Optional[list[int]]:
59
+ """The ranks a trial's outcomes settle without the operator, or ``None``.
60
+
61
+ A success got further than a rollout that did not succeed, so a trial of one
62
+ success and one other ranks the success first. Between two successes, or two
63
+ that did not succeed, how far each got is for the operator to judge."""
64
+ successes = [outcome == "success" for outcome in outcomes]
65
+ if len(successes) == 2 and sum(successes) == 1:
66
+ return [1 if success else 2 for success in successes]
67
+ return None
68
+
69
+
70
+ class EvalSession:
71
+ """An eval job's side of its results. Reach it as ``ctx.eval``."""
72
+
73
+ def __init__(self, declaration: EvalDeclaration, cell: "Cell") -> None:
74
+ self.declaration = declaration
75
+ self._cell = cell
76
+ self._committed = False
77
+ self.local_records: list[dict[str, Any]] = []
78
+
79
+ @property
80
+ def kind(self) -> str:
81
+ return self.declaration.kind
82
+
83
+ @property
84
+ def policy_names(self) -> list[str]:
85
+ return self.declaration.policy_names()
86
+
87
+ def plan(self, *, rng: Optional[random.Random] = None, first_layout: int = 0) -> list[EvalTrial]:
88
+ """The job's trials, committed to the cell before the first rollout.
89
+
90
+ A single-policy eval has one trial per episode. A ranked eval runs every
91
+ policy once per trial on the same layout, in an order drawn afresh for
92
+ each trial (from ``rng``; by default the system's), labelled A, B, ... in
93
+ the order they run."""
94
+ names = self.policy_names
95
+ if self.kind == "single":
96
+ trials = [EvalTrial(k, first_layout + k - 1, (EvalSlot("A", names[0]),))
97
+ for k in range(1, int(self.declaration.episodes or 0) + 1)]
98
+ else:
99
+ rng = rng or random.SystemRandom()
100
+ trials = []
101
+ for k in range(1, int(self.declaration.trials or 0) + 1):
102
+ order = list(names)
103
+ rng.shuffle(order)
104
+ trials.append(EvalTrial(k, first_layout + k - 1,
105
+ tuple(EvalSlot(label, name) for label, name in zip(LABELS, order))))
106
+ self.commit(trials)
107
+ return trials
108
+
109
+ def commit(self, trials: Sequence[EvalTrial]) -> None:
110
+ """Commit a plan the job drew itself. Only once, before the first rollout."""
111
+ payload = [{"number": t.number, "layout": t.layout,
112
+ "slots": [{"label": s.label, "policy": s.policy} for s in t.slots]} for t in trials]
113
+ self._request({"op": "eval_plan", "trials": payload})
114
+ self._committed = True
115
+
116
+ def record_rollout(
117
+ self,
118
+ *,
119
+ policy: Optional[str] = None,
120
+ outcome: Optional[str] = None,
121
+ score: Optional[float] = None,
122
+ stages: Optional[Mapping[str, Any]] = None,
123
+ notes: Optional[str] = None,
124
+ dataset_episode: Optional[int] = None,
125
+ detail: Optional[Mapping[str, Any]] = None,
126
+ dataset_repo_id: Optional[str] = None,
127
+ seq: Optional[int] = None,
128
+ ) -> Optional[int]:
129
+ """Add what the job knows of a rollout (by default the latest the cell saw begin).
130
+
131
+ ``outcome`` is the job's own view (``success``, ``failure`` or
132
+ ``timeout``), kept apart from the operator's verdict the cell records."""
133
+ rollout = {k: v for k, v in {
134
+ "policy": policy, "claimed_outcome": outcome, "score": score,
135
+ "stages": dict(stages) if stages is not None else None, "notes": notes,
136
+ "dataset_episode": dataset_episode, "detail": dict(detail) if detail is not None else None,
137
+ }.items() if v is not None}
138
+ request: dict[str, Any] = {"op": "eval_record", "rollout": rollout}
139
+ if seq is not None:
140
+ request["seq"] = seq
141
+ if dataset_repo_id:
142
+ request["dataset_repo_id"] = dataset_repo_id
143
+ response = self._request(request)
144
+ return response.get("seq")
145
+
146
+ def record_trial(self, number: int, *, status: str, labels: Sequence[str], decided_by: Optional[str] = None,
147
+ ranks: Optional[Sequence[Optional[int]]] = None) -> None:
148
+ """Record how a trial the operator did not rank ended (by its outcomes, or not at all)."""
149
+ self._request({"op": "eval_trial", "number": number, "status": status, "labels": list(labels),
150
+ "decided_by": decided_by, "ranks": list(ranks) if ranks is not None else None})
151
+
152
+ def rank(self, trial: EvalTrial, entries: Sequence["RankingEntry"], *, title: Optional[str] = None,
153
+ timeout_s: Optional[float] = None) -> "GroupRanking":
154
+ """Rank a trial's rollouts: by the outcomes when they settle it, otherwise by asking the operator."""
155
+ from armnet_runtime.group_ranking import GroupRanking
156
+
157
+ labels = [e.label for e in entries]
158
+ settled = ranks_from_outcomes([e.outcome for e in entries])
159
+ if settled is not None:
160
+ self.record_trial(trial.number, status="ranked", labels=labels, decided_by="outcomes", ranks=settled)
161
+ return GroupRanking("ranked", settled)
162
+ return self._cell.rank_group(entries, title=title or f"Trial {trial.number}", timeout_s=timeout_s)
163
+
164
+ def _request(self, request: dict[str, Any]) -> dict[str, Any]:
165
+ from armnet_runtime.context import _connector_request
166
+
167
+ endpoint = self._cell.operator_call_endpoint or self._cell.local_control_endpoint
168
+ if not endpoint: # a local run with no cell: keep it here
169
+ self.local_records.append(request)
170
+ return {"ok": True}
171
+ response = _connector_request(endpoint, request)
172
+ if not response.get("ok"):
173
+ raise RuntimeError(response.get("error") or f"{request['op']} failed")
174
+ return response
175
+
176
+
177
+ def eval_session_from_env(raw: Optional[str], cell: "Cell") -> Optional[EvalSession]:
178
+ """``ctx.eval`` from the cell's ``ARMNET_EVAL``; ``None`` when the job is not an eval job."""
179
+ if not raw:
180
+ return None
181
+ return EvalSession(EvalDeclaration.model_validate_json(raw), cell)
@@ -0,0 +1,137 @@
1
+ """Group rankings: an operator ranks several rollouts of the same scene against each other.
2
+
3
+ A job that compares policies runs each of them once on the same staged scene (a
4
+ *trial*) and asks the operator to rank the rollouts with
5
+ :meth:`Cell.rank_group <armnet_runtime.context.Cell.rank_group>`. Each rollout
6
+ is shown under an anonymous label, with its outcome and last top-camera frame,
7
+ so the ranking is blind to which policy produced it.
8
+
9
+ A ranking gives every rollout a rank (1 is best; equal ranks tie) or none, for a
10
+ rollout that made no progress at all. Every pair of rollouts in the trial is one
11
+ *match* (:func:`matches`): the better-ranked rollout wins, equal ranks tie, a
12
+ ranked rollout beats one that made no progress, and a pair that both made no
13
+ progress is dropped, as it orders neither. A trial the operator drops (no
14
+ rollout made progress) has no matches. Fitting a rating such as Bradley-Terry
15
+ or Elo to the matches of many trials ranks the policies.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ from dataclasses import dataclass
22
+ from itertools import combinations
23
+ from typing import Any, Optional, Sequence
24
+
25
+ RANKED = "ranked"
26
+ DROPPED = "dropped"
27
+ TIMEOUT = "timeout"
28
+ CANCELLED = "cancelled"
29
+
30
+ OUTCOMES = ("success", "failure", "timeout")
31
+ THUMBNAIL_WIDTH = 320
32
+ THUMBNAIL_JPEG_QUALITY = 80
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class RankingEntry:
37
+ """One rollout of a group: its anonymous label, outcome and last frame.
38
+
39
+ ``image`` is the rollout's last top-camera frame: an ``H x W x 3`` RGB
40
+ ``uint8`` array (resized to a thumbnail before it is sent) or JPEG bytes.
41
+ """
42
+
43
+ label: str
44
+ outcome: Optional[str] = None
45
+ image: Any = None
46
+
47
+ def __post_init__(self) -> None:
48
+ if self.outcome is not None and self.outcome not in OUTCOMES:
49
+ raise ValueError(f"outcome must be one of {OUTCOMES}, got {self.outcome!r}")
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class GroupRanking:
54
+ """How a ranking request ended: ``status`` and, if ranked, one rank per entry."""
55
+
56
+ status: str
57
+ ranks: Optional[list[Optional[int]]] = None
58
+
59
+ @property
60
+ def ranked(self) -> bool:
61
+ return self.status == RANKED
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Match:
66
+ """One pairwise comparison inside a trial: ``outcome`` is 1 if ``a`` won, 0.5 a tie, 0 a loss."""
67
+
68
+ a: int
69
+ b: int
70
+ outcome: float
71
+
72
+
73
+ def matches(ranks: Optional[Sequence[Optional[int]]]) -> list[Match]:
74
+ """The pairwise matches a ranking implies, by entry index.
75
+
76
+ The better (lower) rank wins and equal ranks tie; a ranked rollout beats one
77
+ with no rank (no progress); two rollouts with no rank are dropped. A dropped
78
+ trial (``None``) has none."""
79
+ if ranks is None:
80
+ return []
81
+ out = []
82
+ for i, j in combinations(range(len(ranks)), 2):
83
+ ri, rj = ranks[i], ranks[j]
84
+ if ri is None and rj is None:
85
+ continue
86
+ if rj is None or (ri is not None and ri < rj):
87
+ out.append(Match(i, j, 1.0))
88
+ elif ri is None or rj < ri:
89
+ out.append(Match(i, j, 0.0))
90
+ else:
91
+ out.append(Match(i, j, 0.5))
92
+ return out
93
+
94
+
95
+ def parse_ranks(text: str, size: int) -> Optional[list[Optional[int]]]:
96
+ """Ranks typed on a terminal, one per rollout: ``1 2 2``, ``-`` for no progress.
97
+
98
+ An empty line (or all ``-``) drops the group: ``None``. Raises ``ValueError``
99
+ for anything else."""
100
+ tokens = text.replace(",", " ").split()
101
+ if not tokens or all(t == "-" for t in tokens):
102
+ return None
103
+ if len(tokens) != size:
104
+ raise ValueError(f"give {size} ranks, one per rollout")
105
+ ranks = [None if t == "-" else int(t) for t in tokens]
106
+ if any(r is not None and not 1 <= r <= size for r in ranks):
107
+ raise ValueError(f"ranks run from 1 to {size}")
108
+ return ranks
109
+
110
+
111
+ def thumbnail_jpeg(image: Any, *, width: int = THUMBNAIL_WIDTH) -> str:
112
+ """Base64 JPEG of ``image`` (an RGB array, resized to ``width``, or JPEG bytes)."""
113
+ if isinstance(image, (bytes, bytearray)):
114
+ return base64.b64encode(bytes(image)).decode("ascii")
115
+ try:
116
+ import cv2
117
+ import numpy as np
118
+ except ImportError as exc:
119
+ raise RuntimeError("encoding a frame needs opencv-python; pass JPEG bytes instead") from exc
120
+
121
+ frame = np.ascontiguousarray(image, dtype=np.uint8)
122
+ if frame.ndim != 3 or frame.shape[2] != 3:
123
+ raise ValueError(f"expected an H x W x 3 RGB frame, got {frame.shape}")
124
+ if frame.shape[1] > width:
125
+ height = max(1, round(frame.shape[0] * width / frame.shape[1]))
126
+ frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
127
+ ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR),
128
+ [cv2.IMWRITE_JPEG_QUALITY, THUMBNAIL_JPEG_QUALITY])
129
+ if not ok:
130
+ raise RuntimeError("could not encode the thumbnail")
131
+ return base64.b64encode(encoded.tobytes()).decode("ascii")
132
+
133
+
134
+ def request_entries(entries: Sequence[RankingEntry]) -> list[dict[str, Any]]:
135
+ """The entries as the operator-call request carries them."""
136
+ return [{"label": e.label, "outcome": e.outcome,
137
+ "image_jpeg": thumbnail_jpeg(e.image) if e.image is not None else None} for e in entries]
@@ -124,6 +124,43 @@ class EdgeRobotLink:
124
124
  )
125
125
  return [dict(decode(sent)) for sent in reply["arms"]]
126
126
 
127
+ def keep_out_status(self) -> dict[str, Any]:
128
+ """Job-scoped keep-out violations the edge has recorded so far.
129
+
130
+ A cell with no keep-out configured, or an edge build too old to know
131
+ this op, reports no violations rather than erroring: this is a
132
+ best-effort signal for an environment's own episode scoring (see
133
+ ``armnet_busybox``), not a safety mechanism in its own right -- the
134
+ edge enforces keep-out regardless of whether anyone reads this.
135
+ """
136
+
137
+ try:
138
+ reply = self._conn.request({"op": "keep_out_status"})
139
+ except Exception: # noqa: BLE001 - advisory only; never break the rollout
140
+ logger.warning("keep_out_status request failed", exc_info=True)
141
+ return {"violation_count": 0, "last_violation": None}
142
+ if not reply.get("ok"):
143
+ # Covers both an edge too old to know this op (see
144
+ # ``_is_unsupported_op``) and any other failure: fail open, since
145
+ # this is advisory, not the enforcement path.
146
+ return {"violation_count": 0, "last_violation": None}
147
+ return {
148
+ "violation_count": int(reply.get("violation_count", 0)),
149
+ "last_violation": reply.get("last_violation"),
150
+ }
151
+
152
+ def clear_keep_out_violations(self) -> None:
153
+ """Forget recorded keep-out breaches so the next episode starts clean.
154
+
155
+ Best-effort. An edge that does not know this op leaves the counter as
156
+ it was; the episode then keeps whatever the edge still reports.
157
+ """
158
+
159
+ try:
160
+ self._conn.request({"op": "clear_keep_out_violations"})
161
+ except Exception: # noqa: BLE001 - advisory only; never break the rollout
162
+ logger.warning("clear_keep_out_violations request failed", exc_info=True)
163
+
127
164
  def close(self) -> None:
128
165
  self._conn.close()
129
166
  if self._decoder is not None:
@@ -199,6 +236,21 @@ class EdgeObservedRobot:
199
236
  self._last_depth = seen.depth
200
237
  self._last_frame_ages_ms = seen.ages_ms
201
238
 
239
+ def keep_out_status(self) -> dict[str, Any]:
240
+ """Job-scoped keep-out violations the edge has recorded so far.
241
+
242
+ See :meth:`EdgeRobotLink.keep_out_status`. Not wrapped in ``_edge()``:
243
+ that method already fails open and never raises
244
+ ``EdgeDeviceUnavailable``, so there is nothing here to translate.
245
+ """
246
+
247
+ return self._link.keep_out_status()
248
+
249
+ def clear_keep_out_violations(self) -> None:
250
+ """See :meth:`EdgeRobotLink.clear_keep_out_violations`."""
251
+
252
+ self._link.clear_keep_out_violations()
253
+
202
254
  def _edge(self, call: Callable[[], _T]) -> _T:
203
255
  try:
204
256
  return call()
@@ -303,6 +303,39 @@ def test_so101_goal_comes_back_bounded_by_the_edge(so101_edge):
303
303
  assert all(isinstance(value, float) for value in sent.values())
304
304
 
305
305
 
306
+ def test_so101_keep_out_status_round_trips_through_a_real_edge(so101_edge):
307
+ robot = _so101(so101_edge)
308
+ robot.connect(calibrate=False)
309
+ try:
310
+ status = robot.keep_out_status()
311
+ finally:
312
+ robot.disconnect()
313
+
314
+ # No keep-out is armed on this edge, so there is nothing to report.
315
+ assert status == {"violation_count": 0, "last_violation": None}
316
+
317
+
318
+ def test_so101_keep_out_status_fails_open_against_an_old_edge(so101_edge, monkeypatch):
319
+ robot = _so101(so101_edge)
320
+ robot.connect(calibrate=False)
321
+ try:
322
+ connector = so101_edge.connector
323
+ real_dispatch = connector._dispatch
324
+
325
+ def old_edge(request): # noqa: ANN001
326
+ if request.get("op") == "keep_out_status":
327
+ return {"ok": False, "error": "unknown op 'keep_out_status'"}
328
+ return real_dispatch(request)
329
+
330
+ monkeypatch.setattr(connector, "_dispatch", old_edge)
331
+
332
+ status = robot.keep_out_status()
333
+ finally:
334
+ robot.disconnect()
335
+
336
+ assert status == {"violation_count": 0, "last_violation": None}
337
+
338
+
306
339
  def test_so101_depth_arrives_with_the_color_frame_it_was_captured_with(so101_edge):
307
340
  robot = _so101(
308
341
  so101_edge, cameras={"top": _camera("/dev/video_top")}, depth_cameras=["top"]
@@ -237,3 +237,25 @@ def test_opencv_camera_config_ignores_edge_depth_fields():
237
237
  assert config.width == 1280
238
238
  assert not hasattr(config, "use_depth")
239
239
  assert not hasattr(config, "serial_number")
240
+
241
+
242
+ def test_opencv_camera_config_ignores_edge_pi_exposure_fields():
243
+ config = _build_camera_config(
244
+ {
245
+ "type": "pi",
246
+ "index_or_path": "/dev/video_front",
247
+ "fps": 20,
248
+ "width": 1280,
249
+ "height": 720,
250
+ "auto_exposure": False,
251
+ "exposure_time_us": 20000,
252
+ "analogue_gain": 2.0,
253
+ }
254
+ )
255
+
256
+ assert config.index_or_path == "/dev/video_front"
257
+ assert config.width == 1280
258
+ assert config.fps == 20
259
+ assert not hasattr(config, "auto_exposure")
260
+ assert not hasattr(config, "exposure_time_us")
261
+ assert not hasattr(config, "analogue_gain")
@@ -26,20 +26,26 @@ def test_a_serial_mount_arrives_with_its_bus_and_measured_aim():
26
26
 
27
27
  front = mounts["front"]
28
28
  assert (front.default_pan, front.default_tilt) == (679.0, 3033.0)
29
- assert front.mount_config["port"] == "/dev/ttyAMA0"
29
+ assert (
30
+ front.mount_config["port"]
31
+ == "/dev/serial/by-id/usb-1a86_USB_Single_Serial_5B3D041203-if00"
32
+ )
30
33
  assert front.mount_config["pan_range"] == [37, 2185]
31
34
  # The wrist camera rides on the arm, so it has no mount to aim.
32
35
  assert "wrist" not in mounts
33
36
 
34
37
 
35
38
  def test_two_serial_mounts_on_one_cell_keep_their_own_bus_and_aim():
36
- """cell-03's front and top brackets sit on separate UARTs."""
39
+ """cell-03's front and top mounts use separate USB serial adapters."""
37
40
  mounts = _build_runtime_camera_mounts(RobotCellConfig.from_file(CELL_3))
38
41
 
39
42
  assert set(mounts) == {"front", "top"}
40
43
  top = mounts["top"]
41
44
  assert (top.default_pan, top.default_tilt) == (1770.0, 1433.0)
42
- assert top.mount_config["port"] == "/dev/ttyAMA3"
45
+ assert (
46
+ top.mount_config["port"]
47
+ == "/dev/serial/by-id/usb-1a86_USB_Single_Serial_5A7C118374-if00"
48
+ )
43
49
  assert top.mount_config["port"] != mounts["front"].mount_config["port"]
44
50
 
45
51
 
@@ -0,0 +1,87 @@
1
+ """ctx.eval: an eval job's plan, its records and its rankings, sent to the cell."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import random
7
+
8
+ import pytest
9
+ from armnet_core import EvalDeclaration
10
+ from armnet_core import env as env_keys
11
+
12
+ from armnet_runtime import RankingEntry, ranks_from_outcomes
13
+ from armnet_runtime import context as context_module
14
+ from armnet_runtime.context import Cell
15
+ from armnet_runtime.evals import EvalSession
16
+
17
+ RANKED = EvalDeclaration(kind="ranked", policies=[{"name": "base"}, {"name": "rtc"}, {"name": "big"}], trials=6)
18
+ SINGLE = EvalDeclaration(kind="single", policies=[{"name": "pi0", "kind": "lerobot", "ref": "org/pi0"}], episodes=3)
19
+
20
+
21
+ def _session(declaration, monkeypatch, replies=None):
22
+ sent = []
23
+
24
+ def request(endpoint, payload, **_kw):
25
+ sent.append(payload)
26
+ return (replies or {}).get(payload["op"], {"ok": True, "seq": len(sent)})
27
+
28
+ monkeypatch.setattr(context_module, "_connector_request", request)
29
+ return EvalSession(declaration, Cell(operator_call_endpoint="tcp://cell:9999")), sent
30
+
31
+
32
+ def test_a_ranked_plan_shuffles_every_trial_on_one_layout_and_is_committed(monkeypatch):
33
+ session, sent = _session(RANKED, monkeypatch)
34
+ plan = session.plan(rng=random.Random(3), first_layout=10)
35
+ assert [t.layout for t in plan] == list(range(10, 16))
36
+ assert all([s.label for s in t.slots] == ["A", "B", "C"] for t in plan)
37
+ assert all(sorted(s.policy for s in t.slots) == ["base", "big", "rtc"] for t in plan)
38
+ assert len({tuple(s.policy for s in t.slots) for t in plan}) > 1
39
+ (commit,) = sent
40
+ assert commit["op"] == "eval_plan" and commit["trials"][0]["slots"][0]["policy"] == plan[0].slots[0].policy
41
+
42
+
43
+ def test_a_single_policy_plan_is_one_trial_per_episode(monkeypatch):
44
+ session, _ = _session(SINGLE, monkeypatch)
45
+ plan = session.plan()
46
+ assert [(t.number, t.layout, t.slots[0].policy) for t in plan] == [(1, 0, "pi0"), (2, 1, "pi0"), (3, 2, "pi0")]
47
+
48
+
49
+ def test_records_go_to_the_cell_without_empty_fields(monkeypatch):
50
+ session, sent = _session(SINGLE, monkeypatch)
51
+ assert session.record_rollout(outcome="timeout", dataset_episode=4, stages={"grasped": True},
52
+ dataset_repo_id="me/eval_x") == 1
53
+ assert sent[0] == {"op": "eval_record", "dataset_repo_id": "me/eval_x",
54
+ "rollout": {"claimed_outcome": "timeout", "stages": {"grasped": True}, "dataset_episode": 4}}
55
+
56
+
57
+ def test_a_success_against_a_failure_is_ranked_by_outcomes_and_anything_else_asks_the_operator(monkeypatch):
58
+ session, sent = _session(RANKED, monkeypatch, {"group_ranking": {"ok": True, "status": "ranked", "ranks": [1, 1]}})
59
+ trial = session.plan(rng=random.Random(0))[0]
60
+ ranking = session.rank(trial, [RankingEntry("A", "timeout"), RankingEntry("B", "success")])
61
+ assert (ranking.status, ranking.ranks) == ("ranked", [2, 1])
62
+ assert sent[-1] == {"op": "eval_trial", "number": 1, "status": "ranked", "labels": ["A", "B"],
63
+ "decided_by": "outcomes", "ranks": [2, 1]}
64
+ ranking = session.rank(trial, [RankingEntry("A", "success"), RankingEntry("B", "success")])
65
+ assert ranking.ranks == [1, 1] and sent[-1]["op"] == "group_ranking"
66
+ assert ranks_from_outcomes(["success", "failure", "failure"]) is None
67
+
68
+
69
+ def test_the_cell_refusing_a_record_raises(monkeypatch):
70
+ session, _ = _session(SINGLE, monkeypatch, {"eval_record": {"ok": False, "error": "no rollout has begun"}})
71
+ with pytest.raises(RuntimeError, match="no rollout has begun"):
72
+ session.record_rollout(notes="x")
73
+
74
+
75
+ def test_ctx_eval_comes_from_the_cells_env_and_is_none_for_other_jobs(monkeypatch):
76
+ monkeypatch.setenv(env_keys.JOB_ID, "job-1")
77
+ monkeypatch.setenv(env_keys.EMBODIMENT, "so101")
78
+ monkeypatch.setenv(env_keys.TASK, "pick_place")
79
+ monkeypatch.delenv(env_keys.CELL_CONFIG, raising=False)
80
+ monkeypatch.delenv(env_keys.EVAL, raising=False)
81
+ assert context_module.build_context().eval is None
82
+ monkeypatch.setenv(env_keys.EVAL, SINGLE.model_dump_json())
83
+ ctx = context_module.build_context()
84
+ assert ctx.eval.policy_names == ["pi0"] and ctx.eval.kind == "single"
85
+ local = ctx.eval.record_rollout(notes="no cell here") # a local run keeps its records
86
+ assert local is None and ctx.eval.local_records == [{"op": "eval_record", "rollout": {"notes": "no cell here"}}]
87
+ json.dumps(ctx.eval.local_records)
@@ -0,0 +1,100 @@
1
+ """Group rankings: the operator ranks a trial's rollouts, and the ranking implies pairwise matches."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from armnet_runtime import GroupRanking, Match, RankingEntry, matches
11
+ from armnet_runtime import context as context_module
12
+ from armnet_runtime.context import Cell
13
+ from armnet_runtime.group_ranking import parse_ranks, thumbnail_jpeg
14
+
15
+
16
+ def _cell() -> Cell:
17
+ return Cell(robot_port="tcp://cell-01:9876", operator_call_endpoint="tcp://cell-01:9999")
18
+
19
+
20
+ def test_one_partial_success_beats_two_rollouts_without_progress_whose_match_is_dropped():
21
+ assert matches([1, None, None]) == [Match(0, 1, 1.0), Match(0, 2, 1.0)]
22
+
23
+
24
+ def test_equal_partial_progress_ties():
25
+ assert matches([1, 2, 2]) == [Match(0, 1, 1.0), Match(0, 2, 1.0), Match(1, 2, 0.5)]
26
+ assert matches([1, 1, 1]) == [Match(0, 1, 0.5), Match(0, 2, 0.5), Match(1, 2, 0.5)]
27
+
28
+
29
+ def test_a_dropped_trial_and_a_pair_without_progress_have_no_matches():
30
+ assert matches(None) == []
31
+ assert matches([None, None]) == []
32
+ assert matches([2, 1]) == [Match(0, 1, 0.0)]
33
+ assert matches([None, 1]) == [Match(0, 1, 0.0)]
34
+
35
+
36
+ @pytest.mark.parametrize("text,ranks", [("1 2 2", [1, 2, 2]), ("1,-,-", [1, None, None]), ("", None), ("- - -", None)])
37
+ def test_typed_ranks(text, ranks):
38
+ assert parse_ranks(text, 3) == ranks
39
+
40
+
41
+ @pytest.mark.parametrize("text", ["1 2", "1 2 4", "a b c"])
42
+ def test_bad_typed_ranks(text):
43
+ with pytest.raises(ValueError):
44
+ parse_ranks(text, 3)
45
+
46
+
47
+ def test_frames_become_small_jpeg_thumbnails():
48
+ frame = np.zeros((480, 640, 3), dtype=np.uint8)
49
+ jpeg = base64.b64decode(thumbnail_jpeg(frame))
50
+ assert jpeg[:2] == b"\xff\xd8" and len(jpeg) < 50_000
51
+ assert base64.b64decode(thumbnail_jpeg(b"\xff\xd8already")) == b"\xff\xd8already"
52
+ with pytest.raises(ValueError):
53
+ RankingEntry(label="A", outcome="partial")
54
+
55
+
56
+ def test_rank_group_asks_the_cell_and_returns_the_operators_ranking(monkeypatch):
57
+ requests: list[dict] = []
58
+
59
+ def connector_request(endpoint: str, request: dict, **_kwargs) -> dict:
60
+ requests.append(dict(request))
61
+ return {"ok": True, "status": "ranked", "ranks": [1, None]}
62
+
63
+ monkeypatch.setattr(context_module, "_connector_request", connector_request)
64
+ frame = np.full((240, 320, 3), 127, dtype=np.uint8)
65
+ ranking = _cell().rank_group(
66
+ [RankingEntry("A", "success", frame), RankingEntry("B", "timeout")], title="Trial 3 of 10")
67
+ assert ranking == GroupRanking("ranked", [1, None]) and ranking.ranked
68
+ (request,) = requests
69
+ assert request["op"] == "group_ranking" and request["title"] == "Trial 3 of 10"
70
+ assert [(e["label"], e["outcome"]) for e in request["entries"]] == [("A", "success"), ("B", "timeout")]
71
+ assert request["entries"][0]["image_jpeg"] and request["entries"][1]["image_jpeg"] is None
72
+ with pytest.raises(ValueError):
73
+ _cell().rank_group([RankingEntry("A")])
74
+
75
+
76
+ @pytest.mark.parametrize("response,supported", [
77
+ ({"ok": True, "supported": True}, True),
78
+ ({"ok": False, "error": "unknown operator-call op: 'group_ranking'"}, False), # a cell from before rankings
79
+ ])
80
+ def test_a_job_can_ask_the_cell_whether_it_ranks_before_running_anything(monkeypatch, response, supported):
81
+ requests: list[dict] = []
82
+ monkeypatch.setattr(context_module, "_connector_request",
83
+ lambda endpoint, request, **_kw: requests.append(dict(request)) or response)
84
+ assert _cell().supports_group_ranking() is supported
85
+ assert requests == [{"op": "group_ranking", "probe": True}]
86
+ assert Cell(robot_port="tcp://cell-01:9876").supports_group_ranking() # local run: typed on the terminal
87
+
88
+
89
+ def test_rollout_begin_carries_the_trial_and_staging_can_pin_the_layout(monkeypatch):
90
+ requests: list[dict] = []
91
+ monkeypatch.setattr(context_module, "_connector_request",
92
+ lambda _endpoint, request, **_kwargs: requests.append(dict(request)) or {"ok": True})
93
+ cell = _cell()
94
+ cell.rollout_begin(index=2, total=3, trial=4, trials=10, label="B")
95
+ cell.confirm_scene_reset(reset_index=7)
96
+ assert requests[0] == {"op": "rollout_begin", "outcome_controls": True, "index": 2, "total": 3, "trial": 4,
97
+ "trials": 10, "label": "B"}
98
+ assert requests[1] == {"op": "reset", "request": {"kind": "manual", "reset_index": 7}}
99
+ with pytest.raises(ValueError):
100
+ cell.confirm_scene_reset(reset_index=-1)
File without changes
File without changes