File size: 2,451 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""Read-only diagnostics around the existing keypose execution boundary."""

import json
from pathlib import Path

import numpy as np
import torch
from pydantic import BaseModel, ConfigDict

from lim.keypose_control import KeyposeEnv, keypose_command


class KeyposeTraceConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    env: KeyposeEnv
    """Unmodified observed-state keypose executor."""
    path: Path
    """New JSONL file of pre-action diagnostics, one row per scene and step."""
    seed_start: int
    """First seed in the recorder's consecutive synchronous episode batches."""


class KeyposeTraceEnv:
    def __init__(self, config: KeyposeTraceConfig):
        self.config = config
        self.stream = config.path.open("x")
        self.batch = 0
        self.step_index = 0

    def __getattr__(self, name):
        return getattr(self.config.env, name)

    def step(self, target):
        env = self.config.env
        target_tensor = torch.as_tensor(target)
        command, reached, position_error, rotation_error = keypose_command(
            env.current, target_tensor, env.gripper, env.config.control
        )
        values = {
            "target": target_tensor,
            "tcp_before": env.current,
            "previous_gripper": env.gripper,
            "recomputed_command": command,
            "reached": reached,
            "position_error_m": position_error,
            "rotation_error_rad": rotation_error,
        }
        values = {k: v.detach().cpu().tolist() for k, v in values.items()}
        result = env.step(target)
        done = np.asarray(result[2]) | np.asarray(result[3])
        if done.any() and not done.all():
            raise ValueError("Keypose trace requires synchronous episode batches")
        for slot in range(env.num_envs):
            row = {key: value[slot] for key, value in values.items()}
            row.update(
                seed=self.config.seed_start + self.batch * env.num_envs + slot,
                step=self.step_index,
                done=bool(done[slot]),
            )
            self.stream.write(json.dumps(row, allow_nan=False) + "\n")
        self.step_index += 1
        if done.all():
            self.batch += 1
            self.step_index = 0
            self.stream.flush()
        return result

    def finish(self):
        self.stream.close()