File size: 17,640 Bytes
1d7c7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/env python3
"""Apply narrow compatibility fixes for the pinned NGC/Megatron-SWIFT stack."""

from __future__ import annotations

import importlib.util
from pathlib import Path


def package_dir(name: str) -> Path:
    spec = importlib.util.find_spec(name)
    if spec is None or spec.submodule_search_locations is None:
        raise SystemExit(f"{name} package not found")
    return Path(next(iter(spec.submodule_search_locations)))


def replace_once(path: Path, old: str, new: str, label: str) -> None:
    text = path.read_text()
    if new not in text:
        if text.count(old) != 1:
            raise SystemExit(f"Unexpected {label} source in {path}")
        path.write_text(text.replace(old, new, 1))
    print(f"Verified {label} in {path}")


def patch_mcore_te_export() -> None:
    path = package_dir("mcore_bridge") / "bridge" / "gpt_bridge.py"
    old = "            from transformer_engine.pytorch import Float8BlockQuantizer\n"
    new = """            try:
                from transformer_engine.pytorch import Float8BlockQuantizer
            except ImportError:
                from transformer_engine.pytorch.tensor.float8_blockwise_tensor import (
                    Float8BlockQuantizer,
                )
"""
    replace_once(path, old, new, "NGC TE quantizer import fallback")


def patch_peft_torchao_probe() -> None:
    path = package_dir("peft") / "import_utils.py"
    old = '''    if torchao_version < TORCHAO_MINIMUM_VERSION:
        raise ImportError(
            f"Found an incompatible version of torchao. Found version {torchao_version}, "
            f"but only versions above {TORCHAO_MINIMUM_VERSION} are supported"
        )
'''
    new = '''    if torchao_version < TORCHAO_MINIMUM_VERSION:
        # Optional backend is present but cannot be used by this PEFT version.
        return False
'''
    replace_once(path, old, new, "PEFT/NGC TorchAO availability fallback")


