Skip to content

torch_world.evaluation ​

INFO

このページはまだ翻訳されていません。 英語版を読む

Planning ​

function goal_reaching ​

torch_world.evaluation.goal_reaching GitHub

python
goal_reaching(
    env,
    policies: dict[str, Callable[[Tensor], Tensor]],
    start: Tensor,
    goal: Tensor,
    steps: int,
    record: Callable[[object], Tensor] | None = None,
    success: str = "final",
) -> GoalReaching

Run each policy(observation) -> action for steps from start and score it against goal states.

The environment provides distance(states, goal) and success(states, goal), and optionally object_position(states) (for SPL, in environments where a path length is meaningful) and coverage(states, goal). success scores an episode by its "final" step, or by whether it "reached" the goal at any step after the start, as LeWM's and PLDM's protocols do; the success rates and intervals follow it. record(env), if given, returns images (N, 3, H, W) of the batch at every step, for example lambda env: env.render(size=192).

Source code in torch_world/evaluation/planning.py
python
@torch.no_grad()
def goal_reaching(
    env,
    policies: dict[str, Callable[[Tensor], Tensor]],
    start: Tensor,
    goal: Tensor,
    steps: int,
    record: Callable[[object], Tensor] | None = None,
    success: str = "final",
) -> GoalReaching:
    """Run each ``policy(observation) -> action`` for ``steps`` from ``start`` and score it against ``goal`` states.

    The environment provides ``distance(states, goal)`` and ``success(states, goal)``, and optionally
    ``object_position(states)`` (for SPL, in environments where a path length is meaningful) and
    ``coverage(states, goal)``. ``success`` scores an episode by its ``"final"`` step, or by whether it
    ``"reached"`` the goal at any step after the start, as LeWM's and PLDM's protocols do; the success rates and
    intervals follow it. ``record(env)``, if given, returns images
    ``(N, 3, H, W)`` of the batch at every step, for example ``lambda env: env.render(size=192)``.
    """
    if success not in ("final", "reached"):
        raise ValueError(f"success must be 'final' or 'reached', not {success!r}")
    scoring, success, paths, distances, frames = success, {}, {}, {}, {}
    reached, actions, seconds, positions, coverage = {}, {}, {}, {}, {}
    for name, policy in policies.items():
        obs = env.reset(start)
        states, video, taken, elapsed = [env.state], [], [], 0.0
        for t in range(steps + 1):
            if record is not None:
                video.append((record(env).clamp(0, 1) * 255).round().to(torch.uint8).cpu())
            if t < steps:
                tic = time.perf_counter()
                action = policy(obs)
                if isinstance(action, Tensor) and action.is_cuda:
                    torch.cuda.synchronize(action.device)  # count the queued GPU work in the step's time
                elapsed += time.perf_counter() - tic
                taken.append(torch.as_tensor(action).float().cpu())
                obs = env.step(action)
                states.append(env.state)
        paths[name] = torch.stack(states, dim=1)
        distances[name] = env.distance(paths[name], goal)
        reached[name] = env.success(paths[name], goal)
        success[name] = reached[name][:, -1] if scoring == "final" else reached[name][:, 1:].any(1)
        actions[name] = torch.stack(taken, dim=1)
        seconds[name] = elapsed / max(steps, 1)
        if hasattr(env, "object_position"):
            positions[name] = env.object_position(paths[name])
        if hasattr(env, "coverage"):
            coverage[name] = env.coverage(paths[name], goal)
        if record is not None:
            frames[name] = torch.stack(video, dim=1)
    goals = env.object_position(goal) if hasattr(env, "object_position") else None
    return GoalReaching(paths, distances, success, reached, actions, seconds, positions, goals, coverage, frames)

class GoalReaching ​

torch_world.evaluation.GoalReaching GitHub

python
GoalReaching(
    paths: dict[str, Tensor],
    distances: dict[str, Tensor],
    success: dict[str, Tensor],
    reached: dict[str, Tensor] = dict(),
    actions: dict[str, Tensor] = dict(),
    seconds: dict[str, float] = dict(),
    positions: dict[str, Tensor] = dict(),
    goals: Tensor | None = None,
    coverage: dict[str, Tensor] = dict(),
    frames: dict[str, Tensor] = dict(),
)

Closed-loop episodes of each policy from the same starts toward the same goals.

Per policy: paths are states (N, steps + 1, state_dim), distances the distance to the goal at every step (N, steps + 1), reached whether each step counts as reaching it (N, steps + 1), success whether the episode succeeds (N,) (at its final step, or at any step with success="reached"), actions the actions taken (N, steps, action_dim) and seconds the mean wall time of one policy call. positions (N, steps + 1, D) and goals (N, D) locate what the task moves (env.object_position), for SPL, coverage (N, steps + 1) is the goal-region overlap for environments that define it (Push-T), and frames holds uint8 videos (N, steps + 1, 3, H, W) when record was given.

Members

