File size: 10,132 Bytes
36b714d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
"""Reusable official base-policy loading for local Phase 4 interface checks.

Only construction/loading changes: parameters are constructed on meta and loaded
in the requested dtype on CPU before official device placement. The upstream
inference implementation, action transform, and websocket protocol are retained.
This is a base checkpoint, not a RoboTwin-finetuned evaluation checkpoint.
"""

import contextlib
import hashlib
import json
import os
from pathlib import Path
import sys
import threading


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_UPSTREAM = ROOT / "third_party/lingbot-vla-v2"
_CONSTRUCTION_LOCK = threading.RLock()


@contextlib.contextmanager
def upstream_working_directory(path):
    previous = Path.cwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(previous)


def prepare_base_runtime(base_path, qwen_path, norm_stats_path, runtime_dir, upstream=DEFAULT_UPSTREAM):
    """Build the directory topology expected by the unchanged official loader."""
    import yaml

    base_path = Path(base_path).resolve()
    qwen_path = Path(qwen_path).resolve()
    norm_stats_path = Path(norm_stats_path).resolve()
    runtime_dir = Path(runtime_dir).resolve()
    upstream = Path(upstream).resolve()
    index_path = base_path / "model.safetensors.index.json"
    index = json.loads(index_path.read_text())
    if not index.get("weight_map"):
        raise ValueError("Checkpoint index has no weight_map")
    shard_names = sorted(set(index["weight_map"].values()))
    if any(Path(name).name != name or not name.endswith(".safetensors") for name in shard_names):
        raise ValueError("Expected plain safetensors shard filenames in checkpoint index")
    for name in shard_names:
        if not (base_path / name).is_file():
            raise FileNotFoundError(base_path / name)
    if not (qwen_path / "config.json").is_file() or not norm_stats_path.is_file():
        raise FileNotFoundError("Qwen config and normalization statistics must exist locally")
    # Fused MoE weights contain 3D experts.*_proj; eager uses experts.N.*.weight.
    eager_keys = [key for key in index["weight_map"] if ".experts." in key and key.endswith(".weight")]
    fused_keys = [key for key in index["weight_map"] if ".experts." in key and key.endswith((".gate_proj", ".up_proj", ".down_proj"))]
    if eager_keys or not fused_keys:
        raise ValueError("This base loader expects the released fused-MoE checkpoint; no automatic key conversion is performed")
    cfg = yaml.safe_load((upstream / "configs/vla/robotwin/robotwin.yaml").read_text())
    if cfg["model"].get("moe_implementation") != "fused":
        raise ValueError("Official runtime configuration must retain fused MoE for these weights")
    cfg["model"]["model_path"] = str(base_path)
    cfg["model"]["tokenizer_path"] = str(qwen_path)
    # The training argument parser serializes these dict-like values as strings.
    for key in ("joints", "norm_type"):
        cfg["data"][key] = [str(value) for value in cfg["data"][key]]
    cfg["data"]["norm_stats_file"] = str(norm_stats_path)
    cfg["data"]["img_size"] = 256
    cfg["train"]["use_compile"] = False
    hf_checkpoint = runtime_dir / "checkpoints/global_step_0/hf_ckpt"
    hf_checkpoint.mkdir(parents=True, exist_ok=True)
    for name in shard_names + [index_path.name]:
        target = base_path / name
        link = hf_checkpoint / name
        if link.exists() or link.is_symlink():
            if not link.is_symlink() or link.resolve() != target:
                raise FileExistsError(f"Runtime checkpoint entry conflicts with requested source: {link}")
        else:
            link.symlink_to(target)
    configuration_path = runtime_dir / "lingbotvla_cli.yaml"
    configuration_text = yaml.safe_dump(cfg, sort_keys=False)
    if configuration_path.exists() and configuration_path.read_text() != configuration_text:
        raise FileExistsError(f"Use a fresh runtime directory for changed configuration: {runtime_dir}")
    configuration_path.write_text(configuration_text)
    provenance = {"base_path": str(base_path), "qwen_path": str(qwen_path),
        "norm_stats_path": str(norm_stats_path), "upstream": str(upstream),
        "checkpoint_index_sha256": hashlib.sha256(index_path.read_bytes()).hexdigest(),
        "checkpoint_tensor_count": len(index["weight_map"]), "checkpoint_shard_count": len(shard_names),
        "checkpoint_expert_layout": "fused", "fused_expert_tensor_count": len(fused_keys),
        "base_checkpoint_only": True, "robotwin_finetuning_performed": False}
    (runtime_dir / "runtime_source.json").write_text(json.dumps(provenance, indent=2) + "\n")
    return hf_checkpoint, provenance