def patch_swift_trainable_audit() -> None:
    path = package_dir("swift") / "megatron" / "utils" / "utils.py"
    original = '''    logger.info_if(
        f'[rank{dist.get_rank()}] model_parameter_info: {get_model_parameter_info(model)}',
        cond=mpu.get_data_parallel_rank() == 0)
    return model
'''
    legacy = '''    logger.info_if(
        f'[rank{dist.get_rank()}] model_parameter_info: {get_model_parameter_info(model)}',
        cond=mpu.get_data_parallel_rank() == 0)
    trainable_names = [name for name, param in model.named_parameters() if param.requires_grad]
    allowed_targets = (
        'linear_q_down_proj', 'linear_q_up_proj', 'linear_kv_proj',
        'linear_proj', 'linear_o_group_proj',
    )
    forbidden = [
        name for name in trainable_names
        if '.router.' in name or '.experts.' in name or '.shared_experts.' in name
    ]
    unexpected = [
        name for name in trainable_names
        if not ('.lora_A.' in name or '.lora_B.' in name)
        or not any(f'.{target}.' in name for target in allowed_targets)
    ]
    logger.info_if(
        f'[rank{dist.get_rank()}] trainable_audit: count={len(trainable_names)}, '
        f'forbidden={forbidden}, unexpected={unexpected}',
        cond=mpu.get_data_parallel_rank() == 0)
    assert not forbidden, f'Router/expert LoRA invariant violated: {forbidden}'
    assert not unexpected, f'Attention-only LoRA invariant violated: {unexpected}'
    return model
'''
    prior = '''    logger.info_if(
        f'[rank{dist.get_rank()}] model_parameter_info: {get_model_parameter_info(model)}',
        cond=mpu.get_data_parallel_rank() == 0)
    # Vision projector gates install their own stricter callback. Keep the
    # legacy attention-only LoRA invariant for every other training launch.
    import os
    if os.environ.get('DSV4VL_STRICT_PROJECTOR_GATE') != '1':
        trainable_names = [name for name, param in model.named_parameters() if param.requires_grad]
        allowed_targets = (
            'linear_q_down_proj', 'linear_q_up_proj', 'linear_kv_proj',
            'linear_proj', 'linear_o_group_proj',
        )
        forbidden = [
            name for name in trainable_names
            if '.router.' in name or '.experts.' in name or '.shared_experts.' in name
        ]
        unexpected = [
            name for name in trainable_names
            if not ('.lora_A.' in name or '.lora_B.' in name)
            or not any(f'.{target}.' in name for target in allowed_targets)
        ]
        logger.info_if(
            f'[rank{dist.get_rank()}] trainable_audit: count={len(trainable_names)}, '
            f'forbidden={forbidden}, unexpected={unexpected}',
            cond=mpu.get_data_parallel_rank() == 0)
        assert not forbidden, f'Router/expert LoRA invariant violated: {forbidden}'
        assert not unexpected, f'Attention-only LoRA invariant violated: {unexpected}'
    return model
'''
    projector_aware = '''    logger.info_if(
        f'[rank{dist.get_rank()}] model_parameter_info: {get_model_parameter_info(model)}',
        cond=mpu.get_data_parallel_rank() == 0)
    # Vision projector gates install their own stricter callback. Stage 2 also
    # keeps the projector trainable alongside audited attention-only LoRA.
    import os
    if os.environ.get('DSV4VL_STRICT_PROJECTOR_GATE') != '1':
        projector_checkpointing = os.environ.get('DSV4VL_PROJECTOR_CHECKPOINTING') == '1'
        trainable_names = [name for name, param in model.named_parameters() if param.requires_grad]
        allowed_targets = (
            'linear_q_down_proj', 'linear_q_up_proj', 'linear_kv_proj',
            'linear_proj', 'linear_o_group_proj',
        )
        forbidden = [
            name for name in trainable_names
            if '.router.' in name or '.experts.' in name or '.shared_experts.' in name
        ]
        unexpected = [
            name for name in trainable_names
            if not (
                projector_checkpointing and 'visual.multi_modal_projector.' in name
            ) and (
                not ('.lora_A.' in name or '.lora_B.' in name)
                or not any(f'.{target}.' in name for target in allowed_targets)
            )
        ]
        logger.info_if(
            f'[rank{dist.get_rank()}] trainable_audit: count={len(trainable_names)}, '
            f'forbidden={forbidden}, unexpected={unexpected}',
            cond=mpu.get_data_parallel_rank() == 0)
        assert not forbidden, f'Router/expert LoRA invariant violated: {forbidden}'
        assert not unexpected, f'Attention-only LoRA invariant violated: {unexpected}'
    return model
'''
    new = projector_aware.replace(
        '''        logger.info_if(
            f'[rank{dist.get_rank()}] trainable_audit: count={len(trainable_names)}, '
            f'forbidden={forbidden}, unexpected={unexpected}',
            cond=mpu.get_data_parallel_rank() == 0)
        assert not forbidden, f'Router/expert LoRA invariant violated: {forbidden}'
        assert not unexpected, f'Attention-only LoRA invariant violated: {unexpected}'
''',
        '''        projector_names = [
            name for name in trainable_names if 'visual.multi_modal_projector.' in name
        ]
        lora_names = [name for name in trainable_names if name not in projector_names]
        expected_lora_tensors = int(os.environ.get('DSV4VL_EXPECTED_LORA_TENSORS', '0'))
        logger.info_if(
            f'[rank{dist.get_rank()}] trainable_audit: count={len(trainable_names)}, '
            f'projector={len(projector_names)}, lora={len(lora_names)}, '
            f'forbidden={forbidden}, unexpected={unexpected}',
            cond=mpu.get_data_parallel_rank() == 0)
        assert not forbidden, f'Router/expert LoRA invariant violated: {forbidden}'
        assert not unexpected, f'Attention-only LoRA invariant violated: {unexpected}'
        if projector_checkpointing:
            assert len(projector_names) == 4, (
                f'Expected four projector tensors, found {len(projector_names)}: {projector_names}'
            )
        if expected_lora_tensors:
            assert len(lora_names) == expected_lora_tensors, (
                f'Expected {expected_lora_tensors} LoRA tensors, found {len(lora_names)}'
            )
''',
    )
    if new == projector_aware:
        raise AssertionError("failed to construct strengthened trainable audit")
    text = path.read_text()
    if new not in text:
        candidates = [
            candidate
            for candidate in (projector_aware, prior, legacy, original)
            if candidate in text
        ]
        if len(candidates) != 1:
            raise SystemExit(f"Unexpected attention-only trainable audit source in {path}")
        path.write_text(text.replace(candidates[0], new, 1))
    print(f"Verified attention-only trainable audit in {path}")


