-
Notifications
You must be signed in to change notification settings - Fork 281
Add sentence_augmentation_mapper #401
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
Closed
Qirui-jiao
wants to merge
6
commits into
modelscope:main
from
Qirui-jiao:sentence_augmentation_mapper
Closed
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
3808fc4
upload sentence_augmentation_mapper
Qirui-jiao ee80af9
Merge branch 'modelscope:main' into sentence_augmentation_mapper
Qirui-jiao cc88377
update
Qirui-jiao 255ceb7
update
Qirui-jiao 5496ad8
Update test_sentence_augmentation_mapper.py
Qirui-jiao 54c98bf
Merge branch 'main' into sentence_augmentation_mapper
Qirui-jiao 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 |
---|---|---|
@@ -0,0 +1,138 @@ | ||
import torch | ||
|
||
from data_juicer.ops.base_op import OPERATORS, Mapper | ||
from data_juicer.utils.model_utils import get_model, prepare_model | ||
|
||
DEFAULT_SYSTEM_PROMPT = "A chat between a curious user and an artificial \ | ||
intelligence assistant. The assistant gives helpful, detailed, and \ | ||
polite answers to the user's questions." | ||
|
||
OP_NAME = 'sentence_augmentation_mapper' | ||
|
||
|
||
@OPERATORS.register_module(OP_NAME) | ||
class SentenceAugmentationMapper(Mapper): | ||
"""Mapper to optimize instruction. | ||
Recommended model list: [ | ||
lmsys/vicuna-13b-v1.5 | ||
Qwen/Qwen2-7B-Instruct | ||
] | ||
""" | ||
_accelerator = 'cuda' | ||
|
||
def __init__(self, | ||
hf_model: str = 'Qwen/Qwen2-7B-Instruct', | ||
system_prompt: str = None, | ||
task_sentence: str = None, | ||
max_new_tokens=256, | ||
temperature=0.2, | ||
top_p=None, | ||
num_beams=1, | ||
*args, | ||
**kwargs): | ||
""" | ||
Initialization method. | ||
:param hf_model: Hugginface model id. | ||
:param system_prompt: System prompt. | ||
:param task_sentence: The instruction for the current task. | ||
:param max_new_tokens: the maximum number of new tokens | ||
generated by the model. | ||
:param temperature: used to control the randomness of \ | ||
generated text. The higher the temperature, the more \ | ||
random and creative the generated text will be. | ||
:param top_p: randomly select the next word from the group \ | ||
of words whose cumulative probability reaches p. | ||
:param num_beams: the larger the beam search size, the higher \ | ||
the quality of the generated text. | ||
:param args: extra args | ||
:param kwargs: extra args | ||
""" | ||
super().__init__(*args, num_proc=1, **kwargs) | ||
|
||
if system_prompt is None: | ||
system_prompt = DEFAULT_SYSTEM_PROMPT | ||
self.system_prompt = system_prompt | ||
self.hf_model = hf_model | ||
self.max_new_tokens = max_new_tokens | ||
|
||
self.model_key = prepare_model(model_type='huggingface', | ||
pretrained_model_name_or_path=hf_model) | ||
self.temperature = temperature | ||
self.top_p = top_p | ||
self.num_beams = num_beams | ||
self.task_sentence = task_sentence | ||
|
||
def process(self, sample=None, rank=None): | ||
|
||
if 'vicuna' in self.hf_model: | ||
Qirui-jiao marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if torch.cuda.is_available(): | ||
model, processor = get_model(self.model_key, | ||
rank=rank, | ||
use_cuda=True) | ||
else: | ||
model, processor = get_model(self.model_key, rank=rank) | ||
|
||
Qirui-jiao marked this conversation as resolved.
Show resolved
Hide resolved
|
||
input_prompt = self.system_prompt + " USER: Here \ | ||
is a sentence: \"" + sample[ | ||
self.text_key] + "\". " + self.task_sentence | ||
Qirui-jiao marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
inputs = processor(input_prompt, | ||
return_tensors='pt').to(model.device) | ||
response = model.generate(**inputs, | ||
max_new_tokens=self.max_new_tokens, | ||
eos_token_id=processor.eos_token_id, | ||
top_p=self.top_p, | ||
temperature=self.temperature, | ||
num_beams=self.num_beams) | ||
input_token_len = inputs.input_ids.shape[1] | ||
n_diff_input_output = (inputs.input_ids != | ||
response[:, :input_token_len]).sum().item() | ||
if n_diff_input_output > 0: | ||
print(f'[Warning] {n_diff_input_output} output_ids are \ | ||
not the same as the input_ids') | ||
output = processor.batch_decode(response[:, input_token_len:], | ||
skip_special_tokens=True)[0] | ||
output = output.strip().strip("\"") | ||
|
||
else: | ||
if torch.cuda.is_available(): | ||
model, processor = get_model(self.model_key, | ||
rank=rank, | ||
use_cuda=True) | ||
else: | ||
model, processor = get_model(self.model_key, rank=rank) | ||
|
||
messages = [{ | ||
'role': 'system', | ||
'content': self.system_prompt | ||
}, { | ||
'role': | ||
'user', | ||
'content': | ||
"Here is a sentence: \"" + sample[self.text_key] + "\". " + | ||
self.task_sentence | ||
}] | ||
input_prompt = processor.apply_chat_template( | ||
messages, tokenize=False, add_generation_prompt=True) | ||
|
||
inputs = processor(input_prompt, | ||
return_tensors='pt').to(model.device) | ||
response = model.generate(**inputs, | ||
max_new_tokens=self.max_new_tokens, | ||
eos_token_id=processor.eos_token_id, | ||
top_p=self.top_p, | ||
temperature=self.temperature, | ||
num_beams=self.num_beams) | ||
input_token_len = inputs.input_ids.shape[1] | ||
n_diff_input_output = (inputs.input_ids != | ||
response[:, :input_token_len]).sum().item() | ||
if n_diff_input_output > 0: | ||
Qirui-jiao marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
print(f'[Warning] {n_diff_input_output} output_ids are not \ | ||
the same as the input_ids') | ||
output = processor.batch_decode(response[:, input_token_len:], | ||
skip_special_tokens=True)[0] | ||
output = output.strip().strip("\"") | ||
|
||
sample[self.text_key] = output | ||
|
||
return sample |
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,37 @@ | ||
import unittest | ||
from data_juicer.ops.mapper.sentence_augmentation_mapper import SentenceAugmentationMapper | ||
from data_juicer.utils.unittest_utils import (SKIPPED_TESTS, | ||
DataJuicerTestCaseBase) | ||
|
||
# These tests have been tested locally. | ||
@SKIPPED_TESTS.register_module() | ||
class SentenceAugmentationMapperTest(DataJuicerTestCaseBase): | ||
|
||
text_key = 'text' | ||
|
||
def _run_sentence_augmentation_mapper(self): | ||
op = SentenceAugmentationMapper( | ||
hf_model='Qwen2-7B-Instruct', | ||
task_sentence="Please replace one entity in this sentence with another entity, such as an animal, a vehicle, or a piece of furniture. Please only answer with the replaced sentence. ASSISTANT:", | ||
max_new_tokens=512, | ||
temperature=0.9, | ||
top_p=0.95, | ||
num_beams=1, | ||
) | ||
|
||
samples = [ | ||
{self.text_key: 'a book is near a cat and a dog'} | ||
] | ||
|
||
for sample in samples: | ||
result = op.process(sample) | ||
print(f'Output results: {result}') | ||
self.assertIn(self.text_key, result) | ||
Qirui-jiao marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
def test_sentence_augmentation_mapper(self): | ||
self._run_sentence_augmentation_mapper() | ||
|
||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
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.
Uh oh!
There was an error while loading. Please reload this page.