MemberDescription
ratesFinal success rate of each policy.
intervalsFinal success rate of each policy with its Wilson interval, as plots.bars draws it.
summaryThe standard measures of goal-reaching episodes, per policy:
Source code in torch_world/evaluation/planning.py
python
@dataclass
class GoalReaching:
    """Closed-loop episodes of each policy from the same starts toward the same goals.

    Per policy: ``paths`` are states ``(N, steps + 1, state_dim)``, ``distances`` the distance to the goal at every
    step ``(N, steps + 1)``, ``reached`` whether each step counts as reaching it ``(N, steps + 1)``, ``success``
    whether the episode succeeds ``(N,)`` (at its final step, or at any step with ``success="reached"``), ``actions`` the actions taken ``(N, steps, action_dim)`` and ``seconds``
    the mean wall time of one policy call. ``positions`` ``(N, steps + 1, D)`` and ``goals`` ``(N, D)`` locate what the
    task moves (``env.object_position``), for SPL, ``coverage`` ``(N, steps + 1)`` is the goal-region overlap for environments that
    define it (Push-T), and ``frames`` holds uint8 videos ``(N, steps + 1, 3, H, W)`` when ``record`` was given.
    """

    paths: dict[str, Tensor]
    distances: dict[str, Tensor]
    success: dict[str, Tensor]
    reached: dict[str, Tensor] = field(default_factory=dict)
    actions: dict[str, Tensor] = field(default_factory=dict)
    seconds: dict[str, float] = field(default_factory=dict)
    positions: dict[str, Tensor] = field(default_factory=dict)
    goals: Tensor | None = None
    coverage: dict[str, Tensor] = field(default_factory=dict)
    frames: dict[str, Tensor] = field(default_factory=dict)

    def rates(self) -> dict[str, float]:
        """Final success rate of each policy."""
        return {name: s.float().mean().item() for name, s in self.success.items()}

    def intervals(self, confidence: float = 0.95) -> dict[str, metrics.Rate]:
        """Final success rate of each policy with its Wilson interval, as ``plots.bars`` draws it."""
        return {name: metrics.success_rate(s, confidence) for name, s in self.success.items()}

    def summary(self) -> dict[str, dict[str, float | metrics.Rate]]:
        """The standard measures of goal-reaching episodes, per policy:

        - ``success``: final success rate with its 95% Wilson interval;
        - ``reached``: fraction of episodes that reach the goal at any step;
        - ``steps``: mean number of steps to first reach the goal, over the episodes that do;
        - ``final distance``: median distance to the goal at the end;
        - ``progress``: median fraction of the initial distance closed, over episodes that do not start at the goal;
        - ``SPL``: success weighted by path length of the scored object;
        - ``smoothness``: mean change between consecutive actions (lower is smoother);
        - ``ms / step``: wall time of one policy call;
        - ``coverage``: mean of the best goal-region overlap of each episode, when the environment defines it.
        """
        out = {}
        for name, success in self.success.items():
            row = {"success": metrics.success_rate(success)}
            if name in self.reached:
                first = metrics.first_success(self.reached[name])
                row["reached"] = (first >= 0).float().mean().item()
                row["steps"] = first[first >= 0].float().mean().item() if (first >= 0).any() else float("nan")
            row["final distance"] = self.distances[name][:, -1].median().item()
            row["progress"] = metrics.progress(self.distances[name]).nanmedian().item()
            if name in self.positions and self.goals is not None:
                row["SPL"] = metrics.spl(success, self.positions[name], self.goals)
            if name in self.actions and self.actions[name].size(1) > 1:
                row["smoothness"] = metrics.smoothness(self.actions[name]).mean().item()
            if name in self.seconds:
                row["ms / step"] = 1000 * self.seconds[name]
            if name in self.coverage:
                row["coverage"] = self.coverage[name].max(1).values.mean().item()
            out[name] = row
        return out

    def __repr__(self) -> str:
        summary = self.summary()
        columns = list(dict.fromkeys(k for row in summary.values() for k in row))
        width = max(map(len, summary)) + 2
        lines = [
            " " * width + "".join(f"{c:>17s}" if c == "success" else f"{c:>{max(len(c), 6) + 2}s}" for c in columns)
        ]
        for name, row in summary.items():
            cells = []
            for c in columns:
                w = 17 if c == "success" else max(len(c), 6) + 2
                v = row.get(c, float("nan"))
                text = (
                    str(v)
                    if isinstance(v, metrics.Rate)
                    else f"{v:.0%}"
                    if c in ("reached", "coverage")
                    else f"{v:.3g}"
                )
                cells.append(f"{text:>{w}s}")
            lines.append(f"{name:{width}s}" + "".join(cells))
        return "\n".join(lines)

method rates ​

torch_world.evaluation.GoalReaching.rates GitHub

python
rates() -> dict[str, float]

Final success rate of each policy.

Source code in torch_world/evaluation/planning.py
python
def rates(self) -> dict[str, float]:
    """Final success rate of each policy."""
    return {name: s.float().mean().item() for name, s in self.success.items()}

method intervals ​

torch_world.evaluation.GoalReaching.intervals GitHub

python
intervals(confidence: float = 0.95) -> dict[str, metrics.Rate]

Final success rate of each policy with its Wilson interval, as plots.bars draws it.

Source code in torch_world/evaluation/planning.py
python
def intervals(self, confidence: float = 0.95) -> dict[str, metrics.Rate]:
    """Final success rate of each policy with its Wilson interval, as ``plots.bars`` draws it."""
    return {name: metrics.success_rate(s, confidence) for name, s in self.success.items()}

method summary ​

torch_world.evaluation.GoalReaching.summary GitHub

python
summary() -> dict[str, dict[str, float | metrics.Rate]]

