File size: 3,127 Bytes
9d8d25c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""End-to-end RDT2-FM reference (CPU, fp32 by default), staged exactly like the TT port:

    host  preprocess:  cameras -> (392, 756) -> pixel_values (1512, 1176); prompt -> input_ids (L); mRoPE cos/sin
    VISION          :  pixel_values -> image embeds (378, 3584)
    PREFIX (VLM)    :  embed + scatter image embeds -> layers 0..12 + layer-13 K/V -> K, V (14, 1, 4, L, 128)
    EXPERT          :  5 x RDT forward (14 blocks) with the Euler update -> normalized action (1, 24, 20)
    host  postproc  :  UMI unnormalize -> action (24, 20)
"""
from __future__ import annotations

from typing import Dict, Optional, Sequence

import numpy as np
import torch

from .config import CONFIG, DEFAULT_DIRS
from .expert import ActionExpert, unnormalize_action
from .preprocess import mrope_cos_sin, preprocess, vision_geometry
from .vision import VisionTower
from .vlm import PrefixLM
from .weights import load_action_normalizer, load_expert_state_dict, load_vlm_index


class RDT2FMReference:
    def __init__(self, vlm_dir: Optional[str] = None, expert_dir: Optional[str] = None,
                 normalizer_dir: Optional[str] = None, processor_dir: Optional[str] = None,
                 dtype: torch.dtype = torch.float32, load_vision: bool = True, load_lm: bool = True):
        self.dtype = dtype
        self.processor_dir = processor_dir or DEFAULT_DIRS["processor"]
        self.index = load_vlm_index(vlm_dir)
        self.vision = VisionTower(self.index.load_prefix("visual."), dtype) if load_vision else None
        if load_vision:
            self.index.drop("visual.")
        self.lm = PrefixLM(self.index, CONFIG.lm.selected_layers, dtype=dtype) if load_lm else None
        self.expert = ActionExpert(load_expert_state_dict(expert_dir), dtype)
        self.norm = load_action_normalizer(normalizer_dir)

    def condition(self, inputs: Dict[str, torch.Tensor], taps: Optional[Dict[str, torch.Tensor]] = None):
        geom = vision_geometry(inputs["image_grid_thw"])
        img = self.vision.forward(inputs["pixel_values"], geom, taps)
        if taps is not None:
            taps["vis.image_embeds"] = img
        x = self.lm.embed(inputs["input_ids"], img)
        if taps is not None:
            taps["llm.inputs_embeds"] = x
        cos, sin = mrope_cos_sin(inputs["position_ids"])
        K, V = self.lm.forward(x, cos, sin, taps)
        return K, V

    @torch.no_grad()
    def __call__(self, images: Sequence[np.ndarray], instruction: str, state: np.ndarray, noise: torch.Tensor,
                 taps: Optional[Dict[str, torch.Tensor]] = None) -> Dict[str, torch.Tensor]:
        """images in model order (left_stereo, right_stereo), (384, 384, 3) uint8 each; state (20,); noise (1, 24, 20)."""
        inputs = preprocess(images, instruction, self.processor_dir)
        K, V = self.condition(inputs, taps)
        mask = inputs["attention_mask"].to(torch.bool)
        a = self.expert.sample(noise, torch.as_tensor(state, dtype=torch.float32), K, V, mask, taps)
        return dict(inputs=inputs, K=K, V=V, nsample=a, action=unnormalize_action(a, self.norm)[0])