def patch_swift_lora_projector_activation() -> None:
    """Keep an unfrozen multimodal aligner trainable after LoRA wrapping.

    The pinned Swift runtime applies ``freeze_aligner`` only to full tuning.
    Its LoRA path wraps the model and leaves every non-LoRA parameter frozen,
    even when ``--freeze_aligner false`` is requested. Stage 2 intentionally
    trains the four projector tensors beside attention-only LoRA, so mirror
    Swift's existing full-vision helper for the aligner alone.
    """

    path = package_dir("swift") / "megatron" / "utils" / "utils.py"
    helper_old = '''def prepare_mcore_model(args, model):
'''
    helper_new = '''def _prepare_full_aligner(args, model):
    megatron_model_meta = args.megatron_model_meta
    visual_cls = megatron_model_meta.visual_cls
    aligner = [f'visual.{aligner}' for aligner in visual_cls._aligner]
    for module_prefix in aligner:
        module = deep_getattr(model, module_prefix)
        if module is not None:
            module.requires_grad_(True)


def prepare_mcore_model(args, model):
'''
    replace_once(path, helper_old, helper_new, "Swift LoRA aligner activation helper")

    branch_old = '''        if args.tuner_type == 'lora_llm':
            _prepare_full_vit(args, model)
'''
    branch_new = '''        if args.tuner_type == 'lora_llm':
            _prepare_full_vit(args, model)
        elif args.is_multimodal and not args.language_model_only and not args.freeze_aligner:
            _prepare_full_aligner(args, model)
'''
    replace_once(path, branch_old, branch_new, "Swift LoRA projector activation")


def patch_swift_gate_checkpoint_suppression() -> None:
    path = package_dir("swift") / "megatron" / "callbacks" / "default_flow.py"
    replace_once(
        path,
        "import gc\n\nfrom .base import MegatronCallback\n",
        "import gc\nimport os\n\nfrom .base import MegatronCallback\n",
        "gate checkpoint suppression import",
    )
    old = '''        if args.save_steps and state.iteration % args.save_steps == 0:
            state.should_save = True

        if state.iteration >= args.train_iters:
            if args.eval_iters > 0:
                state.should_eval = True
            state.should_save = True
'''
    new = '''        disable_save = os.environ.get('DSV4VL_DISABLE_SAVE') == '1'
        if not disable_save and args.save_steps and state.iteration % args.save_steps == 0:
            state.should_save = True

        if state.iteration >= args.train_iters:
            if args.eval_iters > 0:
                state.should_eval = True
            if not disable_save:
                state.should_save = True
'''
    replace_once(path, old, new, "opt-in gate checkpoint suppression")


def patch_swift_datasets4_json_fallback() -> None:
    """Use Swift's structured feature fallback on early Datasets 4.x.

    The pinned ms-swift commit treats every Datasets >=4.0 release as if it
    exports ``datasets.features.Json``. Datasets 4.0.0 does not export that
    feature, so dataset ``map(num_proc>1)`` fails before model loading. The
    existing structured branch is already Swift's compatibility path; select
    it whenever the optional Json feature is unavailable.
    """

    path = package_dir("swift") / "dataset" / "preprocessor" / "core.py"
    old = """                if self.datasets_4:
                    from datasets.features import Json, List
"""
    new = """                if self.datasets_4 and hasattr(datasets.features, 'Json'):
                    from datasets.features import Json, List
"""
    replace_once(path, old, new, "Swift/Datasets 4.0 Json feature fallback")


