#!/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()