File size: 18,877 Bytes
5024339
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
"""Single-round LiveWorld inference with the Wan camcontrol PanoData-v4 I/O.

Model, CFG, scheduler and event behavior come from --system-config.
--num_frames counts the entire saved clip, including the preserved first frame.
"""
from __future__ import annotations

import argparse
import copy
import gc
import json
import os
from pathlib import Path
import sys
import shutil
import tempfile

import numpy as np
import yaml

ROOT = Path(__file__).resolve().parents[1]
DATA_ROOT = Path('/home/zhangzhilu/shared/datasets/Pano-World/PanoData-v4')


def sample_name(dataset, index):
    sample_dir = Path(dataset.data[index]['video']).parent
    return '_'.join(sample_dir.parts[-3:])


def remap_camera_intrinsics(points, c2w, old_k, new_k):
    """Keep the reconstructed depths and source pixels with calibrated rays."""
    camera = (points - c2w[:3, 3]) @ c2w[:3, :3]
    calibrated = camera @ (np.linalg.inv(new_k) @ old_k).T
    return (calibrated @ c2w[:3, :3].T + c2w[:3, 3]).astype(np.float32)


def build_parser():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--dataset_base_path', type=Path, default=DATA_ROOT)
    p.add_argument('--dataset_metadata_path', type=Path, default=Path('test.txt'))
    p.add_argument('--dataset_prompt_path', type=Path, default=Path('perspective_prompts.jsonl'))
    p.add_argument('--system-config', type=Path, default=ROOT / 'configs/infer_system_config_local_14B.yaml')
    p.add_argument('--model_root', type=Path, default=None, help='Model bundle root, e.g. ./ckpt; overrides all seven model locations.')
    p.add_argument('--checkpoint', '--lora_checkpoint', dest='checkpoint', type=Path, default=None,
                   help='LiveWorld LoRA training checkpoint; defaults to MODEL_ROOT/LiveWorld/ckpts/lora/model.pt.')
    p.add_argument('--state_adapter_checkpoint', type=Path, default=None,
                   help='State Adapter training checkpoint; defaults to MODEL_ROOT/LiveWorld/ckpts/state_adapter/model.pt.')
    p.add_argument('--wan_model_path', type=Path, default=None)
    p.add_argument('--qwen_model_path', type=Path, default=None)
    p.add_argument('--sam3_model_path', type=Path, default=None)
    p.add_argument('--stream3r_model_path', type=Path, default=None)
    p.add_argument('--dinov3_model_path', type=Path, default=None)
    p.add_argument('--output_path', type=Path, default=ROOT / 'outputs_panodata/LiveWorld-K1')
    p.add_argument('--work_path', type=Path, default=None)
    p.add_argument('--max_samples', type=int, default=3)
    p.add_argument('--num_shards', type=int, default=1)
    p.add_argument('--shard_rank', type=int, default=0)
    p.add_argument('--perspective_num_frames', type=int, choices=[1], default=1)
    p.add_argument('--num_frames', type=int, default=81)
    p.add_argument('--seed', type=int, default=None, help='Default: LiveWorld system config seed.')
    p.add_argument('--device', default='cuda:0')
    p.add_argument('--fps', type=float, default=16)
    p.add_argument('--quality', type=int, default=5)
    p.add_argument('--camera_preload_workers', type=int, default=8)
    p.add_argument('--camera_translation_scale', type=float, default=1.0,
                   help='Explicit relative camera translation scale; no future RGB/depth calibration.')
    p.add_argument('--preserve_input_frames', action=argparse.BooleanOptionalAction, default=True)
    p.add_argument('--keep_work', action='store_true', help='Retain intermediate outputs and full single-round postprocessing.')
    p.add_argument('--dry_run', action='store_true', help='Prepare/validate inputs without loading GPU models.')
    # Same bounded I/O interface as the reference script; imported after path setup.
    return p


