armnet-runtime 0.3.3__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 (52) hide show
  1. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/.gitignore +2 -0
  2. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/PKG-INFO +2 -2
  3. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/pyproject.toml +2 -2
  4. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/__init__.py +10 -0
  5. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/context.py +207 -24
  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.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/_robot_link.py +52 -0
  9. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_armnet_robots.py +33 -0
  10. armnet_runtime-0.3.5/tests/test_completion.py +134 -0
  11. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_context_arms.py +22 -0
  12. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_context_camera_mounts.py +9 -3
  13. armnet_runtime-0.3.5/tests/test_eval_session.py +87 -0
  14. armnet_runtime-0.3.5/tests/test_group_ranking_api.py +100 -0
  15. armnet_runtime-0.3.3/tests/test_completion.py +0 -37
  16. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/LICENSE +0 -0
  17. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/README.md +0 -0
  18. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/proto/rerun.proto +0 -0
  19. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/scripts/gen_proto.sh +0 -0
  20. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/_rerun_pb2.py +0 -0
  21. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/cli.py +0 -0
  22. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/decorator.py +0 -0
  23. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/depth_view.py +0 -0
  24. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/env.py +0 -0
  25. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/leaderboard.py +0 -0
  26. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/__init__.py +0 -0
  27. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/_remote_protocol.py +0 -0
  28. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/import_swap.py +0 -0
  29. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_arx5.py +0 -0
  30. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_camera.py +0 -0
  31. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_feetech.py +0 -0
  32. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/remote_yam.py +0 -0
  33. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/so101.py +0 -0
  34. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/lerobot/yam.py +0 -0
  35. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/markers.py +0 -0
  36. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/rerun.py +0 -0
  37. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/variation.py +0 -0
  38. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/src/armnet_runtime/volume_sync.py +0 -0
  39. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_cell_instrument.py +0 -0
  40. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_confirm_scene_reset.py +0 -0
  41. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_depth_view.py +0 -0
  42. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_edge_goal_clamp.py +0 -0
  43. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_embodiment.py +0 -0
  44. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_leaderboard.py +0 -0
  45. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_persistent_connection.py +0 -0
  46. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_proxy_method_cache.py +0 -0
  47. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_rail_recovery.py +0 -0
  48. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_rail_reset_restore.py +0 -0
  49. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_remote_yam.py +0 -0
  50. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_robot_telemetry.py +0 -0
  51. {armnet_runtime-0.3.3 → armnet_runtime-0.3.5}/tests/test_scene_calibration_context.py +0 -0
  52. {armnet_runtime-0.3.3 → 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.3
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.2
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.3"
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.2",
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,
@@ -122,6 +125,15 @@ _ROBOT_TELEMETRY_READ_TIMEOUT_S = 1.0
122
125
  # Throttle interval for teleop-channel error logs (they'd otherwise repeat at
123
126
  # the control-loop rate while the channel is down).
124
127
  _TELEOP_ERROR_LOG_INTERVAL_S = 5.0
128
+ # The monitor's verdict is in memory on the connector, so a per-tick poll that
129
+ # takes longer than this is treated as "not decided yet" rather than stalling
130
+ # the control loop.
131
+ _COMPLETION_READ_TIMEOUT_S = 1.0
132
+ # The final, blocking completion check is the episode's score, so a transient
133
+ # network failure (a slow name lookup, a dropped connection) is retried rather
134
+ # than failing the episode.
135
+ _FINAL_COMPLETION_ATTEMPTS = 3
136
+ _FINAL_COMPLETION_RETRY_DELAY_S = 1.0
125
137
 
126
138
 
127
139
  @dataclass
@@ -218,6 +230,14 @@ class RuntimeRail(_CellDevice):
218
230
  # job may be running somewhere else entirely (job_position), so keep both:
219
231
  # this one is what a varied position is measured against.
220
232
  default_position: float = 0.5
233
+ # The last 0-1 position commanded to this carriage through
234
+ # ``_set_rail_targets`` — job start, between-episode reset, or per-episode
235
+ # variation. Every positioning path funnels through that one call, and reset
236
+ # runs before variation, so this is the per-episode "commanded truth"
237
+ # recorded beside the episode. Initialised to ``job_position`` in
238
+ # ``_build_runtime_rails`` so a rail positioned only at job start (no runtime
239
+ # move yet) still reports correctly; updated on every move.
240
+ last_commanded_position: float = 0.5
221
241
 
222
242
  def set(self, position: float) -> None:
223
243
  """Move this rail alone to ``position`` (0..1) and wait until settled.
@@ -383,6 +403,10 @@ class Cell:
383
403
  # the cell program's operator-call endpoint (see is_complete).
384
404
  _completion_conn: Any = field(default=None, init=False, repr=False, compare=False)
385
405
  _completion_last_error_log: float = field(default=0.0, init=False, repr=False, compare=False)
406
+ # Reused connection for polling the automated completion monitor on the
407
+ # robot connector (see is_complete).
408
+ _monitor_conn: Any = field(default=None, init=False, repr=False, compare=False)
409
+ _monitor_last_error_log: float = field(default=0.0, init=False, repr=False, compare=False)
386
410
  # Most-recent completion outcome seen during the current rollout, plus an
387
411
  # optional sink (installed by Context.init_leaderboard) that records each
388
412
  # rollout's cell-scored outcome. Kept here so rollout_end can record the
@@ -798,6 +822,10 @@ class Cell:
798
822
  raise RuntimeError("robot connector is unavailable; cannot position rail")
799
823
  for rail, raw_target in targets:
800
824
  target = max(0.0, min(1.0, float(raw_target)))
825
+ # Record the commanded position before the move so the episode saved
826
+ # after this carries the fraction the carriage was driven to, even if
827
+ # the move itself raises partway through.
828
+ rail.last_commanded_position = target
801
829
  request: dict[str, Any] = {
802
830
  "op": "rail_set",
803
831
  "pos": target,
@@ -947,7 +975,7 @@ class Cell:
947
975
 
948
976
  self._await_operator_reset()
949
977
 
950
- def confirm_scene_reset(self) -> None:
978
+ def confirm_scene_reset(self, *, reset_index: Optional[int] = None) -> None:
951
979
  """Ask the operator to stage the scene and confirm, moving nothing.
952
980
 
953
981
  :meth:`reset` always returns the arm to rest before any operator
@@ -957,15 +985,24 @@ class Cell:
957
985
  could sweep the arm through the objects the operator just placed.
958
986
  Call :meth:`reset` with ``confirm=False`` first, command the start
959
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.
960
992
  """
961
993
 
962
994
  self._report_progress("Waiting for workspace reset...")
963
- self._await_operator_reset()
995
+ self._await_operator_reset(reset_index=reset_index)
964
996
 
965
- def _await_operator_reset(self) -> None:
997
+ def _await_operator_reset(self, *, reset_index: Optional[int] = None) -> None:
966
998
  # Operator confirmation on the cell-served operator-call endpoint
967
999
  # (fallback to the dev local-control endpoint).
968
- 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}
969
1006
  operator_endpoint = self.operator_call_endpoint or self.local_control_endpoint
970
1007
  if operator_endpoint:
971
1008
  response = _connector_request(operator_endpoint, request)
@@ -1021,12 +1058,45 @@ class Cell:
1021
1058
  raise RuntimeError(response.get("error", "local completion check failed"))
1022
1059
  return _completion_from_response(response)
1023
1060
  if self.robot_port and _looks_like_connector_endpoint(self.robot_port):
1024
- response = _connector_request(self.robot_port, request)
1061
+ if block:
1062
+ response = _final_completion_request(self.robot_port, request)
1063
+ else:
1064
+ response = self._poll_completion_monitor(request)
1065
+ if response is None:
1066
+ return CompletionStatus(complete=False, success=False)
1025
1067
  if not response.get("ok"):
1026
1068
  raise RuntimeError(response.get("error", "cell completion check failed"))
1027
1069
  return _completion_from_response(response)
1028
1070
  return CompletionStatus(complete=False, success=False)
1029
1071
 
1072
+ def _poll_completion_monitor(self, request: dict[str, Any]) -> Optional[dict[str, Any]]:
1073
+ """The monitor's current verdict, or None when it could not be read.
1074
+
1075
+ Polled every control tick, so it holds one connection open: opening one
1076
+ per tick looks the connector's host name up again each time, and a
1077
+ single failed lookup would end the episode. An unread verdict counts as
1078
+ "not decided yet", and the final blocking check asks again.
1079
+ """
1080
+
1081
+ endpoint = self.robot_port
1082
+ if self._monitor_conn is None or self._monitor_conn.endpoint != endpoint:
1083
+ if self._monitor_conn is not None:
1084
+ self._monitor_conn.close()
1085
+ self._monitor_conn = _TeleopConnection(endpoint, timeout=_COMPLETION_READ_TIMEOUT_S)
1086
+
1087
+ try:
1088
+ return self._monitor_conn.request(request)
1089
+ except Exception as exc: # noqa: BLE001
1090
+ now = time.monotonic()
1091
+ if now - self._monitor_last_error_log >= _TELEOP_ERROR_LOG_INTERVAL_S:
1092
+ self._monitor_last_error_log = now
1093
+ logger.warning(
1094
+ "completion check on %s failed (treating as not complete): %r",
1095
+ endpoint,
1096
+ exc,
1097
+ )
1098
+ return None
1099
+
1030
1100
  def _human_completion(self) -> Optional[bool]:
1031
1101
  """Return the operator's reported success/fail, or None if none pending.
1032
1102
 
@@ -1069,6 +1139,9 @@ class Cell:
1069
1139
  index: Optional[int] = None,
1070
1140
  total: Optional[int] = None,
1071
1141
  outcome_controls: bool = True,
1142
+ trial: Optional[int] = None,
1143
+ trials: Optional[int] = None,
1144
+ label: Optional[str] = None,
1072
1145
  ) -> list[str]:
