-
Notifications
You must be signed in to change notification settings - Fork 9
npu_megatron_adapt #99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
addsubmuldiv
wants to merge
1
commit into
modelscope:main
Choose a base branch
from
addsubmuldiv:mindspeed_adapt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,7 +34,13 @@ | |
| from twinkle.template import Template | ||
| from twinkle.utils import construct_class, exists | ||
| from .strategy import MegatronStrategy | ||
| from transformers.utils import is_torch_npu_available | ||
|
|
||
| if is_torch_npu_available(): | ||
| # Enable Megatron on Ascend NPU | ||
| from mindspeed.megatron_adaptor import repatch | ||
| else: | ||
| repatch = None | ||
|
|
||
| @dataclass | ||
| class MegatronOptimizerGroup: | ||
|
|
@@ -71,7 +77,17 @@ def do_grad_sync(self, gradient_accumulation_steps: Optional[int] = None) -> boo | |
|
|
||
| def __post_init__(self): | ||
| if self._device_mesh.data_world_size > 1: | ||
| self._dp_group = self._device_mesh.create_process_group(['dp', 'fsdp']) | ||
| is_npu = is_torch_npu_available() | ||
| has_fsdp = (getattr(self._device_mesh, 'fsdp_world_size', 0) or 0) > 1 | ||
|
|
||
| if is_npu and not has_fsdp: | ||
| # On NPU/HCCL without FSDP, cached dim-group creation avoids | ||
| # inconsistent creation order issues. | ||
| self._dp_group = self._device_mesh.get_dim_group('dp') | ||
| else: | ||
| # Keep metrics/data aggregation on the full data axis. | ||
| # This must include fsdp when fsdp_size > 1. | ||
| self._dp_group = self._device_mesh.create_process_group(['dp', 'fsdp']) | ||
| self.train_metrics = [ | ||
| LossMetric(self._device_mesh, self._dp_group), | ||
| TrainMetric(self._device_mesh, self._dp_group), | ||
|
|
@@ -223,6 +239,24 @@ def __init__( | |
| sequence_parallel=self.strategy.sequence_parallel, | ||
| **ac_kwargs, | ||
| ) | ||
|
|
||
| is_npu = is_torch_npu_available() | ||
|
|
||
| if repatch is not None and is_npu: | ||
| from dataclasses import asdict | ||
| megatron_args = asdict(args) | ||
| try: | ||
| repatch(megatron_args) | ||
| except NameError as e: | ||
| # MindSpeed 0.12.1 has a known repatch bug: | ||
| # mindspeed/patch_utils.py references `inspect` without importing it. | ||
| # Keep training alive with initial patches already applied at import time. | ||
| if 'inspect' in str(e): | ||
| logging.getLogger(__name__).warning( | ||
| 'Skip MindSpeed repatch due to upstream bug (%s). Continue with initial patches.', e) | ||
| else: | ||
| raise | ||
|
|
||
| set_args(args) | ||
| self._initialized = False | ||
| self.model: List[nn.Module] = self._create_megatron_model(load_weights, **kwargs) | ||
|
|
@@ -433,6 +467,10 @@ def post_loss_function(output_tensor, inputs): | |
| # forward_step_func(data_iterator, model) -> (output_tensor, partial(loss_func)) | ||
| def forward_step_func(data_iterator, model): | ||
| batch = next(data_iterator) | ||
| local_device = Platform.get_local_device() | ||
| for key, value in batch.items(): | ||
| if isinstance(value, torch.Tensor) and value.device != local_device: | ||
| batch[key] = value.to(local_device, non_blocking=True) | ||
| labels = batch.pop('labels', None) | ||
| output_tensor = model(**batch) | ||
| batch['labels'] = labels | ||
|
|
@@ -726,30 +764,46 @@ def _create_megatron_optimizer(self, **kwargs): | |
| lr = kwargs.pop('lr', 1e-4) | ||
| use_distributed_optimizer: bool = kwargs.pop('use_distributed_optimizer', False) | ||
|
|
||
| opt_config = OptimizerConfig( | ||
| optimizer='adam', | ||
| lr=lr, | ||
| min_lr=kwargs.get('min_lr', 0.0), | ||
| weight_decay=kwargs.get('weight_decay', 0.01), | ||
| adam_beta1=kwargs.get('adam_beta1', 0.9), | ||
| adam_beta2=kwargs.get('adam_beta2', 0.999), | ||
| adam_eps=kwargs.get('adam_eps', 1e-8), | ||
| clip_grad=kwargs.get('clip_grad', 1.0), | ||
| bf16=kwargs.get('bf16', True), | ||
| use_distributed_optimizer=use_distributed_optimizer, | ||
| overlap_param_gather=kwargs.get('overlap_param_gather', False), | ||
| log_num_zeros_in_grad=kwargs.get('log_num_zeros_in_grad', False), | ||
| **kwargs, | ||
| ) | ||
| config_sig = inspect.signature(OptimizerConfig).parameters | ||
| overlap_param_gather = kwargs.get('overlap_param_gather', False) | ||
| overlap_param_gather_with_step = kwargs.get('overlap_param_gather_with_optimizer_step', overlap_param_gather) | ||
|
|
||
| config_kwargs = { | ||
| 'optimizer': 'adam', | ||
| 'lr': lr, | ||
| 'min_lr': kwargs.get('min_lr', 0.0), | ||
| 'weight_decay': kwargs.get('weight_decay', 0.01), | ||
| 'adam_beta1': kwargs.get('adam_beta1', 0.9), | ||
| 'adam_beta2': kwargs.get('adam_beta2', 0.999), | ||
| 'adam_eps': kwargs.get('adam_eps', 1e-8), | ||
| 'clip_grad': kwargs.get('clip_grad', 1.0), | ||
| 'bf16': kwargs.get('bf16', True), | ||
| 'use_distributed_optimizer': use_distributed_optimizer, | ||
| 'log_num_zeros_in_grad': kwargs.get('log_num_zeros_in_grad', False), | ||
| } | ||
| if 'overlap_param_gather' in config_sig: | ||
| config_kwargs['overlap_param_gather'] = overlap_param_gather | ||
| if 'overlap_param_gather_with_optimizer_step' in config_sig: | ||
| config_kwargs['overlap_param_gather_with_optimizer_step'] = overlap_param_gather_with_step | ||
|
|
||
| # Keep compatibility across Megatron-Core versions by only forwarding supported args. | ||
| for key, value in kwargs.items(): | ||
| if key in config_sig and key not in config_kwargs: | ||
| config_kwargs[key] = value | ||
|
|
||
| opt_config = OptimizerConfig(**config_kwargs) | ||
|
|
||
| # Ensure each model chunk has ddp_config attached (required by Megatron optimizer) | ||
| from megatron.core.distributed import DistributedDataParallelConfig | ||
| is_npu = is_torch_npu_available() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
| model_chunks = self.model | ||
| for model_chunk in model_chunks: | ||
| assert hasattr(model_chunk, 'ddp_config') | ||
| optimizer = get_megatron_optimizer( | ||
| config=opt_config, | ||
| model_chunks=model_chunks, | ||
| use_gloo_process_groups=False if is_npu else True | ||
| ) | ||
| return optimizer | ||
|
|
||
|
|
@@ -1419,12 +1473,14 @@ def initialize(self, **kwargs) -> None: | |
| from .args import get_args | ||
| self._try_init_process_group() | ||
| args = get_args() | ||
| is_npu = is_torch_npu_available() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| init_kwargs = { | ||
| 'tensor_model_parallel_size': args.tensor_model_parallel_size, | ||
| 'pipeline_model_parallel_size': args.pipeline_model_parallel_size, | ||
| 'context_parallel_size': args.context_parallel_size, | ||
| 'virtual_pipeline_model_parallel_size': args.virtual_pipeline_model_parallel_size, | ||
| 'expert_model_parallel_size': args.expert_model_parallel_size, | ||
| 'create_gloo_process_groups': False if is_npu else True, | ||
| } | ||
|
|
||
| if args.order: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To avoid repeated calls to
is_torch_npu_available(), it's better to call it once in the initializer and store the result in an instance attribute likeself.is_npu. This attribute can then be reused in other methods of this class, such as_create_megatron_optimizerandinitialize, improving code clarity and maintainability.