File size: 4,178 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Several predictions of one observation from CVAE prior latents, and how they are combined.

Deployment normally decodes the prior mean (z = 0). Here each of K predictions
decodes its own z ~ N(0, I), batched as K copies of the observation. The rules
choose from or average the K chunks; their decisions use only the items that
will be executed (the first ``span``), then apply to the whole chunk.

- mean: every sample, equal weights.
- vote: per executed item the majority phase over samples (ties: lower class);
  samples agreeing with it on the most items are averaged.
- conf: weights proportional to each sample's mean maximum phase probability
  over the executed items.
- medoid: the sample with the smallest summed distance to the others over the
  executed items (positions in 0.1 m controller units, 6D and gripper as they
  are); executed as predicted, nothing averaged.
"""

from typing import Literal

import numpy as np
import torch

from lim.action_encoding import matrix_to_sixd, sixd_to_matrix

Aggregate = Literal["mean", "vote", "conf", "medoid"]
PHASE_RULES = ("vote", "conf")
"""Rules that read a trained phase head."""
POSITION_UNIT_M = 0.1


def predict_with_latents(agent, inputs, latents):
    """Policy outputs (N x Q x D, after denormalization) for a batch of N
    observations, row n decoding latents[n] instead of the prior mean."""
    modules = [m for name, m in agent.named_modules() if name.endswith("latent_out_proj")]
    if len(modules) != 1:
        raise ValueError("Expected the native CVAE latent projection exactly once")
    if latents.ndim != 2 or latents.shape[1] != modules[0].in_features:
        raise ValueError("Expected N x latent_dim prior samples")
    handle = modules[0].register_forward_pre_hook(lambda module, args: (latents,))
    try:
        with torch.inference_mode():
            return agent.get_action(dict(inputs)).cpu()
    finally:
        handle.remove()


def predict_samples(agent, observation, latents):
    """K predictions of one observation, row k decoding latents[k]; same path as
    batch-one inference otherwise."""
    inputs = {
        k: torch.as_tensor(v, device=latents.device)[None].repeat(len(latents), *[1] * np.ndim(v))
        for k, v in observation.items()
    }
    return predict_with_latents(agent, inputs, latents)


def mean_targets(chunks, weights):
    """Weighted mean of world targets (K x ... x 10); the 6D mean is re-orthonormalized."""
    w = weights.to(chunks.dtype).reshape(-1, *[1] * (chunks.ndim - 1))
    mean = (chunks * w).sum(0) / w.sum()
    rotation = matrix_to_sixd(sixd_to_matrix(mean[..., 3:9]))
    return torch.cat([mean[..., :3], rotation, mean[..., 9:]], -1)


def majority(phases):
    """Per-item majority class of K x n integer phases; ties go to the lower class."""
    classes = int(phases.max()) + 1
    counts = torch.nn.functional.one_hot(phases, classes).sum(0)
    return counts.argmax(-1)


def distances(items):
    """K x K summed L1 distance between samples' executed items (K x n x 10)."""
    scaled = torch.cat([items[..., :3] / POSITION_UNIT_M, items[..., 3:]], -1)
    return (scaled[:, None] - scaled[None]).abs().sum((-1, -2))


def decide(rule: Aggregate, items, phases=None, max_prob=None):
    """Sample weights (K) from the executed items alone; zero weight drops a sample.

    items: K x n x 10 world targets; phases: K x n argmax classes; max_prob:
    K x n maximum softmax phase probabilities.
    """
    count = len(items)
    if rule == "mean":
        return torch.ones(count)
    if rule == "vote":
        agree = (phases == majority(phases)[None]).sum(-1)
        return (agree == agree.max()).float()
    if rule == "conf":
        return max_prob.mean(-1)
    if rule == "medoid":
        weights = torch.zeros(count)
        weights[int(distances(items).sum(-1).argmin())] = 1.0
        return weights
    raise ValueError(f"Unknown aggregate rule {rule}")


def combine(rule: Aggregate, chunks, weights):
    """The chunk to execute: the medoid itself, or the weighted mean of the samples."""
    if rule == "medoid":
        return chunks[int(weights.argmax())].clone()
    return mean_targets(chunks, weights)