1073
1146
  """Tell the platform a rollout/episode in this job's loop has started.
1074
1147
 
@@ -1076,6 +1149,11 @@ class Cell:
1076
1149
  ("rollout N / M") for the live job. Pass ``index`` (1-based) and, when
1077
1150
  known, ``total`` so operators see how far along the loop is.
1078
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
+
1079
1157
  ``outcome_controls`` controls whether the FMS also shows operator
1080
1158
  success/fail buttons: keep the default ``True`` for policy evals; pass
1081
1159
  ``False`` for progress-only loops such as teleop data collection, where
@@ -1100,9 +1178,83 @@ class Cell:
1100
1178
  payload["index"] = int(index)
1101
1179
  if total is not None:
1102
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)
1103
1187
  self._rollout_signal("rollout_begin", **payload)
1104
1188
  return problems
1105
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
+
1106
1258
  def _begin_instrumented_episode(self) -> list[str]:
1107
1259
  if self._instrumented is None:
1108
1260
  return []
@@ -1355,6 +1507,22 @@ def _connector_request(
1355
1507
  return json.loads(data.decode("utf-8"))
1356
1508
 
1357
1509
 
1510
+ def _final_completion_request(endpoint: str, request: dict[str, Any]) -> dict[str, Any]:
1511
+ for attempt in range(1, _FINAL_COMPLETION_ATTEMPTS):
1512
+ try:
1513
+ return _connector_request(endpoint, request)
1514
+ except OSError as exc:
1515
+ logger.warning(
1516
+ "final completion check on %s failed (attempt %d of %d), retrying: %r",
1517
+ endpoint,
1518
+ attempt,
1519
+ _FINAL_COMPLETION_ATTEMPTS,
1520
+ exc,
1521
+ )
1522
+ time.sleep(_FINAL_COMPLETION_RETRY_DELAY_S)
1523
+ return _connector_request(endpoint, request)
1524
+
1525
+
1358
1526
  def _connect_connector(endpoint: str) -> socket.socket:
1359
1527
  if endpoint.startswith("tcp://"):
1360
1528
  parsed = urlparse(endpoint)
@@ -1451,6 +1619,9 @@ class Context:
1451
1619
  volume: Volume = field(default_factory=Volume)
1452
1620
  secrets: dict[str, str] = field(default_factory=dict)
1453
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
1454
1625
  # Lazily created background Rerun streamer (see log_rerun_data). Not part of
1455
1626
  # the constructor or the public/comparable surface.
1456
1627
  _rerun_streamer: Any = field(default=None, init=False, repr=False, compare=False)
@@ -1779,7 +1950,7 @@ def build_context() -> Context:
1779
1950
  )
1780
1951
 
1781
1952
  cell_config = _load_cell_config()
1782
- return Context(
1953
+ ctx = Context(
1783
1954
  job_id=job_id,
1784
1955
  embodiment=embodiment_raw,
1785
1956
  task=task_raw,
@@ -1834,6 +2005,10 @@ def build_context() -> Context:
1834
2005
  secrets=_load_secrets(),
1835
2006
  timeout_seconds=timeout,
1836
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
1837
2012
 
1838
2013
 
1839
2014
  def _load_secrets() -> dict[str, str]:
@@ -1882,6 +2057,11 @@ def _build_runtime_rails(
1882
2057
  ) from exc
1883
2058
  if cell_config.rail is not None:
1884
2059
  rail = cell_config.rail
2060
+ job_position = (
2061
+ override
2062
+ if override is not None
2063
+ else _rail_fraction(rail.default_position_percent)
2064
+ )
1885
2065
  return (
1886
2066
  RuntimeRail(
1887
2067
  servo_id=int(rail.servo_id),
@@ -1889,11 +2069,8 @@ def _build_runtime_rails(
1889
2069
  left_dir=int(rail.left_dir),
1890
2070
  home_end=str(getattr(rail, "home_end", "right")),
1891
2071
  default_position=_rail_fraction(rail.default_position_percent),
1892
- job_position=(
1893
- override
1894
- if override is not None
1895
- else _rail_fraction(rail.default_position_percent)
1896
- ),
2072
+ job_position=job_position,
2073
+ last_commanded_position=job_position,
1897
2074
  ),
1898
2075
  )
1899
2076
  rails: list[RuntimeRail] = []
@@ -1901,6 +2078,11 @@ def _build_runtime_rails(
1901
2078
  arm_rail = getattr(arm, "rail", None)
1902
2079
  if arm_rail is None:
1903
2080
  continue
2081
+ job_position = (
2082
+ override
2083
+ if override is not None
2084
+ else _rail_fraction(arm_rail.default_position_percent)
2085
+ )
1904
2086
  rails.append(
1905
2087
  RuntimeRail(
1906
2088
  servo_id=int(arm_rail.servo_id),
@@ -1909,11 +2091,8 @@ def _build_runtime_rails(
1909
2091
  home_end=str(getattr(arm_rail, "home_end", "right")),
1910
2092
  arm=arm_name,
1911
2093
  default_position=_rail_fraction(arm_rail.default_position_percent),
1912
- job_position=(
1913
- override
1914
- if override is not None
1915
- else _rail_fraction(arm_rail.default_position_percent)
1916
- ),
2094
+ job_position=job_position,
2095
+ last_commanded_position=job_position,
1917
2096
  )
1918
2097
  )
1919
2098
  return tuple(rails)
@@ -2035,13 +2214,14 @@ def _build_camera_config(config: Any) -> Any:
2035
2214
  return config
2036
2215
 
2037
2216
  camera_type = str(config.get("type", "opencv")).lower()
2038
- # Strip keys that are not OpenCVCameraConfig params. Mount blocks are only
2039
- # used by the edge connector; id_path is the USB port used at provisioning
2040
- # time to create the /dev/video_<name> symlink. A Pi CSI camera is still
2041
- # described to LeRobot as an OpenCV camera — the edge swaps in PiCamera
2042
- # from the cell config's type. use_depth and serial_number tell the edge to
2043
- # open a RealSense; the job camera is still an OpenCV config, and depth is
2044
- # 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.
2045
2225
  _NON_CAMERA_KEYS = {
2046
2226
  "type",
2047
2227
  "arducam_mount",
@@ -2049,6 +2229,9 @@ def _build_camera_config(config: Any) -> Any:
2049
2229
  "id_path",
2050
2230
  "use_depth",
2051
2231
  "serial_number",
2232
+ "auto_exposure",
2233
+ "exposure_time_us",
2234
+ "analogue_gain",
2052
2235
  }
2053
2236
  _OPENCV_SHAPED = {"opencv", "pi", "picam", "picamera", "picamera2", "csi"}
2054
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)