def load_runtime_system(args, parser):
    """Resolve portable model paths without editing the checked-in train YAML."""
    system = yaml.safe_load(args.system_config.read_text())
    base = args.model_root.expanduser().resolve() if args.model_root is not None else None
    def choose(explicit, relative, current):
        if explicit is not None:
            return str(explicit.expanduser().absolute())
        return str(base / relative) if base is not None else current
    observer = system['observer']
    auxiliary = system.setdefault('auxiliary', {})
    observer['lora_path'] = choose(args.checkpoint, 'LiveWorld/ckpts/lora/model.pt', observer.get('lora_path'))
    observer['sp_path'] = choose(args.state_adapter_checkpoint, 'LiveWorld/ckpts/state_adapter/model.pt', observer.get('sp_path'))
    for argument, key, relative in [
        ('qwen_model_path', 'qwen_model_path', 'Qwen3-VL-8B-Instruct'),
        ('sam3_model_path', 'sam3_model_path', 'sam3/sam3.pt'),
        ('stream3r_model_path', 'stream3r_model_path', 'STream3R'),
    ]:
        auxiliary[key] = choose(getattr(args, argument), relative, auxiliary.get(key))
    dedup = system['event']['deduplication']
    dedup['model_path'] = choose(args.dinov3_model_path, 'dinov3-vith16plus-pretrain-lvd1689m', dedup.get('model_path'))
    portable = base is not None or args.wan_model_path is not None
    train_path = Path(observer['config'])
    if not train_path.is_absolute():
        train_path = ROOT / train_path
    train = yaml.safe_load(train_path.read_text())
    if portable:
        train['wan_model_name'] = choose(args.wan_model_path, 'Wan2.1-T2V-14B', train.get('wan_model_name'))
        # Only change paths. All architecture, LoRA, scheduler and CFG settings
        # remain those in the original LiveWorld configurations.
        generated_train = args.work_path / 'observer_config.yaml'
        generated_train.parent.mkdir(parents=True, exist_ok=True)
        generated_train.write_text(yaml.safe_dump(train, allow_unicode=True, sort_keys=False))
        observer['config'] = str(generated_train)
    required = [Path(observer['lora_path']), Path(observer['sp_path'])]
    for key in ['qwen_model_path', 'sam3_model_path', 'stream3r_model_path']:
        required.append(Path(auxiliary[key]))
    if dedup.get('enabled', True):
        required.extend([Path(dedup['model_path']) / name for name in
                         ['config.json', 'preprocessor_config.json', 'model.safetensors']])
    wan = Path(train['wan_model_name'])
    required.extend([wan / name for name in ['config.json', 'Wan2.1_VAE.pth',
                     'models_t5_umt5-xxl-enc-bf16.pth', 'google/umt5-xxl']])
    for directory, index_name, fallback in [
        (wan, 'diffusion_pytorch_model.safetensors.index.json', 'diffusion_pytorch_model.safetensors'),
        (Path(auxiliary['qwen_model_path']), 'model.safetensors.index.json', 'model.safetensors'),
    ]:
        index = directory / index_name
        if index.is_file():
            weight_map = json.loads(index.read_text())['weight_map']
            required.extend(directory / name for name in sorted(set(weight_map.values())))
        else:
            required.append(directory / fallback)
    required.extend([Path(auxiliary['stream3r_model_path']) / 'config.json',
                     Path(auxiliary['stream3r_model_path']) / 'model.safetensors'])
    missing = [str(path) for path in required if not path.exists()]
    if missing:
        parser.error('Missing model files:\n' + '\n'.join(missing))
    print('LiveWorld model paths: ' + json.dumps({
        'wan': str(wan), 'lora': observer['lora_path'], 'state_adapter': observer['sp_path'],
        **{key: auxiliary[key] for key in ['qwen_model_path', 'sam3_model_path', 'stream3r_model_path']},
        'dinov3': dedup['model_path'],
    }), flush=True)
    return system


