# Copyright (c) Alibaba, Inc. and its affiliates. import math from contextlib import contextmanager from dataclasses import fields from typing import Any, Dict import torch import torch.nn as nn from megatron.training import get_args from megatron.training.checkpointing import load_checkpoint from megatron.training.checkpointing import save_checkpoint as mg_save_checkpoint from megatron.training.initialize import initialize_megatron from megatron.training.utils import get_ltor_masks_and_position_ids from swift.llm import (ExportArguments, HfConfigFactory, prepare_model_template, save_checkpoint, to_device, to_float_dtype) from swift.utils import get_logger, get_n_params_grads from ..argument import MegatronArguments from ..model import get_megatron_model_meta from .patcher import patch_megatron_tokenizer, patch_torch_dist_shard logger = get_logger() def _test_params_sum(model): total_sum = 0 zero_count = 0 n_parameter = 0 for n, p in model.named_parameters(): n_parameter += 1 sum_ = p.cuda().float().abs().sum().cpu().item() if sum_ == 0: zero_count += 1 logger.warning(f'n: {n}, sum: {sum_}') elif math.isnan(sum_) or math.isinf(sum_) or sum_ > 1e10: logger.warning(f'n: {n}, sum: {sum_}') else: total_sum += sum_ logger.info(f'n_parameter: {n_parameter}') logger.info(f'total_sum: {total_sum}') logger.info(f'zero_count: {zero_count}') def _find_modules(model, recurse: bool = True, prefix='', ignore_modules=None): ignore_modules = ignore_modules or [] for k in ignore_modules: if prefix.startswith(k): return [] else: named_children = list(model.named_children()) modules = [] for n, module in named_children: if module.__class__ is nn.ModuleList: modules += _find_modules(module, False, prefix=f'{prefix}{n}.', ignore_modules=ignore_modules) elif recurse: modules += _find_modules(module, prefix=f'{prefix}{n}.', ignore_modules=ignore_modules) else: modules.append(module) if not named_children: modules.append(model) return modules @contextmanager def _model_cpu_forward_context(modules, torch_dtype=None, device=None, share_embedding: bool = False): origin_torch_dtype = next(modules[0].parameters()).dtype def _to_cuda_hook(module, args): if device is not None or torch_dtype is not None: module.to(device=device, dtype=torch_dtype) args = to_float_dtype(args, dtype=torch_dtype) return args def _to_cpu_hook(module, args, output): if share_embedding and module is modules[0]: return module.to(device='cpu', dtype=origin_torch_dtype) hooks = [] for module in modules: hooks.append(module.register_forward_pre_hook(_to_cuda_hook)) hooks.append(module.register_forward_hook(_to_cpu_hook)) try: yield finally: for hook in hooks: hook.remove() def get_examples(is_multimodal: bool) -> Dict[str, Any]: mm_type = 'image' if is_multimodal: if mm_type == 'image': data = { 'messages': [{ 'role': 'user', 'content': 'describe the image.' }, { 'role': 'assistant', 'content': 'The image depicts a close-up of a kitten with striking features. ' 'The kitten has a white and gray coat with distinct black stripes, ' 'particularly noticeable on its face and ears. Its eyes are large ' 'and expressive, with a captivating blue hue that stands out against ' "the darker fur around them. The kitten's nose is small and pink, " 'and it has long, delicate whiskers extending from either side of its mouth. ' "The background is blurred, drawing attention to the kitten's face and " 'making it the focal point of the image. The overall impression is ' 'one of cuteness and charm.' }], 'images': ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png'] } elif mm_type == 'audio': data = { 'messages': [{ 'role': 'user', 'content': '