Add files using upload-large-folder tool
Browse files- examples/app/mllm.sh +13 -0
- examples/custom/dataset.py +30 -0
- examples/custom/infer.sh +9 -0
- examples/custom/model.py +35 -0
- examples/custom/model_hf.py +59 -0
- examples/custom/sft.sh +26 -0
- examples/deploy/README.md +9 -0
- examples/deploy/sglang.sh +18 -0
- examples/deploy/vllm.sh +14 -0
- examples/deploy/vllm_dp.sh +22 -0
- examples/export/merge_lora.sh +5 -0
- examples/export/ollama.sh +4 -0
- examples/export/push_to_hub.sh +6 -0
- examples/infer/cli_demo.sh +6 -0
- examples/infer/demo.py +57 -0
- examples/infer/demo_agent.py +114 -0
- examples/infer/demo_bert.py +55 -0
- examples/infer/demo_embedding.py +64 -0
- examples/infer/demo_grounding.py +45 -0
- examples/infer/demo_hf.py +66 -0
- examples/infer/demo_lora.py +70 -0
- examples/infer/demo_mllm.py +145 -0
- examples/infer/demo_reranker.py +55 -0
- examples/infer/demo_reward_model.py +31 -0
- examples/infer/demo_vllm_reasoning_parser.py +85 -0
- examples/infer/lmdeploy/batch_ddp.sh +8 -0
- examples/infer/lmdeploy/mllm_tp.sh +8 -0
- examples/infer/transformers/mllm_device_map.sh +9 -0
- examples/infer/vllm/dp_tp.sh +11 -0
- examples/infer/vllm/mllm_ddp.sh +11 -0
- examples/infer/vllm/mllm_tp.sh +11 -0
- examples/infer/vllm/mtp.sh +10 -0
- examples/megatron/base_to_chat.sh +32 -0
- examples/megatron/long_text.sh +36 -0
- examples/megatron/muon.sh +36 -0
- examples/megatron/pretrain.sh +30 -0
- examples/megatron/sft.sh +33 -0
- examples/train/infer.sh +8 -0
- examples/train/lora_sft.sh +30 -0
- examples/train/on_policy_distillation.sh +41 -0
examples/app/mllm.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
MAX_PIXELS=1003520 \
|
| 3 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 4 |
+
FPS_MAX_FRAMES=12 \
|
| 5 |
+
swift app \
|
| 6 |
+
--model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 7 |
+
--stream true \
|
| 8 |
+
--infer_backend vllm \
|
| 9 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 10 |
+
--vllm_max_model_len 8192 \
|
| 11 |
+
--max_new_tokens 2048 \
|
| 12 |
+
--vllm_limit_mm_per_prompt '{"image": 5, "video": 2}' \
|
| 13 |
+
--lang zh
|
examples/custom/dataset.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
from typing import Any, Dict, Optional
|
| 3 |
+
|
| 4 |
+
from swift.dataset import DatasetMeta, ResponsePreprocessor, load_dataset, register_dataset
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CustomPreprocessor(ResponsePreprocessor):
|
| 8 |
+
prompt = """Task: Based on the given two sentences, provide a similarity score between 0.0 and 5.0.
|
| 9 |
+
Sentence 1: {text1}
|
| 10 |
+
Sentence 2: {text2}
|
| 11 |
+
Similarity score: """
|
| 12 |
+
|
| 13 |
+
def preprocess(self, row: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 14 |
+
return super().preprocess({
|
| 15 |
+
'query': self.prompt.format(text1=row['text1'], text2=row['text2']),
|
| 16 |
+
'response': f"{row['label']:.1f}"
|
| 17 |
+
})
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
register_dataset(
|
| 21 |
+
DatasetMeta(
|
| 22 |
+
ms_dataset_id='swift/stsb',
|
| 23 |
+
hf_dataset_id='SetFit/stsb',
|
| 24 |
+
preprocess_func=CustomPreprocessor(),
|
| 25 |
+
))
|
| 26 |
+
|
| 27 |
+
if __name__ == '__main__':
|
| 28 |
+
dataset = load_dataset(['swift/stsb'])[0]
|
| 29 |
+
print(f'dataset: {dataset}')
|
| 30 |
+
print(f'dataset[0]: {dataset[0]}')
|
examples/custom/infer.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sh examples/custom/infer.sh
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 3 |
+
swift infer \
|
| 4 |
+
--adapters output/vx-xxx/checkpoint-xxx \
|
| 5 |
+
--load_data_args true \
|
| 6 |
+
--infer_backend transformers \
|
| 7 |
+
--max_batch_size 16 \
|
| 8 |
+
--max_new_tokens 256 \
|
| 9 |
+
--temperature 0
|
examples/custom/model.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
from swift.infer_engine import InferRequest, RequestConfig, TransformersEngine
|
| 3 |
+
from swift.model import Model, ModelGroup, ModelMeta, register_model
|
| 4 |
+
from swift.template import TemplateMeta, register_template
|
| 5 |
+
|
| 6 |
+
register_template(
|
| 7 |
+
TemplateMeta(
|
| 8 |
+
template_type='custom',
|
| 9 |
+
prefix=['<extra_id_0>System\n{{SYSTEM}}\n'],
|
| 10 |
+
prompt=['<extra_id_1>User\n{{QUERY}}\n<extra_id_1>Assistant\n'],
|
| 11 |
+
chat_sep=['\n']))
|
| 12 |
+
|
| 13 |
+
register_model(
|
| 14 |
+
ModelMeta(
|
| 15 |
+
model_type='custom',
|
| 16 |
+
model_groups=[
|
| 17 |
+
ModelGroup([Model('AI-ModelScope/Nemotron-Mini-4B-Instruct', 'nvidia/Nemotron-Mini-4B-Instruct')])
|
| 18 |
+
],
|
| 19 |
+
template='custom',
|
| 20 |
+
ignore_patterns=['nemo'],
|
| 21 |
+
is_multimodal=False,
|
| 22 |
+
))
|
| 23 |
+
|
| 24 |
+
if __name__ == '__main__':
|
| 25 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}])
|
| 26 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 27 |
+
engine = TransformersEngine('AI-ModelScope/Nemotron-Mini-4B-Instruct')
|
| 28 |
+
response = engine.infer([infer_request], request_config)
|
| 29 |
+
swift_response = response[0].choices[0].message.content
|
| 30 |
+
|
| 31 |
+
engine.template.template_backend = 'jinja'
|
| 32 |
+
response = engine.infer([infer_request], request_config)
|
| 33 |
+
jinja_response = response[0].choices[0].message.content
|
| 34 |
+
assert swift_response == jinja_response, f'swift_response: {swift_response}\njinja_response: {jinja_response}'
|
| 35 |
+
print(f'response: {swift_response}')
|
examples/custom/model_hf.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
"""
|
| 3 |
+
Here is another way to register the model, by customizing the get_function.
|
| 4 |
+
|
| 5 |
+
The get_function just needs to return the model + tokenizer/processor.
|
| 6 |
+
"""
|
| 7 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig, PreTrainedModel
|
| 8 |
+
|
| 9 |
+
from swift.infer_engine import InferRequest, RequestConfig, TransformersEngine
|
| 10 |
+
from swift.model import Model, ModelGroup, ModelLoader, ModelMeta, register_model
|
| 11 |
+
from swift.template import TemplateMeta, register_template
|
| 12 |
+
from swift.utils import Processor
|
| 13 |
+
|
| 14 |
+
register_template(
|
| 15 |
+
TemplateMeta(
|
| 16 |
+
template_type='custom',
|
| 17 |
+
prefix=['<extra_id_0>System\n{{SYSTEM}}\n'],
|
| 18 |
+
prompt=['<extra_id_1>User\n{{QUERY}}\n<extra_id_1>Assistant\n'],
|
| 19 |
+
chat_sep=['\n']))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class MyModelLoader(ModelLoader):
|
| 23 |
+
|
| 24 |
+
def get_config(self, model_dir: str) -> PretrainedConfig:
|
| 25 |
+
return AutoConfig.from_pretrained(model_dir, trust_remote_code=True)
|
| 26 |
+
|
| 27 |
+
def get_processor(self, model_dir: str, config: PretrainedConfig) -> Processor:
|
| 28 |
+
return AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
| 29 |
+
|
| 30 |
+
def get_model(self, model_dir: str, config: PretrainedConfig, processor: Processor,
|
| 31 |
+
model_kwargs) -> PreTrainedModel:
|
| 32 |
+
return AutoModelForCausalLM.from_pretrained(
|
| 33 |
+
model_dir, config=config, torch_dtype=self.torch_dtype, trust_remote_code=True, **model_kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
register_model(
|
| 37 |
+
ModelMeta(
|
| 38 |
+
model_type='custom',
|
| 39 |
+
model_groups=[
|
| 40 |
+
ModelGroup([Model('AI-ModelScope/Nemotron-Mini-4B-Instruct', 'nvidia/Nemotron-Mini-4B-Instruct')])
|
| 41 |
+
],
|
| 42 |
+
loader=MyModelLoader,
|
| 43 |
+
template='custom',
|
| 44 |
+
ignore_patterns=['nemo'],
|
| 45 |
+
is_multimodal=False,
|
| 46 |
+
))
|
| 47 |
+
|
| 48 |
+
if __name__ == '__main__':
|
| 49 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}])
|
| 50 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 51 |
+
engine = TransformersEngine('AI-ModelScope/Nemotron-Mini-4B-Instruct')
|
| 52 |
+
response = engine.infer([infer_request], request_config)
|
| 53 |
+
swift_response = response[0].choices[0].message.content
|
| 54 |
+
|
| 55 |
+
engine.template.template_backend = 'jinja'
|
| 56 |
+
response = engine.infer([infer_request], request_config)
|
| 57 |
+
jinja_response = response[0].choices[0].message.content
|
| 58 |
+
assert swift_response == jinja_response, f'swift_response: {swift_response}\njinja_response: {jinja_response}'
|
| 59 |
+
print(f'response: {swift_response}')
|
examples/custom/sft.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sh examples/custom/sft.sh
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 3 |
+
swift sft \
|
| 4 |
+
--external_plugins examples/custom/dataset.py \
|
| 5 |
+
examples/custom/model.py \
|
| 6 |
+
--model AI-ModelScope/Nemotron-Mini-4B-Instruct \
|
| 7 |
+
--tuner_type lora \
|
| 8 |
+
--dataset swift/stsb \
|
| 9 |
+
--split_dataset_ratio 0.01 \
|
| 10 |
+
--num_train_epochs 3 \
|
| 11 |
+
--per_device_train_batch_size 1 \
|
| 12 |
+
--per_device_eval_batch_size 1 \
|
| 13 |
+
--learning_rate 1e-4 \
|
| 14 |
+
--lora_rank 8 \
|
| 15 |
+
--lora_alpha 32 \
|
| 16 |
+
--target_modules all-linear \
|
| 17 |
+
--gradient_accumulation_steps 16 \
|
| 18 |
+
--eval_steps 100 \
|
| 19 |
+
--save_steps 100 \
|
| 20 |
+
--save_total_limit 2 \
|
| 21 |
+
--logging_steps 5 \
|
| 22 |
+
--warmup_ratio 0.05 \
|
| 23 |
+
--dataloader_num_workers 4 \
|
| 24 |
+
--max_length 2048 \
|
| 25 |
+
--output_dir output \
|
| 26 |
+
--dataset_num_proc 4
|
examples/deploy/README.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please refer to the examples in [examples/infer](../../infer/) and change `swift infer` to `swift deploy` to start the service. (You need to additionally remove `--val_dataset`)
|
| 2 |
+
|
| 3 |
+
e.g.
|
| 4 |
+
```shell
|
| 5 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 6 |
+
swift deploy \
|
| 7 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 8 |
+
--infer_backend vllm
|
| 9 |
+
```
|
examples/deploy/sglang.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 2 |
+
swift deploy \
|
| 3 |
+
--model Qwen/Qwen3-8B \
|
| 4 |
+
--infer_backend sglang \
|
| 5 |
+
--max_new_tokens 2048 \
|
| 6 |
+
--sglang_context_length 8192 \
|
| 7 |
+
--sglang_tp_size 2 \
|
| 8 |
+
--served_model_name Qwen3-8B
|
| 9 |
+
|
| 10 |
+
# After the server-side deployment above is successful, use the command below to perform a client call test.
|
| 11 |
+
|
| 12 |
+
# curl http://localhost:8000/v1/chat/completions \
|
| 13 |
+
# -H "Content-Type: application/json" \
|
| 14 |
+
# -d '{
|
| 15 |
+
# "model": "Qwen3-8B",
|
| 16 |
+
# "messages": [{"role": "user", "content": "What is your name?"}],
|
| 17 |
+
# "temperature": 0
|
| 18 |
+
# }'
|
examples/deploy/vllm.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 2 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 3 |
+
--infer_backend vllm \
|
| 4 |
+
--served_model_name Qwen2.5-7B-Instruct
|
| 5 |
+
|
| 6 |
+
# After the server-side deployment above is successful, use the command below to perform a client call test.
|
| 7 |
+
|
| 8 |
+
# curl http://localhost:8000/v1/chat/completions \
|
| 9 |
+
# -H "Content-Type: application/json" \
|
| 10 |
+
# -d '{
|
| 11 |
+
# "model": "Qwen2.5-7B-Instruct",
|
| 12 |
+
# "messages": [{"role": "user", "content": "What is your name?"}],
|
| 13 |
+
# "temperature": 0
|
| 14 |
+
# }'
|
examples/deploy/vllm_dp.sh
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0,1 swift deploy \
|
| 2 |
+
--model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 3 |
+
--infer_backend vllm \
|
| 4 |
+
--served_model_name Qwen2.5-VL-7B-Instruct \
|
| 5 |
+
--vllm_max_model_len 8192 \
|
| 6 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 7 |
+
--vllm_data_parallel_size 2
|
| 8 |
+
|
| 9 |
+
# After the server-side deployment above is successful, use the command below to perform a client call test.
|
| 10 |
+
|
| 11 |
+
# curl http://localhost:8000/v1/chat/completions \
|
| 12 |
+
# -H "Content-Type: application/json" \
|
| 13 |
+
# -d '{
|
| 14 |
+
# "model": "Qwen2.5-VL-7B-Instruct",
|
| 15 |
+
# "messages": [{"role": "user", "content": [
|
| 16 |
+
# {"type": "image", "image": "http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png"},
|
| 17 |
+
# {"type": "image", "image": "http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png"},
|
| 18 |
+
# {"type": "text", "text": "What is the difference between the two images?"}
|
| 19 |
+
# ]}],
|
| 20 |
+
# "max_tokens": 256,
|
| 21 |
+
# "temperature": 0
|
| 22 |
+
# }'
|
examples/export/merge_lora.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Since `output/vx-xxx/checkpoint-xxx` is trained by swift and contains an `args.json` file,
|
| 2 |
+
# there is no need to explicitly set `--model`, `--system`, etc., as they will be automatically read.
|
| 3 |
+
swift export \
|
| 4 |
+
--adapters output/vx-xxx/checkpoint-xxx \
|
| 5 |
+
--merge_lora true
|
examples/export/ollama.sh
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
swift export \
|
| 2 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 3 |
+
--to_ollama true \
|
| 4 |
+
--output_dir Qwen2.5-1.5B-Instruct-ollama
|
examples/export/push_to_hub.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
swift export \
|
| 2 |
+
--adapters output/vx-xxx/checkpoint-xxx \
|
| 3 |
+
--push_to_hub true \
|
| 4 |
+
--hub_model_id '<model-id>' \
|
| 5 |
+
--hub_token '<sdk-token>' \
|
| 6 |
+
--use_hf false
|
examples/infer/cli_demo.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift infer \
|
| 3 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 4 |
+
--infer_backend transformers \
|
| 5 |
+
--stream true \
|
| 6 |
+
--max_new_tokens 2048
|
examples/infer/demo.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer_batch(engine: 'InferEngine', infer_requests: List['InferRequest']):
|
| 9 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 10 |
+
metric = InferStats()
|
| 11 |
+
resp_list = engine.infer(infer_requests, request_config, metrics=[metric])
|
| 12 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 13 |
+
print(f'query0: {query0}')
|
| 14 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 15 |
+
print(f'metric: {metric.compute()}')
|
| 16 |
+
# metric.reset() # reuse
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def infer_stream(engine: 'InferEngine', infer_request: 'InferRequest'):
|
| 20 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
|
| 21 |
+
metric = InferStats()
|
| 22 |
+
gen_list = engine.infer([infer_request], request_config, metrics=[metric])
|
| 23 |
+
query = infer_request.messages[0]['content']
|
| 24 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 25 |
+
for resp in gen_list[0]:
|
| 26 |
+
if resp is None:
|
| 27 |
+
continue
|
| 28 |
+
print(resp.choices[0].delta.content, end='', flush=True)
|
| 29 |
+
print()
|
| 30 |
+
print(f'metric: {metric.compute()}')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
from swift import InferEngine, InferRequest, InferStats, RequestConfig, TransformersEngine, load_dataset
|
| 35 |
+
model = 'Qwen/Qwen2.5-1.5B-Instruct'
|
| 36 |
+
infer_backend = 'transformers'
|
| 37 |
+
|
| 38 |
+
if infer_backend == 'transformers':
|
| 39 |
+
engine = TransformersEngine(model, max_batch_size=64)
|
| 40 |
+
elif infer_backend == 'vllm':
|
| 41 |
+
from swift.infer_engine import VllmEngine
|
| 42 |
+
engine = VllmEngine(model, max_model_len=8192)
|
| 43 |
+
elif infer_backend == 'sglang':
|
| 44 |
+
from swift.infer_engine import SglangEngine
|
| 45 |
+
engine = SglangEngine(model)
|
| 46 |
+
elif infer_backend == 'lmdeploy':
|
| 47 |
+
from swift.infer_engine import LmdeployEngine
|
| 48 |
+
engine = LmdeployEngine(model)
|
| 49 |
+
|
| 50 |
+
# Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
|
| 51 |
+
dataset = load_dataset(['AI-ModelScope/alpaca-gpt4-data-zh#1000'], seed=42)[0]
|
| 52 |
+
print(f'dataset: {dataset}')
|
| 53 |
+
infer_requests = [InferRequest(**data) for data in dataset]
|
| 54 |
+
infer_batch(engine, infer_requests)
|
| 55 |
+
|
| 56 |
+
messages = [{'role': 'user', 'content': 'who are you?'}]
|
| 57 |
+
infer_stream(engine, InferRequest(messages=messages))
|
examples/infer/demo_agent.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 5 |
+
# os.environ['SWIFT_DEBUG'] = '1'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(engine: 'InferEngine', infer_request: 'InferRequest'):
|
| 9 |
+
stop = [engine.template.agent_template.keyword.observation] # compat react_en
|
| 10 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stop=stop)
|
| 11 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 12 |
+
query = infer_request.messages[0]['content']
|
| 13 |
+
response = resp_list[0].choices[0].message.content
|
| 14 |
+
print(f'query: {query}')
|
| 15 |
+
print(f'response: {response}')
|
| 16 |
+
print(f'tool_calls: {resp_list[0].choices[0].message.tool_calls}')
|
| 17 |
+
|
| 18 |
+
tool = '{"temperature": 32, "condition": "Sunny", "humidity": 50}'
|
| 19 |
+
print(f'tool_response: {tool}')
|
| 20 |
+
infer_request.messages += [{'role': 'assistant', 'content': response}, {'role': 'tool', 'content': tool}]
|
| 21 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 22 |
+
response2 = resp_list[0].choices[0].message.content
|
| 23 |
+
print(f'response2: {response2}')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def infer_stream(engine: 'InferEngine', infer_request: 'InferRequest'):
|
| 27 |
+
stop = [engine.template.agent_template.keyword.observation]
|
| 28 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stream=True, stop=stop)
|
| 29 |
+
gen_list = engine.infer([infer_request], request_config)
|
| 30 |
+
query = infer_request.messages[0]['content']
|
| 31 |
+
response = ''
|
| 32 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 33 |
+
for resp in gen_list[0]:
|
| 34 |
+
if resp is None:
|
| 35 |
+
continue
|
| 36 |
+
delta = resp.choices[0].delta.content
|
| 37 |
+
response += delta
|
| 38 |
+
print(delta, end='', flush=True)
|
| 39 |
+
print()
|
| 40 |
+
print(f'tool_calls: {resp.choices[0].delta.tool_calls}')
|
| 41 |
+
|
| 42 |
+
tool = '{"temperature": 32, "condition": "Sunny", "humidity": 50}'
|
| 43 |
+
print(f'tool_response: {tool}\nresponse2: ', end='')
|
| 44 |
+
infer_request.messages += [{'role': 'assistant', 'content': response}, {'role': 'tool', 'content': tool}]
|
| 45 |
+
gen_list = engine.infer([infer_request], request_config)
|
| 46 |
+
for resp in gen_list[0]:
|
| 47 |
+
if resp is None:
|
| 48 |
+
continue
|
| 49 |
+
print(resp.choices[0].delta.content, end='', flush=True)
|
| 50 |
+
print()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_infer_request():
|
| 54 |
+
return InferRequest(
|
| 55 |
+
messages=[{
|
| 56 |
+
'role': 'user',
|
| 57 |
+
'content': "How's the weather in Beijing today?"
|
| 58 |
+
}],
|
| 59 |
+
tools=[{
|
| 60 |
+
'name': 'get_current_weather',
|
| 61 |
+
'description': 'Get the current weather in a given location',
|
| 62 |
+
'parameters': {
|
| 63 |
+
'type': 'object',
|
| 64 |
+
'properties': {
|
| 65 |
+
'location': {
|
| 66 |
+
'type': 'string',
|
| 67 |
+
'description': 'The city and state, e.g. San Francisco, CA'
|
| 68 |
+
},
|
| 69 |
+
'unit': {
|
| 70 |
+
'type': 'string',
|
| 71 |
+
'enum': ['celsius', 'fahrenheit']
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
'required': ['location']
|
| 75 |
+
}
|
| 76 |
+
}])
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def infer_continue_generate(engine):
|
| 80 |
+
# Continue generating after the assistant message.
|
| 81 |
+
infer_request = InferRequest(messages=[{
|
| 82 |
+
'role': 'user',
|
| 83 |
+
'content': 'How is the weather today?'
|
| 84 |
+
}, {
|
| 85 |
+
'role': 'assistant',
|
| 86 |
+
'content': 'It is sunny today, '
|
| 87 |
+
}])
|
| 88 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 89 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 90 |
+
response = resp_list[0].choices[0].message.content
|
| 91 |
+
print(f'response: {response}')
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == '__main__':
|
| 95 |
+
from swift.agent_template import agent_template_map
|
| 96 |
+
from swift.infer_engine import InferEngine, InferRequest, RequestConfig, TransformersEngine
|
| 97 |
+
model = 'Qwen/Qwen2.5-1.5B-Instruct'
|
| 98 |
+
infer_backend = 'transformers'
|
| 99 |
+
|
| 100 |
+
if infer_backend == 'transformers':
|
| 101 |
+
engine = TransformersEngine(model, max_batch_size=64)
|
| 102 |
+
elif infer_backend == 'vllm':
|
| 103 |
+
from swift.infer_engine import VllmEngine
|
| 104 |
+
engine = VllmEngine(model, max_model_len=8192)
|
| 105 |
+
elif infer_backend == 'lmdeploy':
|
| 106 |
+
from swift.infer_engine import LmdeployEngine
|
| 107 |
+
engine = LmdeployEngine(model)
|
| 108 |
+
|
| 109 |
+
# engine.template._agent_template = 'hermes' # react_en/qwen_en/qwen_en_parallel
|
| 110 |
+
|
| 111 |
+
infer(engine, get_infer_request())
|
| 112 |
+
infer_stream(engine, get_infer_request())
|
| 113 |
+
|
| 114 |
+
# infer_continue_generate(engine)
|
examples/infer/demo_bert.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
# demo_seq_cls: https://github.com/modelscope/ms-swift/blob/main/examples/train/seq_cls/qwen2_5_omni/infer.py
|
| 3 |
+
import os
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def infer_batch(engine: 'InferEngine', infer_requests: List['InferRequest']):
|
| 10 |
+
resp_list = engine.infer(infer_requests)
|
| 11 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 12 |
+
query1 = infer_requests[1].messages[0]['content']
|
| 13 |
+
print(f'query0: {query0}')
|
| 14 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 15 |
+
print(f'query1: {query1}')
|
| 16 |
+
print(f'response1: {resp_list[1].choices[0].message.content}')
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if __name__ == '__main__':
|
| 20 |
+
# This is an example of BERT with LoRA.
|
| 21 |
+
from peft import PeftModel
|
| 22 |
+
|
| 23 |
+
from swift import BaseArguments, InferEngine, InferRequest, TransformersEngine, load_dataset, safe_snapshot_download
|
| 24 |
+
adapter_path = safe_snapshot_download('swift/test_bert')
|
| 25 |
+
args = BaseArguments.from_pretrained(adapter_path)
|
| 26 |
+
args.max_length = 512
|
| 27 |
+
args.truncation_strategy = 'right'
|
| 28 |
+
# method1
|
| 29 |
+
model, processor = args.get_model_processor()
|
| 30 |
+
model = PeftModel.from_pretrained(model, adapter_path)
|
| 31 |
+
template = args.get_template(processor)
|
| 32 |
+
engine = TransformersEngine(model, template=template, max_batch_size=64)
|
| 33 |
+
|
| 34 |
+
# method2
|
| 35 |
+
# engine = TransformersEngine(args.model, adapters=[adapter_path], max_batch_size=64,
|
| 36 |
+
# task_type=args.task_type, num_labels=args.num_labels)
|
| 37 |
+
# template = args.get_template(engine.processor)
|
| 38 |
+
# engine.template = template
|
| 39 |
+
|
| 40 |
+
# Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
|
| 41 |
+
dataset = load_dataset(['DAMO_NLP/jd:cls#1000'], seed=42)[0]
|
| 42 |
+
print(f'dataset: {dataset}')
|
| 43 |
+
infer_requests = [InferRequest(messages=data['messages']) for data in dataset]
|
| 44 |
+
infer_batch(engine, infer_requests)
|
| 45 |
+
|
| 46 |
+
infer_batch(engine, [
|
| 47 |
+
InferRequest(messages=[{
|
| 48 |
+
'role': 'user',
|
| 49 |
+
'content': '今天天气真好呀'
|
| 50 |
+
}]),
|
| 51 |
+
InferRequest(messages=[{
|
| 52 |
+
'role': 'user',
|
| 53 |
+
'content': '真倒霉'
|
| 54 |
+
}])
|
| 55 |
+
])
|
examples/infer/demo_embedding.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from swift.infer_engine import InferRequest, TransformersEngine
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def run_qwen3_emb():
|
| 7 |
+
engine = TransformersEngine(
|
| 8 |
+
'Qwen/Qwen3-Embedding-4B', task_type='embedding', torch_dtype=torch.float16, attn_impl='flash_attention_2')
|
| 9 |
+
|
| 10 |
+
infer_requests = [
|
| 11 |
+
InferRequest(messages=[
|
| 12 |
+
{
|
| 13 |
+
'role':
|
| 14 |
+
'user',
|
| 15 |
+
'content':
|
| 16 |
+
'Instruct: Given a web search query, retrieve relevant passages that answer the query\n'
|
| 17 |
+
'Query:What is the capital of China?'
|
| 18 |
+
},
|
| 19 |
+
]),
|
| 20 |
+
InferRequest(messages=[
|
| 21 |
+
{
|
| 22 |
+
'role': 'user',
|
| 23 |
+
'content': 'The capital of China is Beijing.'
|
| 24 |
+
},
|
| 25 |
+
])
|
| 26 |
+
]
|
| 27 |
+
resp_list = engine.infer(infer_requests)
|
| 28 |
+
embedding0 = torch.tensor(resp_list[0].data[0].embedding)
|
| 29 |
+
embedding1 = torch.tensor(resp_list[1].data[0].embedding)
|
| 30 |
+
print(f'scores: {(embedding0 * embedding1).sum()}')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def run_qwen3_vl_emb():
|
| 34 |
+
engine = TransformersEngine(
|
| 35 |
+
'Qwen/Qwen3-VL-Embedding-2B', task_type='embedding', max_batch_size=2, attn_impl='flash_attention_2')
|
| 36 |
+
|
| 37 |
+
infer_requests = [
|
| 38 |
+
InferRequest(messages=[
|
| 39 |
+
{
|
| 40 |
+
'role': 'user',
|
| 41 |
+
'content': 'A woman playing with her dog on a beach at sunset.'
|
| 42 |
+
},
|
| 43 |
+
]),
|
| 44 |
+
InferRequest(
|
| 45 |
+
messages=[
|
| 46 |
+
{
|
| 47 |
+
'role':
|
| 48 |
+
'user',
|
| 49 |
+
'content':
|
| 50 |
+
'<image>A woman shares a joyful moment with her golden retriever on a sun-drenched beach at '
|
| 51 |
+
'sunset, as the dog offers its paw in a heartwarming display of companionship and trust.'
|
| 52 |
+
},
|
| 53 |
+
],
|
| 54 |
+
images=['https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'])
|
| 55 |
+
]
|
| 56 |
+
resp_list = engine.infer(infer_requests)
|
| 57 |
+
embedding0 = torch.tensor(resp_list[0].data[0].embedding)
|
| 58 |
+
embedding1 = torch.tensor(resp_list[1].data[0].embedding)
|
| 59 |
+
print(f'scores: {(embedding0 * embedding1).sum()}')
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == '__main__':
|
| 63 |
+
# run_qwen3_emb()
|
| 64 |
+
run_qwen3_vl_emb()
|
examples/infer/demo_grounding.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
os.environ['MAX_PIXELS'] = '1003520'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def draw_bbox_qwen2_vl(image, response, norm_bbox: Literal['norm1000', 'none']):
|
| 10 |
+
matches = re.findall(
|
| 11 |
+
r'<\|object_ref_start\|>(.*?)<\|object_ref_end\|><\|box_start\|>\((\d+),(\d+)\),\((\d+),(\d+)\)<\|box_end\|>',
|
| 12 |
+
response)
|
| 13 |
+
ref = []
|
| 14 |
+
bbox = []
|
| 15 |
+
for match_ in matches:
|
| 16 |
+
ref.append(match_[0])
|
| 17 |
+
bbox.append(list(match_[1:]))
|
| 18 |
+
draw_bbox(image, ref, bbox, norm_bbox=norm_bbox)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def infer_grounding():
|
| 22 |
+
# use transformers==4.51.3
|
| 23 |
+
from swift import BaseArguments, InferRequest, RequestConfig, TransformersEngine, safe_snapshot_download
|
| 24 |
+
output_path = 'bbox.png'
|
| 25 |
+
image = load_image('http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png')
|
| 26 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'Task: Object Detection'}], images=[image])
|
| 27 |
+
|
| 28 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, return_details=True)
|
| 29 |
+
adapter_path = safe_snapshot_download('swift/test_grounding')
|
| 30 |
+
args = BaseArguments.from_pretrained(adapter_path)
|
| 31 |
+
|
| 32 |
+
engine = TransformersEngine(args.model, adapters=[adapter_path])
|
| 33 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 34 |
+
image = image.resize(resp_list[0].images_size[0])
|
| 35 |
+
response = resp_list[0].choices[0].message.content
|
| 36 |
+
print(f'lora-response: {response}')
|
| 37 |
+
|
| 38 |
+
draw_bbox_qwen2_vl(image, response, norm_bbox=args.norm_bbox)
|
| 39 |
+
print(f'output_path: {output_path}')
|
| 40 |
+
image.save(output_path)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
from swift.template import draw_bbox, load_image
|
| 45 |
+
infer_grounding()
|
examples/infer/demo_hf.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def infer_hf():
|
| 2 |
+
from modelscope import snapshot_download
|
| 3 |
+
from peft import PeftModel
|
| 4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 5 |
+
model_dir = snapshot_download('Qwen/Qwen2.5-7B-Instruct')
|
| 6 |
+
adapter_dir = snapshot_download('swift/test_lora')
|
| 7 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 8 |
+
model_dir, torch_dtype='auto', device_map='auto', trust_remote_code=True)
|
| 9 |
+
model = PeftModel.from_pretrained(model, adapter_dir)
|
| 10 |
+
|
| 11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
| 12 |
+
|
| 13 |
+
messages = [{
|
| 14 |
+
'role': 'system',
|
| 15 |
+
'content': 'You are a helpful assistant.'
|
| 16 |
+
}, {
|
| 17 |
+
'role': 'user',
|
| 18 |
+
'content': 'who are you?'
|
| 19 |
+
}]
|
| 20 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 21 |
+
model_inputs = tokenizer([text], return_tensors='pt', add_special_tokens=False).to(model.device)
|
| 22 |
+
|
| 23 |
+
generated_ids = model.generate(**model_inputs, max_new_tokens=512, do_sample=False)
|
| 24 |
+
generated_ids = [
|
| 25 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 29 |
+
print(f'response: {response}')
|
| 30 |
+
return response
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def infer_swift():
|
| 34 |
+
from modelscope import snapshot_download
|
| 35 |
+
from peft import PeftModel
|
| 36 |
+
|
| 37 |
+
from swift import get_model_processor, get_template
|
| 38 |
+
from swift.infer_engine import InferRequest, RequestConfig, TransformersEngine
|
| 39 |
+
from swift.tuners import Swift
|
| 40 |
+
model_dir = snapshot_download('Qwen/Qwen2.5-7B-Instruct')
|
| 41 |
+
adapter_dir = snapshot_download('swift/test_lora')
|
| 42 |
+
model, tokenizer = get_model_processor(model_dir, device_map='auto')
|
| 43 |
+
model = Swift.from_pretrained(model, adapter_dir)
|
| 44 |
+
# You can also write it as:
|
| 45 |
+
# model = PeftModel.from_pretrained(model, adapter_dir)
|
| 46 |
+
template = get_template(tokenizer)
|
| 47 |
+
engine = TransformersEngine(model, template=template)
|
| 48 |
+
|
| 49 |
+
messages = [{
|
| 50 |
+
'role': 'system',
|
| 51 |
+
'content': 'You are a helpful assistant.'
|
| 52 |
+
}, {
|
| 53 |
+
'role': 'user',
|
| 54 |
+
'content': 'who are you?'
|
| 55 |
+
}]
|
| 56 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 57 |
+
resp_list = engine.infer([InferRequest(messages=messages)], request_config=request_config)
|
| 58 |
+
response = resp_list[0].choices[0].message.content
|
| 59 |
+
print(f'response: {response}')
|
| 60 |
+
return response
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == '__main__':
|
| 64 |
+
response = infer_hf()
|
| 65 |
+
response2 = infer_swift()
|
| 66 |
+
assert response == response2
|
examples/infer/demo_lora.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def infer_multilora(infer_request: 'InferRequest', infer_backend: Literal['vllm', 'transformers']):
|
| 8 |
+
# Dynamic LoRA
|
| 9 |
+
adapter_path = safe_snapshot_download('swift/test_lora')
|
| 10 |
+
adapter_path2 = safe_snapshot_download('swift/test_lora2')
|
| 11 |
+
args = BaseArguments.from_pretrained(adapter_path)
|
| 12 |
+
if infer_backend == 'transformers':
|
| 13 |
+
engine = TransformersEngine(args.model)
|
| 14 |
+
elif infer_backend == 'vllm':
|
| 15 |
+
from swift.infer_engine import VllmEngine
|
| 16 |
+
engine = VllmEngine(args.model, enable_lora=True, max_loras=1, max_lora_rank=16)
|
| 17 |
+
template = get_template(engine.processor, template_type=args.template, default_system=args.system)
|
| 18 |
+
engine.template = template
|
| 19 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 20 |
+
adapter_request = AdapterRequest('lora1', adapter_path)
|
| 21 |
+
adapter_request2 = AdapterRequest('lora2', adapter_path2)
|
| 22 |
+
|
| 23 |
+
# use lora
|
| 24 |
+
resp_list = engine.infer([infer_request], request_config, adapter_request=adapter_request)
|
| 25 |
+
response = resp_list[0].choices[0].message.content
|
| 26 |
+
print(f'lora1-response: {response}')
|
| 27 |
+
# origin model
|
| 28 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 29 |
+
response = resp_list[0].choices[0].message.content
|
| 30 |
+
print(f'response: {response}')
|
| 31 |
+
# use lora
|
| 32 |
+
resp_list = engine.infer([infer_request], request_config, adapter_request=adapter_request2)
|
| 33 |
+
response = resp_list[0].choices[0].message.content
|
| 34 |
+
print(f'lora2-response: {response}')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def infer_lora(infer_request: 'InferRequest'):
|
| 38 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 39 |
+
adapter_path = safe_snapshot_download('swift/test_lora')
|
| 40 |
+
args = BaseArguments.from_pretrained(adapter_path)
|
| 41 |
+
# method1
|
| 42 |
+
# engine = TransformersEngine(args.model, adapters=[adapter_path])
|
| 43 |
+
# template = get_template(engine.processor, args.system, template_type=args.template)
|
| 44 |
+
# engine.template = template
|
| 45 |
+
|
| 46 |
+
# method2
|
| 47 |
+
# model, processor = args.get_model_processor()
|
| 48 |
+
# model = PeftModel.from_pretrained(model, adapter_path)
|
| 49 |
+
# template = args.get_template(processor)
|
| 50 |
+
# engine = TransformersEngine(model, template=template)
|
| 51 |
+
|
| 52 |
+
# method3
|
| 53 |
+
model, tokenizer = get_model_processor(args.model)
|
| 54 |
+
model = PeftModel.from_pretrained(model, adapter_path)
|
| 55 |
+
template = get_template(tokenizer, args.system, template_type=args.template)
|
| 56 |
+
engine = TransformersEngine(model, template=template)
|
| 57 |
+
|
| 58 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 59 |
+
response = resp_list[0].choices[0].message.content
|
| 60 |
+
print(f'lora-response: {response}')
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == '__main__':
|
| 64 |
+
from peft import PeftModel
|
| 65 |
+
|
| 66 |
+
from swift import (AdapterRequest, BaseArguments, InferRequest, RequestConfig, TransformersEngine,
|
| 67 |
+
get_model_processor, get_template, safe_snapshot_download)
|
| 68 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}])
|
| 69 |
+
# infer_lora(infer_request)
|
| 70 |
+
infer_multilora(infer_request, 'transformers')
|
examples/infer/demo_mllm.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from typing import List, Literal
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer_batch(engine: 'InferEngine', infer_requests: List['InferRequest']):
|
| 9 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 10 |
+
metric = InferStats()
|
| 11 |
+
resp_list = engine.infer(infer_requests, request_config, metrics=[metric])
|
| 12 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 13 |
+
print(f'query0: {query0}')
|
| 14 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 15 |
+
print(f'metric: {metric.compute()}')
|
| 16 |
+
# metric.reset() # reuse
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def infer_stream(engine: 'InferEngine', infer_request: 'InferRequest'):
|
| 20 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
|
| 21 |
+
metric = InferStats()
|
| 22 |
+
gen_list = engine.infer([infer_request], request_config, metrics=[metric])
|
| 23 |
+
query = infer_request.messages[0]['content']
|
| 24 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 25 |
+
for resp in gen_list[0]:
|
| 26 |
+
if resp is None:
|
| 27 |
+
continue
|
| 28 |
+
print(resp.choices[0].delta.content, end='', flush=True)
|
| 29 |
+
print()
|
| 30 |
+
print(f'metric: {metric.compute()}')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_message(mm_type: Literal['text', 'image', 'video', 'audio']):
|
| 34 |
+
if mm_type == 'text':
|
| 35 |
+
message = {'role': 'user', 'content': 'who are you?'}
|
| 36 |
+
elif mm_type == 'image':
|
| 37 |
+
message = {
|
| 38 |
+
'role':
|
| 39 |
+
'user',
|
| 40 |
+
'content': [
|
| 41 |
+
{
|
| 42 |
+
'type': 'image',
|
| 43 |
+
# url or local_path or PIL.Image or base64
|
| 44 |
+
'image': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png'
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
'type': 'text',
|
| 48 |
+
'text': 'How many sheep are there in the picture?'
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
elif mm_type == 'video':
|
| 54 |
+
message = {
|
| 55 |
+
'role':
|
| 56 |
+
'user',
|
| 57 |
+
'content': [{
|
| 58 |
+
'type': 'video',
|
| 59 |
+
'video': 'https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'
|
| 60 |
+
}, {
|
| 61 |
+
'type': 'text',
|
| 62 |
+
'text': 'Describe this video.'
|
| 63 |
+
}]
|
| 64 |
+
}
|
| 65 |
+
elif mm_type == 'audio':
|
| 66 |
+
message = {
|
| 67 |
+
'role':
|
| 68 |
+
'user',
|
| 69 |
+
'content': [{
|
| 70 |
+
'type': 'audio',
|
| 71 |
+
'audio': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav'
|
| 72 |
+
}, {
|
| 73 |
+
'type': 'text',
|
| 74 |
+
'text': 'What does this audio say?'
|
| 75 |
+
}]
|
| 76 |
+
}
|
| 77 |
+
return message
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_data(mm_type: Literal['text', 'image', 'video', 'audio']):
|
| 81 |
+
data = {}
|
| 82 |
+
if mm_type == 'text':
|
| 83 |
+
messages = [{'role': 'user', 'content': 'who are you?'}]
|
| 84 |
+
elif mm_type == 'image':
|
| 85 |
+
# The number of <image> tags must be the same as len(images).
|
| 86 |
+
messages = [{'role': 'user', 'content': '<image>How many sheep are there in the picture?'}]
|
| 87 |
+
# Support URL/Path/base64/PIL.Image
|
| 88 |
+
data['images'] = ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']
|
| 89 |
+
elif mm_type == 'video':
|
| 90 |
+
messages = [{'role': 'user', 'content': '<video>Describe this video.'}]
|
| 91 |
+
data['videos'] = ['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']
|
| 92 |
+
elif mm_type == 'audio':
|
| 93 |
+
messages = [{'role': 'user', 'content': '<audio>What does this audio say?'}]
|
| 94 |
+
data['audios'] = ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav']
|
| 95 |
+
data['messages'] = messages
|
| 96 |
+
return data
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == '__main__':
|
| 100 |
+
# The inference of the trained model can be referred to as:
|
| 101 |
+
# https://github.com/modelscope/ms-swift/tree/main/examples/notebook
|
| 102 |
+
from swift import InferEngine, InferRequest, InferStats, RequestConfig, TransformersEngine, load_dataset
|
| 103 |
+
infer_backend = 'transformers'
|
| 104 |
+
|
| 105 |
+
if infer_backend == 'transformers':
|
| 106 |
+
# test env: transformers==4.55.2
|
| 107 |
+
model = 'Qwen/Qwen2.5-Omni-7B'
|
| 108 |
+
mm_type = 'audio'
|
| 109 |
+
engine = TransformersEngine(model, max_batch_size=64, attn_impl='flash_attention_2')
|
| 110 |
+
elif infer_backend == 'vllm':
|
| 111 |
+
# test env: vllm==0.8.5.post1, transformers==4.51.3
|
| 112 |
+
# The meaning of environment variables can be found at:
|
| 113 |
+
# https://swift.readthedocs.io/zh-cn/latest/Instruction/%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0.html#id17
|
| 114 |
+
from swift.infer_engine import VllmEngine
|
| 115 |
+
os.environ['MAX_PIXELS'] = '1003520'
|
| 116 |
+
os.environ['VIDEO_MAX_PIXELS'] = '50176'
|
| 117 |
+
os.environ['FPS_MAX_FRAMES'] = '12'
|
| 118 |
+
model = 'Qwen/Qwen2.5-VL-3B-Instruct'
|
| 119 |
+
# If you encounter insufficient GPU memory, please reduce `max_model_len` and set `max_num_seqs=5`.
|
| 120 |
+
engine = VllmEngine(model, max_model_len=8192, limit_mm_per_prompt={'image': 5, 'video': 2})
|
| 121 |
+
mm_type = 'image' # or 'video'
|
| 122 |
+
elif infer_backend == 'lmdeploy':
|
| 123 |
+
# test env: lmdeploy==0.7.1
|
| 124 |
+
from swift.infer_engine import LmdeployEngine
|
| 125 |
+
model = 'OpenGVLab/InternVL2_5-1B'
|
| 126 |
+
engine = LmdeployEngine(model, vision_batch_size=8)
|
| 127 |
+
mm_type = 'image' # or 'video'
|
| 128 |
+
|
| 129 |
+
# infer dataset
|
| 130 |
+
if mm_type == 'audio':
|
| 131 |
+
dataset = 'speech_asr/speech_asr_aishell1_trainsets:validation#1000'
|
| 132 |
+
elif mm_type == 'image':
|
| 133 |
+
dataset = 'AI-ModelScope/LaTeX_OCR:small#1000'
|
| 134 |
+
elif mm_type == 'video':
|
| 135 |
+
dataset = 'swift/VideoChatGPT:Generic#100'
|
| 136 |
+
|
| 137 |
+
# Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
|
| 138 |
+
dataset = load_dataset([dataset], seed=42)[0]
|
| 139 |
+
print(f'dataset: {dataset}')
|
| 140 |
+
infer_requests = [InferRequest(**data) for data in dataset]
|
| 141 |
+
infer_batch(engine, infer_requests)
|
| 142 |
+
|
| 143 |
+
infer_stream(engine, InferRequest(messages=[get_message(mm_type)]))
|
| 144 |
+
# This writing is equivalent to the above writing.
|
| 145 |
+
infer_stream(engine, InferRequest(**get_data(mm_type)))
|
examples/infer/demo_reranker.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from swift.infer_engine import InferRequest, TransformersEngine
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def run_qwen3_reranker():
|
| 7 |
+
engine = TransformersEngine(
|
| 8 |
+
'Qwen/Qwen3-Reranker-4B',
|
| 9 |
+
task_type='generative_reranker',
|
| 10 |
+
torch_dtype=torch.float16,
|
| 11 |
+
attn_impl='flash_attention_2')
|
| 12 |
+
|
| 13 |
+
infer_request = InferRequest(
|
| 14 |
+
messages=[{
|
| 15 |
+
'role': 'system',
|
| 16 |
+
'content': 'Given a web search query, retrieve relevant passages that answer the query'
|
| 17 |
+
}, {
|
| 18 |
+
'role': 'user',
|
| 19 |
+
'content': 'What is the capital of China?'
|
| 20 |
+
}, {
|
| 21 |
+
'role': 'assistant',
|
| 22 |
+
'content': 'The capital of China is Beijing.'
|
| 23 |
+
}])
|
| 24 |
+
|
| 25 |
+
response = engine.infer([infer_request])[0]
|
| 26 |
+
print(f'scores: {response.choices[0].message.content}')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def run_qwen3_vl_reranker():
|
| 30 |
+
engine = TransformersEngine(
|
| 31 |
+
'Qwen/Qwen3-VL-Reranker-2B', task_type='generative_reranker', attn_impl='flash_attention_2')
|
| 32 |
+
|
| 33 |
+
infer_request = InferRequest(
|
| 34 |
+
messages=[{
|
| 35 |
+
'role': 'system',
|
| 36 |
+
'content': "Retrieval relevant image or text with user's query"
|
| 37 |
+
}, {
|
| 38 |
+
'role': 'user',
|
| 39 |
+
'content': 'A woman playing with her dog on a beach at sunset.'
|
| 40 |
+
}, {
|
| 41 |
+
'role':
|
| 42 |
+
'assistant',
|
| 43 |
+
'content':
|
| 44 |
+
'<image>A woman shares a joyful moment with her golden retriever on a sun-drenched beach '
|
| 45 |
+
'at sunset, as the dog offers its paw in a heartwarming display of companionship and trust.'
|
| 46 |
+
}],
|
| 47 |
+
images=['https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'])
|
| 48 |
+
|
| 49 |
+
response = engine.infer([infer_request])[0]
|
| 50 |
+
print(f'scores: {response.choices[0].message.content}')
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == '__main__':
|
| 54 |
+
# run_qwen3_reranker()
|
| 55 |
+
run_qwen3_vl_reranker()
|
examples/infer/demo_reward_model.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer_batch(engine: 'InferEngine', infer_requests: List['InferRequest']):
|
| 9 |
+
resp_list = engine.infer(infer_requests)
|
| 10 |
+
print(f'messages0: {infer_requests[0].messages}')
|
| 11 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if __name__ == '__main__':
|
| 15 |
+
from swift import InferEngine, InferRequest, TransformersEngine, load_dataset
|
| 16 |
+
model = 'Shanghai_AI_Laboratory/internlm2-1_8b-reward'
|
| 17 |
+
engine = TransformersEngine(model, max_batch_size=64)
|
| 18 |
+
# Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
|
| 19 |
+
dataset = load_dataset(['AI-ModelScope/alpaca-gpt4-data-zh#1000'], seed=42)[0]
|
| 20 |
+
print(f'dataset: {dataset}')
|
| 21 |
+
infer_requests = [InferRequest(**data) for data in dataset]
|
| 22 |
+
infer_batch(engine, infer_requests)
|
| 23 |
+
|
| 24 |
+
messages = [{
|
| 25 |
+
'role': 'user',
|
| 26 |
+
'content': "Hello! What's your name?"
|
| 27 |
+
}, {
|
| 28 |
+
'role': 'assistant',
|
| 29 |
+
'content': 'My name is InternLM2! A helpful AI assistant. What can I do for you?'
|
| 30 |
+
}]
|
| 31 |
+
infer_batch(engine, [InferRequest(messages=messages)])
|
examples/infer/demo_vllm_reasoning_parser.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Example of using reasoning_parser
|
| 3 |
+
|
| 4 |
+
This example demonstrates how to use reasoning_parser in Swift's VllmEngine to support reasoning models.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from swift.infer_engine import InferRequest, RequestConfig, VllmEngine
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main(engine: VllmEngine):
|
| 11 |
+
# Create inference request
|
| 12 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': '9.11 and 9.8, which is greater?'}])
|
| 13 |
+
|
| 14 |
+
# Configure request parameters
|
| 15 |
+
request_config = RequestConfig(
|
| 16 |
+
max_tokens=8192,
|
| 17 |
+
temperature=0.7,
|
| 18 |
+
stream=False # Non-streaming inference
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Execute inference
|
| 22 |
+
responses = engine.infer(infer_requests=[infer_request], request_config=request_config)
|
| 23 |
+
|
| 24 |
+
# Process responses
|
| 25 |
+
for response in responses:
|
| 26 |
+
if hasattr(response, 'choices') and response.choices:
|
| 27 |
+
choice = response.choices[0]
|
| 28 |
+
message = choice.message
|
| 29 |
+
|
| 30 |
+
print('=== Reasoning Content ===')
|
| 31 |
+
if message.reasoning_content:
|
| 32 |
+
print(f'Reasoning steps: {message.reasoning_content}')
|
| 33 |
+
else:
|
| 34 |
+
print('No reasoning content detected')
|
| 35 |
+
|
| 36 |
+
print('\n=== Final Answer ===')
|
| 37 |
+
print(f'Answer: {message.content}')
|
| 38 |
+
|
| 39 |
+
print('\n=== Finish Reason ===')
|
| 40 |
+
print(f'Reason: {choice.finish_reason}')
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def streaming_example(engine: VllmEngine):
|
| 44 |
+
"""Streaming inference example"""
|
| 45 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'Calculate the result of 15 + 27'}])
|
| 46 |
+
|
| 47 |
+
request_config = RequestConfig(
|
| 48 |
+
max_tokens=8192,
|
| 49 |
+
temperature=0.7,
|
| 50 |
+
stream=True # Enable streaming inference
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Streaming inference
|
| 54 |
+
responses = engine.infer(infer_requests=[infer_request], request_config=request_config)
|
| 55 |
+
|
| 56 |
+
print('=== Streaming Inference Results ===')
|
| 57 |
+
for chunk in responses[0]: # responses[0] is the streaming generator
|
| 58 |
+
if chunk and chunk.choices:
|
| 59 |
+
choice = chunk.choices[0]
|
| 60 |
+
delta = choice.delta
|
| 61 |
+
|
| 62 |
+
if delta.reasoning_content:
|
| 63 |
+
print(f'Reasoning: {delta.reasoning_content}', end='', flush=True)
|
| 64 |
+
|
| 65 |
+
if delta.content:
|
| 66 |
+
print(f'Content: {delta.content}', end='', flush=True)
|
| 67 |
+
|
| 68 |
+
print('\n=== Inference Complete ===')
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == '__main__':
|
| 72 |
+
# Initialize VllmEngine with reasoning_parser enabled
|
| 73 |
+
engine = VllmEngine(
|
| 74 |
+
model_id_or_path='Qwen/Qwen3-8B',
|
| 75 |
+
reasoning_parser='qwen3', # Specify reasoning parser
|
| 76 |
+
gpu_memory_utilization=0.9,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
print('=== Non-streaming Inference Example ===')
|
| 80 |
+
main(engine)
|
| 81 |
+
|
| 82 |
+
print('\n' + '=' * 50 + '\n')
|
| 83 |
+
|
| 84 |
+
print('=== Streaming Inference Example ===')
|
| 85 |
+
streaming_example(engine)
|
examples/infer/lmdeploy/batch_ddp.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# test env: lmdeploy 0.9.2.post1
|
| 2 |
+
NPROC_PER_NODE=4 \
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 \
|
| 4 |
+
swift infer \
|
| 5 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 6 |
+
--infer_backend lmdeploy \
|
| 7 |
+
--val_dataset AI-ModelScope/alpaca-gpt4-data-zh#1000 \
|
| 8 |
+
--max_new_tokens 512
|
examples/infer/lmdeploy/mllm_tp.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 2 |
+
swift infer \
|
| 3 |
+
--model OpenGVLab/InternVL2_5-1B \
|
| 4 |
+
--infer_backend lmdeploy \
|
| 5 |
+
--val_dataset AI-ModelScope/captcha-images#1000 \
|
| 6 |
+
--lmdeploy_tp 2 \
|
| 7 |
+
--lmdeploy_vision_batch_size 8 \
|
| 8 |
+
--max_new_tokens 2048
|
examples/infer/transformers/mllm_device_map.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NPROC_PER_NODE=2 \
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 \
|
| 3 |
+
MAX_PIXELS=1003520 \
|
| 4 |
+
swift infer \
|
| 5 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 6 |
+
--infer_backend transformers \
|
| 7 |
+
--val_dataset AI-ModelScope/LaTeX_OCR#1000 \
|
| 8 |
+
--max_batch_size 16 \
|
| 9 |
+
--max_new_tokens 512
|
examples/infer/vllm/dp_tp.sh
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NPROC_PER_NODE=4 \
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 \
|
| 3 |
+
swift infer \
|
| 4 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 5 |
+
--infer_backend vllm \
|
| 6 |
+
--val_dataset AI-ModelScope/alpaca-gpt4-data-zh#2000 \
|
| 7 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 8 |
+
--vllm_max_model_len 8192 \
|
| 9 |
+
--vllm_tensor_parallel_size 2 \
|
| 10 |
+
--max_new_tokens 2048 \
|
| 11 |
+
--write_batch_size 1000
|
examples/infer/vllm/mllm_ddp.sh
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# You need to use flash-attn (manual installation) instead of xformers.
|
| 2 |
+
NPROC_PER_NODE=2 \
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 4 |
+
swift infer \
|
| 5 |
+
--model Qwen/Qwen2.5-Omni-7B \
|
| 6 |
+
--infer_backend vllm \
|
| 7 |
+
--val_dataset speech_asr/speech_asr_aishell1_trainsets:validation#1000 \
|
| 8 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 9 |
+
--vllm_max_model_len 8192 \
|
| 10 |
+
--max_new_tokens 2048 \
|
| 11 |
+
--vllm_limit_mm_per_prompt '{"audio": 5}'
|
examples/infer/vllm/mllm_tp.sh
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 2 |
+
MAX_PIXELS=1003520 \
|
| 3 |
+
swift infer \
|
| 4 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 5 |
+
--infer_backend vllm \
|
| 6 |
+
--val_dataset AI-ModelScope/LaTeX_OCR#1000 \
|
| 7 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 8 |
+
--vllm_tensor_parallel_size 2 \
|
| 9 |
+
--vllm_max_model_len 32768 \
|
| 10 |
+
--max_new_tokens 2048 \
|
| 11 |
+
--vllm_limit_mm_per_prompt '{"image": 5, "video": 2}'
|
examples/infer/vllm/mtp.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 \
|
| 2 |
+
swift infer \
|
| 3 |
+
--model Qwen/Qwen3-Next-80B-A3B-Instruct \
|
| 4 |
+
--vllm_tensor_parallel_size 4 \
|
| 5 |
+
--infer_backend vllm \
|
| 6 |
+
--vllm_max_model_len 8192 \
|
| 7 |
+
--val_dataset AI-ModelScope/alpaca-gpt4-data-zh#100 \
|
| 8 |
+
--vllm_speculative_config '{"method":"qwen3_next_mtp","num_speculative_tokens":2}' \
|
| 9 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 10 |
+
--max_new_tokens 2048
|
examples/megatron/base_to_chat.sh
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 8 * 65GiB
|
| 2 |
+
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \
|
| 3 |
+
NPROC_PER_NODE=8 \
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
|
| 5 |
+
megatron sft \
|
| 6 |
+
--model Qwen/Qwen2.5-14B \
|
| 7 |
+
--save_safetensors true \
|
| 8 |
+
--dataset 'liucong/Chinese-DeepSeek-R1-Distill-data-110k-SFT' \
|
| 9 |
+
--load_from_cache_file true \
|
| 10 |
+
--split_dataset_ratio 0.01 \
|
| 11 |
+
--tensor_model_parallel_size 4 \
|
| 12 |
+
--micro_batch_size 1 \
|
| 13 |
+
--global_batch_size 16 \
|
| 14 |
+
--packing true \
|
| 15 |
+
--recompute_granularity selective \
|
| 16 |
+
--train_iters 2000 \
|
| 17 |
+
--eval_iters 50 \
|
| 18 |
+
--finetune true \
|
| 19 |
+
--cross_entropy_loss_fusion true \
|
| 20 |
+
--lr 1e-5 \
|
| 21 |
+
--lr_warmup_fraction 0.05 \
|
| 22 |
+
--min_lr 1e-6 \
|
| 23 |
+
--output_dir megatron_output/Qwen2.5-14B \
|
| 24 |
+
--eval_steps 200 \
|
| 25 |
+
--save_steps 200 \
|
| 26 |
+
--max_length 8192 \
|
| 27 |
+
--dataloader_num_workers 8 \
|
| 28 |
+
--dataset_num_proc 8 \
|
| 29 |
+
--no_save_optim true \
|
| 30 |
+
--no_save_rng true \
|
| 31 |
+
--sequence_parallel true \
|
| 32 |
+
--attention_backend flash
|
examples/megatron/long_text.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Env: 4 * A100
|
| 2 |
+
# Max Length: 32K
|
| 3 |
+
# GPU Memory: 4 * 50GB, Training Speed 23s/it
|
| 4 |
+
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \
|
| 5 |
+
NPROC_PER_NODE=4 \
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 \
|
| 7 |
+
megatron sft \
|
| 8 |
+
--model Qwen/Qwen2.5-7B \
|
| 9 |
+
--save_safetensors true \
|
| 10 |
+
--dataset 'ZhipuAI/LongWriter-6k' \
|
| 11 |
+
--load_from_cache_file true \
|
| 12 |
+
--split_dataset_ratio 0.01 \
|
| 13 |
+
--tensor_model_parallel_size 4 \
|
| 14 |
+
--micro_batch_size 1 \
|
| 15 |
+
--global_batch_size 8 \
|
| 16 |
+
--packing true \
|
| 17 |
+
--recompute_granularity full \
|
| 18 |
+
--recompute_method uniform \
|
| 19 |
+
--recompute_num_layers 1 \
|
| 20 |
+
--train_iters 1000 \
|
| 21 |
+
--eval_iters 50 \
|
| 22 |
+
--finetune true \
|
| 23 |
+
--cross_entropy_loss_fusion true \
|
| 24 |
+
--lr 1e-5 \
|
| 25 |
+
--lr_warmup_fraction 0.05 \
|
| 26 |
+
--min_lr 1e-6 \
|
| 27 |
+
--output_dir megatron_output/Qwen2.5-7B \
|
| 28 |
+
--eval_steps 200 \
|
| 29 |
+
--save_steps 200 \
|
| 30 |
+
--max_length 32768 \
|
| 31 |
+
--dataloader_num_workers 8 \
|
| 32 |
+
--dataset_num_proc 8 \
|
| 33 |
+
--no_save_optim true \
|
| 34 |
+
--no_save_rng true \
|
| 35 |
+
--sequence_parallel true \
|
| 36 |
+
--attention_backend flash
|
examples/megatron/muon.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# muon: 2 * 65GiB, 4m 14s
|
| 2 |
+
# adam(w): 2 * 78GiB, 1m 19s
|
| 3 |
+
# mcore>=0.16
|
| 4 |
+
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \
|
| 5 |
+
NPROC_PER_NODE=2 \
|
| 6 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 7 |
+
megatron sft \
|
| 8 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 9 |
+
--save_safetensors true \
|
| 10 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 11 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 12 |
+
'swift/self-cognition#500' \
|
| 13 |
+
--optimizer dist_muon \
|
| 14 |
+
--tensor_model_parallel_size 2 \
|
| 15 |
+
--sequence_parallel true \
|
| 16 |
+
--micro_batch_size 16 \
|
| 17 |
+
--global_batch_size 16 \
|
| 18 |
+
--recompute_granularity full \
|
| 19 |
+
--recompute_method uniform \
|
| 20 |
+
--recompute_num_layers 1 \
|
| 21 |
+
--finetune true \
|
| 22 |
+
--cross_entropy_loss_fusion true \
|
| 23 |
+
--lr 1e-5 \
|
| 24 |
+
--lr_warmup_fraction 0.05 \
|
| 25 |
+
--min_lr 1e-6 \
|
| 26 |
+
--num_train_epochs 1 \
|
| 27 |
+
--output_dir megatron_output/Qwen2.5-7B-Instruct \
|
| 28 |
+
--save_steps 100 \
|
| 29 |
+
--max_length 2048 \
|
| 30 |
+
--system 'You are a helpful assistant.' \
|
| 31 |
+
--dataloader_num_workers 4 \
|
| 32 |
+
--no_save_optim true \
|
| 33 |
+
--no_save_rng true \
|
| 34 |
+
--dataset_num_proc 4 \
|
| 35 |
+
--model_author swift \
|
| 36 |
+
--model_name swift-robot
|
examples/megatron/pretrain.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 4 * 80GiB
|
| 2 |
+
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \
|
| 3 |
+
NPROC_PER_NODE=4 \
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 \
|
| 5 |
+
megatron pt \
|
| 6 |
+
--model Qwen/Qwen2.5-7B \
|
| 7 |
+
--save_safetensors true \
|
| 8 |
+
--dataset swift/chinese-c4 \
|
| 9 |
+
--streaming true \
|
| 10 |
+
--packing true \
|
| 11 |
+
--tensor_model_parallel_size 4 \
|
| 12 |
+
--micro_batch_size 1 \
|
| 13 |
+
--global_batch_size 16 \
|
| 14 |
+
--recompute_granularity selective \
|
| 15 |
+
--train_iters 10000 \
|
| 16 |
+
--finetune true \
|
| 17 |
+
--cross_entropy_loss_fusion true \
|
| 18 |
+
--lr 1e-5 \
|
| 19 |
+
--lr_warmup_iters 300 \
|
| 20 |
+
--min_lr 1e-6 \
|
| 21 |
+
--output_dir megatron_output/Qwen2.5-7B \
|
| 22 |
+
--eval_steps 500 \
|
| 23 |
+
--save_steps 500 \
|
| 24 |
+
--max_length 8192 \
|
| 25 |
+
--dataloader_num_workers 4 \
|
| 26 |
+
--dataset_num_proc 8 \
|
| 27 |
+
--no_save_optim true \
|
| 28 |
+
--no_save_rng true \
|
| 29 |
+
--sequence_parallel true \
|
| 30 |
+
--attention_backend flash
|
examples/megatron/sft.sh
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 2 * 80GiB
|
| 2 |
+
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \
|
| 3 |
+
NPROC_PER_NODE=2 \
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 5 |
+
megatron sft \
|
| 6 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 7 |
+
--save_safetensors true \
|
| 8 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 9 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 10 |
+
'swift/self-cognition#500' \
|
| 11 |
+
--tensor_model_parallel_size 2 \
|
| 12 |
+
--sequence_parallel true \
|
| 13 |
+
--micro_batch_size 16 \
|
| 14 |
+
--global_batch_size 16 \
|
| 15 |
+
--recompute_granularity full \
|
| 16 |
+
--recompute_method uniform \
|
| 17 |
+
--recompute_num_layers 1 \
|
| 18 |
+
--finetune true \
|
| 19 |
+
--cross_entropy_loss_fusion true \
|
| 20 |
+
--lr 1e-5 \
|
| 21 |
+
--lr_warmup_fraction 0.05 \
|
| 22 |
+
--min_lr 1e-6 \
|
| 23 |
+
--num_train_epochs 1 \
|
| 24 |
+
--output_dir megatron_output/Qwen2.5-7B-Instruct \
|
| 25 |
+
--save_steps 100 \
|
| 26 |
+
--max_length 2048 \
|
| 27 |
+
--system 'You are a helpful assistant.' \
|
| 28 |
+
--dataloader_num_workers 4 \
|
| 29 |
+
--no_save_optim true \
|
| 30 |
+
--no_save_rng true \
|
| 31 |
+
--dataset_num_proc 4 \
|
| 32 |
+
--model_author swift \
|
| 33 |
+
--model_name swift-robot
|
examples/train/infer.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# If it's full parameter training, use `--model xxx` instead of `--adapters xxx`.
|
| 2 |
+
# If you are using the validation set for inference, add the parameter `--load_data_args true`.
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
swift infer \
|
| 5 |
+
--adapters output/vx-xxx/checkpoint-xxx \
|
| 6 |
+
--stream true \
|
| 7 |
+
--temperature 0 \
|
| 8 |
+
--max_new_tokens 2048
|
examples/train/lora_sft.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 22GB
|
| 2 |
+
# qwen3: https://github.com/modelscope/ms-swift/blob/main/examples/train/think_model/qwen3_demo1.sh
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
swift sft \
|
| 5 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 6 |
+
--tuner_type lora \
|
| 7 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 8 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 9 |
+
'swift/self-cognition#500' \
|
| 10 |
+
--torch_dtype bfloat16 \
|
| 11 |
+
--num_train_epochs 1 \
|
| 12 |
+
--per_device_train_batch_size 1 \
|
| 13 |
+
--per_device_eval_batch_size 1 \
|
| 14 |
+
--learning_rate 1e-4 \
|
| 15 |
+
--lora_rank 8 \
|
| 16 |
+
--lora_alpha 32 \
|
| 17 |
+
--target_modules all-linear \
|
| 18 |
+
--gradient_accumulation_steps 16 \
|
| 19 |
+
--eval_steps 50 \
|
| 20 |
+
--save_steps 50 \
|
| 21 |
+
--save_total_limit 2 \
|
| 22 |
+
--logging_steps 5 \
|
| 23 |
+
--max_length 2048 \
|
| 24 |
+
--output_dir output \
|
| 25 |
+
--system 'You are a helpful assistant.' \
|
| 26 |
+
--warmup_ratio 0.05 \
|
| 27 |
+
--dataset_num_proc 4 \
|
| 28 |
+
--dataloader_num_workers 4 \
|
| 29 |
+
--model_author swift \
|
| 30 |
+
--model_name swift-robot
|
examples/train/on_policy_distillation.sh
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# On-Policy Distillation https://thinkingmachines.ai/blog/on-policy-distillation/
|
| 2 |
+
|
| 3 |
+
# CUDA_VISIBLE_DEVICES=7 \
|
| 4 |
+
# swift rollout \
|
| 5 |
+
# --model Qwen/Qwen3-8B-Base \
|
| 6 |
+
# --vllm_max_model_len 24192
|
| 7 |
+
|
| 8 |
+
NPROC_PER_NODE=7 \
|
| 9 |
+
PYTORCH_CUDA_ALLOC_CONF='expandable_segments:True' \
|
| 10 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6 \
|
| 11 |
+
swift rlhf \
|
| 12 |
+
--rlhf_type gkd \
|
| 13 |
+
--model Qwen/Qwen3-8B-Base \
|
| 14 |
+
--teacher_model Qwen/Qwen3-32B \
|
| 15 |
+
--tuner_type full \
|
| 16 |
+
--dataset open-thoughts/OpenThoughts3-1.2M#10000 \
|
| 17 |
+
--seq_kd false \
|
| 18 |
+
--lmbda 1 \
|
| 19 |
+
--beta 1 \
|
| 20 |
+
--torch_dtype bfloat16 \
|
| 21 |
+
--num_train_epochs 1 \
|
| 22 |
+
--per_device_train_batch_size 1 \
|
| 23 |
+
--learning_rate 1e-5 \
|
| 24 |
+
--gradient_accumulation_steps 1 \
|
| 25 |
+
--save_steps 1000 \
|
| 26 |
+
--save_total_limit 2 \
|
| 27 |
+
--logging_steps 1 \
|
| 28 |
+
--max_length 16000 \
|
| 29 |
+
--max_completion_length 8192 \
|
| 30 |
+
--output_dir output \
|
| 31 |
+
--warmup_ratio 0.05 \
|
| 32 |
+
--save_only_model true \
|
| 33 |
+
--dataloader_num_workers 64 \
|
| 34 |
+
--dataset_num_proc 4 \
|
| 35 |
+
--deepspeed zero2 \
|
| 36 |
+
--teacher_deepspeed zero3 \
|
| 37 |
+
--attn_impl flash_attn \
|
| 38 |
+
--use_vllm true \
|
| 39 |
+
--vllm_mode server \
|
| 40 |
+
--vllm_server_host 127.0.0.1 \
|
| 41 |
+
--vllm_server_port 8000
|