The standard measures of goal-reaching episodes, per policy:

  • success: final success rate with its 95% Wilson interval;
  • reached: fraction of episodes that reach the goal at any step;
  • steps: mean number of steps to first reach the goal, over the episodes that do;
  • final distance: median distance to the goal at the end;
  • progress: median fraction of the initial distance closed, over episodes that do not start at the goal;
  • SPL: success weighted by path length of the scored object;
  • smoothness: mean change between consecutive actions (lower is smoother);
  • ms / step: wall time of one policy call;
  • coverage: mean of the best goal-region overlap of each episode, when the environment defines it.
Source code in torch_world/evaluation/planning.py
python
def summary(self) -> dict[str, dict[str, float | metrics.Rate]]:
    """The standard measures of goal-reaching episodes, per policy:

    - ``success``: final success rate with its 95% Wilson interval;
    - ``reached``: fraction of episodes that reach the goal at any step;
    - ``steps``: mean number of steps to first reach the goal, over the episodes that do;
    - ``final distance``: median distance to the goal at the end;
    - ``progress``: median fraction of the initial distance closed, over episodes that do not start at the goal;
    - ``SPL``: success weighted by path length of the scored object;
    - ``smoothness``: mean change between consecutive actions (lower is smoother);
    - ``ms / step``: wall time of one policy call;
    - ``coverage``: mean of the best goal-region overlap of each episode, when the environment defines it.
    """
    out = {}
    for name, success in self.success.items():
        row = {"success": metrics.success_rate(success)}
        if name in self.reached:
            first = metrics.first_success(self.reached[name])
            row["reached"] = (first >= 0).float().mean().item()
            row["steps"] = first[first >= 0].float().mean().item() if (first >= 0).any() else float("nan")
        row["final distance"] = self.distances[name][:, -1].median().item()
        row["progress"] = metrics.progress(self.distances[name]).nanmedian().item()
        if name in self.positions and self.goals is not None:
            row["SPL"] = metrics.spl(success, self.positions[name], self.goals)
        if name in self.actions and self.actions[name].size(1) > 1:
            row["smoothness"] = metrics.smoothness(self.actions[name]).mean().item()
        if name in self.seconds:
            row["ms / step"] = 1000 * self.seconds[name]
        if name in self.coverage:
            row["coverage"] = self.coverage[name].max(1).values.mean().item()
        out[name] = row
    return out

function goal_policy ​

torch_world.evaluation.goal_policy GitHub

python
goal_policy(
    model,
    planner,
    goal_images: Tensor,
    action_dim: int | None = None,
    execute: int = 1,
    **encode,
) -> Callable[[Tensor], Tensor]

Closed-loop policy that plans with planner(model, z, goal) from each observation toward goal images.