def streaming_server_class(upstream=DEFAULT_UPSTREAM):
    """Return a subclass with the official constructor, infer, and reset interface."""
    import torch
    from accelerate import init_empty_weights
    from safetensors import safe_open

    upstream = Path(upstream).resolve()
    if str(upstream) not in sys.path:
        sys.path.insert(0, str(upstream))
    import deploy.lingbot_vla_v2_policy as official

    class StreamingBaseServer(official.LingbotVLAv2Server):
        def __init__(self, *args, **kwargs):
            # Official use_bf16 is positional argument 6, default True.
            use_bf16 = kwargs.get("use_bf16", args[6] if len(args) > 6 else True)
            self._checkpoint_dtype = torch.bfloat16 if use_bf16 else torch.float32
            with upstream_working_directory(upstream):
                super().__init__(*args, **kwargs)

        def load_vla(self, path_to_pi_model):
            with _CONSTRUCTION_LOCK, upstream_working_directory(upstream):
                original = official.LingBotVlaV2InferencePolicy

                def empty_constructor(*args, **kwargs):
                    # Keep initialized buffers on CPU. Meta is only for parameters;
                    # putting nonpersistent rotary buffers on meta loses their values.
                    with init_empty_weights(include_buffers=False):
                        return original(*args, **kwargs)

                official.LingBotVlaV2InferencePolicy = empty_constructor
                try:
                    return super().load_vla(path_to_pi_model)
                finally:
                    official.LingBotVlaV2InferencePolicy = original

        def load_model_weights(self, path_to_pi_model, strict=True):
            if not strict:
                raise ValueError("The base-policy wrapper requires strict checkpoint loading")
            path = Path(path_to_pi_model)
            index = json.loads((path / "model.safetensors.index.json").read_text())
            expected = self.vla.state_dict()
            index_keys = set(index["weight_map"])
            if set(expected) != index_keys:
                missing = sorted(set(expected) - index_keys)
                unexpected = sorted(index_keys - set(expected))
                raise ValueError(f"Checkpoint/model key mismatch before tensor loading; missing={missing[:20]}, unexpected={unexpected[:20]}")
            tensors = {}
            for name in sorted(set(index["weight_map"].values())):
                with safe_open(path / name, framework="pt", device="cpu") as shard:
                    for key in shard.keys():
                        if key in tensors:
                            raise ValueError(f"Duplicate checkpoint key: {key}")
                        if key not in expected or index["weight_map"].get(key) != name:
                            raise ValueError(f"Unexpected checkpoint key/shard assignment: {key} in {name}")
                        tensor = shard.get_tensor(key)
                        if tensor.shape != expected[key].shape:
                            raise ValueError(f"Checkpoint shape mismatch: {key}, {tensor.shape} != {expected[key].shape}")
                        tensors[key] = tensor.to(self._checkpoint_dtype) if tensor.is_floating_point() else tensor
                print("Loaded shard", name, flush=True)
            result = self.vla.load_state_dict(tensors, strict=True, assign=True)
            if result.missing_keys or result.unexpected_keys:
                raise ValueError(f"Strict checkpoint load failed: {result}")
            remaining_meta = [name for name, value in list(self.vla.named_parameters()) + list(self.vla.named_buffers()) if value.is_meta]
            if remaining_meta:
                raise ValueError(f"Uninitialized meta tensors after strict loading: {remaining_meta[:20]}")
            self.loaded_parameter_count = sum(param.numel() for param in self.vla.parameters())
            self.loaded_tensor_count = len(tensors)
            print("Strict load complete; parameters", self.loaded_parameter_count, "tensors", self.loaded_tensor_count, flush=True)

        def reset(self, robo_name, path_to_pi_model=None):
            # Upstream reset resolves configs/robot_configs relative to cwd.
            with upstream_working_directory(upstream):
                return super().reset(robo_name, path_to_pi_model)

    return StreamingBaseServer


def load_base_policy(base_path, qwen_path, norm_stats_path, runtime_dir,
        upstream=DEFAULT_UPSTREAM, use_bf16=True, use_compile=False,
        use_length=50, chunk_ret=True, robo_name="robotwin"):
    """Strictly load and reset the official policy; `.infer()` stays upstream's."""
    qwen_path = Path(qwen_path).resolve()
    norm_stats_path = Path(norm_stats_path).resolve()
    os.environ["QWEN3VL_PATH"] = str(qwen_path)
    os.environ.setdefault("HF_HUB_OFFLINE", "1")
    os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
    checkpoint, provenance = prepare_base_runtime(base_path, qwen_path,
        norm_stats_path, runtime_dir, upstream=upstream)
    server_type = streaming_server_class(upstream)
    policy = server_type(path_to_pi_model=str(checkpoint), robot_norm_path=str(norm_stats_path),
        use_bf16=use_bf16, use_fp32=not use_bf16, use_compile=use_compile,
        use_length=use_length, chunk_ret=chunk_ret)
    policy.reset(robo_name)
    policy.phase4_source = provenance
    return policy