File size: 7,649 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
from typing import Dict, Optional, Sequence, Tuple

import torch
from torch import Tensor, nn
from transformers.models.gemma.modeling_gemma import GemmaRMSNorm
from transformers.models.llama.modeling_llama import LlamaRMSNorm
from transformers.models.qwen2.modeling_qwen2 import Qwen2RMSNorm
try:
    from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLTextRMSNorm
except ImportError:
    # FastVLM's official environment uses transformers 4.48 (no Qwen3-VL).
    Qwen3VLTextRMSNorm = Qwen2RMSNorm

from utils.custom_types import ParamGroup, TrainingOutput


def configure_params_groups(model: nn.Module, param_groups: Sequence[ParamGroup], verbose: bool = True):
    # Partition the parameters into those that will and those that will not experience regularising weight decay
    whitelist_weight_modules = (
        torch.nn.Linear,
        torch.nn.Conv2d,
        torch.nn.Conv3d,
        torch.nn.MultiheadAttention,
        torch.nn.GRU,
    )
    blacklist_weight_modules = (
        LlamaRMSNorm,
        GemmaRMSNorm,
        Qwen2RMSNorm,
        Qwen3VLTextRMSNorm,
        torch.nn.GroupNorm,
        torch.nn.LayerNorm,
        torch.nn.BatchNorm2d,
        torch.nn.Embedding,
        torch.nn.SyncBatchNorm,
    )

    black_list_weight_names = (
        "latent",
        "logit_scale",
        "pos_enc",
        'image_newline',
        'class_embedding',
        'temporal_embedding',
        "pos_embed",
        "positional_encoding",
        "temporal_encoding",
        "camera_encoding",
        "register_tokens",
        "sink_token",
        "egoposition_head",
        "route_head",
        "acceleration_head",
        "curvature_rate_head",
        "query_embeds",
        # world predictor bare parameters (positional/type embeddings)
        "state_type_embed",
        "action_type_embed",
        "spatial_embed",
        "action_slot_embed",
        "time_embed",
        # transformers 5.x Qwen2.5-VL specific parameters
        'norm1.weight',
        'norm2.weight',
        'fc1.weight',
        'fc2.weight',
        'merger.ln_q.weight',
        'spatial_merge.weight',
    )

    decay_params = set()
    no_decay_params = set()
    not_trainable_params = set()
    for mn, m in model.named_modules():
        for pn, p in m.named_parameters():

            fpn = f"{mn}.{pn}" if mn else pn  # full param name
            if not p.requires_grad:
                not_trainable_params.add(fpn)
                continue
            if pn.endswith('bias'):
                # all biases will not be decayed
                no_decay_params.add(fpn)
            elif (
                pn.endswith('weight')
                and isinstance(m, blacklist_weight_modules)
                or any(x in fpn for x in black_list_weight_names)
            ):
                # weights of blacklist modules will NOT be weight decayed
                no_decay_params.add(fpn)
            elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
                # weights of whitelist modules will be weight decayed
                decay_params.add(fpn)

    # validate that we considered every parameter
    param_dict = {pn: p for pn, p in model.named_parameters()}
    inter_params = decay_params & no_decay_params
    union_params = decay_params | no_decay_params | not_trainable_params
    assert len(inter_params) == 0, f"parameters {inter_params} made it into both decay/no_decay sets!"
    assert len(param_dict.keys() - union_params) == 0, (
        f"parameters {param_dict.keys() - union_params} were not separated "
        f"into either decay/no_decay/not_trainable set!"
    )

    union_params = set(not_trainable_params)

    # split decay/no decay params into separate param groups with different lr
    out = []
    for pg in param_groups:
        group_params_decay = sorted(k for k in decay_params if re.match(pg.pattern, k))
        group_params_no_decay = sorted(k for k in no_decay_params if re.match(pg.pattern, k))

        inter_params = union_params.intersection(group_params_decay)
        assert len(inter_params) == 0, f"decay parameters {inter_params} made it into multiple param groups"
        inter_params = union_params.intersection(group_params_no_decay)
        assert len(inter_params) == 0, f"no-decay parameters {inter_params} made it into multiple param groups"

        if pg.weight_decay <= 0.0:
            group_params_no_decay = group_params_decay + group_params_no_decay
            group_params_decay = []
        if verbose and rank_zero_only.rank == 0:
            print(f"==== PARAM_GROUP {pg.pattern} ====")
            for pn in group_params_decay:
                print(f"(DECAY) {pn}")
            for pn in group_params_no_decay:
                print(f"(NO_DECAY) {pn}")
        if len(group_params_decay) > 0:
            out.append(
                {'params': [param_dict[pn] for pn in group_params_decay], 'lr': pg.lr, 'weight_decay': pg.weight_decay}
            )
        if len(group_params_no_decay) > 0:
            out.append({'params': [param_dict[pn] for pn in group_params_no_decay], 'lr': pg.lr, 'weight_decay': 0.0})

        union_params.update(group_params_decay)
        union_params.update(group_params_no_decay)

    assert (
        len(param_dict.keys() - union_params) == 0
    ), f"parameters {param_dict.keys() - union_params} were not separated into any param groups!"

    return out


def normalize_imagenet(x):
    """ 
    Normalize input images according to ImageNet standards.
    Args:
        x (tensor): input images
    """
    x = x.copy()
    x[:, 0] = ((x[:, 0] / 255.0) - 0.485) / 0.229
    x[:, 1] = ((x[:, 1] / 255.0) - 0.456) / 0.224
    x[:, 2] = ((x[:, 2] / 255.0) - 0.406) / 0.225
    return x


def summarise_losses(
    loss_dict: Dict[str, Tuple[Tensor, Tensor]], weights: Optional[Dict[str, float]] = None
) -> TrainingOutput:
    """
    Computes the total loss from a dictionary of losses and their counts.

    The loss dict should contain two tensor for each key:
    - The loss value for each batch sample; shape [B].
    - The loss count for each batch sample; shape [B]. This is the number of items to average over, i.e.
      number of tokens, number of cuboids etc. For the case where each batch sample has a loss, you
      can set it to a ones tensor of shape [B].

    Optionally, a weights dictionary can be provided to weight the losses.

    Args:
        loss_dict: A dictionary of losses and their counts, for each batch sample.
        weights: A dictionary of weights for each loss key.

    Returns:
        A TrainingOutput object with the total loss and its components.
    """

    loss_values = {k: v for k, (v, _) in loss_dict.items()}
    loss_counts = {k: n for k, (_, n) in loss_dict.items()}
    # Clamp the denominator so the unselected `where` branch never divides by
    # zero: `d(v/n)/dv = grad/n` is evaluated in backward even when the branch
    # is masked out, and 0/0 poisons every upstream gradient with NaN.  This
    # triggers whenever a loss term has zero valid items in the whole batch
    # (e.g. no dream pair / no complete future-box geometry).
    loss_averages = {
        k: torch.where(n.sum() > 0, v.sum() / n.sum().clamp_min(1), 0.0)
        for k, (v, n) in loss_dict.items()
    }
    if weights is None:
        loss = torch.stack(list(loss_averages.values())).sum()
    else:
        loss = torch.stack([weights.get(k, 1.0) * v for k, v in loss_averages.items()]).sum()
    return TrainingOutput(
        loss=loss,
        loss_values=loss_values,
        loss_counts=loss_counts,
        loss_averages=loss_averages,
    )