# Copyright (c) ModelScope Contributors. All rights reserved. import math import torch import torch.distributed as dist import torch.nn as nn from contextlib import contextmanager from megatron.core import mpu from megatron.core.tensor_parallel import VocabParallelEmbedding from typing import Any, Dict from swift.utils import HfConfigFactory, get_logger, to_device, to_float_dtype from .utils import forward_step_helper, get_padding_to 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.to(device='cuda', dtype=torch.float32).abs().sum().cpu().item() if sum_ == 0 and '.lora_B.' not in n: 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_ cond = mpu.get_data_parallel_rank() == 0 logger.info_if(f'n_parameter: {n_parameter}', cond=cond) logger.info_if(f'total_sum: {total_sum}', cond=cond) logger.info_if(f'zero_count: {zero_count}', cond=cond) 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, compute_device=None, share_embedding: bool = False, target_device='cpu'): try: origin_torch_dtype = next(modules[0].parameters()).dtype except StopIteration: origin_torch_dtype = next(modules[-1].parameters()).dtype embedding = None if share_embedding: embedding = [module for module in modules if isinstance(module, (nn.Embedding, VocabParallelEmbedding))][-1] def _to_cuda_hook(module, args): if compute_device is not None or torch_dtype is not None: module.to(device=compute_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 embedding: return module.to(device=target_device, 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': '