# Created by BVH, Jul 2025.

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

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

job = dict(  # this becomes JobConfig
    project='a4d2',
    group='cvpr',
    name='dvs2',
    prepend_datetime=True,  # becomes {now:%m-%d-%H-%M}_{config.job.name}
)

wandb = dict(
    enabled=True,
    entity='tri',
    project='a4d2_cvpr',
    num_validation_logs=5,
)

any4d_config = dict(  # this is part of Any4DConfig, which inherits from Predict2Video2WorldModelConfig
    transforms='default',  # reference_camera now separate per dataset
    dataloader='basile',
    vae='a4d_vae',
    video_entries=[
        # first entry = base / pretrained
        dict(
            # key: (channel_start, channel_end, in_proj_init, out_proj_init)
            # NOTE: there will be T*H*W tokens with this information
            rgb0=(0, 16, 'load', 'load'),  # do not change
            rgb0_input_mask=(16, 17, 'load', None),  # do not change
            rgb0_output_mask=(17, 18, 'zero', None),  # do not change
            cams0=(18, 50, 'zero/load', 'zero/load'),
            cams0_input_mask=(50, 51, 'zero/load', None),
            cams0_output_mask=(51, 52, 'zero', None),
        ),
        # later entries = new viewpoints
        dict(
            # key: (channel_start, channel_end, in_proj_init, out_proj_init)
            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, 'zero', None),
            cams1=(18, 50, 'zero/load', 'zero/load'),
            cams1_input_mask=(50, 51, 'zero/load', None),
            cams1_output_mask=(51, 52, 'zero', None),
        ),
    ],
    num_views=2,
    video_concat_mode='view',
    video_proj_mode='per_view',
    view_timestep_mode='per_view',
    loss_weights=dict(
        rgb0=1.0,
        # rgb1=1.0,
    ),
    harmonize_streams=True,
    harmonize_frames=True,
    load_modals=['rgb', 'cams'],  # 'language', 'action', ],
    # =['rgb', 'language', 'action', 'cams'],
    task_probs=dict(
        cross_modal=0.0,
        dyn_view_synth=1.0,
        forecast=0.0,
        pose_estimation=0.0,
        inverse_dynamics=0.0,
        policy=0.0,
        world_model=0.0,
    ),
    use_views='all',
    # shuffle_cams2views=True,
    shuffle_cams2views=False,
    train_directives=dict(
        num_pred_views=1,
    ),
    val_directives=dict(
        tasks='dyn_view_synth',
        num_pred_views=1,
        remove_cond=True,
    ),
    data_val_overrides=dict(frame_stride=1),
    track_metrics=dict(
        rgb0=['psnr', 'ssim'],
        # rgb1=['psnr', 'ssim'],
    ),
    train_visuals_interval=99,
    train_visuals_detail=1,  # 2,
    val_visuals_detail=1,  # 2,
    viz_input_blacklist=[],  # overridden to show cams
    viz_mask_border_width=0,  # overridden because DVS is temporally invariant
    # val_num_steps=15,
    # val_num_steps=25,
    val_num_steps=35,
)

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

S3_PRETRAINED_PREFIX = r's3://tri-ml-sandbox-16011-us-west-2-datasets/cosmos-predict-2/checkpoints'

model = dict(  # this makes up parts of Predict2Video2WorldModelConfig and Predict2ModelManagerConfig
    # dit_path='',
    # dit_path='s3://tri-ml-sandbox-16011-us-west-2-datasets/sagemaker/cosmos-predict2/a4d2/cvpr/10-19-19-24_s23_rdvs2_mix_b6_scratch/model/iter_000003000_001152000.pt',
    # dit_path='s3://tri-ml-sandbox-16011-us-west-2-datasets/sagemaker/cosmos-predict2/a4d2/cvpr/10-21-04-09_s24_rdvs2_mix_b8_scratch/model/iter_000004000_002048000.pt',
    dit_path='s3://tri-ml-sandbox-16011-us-west-2-datasets/sagemaker/cosmos-predict2/a4d2/cvpr/10-24-00-43_s25_rdvs2_mix_b8_scratch/model/iter_000001000_000512000.pt',
    # text_encoder_path=f'{S3_PRETRAINED_PREFIX}/google-t5/t5-11b',
    text_encoder_path='',
    vae_path=f'{S3_PRETRAINED_PREFIX}/nvidia/Cosmos-Predict2-2B-Video2World/tokenizer/tokenizer.pth',
    fsdp_shard_size=8,
    ############
    run_validation=True,
    validation_iter=500,  # frequency / interval of validation runs
    # max_val_iter=8,  # number of steps per validation run
    # max_iter=120000,  # total number of training steps
    # max_iter=60000,  # total number of training steps
    max_iter=50000,  # total number of training steps
    # grad_accum_iter=2,
    grad_accum_iter=1,
    context_parallel_size=1,
    device_monitor=0,
    manual_gc_iter=288,
    manual_gc_warm_up=-1,  # never disable automatic GC to be safe (weird VRAM issue)
    ############
    state_t=11,  # for noise level; = latent # frames for now
    tokenizer_chunk_duration=41,  # for VAE; = num_frames for now
)

checkpoint = dict(
    save_iter=1000,
    s3_folder='s3://tri-ml-sandbox-16011-us-west-2-datasets/sagemaker/cosmos-predict2/',
    early_sanity_check=5,
)

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

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