def patch_swift_canonical_lr_logging() -> None:
    """Log the canonical optimizer schedule across fresh and resumed runs.

    Distributed checkpoint restore can reorder aligned parameter groups. The
    pinned Swift trainer logs the first nonempty group, which may switch from
    the LLM schedule to the projector schedule after recovery even when both
    schedules restored correctly. The LLM schedule is the largest active
    learning rate in this recipe (the projector uses a 10x multiplier below
    it), so select it independently of restored group order or optional group
    metadata.
    """

    path = package_dir("swift") / "megatron" / "trainers" / "base.py"
    original = '''        for param_group in self.optimizer.param_groups:
            if len(param_group['params']) == 0:
                continue
            self._train_metrics['learning_rate'] = param_group['lr']
            break
'''
    prior = '''        from megatron.core.optimizer_param_scheduler import get_canonical_lr_for_logging
        learning_rate = get_canonical_lr_for_logging(self.optimizer.param_groups)
        if learning_rate is None:
            raise RuntimeError('canonical learning-rate parameter group is missing')
        self._train_metrics['learning_rate'] = learning_rate
'''
    prior_max_lr = '''        learning_rate = None
        for param_group in self.optimizer.param_groups:
            if not param_group['params'] or param_group.get('max_lr') != args.lr:
                continue
            learning_rate = param_group['lr']
            break
        if learning_rate is None:
            raise RuntimeError('canonical LLM learning-rate parameter group is missing')
        self._train_metrics['learning_rate'] = learning_rate
'''
    new = '''        learning_rates = [
            param_group['lr']
            for param_group in self.optimizer.param_groups
            if param_group['params']
        ]
        if not learning_rates:
            raise RuntimeError('active learning-rate parameter group is missing')
        self._train_metrics['learning_rate'] = max(learning_rates)
'''
    text = path.read_text()
    if new not in text:
        candidates = [
            candidate
            for candidate in (prior_max_lr, prior, original)
            if candidate in text
        ]
        if len(candidates) != 1:
            raise SystemExit(f"Unexpected Swift learning-rate logging source in {path}")
        path.write_text(text.replace(candidates[0], new, 1))
    print(f"Verified Swift canonical learning-rate logging in {path}")


def patch_swift_multimodal_lr_group_identity() -> None:
    """Keep the LR multiplier that distinguishes LLM and projector groups.

    Swift materializes ``max_lr``/``min_lr`` with the multiplier applied, then
    replaces ``lr_mult`` with 1.0. Megatron excludes max/min LR from its
    checkpoint group identity but includes lr_mult, so the replacement makes
    otherwise-identical LLM and projector groups collide on optimizer reload.
    Retaining the multiplier leaves the scheduled LR unchanged and makes the
    checkpoint mapping injective.
    """

    path = package_dir("swift") / "megatron" / "trainers" / "base.py"
    old = '''            lr_mult = param_group.pop('lr_mult')
            # Instead of using lr_mult to control the learning rate, we directly use max_lr/min_lr.
            param_group['lr_mult'] = 1.
            param_group['max_lr'] *= lr_mult
            param_group['min_lr'] *= lr_mult
'''
    new = '''            lr_mult = param_group['lr_mult']
            # max_lr/min_lr control the schedule. Keep lr_mult as checkpoint
            # identity so scaled multimodal groups cannot collide on reload.
            param_group['max_lr'] *= lr_mult
            param_group['min_lr'] *= lr_mult
'''
    replace_once(path, old, new, "Swift multimodal LR parameter-group identity")


def patch_swift_numeric_checkpoint_rotation() -> None:
    """Exclude support directories from Swift's checkpoint rotation.

    ``checkpoint-audits`` is deliberately adjacent to numeric checkpoints, but
    the pinned trainer counts it toward ``save_total_limit`` because its glob
    only excludes ``*-merged``.  Restrict rotation to checkpoint names whose
    suffix is entirely numeric.
    """

    path = package_dir("swift") / "megatron" / "trainers" / "base.py"
    old = """        glob_checkpoints = [
            str(p) for p in Path(output_dir).glob('checkpoint-*') if p.is_dir() and not p.name.endswith('-merged')
        ]
"""
    new = """        glob_checkpoints = [
            str(p)
            for p in Path(output_dir).glob('checkpoint-*')
            if p.is_dir() and p.name.removeprefix('checkpoint-').isdigit()
        ]
"""
    replace_once(path, old, new, "Swift numeric-only checkpoint rotation")


def main() -> None:
    patch_mcore_te_export()
    patch_peft_torchao_probe()
    patch_swift_lora_projector_activation()
    patch_swift_trainable_audit()
    patch_swift_gate_checkpoint_suppression()
    patch_swift_datasets4_json_fallback()
    patch_swift_canonical_lr_logging()
    patch_swift_multimodal_lr_group_identity()
    patch_swift_numeric_checkpoint_rotation()


if __name__ == "__main__":
    main()