File size: 11,299 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from dataclasses import dataclass
from typing import Any, Dict, Optional, Tuple, Union
import time

from hydra.core.config_store import ConfigStore

@dataclass
class LLaVAnextEncoderConfig:
    variant: str = "llava-hf/llava-v1.6-mistral-7b-hf"
    embed_dim: int = 512
    freeze: bool = False
    downsample_feature_grid_factor: Optional[int] = 2
    use_global_img: bool = False

    _target_: str = "models.encoder.llavanext.LLaVAnextEncoderModel"

@dataclass
class ResnetEncoderConfig:
    variant: str = 'microsoft/resnet-34'
    embed_dim: int = 512
    freeze: bool = False
    downsample_feature_grid_factor: Optional[int] = 2
    use_global_img: bool = True

    _target_: str = "models.encoder.resnet.ResnetEncoderModel"


@dataclass
class Qwen2_5VLEncoderConfig:
    variant: str = "/public/ZLCODE/model/Qwen2.5-VL-3B-Instruct"
    freeze: bool = False
    max_visual_tokens: Optional[int] = None
    local_files_only: bool = True
    use_global_img: bool = False
    torch_dtype: str = "bfloat16"

    _target_: str = "models.encoder.qwen2_5_vl.Qwen2_5VLEncoderModel"


@dataclass
class Qwen3VLEncoderConfig:
    variant: str = "/public/ZLCODE/model/Qwen3-VL-8B-Instruct"
    freeze: bool = False
    max_visual_tokens: Optional[int] = None
    local_files_only: bool = True
    use_global_img: bool = False
    torch_dtype: str = "bfloat16"

    _target_: str = "models.encoder.qwen3_vl.Qwen3VLEncoderModel"


@dataclass
class DinoV2LoRAEncoderConfig:
    model_name: str = "timm/vit_small_patch14_reg4_dinov2.lvd142m"
    model_weights: Optional[str] = (
        "/home/billyhe/.cache/huggingface/hub/"
        "models--timm--vit_small_patch14_reg4_dinov2.lvd142m/"
        "blobs/dca70548ecd7b03ffba6172c4db403014511b5ee6073f9fca72ba9e6e602a25d"
    )
    embed_dim: int = 512
    image_size: Tuple[int, int] = (518, 518)
    use_lora: bool = True
    lora_rank: int = 16
    lora_layers: Optional[Tuple[int, ...]] = None
    lora_use_layer_norm: bool = False
    lora_use_qkv: bool = False
    finetune: bool = False
    num_register_tokens: int = 4
    use_feature_pooling: bool = False
    freeze: bool = False
    max_frames: int = 4
    max_cameras: int = 6
    use_global_img: bool = False

    _target_: str = "models.encoder.dinov2_lora.DinoV2LoRAEncoderModel"


@dataclass
class LanguageModelConfig:
    variant: str = "x-small"
    lora: bool = False
    _target_: str = "models.language_model.llama.Llama"


@dataclass
class Qwen2_5VLLanguageModelConfig:
    variant: str = "/public/ZLCODE/model/Qwen2.5-VL-3B-Instruct"
    freeze: bool = False
    lora: bool = False
    lora_r: int = 16
    lora_alpha: int = 32
    lora_dropout: float = 0.1
    local_files_only: bool = True
    torch_dtype: str = "bfloat16"

    _target_: str = "models.language_model.qwen2_5_vl.Qwen2_5VLLanguageModel"


@dataclass
class Qwen3VLLanguageModelConfig:
    variant: str = "/public/ZLCODE/model/Qwen3-VL-8B-Instruct"
    freeze: bool = False
    lora: bool = False
    lora_r: int = 16
    lora_alpha: int = 32
    lora_dropout: float = 0.1
    local_files_only: bool = True
    torch_dtype: str = "bfloat16"

    _target_: str = "models.language_model.qwen3_vl.Qwen3VLLanguageModel"


@dataclass
class Qwen3VLScratchLanguageModelConfig:
    variant: str = "pretrained/Qwen3-VL-2B-Instruct"
    hidden_size: int = 1024
    num_hidden_layers: int = 22
    num_attention_heads: int = 8
    num_key_value_heads: int = 8
    intermediate_size: int = 4096
    head_dim: int = 128
    vocab_size: int = 16
    local_files_only: bool = True
    torch_dtype: str = "bfloat16"

    _target_: str = "models.language_model.qwen3_vl_scratch.Qwen3VLScratchLanguageModel"