def prepare_sample(args, dataset, index, sample, system):
    name = sample_name(dataset, index)
    work = args.work_path / name
    work.mkdir(parents=True, exist_ok=True)
    first = sample['video'][0].convert('RGB')
    if first.size != (832, 480):
        raise ValueError(f'{name}: expected 832x480, got {first.size}')
    first.save(work / 'first_frame.png')
    poses = sample['camera_control_origin'][:args.num_frames].cpu().numpy().astype(np.float32)
    intrinsics = sample['intrinsics'][:args.num_frames].cpu().numpy().astype(np.float32)
    if poses.shape != (args.num_frames, 4, 4) or intrinsics.shape != (args.num_frames, 3, 3):
        raise ValueError(f'{name}: invalid camera shapes {poses.shape}, {intrinsics.shape}')
    if not np.isfinite(poses).all() or not np.isfinite(intrinsics).all():
        raise ValueError(f'{name}: nonfinite camera values')
    if np.any(intrinsics[:, [0, 1], [0, 1]] <= 0):
        raise ValueError(f'{name}: invalid focal length')
    poses[:, :3, 3] = poses[0, :3, 3] + args.camera_translation_scale * (poses[:, :3, 3] - poses[0, :3, 3])
    # The native renderer uses poses 0..N-1. A repeated terminal pose supports
    # the native post-generation bookkeeping at indices 1..N, with no new motion.
    np.savez(work / 'geometry.npz', poses_c2w=np.concatenate([poses, poses[-1:]]),
             intrinsics=np.concatenate([intrinsics, intrinsics[-1:]]), processed_size=[480, 832])
    cfg = copy.deepcopy(system)
    cfg['runtime']['device'] = args.device
    if args.seed is not None:
        cfg['runtime']['seed'] = args.seed
    cfg['observer']['frames_per_iter'] = args.num_frames
    cfg['observer']['fps'] = args.fps
    cfg['first_frame_image'] = str(work / 'first_frame.png')
    cfg['geometry_file_name'] = str(work / 'geometry.npz')
    cfg['iter_input'] = {'0': {'scene_text': sample['prompt'], 'fg_text': ''}}
    cfg.pop('entities_file', None)
    cfg.pop('storyline_file', None)
    cfg['output']['root'] = str(work / 'liveworld')
    if not getattr(args, 'keep_work', False):
        for key in list(cfg['output']):
            if key.startswith('save_'):
                cfg['output'][key] = False
        cfg['output']['final_video_only'] = True
    cfg['pano_input'] = {'intrinsics': intrinsics.tolist(), 'image_size': [480, 832]}
    (work / 'infer.yaml').write_text(yaml.safe_dump(cfg, allow_unicode=True, sort_keys=False))
    metadata = {
        'sample': name, 'source_video': dataset.data[index]['video'],
        'input_rgb_indices': [0], 'target_camera_indices': list(range(args.num_frames)),
        'num_frames': args.num_frames, 'prefix_frames': 1,
        'preserve_input_frames': args.preserve_input_frames,
        'camera_translation_scale': args.camera_translation_scale,
        'system_config': str(args.system_config), 'seed': cfg['runtime']['seed'],
        'model_parameters': {k: cfg['observer'].get(k) for k in
                             ['infer_steps', 'guidance_scale', 'timestep_shift', 'backbone_path']},
        'output_video': str(args.output_path / f'{name}.mp4'),
    }
    (work / 'input_metadata.json').write_text(json.dumps(metadata, indent=2, ensure_ascii=False))
    return name, work, first, cfg


def make_pipeline_class():
    from liveworld.pipelines.monitor_centric import MonitorCentricEvolutionPipeline
    from liveworld.pipelines.pointcloud_updater import _project_points_to_depth_map

    class PanoSingleRoundPipeline(MonitorCentricEvolutionPipeline):
        def _initialize_first_frame_projections(self, first_frame_np, dynamic_mask):
            # Called after native Stream3R reconstruction/alignment and before
            # any event/observer diffusion. Only calibrate external input geometry.
            given = np.asarray(self.config['pano_input']['intrinsics'], dtype=np.float32)
            source_hw = self.geometry.intrinsics_size
            old_k = np.asarray(self.geometry.intrinsics, dtype=np.float32).copy()
            if old_k.ndim != 2:
                raise ValueError('Expected one initial reconstruction intrinsic matrix')
            height, width = first_frame_np.shape[:2]
            old_k[0] *= width / source_hw[1]
            old_k[1] *= height / source_hw[0]
            pose = self.geometry.poses_c2w[0]
            points, colors = self.world_state.get_static()
            points = remap_camera_intrinsics(points, pose, old_k, given[0])
            self.world_state.update_static(points, colors)
            self.geometry.intrinsics = np.concatenate([given, given[-1:]])
            self.geometry.intrinsics_size = (height, width)
            # Keep the updater's reconstruction camera internally consistent.
            handler = self.pointcloud_handler
            handler._points_world = points
            handler._intrinsics = given[0].copy()
            handler._intrinsics_size = (height, width)
            handler._depth_history[0] = (
                _project_points_to_depth_map(points, pose, given[0], height, width),
                pose.copy(), given[0].copy(), (height, width),
            )
            super()._initialize_first_frame_projections(first_frame_np, dynamic_mask)

    return PanoSingleRoundPipeline


