File size: 11,622 Bytes
e588892
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python
"""Run a bounded ValueCriticModel data/forward/backward/checkpoint smoke.

This deliberately uses one local RECAP episode and the tiny ``gemma_1m`` value
expert.  It validates the wiring and memory envelope; it is not a useful value
model training run and its checkpoint must not be used for a paper result.
"""

from __future__ import annotations

import argparse
import gc
import json
import logging
import os
from pathlib import Path

os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")

import torch
from omegaconf import OmegaConf

from rlinf.data.datasets.recap.value_model import ValueDataset
from rlinf.models.embodiment.value_model import get_model
from rlinf.models.embodiment.value_model.data_collator import ValueDataCollator
from rlinf.models.embodiment.value_model.processing import ValueProcessor


def _move(value, device):
    if isinstance(value, torch.Tensor):
        return value.to(device)
    if isinstance(value, dict):
        return {k: _move(v, device) for k, v in value.items()}
    return value


def _grad_summary(model: torch.nn.Module) -> tuple[int, float]:
    count = 0
    squared = 0.0
    for param in model.parameters():
        if param.grad is None:
            continue
        count += 1
        squared += float(param.grad.detach().float().pow(2).sum().item())
    return count, squared**0.5


def parse_args() -> argparse.Namespace:
    root = Path(os.environ.get("PROJECT_ROOT", "/data/myx/RL_post_train"))
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--dataset",
        type=Path,
        default=root / "datasets/recap_value_smoke/libero10_task0_train",
    )
    parser.add_argument(
        "--siglip", type=Path, default=root / "checkpoints/pretrained/siglip2-so400m-patch14-224"
    )
    parser.add_argument(
        "--gemma3", type=Path, default=root / "checkpoints/pretrained/gemma-3-270m"
    )
    parser.add_argument(
        "--tokenizer",
        type=Path,
        default=None,
        help="Tokenizer directory; defaults to --gemma3 (use SigLIP tokenizer for the random smoke fallback).",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=root / "checkpoints/value/value_smoke_gemma1m",
    )
    parser.add_argument("--critic-expert-variant", default="gemma_1m")
    parser.add_argument("--max-token-len", type=int, default=64)
    parser.add_argument("--freeze-vlm", action="store_true")
    parser.add_argument("--freeze-vision", action="store_true")
    parser.add_argument("--skip-backward", action="store_true")
    parser.add_argument(
        "--steps",
        type=int,
        default=10,
        help="Number of repeated steps on the same micro-batch (wiring smoke only).",
    )
    parser.add_argument("--device", default="cuda")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    if args.steps < 1:
        raise ValueError("--steps must be >= 1")
    logging.basicConfig(level=logging.INFO)
    for name, path in (("dataset", args.dataset), ("siglip", args.siglip), ("gemma3", args.gemma3)):
        if not path.exists():
            raise FileNotFoundError(f"{name} path does not exist: {path}")
    if not torch.cuda.is_available() and args.device.startswith("cuda"):
        raise RuntimeError("CUDA is required for this preflight; torch.cuda.is_available() is false")

    device = torch.device(args.device)
    torch.manual_seed(0)
    if device.type == "cuda":
        torch.cuda.manual_seed_all(0)
        torch.set_float32_matmul_precision("high")

    dataset = ValueDataset(
        dataset_path=str(args.dataset),
        robot_type="libero",
        model_type="pi05",
        action_horizon=10,
        action_dim=7,
        return_min=-779.0,
        return_max=0.0,
        normalize_to_minus_one_zero=True,
        tag="formula_v1",
    )
    processor = ValueProcessor(
        max_token_len=args.max_token_len,
        tokenizer_name_or_path=str(args.tokenizer or args.gemma3),
        do_augment=False,
    )
    collator = ValueDataCollator(
        processor=processor,
        max_length=args.max_token_len,
        train=False,
    )
    batch = collator([dataset[0]])
    observation = _move(batch["observation"], device)
    target_values = _move(batch["target_values"], device)
    print(
        "batch=",
        json.dumps(
            {
                "images": {k: list(v.shape) for k, v in observation["images"].items()},
                "image_masks": {k: list(v.shape) for k, v in observation["image_masks"].items()},
                "tokens": list(observation["tokenized_prompt"].shape),
                "target_values": target_values.detach().cpu().tolist(),
            },
            sort_keys=True,
        ),
        flush=True,
    )

    cfg = OmegaConf.create(
        {
            "precision": "bf16",
            "critic_expert_variant": args.critic_expert_variant,
            "num_bins": 201,
            "v_min": -1.0,
            "v_max": 0.0,
            "value_dropout": 0.0,
            "action_dim": 7,
            "action_horizon": 10,
            "max_token_len": args.max_token_len,
            "siglip_path": str(args.siglip),
            "gemma3_path": str(args.gemma3),
            "freeze_vlm": bool(args.freeze_vlm),
            "freeze_vision_encoder": bool(args.freeze_vision),
            "train_expert_only": bool(args.freeze_vlm),
            "forward_mode": "vla",
            "stop_gradient_to_vlm": bool(args.freeze_vlm),
        }
    )
    print(
        "config=",
        json.dumps(OmegaConf.to_container(cfg, resolve=True), sort_keys=True),
        flush=True,
    )

    print("constructing model", flush=True)
    model = get_model(cfg)
    total_params = sum(p.numel() for p in model.parameters())
    trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
    print(
        f"params total={total_params} trainable={trainable_params} "
        f"cpu_bytes~={sum(p.numel() * p.element_size() for p in model.parameters())}",
        flush=True,
    )
    model = model.to(device)
    model.train(not args.skip_backward)
    if device.type == "cuda":
        torch.cuda.reset_peak_memory_stats(device)

    reference_prediction = None
    optimizer = None
    if not args.skip_backward:
        optimizer = torch.optim.AdamW(
            [p for p in model.parameters() if p.requires_grad], lr=1e-4
        )

    last_grad_count = 0
    last_grad_norm = 0.0
    print(f"pipeline_steps={args.steps}", flush=True)
    for step in range(args.steps):
        if optimizer is not None:
            optimizer.zero_grad(set_to_none=True)
        output = model(observation=observation, target_values=target_values)
        if output.loss is None or not torch.isfinite(output.loss).all():
            raise RuntimeError(f"non-finite value loss at step {step}: {output.loss}")
        if not torch.isfinite(output.predicted_values).all():
            raise RuntimeError(
                f"non-finite predicted values at step {step}: {output.predicted_values}"
            )
        if optimizer is not None:
            output.loss.backward()
            last_grad_count, last_grad_norm = _grad_summary(model)
            if last_grad_count == 0 or not torch.isfinite(torch.tensor(last_grad_norm)):
                raise RuntimeError(
                    f"no finite gradients at step {step}: "
                    f"count={last_grad_count}, norm={last_grad_norm}"
                )
            optimizer.step()
        if step in (0, args.steps - 1):
            print(
                "step_result=",
                json.dumps(
                    {
                        "step": step + 1,
                        "loss": float(output.loss.detach().float().cpu()),
                        "predicted_values": output.predicted_values.detach()
                        .float()
                        .cpu()
                        .tolist(),
                        "logits_shape": list(output.logits.shape),
                        "mae": None
                        if output.mae is None
                        else float(output.mae.detach().float().cpu()),
                    },
                    sort_keys=True,
                ),
                flush=True,
            )

    if optimizer is not None:
        print(
            f"backward_result=grad_tensors:{last_grad_count},"
            f"grad_norm:{last_grad_norm:.6f}",
            flush=True,
        )
        # Evaluate once after the update.  The reload check below compares
        # against this post-update value (rather than the pre-update forward
        # value), making checkpoint restoration an actual numerical check.
        model.eval()
        with torch.no_grad():
            reference_prediction = model(
                observation=observation, target_values=None
            ).predicted_values.detach().cpu()
        model.train()

    # Do not retain the last autograd graph while constructing the fresh model
    # below; keeping it alive would unnecessarily raise the reload peak.
    if "output" in locals():
        del output

    args.output.mkdir(parents=True, exist_ok=True)
    state_dir = args.output / "model_state_dict"
    state_dir.mkdir(parents=True, exist_ok=True)
    full_weights = state_dir / "full_weights.pt"
    state_cpu = {k: v.detach().cpu() for k, v in model.state_dict().items()}
    torch.save(state_cpu, full_weights)
    (args.output / "config.json").write_text(
        json.dumps(OmegaConf.to_container(cfg, resolve=True), indent=2, sort_keys=True) + "\n"
    )
    print(f"saved_checkpoint={full_weights} bytes={full_weights.stat().st_size}", flush=True)

    # A fresh model verifies that the exact checkpoint format can be loaded.
    if device.type == "cuda":
        model = model.cpu()
        torch.cuda.empty_cache()
    if not args.skip_backward:
        del optimizer
    del model
    gc.collect()
    if device.type == "cuda":
        torch.cuda.empty_cache()
    print("reloading model", flush=True)
    reloaded = get_model(cfg)
    missing, unexpected = reloaded.load_state_dict(torch.load(full_weights, map_location="cpu", weights_only=False), strict=False)
    if missing or unexpected:
        raise RuntimeError(f"checkpoint mismatch: missing={missing}, unexpected={unexpected}")
    reloaded = reloaded.to(device).eval()
    with torch.no_grad():
        reloaded_output = reloaded(observation=observation, target_values=None)
    if not torch.isfinite(reloaded_output.predicted_values).all():
        raise RuntimeError("reloaded model produced non-finite prediction")
    if reference_prediction is not None:
        reloaded_cpu = reloaded_output.predicted_values.detach().float().cpu()
        if not torch.allclose(reloaded_cpu, reference_prediction.float(), atol=1e-5, rtol=1e-4):
            raise RuntimeError(
                "checkpoint reload prediction differs from post-update reference: "
                f"reference={reference_prediction.tolist()} reload={reloaded_cpu.tolist()}"
            )
    print(
        "reload_result=",
        json.dumps(
            {"predicted_values": reloaded_output.predicted_values.detach().float().cpu().tolist()},
            sort_keys=True,
        ),
        flush=True,
    )
    if device.type == "cuda":
        print(
            f"cuda_peak_allocated={torch.cuda.max_memory_allocated(device)} "
            f"cuda_peak_reserved={torch.cuda.max_memory_reserved(device)}",
            flush=True,
        )
    print("VALUE_PREFLIGHT_PASS", flush=True)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())