Observations and goal_images (B, C, H, W) are encoded with model.encode (one frame, on the model's device; encode holds extra keyword arguments). Without action_dim the policy runs the first planned action and plans again. When the planner's steps are chunks of k environment actions (a model trained with a frameskip of k), pass the environment's action_dim: the policy runs execute chunks, one action per call, before planning again, and needs reset() between episodes.

Source code in torch_world/evaluation/planning.py
python
def goal_policy(
    model, planner, goal_images: Tensor, action_dim: int | None = None, execute: int = 1, **encode
) -> Callable[[Tensor], Tensor]:
    """Closed-loop policy that plans with ``planner(model, z, goal)`` from each observation toward goal images.

    Observations and ``goal_images`` ``(B, C, H, W)`` are encoded with ``model.encode`` (one frame, on the model's
    device; ``encode`` holds extra keyword arguments). Without ``action_dim`` the policy runs the first planned action
    and plans again. When the planner's steps are chunks of ``k`` environment actions (a model trained with a
    frameskip of ``k``), pass the environment's ``action_dim``: the policy runs ``execute`` chunks, one action per call,
    before planning again, and needs ``reset()`` between episodes.
    """
    from torch_world.planning.mpc import RecedingHorizon

    device = next(model.parameters()).device
    with torch.no_grad():
        goal = model.encode(goal_images[:, None].to(device), **encode)[:, 0]

    def plan(obs: Tensor) -> Tensor:
        return planner(model, model.encode(obs[:, None].to(device), **encode), goal).to(obs.device)

    if action_dim is None:
        return lambda obs: plan(obs)[:, 0]
    return RecedingHorizon(plan, action_dim, execute)

function random_policy ​

torch_world.evaluation.random_policy GitHub

python
random_policy(env) -> Callable[[Tensor], Tensor]

Uniform actions in [-1, 1]^action_dim.

Source code in torch_world/evaluation/planning.py
python
def random_policy(env) -> Callable[[Tensor], Tensor]:
    """Uniform actions in ``[-1, 1]^action_dim``."""
    return lambda obs: torch.rand(len(obs), env.action_dim, device=obs.device) * 2 - 1

function run_episodes ​

torch_world.evaluation.run_episodes GitHub

python
run_episodes(
    episode: Callable[[Any], dict],
    seeds: Iterable,
    *,
    timeout: float,
    path: str | Path | None = None,
) -> list[dict]

Run episode(seed) for every seed in one worker process, with a time limit per episode.

A stall inside native code (for example MuJoCo's EGL rendering on a headless GPU server) cannot be interrupted from Python, so the episodes run in a spawned worker. The worker is reused from one episode to the next, keeping whatever episode caches (a loaded model, an open environment); when an episode exceeds timeout seconds the worker is killed, the episode is recorded with status="timeout" and a new worker carries on with the next seed. A worker that dies (a segfault) is replaced the same way, with status="crashed". An exception is recorded with status="error"; a finished episode with status="ok" and the keys of its result. episode must be picklable, a function defined at the top level of a module.

With path, each record is appended to that JSON Lines file as soon as its episode ends, and seeds already recorded there are skipped, so an interrupted evaluation resumes where it stopped. Returns the records of all seeds, in their order, including those read back from path.

Source code in torch_world/evaluation/watchdog.py
python
def run_episodes(
    episode: Callable[[Any], dict],
    seeds: Iterable,
    *,
    timeout: float,
    path: str | Path | None = None,
) -> list[dict]:
    """Run ``episode(seed)`` for every seed in one worker process, with a time limit per episode.

    A stall inside native code (for example MuJoCo's EGL rendering on a headless GPU server) cannot be interrupted
    from Python, so the episodes run in a spawned worker. The worker is reused from one episode to the next, keeping
    whatever ``episode`` caches (a loaded model, an open environment); when an episode exceeds ``timeout`` seconds the
    worker is killed, the episode is recorded with ``status="timeout"`` and a new worker carries on with the next seed.
    A worker that dies (a segfault) is replaced the same way, with ``status="crashed"``. An exception is recorded with
    ``status="error"``; a finished episode with ``status="ok"`` and the keys of its
    result. ``episode`` must be picklable, a function defined at the top level of a module.

    With ``path``, each record is appended to that JSON Lines file as soon as its episode ends, and seeds already
    recorded there are skipped, so an interrupted evaluation resumes where it stopped. Returns the records of all
    ``seeds``, in their order, including those read back from ``path``.
    """
    seeds = list(seeds)
    path = None if path is None else Path(path)
    done = {}
    if path is not None and path.exists():
        for line in path.read_text().splitlines():
            if line.strip():
                record = json.loads(line)
                done[json.dumps(record["seed"])] = record
    context = mp.get_context("spawn")
    worker = None
    try:
        for seed in seeds:
            key = json.dumps(seed)
            if key in done:
                continue
            if worker is None:
                worker = _Worker(context, episode)
            tic = time.monotonic()
            worker.tasks.put(seed)
            status, value = worker.wait(tic + timeout)
            if status in ("timeout", "crashed"):
                worker.kill()
                worker = None
            record = {"seed": seed, "status": status, "seconds": round(time.monotonic() - tic, 3)}
            if status == "ok":
                record.update(value)
            elif value is not None:
                record["error"] = value
            done[key] = record
            if path is not None:
                with path.open("a") as file:
                    file.write(json.dumps(record) + "\n")
    finally:
        if worker is not None:
            worker.stop()
    return [done[json.dumps(seed)] for seed in seeds]

RoboDojo ​

class RoboDojoPolicy ​

torch_world.evaluation.RoboDojoPolicy GitHub

python
RoboDojoPolicy(
    policy: Callable[[Tensor], Tensor],
    *,
    observation: str = "rgb",
    camera: str = "cam_head",
    size: int = 64,
    action_type: str = "joint",
    robot: dict | None = None,
    action_bounds: tuple | None = None,
    relative: bool = False,
    device: str | torch.device | None = None,
)

Serve a policy to RoboDojo <https://github.com/RoboDojo-Benchmark/RoboDojo>_ as an XPolicyLab Model.

RoboDojo evaluates in Isaac Sim and asks an XPolicyLab policy server for actions over WebSocket, so the policy runs in its own environment and is scored on RoboDojo's own layouts. Subclass this as the Model of an XPolicyLab policy folder; the server calls reset, update_obs(_batch) and get_action(_batch).

policy maps a batch of observations to actions (B, A), or to chunks (B, H, A) that RoboDojo executes in order. With observation="rgb" it sees camera frames (B, 3, size, size) in [0, 1], resized as load_robodojo resizes them for training; with "state", the packed robot vector (B, D) of robot_layout. Actions use the same packing. action_bounds=(low, high), each (A,), maps policy actions in [-1, 1] to robot units, for example the range of the training actions; without it they are robot units. With relative=True the policy's joint actions are offsets from the current robot state, and the robot is sent state + action; at 25 Hz consecutive joint targets are nearly the current state, so offsets are the informative quantity to learn and plan.

Members

MemberDescription
observeOne RoboDojo observation dict as the policy's input, without the batch dimension.
get_action_batchAn action chunk per environment, each action a dict of robot fields in robot units.
Source code in torch_world/evaluation/robodojo.py
python
class RoboDojoPolicy:
    """Serve a policy to `RoboDojo <https://github.com/RoboDojo-Benchmark/RoboDojo>`_ as an XPolicyLab ``Model``.

    RoboDojo evaluates in Isaac Sim and asks an XPolicyLab policy server for actions over WebSocket, so the policy
    runs in its own environment and is scored on RoboDojo's own layouts. Subclass this as the ``Model`` of an
    XPolicyLab policy folder; the server calls ``reset``, ``update_obs(_batch)`` and ``get_action(_batch)``.

    ``policy`` maps a batch of observations to actions ``(B, A)``, or to chunks ``(B, H, A)`` that RoboDojo executes
    in order. With ``observation="rgb"`` it sees ``camera`` frames ``(B, 3, size, size)`` in [0, 1], resized as
    `load_robodojo` resizes them for training; with ``"state"``, the packed robot vector ``(B, D)`` of
    `robot_layout`. Actions use the same packing. ``action_bounds=(low, high)``, each ``(A,)``, maps policy actions
    in [-1, 1] to robot units, for example the range of the training actions; without it they are robot units.
    With ``relative=True`` the policy's joint actions are offsets from the current robot state, and the robot is sent
    ``state + action``; at 25 Hz consecutive joint targets are nearly the current state, so offsets are the
    informative quantity to learn and plan.
    """

    def __init__(
        self,
        policy: Callable[[Tensor], Tensor],
        *,
        observation: str = "rgb",
        camera: str = "cam_head",
        size: int = 64,
        action_type: str = "joint",
        robot: dict | None = None,
        action_bounds: tuple | None = None,
        relative: bool = False,
        device: str | torch.device | None = None,
    ):
        if observation not in ("rgb", "state"):
            raise ValueError("observation must be 'rgb' or 'state'")
        if relative and action_type != "joint":
            raise ValueError("relative actions are joint offsets; poses do not add")
        self.policy, self.observation, self.camera, self.size = policy, observation, camera, size
        self.relative = relative
        self.layout = robot_layout(action_type, robot)
        self.action_dim = sum(width for _, width in self.layout)
        self.device = torch.device(device or "cpu")
        self.bounds = None
        if action_bounds is not None:
            self.bounds = tuple(torch.as_tensor(b, dtype=torch.float32, device=self.device) for b in action_bounds)
            if any(b.shape != (self.action_dim,) for b in self.bounds):
                raise ValueError(f"action_bounds must be two tensors of shape ({self.action_dim},)")
        self.reset()

    def observe(self, obs: dict) -> Tensor:
        """One RoboDojo observation dict as the policy's input, without the batch dimension."""
        if self.observation == "state":
            return torch.from_numpy(pack(obs["state"], self.layout))
        return resize_images(obs["vision"][self.camera]["color"], self.size).float() / 255

    def update_obs(self, obs: dict):
        self.update_obs_batch([obs])

    def update_obs_batch(self, obs_list: list[dict]):
        self._latest = [obs.get("env_idx", 0) for obs in obs_list]
        self._observations.update(zip(self._latest, map(self.observe, obs_list)))
        if self.relative:
            self._states.update(
                (i, torch.from_numpy(pack(obs["state"], self.layout))) for i, obs in zip(self._latest, obs_list)
            )

    def get_action(self) -> list[dict]:
        if not self._latest:
            raise RuntimeError("get_action() called before update_obs()")
        return self.get_action_batch(self._latest[:1])[0]

    def get_action_batch(self, env_idx_list: list[int] | None = None) -> list[list[dict]]:
        """An action chunk per environment, each action a dict of robot fields in robot units."""
        env_idx_list = self._latest if env_idx_list is None else env_idx_list
        if not env_idx_list:
            raise RuntimeError("get_action_batch() called before update_obs_batch()")
        observations = torch.stack([self._observations[i] for i in env_idx_list]).to(self.device)
        with torch.no_grad():
            actions = torch.as_tensor(self.policy(observations), dtype=torch.float32, device=self.device)
        actions = actions[:, None] if actions.ndim == 2 else actions
        expected = actions.ndim == 3 and actions.shape[::2] == (len(env_idx_list), self.action_dim)
        if not expected or not torch.isfinite(actions).all():
            raise ValueError(f"policy must return finite actions (B, {self.action_dim}) or chunks (B, H, A)")
        if self.bounds is not None:
            low, high = self.bounds
            actions = low + (actions.clamp(-1, 1) + 1) / 2 * (high - low)
        if self.relative:
            actions = actions + torch.stack([self._states[i] for i in env_idx_list]).to(self.device)[:, None]
        return [[self._unpack(action) for action in chunk] for chunk in actions.cpu().numpy()]

    def _unpack(self, action) -> dict:
        fields, offset = {}, 0
        for key, width in self.layout:
            fields[key], offset = action[offset : offset + width], offset + width
        return fields

    def reset(self):
        self._observations, self._states, self._latest = {}, {}, []
        if hasattr(self.policy, "reset"):
            self.policy.reset()

method observe ​

torch_world.evaluation.RoboDojoPolicy.observe GitHub

python
observe(obs: dict) -> Tensor

One RoboDojo observation dict as the policy's input, without the batch dimension.

Source code in torch_world/evaluation/robodojo.py
python
def observe(self, obs: dict) -> Tensor:
    """One RoboDojo observation dict as the policy's input, without the batch dimension."""
    if self.observation == "state":
        return torch.from_numpy(pack(obs["state"], self.layout))
    return resize_images(obs["vision"][self.camera]["color"], self.size).float() / 255

method get_action_batch ​

torch_world.evaluation.RoboDojoPolicy.get_action_batch GitHub

python
get_action_batch(env_idx_list: list[int] | None = None) -> list[list[dict]]

An action chunk per environment, each action a dict of robot fields in robot units.

Source code in torch_world/evaluation/robodojo.py
python
def get_action_batch(self, env_idx_list: list[int] | None = None) -> list[list[dict]]:
    """An action chunk per environment, each action a dict of robot fields in robot units."""
    env_idx_list = self._latest if env_idx_list is None else env_idx_list
    if not env_idx_list:
        raise RuntimeError("get_action_batch() called before update_obs_batch()")
    observations = torch.stack([self._observations[i] for i in env_idx_list]).to(self.device)
    with torch.no_grad():
        actions = torch.as_tensor(self.policy(observations), dtype=torch.float32, device=self.device)
    actions = actions[:, None] if actions.ndim == 2 else actions
    expected = actions.ndim == 3 and actions.shape[::2] == (len(env_idx_list), self.action_dim)
    if not expected or not torch.isfinite(actions).all():
        raise ValueError(f"policy must return finite actions (B, {self.action_dim}) or chunks (B, H, A)")
    if self.bounds is not None:
        low, high = self.bounds
        actions = low + (actions.clamp(-1, 1) + 1) / 2 * (high - low)
    if self.relative:
        actions = actions + torch.stack([self._states[i] for i in env_idx_list]).to(self.device)[:, None]
    return [[self._unpack(action) for action in chunk] for chunk in actions.cpu().numpy()]

Question answering ​

module vqa ​

torch_world.evaluation.vqa

class VQAResults ​

torch_world.evaluation.vqa.VQAResults GitHub

python
VQAResults(
    dataset: Dataset,
    predictions: list[str],
    truths: list[str],
    kinds: list[str],
)

Predicted and true answers of every question in dataset, with the kind of each question.

Members

MemberDescription
accuracyAccuracy per question kind, and over all questions.
majorityAccuracy of always giving the most common true answer of each kind.
scoresAccuracy beside the majority baseline per kind, as plots.bars expects.
cardsper_kind questions of each kind, a mistake first when there is one, as plots.answers expects.
Source code in torch_world/evaluation/vqa.py
python
@dataclass
class VQAResults:
    """Predicted and true answers of every question in ``dataset``, with the kind of each question."""

    dataset: Dataset
    predictions: list[str]
    truths: list[str]
    kinds: list[str]

    def accuracy(self) -> dict[str, float]:
        """Accuracy per question kind, and over all questions."""
        out = {}
        for kind in [*dict.fromkeys(self.kinds), "all"]:
            pairs = [(p, t) for p, t, k in zip(self.predictions, self.truths, self.kinds) if kind in (k, "all")]
            out[kind] = sum(p == t for p, t in pairs) / len(pairs)
        return out

    def majority(self) -> dict[str, float]:
        """Accuracy of always giving the most common true answer of each kind."""
        out = {}
        for kind in dict.fromkeys(self.kinds):
            answers = [t for t, k in zip(self.truths, self.kinds) if k == kind]
            out[kind] = max(map(answers.count, set(answers))) / len(answers)
        return out

    def scores(self, name: str = "model") -> dict[str, dict[str, float]]:
        """Accuracy beside the majority baseline per kind, as ``plots.bars`` expects."""
        majority = self.majority()
        return {
            kind: {name: acc, "majority answer": majority[kind]}
            for kind, acc in self.accuracy().items()
            if kind in majority
        }

    def cards(self, per_kind: int = 2, seed: int = 0) -> tuple[Tensor, list[str], list[str], list[str]]:
        """``per_kind`` questions of each kind, a mistake first when there is one, as ``plots.answers`` expects."""
        order = list(range(len(self.truths)))
        random.Random(seed).shuffle(order)
        picks = []
        for kind in dict.fromkeys(self.kinds):
            right = [i for i in order if self.kinds[i] == kind and self.predictions[i] == self.truths[i]]
            wrong = [i for i in order if self.kinds[i] == kind and self.predictions[i] != self.truths[i]]
            picks += (wrong[:1] + right)[:per_kind]
        questions = [self.dataset[i]["question"].replace(" ?", "?") for i in picks]
        return (
            self.dataset.pixels(picks),
            questions,
            [self.predictions[i] for i in picks],
            [self.truths[i] for i in picks],
        )

    def __repr__(self) -> str:
        majority = self.majority()
        rows = [f"{'kind':14s}{'accuracy':>10s}{'majority':>10s}{'questions':>11s}"]
        for kind, acc in self.accuracy().items():
            n = len(self.kinds) if kind == "all" else self.kinds.count(kind)
            base = f"{majority[kind]:10.3f}" if kind in majority else " " * 10
            rows.append(f"{kind:14s}{acc:10.3f}{base}{n:11d}")
        return "\n".join(rows)

method accuracy ​

torch_world.evaluation.vqa.VQAResults.accuracy GitHub

python
accuracy() -> dict[str, float]

Accuracy per question kind, and over all questions.

Source code in torch_world/evaluation/vqa.py
python
def accuracy(self) -> dict[str, float]:
    """Accuracy per question kind, and over all questions."""
    out = {}
    for kind in [*dict.fromkeys(self.kinds), "all"]:
        pairs = [(p, t) for p, t, k in zip(self.predictions, self.truths, self.kinds) if kind in (k, "all")]
        out[kind] = sum(p == t for p, t in pairs) / len(pairs)
    return out

method majority ​

torch_world.evaluation.vqa.VQAResults.majority GitHub

python
majority() -> dict[str, float]

Accuracy of always giving the most common true answer of each kind.

Source code in torch_world/evaluation/vqa.py
python
def majority(self) -> dict[str, float]:
    """Accuracy of always giving the most common true answer of each kind."""
    out = {}
    for kind in dict.fromkeys(self.kinds):
        answers = [t for t, k in zip(self.truths, self.kinds) if k == kind]
        out[kind] = max(map(answers.count, set(answers))) / len(answers)
    return out

method scores ​

torch_world.evaluation.vqa.VQAResults.scores GitHub

python
scores(name: str = "model") -> dict[str, dict[str, float]]

Accuracy beside the majority baseline per kind, as plots.bars expects.

Source code in torch_world/evaluation/vqa.py
python
def scores(self, name: str = "model") -> dict[str, dict[str, float]]:
    """Accuracy beside the majority baseline per kind, as ``plots.bars`` expects."""
    majority = self.majority()
    return {
        kind: {name: acc, "majority answer": majority[kind]}
        for kind, acc in self.accuracy().items()
        if kind in majority
    }

method cards ​

torch_world.evaluation.vqa.VQAResults.cards GitHub

python
cards(
    per_kind: int = 2, seed: int = 0
) -> tuple[Tensor, list[str], list[str], list[str]]

per_kind questions of each kind, a mistake first when there is one, as plots.answers expects.

Source code in torch_world/evaluation/vqa.py
python
def cards(self, per_kind: int = 2, seed: int = 0) -> tuple[Tensor, list[str], list[str], list[str]]:
    """``per_kind`` questions of each kind, a mistake first when there is one, as ``plots.answers`` expects."""
    order = list(range(len(self.truths)))
    random.Random(seed).shuffle(order)
    picks = []
    for kind in dict.fromkeys(self.kinds):
        right = [i for i in order if self.kinds[i] == kind and self.predictions[i] == self.truths[i]]
        wrong = [i for i in order if self.kinds[i] == kind and self.predictions[i] != self.truths[i]]
        picks += (wrong[:1] + right)[:per_kind]
    questions = [self.dataset[i]["question"].replace(" ?", "?") for i in picks]
    return (
        self.dataset.pixels(picks),
        questions,
        [self.predictions[i] for i in picks],
        [self.truths[i] for i in picks],
    )

function compare ​

torch_world.evaluation.vqa.compare GitHub

python
compare(
    results: dict[str, VQAResults], baseline: str = "majority answer"
) -> dict[str, dict[str, float]]

Accuracy per kind of several evaluations, e.g. on train and test, beside the majority baseline of the last one, as plots.bars expects.

Source code in torch_world/evaluation/vqa.py
python
def compare(results: dict[str, VQAResults], baseline: str = "majority answer") -> dict[str, dict[str, float]]:
    """Accuracy per kind of several evaluations, e.g. on train and test, beside the majority baseline of the last one,
    as ``plots.bars`` expects."""
    majority = list(results.values())[-1].majority()
    return {
        kind: {name: r.accuracy()[kind] for name, r in results.items()} | {baseline: base}
        for kind, base in majority.items()
    }

function vqa ​

torch_world.evaluation.vqa.vqa GitHub

python
vqa(
    model,
    dataset: Dataset,
    tokenizer,
    candidates: list[str] | None = None,
    batch_size: int = 1024,
    shuffle_images: bool = False,
    generator: torch.Generator | None = None,
) -> VQAResults

Answer every question of dataset by retrieval over candidates (by default dataset.answers).

model follows the VLJEPA interface (embed_text and retrieve) and items carry image, question, answer and kind. With shuffle_images, each question is asked about a random image of the whole dataset: a control that measures how much the answers come from the image rather than from the question.

Source code in torch_world/evaluation/vqa.py
python
@torch.no_grad()
def vqa(
    model,
    dataset: Dataset,
    tokenizer,
    candidates: list[str] | None = None,
    batch_size: int = 1024,
    shuffle_images: bool = False,
    generator: torch.Generator | None = None,
) -> VQAResults:
    """Answer every question of ``dataset`` by retrieval over ``candidates`` (by default ``dataset.answers``).

    ``model`` follows the ``VLJEPA`` interface (``embed_text`` and ``retrieve``) and items carry ``image``,
    ``question``, ``answer`` and ``kind``. With ``shuffle_images``, each question is asked about a
    random image of the whole dataset: a control that measures how much the answers come from the image rather than
    from the question.
    """
    candidates = candidates or dataset.answers
    bank = model.embed_text(*tokenizer(candidates))
    predictions, truths, kinds = [], [], []
    for batch in DataLoader(_Shuffled(dataset, generator) if shuffle_images else dataset, batch_size=batch_size):
        x = batch["image"].to(bank.device)
        x = x.float() if x.is_floating_point() else x
        predictions += [candidates[i] for i in model.retrieve(x, bank, *tokenizer(batch["question"])).tolist()]
        truths += batch["answer"]
        kinds += batch["kind"]
    return VQAResults(dataset, predictions, truths, kinds)

class VQAResults ​

torch_world.evaluation.VQAResults GitHub

python
VQAResults(
    dataset: Dataset,
    predictions: list[str],
    truths: list[str],
    kinds: list[str],
)

Predicted and true answers of every question in dataset, with the kind of each question.

Members

MemberDescription
accuracyAccuracy per question kind, and over all questions.
majorityAccuracy of always giving the most common true answer of each kind.
scoresAccuracy beside the majority baseline per kind, as plots.bars expects.
cardsper_kind questions of each kind, a mistake first when there is one, as plots.answers expects.
Source code in torch_world/evaluation/vqa.py
python
@dataclass
class VQAResults:
    """Predicted and true answers of every question in ``dataset``, with the kind of each question."""

    dataset: Dataset
    predictions: list[str]
    truths: list[str]
    kinds: list[str]

    def accuracy(self) -> dict[str, float]:
        """Accuracy per question kind, and over all questions."""
        out = {}
        for kind in [*dict.fromkeys(self.kinds), "all"]:
            pairs = [(p, t) for p, t, k in zip(self.predictions, self.truths, self.kinds) if kind in (k, "all")]
            out[kind] = sum(p == t for p, t in pairs) / len(pairs)
        return out

    def majority(self) -> dict[str, float]:
        """Accuracy of always giving the most common true answer of each kind."""
        out = {}
        for kind in dict.fromkeys(self.kinds):
            answers = [t for t, k in zip(self.truths, self.kinds) if k == kind]
            out[kind] = max(map(answers.count, set(answers))) / len(answers)
        return out

    def scores(self, name: str = "model") -> dict[str, dict[str, float]]:
        """Accuracy beside the majority baseline per kind, as ``plots.bars`` expects."""
        majority = self.majority()
        return {
            kind: {name: acc, "majority answer": majority[kind]}
            for kind, acc in self.accuracy().items()
            if kind in majority
        }

    def cards(self, per_kind: int = 2, seed: int = 0) -> tuple[Tensor, list[str], list[str], list[str]]:
        """``per_kind`` questions of each kind, a mistake first when there is one, as ``plots.answers`` expects."""
        order = list(range(len(self.truths)))
        random.Random(seed).shuffle(order)
        picks = []
        for kind in dict.fromkeys(self.kinds):
            right = [i for i in order if self.kinds[i] == kind and self.predictions[i] == self.truths[i]]
            wrong = [i for i in order if self.kinds[i] == kind and self.predictions[i] != self.truths[i]]
            picks += (wrong[:1] + right)[:per_kind]
        questions = [self.dataset[i]["question"].replace(" ?", "?") for i in picks]
        return (
            self.dataset.pixels(picks),
            questions,
            [self.predictions[i] for i in picks],
            [self.truths[i] for i in picks],
        )

    def __repr__(self) -> str:
        majority = self.majority()
        rows = [f"{'kind':14s}{'accuracy':>10s}{'majority':>10s}{'questions':>11s}"]
        for kind, acc in self.accuracy().items():
            n = len(self.kinds) if kind == "all" else self.kinds.count(kind)
            base = f"{majority[kind]:10.3f}" if kind in majority else " " * 10
            rows.append(f"{kind:14s}{acc:10.3f}{base}{n:11d}")
        return "\n".join(rows)

method accuracy ​

torch_world.evaluation.VQAResults.accuracy GitHub

python
accuracy() -> dict[str, float]

Accuracy per question kind, and over all questions.

Source code in torch_world/evaluation/vqa.py
python
def accuracy(self) -> dict[str, float]:
    """Accuracy per question kind, and over all questions."""
    out = {}
    for kind in [*dict.fromkeys(self.kinds), "all"]:
        pairs = [(p, t) for p, t, k in zip(self.predictions, self.truths, self.kinds) if kind in (k, "all")]
        out[kind] = sum(p == t for p, t in pairs) / len(pairs)
    return out

method majority ​

torch_world.evaluation.VQAResults.majority GitHub

python
majority() -> dict[str, float]

Accuracy of always giving the most common true answer of each kind.

Source code in torch_world/evaluation/vqa.py
python
def majority(self) -> dict[str, float]:
    """Accuracy of always giving the most common true answer of each kind."""
    out = {}
    for kind in dict.fromkeys(self.kinds):
        answers = [t for t, k in zip(self.truths, self.kinds) if k == kind]
        out[kind] = max(map(answers.count, set(answers))) / len(answers)
    return out

method scores ​

torch_world.evaluation.VQAResults.scores GitHub

python
scores(name: str = "model") -> dict[str, dict[str, float]]

Accuracy beside the majority baseline per kind, as plots.bars expects.

Source code in torch_world/evaluation/vqa.py
python
def scores(self, name: str = "model") -> dict[str, dict[str, float]]:
    """Accuracy beside the majority baseline per kind, as ``plots.bars`` expects."""
    majority = self.majority()
    return {
        kind: {name: acc, "majority answer": majority[kind]}
        for kind, acc in self.accuracy().items()
        if kind in majority
    }

method cards ​

torch_world.evaluation.VQAResults.cards GitHub

python
cards(
    per_kind: int = 2, seed: int = 0
) -> tuple[Tensor, list[str], list[str], list[str]]

per_kind questions of each kind, a mistake first when there is one, as plots.answers expects.

Source code in torch_world/evaluation/vqa.py
python
def cards(self, per_kind: int = 2, seed: int = 0) -> tuple[Tensor, list[str], list[str], list[str]]:
    """``per_kind`` questions of each kind, a mistake first when there is one, as ``plots.answers`` expects."""
    order = list(range(len(self.truths)))
    random.Random(seed).shuffle(order)
    picks = []
    for kind in dict.fromkeys(self.kinds):
        right = [i for i in order if self.kinds[i] == kind and self.predictions[i] == self.truths[i]]
        wrong = [i for i in order if self.kinds[i] == kind and self.predictions[i] != self.truths[i]]
        picks += (wrong[:1] + right)[:per_kind]
    questions = [self.dataset[i]["question"].replace(" ?", "?") for i in picks]
    return (
        self.dataset.pixels(picks),
        questions,
        [self.predictions[i] for i in picks],
        [self.truths[i] for i in picks],
    )