-
Notifications
You must be signed in to change notification settings - Fork 343
[Feature] Hybrid Data Pipeline #495
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
pppppM
wants to merge
7
commits into
InternLM:main
Choose a base branch
from
pppppM:hybrid
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.
Open
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e097793
hybrid data pipeline
pppppM 40c2fe6
fix forward error
pppppM 5c8c265
support varlen attn
pppppM e571688
support code interpreter finetune
pppppM c4b26cb
fix code interpreter error
pppppM 8cd458c
fix lint
pppppM b5a412d
fix cuda error
pppppM 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
62 changes: 62 additions & 0 deletions
62
xtuner/configs/internlm/internlm2_chat_1_8b/hybrid/agent.json
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,62 @@ | ||
{ | ||
"messages": [ | ||
{"role": "system", "content": "You are InternLM2-Chat, a harmless AI assistant"}, | ||
{ | ||
"role": "user", | ||
"content": "Please help me process and visualize this dataset.", | ||
"files": [{"path": "data.csv", "size": "10K"}] | ||
}, | ||
{ | ||
"role": "assistant", | ||
"content": "I have processed the data and visualized it for you.", | ||
"code_interpreter_call": "```python\nimport plotly.express as px\nimport pandas as pd\n\n# Load the data into a pandas dataframe\ndf = pd.read_csv('data.csv')\n\n# Create a scatter plot of rainfall vs wind direction\nfig = px.scatter(df, x='WindDir9am', y='Rainfall', color='WindDir3pm',\n labels={'WindDir9am': 'Wind Direction 9am', 'Rainfall': '\n\nRainfall', 'WindDir3pm': 'Wind Direction 3pm'},\n title='Rainfall vs Wind Direction',\n template='plotly_dark',\n width=600, height=500)\n\n# Add a hover effect to show the date\nfig.update_traces(hovertemplate='<b>Date: %{text}</b><br>Wind Direction 9am: %{x}<br>Rainfall: %{y}<br>Wind Direction 3pm: %{marker.color}')\n\n# Show the plot\nfig.show()\n```" | ||
}, | ||
{ | ||
"role": "code_interpreter", | ||
"content": "" | ||
}, | ||
{ | ||
"role": "assistant", | ||
"content": "Since the code output is not included here, I cannot provide specific chart content. However, if the code executed correctly, it should display a polar plot with two filled areas representing the relationship between wind direction at 9 am and rainfall, and between wind direction at 3 pm and rainfall, respectively. The values for each direction are based on the average rainfall calculated from the provided dataset. The chart should have a clear title, a legend, and be intuitive for comparing rainfall with different wind directions. Given the use of a dark theme, the overall appearance of the chart should be bright lines and filled areas on a dark background." | ||
}, | ||
{ | ||
"role": "user", | ||
"content": "I want to know today's weather in Shanghai" | ||
}, | ||
{ | ||
"role": "assistant", | ||
"content": "Sure, I will search for the weather of Shanghai.", | ||
"function_call": { | ||
"name": "get_current_weather", | ||
"parameters": {"location": "Shanghai"} | ||
} | ||
}, | ||
{ | ||
"role": "function", | ||
"name": "get_current_weather", | ||
"content": "{'temperature': 22}" | ||
}, | ||
{ | ||
"role": "assistant", | ||
"content": "The weather in Shanghai is 22 celsius" | ||
} | ||
], | ||
|
||
"functions": [ | ||
{ | ||
"name": "get_current_weather", | ||
"description": "Get the current weather in a given location", | ||
"parameters": { | ||
"type": "object", | ||
"properties": { | ||
"location": { | ||
"type": "string", | ||
"description": "The city and state, e.g. San Francisco, CA", | ||
"unit": {"type": "string"}}, | ||
"required": ["location"] | ||
} | ||
} | ||
} | ||
], | ||
|
||
"code_interpreter": "You now have access to a Jupyter notebook environment supporting Python code execution. Just send code to python to run in this stateful environment. This feature is suitable for:\n- Data analysis or processing (such as data manipulation and graphic creation)\n- Complex calculations (such as math and physics problems)\n- Programming examples (for understanding programming concepts or language features)\n- Text processing and analysis (including text analysis and natural language processing)\n- Machine learning and data science (model training and data visualization)\n- File operations and data import (handling CSV, JSON, etc. formats)"} |
29 changes: 29 additions & 0 deletions
29
xtuner/configs/internlm/internlm2_chat_1_8b/hybrid/example.py
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,29 @@ | ||
import json | ||
|
||
from xtuner.types import HybridChatTemplate, TrainingHybridChatMessages | ||
|
||
|
||
chat_template = HybridChatTemplate( | ||
system='<|im_start|>system\n{system}<|im_end|>\n', | ||
user='<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n', | ||
assistant='{assistant}<|im_end|>\n', | ||
stop_words=['<|im_end|>'], | ||
image_token='<image>', | ||
files='<|im_start|>user name=file\n{files}<|im_end|>\n', | ||
function_call='{assistant}<|action_start|><|plugin|>\n{function_call}<|action_end|><|im_end|>\n', # noqa: E501, E251 | ||
function_result='<|im_start|>environment name=<|plugin|>\n{function_result}<|im_end|>\n<|im_start|>assistant\n', # noqa: E501, E251 | ||
functions='<|im_start|>system name=<|plugin|>\n{functions}<|im_end|>\n', | ||
code_interpreter_call='{assistant}<|action_start|><|interpreter|>\n{code_interpreter_call}<|action_end|><|im_end|>\n', # noqa: E501, E251 | ||
code_interpreter_result='<|im_start|>environment name=<|interpreter|>\n{code_interpreter_result}<|im_end|>\n<|im_start|>assistant\n', # noqa: E501, E251 | ||
code_interpreter='<|im_start|>system name=<|interpreter|>\n{code_interpreter}<|im_end|>\n' | ||
|
||
) | ||
|
||
agent_data = json.load(open('agent.json')) | ||
|
||
msg = TrainingHybridChatMessages.from_dict(agent_data) | ||
print(msg.apply_chat_template(chat_template)) | ||
|
||
from transformers import AutoTokenizer | ||
tokenizer = AutoTokenizer.from_pretrained('internlm/internlm2-chat-7b', trust_remote_code=True) | ||
print(msg.tokenize(tokenizer, chat_template)) |
54 changes: 54 additions & 0 deletions
54
xtuner/configs/internlm/internlm2_chat_1_8b/hybrid/function_call.json
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,54 @@ | ||
[ | ||
{ | ||
"messages": [ | ||
{ | ||
"role": "user", | ||
"content": "I want to know today's weather in Shanghai" | ||
}, | ||
|
||
{ | ||
"role": "assistant", | ||
"content": "Sure, I will search for the weather of Shanghai.", | ||
"function_call": { | ||
"name": "get_current_weather", | ||
"parameters": { | ||
"location": "Shanghai" | ||
} | ||
} | ||
}, | ||
|
||
{ | ||
"role": "function", | ||
"name": "get_current_weather", | ||
"content": "{'temperature': 22}" | ||
}, | ||
{ | ||
"role": "assistant", | ||
"content": "The weather in Shanghai is 22 celsius" | ||
} | ||
|
||
|
||
], | ||
|
||
"functions": [ | ||
{ | ||
"name": "get_current_weather", | ||
"description": "Get the current weather in a given location", | ||
"parameters": { | ||
"type": "object", | ||
"properties": { | ||
"location": { | ||
"type": "string", | ||
"description": "The city and state, e.g. San Francisco, CA", | ||
"unit": {"type": "string"} | ||
}, | ||
"required": ["location"] | ||
} | ||
} | ||
} | ||
] | ||
} | ||
|
||
] | ||
|
||
|
201 changes: 201 additions & 0 deletions
201
xtuner/configs/internlm/internlm2_chat_1_8b/hybrid/internlm2_chat_1_8b_function_call.py
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,201 @@ | ||
# Copyright (c) OpenMMLab. All rights reserved. | ||
import torch | ||
from mmengine.dataset import DefaultSampler | ||
from mmengine.hooks import (CheckpointHook, DistSamplerSeedHook, IterTimerHook, | ||
LoggerHook, ParamSchedulerHook) | ||
from mmengine.optim import AmpOptimWrapper, CosineAnnealingLR, LinearLR | ||
from torch.optim import AdamW | ||
from transformers import AutoModelForCausalLM, AutoTokenizer | ||
|
||
from xtuner.dataset.hybrid import HybridDataset, hybrid_collate_fn | ||
from xtuner.dataset.hybrid.mappings import openai_to_raw_training | ||
from xtuner.engine.hooks import DatasetInfoHook | ||
from xtuner.engine.runner import TrainLoop | ||
from xtuner.model import HybridFinetune | ||
from xtuner.types import HybridChatTemplate | ||
|
||
####################################################################### | ||
# PART 1 Settings # | ||
####################################################################### | ||
# Model | ||
llm_name_or_path = '/mnt/petrelfs/share_data/linzhihao/model/models--internlm--internlm2-chat-7b/snapshots/2292b86b21cb856642782cebed0a453997453b1f/' | ||
visual_encoder_name_or_path = 'openai/clip-vit-large-patch14-336' | ||
# Specify the pretrained pth | ||
pretrained_pth = None | ||
# Data | ||
data_dir = './' | ||
data_files = ['function_call.json'] | ||
max_length = 2048 | ||
|
||
# Chat Template | ||
chat_template = dict( | ||
type=HybridChatTemplate, | ||
system='<|im_start|>system\n{system}<|im_end|>\n', | ||
user='<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n', | ||
assistant='{assistant}<|im_end|>\n', | ||
stop_words=['<|im_end|>'], | ||
image_token='<image>', | ||
function_call= | ||
'{assistant}<|action_start|><|plugin|>\n{function_call}<|action_end|><|im_end|>\n', # noqa: E501, E251 | ||
function_result= | ||
'<|im_start|>environment name=<|plugin|>\n{function_result}<|im_end|>\n<|im_start|>assistant\n', # noqa: E501, E251 | ||
functions='<|im_start|>system name=<|plugin|>\n{functions}<|im_end|>\n') | ||
|
||
# Scheduler & Optimizer | ||
batch_size = 1 # per_device | ||
accumulative_counts = 1 | ||
dataloader_num_workers = 0 | ||
max_epochs = 1 | ||
optim_type = AdamW | ||
lr = 2e-4 | ||
betas = (0.9, 0.999) | ||
weight_decay = 0 | ||
max_norm = 1 # grad clip | ||
warmup_ratio = 0.03 | ||
|
||
# Save | ||
save_steps = 500 | ||
save_total_limit = 2 # Maximum checkpoints to keep (-1 means unlimited) | ||
|
||
# Evaluate the generation performance during the training | ||
evaluation_freq = 500 | ||
SYSTEM = '' | ||
evaluation_images = 'https://llava-vl.github.io/static/images/view.jpg' | ||
evaluation_inputs = ['请描述一下这张照片', 'Please describe this picture'] | ||
|
||
####################################################################### | ||
# PART 2 Model & Tokenizer & Image Processor # | ||
####################################################################### | ||
tokenizer = dict( | ||
type=AutoTokenizer.from_pretrained, | ||
pretrained_model_name_or_path=llm_name_or_path, | ||
trust_remote_code=True, | ||
padding_side='right') | ||
|
||
model = dict( | ||
type=HybridFinetune, | ||
llm=dict( | ||
type=AutoModelForCausalLM.from_pretrained, | ||
pretrained_model_name_or_path=llm_name_or_path, | ||
trust_remote_code=True, | ||
torch_dtype=torch.float16)) | ||
|
||
####################################################################### | ||
# PART 3 Dataset & Dataloader # | ||
####################################################################### | ||
llava_dataset = dict( | ||
type=HybridDataset, | ||
data_dir=data_dir, | ||
data_files=data_files, | ||
sample_ratio=1, | ||
tokenizer=tokenizer, | ||
chat_template=chat_template, | ||
max_length=max_length, | ||
pack_to_max_length=True, | ||
num_workers=dataloader_num_workers, | ||
mappings=[openai_to_raw_training]) | ||
|
||
train_dataloader = dict( | ||
batch_size=batch_size, | ||
num_workers=dataloader_num_workers, | ||
dataset=llava_dataset, | ||
sampler=dict(type=DefaultSampler, shuffle=True), | ||
collate_fn=dict(type=hybrid_collate_fn)) | ||
|
||
####################################################################### | ||
# PART 4 Scheduler & Optimizer # | ||
####################################################################### | ||
# optimizer | ||
optim_wrapper = dict( | ||
type=AmpOptimWrapper, | ||
optimizer=dict( | ||
type=optim_type, lr=lr, betas=betas, weight_decay=weight_decay), | ||
clip_grad=dict(max_norm=max_norm, error_if_nonfinite=False), | ||
accumulative_counts=accumulative_counts, | ||
loss_scale='dynamic', | ||
dtype='float16') | ||
|
||
# learning policy | ||
# More information: https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/param_scheduler.md # noqa: E501 | ||
param_scheduler = [ | ||
dict( | ||
type=LinearLR, | ||
start_factor=1e-5, | ||
by_epoch=True, | ||
begin=0, | ||
end=warmup_ratio * max_epochs, | ||
convert_to_iter_based=True), | ||
dict( | ||
type=CosineAnnealingLR, | ||
eta_min=0.0, | ||
by_epoch=True, | ||
begin=warmup_ratio * max_epochs, | ||
end=max_epochs, | ||
convert_to_iter_based=True) | ||
] | ||
|
||
# train, val, test setting | ||
train_cfg = dict(type=TrainLoop, max_epochs=max_epochs) | ||
|
||
####################################################################### | ||
# PART 5 Runtime # | ||
####################################################################### | ||
# Log the dialogue periodically during the training process, optional | ||
custom_hooks = [ | ||
dict(type=DatasetInfoHook, tokenizer=tokenizer), | ||
# dict( | ||
# type=EvaluateChatHook, | ||
# tokenizer=tokenizer, | ||
# image_processor=image_processor, | ||
# every_n_iters=evaluation_freq, | ||
# evaluation_inputs=evaluation_inputs, | ||
# evaluation_images=evaluation_images, | ||
# system=SYSTEM, | ||
# prompt_template=prompt_template) | ||
] | ||
|
||
# configure default hooks | ||
default_hooks = dict( | ||
# record the time of every iteration. | ||
timer=dict(type=IterTimerHook), | ||
# print log every 10 iterations. | ||
logger=dict(type=LoggerHook, log_metric_by_epoch=False, interval=10), | ||
# enable the parameter scheduler. | ||
param_scheduler=dict(type=ParamSchedulerHook), | ||
# save checkpoint per `save_steps`. | ||
checkpoint=dict( | ||
type=CheckpointHook, | ||
by_epoch=False, | ||
interval=save_steps, | ||
max_keep_ckpts=save_total_limit), | ||
# set sampler seed in distributed evrionment. | ||
sampler_seed=dict(type=DistSamplerSeedHook), | ||
) | ||
|
||
# configure environment | ||
env_cfg = dict( | ||
# whether to enable cudnn benchmark | ||
cudnn_benchmark=False, | ||
# set multi process parameters | ||
mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), | ||
# set distributed parameters | ||
dist_cfg=dict(backend='nccl'), | ||
) | ||
|
||
# set visualizer | ||
visualizer = None | ||
|
||
# set log level | ||
log_level = 'INFO' | ||
|
||
# load from which checkpoint | ||
load_from = None | ||
|
||
# whether to resume training from the loaded checkpoint | ||
resume = False | ||
|
||
# Defaults to use random seed and disable `deterministic` | ||
randomness = dict(seed=None, deterministic=False) | ||
|
||
# set log processor | ||
log_processor = dict(by_epoch=False) |
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.
这个名字有点奇怪,要不叫做 HybridFinetuneModel,不过还有一个疑问,如果直接写了 finetune,用户会不会以为只能 finetune model 而不能 pretrain model?