@dataclass
class Qwen3VLTruncatedLanguageModelConfig:
    variant: str = "pretrained/Qwen3-VL-2B-Instruct"
    num_hidden_layers: int = 10
    freeze_embed: bool = True
    local_files_only: bool = True
    torch_dtype: str = "bfloat16"

    _target_: str = "models.language_model.qwen3_vl_truncated.Qwen3VLTruncatedLanguageModel"


@dataclass
class TinyTransformerLanguageModelConfig:
    hidden_size: int = 512
    num_hidden_layers: int = 6
    num_attention_heads: int = 8
    intermediate_size: int = 2048
    max_position_embeddings: int = 4096
    tokenizer_max_length: int = 96
    dropout: float = 0.0
    freeze: bool = False

    _target_: str = "models.language_model.tiny_transformer.TinyTransformerLanguageModel"


@dataclass
class DrivingModelConfig:
    vision_model: Any
    language_model: Any

    lr: float = 1e-4
    vision_lr: Optional[float] = 1e-4
    # Separate LR for the LM trunk (None = trunk shares `lr`); used by
    # pretrained-initialised small trunks that want a lower LR than the
    # freshly initialised adaptors/heads.
    lm_lr: Optional[float] = None

    weight_decay: float = 0.1
    betas: Tuple[float, float] = (0.9, 0.999)
    pct_start: float = 0.05
    speed_wps_mode: str = '2d'
    predict_route_as_wps: bool = False
    speed_as_input: bool = True
    new_layer_norm_minmax: bool = False
    waypoint_loss_fn: str = "mse"
    smooth_l1_beta: float = 1.0

    # three-state navigation dropout (only used with route_as='command_tp')
    nav_p_both: float = 0.4
    nav_p_command: float = 0.4
    nav_p_tp: float = 0.2

    # V-JEPA2 world-model supervision on latent action queries
    jepa: Optional[Dict[str, Any]] = None
    # Training-only plan-conditioned consequence supervision
    consequence: Optional[Dict[str, Any]] = None

    # vision-tower LR schedule: hold lr=0 for `vision_freeze_steps` optimizer
    # steps, then ramp linearly to `vision_lr` over `vision_ramp_steps`
    # (0/0 keeps the original OneCycleLR behaviour)
    vision_freeze_steps: int = 0
    vision_ramp_steps: int = 0

    _target_: str = "models.driving.DrivingModel"


@dataclass
class DrivingDataModuleConfig:
    batch_size: int = 16
    num_workers: int = 10
    data_path: str = "database/simlingo"
    bucket_path: str = "database/bucketsv2_simlingo"
    encoder: str = "llavanext" # "resnet"
    train_partitions: Optional[Dict[str, float]] = None
    # Epoch length in driving samples (before dreamer mixing).  When unset,
    # the SimLingo heuristic min(len(bucket)/weight) applies, which shrinks
    # the epoch whenever a small bucket's weight is raised.  Pin this to keep
    # the optimizer-update count comparable across bucket configurations.
    train_num_samples: Optional[int] = None
    cut_bottom_quarter: bool = False

    use_global_img: bool = False

    skip_first_n_frames: int = 10
    pred_len: int = 11 # including the current time step
    hist_len: int = 3 # including the current time step

    image_enhancing: bool = False
    img_augmentation: bool = True
    img_augmentation_prob: float = 0.5
    img_shift_augmentation: bool = True
    img_shift_augmentation_prob: float = 0.5 # 80% of the data that conains augmented views -> only a small portion of the dataset contains augmented views
    
    num_route_points: int = 20

    use_town13: bool = True
    use_old_towns: bool = True

    route_as: str = 'target_point' # coords, image, target_point, command, command_tp
    # With route_as='command_tp': also append the TP coordinates to the
    # command text so the language pathway sees the navigation goal
    # (SimLingo-style).  Must match between training and evaluation.
    command_tp_text: bool = False

    # Action Dreaming
    use_dreamer: bool = False
    dreamer_ratio: float = 0.35
    use_safety_flag: bool = False

    # V-JEPA2 future-latent cache (world-model supervision)
    use_jepa_cache: bool = False
    jepa_cache_root: str = "/public/ZLCODE/simlingo_vjepa_cache_v2"

    # Fixed actor padding used by plan-consequence labels
    use_plan_consequence: bool = False
    consequence_use_future_boxes: bool = False
    # Offline per-route box cache (scripts/build_consequence_box_cache.py).
    # When set it replaces per-sample boxes/*.json.gz probing entirely.
    consequence_box_cache_root: Optional[str] = None
    consequence_max_obstacles: int = 32
    consequence_max_clearance: float = 20.0
    consequence_ego_radius: float = 0.9

    # Seed for the epoch-reseeded train sampler; train.py overrides it with
    # TrainConfig.seed so there is a single seed source per run.
    sampler_seed: int = 42

    # Multi-view finetune: extra collected routes and/or a mixed index.
    extra_data_path: Optional[str] = None
    mixed_index_path: Optional[str] = None
    load_side_cameras: bool = False

    _target_: str = "dataloader.datamodule.DataModule"


