Skip to content
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

[Feature] Hybrid Data Pipeline #495

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
62 changes: 62 additions & 0 deletions xtuner/configs/internlm/internlm2_chat_1_8b/hybrid/agent.json
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": "![image](xxx.png)"
},
{
"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)"}
33 changes: 33 additions & 0 deletions xtuner/configs/internlm/internlm2_chat_1_8b/hybrid/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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))
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
[
{
"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"]
}
}
}
]
}

]
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# 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 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 AgentFinetune, AutoModelForCausalLM
from xtuner.types import HybridChatTemplate

#######################################################################
# PART 1 Settings #
#######################################################################
# Model
llm_name_or_path = '/mnt/petrelfs/share_data/basemodel/checkpoints/llm/hf_hub/models--internlm--internlm2-chat-1_8b/snapshots/aa8a7450c2227a3b6733b3c6fe33fefbb2ca54f9/'

# Data
data_dir = './'
data_files = ['agentlego.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)

#######################################################################
# 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=AgentFinetune,
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 #
#######################################################################
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=4,
mappings=[openai_to_raw_training])

train_dataloader = dict(
batch_size=batch_size,
num_workers=dataloader_num_workers,
dataset=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)