| """ |
| Independent reproduction of AQM (Adaptive Quasimetric Mapping), ICML 2026 #23758. |
| |
| No official code / arXiv exists. Method reconstructed from the OpenReview abstract and |
| the authors' predecessor paper ProQ/PQP (arXiv:2506.18847): a time-to-reach quasimetric |
| (IQE + QRL-style loss) is learned from an offline dataset; AQM's novelties are |
| (1) a sparse keypoint cover built as a greedy approximation to a dominating-set problem, |
| (2) graph planning over those keypoints, |
| (3) zero-shot replanning by pruning edges whose observed traversal time exceeds a |
| time-to-reach budget derived from the quasimetric. |
| |
| Env: 2D continuous point-mass mazes (OGBench pointmaze-style layouts). The low-level |
| controller is a shared oracle waypoint-follower for ALL methods, isolating the |
| graph-level claims from policy learning quality. |
| """ |
| import numpy as np |
| import torch |
| import torch.nn as nn |
| import time |
| import heapq |
|
|
| |
| |
| |
| |
| def gen_maze(n_cells, seed, braid=0.35): |
| rng = np.random.default_rng(seed) |
| H = W = 2 * n_cells + 1 |
| g = np.ones((H, W), dtype=int) |
| def carve(r, c): |
| g[r, c] = 0 |
| dirs = [(0, 2), (0, -2), (2, 0), (-2, 0)] |
| rng.shuffle(dirs) |
| for dr, dc in dirs: |
| nr, nc = r + dr, c + dc |
| if 1 <= nr < H - 1 and 1 <= nc < W - 1 and g[nr, nc] == 1: |
| g[r + dr // 2, c + dc // 2] = 0 |
| carve(nr, nc) |
| import sys as _s |
| _s.setrecursionlimit(10000) |
| carve(1, 1) |
| |
| walls = [(r, c) for r in range(1, H - 1) for c in range(1, W - 1) |
| if g[r, c] == 1 and ((g[r - 1, c] == 0 and g[r + 1, c] == 0) or |
| (g[r, c - 1] == 0 and g[r, c + 1] == 0))] |
| rng.shuffle(walls) |
| for r, c in walls[:int(len(walls) * braid)]: |
| g[r, c] = 0 |
| return ["".join(str(x) for x in row) for row in g] |
|
|
| MAZES = { |
| "medium": gen_maze(4, seed=7), |
| "large": gen_maze(6, seed=11), |
| "giant": gen_maze(8, seed=13), |
| } |
| CELL = 1.0 |
|
|
|
|
| class Maze: |
| def __init__(self, name, extra_walls=()): |
| self.grid = np.array([[int(c) for c in row] for row in MAZES[name]]) |
| self.name = name |
| self.extra = set(extra_walls) |
|
|
| def blocked_cell(self, r, c): |
| if r < 0 or c < 0 or r >= self.grid.shape[0] or c >= self.grid.shape[1]: |
| return True |
| return self.grid[r, c] == 1 or (r, c) in self.extra |
|
|
| def blocked(self, xy): |
| return self.blocked_cell(int(xy[1] // CELL), int(xy[0] // CELL)) |
|
|
| def free_cells(self): |
| return [(r, c) for r in range(self.grid.shape[0]) |
| for c in range(self.grid.shape[1]) if not self.blocked_cell(r, c)] |
|
|
| def cell_center(self, rc): |
| return np.array([rc[1] + 0.5, rc[0] + 0.5]) * CELL |
|
|
| def step(self, pos, vel, dt=1.0, max_speed=0.25): |
| """Move with collision: sub-step and stop at walls.""" |
| v = np.clip(vel, -max_speed, max_speed) |
| p = pos.copy() |
| for _ in range(4): |
| q = p + v * dt / 4 |
| if not self.blocked(q): |
| p = q |
| else: |
| qx = p + np.array([v[0], 0.0]) * dt / 4 |
| qy = p + np.array([0.0, v[1]]) * dt / 4 |
| if not self.blocked(qx): |
| p = qx |
| elif not self.blocked(qy): |
| p = qy |
| return p |
|
|
| |
| def astar(self, start_rc, goal_rc): |
| def h(a, b): |
| return abs(a[0] - b[0]) + abs(a[1] - b[1]) |
| openq = [(h(start_rc, goal_rc), 0, start_rc, None)] |
| came, costs = {}, {start_rc: 0} |
| while openq: |
| _, g, cur, par = heapq.heappop(openq) |
| if cur in came: |
| continue |
| came[cur] = par |
| if cur == goal_rc: |
| path = [cur] |
| while came[path[-1]] is not None: |
| path.append(came[path[-1]]) |
| return path[::-1] |
| for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)): |
| nxt = (cur[0] + dr, cur[1] + dc) |
| if self.blocked_cell(*nxt) or nxt in came: |
| continue |
| ng = g + 1 |
| if ng < costs.get(nxt, 1e9): |
| costs[nxt] = ng |
| heapq.heappush(openq, (ng + h(nxt, goal_rc), ng, nxt, cur)) |
| return None |
|
|
|
|
| def traj_pairs(trajs, n_pairs, rng, max_gap=200): |
| """Sample (s_i, s_{i+k}) within trajectories: d(s_i, s_{i+k}) <= k (time-to-reach upper bound).""" |
| A, B, K = [], [], [] |
| for _ in range(n_pairs): |
| tr = trajs[rng.integers(len(trajs))] |
| if len(tr) < 3: |
| continue |
| i = rng.integers(0, len(tr) - 2) |
| j = rng.integers(i + 1, min(len(tr), i + max_gap)) |
| A.append(tr[i]); B.append(tr[j]); K.append(j - i) |
| return (np.array(A, dtype=np.float32), np.array(B, dtype=np.float32), |
| np.array(K, dtype=np.float32)) |
|
|
|
|
| def make_dataset(maze, n_traj=500, seed=0, noise=0.05): |
| """Offline dataset: noisy waypoint-following trajectories between random cells.""" |
| rng = np.random.default_rng(seed) |
| cells = maze.free_cells() |
| obs, nxt = [], [] |
| trajs = [] |
| for _ in range(n_traj): |
| a, b = rng.choice(len(cells), 2, replace=False) |
| path = maze.astar(cells[a], cells[b]) |
| if path is None or len(path) < 2: |
| continue |
| wps = [maze.cell_center(rc) for rc in path] |
| pos = wps[0] + rng.uniform(-0.2, 0.2, 2) |
| traj = [pos.copy()] |
| wi = 0 |
| for _ in range(60 * len(wps)): |
| tgt = wps[min(wi, len(wps) - 1)] |
| if np.linalg.norm(tgt - pos) < 0.3: |
| wi += 1 |
| if wi >= len(wps): |
| break |
| continue |
| v = tgt - pos |
| v = v / (np.linalg.norm(v) + 1e-8) * 0.25 + rng.normal(0, noise, 2) |
| newp = maze.step(pos, v) |
| obs.append(pos.copy()) |
| nxt.append(newp.copy()) |
| pos = newp |
| traj.append(pos.copy()) |
| trajs.append(np.array(traj)) |
| return np.array(obs, dtype=np.float32), np.array(nxt, dtype=np.float32), trajs |
|
|
|
|
| |
| class IQE(nn.Module): |
| """Interval Quasimetric Embedding (Wang & Isola 2022), maxmean reduction.""" |
|
|
| def __init__(self, in_dim=2, latent=64, groups=8, hidden=256): |
| super().__init__() |
| assert latent % groups == 0 |
| self.groups, self.k = groups, latent // groups |
| self.enc = nn.Sequential( |
| nn.Linear(in_dim, hidden), nn.ReLU(), |
| nn.Linear(hidden, hidden), nn.ReLU(), |
| nn.Linear(hidden, latent), |
| ) |
| self.alpha = nn.Parameter(torch.zeros(())) |
| self.scale = nn.Parameter(torch.zeros(())) |
|
|
| def dist(self, x, y): |
| zx, zy = self.enc(x), self.enc(y) |
| zx = zx.view(*zx.shape[:-1], self.groups, self.k) |
| zy = zy.view(*zy.shape[:-1], self.groups, self.k) |
| |
| d = torch.relu(zy - zx).sum(-1) |
| alpha = torch.sigmoid(self.alpha) |
| maxmean = alpha * d.max(-1).values + (1 - alpha) * d.mean(-1) |
| return maxmean * torch.exp(self.scale) |
|
|
|
|
| def train_quasimetric(obs, nxt, steps=4000, batch=1024, device="cpu", seed=0, |
| margin_target=1.0, verbose=True, trajs=None): |
| """QRL-style loss: 1-step transitions have d<=1; within-trajectory pairs give |
| multi-step upper bounds d(s_i, s_{i+k}) <= k; random pairs are pushed apart |
| under a Lagrangian so distances are maximal subject to consistency.""" |
| torch.manual_seed(seed) |
| rng = np.random.default_rng(seed) |
| model = IQE().to(device) |
| opt = torch.optim.Adam(model.parameters(), lr=3e-4) |
| lam = torch.zeros((), device=device, requires_grad=True) |
| opt_lam = torch.optim.Adam([lam], lr=1e-2) |
| O = torch.as_tensor(obs, device=device) |
| N = torch.as_tensor(nxt, device=device) |
| n = len(O) |
| if trajs is not None: |
| A, B, K = traj_pairs(trajs, 200000, rng) |
| A = torch.as_tensor(A, device=device); B = torch.as_tensor(B, device=device) |
| K = torch.as_tensor(K, device=device) |
| |
| |
| |
| margin = float(np.quantile(K.cpu().numpy(), 0.95)) * 1.5 |
| else: |
| margin = 200.0 |
| for it in range(steps): |
| i = torch.randint(0, n, (batch,), device=device) |
| j = torch.randint(0, n, (batch,), device=device) |
| d_loc = model.dist(O[i], N[i]) |
| viol = (torch.relu(d_loc - margin_target) ** 2).mean() |
| if trajs is not None: |
| m = torch.randint(0, len(A), (batch,), device=device) |
| d_multi = model.dist(A[m], B[m]) |
| viol = viol + (torch.relu((d_multi - K[m]) / K[m].clamp(min=1)) ** 2).mean() |
| d_glob = model.dist(O[i], O[j]) |
| glob = torch.relu(margin - d_glob).mean() / margin |
| loss = glob + torch.exp(lam.detach()) * viol |
| opt.zero_grad(); loss.backward(); opt.step() |
| lam_loss = -torch.exp(lam) * (viol.detach() - 0.05) |
| opt_lam.zero_grad(); lam_loss.backward(); opt_lam.step() |
| if verbose and (it + 1) % 1000 == 0: |
| print(f" [qm] step {it+1}: viol={viol.item():.4f} " |
| f"E[d_glob]={d_glob.mean().item():.2f} lam={lam.item():.2f}") |
| return model |
|
|
|
|
| @torch.no_grad() |
| def qdist(model, X, Y, device="cpu", bs=4096): |
| """Pairwise quasimetric d(X_i, Y_j) -> (len(X), len(Y)) matrix.""" |
| X = torch.as_tensor(X, dtype=torch.float32, device=device) |
| Y = torch.as_tensor(Y, dtype=torch.float32, device=device) |
| out = torch.empty(len(X), len(Y)) |
| for a in range(0, len(X), 256): |
| xa = X[a:a + 256].unsqueeze(1).expand(-1, len(Y), -1) |
| out[a:a + 256] = model.dist(xa, Y.unsqueeze(0).expand(xa.shape[0], -1, -1)).cpu() |
| return out.numpy() |
|
|
|
|
| |
| def greedy_dominating_set(D_sym, tau): |
| """Greedy set-cover approximation of the dominating set of the tau-ball graph. |
| |
| D_sym: (n, n) symmetrized quasimetric among candidate states. |
| Returns (keypoint indices, cover time, n_uncovered).""" |
| n = len(D_sym) |
| covered = np.zeros(n, dtype=bool) |
| cover_mask = D_sym <= tau |
| keypoints = [] |
| t0 = time.time() |
| gain = cover_mask.sum(1).astype(np.int64) |
| while not covered.all(): |
| i = int(np.argmax(gain)) |
| if gain[i] <= 0: |
| break |
| newly = cover_mask[i] & ~covered |
| keypoints.append(i) |
| covered |= cover_mask[i] |
| gain = (cover_mask & ~covered[None, :]).sum(1) |
| gain[keypoints] = -1 |
| return keypoints, time.time() - t0, int((~covered).sum()) |
|
|
|
|
| def ilp_dominating_set_lb(D_sym, tau, time_limit=10): |
| """LP relaxation lower bound of dominating set size (for approximation-quality check).""" |
| try: |
| from scipy.optimize import linprog |
| except ImportError: |
| return None |
| n = len(D_sym) |
| A = -(D_sym <= tau).astype(float).T |
| res = linprog(c=np.ones(n), A_ub=A, b_ub=-np.ones(n), bounds=[(0, 1)] * n, |
| method="highs") |
| return res.fun if res.success else None |
|
|
|
|
| |
| class AQMGraph: |
| def __init__(self, keypoints_xy, D_kk, edge_thresh, knn=4): |
| self.kp = keypoints_xy |
| self.D = D_kk |
| n = len(keypoints_xy) |
| keep = np.zeros((n, n), dtype=bool) |
| for i in range(n): |
| order = np.argsort(D_kk[i]) |
| for j in order[1:knn + 1]: |
| keep[i, int(j)] = keep[int(j), i] = True |
| keep[i] |= D_kk[i] <= edge_thresh |
| |
| |
| |
| Ds = np.maximum(D_kk, D_kk.T) |
| in_tree = [0] |
| best = Ds[0].copy(); best_from = np.zeros(n, dtype=int) |
| for _ in range(n - 1): |
| best[in_tree] = np.inf |
| j = int(np.argmin(best)) |
| if not np.isfinite(best[j]): |
| break |
| keep[best_from[j], j] = keep[j, best_from[j]] = True |
| in_tree.append(j) |
| upd = Ds[j] < best |
| best[upd] = Ds[j][upd]; best_from[upd] = j |
| self.edges = {i: [(j, D_kk[i, j]) for j in range(n) if j != i and keep[i, j]] |
| for i in range(n)} |
| self.pruned = set() |
|
|
| def n_edges(self): |
| return sum(len(v) for v in self.edges.values()) |
|
|
| def dijkstra(self, src, dst): |
| dist = {src: 0.0} |
| par = {} |
| pq = [(0.0, src)] |
| while pq: |
| d, u = heapq.heappop(pq) |
| if u == dst: |
| break |
| if d > dist.get(u, 1e18): |
| continue |
| for v, w in self.edges[u]: |
| if (u, v) in self.pruned: |
| continue |
| nd = d + w |
| if nd < dist.get(v, 1e18): |
| dist[v] = nd |
| par[v] = u |
| heapq.heappush(pq, (nd, v)) |
| if dst not in par and dst != src: |
| return None |
| path = [dst] |
| while path[-1] != src: |
| path.append(par[path[-1]]) |
| return path[::-1] |
|
|
|
|
| def navigate(maze, graph, model, start, goal, device="cpu", max_steps=2000, |
| replan=False, budget_beta=3.0, goal_radius=0.5, waypoint_radius=0.35): |
| """Follow keypoint plan with oracle local controller. |
| replan=True: prune current edge if time-on-edge exceeds beta * d_q(edge) and replan.""" |
| def nearest_kp(x, to=False): |
| d = qdist(model, graph.kp, x[None], device=device)[:, 0] if to else \ |
| qdist(model, x[None], graph.kp, device=device)[0] |
| return int(np.argmin(d)), float(np.min(d)) |
|
|
| def local_step(pos, tgt, horizon=6): |
| """Bounded-horizon local policy emulator (shared by ALL methods): a competent |
| goal-conditioned policy can reach nearby targets around local geometry, but |
| has no global knowledge. If the target needs a detour longer than `horizon` |
| cells, the policy makes no progress (returns straight-push attempt).""" |
| cur_rc = (int(pos[1]), int(pos[0])) |
| tgt_rc = (int(tgt[1]), int(tgt[0])) |
| if cur_rc != tgt_rc: |
| p = maze.astar(cur_rc, tgt_rc) |
| if p is not None and len(p) - 1 <= horizon: |
| sub = maze.cell_center(p[1]) if len(p) > 1 else tgt |
| |
| aim = tgt if len(p) <= 2 else sub |
| v = aim - pos |
| return v / (np.linalg.norm(v) + 1e-8) * 0.25 |
| |
| v = tgt - pos |
| return v / (np.linalg.norm(v) + 1e-8) * 0.25 |
|
|
| pos = start.copy() |
| k_cur, _ = nearest_kp(pos) |
| k_goal, _ = nearest_kp(goal, to=True) |
| path = graph.dijkstra(k_cur, k_goal) |
| if path is None: |
| return False, 0, 0 |
| leg = 1 if len(path) > 1 else 0 |
| t_edge, replans = 0, 0 |
| for t in range(max_steps): |
| if np.linalg.norm(pos - goal) < goal_radius: |
| return True, t, replans |
| tgt = graph.kp[path[leg]] if leg < len(path) else goal |
| if np.linalg.norm(tgt - pos) < waypoint_radius and leg < len(path): |
| leg += 1 |
| t_edge = 0 |
| continue |
| pos = maze.step(pos, local_step(pos, tgt)) |
| t_edge += 1 |
| if replan and leg < len(path) and leg >= 1: |
| d_edge = graph.D[path[leg - 1], path[leg]] |
| if t_edge > budget_beta * max(d_edge, 4.0): |
| graph.pruned.add((path[leg - 1], path[leg])) |
| replans += 1 |
| k_here, _ = nearest_kp(pos) |
| path = graph.dijkstra(k_here, k_goal) |
| if path is None: |
| return False, t, replans |
| leg = 1 if len(path) > 1 else 0 |
| t_edge = 0 |
| return False, max_steps, replans |
|
|
|
|
| |
| class DenseGraph(AQMGraph): |
| """One node per (subsampled) dataset state — prior graph-based approach scale.""" |
| pass |
|
|