# Created by BVH/claude, 2026-04-29.
# DROID-only train + val for VRAM leak debugging.
# Cloned from custom/experiment/examples_anydata/rwm3_robot.py.
#
# Goals:
#   - reproduce the slow VRAM climb that hits OOM on long DROID runs
#   - frequent val (every 50 train iters) so the leak shows up fast
#   - PyTorch memory snapshot enabled so each leaked tensor has a stack trace

import os
from hydra.core.config_store import ConfigStore
from custom.experiment.template import template_any4d_2b, S3_PRETRAINED_ROOT, S3_OUTPUT_ROOT

#################################################################

job = dict(
    project='a4d2',
    group='bcdbg',
    name='rwm3_droid_leak',
    prepend_datetime=True,
    local_root='',
    s3_root=S3_OUTPUT_ROOT,
)

wandb = dict(
    enabled=True,
    entity='tri',
    project='a4d2',
    num_validation_logs=2,
)

any4d_config = dict(
    dataloader='unified_anyact',
    vae='a4d_vae',
    video_entries=[
        dict(
            rgb0=(0, 16, 'load', 'load'),
            rgb0_input_mask=(16, 17, 'load', None),
            rgb0_output_mask=(17, 18, 'load', None),
        ),
        dict(
            rgb1=(0, 16, 'copy:rgb0/load', 'copy:rgb0/load'),
            rgb1_input_mask=(16, 17, 'copy:rgb0_input_mask/load', None),
            rgb1_output_mask=(17, 18, 'copy:rgb0_output_mask/load', None),
        ),
        dict(
            rgb2=(0, 16, 'copy:rgb1/load', 'copy:rgb1/load'),
            rgb2_input_mask=(16, 17, 'copy:rgb1_input_mask/load', None),
            rgb2_output_mask=(17, 18, 'copy:rgb1_output_mask/load', None),
        ),
    ],
    lowdim_adaln_entries=dict(
        action=(0, 41, 0, 20, 'zero/load'),
        action_input_mask=(0, 41, 20, 21, 'zero/load'),
    ),
    num_views=3,
    video_concat_mode='view',
    video_proj_mode='per_view',
    view_timestep_mode='per_view',
    block_gate_fix=True,
    disable_risky_sharding=True,  # keep final_layer / t_embedder un-sharded to avoid multi-view hangs
    train_cond_aug_sigma_range=(0.001, 0.01),
    val_cond_aug_sigma=0.001,
    loss_weights=dict(
        rgb0=1.0,
        rgb1=1.0,
        rgb2=1.0,
    ),
    harmonize_streams=True,
    harmonize_frames=True,
    data_train_overrides=dict(
        subsample=None,
        single_sample='random',
    ),
    data_val_overrides=dict(
        frame_stride=1,
        subsample=20,
        single_sample='first',
    ),
    use_views='all',
    shuffle_cams2views=False,
    task_probs=dict(
        cross_modal=0.0,
        dyn_view_synth=0.0,
        forecast=1.0,
        pose_est=0.0,
        inv_dyn=0.0,
        policy=0.0,
        world_model=0.9,
    ),
    train_directives=dict(),
    val_directives=dict(
        tasks='forecast,world_model',
    ),
    action_multiplier=3.0,
    # NOTE(bvh/claude): LPIPS disabled to stop iter 2+ from burning 10+ min on
    # VGG16 conv2d (apparent CPU fallback for the metric). We don't need image
    # quality numbers for a leak hunt, just the per-iter VRAM trajectory.
    track_metrics=dict(
        rgb0=['psnr'],
        rgb1=['psnr'],
        rgb2=['psnr'],
    ),
    # NOTE(bvh/claude): bump to a value > max_iter so train visuals never trigger;
    # the early-iter visuals (train_step <= 2 + train_step % (interval//2) == 1)
    # were eating 30s+/iter on rank0.
    train_visuals_interval=99999,
    train_visuals_detail=0,
    val_visuals_detail=0,
    visuals_quality=8,
    viz_input_blacklist=[],
    viz_extra_modes=['anyact1'],
    viz_mask_border_width=2,
    val_num_steps=5,  # NOTE(bvh/claude): only need val to *run* the same code path; quality irrelevant
)

#################################################################

model = dict(
    dit_path='s3://tri-ml-sandbox-16011-us-west-2-datasets/sagemaker/cosmos-predict2/a4d2/debug/12-29-17-35_s26b_rwm2_lbm40h_b8/model/iter_000119000_030464000.pt',
    text_encoder_path=f'{S3_PRETRAINED_ROOT}/google-t5/t5-11b',
    vae_path=f'{S3_PRETRAINED_ROOT}/nvidia/Cosmos-Predict2-2B-Video2World/tokenizer/tokenizer.pth',
    fsdp_shard_size=4,  # 4 GPUs
    run_validation=True,
    skip_first_validation='delay3',
    validation_iter=50,  # frequent val so the leak appears within ~1h
    max_val_iter=2,  # cap each val phase since DROID-only and we just need val pressure
    max_iter=60000,
    grad_accum_iter=1,
    context_parallel_size=1,
    device_monitor=10,
    manual_gc_iter=100,
    manual_gc_warm_up=-1,
    state_t=11,
    tokenizer_chunk_duration=41,
    profiling=dict(
        enable_memory_snapshot=True,
        enable_profiling=False,
        profile_freq=100,
        first_n_rank=4,
        record_shape=True,
        profile_memory=True,
        with_stack=True,
        with_modules=True,
    ),
)

checkpoint = dict(
    save_iter=2000,
    early_sanity_check=-1,
)

optimizer = dict(
    lr=1e-5,
)

scheduler = dict(
    warm_up_steps=[500],
    cycle_lengths=[model['max_iter']],
    f_start=[0.01],
    f_max=[1.0],
    f_min=[0.05],
)

# DROID-only train: 4 entries (one per rank) so all 4 GPUs train DROID.
dataset_train = dict(
    config=[
        'custom/config/anydata/web/debug/droid_ikela3_41.yaml',
        'custom/config/anydata/web/debug/droid_ikela3_41.yaml',
        'custom/config/anydata/web/debug/droid_ikela3_41.yaml',
        'custom/config/anydata/web/debug/droid_ikela3_41.yaml',
    ],
    num_workers=2,
    batch_size=2,
)

# DROID-only val.
dataset_val = dict(
    config=dict(
        DROID='custom/config/anydata/web/debug/droid_ikela3_41.yaml',
    ),
    num_workers=0,
    batch_size=1,
)

metrics = None


#################################################################

cs = ConfigStore.instance()

this_config = template_any4d_2b(
    job, wandb, any4d_config, model,
    checkpoint, optimizer, scheduler,
    metrics, dataset_train, dataset_val)

experiment_name = 'any4d_' + os.path.splitext(os.path.basename(__file__))[0]

cs.store(
    group='experiment',
    package='_global_',
    name=experiment_name,
    node=this_config,
)
