-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[WIP] [megatron] support megatron embedding/reranker #7630
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
Open
Jintao-Huang
wants to merge
8
commits into
modelscope:main
Choose a base branch
from
Jintao-Huang:support_megatron_embedding/reranker
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.
+214
−18
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
df6d953
support megatron embedding/reranker
Jintao-Huang 834f90e
update
Jintao-Huang 7eac8e0
update
Jintao-Huang 6ed4f97
update
Jintao-Huang 744a0b1
update
Jintao-Huang 52aa5ba
update
Jintao-Huang e3cbe89
update
Jintao-Huang f52aa1a
Merge branch 'main' into support_megatron_embedding/reranker
Jintao-Huang 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
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 |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # Copyright (c) ModelScope Contributors. All rights reserved. | ||
|
|
||
| import megatron.core | ||
| from packaging import version | ||
|
|
||
| from swift.model import ModelType | ||
| from ..constant import MegatronModelType | ||
| from ..gpt_bridge import GPTBridge | ||
| from ..register import MegatronModelMeta, register_megatron_model | ||
|
|
||
|
|
||
| class Qwen3EmbBridge(GPTBridge): | ||
|
|
||
| def _convert_hf_state_dict(self, hf_state_dict, to_mcore): | ||
| res = super()._convert_hf_state_dict(hf_state_dict, to_mcore) | ||
| if to_mcore: | ||
| res = self._add_prefix(res, 'model.') | ||
| elif not to_mcore: | ||
| res = self._remove_prefix(res, 'model.') | ||
| return res | ||
|
|
||
|
|
||
| register_megatron_model( | ||
| MegatronModelMeta( | ||
| MegatronModelType.qwen3_emb, | ||
| [ | ||
| ModelType.qwen3_emb, | ||
| ], | ||
| bridge_cls=Qwen3EmbBridge, | ||
| )) |
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
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 |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # Copyright (c) ModelScope Contributors. All rights reserved. | ||
| from functools import partial | ||
|
|
||
| import torch.nn | ||
| from megatron.training import get_args, get_timers | ||
|
|
||
| from swift.loss import loss_map | ||
| from swift.utils import get_logger | ||
| from .base import BaseMegatronTrainer | ||
|
|
||
| logger = get_logger() | ||
|
|
||
|
|
||
| class MegatronEmbeddingTrainer(BaseMegatronTrainer): | ||
|
|
||
| def __init__(self, args, template): | ||
| super().__init__(args, template) | ||
| if not args.padding_free: | ||
| raise ValueError('Currently, task_type embedding only supports padding_free.') | ||
| self._loss_func = loss_map[self.args.loss_type](args, self) | ||
|
|
||
| def loss_func(self, output_tensor: torch.Tensor, *, labels: torch.Tensor, packed_seq_params=None): | ||
| args = self.args | ||
| last_hidden_state = self.get_last_tokens(output_tensor, packed_seq_params) | ||
| loss = self._loss_func({'last_hidden_state': last_hidden_state}, labels) | ||
| metric = {'loss': loss.detach().clone()} | ||
| metric = self._all_reduce_metric(metric) | ||
| return loss, metric | ||
|
|
||
| def forward_step(self, data_iterator, model): | ||
| timers = get_timers() | ||
|
|
||
| # Get the batch. | ||
| vp_stage = model.module.module.vp_stage | ||
| timers('batch-generator', log_level=2).start() | ||
| with self.stimer(bdata=True): | ||
| data = self.get_batch(data_iterator, vp_stage) | ||
| timers('batch-generator').stop() | ||
| labels = data.get('labels') | ||
| if self.args.task_type == 'seq_cls': | ||
| data.pop('labels', None) | ||
| with self.stimer: | ||
| output_tensor = model(**data) | ||
| packed_seq_params = data.get('packed_seq_params') | ||
| loss_func = partial(self.loss_func, labels=labels, packed_seq_params=packed_seq_params) | ||
| return output_tensor, loss_func |
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 |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # Copyright (c) ModelScope Contributors. All rights reserved. | ||
| import torch.nn | ||
| from megatron.training import get_args, get_timers | ||
|
|
||
| from swift.utils import get_logger | ||
| from .base import BaseMegatronTrainer | ||
|
|
||
| logger = get_logger() | ||
|
|
||
|
|
||
| class MegatronRerankerTrainer(BaseMegatronTrainer): | ||
|
|
||
| def loss_func(self, output_tensor: torch.Tensor, *, labels: torch.Tensor, packed_seq_params=None): | ||
| pass | ||
|
|
||
| def forward_step(self, data_iterator, model): | ||
| timers = get_timers() | ||
|
|
||
| # Get the batch. | ||
| vp_stage = model.module.module.vp_stage | ||
| timers('batch-generator', log_level=2).start() | ||
| with self.stimer(bdata=True): | ||
| data = self.get_batch(data_iterator, vp_stage) | ||
| timers('batch-generator').stop() | ||
| labels = data.get('labels') | ||
| if self.args.task_type == 'seq_cls': | ||
| data.pop('labels', None) | ||
| with self.stimer: | ||
| output_tensor = model(**data) | ||
| packed_seq_params = data.get('packed_seq_params') |
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
File renamed without changes.
File renamed without changes.
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 |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import os | ||
|
|
||
| os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' | ||
|
|
||
|
|
||
| def test_embedding(): | ||
| from swift.megatron import megatron_sft_main, MegatronSftArguments | ||
| megatron_sft_main( | ||
| MegatronSftArguments( | ||
| model='Qwen/Qwen3-Embedding-0.6B', | ||
| task_type='embedding', | ||
| dataset=['sentence-transformers/stsb:positive'], | ||
| split_dataset_ratio=0.01, | ||
| tensor_model_parallel_size=2, | ||
| tuner_type='lora', | ||
| recompute_granularity='full', | ||
| recompute_method='uniform', | ||
| recompute_num_layers=1, | ||
| loss_type='infonce', | ||
| attn_impl='flash_attn', | ||
| max_length=2048, | ||
| eval_iters=5, | ||
| save_interval=5, | ||
| no_save_optim=True, | ||
| no_save_rng=True, | ||
| sequence_parallel=True, | ||
| finetune=True)) | ||
|
|
||
|
|
||
| def test_reranker(): | ||
| from swift.megatron import megatron_sft_main, MegatronSftArguments | ||
| megatron_sft_main( | ||
| MegatronSftArguments( | ||
| model='Qwen/Qwen3-Reranker-4B', | ||
| tuner_type='lora', | ||
| load_from_cache_file=True, | ||
| task_type='generative_reranker', | ||
| dataset=['MTEB/scidocs-reranking#10000'], | ||
| loss_type='pointwise_reranker', | ||
| split_dataset_ratio=0.01, | ||
| tensor_model_parallel_size=2, | ||
| recompute_granularity='full', | ||
| recompute_method='uniform', | ||
| recompute_num_layers=1, | ||
| train_iters=100, | ||
| eval_iters=5, | ||
| save_interval=5, | ||
| no_save_optim=True, | ||
| no_save_rng=True, | ||
| sequence_parallel=True, | ||
| finetune=True)) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| test_embedding() | ||
|
Comment on lines
+54
to
+55
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. |
||
| # test_reranker() | ||
Oops, something went wrong.
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.
The import statement
from swift.megatron import megatron_sft_main, MegatronSftArgumentsis repeated in bothtest_embedding(line 7) andtest_reranker(line 31). To follow the DRY (Don't Repeat Yourself) principle and improve code clarity, it's recommended to move this import to the top of the file, outside of the test functions.