def main():
    # All LiveWorld relative model paths retain the repository-root convention.
    os.chdir(ROOT)
    p = build_parser()
    sys.path.insert(0, str(ROOT))
    from pano_inference.inference_io import (
        BoundedVideoWriter, add_inference_io_arguments, complete_video,
        prefetch_samples, validate_inference_io_arguments,
    )
    add_inference_io_arguments(p)
    args = p.parse_args()
    validate_inference_io_arguments(p, args)
    if args.num_shards < 1 or not 0 <= args.shard_rank < args.num_shards:
        p.error('Require num_shards >= 1 and 0 <= shard_rank < num_shards')
    if args.max_samples < 1 or not 1 <= args.num_frames <= 81 or (args.num_frames - 1) % 4:
        p.error('Require max_samples >= 1 and num_frames = 4n+1 in [1,81]')
    if args.fps <= 0 or not np.isfinite(args.camera_translation_scale) or args.camera_translation_scale <= 0:
        p.error('Require positive fps and camera_translation_scale')
    args.output_path = args.output_path.resolve()
    temporary_work = None
    if args.keep_work:
        args.work_path = (args.work_path or (args.output_path / '_work')).resolve()
    else:
        temporary_work = tempfile.TemporaryDirectory(prefix='liveworld-k1-')
        args.work_path = Path(temporary_work.name)
        print(f'Final-video-only mode; temporary workspace: {args.work_path}', flush=True)
    args.system_config = args.system_config.resolve()
    args.dataset_base_path = args.dataset_base_path.resolve()
    for field in ['dataset_metadata_path', 'dataset_prompt_path']:
        path = getattr(args, field)
        if not path.is_absolute():
            setattr(args, field, args.dataset_base_path / path)
    system = load_runtime_system(args, p)
    if system['observer'].get('backbone_path') or system['observer'].get('denoising_step_list'):
        p.error('This entry is for full-step LiveWorld; use a non-distilled system config')
    from pano_inference.dataset import PanoDataset
    from pano_inference.save_video import save_video
    dataset = PanoDataset(
        base_path=args.dataset_base_path, metadata_path=args.dataset_metadata_path,
        prompt_path=args.dataset_prompt_path, max_data_items=args.max_samples,
        check_files=True, check_resolution=True, camera_preload_workers=args.camera_preload_workers,
    )
    indices = [i for i in range(min(args.max_samples, len(dataset)))
               if i % args.num_shards == args.shard_rank
               and not (args.skip_existing and complete_video(
                   args.output_path / f'{sample_name(dataset, i)}.mp4',
                   frames=args.num_frames, fps=args.fps, width=832, height=480))]
    print(f'Shard {args.shard_rank}/{args.num_shards}: {len(indices)} pending samples', flush=True)
    shared = None
    failures = []
    Pipeline = None
    with BoundedVideoWriter(save_video, max_pending=args.save_queue_size,
                            encoder_threads=args.encoder_threads) as writer:
        for index, sample in prefetch_samples(dataset, indices, depth=args.prefetch):
            name, work, first, cfg = prepare_sample(args, dataset, index, sample, system)
            print(f'[{index+1}/{len(dataset)}] {name}: K=1, rounds=1, frames={args.num_frames}, '
                  f'steps={cfg["observer"]["infer_steps"]}, CFG={cfg["observer"]["guidance_scale"]}', flush=True)
            if args.dry_run:
                print(f'Validated inputs: {work}', flush=True)
                continue
            import torch
            from liveworld.utils import set_seed
            from liveworld.pipelines.monitor_centric.shared_models import create_shared_models
            if Pipeline is None:
                Pipeline = make_pipeline_class()
            if shared is None:
                set_seed(cfg['runtime']['seed'])
                shared = create_shared_models(cfg)
            shared.pointcloud_handler.reset_session()
            pipeline = None
            try:
                set_seed(cfg['runtime']['seed'])
                pipeline = Pipeline(config=cfg, shared_models=shared)
                pipeline.run(cfg['iter_input'])
                frames = list(pipeline.geometry.all_generated_frames)
                if len(frames) != args.num_frames:
                    raise RuntimeError(f'Expected {args.num_frames} output frames, got {len(frames)}')
                if args.preserve_input_frames:
                    frames[0] = np.array(first, dtype=np.uint8)
                writer.submit(frames, args.output_path / f'{name}.mp4', fps=args.fps, quality=args.quality)
                if args.keep_work:
                    (work / 'status.json').write_text(json.dumps({'state': 'generated', 'frames': len(frames)}))
            except Exception as exc:
                import traceback
                traceback.print_exc()
                failures.append(name)
                if args.keep_work:
                    (work / 'status.json').write_text(json.dumps({'state': 'failed', 'error': str(exc)}))
                if isinstance(exc, torch.cuda.OutOfMemoryError):
                    raise
            finally:
                del pipeline
                gc.collect()
                torch.cuda.empty_cache()
                if not args.keep_work:
                    shutil.rmtree(work, ignore_errors=True)
    if not args.dry_run:
        for index in indices:
            name = sample_name(dataset, index)
            if not complete_video(args.output_path / f'{name}.mp4', frames=args.num_frames,
                                  fps=args.fps, width=832, height=480):
                if name not in failures:
                    failures.append(name)
            elif args.keep_work:
                (args.work_path / name / 'status.json').write_text(json.dumps({'state': 'complete', 'frames': args.num_frames}))
    if temporary_work is not None:
        temporary_work.cleanup()
    if failures:
        raise RuntimeError(f'Failed samples: {failures}')
    print('Input preflight passed.' if args.dry_run else 'All requested outputs verified.', flush=True)


if __name__ == '__main__':
    main()