import warp as wp
import newton
COLOR_NAMES = ["red", "green", "blue"]
COLOR_RGB = np.array([[0.835, 0.369, 0.0], [0.0, 0.62, 0.451], [0.0, 0.447, 0.698]], dtype=np.float32)
TEMPLATES = ["grab the {} square", "get the {} one", "pick up the {} block"]
VOCAB = ["<pad>"] + sorted({w for t in TEMPLATES for w in t.format("x").split() if w != "x"} | set(COLOR_NAMES))
WORD_ID = {w: i for i, w in enumerate(VOCAB)}
L_TEXT = 5 # instruction length in words, padded
IMG = 64 # image side in pixels
MAX_STEP = 0.05 # largest claw move per step along each axis
N_BINS = 21 # bins per motion axis; the grip token has 2 values, open and closed
SIDE = 0.08 # side of a square
CHUTE_X = 0.15 # the chute opening spans 0 <= x < CHUTE_X
START = np.array([0.07, 0.9], dtype=np.float32) # the claw starts above the chute
T_MAX = 60 # step limit of an episode: a clean grab and delivery takes about 48
CATCH_WIDTH = 0.03 # catch probability exp(-(offset / CATCH_WIDTH)^2)
SLIP_BASE, SLIP_GAIN = 0.002, 0.01 # slip probability per carried step: SLIP_BASE + SLIP_GAIN (offset / 0.02)^2
def tokenize(color_idx, template_idx):
"""Word ids of one instruction, padded with 0 to L_TEXT words."""
words = TEMPLATES[template_idx].format(COLOR_NAMES[color_idx]).split()
return [WORD_ID[w] for w in words] + [0] * (L_TEXT - len(words))
TEXT_TABLE = np.array([[tokenize(c, t) for t in range(len(TEMPLATES))] for c in range(3)])
wp.config.log_level = wp.LOG_WARNING
wp.config.quiet = True
CONTROL_DT = 0.1 # seconds of physics per control step
SUBSTEPS = 16 # physics substeps per control step (even, so the double buffer ends where it started)
HALF = SIDE / 2
def render_torch(sq, claw, closed, device):
"""Front-view images (n, 3, IMG, IMG) of machines, drawn on the GPU from square and claw positions.
Args:
sq: (n, 3, 2) bottom-centers of the squares; x < 0 means the square is gone.
claw: (n, 2) claw tip positions.
closed: (n,) bool, claw closed.
"""
sq = torch.as_tensor(sq, device=device, dtype=torch.float32)
claw = torch.as_tensor(claw, device=device, dtype=torch.float32)
closed = torch.as_tensor(closed, device=device)
n = len(claw)
c = (torch.arange(IMG, device=device, dtype=torch.float32) + 0.5) / IMG
gx = c[None, None, :] # (1, 1, IMG) columns
gz = (1 - c)[None, :, None] # (1, IMG, 1) rows, z up
img = torch.full((n, 3, IMG, IMG), 0.86, device=device)
img[:, :, (gz < 0.02).expand(1, IMG, IMG)[0]] = 0.55
chute = ((gx < CHUTE_X) & (gz < 0.12)).expand(1, IMG, IMG)[0]
img[:, :, chute] = 0.3
rgb = torch.as_tensor(COLOR_RGB, device=device)
for k in range(3):
x = sq[:, k, 0, None, None]; z = sq[:, k, 1, None, None]
m = (torch.abs(gx - x) < HALF) & (gz >= z) & (gz < z + SIDE) # (n, IMG, IMG)
img = torch.where(m[:, None], rgb[k][None, :, None, None], img)
x = claw[:, 0, None, None]; z = claw[:, 1, None, None]
px = 1.0 / IMG
cable = (torch.abs(gx - x) < 0.6 * px) & (gz > z + 0.05)
body = (torch.abs(gx - x) < 4 * px) & (gz > z + 0.035) & (gz <= z + 0.05)
spread = torch.where(closed, 2.0, 4.0)[:, None, None] * px
prongs = (torch.abs(torch.abs(gx - x) - spread) < 0.6 * px) & (gz > z) & (gz <= z + 0.05)
m = cable | body | prongs
return torch.where(m[:, None], torch.tensor(0.12, device=device), img)
class ClawGrab:
"""A batch of n claw machines, simulated with Newton as parallel worlds on the GPU.
The three squares are rigid boxes (side SIDE) with gravity and contact against the floor and
each other. The claw is a kinematic point moved by the gantry. Grasping keeps the stochastic
rule of ClawGrab: a caught box is switched to a kinematic body that follows the claw, and on
release or slip it becomes dynamic again and falls. A box released over the chute is delivered
and removed from the machine. The public attributes and methods match ClawGrab, so the operator,
the token helpers and the training code work unchanged.
Args:
n: number of machines.
seed: seed of the layout and of the grasp rule.
slip: scale of the slip probability.
random_start: start the claw at a random position above the squares.
as_torch: observe() returns a CUDA tensor instead of a numpy array.
"""
def __init__(self, n, seed=0, slip=1.0, random_start=False, as_torch=False):
self.n, self.rng, self.slip, self.random_start, self.as_torch = n, np.random.default_rng(seed), slip, random_start, as_torch
self.device = "cuda" if torch.cuda.is_available() else "cpu"
world = newton.ModelBuilder()
box = newton.ModelBuilder.ShapeConfig(density=200.0, mu=0.6)
for k in range(3):
b = world.add_body(xform=wp.transform(p=wp.vec3(0.3 + 0.2 * k, 0.0, HALF), q=wp.quat_identity()), label=f"square{k}")
world.add_shape_box(b, hx=HALF, hy=HALF, hz=HALF, cfg=box)
builder = newton.ModelBuilder()
builder.replicate(world, n)
builder.add_ground_plane(cfg=newton.ModelBuilder.ShapeConfig(mu=0.6))
self.model = builder.finalize(device=self.device)
self.solver = newton.solvers.SolverXPBD(self.model, iterations=4)
self.state, self.next_state = self.model.state(), self.model.state()
self.control = self.model.control()
self.collision = newton.CollisionPipeline(self.model, rigid_contact_max=48 * n)
self.contacts = self.collision.contacts()
self.flags = np.full(3 * n, int(newton.BodyFlags.DYNAMIC), np.int32)
self.graph = None
self.claw = np.zeros((n, 2), np.float32)
self.closed = np.zeros(n, bool)
self.held = np.full(n, -1)
self.gone = np.zeros((n, 3), bool) # delivered squares, removed from the machine
self.offset = np.zeros(n, np.float32)
self.target = np.zeros(n, int)
self.template = np.zeros(n, int)
self.t = np.zeros(n, int)
self.misses = np.zeros(n, int)
self.slips = np.zeros(n, int)
self.drops = np.zeros(n, int)
self.wrong = np.zeros(n, bool)
self.sq = np.zeros((n, 3, 2), np.float32)
self._q = self.state.body_q.numpy().reshape(n, 3, 7)
self._touched = np.zeros((n, 3), bool) # boxes moved by hand this step
self.reset(np.ones(n, bool))
self._warm = False
# -- physics plumbing -------------------------------------------------------------------------
def _simulate(self):
"""Advance the physics by CONTROL_DT in SUBSTEPS substeps (captured as a CUDA graph)."""
dt = CONTROL_DT / SUBSTEPS
def advance():
for _ in range(SUBSTEPS):
self.state.clear_forces()
self.collision.collide(self.state, self.contacts)
self.solver.step(self.state, self.next_state, self.control, self.contacts, dt)
self.state, self.next_state = self.next_state, self.state
if self.device != "cuda" or not getattr(self, "_warm", True):
self._warm = True # first call compiles the kernels outside a capture
return advance()
if self.graph is None:
with wp.ScopedCapture() as capture:
advance()
self.graph = capture.graph
wp.capture_launch(self.graph)
def _push(self, flags_changed):
"""Write the host copy of the box poses to the GPU; zero the velocity of every box moved by hand."""
self.state.body_q.assign(self._q.reshape(-1, 7))
if self._touched.any():
qd = self.state.body_qd.numpy().reshape(self.n, 3, 6)
qd[self._touched] = 0.0
self.state.body_qd.assign(qd.reshape(-1, 6))
self._touched[:] = False
if flags_changed:
self.model.body_flags.assign(self.flags)
self.solver.notify_model_changed(newton.ModelFlags.BODY_PROPERTIES)
def _pull(self):
"""Read the box poses from the GPU and update sq (bottom-centers)."""
self._q = self.state.body_q.numpy().reshape(self.n, 3, 7)
self.sq[..., 0] = np.where(self.gone, -1.0, self._q[..., 0])
self.sq[..., 1] = np.where(self.gone, 0.0, self._q[..., 2] - HALF)
def _set_flag(self, i, k, kinematic):
"""Mark box k of machine i kinematic or dynamic; returns True if the flag changed."""
f = int(newton.BodyFlags.KINEMATIC if kinematic else newton.BodyFlags.DYNAMIC)
j = 3 * i + k
changed = self.flags[j] != f
self.flags[j] = f
return changed
# -- ClawGrab API -----------------------------------------------------------------------------
def reset(self, mask):
"""Start new episodes on the machines selected by the boolean array mask."""
self._pull()
changed = False
for i in np.flatnonzero(mask):
while True:
x = self.rng.uniform(0.25, 0.92, 3)
if np.abs(x[:, None] - x[None] + 2 * np.eye(3)).min() > 0.14:
break
self._q[i] = 0.0
self._q[i, :, 0], self._q[i, :, 2], self._q[i, :, 6] = x, HALF, 1.0
for k in range(3):
changed |= self._set_flag(i, k, False)
self._touched[i] = True
k = mask.sum()
self.gone[mask] = False
self.claw[mask] = START
if self.random_start:
self.claw[mask] = self.rng.uniform([0.2, 0.35], [0.95, 0.9], size=(k, 2))
self.closed[mask] = False
self.held[mask] = -1
self.target[mask] = self.rng.integers(3, size=k)
self.template[mask] = self.rng.integers(len(TEMPLATES), size=k)
for a in (self.t, self.misses, self.slips, self.drops):
a[mask] = 0
self.wrong[mask] = False
self._push(True)
self._pull()
def support(self):
"""Lowest z the claw tip can reach at its x, and the index of the square under it (-1 for the floor)."""
free = (np.arange(3)[None] != self.held[:, None]) & ~self.gone
under = free & (np.abs(self.sq[:, :, 0] - self.claw[:, None, 0]) < HALF)
top = np.where(under, self.sq[:, :, 1] + SIDE, -1.0)
k, z = top.argmax(1), top.max(1)
return np.where(z < 0, 0.02, z), np.where(z < 0, -1, k)
def observe(self):
"""Camera image and instruction of every machine; the image is drawn on the GPU."""
img = render_torch(self.sq, self.claw, self.closed, self.device)
if not self.as_torch:
img = img.cpu().numpy()
return img, TEXT_TABLE[self.target, self.template]
def goal(self):
"""Bottom-center of the named square on every machine, shape (n, 2)."""
return self.sq[np.arange(self.n), self.target]
def step(self, action):
"""Apply (dx, dz, grip) on every machine, then advance the physics by one control step.
Returns:
reward: 1 where the named square was delivered, else 0.
done: True where a square was delivered or the step limit was reached.
"""
d = np.clip(action[:, :2], -MAX_STEP, MAX_STEP)
close = action[:, 2] > 0.5
self.claw[:, 0] = np.clip(self.claw[:, 0] + d[:, 0], 0.03, 0.97)
floor, _ = self.support()
self.claw[:, 1] = np.clip(self.claw[:, 1] + d[:, 1], floor, 0.95)
holding = self.held >= 0
# closing an open claw on a square under it may catch the square
floor, k = self.support()
grab = close & ~self.closed & (k >= 0) & (self.claw[:, 1] - floor < 0.02)
g = np.flatnonzero(grab)
off = self.claw[g, 0] - self.sq[g, k[g], 0]
caught = self.rng.random(len(g)) < np.exp(-(off / CATCH_WIDTH) ** 2)
changed = False
for i, kk, o in zip(g[caught], k[g[caught]], off[caught]):
self.held[i], self.offset[i] = kk, o
changed |= self._set_flag(i, kk, True)
self._touched[i, kk] = True
self.misses[g[~caught]] += 1
# opening, or a slip, releases the held square
p_slip = self.slip * (SLIP_BASE + SLIP_GAIN * (self.offset / 0.02) ** 2)
slipped = holding & close & (self.rng.random(self.n) < p_slip) & (np.abs(d).sum(1) > 0)
drop = holding & (~close | slipped)
self.slips += slipped
delivered = np.zeros(self.n, bool)
dropped = self.held.copy()
for i in np.flatnonzero(drop):
j = self.held[i]
if self.claw[i, 0] - self.offset[i] < CHUTE_X:
delivered[i] = True
self.gone[i, j] = True
self._q[i, j, :3] = (-2.0, 0.0, HALF + 0.2 * j) # parked out of the machine
changed |= self._set_flag(i, j, True)
else:
self.drops[i] += ~slipped[i]
changed |= self._set_flag(i, j, False) # falls under gravity from where it hangs
self._touched[i, j] = True
self.held[i] = -1
# held squares hang from the prongs
h = np.flatnonzero(self.held >= 0)
self._q[h, self.held[h], 0] = self.claw[h, 0] - self.offset[h]
self._q[h, self.held[h], 1] = 0.0
self._q[h, self.held[h], 2] = self.claw[h, 1] - HALF
self._q[h, self.held[h], 3:] = (0.0, 0.0, 0.0, 1.0)
self._touched[h, self.held[h]] = True
self._push(changed)
self._simulate()
self._pull()
reward = (delivered & (dropped == self.target)).astype(np.float32)
self.wrong |= delivered & (dropped != self.target)
self.closed = close
self.t += 1
return reward, delivered | (self.t >= T_MAX)
def expert_action(env, rng, bias=(0.0, 0.04)):
"""Scripted operator who aligns the claw by eye.
Before each descent the operator picks an aim point to the right of the named square's center,
off by a random amount in the interval bias, and stops correcting x once above it. After a
missed catch it opens, rises and aims again. It carries the square at height 0.75 to the chute.
Args:
env: the ClawGrab batch.
rng: generator of the aiming error.
bias: interval of the aiming error.
Returns:
float array (n, 3) of actions (dx, dz, grip).
"""
if not hasattr(env, "aim") or len(env.aim) != env.n:
env.aim = np.full(env.n, np.nan, np.float32)
a = np.zeros((env.n, 3), np.float32)
x, z = env.claw[:, 0], env.claw[:, 1]
g = env.goal()
holding_target = env.held == env.target
holding_other = (env.held >= 0) & ~holding_target
free = env.held < 0
# carry: rise, then move over the chute, then open
up = holding_target & (z < 0.75)
a[up, 1] = MAX_STEP; a[up, 2] = 1
go = holding_target & ~up & (x >= CHUTE_X - 0.05)
a[go, 0] = -MAX_STEP; a[go, 2] = 1
# (opening over the chute: grip stays 0)
# a wrong square in the claw: open
# free claw that is closed: open and rise (the miss)
missed = free & env.closed
env.aim[missed] = np.nan
a[missed, 1] = MAX_STEP
# free and open: pick an aim point, align, descend, close
ready = free & ~env.closed
new = ready & np.isnan(env.aim)
env.aim[new] = rng.uniform(*bias, new.sum())
tx = g[:, 0] + env.aim
far = ready & (np.abs(tx - x) > 0.01)
a[far, 0] = np.clip(tx - x, -MAX_STEP, MAX_STEP)[far]
a[far, 1] = np.clip(0.6 - z, -MAX_STEP, MAX_STEP)[far]
top = g[:, 1] + SIDE
near = ready & ~far
a[near, 1] = np.clip(top - z, -MAX_STEP, MAX_STEP)[near]
a[near & (z - top < 0.02), 2] = 1
env.aim[env.held >= 0] = np.nan
return a
def to_tokens(a):
"""Tokens of actions a (n, 3): a bin index 0..N_BINS-1 for dx and dz, and the grip as 0 or 1."""
b = np.rint((np.clip(a[:, :2], -MAX_STEP, MAX_STEP) + MAX_STEP) / (2 * MAX_STEP) * (N_BINS - 1)).astype(int)
return np.concatenate([b, (a[:, 2:] > 0.5).astype(int)], 1)
def from_tokens(z):
"""Actions (n, 3) at the centers of the bins z."""
return np.concatenate([-MAX_STEP + z[:, :2] * (2 * MAX_STEP / (N_BINS - 1)), z[:, 2:]], 1).astype(np.float32)