Download fair-comparison/extract-train-v1/code/lim/chunk_ensemble.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 7.45 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/extract-train-v1/code/lim/chunk_ensemble.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/extract-train-v1/code/lim/chunk_ensemble.py
-
curl -L -o chunk_ensemble.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/extract-train-v1/code/lim/chunk_ensemble.py
7.45 kB
| """Several separately trained models predicting one observation, and how their chunks combine. | |
| Phase information comes from a boundary probe fitted on a frozen model's | |
| decoder features (experiments/fair-comparison/fit_phase_probe.py), so the | |
| members' actions are exactly their checkpoints'. Boundary k (1-6) of an item | |
| means its time is at or past the start of StackCube primitive k, where 6 is | |
| the done class (past the demonstration's end); being past k + 1 implies being | |
| past k. Each boundary's transition is read by lim.chunk_done's suffix rule and | |
| transitions are then made non-decreasing (a later boundary cannot be crossed | |
| before an earlier one), so every member's phase sequence is monotone. | |
| Rules combine the members' executed items (the first ``span``), K x n x 10 | |
| world targets: | |
| - mean: equal-weight average (6D re-orthonormalized, gripper averaged). | |
| - medoid: the member closest to the others (lim.chunk_samples distance), as is. | |
| - mode: members linked when their executed positions are on average closer | |
| than MODE_RADIUS_M and every executed gripper sign agrees; the largest | |
| single-linkage group is averaged (ties: the group nearer the others). | |
| - phase: consensus transitions are the lower median of the members' (still | |
| monotone); each executed item takes the consensus phase and averages, over | |
| the members that have that phase among their executed items, each member's | |
| own items of that phase; with none, the item falls back to the plain mean. | |
| - split: exactly two members; the first member's poses with the second | |
| member's gripper values (pose and gripper from separately trained models). | |
| """ | |
| from contextlib import contextmanager | |
| from typing import Literal | |
| import torch | |
| from torch import nn | |
| from lim.chunk_done import done_items | |
| from lim.chunk_samples import combine, decide, mean_targets | |
| EnsembleRule = Literal["mean", "medoid", "mode", "phase", "split"] | |
| BOUNDARIES = 6 | |
| MODE_RADIUS_M = 0.010 | |
| """Fixed before any ensemble run: 10 mm, about the seeds' median spread before success.""" | |
| class BoundaryProbe(nn.Module): | |
| """One hidden layer: a linear probe of the frozen features underfits (held-out | |
| phase accuracy 91.8% at 10 epochs, 95.0% at 60 (95.2% at lr 3e-3); this probe 96.0%, seed 100).""" | |
| def __init__(self, features=256, hidden=256): | |
| super().__init__() | |
| self.net = nn.Sequential(nn.Linear(features, hidden), nn.GELU(), nn.Linear(hidden, BOUNDARIES)) | |
| def forward(self, features): | |
| return self.net(features) | |
| def decoder_head(agent): | |
| """The outermost module the native decoder calls as its action head.""" | |
| heads = [(name, m) for name, m in agent.named_modules() if name.endswith("action_head")] | |
| if not heads: | |
| raise ValueError("No ACT action head found") | |
| return min(heads, key=lambda pair: len(pair[0]))[1] | |
| def decoder_features(agent): | |
| """Yield a list that receives the decoder features (batch x Q x hidden) of each forward.""" | |
| captured = [] | |
| handle = decoder_head(agent).register_forward_pre_hook( | |
| lambda module, args: captured.append(args[0].detach()) | |
| ) | |
| try: | |
| yield captured | |
| finally: | |
| handle.remove() | |
| def boundary_labels(phases): | |
| """Integer phases 0-6 (... x Q) -> float labels (... x Q x 6), 1 where past boundary k.""" | |
| return (phases[..., None] >= torch.arange(1, BOUNDARIES + 1, device=phases.device)).float() | |
| def transitions(logits): | |
| """Q x 6 boundary logits -> 6 non-decreasing item indices where each boundary is crossed | |
| (Q if not within the chunk).""" | |
| if logits.ndim != 2 or logits.shape[1] != BOUNDARIES: | |
| raise ValueError("Expected items x six boundary logits") | |
| raw = torch.tensor([done_items(logits[:, k]) for k in range(BOUNDARIES)]) | |
| # A later boundary crossed at item t means every earlier one is crossed by t. | |
| return raw.flip(0).cummin(0).values.flip(0) | |
| def phases_from(transitions, items): | |
| """Phase (0-6) of items 0..items-1 from monotone transitions.""" | |
| index = torch.arange(items) | |
| return (transitions[None, :] <= index[:, None]).sum(-1) | |
| def consensus(member_transitions): | |
| """Lower median over members of each boundary's transition; monotone when theirs are.""" | |
| ordered = member_transitions.sort(0).values | |
| return ordered[(len(ordered) - 1) // 2] | |
| def mode_weights(items): | |
| """Largest single-linkage group of members (MODE_RADIUS_M, equal gripper signs).""" | |
| count = len(items) | |
| distance = (items[:, None, :, :3] - items[None, :, :, :3]).norm(dim=-1).mean(-1) | |
| close = items[..., 9] < 0 | |
| same = (close[:, None] == close[None]).all(-1) | |
| linked = (distance < MODE_RADIUS_M) & same | |
| parent = list(range(count)) | |
| def find(i): | |
| while parent[i] != i: | |
| parent[i] = parent[parent[i]] | |
| i = parent[i] | |
| return i | |
| for a in range(count): | |
| for b in range(a + 1, count): | |
| if linked[a, b]: | |
| parent[find(a)] = find(b) | |
| roots = torch.tensor([find(i) for i in range(count)]) | |
| groups = [roots == r for r in roots.unique()] | |
| size = max(int(g.sum()) for g in groups) | |
| largest = [g for g in groups if int(g.sum()) == size] | |
| nearness = distance.sum(-1) | |
| group = min(largest, key=lambda g: float(nearness[g].mean())) | |
| return group.float() | |
| def phase_combine(items, member_transitions): | |
| """The phase rule; returns the combined items, consensus transitions and fallback count.""" | |
| count, n = items.shape[:2] | |
| agreed = consensus(member_transitions) | |
| target = phases_from(agreed, n) | |
| own = torch.stack([phases_from(t, n) for t in member_transitions]) | |
| out, fallback, used = [], 0, [] | |
| for i in range(n): | |
| estimates = [] | |
| for m in range(count): | |
| mine = own[m] == target[i] | |
| if mine.any(): | |
| estimates.append(mean_targets(items[m, mine], torch.ones(int(mine.sum())))) | |
| used.append(len(estimates)) | |
| if estimates: | |
| out.append(mean_targets(torch.stack(estimates), torch.ones(len(estimates)))) | |
| else: | |
| fallback += 1 | |
| out.append(mean_targets(items[:, i], torch.ones(count))) | |
| return torch.stack(out), agreed, fallback, used | |
| def combine_members(rule: EnsembleRule, items, member_transitions=None): | |
| """The executed items (n x 10) the rule forms, and what it decided.""" | |
| if items.ndim != 3 or items.shape[-1] != 10: | |
| raise ValueError("Expected members x items x 10 world targets") | |
| if rule == "phase": | |
| if member_transitions is None: | |
| raise ValueError("The phase rule needs every member's boundary transitions") | |
| combined, agreed, fallback, used = phase_combine(items, member_transitions) | |
| return combined, {"consensus": agreed.tolist(), "fallback_items": fallback, "members_per_item": used} | |
| if rule == "split": | |
| if len(items) != 2: | |
| raise ValueError("The split rule takes poses from one member and the gripper from another") | |
| return torch.cat([items[0, :, :-1], items[1, :, -1:]], dim=-1), {"pose_member": 0, "gripper_member": 1} | |
| if rule == "mean": | |
| weights = torch.ones(len(items)) | |
| elif rule == "medoid": | |
| weights = decide("medoid", items) | |
| elif rule == "mode": | |
| weights = mode_weights(items) | |
| else: | |
| raise ValueError(f"Unknown ensemble rule {rule}") | |
| return combine("medoid" if rule == "medoid" else "mean", items, weights), {"weights": weights.tolist()} | |