dataset_train = dict(
    config='custom/config/cvpr/mixed/train_2v.yaml',
    num_workers=4,
    batch_size=8,
)

dataset_val = dict(
    config=dict(
        ### DRIVING
        ArgoVerseFront  = 'custom/config/cvpr/mixed/val_2v/argoverse_front.yaml',
        ArgoVerseLeft   = 'custom/config/cvpr/mixed/val_2v/argoverse_left.yaml',
        ArgoVerseRight  = 'custom/config/cvpr/mixed/val_2v/argoverse_right.yaml',
        DDADFront       = 'custom/config/cvpr/mixed/val_2v/ddad_front.yaml',
        DDADLeft        = 'custom/config/cvpr/mixed/val_2v/ddad_left.yaml',
        DDADRight       = 'custom/config/cvpr/mixed/val_2v/ddad_right.yaml',
        LyftL5Front     = 'custom/config/cvpr/mixed/val_2v/lyftl5_front.yaml',
        LyftL5Left      = 'custom/config/cvpr/mixed/val_2v/lyftl5_left.yaml',
        LyftL5Right     = 'custom/config/cvpr/mixed/val_2v/lyftl5_right.yaml',
        WaymoFront      = 'custom/config/cvpr/mixed/val_2v/waymo_front.yaml',
        WaymoLeft       = 'custom/config/cvpr/mixed/val_2v/waymo_left.yaml',
        WaymoRight      = 'custom/config/cvpr/mixed/val_2v/waymo_right.yaml',
        ### ROBOTICS
        DROIDIDLeft     = 'custom/config/cvpr/mixed/val_2v/droidcalib_id_left.yaml',
        DROIDIDRight    = 'custom/config/cvpr/mixed/val_2v/droidcalib_id_right.yaml',
        DROIDOODLeft    = 'custom/config/cvpr/mixed/val_2v/droidcalib_ood_left.yaml',
        DROIDOODRight   = 'custom/config/cvpr/mixed/val_2v/droidcalib_ood_right.yaml',
        LBMv12Left      = 'custom/config/cvpr/mixed/val_2v/lbmv12_left.yaml',
        LBMv12Right     = 'custom/config/cvpr/mixed/val_2v/lbmv12_right.yaml',
        ### 3D
        TartanAir       = 'custom/config/cvpr/mixed/val_2v/tartanair.yaml',
        DL3DV0          = 'custom/config/cvpr/mixed/val_2v/dl3dv_0.yaml',
        # DL3DV1          = 'custom/config/cvpr/mixed/val_2v/dl3dv_1.yaml',
        MVImgNet0       = 'custom/config/cvpr/mixed/val_2v/mvimgnet_0.yaml',
        # MVImgNet1       = 'custom/config/cvpr/mixed/val_2v/mvimgnet_1.yaml',
        RE10K0          = 'custom/config/cvpr/mixed/val_2v/re10k_0.yaml',
        # RE10K1          = 'custom/config/cvpr/mixed/val_2v/re10k_1.yaml',
        WildRGBD0       = 'custom/config/cvpr/mixed/val_2v/wildrgbd_0.yaml',
        # WildRGBD1       = 'custom/config/cvpr/mixed/val_2v/wildrgbd_1.yaml',
        ScanNet0        = 'custom/config/cvpr/mixed/val_2v/scannet_0.yaml',
        # ScanNet1        = 'custom/config/cvpr/mixed/val_2v/scannet_1.yaml',
        ### 4D
        DyCheck         = 'custom/config/cvpr/mixed/val_2v/dycheck.yaml',
        GCDKB4DDirect   = 'custom/config/cvpr/mixed/val_2v/gcd_kubric4d_dir.yaml',
        GCDKB4DGradual  = 'custom/config/cvpr/mixed/val_2v/gcd_kubric4d_grad.yaml',
        GCDPD4DDirect   = 'custom/config/cvpr/mixed/val_2v/gcd_pd4d_dir.yaml',
        GCDPD4DGradual  = 'custom/config/cvpr/mixed/val_2v/gcd_pd4d_grad.yaml',
        Kubric4D        = 'custom/config/cvpr/mixed/val_2v/kubric4d.yaml',
        Kubric5D        = 'custom/config/cvpr/mixed/val_2v/kubric5d.yaml',
        ParDom4D        = 'custom/config/cvpr/mixed/val_2v/pd4d.yaml',
        EgoExo4D0       = 'custom/config/cvpr/mixed/val_2v/egoexo4d_0.yaml',
        EgoExo4D1       = 'custom/config/cvpr/mixed/val_2v/egoexo4d_1.yaml',
        EgoExo4D2       = 'custom/config/cvpr/mixed/val_2v/egoexo4d_2.yaml',
        EgoExo4D3       = 'custom/config/cvpr/mixed/val_2v/egoexo4d_3.yaml',
    ),
    num_workers=0,  # can crash debugger otherwise
    batch_size=1,
)

metrics = dict(
    # gt_source='rec',
    gt_source='gt',
    modes=['r','rpv','apv','ipv'],
    rgb=dict(),
)

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

cs = ConfigStore.instance()

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

# Use the filename (without extension) as the experiment name
experiment_name = 'any4d_' + os.path.splitext(os.path.basename(__file__))[0]

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