@dataclass
class TrainConfig:
    model: DrivingModelConfig
    data_module: Any

    seed: int = 42
    gpus: int = 8

    # Deterministic mode: cudnn.benchmark off, torch deterministic algorithms
    # in warn-only mode, CUBLAS workspace pinned. Needed for reproducible
    # resume; costs some throughput. Disable with deterministic=false.
    deterministic: bool = True

    resume: bool = False
    resume_path: Optional[str] = ""


    debug: bool = False
    overfit: int = 0
    submit: bool = True  # whether to checkpoint and submit the model during training
    fp16_loss_scale: float = 32.0 # 0.0 means dynamic loss scaling, only used with deepspeed

    enable_wandb: bool = False
    wandb_project: Optional[str] = "drivevla"
    console_log_file: str = "train.log"
    if debug:
        wandb_name: Optional[str] = f"debug"
        gpus: int = 1
    else:
        # wandb_name: Optional[str] = f"debug"
        name: Optional[str] = "test"
        wandb_name: Optional[str] = f"{time.strftime('%Y_%m_%d_%H_%M_%S')}"
    

    # max_steps: int = 100_000
    max_epochs: int = 20
    precision: str = "16-mixed"
    strategy: str = "deepspeed_stage_2" # deepspeed_stage_2 ddp
    accumulate_grad_batches: int = 1
    devices: Union[str, int] = "auto"
    # val_check_interval: int = 5000
    val_every_n_epochs: int = 1

    checkpoint: Optional[str] = None
    weights: Optional[str] = None  # same as checkpoint, except we don't load optimizer


def register_configs():
    cs = ConfigStore.instance()
    cs.store(name="train_base", node=TrainConfig)
    cs.store(group="data_module", name="driving", node=DrivingDataModuleConfig)
    cs.store(group="model", name="driving", node=DrivingModelConfig)
    cs.store(group="model/vision_model", name="llavanext", node=LLaVAnextEncoderConfig)
    cs.store(group="model/vision_model", name="resnet", node=ResnetEncoderConfig)
    cs.store(group="model/vision_model", name="qwen2_5_vl", node=Qwen2_5VLEncoderConfig)
    cs.store(group="model/vision_model", name="qwen3_vl", node=Qwen3VLEncoderConfig)
    cs.store(group="model/vision_model", name="dinov2_lora", node=DinoV2LoRAEncoderConfig)
    cs.store(group="model/language_model", name="llm", node=LanguageModelConfig)
    cs.store(group="model/language_model", name="qwen2_5_vl", node=Qwen2_5VLLanguageModelConfig)
    cs.store(group="model/language_model", name="qwen3_vl", node=Qwen3VLLanguageModelConfig)
    cs.store(group="model/language_model", name="qwen3_vl_scratch", node=Qwen3VLScratchLanguageModelConfig)
    cs.store(group="model/language_model", name="qwen3_vl_truncated", node=Qwen3VLTruncatedLanguageModelConfig)
    cs.store(group="model/language_model", name="tiny_transformer", node=TinyTransformerLanguageModelConfig)


register_configs()