Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- examples/app/base_url/demo.py +14 -0
- examples/app/base_url/demo.sh +7 -0
- examples/app/llm/sglang.sh +7 -0
- examples/app/llm/vllm.sh +8 -0
- examples/custom/my_qwen2_5_omni/my_register.py +455 -0
- examples/custom/my_qwen2_5_omni/test_register.py +89 -0
- examples/custom/my_qwen2_5_omni/train.py +42 -0
- examples/deploy/agent/client.py +90 -0
- examples/deploy/agent/server.sh +8 -0
- examples/deploy/bert/client.py +29 -0
- examples/deploy/bert/server.sh +10 -0
- examples/deploy/client/llm/base/openai_client.py +44 -0
- examples/deploy/client/llm/base/swift_client.py +37 -0
- examples/deploy/client/llm/chat/openai_client.py +47 -0
- examples/deploy/client/llm/chat/swift_client.py +60 -0
- examples/deploy/client/mllm/openai_client.py +98 -0
- examples/deploy/client/mllm/swift_client.py +127 -0
- examples/deploy/embedding/client.py +56 -0
- examples/deploy/embedding/server.sh +8 -0
- examples/deploy/lora/client.py +27 -0
- examples/deploy/lora/server.sh +7 -0
- examples/deploy/reranker/client.py +46 -0
- examples/deploy/reranker/client_generative.py +44 -0
- examples/deploy/reranker/server.sh +9 -0
- examples/deploy/reward_model/client.py +17 -0
- examples/deploy/reward_model/server.sh +5 -0
- examples/deploy/seq_cls/client.py +44 -0
- examples/deploy/seq_cls/server.sh +9 -0
- examples/eval/eval_url/demo.py +15 -0
- examples/eval/eval_url/eval.sh +7 -0
- examples/eval/llm/sglang.sh +7 -0
- examples/eval/llm/vllm.sh +7 -0
- examples/eval/train_eval/train.sh +24 -0
- examples/eval/vlm/eval.sh +8 -0
- examples/export/quantize/awq.sh +14 -0
- examples/export/quantize/bert/bnb.sh +16 -0
- examples/export/quantize/bert/gptq.sh +33 -0
- examples/export/quantize/bnb.sh +8 -0
- examples/export/quantize/fp8.sh +9 -0
- examples/export/quantize/gptq.sh +13 -0
- examples/export/quantize/gptq_v2.sh +14 -0
- examples/export/quantize/mllm/awq.sh +18 -0
- examples/export/quantize/mllm/bnb.sh +6 -0
- examples/export/quantize/mllm/fp8.sh +10 -0
- examples/export/quantize/mllm/gptq.sh +18 -0
- examples/export/quantize/moe/awq.sh +13 -0
- examples/export/quantize/moe/bnb.sh +6 -0
- examples/export/quantize/moe/fp8.sh +11 -0
- examples/export/quantize/moe/gptq.sh +13 -0
- examples/export/quantize/omni/gptq.sh +18 -0
examples/app/base_url/demo.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 5 |
+
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
from swift import AppArguments, DeployArguments, app_main, run_deploy
|
| 8 |
+
|
| 9 |
+
# Here's a runnable demo provided.
|
| 10 |
+
# In a real scenario, you can simply remove the deployed context.
|
| 11 |
+
with run_deploy(
|
| 12 |
+
DeployArguments(model='Qwen/Qwen2.5-1.5B-Instruct', verbose=False, log_interval=-1, infer_backend='vllm'),
|
| 13 |
+
return_url=True) as url:
|
| 14 |
+
app_main(AppArguments(model='Qwen2.5-1.5B-Instruct', base_url=url, stream=True, max_new_tokens=2048))
|
examples/app/base_url/demo.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# You need to have a deployed model or api service first
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 swift app \
|
| 3 |
+
--model '<model_name>' \
|
| 4 |
+
--base_url http://127.0.0.1:8000/v1 \
|
| 5 |
+
--stream true \
|
| 6 |
+
--max_new_tokens 2048 \
|
| 7 |
+
--lang zh
|
examples/app/llm/sglang.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# test_env: pip install "sglang[all]==0.4.6.*" -U
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 swift app \
|
| 3 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 4 |
+
--stream true \
|
| 5 |
+
--infer_backend sglang \
|
| 6 |
+
--max_new_tokens 2048 \
|
| 7 |
+
--lang zh
|
examples/app/llm/vllm.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 swift app \
|
| 2 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 3 |
+
--stream true \
|
| 4 |
+
--infer_backend vllm \
|
| 5 |
+
--max_new_tokens 2048 \
|
| 6 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 7 |
+
--vllm_max_model_len 8192 \
|
| 8 |
+
--lang zh
|
examples/custom/my_qwen2_5_omni/my_register.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from functools import partial
|
| 3 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 4 |
+
from transformers.integrations import is_deepspeed_zero3_enabled
|
| 5 |
+
from typing import Any, Dict, List, Literal, Optional
|
| 6 |
+
|
| 7 |
+
from swift.model import (Model, ModelGroup, ModelLoader, ModelMeta, MultiModelKeys, get_model_processor, register_model,
|
| 8 |
+
register_model_arch)
|
| 9 |
+
from swift.model.models.qwen import patch_qwen_vl_utils
|
| 10 |
+
from swift.model.patcher import patch_get_input_embeddings
|
| 11 |
+
from swift.model.utils import use_submodel_func
|
| 12 |
+
from swift.template import StdTemplateInputs, Template, TemplateMeta, get_template, register_template
|
| 13 |
+
from swift.template.utils import Context, findall
|
| 14 |
+
from swift.template.vision_utils import load_audio
|
| 15 |
+
from swift.utils import Processor, get_env_args, get_logger, get_packed_seq_params, is_deepspeed_enabled, to_float_dtype
|
| 16 |
+
|
| 17 |
+
register_model_arch(
|
| 18 |
+
MultiModelKeys(
|
| 19 |
+
'my_qwen2_5_omni',
|
| 20 |
+
# `freeze_llm`, `freeze_vit`, `freeze_aligner` behavior is determined by the values below.
|
| 21 |
+
# For example: full parameter training, if `freeze_vit=True`, it will freeze parameters of
|
| 22 |
+
# model layers prefixed with `thinker.audio_tower` and `thinker.visual`.
|
| 23 |
+
# LoRA training, if `freeze_vit=False`, it will additionally add LoRA to Linear layers
|
| 24 |
+
# prefixed with `thinker.audio_tower` and `thinker.visual`.
|
| 25 |
+
language_model=['thinker.model', 'thinker.lm_head'],
|
| 26 |
+
vision_tower=['thinker.audio_tower', 'thinker.visual'],
|
| 27 |
+
aligner=['thinker.audio_tower.proj', 'thinker.visual.merger'],
|
| 28 |
+
# Generator parts will never be trained or remain frozen.
|
| 29 |
+
# If you want `thinker.audio_tower` and `thinker.audio_tower.proj` to never be trained,
|
| 30 |
+
# you can place them in the generator and remove them from vision_tower and aligner.
|
| 31 |
+
generator=['talker', 'token2wav'],
|
| 32 |
+
))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Qwen2_5OmniLoader(ModelLoader):
|
| 36 |
+
|
| 37 |
+
def get_config(self, model_dir: str) -> PretrainedConfig:
|
| 38 |
+
from transformers import Qwen2_5OmniConfig
|
| 39 |
+
config = Qwen2_5OmniConfig.from_pretrained(model_dir, trust_remote_code=True)
|
| 40 |
+
enable_audio_output = get_env_args('ENABLE_AUDIO_OUTPUT', bool, None)
|
| 41 |
+
if enable_audio_output is not None:
|
| 42 |
+
config.enable_audio_output = enable_audio_output
|
| 43 |
+
return config
|
| 44 |
+
|
| 45 |
+
def get_processor(self, model_dir: str, config: PretrainedConfig) -> Processor:
|
| 46 |
+
from qwen_omni_utils import vision_process
|
| 47 |
+
from transformers import Qwen2_5OmniProcessor
|
| 48 |
+
processor = Qwen2_5OmniProcessor.from_pretrained(model_dir, trust_remote_code=True)
|
| 49 |
+
# Control constants in qwen_omni_utils library via environment variables,
|
| 50 |
+
# e.g., `MAX_PIXELS`, etc.
|
| 51 |
+
patch_qwen_vl_utils(vision_process)
|
| 52 |
+
return processor
|
| 53 |
+
|
| 54 |
+
def get_model(self, model_dir: str, config: PretrainedConfig, processor: Processor,
|
| 55 |
+
model_kwargs) -> PreTrainedModel:
|
| 56 |
+
from transformers import Qwen2_5OmniForConditionalGeneration
|
| 57 |
+
print('Run my_qwen2_5_omni...')
|
| 58 |
+
self.auto_model_cls = self.auto_model_cls or Qwen2_5OmniForConditionalGeneration
|
| 59 |
+
model = super().get_model(model_dir, config, processor, model_kwargs)
|
| 60 |
+
# For multimodal model consistency, we replace the model's forward/generate functions
|
| 61 |
+
# with those of its language_model.
|
| 62 |
+
# Handle additional parts separately.
|
| 63 |
+
use_submodel_func(model, 'thinker')
|
| 64 |
+
# Avoid inplace operations on leaf_variable during training
|
| 65 |
+
# (replacing parts of input_embeds with images_embeds)
|
| 66 |
+
patch_get_input_embeddings(model.thinker.visual, 'patch_embed')
|
| 67 |
+
# Some custom settings for model/config (usually not needed; configure based on
|
| 68 |
+
# specific model if errors occur during training/inference)
|
| 69 |
+
model.config.keys_to_ignore_at_inference += ['hidden_states', 'attention_mask']
|
| 70 |
+
model.config.talker_config.pad_token_id = None
|
| 71 |
+
return model
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
register_model(
|
| 75 |
+
ModelMeta(
|
| 76 |
+
'my_qwen2_5_omni',
|
| 77 |
+
[
|
| 78 |
+
ModelGroup([
|
| 79 |
+
Model('Qwen/Qwen2.5-Omni-3B', 'Qwen/Qwen2.5-Omni-3B'),
|
| 80 |
+
Model('Qwen/Qwen2.5-Omni-7B', 'Qwen/Qwen2.5-Omni-7B'),
|
| 81 |
+
]),
|
| 82 |
+
],
|
| 83 |
+
# Function to get model and processor.
|
| 84 |
+
Qwen2_5OmniLoader,
|
| 85 |
+
template='my_qwen2_5_omni',
|
| 86 |
+
is_multimodal=True, # Whether it's a multimodal model
|
| 87 |
+
model_arch='my_qwen2_5_omni', # Usually set only for multimodal models
|
| 88 |
+
# Used for automatic model_type matching
|
| 89 |
+
architectures=['Qwen2_5OmniModel', 'Qwen2_5OmniForConditionalGeneration'],
|
| 90 |
+
# Used to prompt users about dependency versions (can be removed)
|
| 91 |
+
requires=['transformers>=4.50', 'soundfile', 'qwen_omni_utils', 'decord'],
|
| 92 |
+
# Used to prompt users (can be removed)
|
| 93 |
+
tags=['vision', 'video', 'audio'],
|
| 94 |
+
# Additional files to save during full parameter training/merge-lora
|
| 95 |
+
additional_saved_files=['spk_dict.pt'],
|
| 96 |
+
))
|
| 97 |
+
|
| 98 |
+
if __name__ == '__main__':
|
| 99 |
+
# Test and debug
|
| 100 |
+
model, processor = get_model_processor('Qwen/Qwen2.5-Omni-7B', model_type='my_qwen2_5_omni')
|
| 101 |
+
|
| 102 |
+
logger = get_logger()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class Qwen2_5OmniTemplate(Template):
|
| 106 |
+
use_model = True # Whether model participation is required during preprocessing
|
| 107 |
+
# Note: Not all multimodal models support padding_free/packing. Models in `transformers` library usually support it
|
| 108 |
+
support_padding_free = True # Whether padding_free and packing are supported (multimodal models)
|
| 109 |
+
norm_bbox = 'none' # Whether grounding tasks use absolute or norm1000 coordinates
|
| 110 |
+
|
| 111 |
+
# These tokens will not be truncated (e.g., when setting `--truncation_strategy left/right`)
|
| 112 |
+
# and will be printed in abbreviated form (calling `template.safe_decode`)
|
| 113 |
+
placeholder_tokens = ['<|IMAGE|>', '<|AUDIO|>', '<|VIDEO|>']
|
| 114 |
+
|
| 115 |
+
def init_processor(self, processor) -> None:
|
| 116 |
+
"""Initialize some required constants when initializing the processor"""
|
| 117 |
+
if processor is None:
|
| 118 |
+
return
|
| 119 |
+
super().init_processor(processor)
|
| 120 |
+
from transformers.models.qwen2_5_omni.processing_qwen2_5_omni import Qwen2_5OmniProcessorKwargs
|
| 121 |
+
default = Qwen2_5OmniProcessorKwargs._defaults
|
| 122 |
+
self.seconds_per_chunk = default['videos_kwargs']['seconds_per_chunk']
|
| 123 |
+
self.position_id_per_seconds = default['videos_kwargs']['position_id_per_seconds']
|
| 124 |
+
self.use_audio_in_video = get_env_args('use_audio_in_video', bool, False)
|
| 125 |
+
self.sampling_rate = get_env_args('sampling_rate', int, self.processor.feature_extractor.sampling_rate)
|
| 126 |
+
# See grounding dataset customization documentation for `QWENVL_BBOX_FORMAT` meaning
|
| 127 |
+
self.bbox_format = get_env_args('QWENVL_BBOX_FORMAT', str, 'legacy')
|
| 128 |
+
|
| 129 |
+
def replace_tag(self, media_type: Literal['image', 'video', 'audio'], index: int,
|
| 130 |
+
inputs: StdTemplateInputs) -> List[Context]:
|
| 131 |
+
"""Load multimodal data and replace generic multimodal tags.
|
| 132 |
+
For example: image tag from `<image>` -> `<|vision_bos|><|IMAGE|><|vision_eos|>`"""
|
| 133 |
+
# Loading multimodal data can also be done in the `_encode` function, whichever is more convenient.
|
| 134 |
+
from qwen_omni_utils import fetch_image, fetch_video
|
| 135 |
+
if media_type == 'image':
|
| 136 |
+
inputs.images[index] = fetch_image({'image': inputs.images[index]})
|
| 137 |
+
return ['<|vision_bos|><|IMAGE|><|vision_eos|>']
|
| 138 |
+
elif media_type == 'audio':
|
| 139 |
+
if self.mode != 'vllm': # No processing needed in 'vllm' inference scenario
|
| 140 |
+
inputs.audios[index] = load_audio(inputs.audios[index], self.sampling_rate)
|
| 141 |
+
return ['<|audio_bos|><|AUDIO|><|audio_eos|>']
|
| 142 |
+
elif media_type == 'video':
|
| 143 |
+
video = inputs.videos[index]
|
| 144 |
+
_video = fetch_video({'video': video})
|
| 145 |
+
if isinstance(_video, torch.Tensor):
|
| 146 |
+
_video = _video.to(torch.uint8)
|
| 147 |
+
inputs.videos[index] = _video
|
| 148 |
+
if self.use_audio_in_video:
|
| 149 |
+
import librosa
|
| 150 |
+
if video.startswith('http://') or video.startswith('https://'):
|
| 151 |
+
import audioread
|
| 152 |
+
video = audioread.ffdec.FFmpegAudioFile(video)
|
| 153 |
+
video = librosa.load(video, sr=self.sampling_rate)[0]
|
| 154 |
+
inputs.audios.insert(inputs.audio_idx, (video, 'video'))
|
| 155 |
+
inputs.audio_idx += 1
|
| 156 |
+
return ['<|vision_bos|><|audio_bos|><|VIDEO|><|audio_eos|><|vision_eos|>']
|
| 157 |
+
else:
|
| 158 |
+
return ['<|vision_bos|><|VIDEO|><|vision_eos|>']
|
| 159 |
+
|
| 160 |
+
def replace_ref(self, ref: str, index: int, inputs: StdTemplateInputs) -> List[Context]:
|
| 161 |
+
"""Replace generic tag for grounding tasks: `<ref-object>`"""
|
| 162 |
+
if self.bbox_format == 'legacy':
|
| 163 |
+
return [f'<|object_ref_start|>{ref}<|object_ref_end|>']
|
| 164 |
+
else:
|
| 165 |
+
return [ref]
|
| 166 |
+
|
| 167 |
+
def replace_bbox(self, bbox: List[int], index: int, inputs: StdTemplateInputs) -> List[Context]:
|
| 168 |
+
"""Replace generic tag for grounding tasks: `<bbox>`"""
|
| 169 |
+
if self.bbox_format == 'legacy':
|
| 170 |
+
return [f'<|box_start|>{self._get_bbox_str(bbox)}<|box_end|>']
|
| 171 |
+
else:
|
| 172 |
+
return [str(bbox)]
|
| 173 |
+
|
| 174 |
+
def packing_row(self, row: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 175 |
+
"""Support packing & mrope.
|
| 176 |
+
|
| 177 |
+
Usually no need to inherit this function; here for customizing mrope's position_ids."""
|
| 178 |
+
position_ids = []
|
| 179 |
+
for r in row:
|
| 180 |
+
r = r.copy()
|
| 181 |
+
r['input_ids'] = torch.tensor(r['input_ids'])[None]
|
| 182 |
+
position_ids.append(self._get_position_ids(r))
|
| 183 |
+
packed = super().packing_row(row)
|
| 184 |
+
packed['position_ids'] = torch.concat(position_ids, dim=-1)
|
| 185 |
+
return packed
|
| 186 |
+
|
| 187 |
+
def _get_new_tokens_use_audio_in_video(self, i, *, video_grid_thw, video_second_per_grid, audio_lengths,
|
| 188 |
+
video_token_id, audio_token_id):
|
| 189 |
+
"""Helper function to support `use_audio_in_video` being True"""
|
| 190 |
+
merge_size = self.processor.image_processor.merge_size
|
| 191 |
+
grid_thw = video_grid_thw[i]
|
| 192 |
+
height = grid_thw[1] // merge_size
|
| 193 |
+
width = grid_thw[2] // merge_size
|
| 194 |
+
audio_token_indices = torch.arange(audio_lengths[i])
|
| 195 |
+
video_token_indices = torch.arange(grid_thw[0]).reshape(-1, 1, 1)
|
| 196 |
+
|
| 197 |
+
video_token_indices = torch.broadcast_to(video_token_indices,
|
| 198 |
+
(video_token_indices.shape[0], height, width)).reshape(-1)
|
| 199 |
+
video_token_indices = (video_token_indices * video_second_per_grid[i] * self.position_id_per_seconds)
|
| 200 |
+
tokens_per_chunk = int(self.position_id_per_seconds * self.seconds_per_chunk)
|
| 201 |
+
video_chunk_indexes = self.processor.get_chunked_index(video_token_indices, tokens_per_chunk)
|
| 202 |
+
audio_chunk_indexes = self.processor.get_chunked_index(audio_token_indices, tokens_per_chunk)
|
| 203 |
+
|
| 204 |
+
res = []
|
| 205 |
+
for j in range(max(len(video_chunk_indexes), len(audio_chunk_indexes))):
|
| 206 |
+
if j < len(video_chunk_indexes):
|
| 207 |
+
video_seq_length = video_chunk_indexes[j][1] - video_chunk_indexes[j][0]
|
| 208 |
+
res += video_token_id * video_seq_length
|
| 209 |
+
if j < len(audio_chunk_indexes):
|
| 210 |
+
audio_seq_length = audio_chunk_indexes[j][1] - audio_chunk_indexes[j][0]
|
| 211 |
+
res += audio_token_id * audio_seq_length
|
| 212 |
+
return res
|
| 213 |
+
|
| 214 |
+
def _encode(self, inputs: StdTemplateInputs) -> Dict[str, Any]:
|
| 215 |
+
"""This determines how to convert text/images/audios/videos ->
|
| 216 |
+
input_ids, labels, loss_scale, and multimodal content like pixel_values.
|
| 217 |
+
|
| 218 |
+
Processing logic can usually be borrowed from the corresponding model's preprocessing code implementation.
|
| 219 |
+
Recommended: Perform inference alignment first, then training."""
|
| 220 |
+
encoded = Template._encode(self, inputs) # Process text-only part; see custom model documentation for details
|
| 221 |
+
logger.info_once('Run qwen2_5_omni template')
|
| 222 |
+
processor = self.processor
|
| 223 |
+
# Get multimodal content
|
| 224 |
+
media_inputs = processor(
|
| 225 |
+
text='',
|
| 226 |
+
audio=inputs.audios or None,
|
| 227 |
+
images=inputs.images or None,
|
| 228 |
+
videos=inputs.videos or None,
|
| 229 |
+
do_resize=False,
|
| 230 |
+
return_tensors='pt')
|
| 231 |
+
# We don't use input_ids and attention_mask produced by `processor` because it doesn't produce `labels`.
|
| 232 |
+
media_inputs.pop('input_ids')
|
| 233 |
+
media_inputs.pop('attention_mask')
|
| 234 |
+
media_inputs = to_float_dtype(media_inputs, self.model_info.torch_dtype)
|
| 235 |
+
|
| 236 |
+
input_ids = encoded['input_ids']
|
| 237 |
+
labels = encoded['labels']
|
| 238 |
+
loss_scale = encoded.get('loss_scale', None)
|
| 239 |
+
# audio modality
|
| 240 |
+
audio_token_id = self._tokenize('<|AUDIO|>')
|
| 241 |
+
idx_list = findall(input_ids, audio_token_id) # Find all audio_tokens
|
| 242 |
+
feature_attention_mask = media_inputs.get('feature_attention_mask')
|
| 243 |
+
if feature_attention_mask is not None:
|
| 244 |
+
audio_feature_lengths = torch.sum(feature_attention_mask, dim=1)
|
| 245 |
+
audio_lengths = ((audio_feature_lengths - 1) // 2 + 1 - 2) // 2 + 1
|
| 246 |
+
else:
|
| 247 |
+
audio_lengths = None
|
| 248 |
+
audio_lengths_origin = audio_lengths
|
| 249 |
+
# video_audios_mask is used to handle `use_audio_in_video`, distinguishing pure audio(0) from audio in video(1)
|
| 250 |
+
video_audios_mask = []
|
| 251 |
+
for i, audio in enumerate(inputs.audios):
|
| 252 |
+
if isinstance(audio, tuple) and audio[1] == 'video':
|
| 253 |
+
inputs.audios[i] = audio[0]
|
| 254 |
+
video_audios_mask.append(True)
|
| 255 |
+
else:
|
| 256 |
+
video_audios_mask.append(False)
|
| 257 |
+
video_audios_mask = torch.tensor(video_audios_mask)
|
| 258 |
+
if idx_list:
|
| 259 |
+
# Filter out audio content in videos (will be handled in video section)
|
| 260 |
+
if self.use_audio_in_video:
|
| 261 |
+
audio_lengths = audio_lengths[~video_audios_mask]
|
| 262 |
+
|
| 263 |
+
def _get_new_audio_tokens(i):
|
| 264 |
+
return audio_token_id * audio_lengths[i]
|
| 265 |
+
|
| 266 |
+
# Expand multimodal tokens in input_ids
|
| 267 |
+
input_ids, labels, loss_scale = self._extend_tokens(input_ids, labels, loss_scale, idx_list,
|
| 268 |
+
_get_new_audio_tokens)
|
| 269 |
+
|
| 270 |
+
# image and video modalities
|
| 271 |
+
for media_type in ['image', 'video']:
|
| 272 |
+
token = f'<|{media_type.upper()}|>'
|
| 273 |
+
token_id = self._tokenize(token)
|
| 274 |
+
idx_list = findall(input_ids, token_id)
|
| 275 |
+
if idx_list:
|
| 276 |
+
merge_size = processor.image_processor.merge_size
|
| 277 |
+
media_grid_thw = media_inputs.get(f'{media_type}_grid_thw')
|
| 278 |
+
if media_type == 'video' and self.use_audio_in_video:
|
| 279 |
+
audio_lengths = audio_lengths_origin[video_audios_mask]
|
| 280 |
+
video_second_per_grid = media_inputs['video_second_per_grid']
|
| 281 |
+
_get_new_tokens_use_audio_in_video = partial(
|
| 282 |
+
self._get_new_tokens_use_audio_in_video,
|
| 283 |
+
video_grid_thw=media_grid_thw,
|
| 284 |
+
video_second_per_grid=video_second_per_grid,
|
| 285 |
+
audio_lengths=audio_lengths,
|
| 286 |
+
video_token_id=token_id,
|
| 287 |
+
audio_token_id=audio_token_id)
|
| 288 |
+
input_ids, labels, loss_scale = self._extend_tokens(input_ids, labels, loss_scale, idx_list,
|
| 289 |
+
_get_new_tokens_use_audio_in_video)
|
| 290 |
+
|
| 291 |
+
else:
|
| 292 |
+
|
| 293 |
+
def _get_new_tokens(i):
|
| 294 |
+
token_len = (media_grid_thw[i].prod() // (merge_size**2))
|
| 295 |
+
return token_id * token_len
|
| 296 |
+
|
| 297 |
+
input_ids, labels, loss_scale = self._extend_tokens(input_ids, labels, loss_scale, idx_list,
|
| 298 |
+
_get_new_tokens)
|
| 299 |
+
|
| 300 |
+
encoded['input_ids'] = input_ids
|
| 301 |
+
encoded['labels'] = labels
|
| 302 |
+
encoded['loss_scale'] = loss_scale
|
| 303 |
+
encoded.update(media_inputs) # Add multimodal content
|
| 304 |
+
return encoded
|
| 305 |
+
|
| 306 |
+
def _post_encode(self, model, inputs: Dict[str, Any]) -> Dict[str, Any]:
|
| 307 |
+
"""This function is typically used to solve the zero2/zero3 hanging issue in mixed model training,
|
| 308 |
+
i.e., some processes have pure text data without passing through vit,
|
| 309 |
+
while others have image data that passed through vit.
|
| 310 |
+
Here we create dummy_image to solve this.
|
| 311 |
+
|
| 312 |
+
This function will be registered in the pre_forward_hook before `model.forward`.
|
| 313 |
+
This function should return input_embeds containing multimodal information.
|
| 314 |
+
"""
|
| 315 |
+
if not self.is_training:
|
| 316 |
+
return inputs
|
| 317 |
+
|
| 318 |
+
input_ids = inputs['input_ids']
|
| 319 |
+
input_features = inputs.get('input_features')
|
| 320 |
+
feature_attention_mask = inputs.get('feature_attention_mask')
|
| 321 |
+
|
| 322 |
+
base_model = self.get_base_model(model)
|
| 323 |
+
inputs_embeds = base_model.thinker.model.embed_tokens(input_ids)
|
| 324 |
+
thinker_config = model.config.thinker_config
|
| 325 |
+
# Helper function for handling text/image/video mixed modality data scenarios. (internally creates dummy_image)
|
| 326 |
+
inputs_embeds = self._get_inputs_embeds_hf(inputs_embeds, inputs, model.thinker.visual, self.processor,
|
| 327 |
+
thinker_config)
|
| 328 |
+
# Mixed modality data scenarios containing audio
|
| 329 |
+
if input_features is None:
|
| 330 |
+
if is_deepspeed_enabled() and not is_deepspeed_zero3_enabled():
|
| 331 |
+
# Note: Due to transformers implementation,
|
| 332 |
+
# the number of passes through audio model layers is related to the number of audios
|
| 333 |
+
# Therefore, zero3 will hang in scenarios where different processes have different numbers of audios
|
| 334 |
+
# (requires modification of transformers code to fix).
|
| 335 |
+
# Use zero2 in this scenario.
|
| 336 |
+
input_features = input_ids.new_zeros([1, 128, 128], dtype=model.thinker.audio_tower.dtype)
|
| 337 |
+
feature_attention_mask = input_ids.new_ones([1, 128], dtype=torch.bool)
|
| 338 |
+
audio_res = model.thinker.get_audio_features(input_features, feature_attention_mask)
|
| 339 |
+
# Compatible with transformers 5.0
|
| 340 |
+
if hasattr(audio_res, 'last_hidden_state'):
|
| 341 |
+
audio_embeds = audio_res.last_hidden_state
|
| 342 |
+
else:
|
| 343 |
+
audio_embeds = audio_res
|
| 344 |
+
inputs_embeds = inputs_embeds + audio_embeds.mean() * 0.
|
| 345 |
+
else:
|
| 346 |
+
audio_res = model.thinker.get_audio_features(input_features, feature_attention_mask)
|
| 347 |
+
# Compatible with transformers 5.0
|
| 348 |
+
if hasattr(audio_res, 'last_hidden_state'):
|
| 349 |
+
audio_embeds = audio_res.last_hidden_state
|
| 350 |
+
else:
|
| 351 |
+
audio_embeds = audio_res
|
| 352 |
+
audio_mask = (input_ids == thinker_config.audio_token_index).unsqueeze(-1).expand_as(inputs_embeds)
|
| 353 |
+
audio_embeds = audio_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 354 |
+
inputs_embeds = inputs_embeds.masked_scatter(audio_mask, audio_embeds)
|
| 355 |
+
|
| 356 |
+
return {'inputs_embeds': inputs_embeds}
|
| 357 |
+
|
| 358 |
+
def _get_position_ids(self, inputs: Dict[str, Any]):
|
| 359 |
+
"""Helper function to get mrope's position_ids"""
|
| 360 |
+
feature_attention_mask = inputs.get('feature_attention_mask')
|
| 361 |
+
if feature_attention_mask is not None:
|
| 362 |
+
audio_feature_lengths = torch.sum(feature_attention_mask, dim=1)
|
| 363 |
+
else:
|
| 364 |
+
audio_feature_lengths = None
|
| 365 |
+
video_second_per_grid = inputs.pop('video_second_per_grid', None)
|
| 366 |
+
input_ids = inputs['input_ids']
|
| 367 |
+
attention_mask = inputs.get('attention_mask')
|
| 368 |
+
if attention_mask is None:
|
| 369 |
+
attention_mask = torch.ones_like(input_ids)
|
| 370 |
+
position_ids, _ = self.model.thinker.get_rope_index(
|
| 371 |
+
input_ids,
|
| 372 |
+
inputs.get('image_grid_thw'),
|
| 373 |
+
inputs.get('video_grid_thw'),
|
| 374 |
+
attention_mask,
|
| 375 |
+
self.use_audio_in_video,
|
| 376 |
+
audio_feature_lengths,
|
| 377 |
+
video_second_per_grid,
|
| 378 |
+
)
|
| 379 |
+
return self._concat_text_position_ids(position_ids) # First dimension is text_position_ids
|
| 380 |
+
|
| 381 |
+
def _data_collator(self, batch: List[Dict[str, Any]], *, padding_to: Optional[int] = None) -> Dict[str, Any]:
|
| 382 |
+
"""Passed to dataloader's `collate_fn`"""
|
| 383 |
+
res = super()._data_collator(batch, padding_to=padding_to)
|
| 384 |
+
if not self.padding_free and self.is_training:
|
| 385 |
+
# padding_free/packing scenarios will handle position_ids in packing_row.
|
| 386 |
+
res['position_ids'] = self._get_position_ids(res)
|
| 387 |
+
if 'position_ids' in res:
|
| 388 |
+
# Create `packed_seq_params` to support padding_free/packing & flash-attn
|
| 389 |
+
position_ids = res['position_ids']
|
| 390 |
+
res['position_ids'] = position_ids[1:]
|
| 391 |
+
res['text_position_ids'] = text_position_ids = position_ids[0]
|
| 392 |
+
# https://github.com/huggingface/transformers/pull/40194
|
| 393 |
+
res.update(get_packed_seq_params(text_position_ids))
|
| 394 |
+
return res
|
| 395 |
+
|
| 396 |
+
def _data_collator_mm_data(self, batch: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 397 |
+
"""Handle multimodal part in `_data_collator` function.
|
| 398 |
+
(This function is compatible with padding_free/packing)"""
|
| 399 |
+
res = super()._data_collator_mm_data(batch)
|
| 400 |
+
video_second_per_grid = self.gather_list(batch, 'video_second_per_grid')
|
| 401 |
+
if video_second_per_grid:
|
| 402 |
+
res['video_second_per_grid'] = video_second_per_grid
|
| 403 |
+
input_features = [b['input_features'] for b in batch if b.get('input_features') is not None]
|
| 404 |
+
feature_attention_mask = [
|
| 405 |
+
b['feature_attention_mask'] for b in batch if b.get('feature_attention_mask') is not None
|
| 406 |
+
]
|
| 407 |
+
if input_features:
|
| 408 |
+
res['input_features'] = torch.concat(input_features)
|
| 409 |
+
res['feature_attention_mask'] = torch.concat(feature_attention_mask)
|
| 410 |
+
return res
|
| 411 |
+
|
| 412 |
+
def generate(self, model, *args, **kwargs):
|
| 413 |
+
"""`TransformersEngine` will call template.generate method for text generation;
|
| 414 |
+
inherit here for customization."""
|
| 415 |
+
if kwargs.get('video_grid_thw') is not None:
|
| 416 |
+
kwargs['use_audio_in_video'] = self.use_audio_in_video
|
| 417 |
+
return super().generate(model, *args, **kwargs)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
register_template(
|
| 421 |
+
TemplateMeta(
|
| 422 |
+
'my_qwen2_5_omni',
|
| 423 |
+
prefix=[],
|
| 424 |
+
prompt=['<|im_start|>user\n{{QUERY}}<|im_end|>\n<|im_start|>assistant\n'],
|
| 425 |
+
chat_sep=['<|im_end|>\n'],
|
| 426 |
+
suffix=['<|im_end|>'],
|
| 427 |
+
system_prefix=['<|im_start|>system\n{{SYSTEM}}<|im_end|>\n'],
|
| 428 |
+
default_system='You are a helpful assistant.',
|
| 429 |
+
stop_words=['<|endoftext|>'],
|
| 430 |
+
agent_template='hermes',
|
| 431 |
+
template_cls=Qwen2_5OmniTemplate))
|
| 432 |
+
|
| 433 |
+
if __name__ == '__main__':
|
| 434 |
+
# Test and debug
|
| 435 |
+
model, processor = get_model_processor('Qwen/Qwen2.5-Omni-7B', model_type='my_qwen2_5_omni')
|
| 436 |
+
template = get_template(processor, template_type='my_qwen2_5_omni')
|
| 437 |
+
data = {
|
| 438 |
+
'messages': [
|
| 439 |
+
{
|
| 440 |
+
'role': 'user',
|
| 441 |
+
'content': 'Describe the video<video> and image<image> content.'
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
'role': 'assistant',
|
| 445 |
+
'content': 'A child and a cat.'
|
| 446 |
+
},
|
| 447 |
+
],
|
| 448 |
+
'videos': ['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'],
|
| 449 |
+
'images': ['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png'],
|
| 450 |
+
}
|
| 451 |
+
template.set_mode('train')
|
| 452 |
+
encoded = template.encode(data)
|
| 453 |
+
print('input_ids: ' + template.safe_decode(encoded['input_ids']))
|
| 454 |
+
print('labels: ' + template.safe_decode(encoded['labels']))
|
| 455 |
+
print('keys: ' + str(encoded.keys()))
|
examples/custom/my_qwen2_5_omni/test_register.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import sys
|
| 4 |
+
from modelscope import snapshot_download
|
| 5 |
+
from qwen_omni_utils import process_mm_info
|
| 6 |
+
from transformers import Qwen2_5OmniForConditionalGeneration, Qwen2_5OmniProcessor
|
| 7 |
+
|
| 8 |
+
from swift.infer_engine import InferRequest, RequestConfig, TransformersEngine
|
| 9 |
+
|
| 10 |
+
sys.path.append('examples/custom/my_qwen2_5_omni')
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def infer_hf():
|
| 14 |
+
model_dir = snapshot_download('Qwen/Qwen2.5-Omni-7B')
|
| 15 |
+
model = Qwen2_5OmniForConditionalGeneration.from_pretrained(
|
| 16 |
+
model_dir, torch_dtype='auto', device_map='auto', attn_implementation='flash_attention_2')
|
| 17 |
+
processor = Qwen2_5OmniProcessor.from_pretrained(model_dir)
|
| 18 |
+
# Use decord to read video (url not yet supported)
|
| 19 |
+
resp = requests.get('https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4')
|
| 20 |
+
with open('_baby.mp4', 'wb') as f:
|
| 21 |
+
f.write(resp.content)
|
| 22 |
+
|
| 23 |
+
conversation = [
|
| 24 |
+
{
|
| 25 |
+
'role':
|
| 26 |
+
'user',
|
| 27 |
+
'content': [
|
| 28 |
+
{
|
| 29 |
+
'type': 'video',
|
| 30 |
+
'video': '_baby.mp4'
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
'type': 'image',
|
| 34 |
+
'image': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png'
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
'type': 'text',
|
| 38 |
+
'text': 'Describe the video and image.'
|
| 39 |
+
},
|
| 40 |
+
],
|
| 41 |
+
},
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
USE_AUDIO_IN_VIDEO = False
|
| 45 |
+
text = processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
|
| 46 |
+
audios, images, videos = process_mm_info(conversation, use_audio_in_video=USE_AUDIO_IN_VIDEO)
|
| 47 |
+
inputs = processor(
|
| 48 |
+
text=text,
|
| 49 |
+
audio=audios,
|
| 50 |
+
images=images,
|
| 51 |
+
videos=videos,
|
| 52 |
+
return_tensors='pt',
|
| 53 |
+
padding=True,
|
| 54 |
+
use_audio_in_video=USE_AUDIO_IN_VIDEO)
|
| 55 |
+
inputs = inputs.to(model.device).to(model.dtype)
|
| 56 |
+
text_ids = model.generate(
|
| 57 |
+
**inputs, use_audio_in_video=USE_AUDIO_IN_VIDEO, thinker_do_sample=False, return_audio=False)
|
| 58 |
+
text = processor.batch_decode(
|
| 59 |
+
text_ids[:, inputs['input_ids'].shape[1]:], skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 60 |
+
return inputs['input_ids'][0].tolist(), text[0]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_my_qwen2_5_omni():
|
| 64 |
+
engine = TransformersEngine('Qwen/Qwen2.5-Omni-7B', model_type='my_qwen2_5_omni', attn_impl='flash_attention_2')
|
| 65 |
+
infer_request = InferRequest(
|
| 66 |
+
messages=[{
|
| 67 |
+
'role': 'user',
|
| 68 |
+
'content': '<video><image>Describe the video and image.',
|
| 69 |
+
}],
|
| 70 |
+
videos=['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'],
|
| 71 |
+
images=['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png'],
|
| 72 |
+
)
|
| 73 |
+
request_config = RequestConfig(temperature=0, max_tokens=512)
|
| 74 |
+
input_ids = engine.template.encode(infer_request)['input_ids']
|
| 75 |
+
resp_list = engine.infer([infer_request], request_config)
|
| 76 |
+
resp = resp_list[0].choices[0].message.content
|
| 77 |
+
return input_ids, resp
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == '__main__':
|
| 81 |
+
import my_register
|
| 82 |
+
|
| 83 |
+
# Enable debug mode, will print input_ids and generate_ids from `TransformersEngine.infer`
|
| 84 |
+
os.environ['SWIFT_DEBUG'] = '1'
|
| 85 |
+
input_ids_hf, response_hf = infer_hf()
|
| 86 |
+
input_ids_swift, response_swift = test_my_qwen2_5_omni()
|
| 87 |
+
# Test input_ids and response alignment
|
| 88 |
+
assert input_ids_hf == input_ids_swift
|
| 89 |
+
assert response_hf == response_swift
|
examples/custom/my_qwen2_5_omni/train.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from swift import SftArguments, sft_main
|
| 5 |
+
|
| 6 |
+
sys.path.append('examples/custom/my_qwen2_5_omni')
|
| 7 |
+
|
| 8 |
+
if __name__ == '__main__':
|
| 9 |
+
import my_register
|
| 10 |
+
os.environ['MAX_PIXELS'] = '1003520'
|
| 11 |
+
sft_main(
|
| 12 |
+
SftArguments(
|
| 13 |
+
model='Qwen/Qwen2.5-Omni-7B',
|
| 14 |
+
dataset=['AI-ModelScope/LaTeX_OCR#5000'],
|
| 15 |
+
model_type='my_qwen2_5_omni',
|
| 16 |
+
template='my_qwen2_5_omni',
|
| 17 |
+
load_from_cache_file=True,
|
| 18 |
+
split_dataset_ratio=0.01,
|
| 19 |
+
tuner_type='lora',
|
| 20 |
+
torch_dtype='bfloat16',
|
| 21 |
+
attn_impl='flash_attn',
|
| 22 |
+
padding_free=True,
|
| 23 |
+
num_train_epochs=1,
|
| 24 |
+
per_device_train_batch_size=16,
|
| 25 |
+
per_device_eval_batch_size=16,
|
| 26 |
+
learning_rate=1e-4,
|
| 27 |
+
lora_rank=8,
|
| 28 |
+
lora_alpha=32,
|
| 29 |
+
target_modules=['all-linear'],
|
| 30 |
+
freeze_vit=True,
|
| 31 |
+
freeze_aligner=True,
|
| 32 |
+
gradient_accumulation_steps=1,
|
| 33 |
+
eval_steps=50,
|
| 34 |
+
save_steps=50,
|
| 35 |
+
save_total_limit=2,
|
| 36 |
+
logging_steps=5,
|
| 37 |
+
max_length=2048,
|
| 38 |
+
output_dir='output',
|
| 39 |
+
warmup_ratio=0.05,
|
| 40 |
+
dataloader_num_workers=4,
|
| 41 |
+
dataset_num_proc=1,
|
| 42 |
+
))
|
examples/deploy/agent/client.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_infer_request():
|
| 9 |
+
messages = [{'role': 'user', 'content': "How's the weather in Beijing today?"}]
|
| 10 |
+
tools = [{
|
| 11 |
+
'name': 'get_current_weather',
|
| 12 |
+
'description': 'Get the current weather in a given location',
|
| 13 |
+
'parameters': {
|
| 14 |
+
'type': 'object',
|
| 15 |
+
'properties': {
|
| 16 |
+
'location': {
|
| 17 |
+
'type': 'string',
|
| 18 |
+
'description': 'The city and state, e.g. San Francisco, CA'
|
| 19 |
+
},
|
| 20 |
+
'unit': {
|
| 21 |
+
'type': 'string',
|
| 22 |
+
'enum': ['celsius', 'fahrenheit']
|
| 23 |
+
}
|
| 24 |
+
},
|
| 25 |
+
'required': ['location']
|
| 26 |
+
}
|
| 27 |
+
}]
|
| 28 |
+
return messages, tools
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def infer(client, model: str, messages, tools):
|
| 32 |
+
messages = messages.copy()
|
| 33 |
+
query = messages[0]['content']
|
| 34 |
+
resp = client.chat.completions.create(model=model, messages=messages, tools=tools, max_tokens=512, temperature=0)
|
| 35 |
+
response = resp.choices[0].message.content
|
| 36 |
+
print(f'query: {query}')
|
| 37 |
+
print(f'response: {response}')
|
| 38 |
+
print(f'tool_calls: {resp.choices[0].message.tool_calls}')
|
| 39 |
+
|
| 40 |
+
tool = '{"temperature": 32, "condition": "Sunny", "humidity": 50}'
|
| 41 |
+
print(f'tool_response: {tool}')
|
| 42 |
+
messages += [{'role': 'assistant', 'content': response}, {'role': 'tool', 'content': tool}]
|
| 43 |
+
resp = client.chat.completions.create(model=model, messages=messages, tools=tools, max_tokens=512, temperature=0)
|
| 44 |
+
response2 = resp.choices[0].message.content
|
| 45 |
+
print(f'response2: {response2}')
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# streaming
|
| 49 |
+
def infer_stream(client, model: str, messages, tools):
|
| 50 |
+
messages = messages.copy()
|
| 51 |
+
query = messages[0]['content']
|
| 52 |
+
gen = client.chat.completions.create(
|
| 53 |
+
model=model, messages=messages, tools=tools, max_tokens=512, temperature=0, stream=True)
|
| 54 |
+
response = ''
|
| 55 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 56 |
+
for chunk in gen:
|
| 57 |
+
if chunk is None:
|
| 58 |
+
continue
|
| 59 |
+
delta = chunk.choices[0].delta.content
|
| 60 |
+
response += delta
|
| 61 |
+
print(delta, end='', flush=True)
|
| 62 |
+
print()
|
| 63 |
+
print(f'tool_calls: {chunk.choices[0].delta.tool_calls}')
|
| 64 |
+
|
| 65 |
+
tool = '{"temperature": 32, "condition": "Sunny", "humidity": 50}'
|
| 66 |
+
print(f'tool_response: {tool}')
|
| 67 |
+
messages += [{'role': 'assistant', 'content': response}, {'role': 'tool', 'content': tool}]
|
| 68 |
+
gen = client.chat.completions.create(
|
| 69 |
+
model=model, messages=messages, tools=tools, max_tokens=512, temperature=0, stream=True)
|
| 70 |
+
print(f'query: {query}\nresponse2: ', end='')
|
| 71 |
+
for chunk in gen:
|
| 72 |
+
if chunk is None:
|
| 73 |
+
continue
|
| 74 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 75 |
+
print()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == '__main__':
|
| 79 |
+
host: str = '127.0.0.1'
|
| 80 |
+
port: int = 8000
|
| 81 |
+
client = OpenAI(
|
| 82 |
+
api_key='EMPTY',
|
| 83 |
+
base_url=f'http://{host}:{port}/v1',
|
| 84 |
+
)
|
| 85 |
+
model = client.models.list().data[0].id
|
| 86 |
+
print(f'model: {model}')
|
| 87 |
+
|
| 88 |
+
messages, tools = get_infer_request()
|
| 89 |
+
infer(client, model, messages, tools)
|
| 90 |
+
infer_stream(client, model, messages, tools)
|
examples/deploy/agent/server.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 2 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 3 |
+
--infer_backend vllm \
|
| 4 |
+
--vllm_gpu_memory_utilization 0.9 \
|
| 5 |
+
--vllm_max_model_len 8192 \
|
| 6 |
+
--max_new_tokens 2048 \
|
| 7 |
+
--agent_template hermes \
|
| 8 |
+
--served_model_name Qwen2.5-7B-Instruct
|
examples/deploy/bert/client.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
from swift.infer_engine import InferClient, InferRequest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def infer_batch(engine: InferClient, infer_requests: List[InferRequest]):
|
| 7 |
+
resp_list = engine.infer(infer_requests)
|
| 8 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 9 |
+
query1 = infer_requests[1].messages[0]['content']
|
| 10 |
+
print(f'query0: {query0}')
|
| 11 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 12 |
+
print(f'query1: {query1}')
|
| 13 |
+
print(f'response1: {resp_list[1].choices[0].message.content}')
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if __name__ == '__main__':
|
| 17 |
+
engine = InferClient(host='127.0.0.1', port=8000)
|
| 18 |
+
models = engine.models
|
| 19 |
+
print(f'models: {models}')
|
| 20 |
+
infer_batch(engine, [
|
| 21 |
+
InferRequest(messages=[{
|
| 22 |
+
'role': 'user',
|
| 23 |
+
'content': '今天天气真好呀'
|
| 24 |
+
}]),
|
| 25 |
+
InferRequest(messages=[{
|
| 26 |
+
'role': 'user',
|
| 27 |
+
'content': '真倒霉'
|
| 28 |
+
}])
|
| 29 |
+
])
|
examples/deploy/bert/server.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Since `swift/test_lora` 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 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 4 |
+
--host 0.0.0.0 \
|
| 5 |
+
--port 8000 \
|
| 6 |
+
--adapters swift/test_bert \
|
| 7 |
+
--served_model_name bert-base-chinese \
|
| 8 |
+
--infer_backend transformers \
|
| 9 |
+
--truncation_strategy right \
|
| 10 |
+
--max_length 512
|
examples/deploy/client/llm/base/openai_client.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(client, model: str, messages):
|
| 9 |
+
query = messages[0]['content']
|
| 10 |
+
print(f'query: {query}')
|
| 11 |
+
resp = client.completions.create(model=model, prompt=query, max_tokens=64, temperature=0)
|
| 12 |
+
response = resp.choices[0].text
|
| 13 |
+
print(f'response: {response}')
|
| 14 |
+
# or (The two calling methods are equivalent.)
|
| 15 |
+
resp = client.chat.completions.create(model=model, messages=messages, max_tokens=64, temperature=0)
|
| 16 |
+
response = resp.choices[0].message.content
|
| 17 |
+
print(f'response: {response}')
|
| 18 |
+
return response
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 22 |
+
client = OpenAI(
|
| 23 |
+
api_key='EMPTY',
|
| 24 |
+
base_url=f'http://{host}:{port}/v1',
|
| 25 |
+
)
|
| 26 |
+
model = client.models.list().data[0].id
|
| 27 |
+
print(f'model: {model}')
|
| 28 |
+
|
| 29 |
+
messages = [{'role': 'user', 'content': '浙江 -> 杭州\n安徽 -> 合肥\n四川 ->'}]
|
| 30 |
+
infer(client, model, messages)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
from swift import DeployArguments, run_deploy
|
| 35 |
+
|
| 36 |
+
# NOTE: In a real deployment scenario, please comment out the context of run_deploy.
|
| 37 |
+
with run_deploy(
|
| 38 |
+
DeployArguments(
|
| 39 |
+
model='Qwen/Qwen2.5-1.5B',
|
| 40 |
+
verbose=False,
|
| 41 |
+
log_interval=-1,
|
| 42 |
+
infer_backend='transformers',
|
| 43 |
+
use_chat_template=False)) as port:
|
| 44 |
+
run_client(port=port)
|
examples/deploy/client/llm/base/swift_client.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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=64, temperature=0)
|
| 10 |
+
|
| 11 |
+
resp_list = engine.infer(infer_requests, request_config)
|
| 12 |
+
|
| 13 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 14 |
+
print(f'query0: {query0}')
|
| 15 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 19 |
+
engine = InferClient(host=host, port=port)
|
| 20 |
+
print(f'models: {engine.models}')
|
| 21 |
+
|
| 22 |
+
infer_requests = [InferRequest(messages=[{'role': 'user', 'content': '浙江 -> 杭州\n安徽 -> 合肥\n四川 ->'}])]
|
| 23 |
+
infer_batch(engine, infer_requests)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__ == '__main__':
|
| 27 |
+
from swift import DeployArguments, InferClient, InferEngine, InferRequest, RequestConfig, run_deploy
|
| 28 |
+
|
| 29 |
+
# NOTE: In a real deployment scenario, please comment out the context of run_deploy.
|
| 30 |
+
with run_deploy(
|
| 31 |
+
DeployArguments(
|
| 32 |
+
model='Qwen/Qwen2.5-1.5B',
|
| 33 |
+
verbose=False,
|
| 34 |
+
log_interval=-1,
|
| 35 |
+
infer_backend='transformers',
|
| 36 |
+
use_chat_template=False)) as port:
|
| 37 |
+
run_client(port=port)
|
examples/deploy/client/llm/chat/openai_client.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(client, model: str, messages):
|
| 9 |
+
resp = client.chat.completions.create(model=model, messages=messages, max_tokens=512, temperature=0)
|
| 10 |
+
query = messages[0]['content']
|
| 11 |
+
response = resp.choices[0].message.content
|
| 12 |
+
print(f'query: {query}')
|
| 13 |
+
print(f'response: {response}')
|
| 14 |
+
return response
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# streaming
|
| 18 |
+
def infer_stream(client, model: str, messages):
|
| 19 |
+
gen = client.chat.completions.create(model=model, messages=messages, stream=True, temperature=0)
|
| 20 |
+
print(f'messages: {messages}\nresponse: ', end='')
|
| 21 |
+
for chunk in gen:
|
| 22 |
+
if chunk is None:
|
| 23 |
+
continue
|
| 24 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 25 |
+
print()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 29 |
+
client = OpenAI(
|
| 30 |
+
api_key='EMPTY',
|
| 31 |
+
base_url=f'http://{host}:{port}/v1',
|
| 32 |
+
)
|
| 33 |
+
model = client.models.list().data[0].id
|
| 34 |
+
print(f'model: {model}')
|
| 35 |
+
|
| 36 |
+
query = 'Where is the capital of Zhejiang?'
|
| 37 |
+
messages = [{'role': 'user', 'content': query}]
|
| 38 |
+
response = infer(client, model, messages)
|
| 39 |
+
messages.append({'role': 'assistant', 'content': response})
|
| 40 |
+
messages.append({'role': 'user', 'content': 'What delicious food is there?'})
|
| 41 |
+
infer_stream(client, model, messages)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == '__main__':
|
| 45 |
+
from swift import DeployArguments, run_deploy
|
| 46 |
+
with run_deploy(DeployArguments(model='Qwen/Qwen2.5-1.5B-Instruct', verbose=False, log_interval=-1)) as port:
|
| 47 |
+
run_client(port=port)
|
examples/deploy/client/llm/chat/swift_client.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 12 |
+
resp_list = engine.infer(infer_requests, request_config, metrics=[metric])
|
| 13 |
+
# # The asynchronous interface below is equivalent to the synchronous interface above.
|
| 14 |
+
# async def _run():
|
| 15 |
+
# tasks = [engine.infer_async(infer_request, request_config) for infer_request in infer_requests]
|
| 16 |
+
# return await asyncio.gather(*tasks)
|
| 17 |
+
# resp_list = asyncio.run(_run())
|
| 18 |
+
|
| 19 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 20 |
+
print(f'query0: {query0}')
|
| 21 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 22 |
+
print(f'metric: {metric.compute()}')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def infer_stream(engine: 'InferEngine', infer_request: 'InferRequest'):
|
| 26 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
|
| 27 |
+
metric = InferStats()
|
| 28 |
+
gen_list = engine.infer([infer_request], request_config, metrics=[metric])
|
| 29 |
+
query = infer_request.messages[0]['content']
|
| 30 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 31 |
+
for resp in gen_list[0]:
|
| 32 |
+
if resp is None:
|
| 33 |
+
continue
|
| 34 |
+
print(resp.choices[0].delta.content, end='', flush=True)
|
| 35 |
+
print()
|
| 36 |
+
print(f'metric: {metric.compute()}')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 40 |
+
engine = InferClient(host=host, port=port)
|
| 41 |
+
print(f'models: {engine.models}')
|
| 42 |
+
# Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
|
| 43 |
+
dataset = load_dataset(['AI-ModelScope/alpaca-gpt4-data-zh#1000'], seed=42)[0]
|
| 44 |
+
print(f'dataset: {dataset}')
|
| 45 |
+
infer_requests = [InferRequest(**data) for data in dataset]
|
| 46 |
+
infer_batch(engine, infer_requests)
|
| 47 |
+
|
| 48 |
+
messages = [{'role': 'user', 'content': 'who are you?'}]
|
| 49 |
+
infer_stream(engine, InferRequest(messages=messages))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if __name__ == '__main__':
|
| 53 |
+
from swift import (DeployArguments, InferClient, InferEngine, InferRequest, InferStats, RequestConfig, load_dataset,
|
| 54 |
+
run_deploy)
|
| 55 |
+
|
| 56 |
+
# NOTE: In a real deployment scenario, please comment out the context of run_deploy.
|
| 57 |
+
with run_deploy(
|
| 58 |
+
DeployArguments(model='Qwen/Qwen2.5-1.5B-Instruct', verbose=False, log_interval=-1,
|
| 59 |
+
infer_backend='vllm')) as port:
|
| 60 |
+
run_client(port=port)
|
examples/deploy/client/mllm/openai_client.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
from typing import Literal
|
| 5 |
+
|
| 6 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def infer(client, model: str, messages):
|
| 10 |
+
resp = client.chat.completions.create(model=model, messages=messages, max_tokens=512, temperature=0)
|
| 11 |
+
query = messages[0]['content']
|
| 12 |
+
response = resp.choices[0].message.content
|
| 13 |
+
print(f'query: {query}')
|
| 14 |
+
print(f'response: {response}')
|
| 15 |
+
return response
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# streaming
|
| 19 |
+
def infer_stream(client, model: str, messages):
|
| 20 |
+
gen = client.chat.completions.create(model=model, messages=messages, stream=True, temperature=0)
|
| 21 |
+
print(f'messages: {messages}\nresponse: ', end='')
|
| 22 |
+
for chunk in gen:
|
| 23 |
+
if chunk is None:
|
| 24 |
+
continue
|
| 25 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 26 |
+
print()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_message(mm_type: Literal['text', 'image', 'video', 'audio']):
|
| 30 |
+
if mm_type == 'text':
|
| 31 |
+
message = {'role': 'user', 'content': 'who are you?'}
|
| 32 |
+
elif mm_type == 'image':
|
| 33 |
+
message = {
|
| 34 |
+
'role':
|
| 35 |
+
'user',
|
| 36 |
+
'content': [{
|
| 37 |
+
'type': 'image',
|
| 38 |
+
'image': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png'
|
| 39 |
+
}, {
|
| 40 |
+
'type': 'text',
|
| 41 |
+
'text': 'How many sheep are there in the picture?'
|
| 42 |
+
}]
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
elif mm_type == 'video':
|
| 46 |
+
# # use base64
|
| 47 |
+
# import base64
|
| 48 |
+
# with open('baby.mp4', 'rb') as f:
|
| 49 |
+
# vid_base64 = base64.b64encode(f.read()).decode('utf-8')
|
| 50 |
+
# video = f'data:video/mp4;base64,{vid_base64}'
|
| 51 |
+
|
| 52 |
+
# use url
|
| 53 |
+
video = 'https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'
|
| 54 |
+
message = {
|
| 55 |
+
'role': 'user',
|
| 56 |
+
'content': [{
|
| 57 |
+
'type': 'video',
|
| 58 |
+
'video': video
|
| 59 |
+
}, {
|
| 60 |
+
'type': 'text',
|
| 61 |
+
'text': 'Describe this video.'
|
| 62 |
+
}]
|
| 63 |
+
}
|
| 64 |
+
elif mm_type == 'audio':
|
| 65 |
+
message = {
|
| 66 |
+
'role':
|
| 67 |
+
'user',
|
| 68 |
+
'content': [{
|
| 69 |
+
'type': 'audio',
|
| 70 |
+
'audio': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav'
|
| 71 |
+
}, {
|
| 72 |
+
'type': 'text',
|
| 73 |
+
'text': 'What does this audio say?'
|
| 74 |
+
}]
|
| 75 |
+
}
|
| 76 |
+
return message
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 80 |
+
client = OpenAI(
|
| 81 |
+
api_key='EMPTY',
|
| 82 |
+
base_url=f'http://{host}:{port}/v1',
|
| 83 |
+
)
|
| 84 |
+
model = client.models.list().data[0].id
|
| 85 |
+
print(f'model: {model}')
|
| 86 |
+
|
| 87 |
+
query = 'who are you?'
|
| 88 |
+
messages = [{'role': 'user', 'content': query}]
|
| 89 |
+
response = infer(client, model, messages)
|
| 90 |
+
messages.append({'role': 'assistant', 'content': response})
|
| 91 |
+
messages.append(get_message(mm_type='video'))
|
| 92 |
+
infer_stream(client, model, messages)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if __name__ == '__main__':
|
| 96 |
+
from swift import DeployArguments, run_deploy
|
| 97 |
+
with run_deploy(DeployArguments(model='Qwen/Qwen2.5-VL-3B-Instruct', verbose=False, log_interval=-1)) as port:
|
| 98 |
+
run_client(port=port)
|
examples/deploy/client/mllm/swift_client.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
|
| 18 |
+
def infer_stream(engine: 'InferEngine', infer_request: 'InferRequest'):
|
| 19 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
|
| 20 |
+
metric = InferStats()
|
| 21 |
+
gen_list = engine.infer([infer_request], request_config, metrics=[metric])
|
| 22 |
+
query = infer_request.messages[0]['content']
|
| 23 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 24 |
+
for resp in gen_list[0]:
|
| 25 |
+
if resp is None:
|
| 26 |
+
continue
|
| 27 |
+
print(resp.choices[0].delta.content, end='', flush=True)
|
| 28 |
+
print()
|
| 29 |
+
print(f'metric: {metric.compute()}')
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_message(mm_type: Literal['text', 'image', 'video', 'audio']):
|
| 33 |
+
if mm_type == 'text':
|
| 34 |
+
message = {'role': 'user', 'content': 'who are you?'}
|
| 35 |
+
elif mm_type == 'image':
|
| 36 |
+
message = {
|
| 37 |
+
'role':
|
| 38 |
+
'user',
|
| 39 |
+
'content': [
|
| 40 |
+
{
|
| 41 |
+
'type': 'image',
|
| 42 |
+
# url or local_path or PIL.Image or base64
|
| 43 |
+
'image': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png'
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
'type': 'text',
|
| 47 |
+
'text': 'How many sheep are there in the picture?'
|
| 48 |
+
}
|
| 49 |
+
]
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
elif mm_type == 'video':
|
| 53 |
+
# # use base64
|
| 54 |
+
# import base64
|
| 55 |
+
# with open('baby.mp4', 'rb') as f:
|
| 56 |
+
# vid_base64 = base64.b64encode(f.read()).decode('utf-8')
|
| 57 |
+
# video = f'data:video/mp4;base64,{vid_base64}'
|
| 58 |
+
|
| 59 |
+
# use url
|
| 60 |
+
video = 'https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'
|
| 61 |
+
message = {
|
| 62 |
+
'role': 'user',
|
| 63 |
+
'content': [{
|
| 64 |
+
'type': 'video',
|
| 65 |
+
'video': video
|
| 66 |
+
}, {
|
| 67 |
+
'type': 'text',
|
| 68 |
+
'text': 'Describe this video.'
|
| 69 |
+
}]
|
| 70 |
+
}
|
| 71 |
+
elif mm_type == 'audio':
|
| 72 |
+
message = {
|
| 73 |
+
'role':
|
| 74 |
+
'user',
|
| 75 |
+
'content': [{
|
| 76 |
+
'type': 'audio',
|
| 77 |
+
'audio': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav'
|
| 78 |
+
}, {
|
| 79 |
+
'type': 'text',
|
| 80 |
+
'text': 'What does this audio say?'
|
| 81 |
+
}]
|
| 82 |
+
}
|
| 83 |
+
return message
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_data(mm_type: Literal['text', 'image', 'video', 'audio']):
|
| 87 |
+
data = {}
|
| 88 |
+
if mm_type == 'text':
|
| 89 |
+
messages = [{'role': 'user', 'content': 'who are you?'}]
|
| 90 |
+
elif mm_type == 'image':
|
| 91 |
+
# The number of <image> tags must be the same as len(images).
|
| 92 |
+
messages = [{'role': 'user', 'content': '<image>How many sheep are there in the picture?'}]
|
| 93 |
+
# Support URL/Path/base64/PIL.Image
|
| 94 |
+
data['images'] = ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']
|
| 95 |
+
elif mm_type == 'video':
|
| 96 |
+
messages = [{'role': 'user', 'content': '<video>Describe this video.'}]
|
| 97 |
+
data['videos'] = ['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']
|
| 98 |
+
elif mm_type == 'audio':
|
| 99 |
+
messages = [{'role': 'user', 'content': '<audio>What does this audio say?'}]
|
| 100 |
+
data['audios'] = ['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/weather.wav']
|
| 101 |
+
data['messages'] = messages
|
| 102 |
+
return data
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 106 |
+
engine = InferClient(host=host, port=port)
|
| 107 |
+
print(f'models: {engine.models}')
|
| 108 |
+
# Here, `load_dataset` is used for convenience; `infer_batch` does not require creating a dataset.
|
| 109 |
+
dataset = load_dataset(['AI-ModelScope/LaTeX_OCR:small#1000'], seed=42)[0]
|
| 110 |
+
print(f'dataset: {dataset}')
|
| 111 |
+
infer_requests = [InferRequest(**data) for data in dataset]
|
| 112 |
+
infer_batch(engine, infer_requests)
|
| 113 |
+
|
| 114 |
+
infer_stream(engine, InferRequest(messages=[get_message(mm_type='video')]))
|
| 115 |
+
# This writing is equivalent to the above writing.
|
| 116 |
+
infer_stream(engine, InferRequest(**get_data(mm_type='video')))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == '__main__':
|
| 120 |
+
from swift import (DeployArguments, InferClient, InferEngine, InferRequest, InferStats, RequestConfig, load_dataset,
|
| 121 |
+
run_deploy)
|
| 122 |
+
|
| 123 |
+
# NOTE: In a real deployment scenario, please comment out the context of run_deploy.
|
| 124 |
+
with run_deploy(
|
| 125 |
+
DeployArguments(model='Qwen/Qwen2.5-VL-3B-Instruct', verbose=False, log_interval=-1,
|
| 126 |
+
infer_backend='vllm')) as port:
|
| 127 |
+
run_client(port=port)
|
examples/deploy/embedding/client.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(client, model: str, messages):
|
| 9 |
+
# You can also use client.embeddings.create
|
| 10 |
+
# But this interface does not support multi-modal medias
|
| 11 |
+
resp = client.chat.completions.create(model=model, messages=messages)
|
| 12 |
+
emb = resp.data[0]['embedding']
|
| 13 |
+
shape = len(emb)
|
| 14 |
+
sample = str(emb)
|
| 15 |
+
if len(emb) > 6:
|
| 16 |
+
sample = str(emb[:3])[:-1] + ', ..., ' + str(emb[-3:])[1:]
|
| 17 |
+
print(f'messages: {messages}')
|
| 18 |
+
print(f'Embedding(shape: [1, {shape}]): {sample}')
|
| 19 |
+
return emb
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 23 |
+
client = OpenAI(
|
| 24 |
+
api_key='EMPTY',
|
| 25 |
+
base_url=f'http://{host}:{port}/v1',
|
| 26 |
+
)
|
| 27 |
+
model = client.models.list().data[0].id
|
| 28 |
+
print(f'model: {model}')
|
| 29 |
+
|
| 30 |
+
messages = [{
|
| 31 |
+
'role':
|
| 32 |
+
'user',
|
| 33 |
+
'content': [
|
| 34 |
+
# {
|
| 35 |
+
# 'type': 'image',
|
| 36 |
+
# 'image': 'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png'
|
| 37 |
+
# },
|
| 38 |
+
{
|
| 39 |
+
'type': 'text',
|
| 40 |
+
'text': 'What is the capital of China?'
|
| 41 |
+
},
|
| 42 |
+
]
|
| 43 |
+
}]
|
| 44 |
+
infer(client, model, messages)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == '__main__':
|
| 48 |
+
from swift import DeployArguments, run_deploy
|
| 49 |
+
with run_deploy(
|
| 50 |
+
DeployArguments(
|
| 51 |
+
model='Qwen/Qwen3-Embedding-0.6B', # GME/GTE models or your checkpoints are also supported
|
| 52 |
+
task_type='embedding',
|
| 53 |
+
infer_backend='vllm',
|
| 54 |
+
verbose=False,
|
| 55 |
+
log_interval=-1)) as port:
|
| 56 |
+
run_client(port=port)
|
examples/deploy/embedding/server.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GME/GTE models or your checkpoints are also supported
|
| 2 |
+
# transformers/vllm/sglang supported
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 4 |
+
--host 0.0.0.0 \
|
| 5 |
+
--port 8000 \
|
| 6 |
+
--task_type embedding \
|
| 7 |
+
--model Qwen/Qwen3-Embedding-0.6B \
|
| 8 |
+
--infer_backend sglang
|
examples/deploy/lora/client.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from swift.infer_engine import InferClient, InferRequest, RequestConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def infer_multilora(engine: InferClient, infer_request: InferRequest):
|
| 5 |
+
# Dynamic LoRA
|
| 6 |
+
models = engine.models
|
| 7 |
+
print(f'models: {models}')
|
| 8 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 9 |
+
|
| 10 |
+
# use lora1
|
| 11 |
+
resp_list = engine.infer([infer_request], request_config, model=models[1])
|
| 12 |
+
response = resp_list[0].choices[0].message.content
|
| 13 |
+
print(f'lora1-response: {response}')
|
| 14 |
+
# origin model
|
| 15 |
+
resp_list = engine.infer([infer_request], request_config, model=models[0])
|
| 16 |
+
response = resp_list[0].choices[0].message.content
|
| 17 |
+
print(f'response: {response}')
|
| 18 |
+
# use lora2
|
| 19 |
+
resp_list = engine.infer([infer_request], request_config, model=models[2])
|
| 20 |
+
response = resp_list[0].choices[0].message.content
|
| 21 |
+
print(f'lora2-response: {response}')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if __name__ == '__main__':
|
| 25 |
+
engine = InferClient(host='127.0.0.1', port=8000)
|
| 26 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}])
|
| 27 |
+
infer_multilora(engine, infer_request)
|
examples/deploy/lora/server.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Since `swift/test_lora` 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 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 4 |
+
--host 0.0.0.0 \
|
| 5 |
+
--port 8000 \
|
| 6 |
+
--adapters lora1=swift/test_lora lora2=swift/test_lora2 \
|
| 7 |
+
--infer_backend vllm
|
examples/deploy/reranker/client.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(client, model: str, messages):
|
| 9 |
+
resp = client.chat.completions.create(model=model, messages=messages)
|
| 10 |
+
scores = resp.choices[0].message.content
|
| 11 |
+
print(f'messages: {messages}')
|
| 12 |
+
print(f'scores: {scores}')
|
| 13 |
+
return scores
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 17 |
+
client = OpenAI(
|
| 18 |
+
api_key='EMPTY',
|
| 19 |
+
base_url=f'http://{host}:{port}/v1',
|
| 20 |
+
)
|
| 21 |
+
model = client.models.list().data[0].id
|
| 22 |
+
print(f'model: {model}')
|
| 23 |
+
|
| 24 |
+
messages = [{
|
| 25 |
+
'role': 'user',
|
| 26 |
+
'content': 'what is the capital of China?',
|
| 27 |
+
}, {
|
| 28 |
+
'role': 'assistant',
|
| 29 |
+
'content': 'Beijing',
|
| 30 |
+
}]
|
| 31 |
+
infer(client, model, messages)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == '__main__':
|
| 35 |
+
from swift import DeployArguments, run_deploy
|
| 36 |
+
with run_deploy(
|
| 37 |
+
DeployArguments(
|
| 38 |
+
model='BAAI/bge-reranker-v2-m3',
|
| 39 |
+
task_type='reranker',
|
| 40 |
+
infer_backend='vllm',
|
| 41 |
+
gpu_memory_utilization=0.7,
|
| 42 |
+
vllm_enforce_eager=True,
|
| 43 |
+
reranker_use_activation=True,
|
| 44 |
+
verbose=False,
|
| 45 |
+
log_interval=-1)) as port:
|
| 46 |
+
run_client(port=port)
|
examples/deploy/reranker/client_generative.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(client, model: str, messages):
|
| 9 |
+
resp = client.chat.completions.create(model=model, messages=messages)
|
| 10 |
+
scores = resp.choices[0].message.content
|
| 11 |
+
print(f'messages: {messages}')
|
| 12 |
+
print(f'scores: {scores}')
|
| 13 |
+
return scores
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 17 |
+
client = OpenAI(
|
| 18 |
+
api_key='EMPTY',
|
| 19 |
+
base_url=f'http://{host}:{port}/v1',
|
| 20 |
+
)
|
| 21 |
+
model = client.models.list().data[0].id
|
| 22 |
+
print(f'model: {model}')
|
| 23 |
+
|
| 24 |
+
messages = [{
|
| 25 |
+
'role': 'user',
|
| 26 |
+
'content': 'what is the capital of China?',
|
| 27 |
+
}, {
|
| 28 |
+
'role': 'assistant',
|
| 29 |
+
'content': 'Beijing.',
|
| 30 |
+
}]
|
| 31 |
+
infer(client, model, messages)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == '__main__':
|
| 35 |
+
from swift import DeployArguments, run_deploy
|
| 36 |
+
with run_deploy(
|
| 37 |
+
DeployArguments(
|
| 38 |
+
model='Qwen/Qwen3-Reranker-0.6B',
|
| 39 |
+
task_type='generative_reranker',
|
| 40 |
+
infer_backend='vllm',
|
| 41 |
+
gpu_memory_utilization=0.7,
|
| 42 |
+
verbose=False,
|
| 43 |
+
log_interval=-1)) as port:
|
| 44 |
+
run_client(port=port)
|
examples/deploy/reranker/server.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GME/GTE models or your checkpoints are also supported
|
| 2 |
+
# transformers/vllm/sglang supported
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 4 |
+
--host 0.0.0.0 \
|
| 5 |
+
--port 8000 \
|
| 6 |
+
--model BAAI/bge-reranker-v2-m3 \
|
| 7 |
+
--infer_backend vllm \
|
| 8 |
+
--task_type reranker \
|
| 9 |
+
--vllm_enforce_eager true \
|
examples/deploy/reward_model/client.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
from swift.infer_engine import InferClient, InferRequest
|
| 3 |
+
|
| 4 |
+
if __name__ == '__main__':
|
| 5 |
+
engine = InferClient(host='127.0.0.1', port=8000)
|
| 6 |
+
models = engine.models
|
| 7 |
+
print(f'models: {models}')
|
| 8 |
+
messages = [{
|
| 9 |
+
'role': 'user',
|
| 10 |
+
'content': "Hello! What's your name?"
|
| 11 |
+
}, {
|
| 12 |
+
'role': 'assistant',
|
| 13 |
+
'content': 'My name is InternLM2! A helpful AI assistant. What can I do for you?'
|
| 14 |
+
}]
|
| 15 |
+
resp_list = engine.infer([InferRequest(messages=messages)])
|
| 16 |
+
print(f'messages: {messages}')
|
| 17 |
+
print(f'response: {resp_list[0].choices[0].message.content}')
|
examples/deploy/reward_model/server.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 2 |
+
--host 0.0.0.0 \
|
| 3 |
+
--port 8000 \
|
| 4 |
+
--model Shanghai_AI_Laboratory/internlm2-1_8b-reward \
|
| 5 |
+
--infer_backend transformers
|
examples/deploy/seq_cls/client.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def infer(client, model: str, messages):
|
| 9 |
+
resp = client.chat.completions.create(model=model, messages=messages)
|
| 10 |
+
classify = resp.choices[0].message.content
|
| 11 |
+
print(f'messages: {messages}')
|
| 12 |
+
print(f'classify: {classify}')
|
| 13 |
+
return classify
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 17 |
+
client = OpenAI(
|
| 18 |
+
api_key='EMPTY',
|
| 19 |
+
base_url=f'http://{host}:{port}/v1',
|
| 20 |
+
)
|
| 21 |
+
model = client.models.list().data[0].id
|
| 22 |
+
print(f'model: {model}')
|
| 23 |
+
|
| 24 |
+
messages = [{
|
| 25 |
+
'role': 'user',
|
| 26 |
+
'content': 'What is the capital of China?',
|
| 27 |
+
}, {
|
| 28 |
+
'role': 'assistant',
|
| 29 |
+
'content': 'Beijing',
|
| 30 |
+
}]
|
| 31 |
+
infer(client, model, messages)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if __name__ == '__main__':
|
| 35 |
+
from swift import DeployArguments, run_deploy
|
| 36 |
+
with run_deploy(
|
| 37 |
+
DeployArguments(
|
| 38 |
+
model='/your/seq_cls/checkpoint-xxx',
|
| 39 |
+
task_type='seq_cls',
|
| 40 |
+
infer_backend='vllm',
|
| 41 |
+
num_labels=2,
|
| 42 |
+
verbose=False,
|
| 43 |
+
log_interval=-1)) as port:
|
| 44 |
+
run_client(port=port)
|
examples/deploy/seq_cls/server.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GME/GTE models or your checkpoints are also supported
|
| 2 |
+
# transformers/vllm/sglang supported
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 4 |
+
--host 0.0.0.0 \
|
| 5 |
+
--port 8000 \
|
| 6 |
+
--model /your/seq_cls/checkpoint-xxx \
|
| 7 |
+
--infer_backend vllm \
|
| 8 |
+
--task_type seq_cls \
|
| 9 |
+
--num_labels 2 \
|
examples/eval/eval_url/demo.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ModelScope Contributors. All rights reserved.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 5 |
+
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
from swift import DeployArguments, EvalArguments, eval_main, run_deploy
|
| 8 |
+
|
| 9 |
+
# Here's a runnable demo provided. Use the eval_url method for evaluation.
|
| 10 |
+
# In a real scenario, you can simply remove the deployed context.
|
| 11 |
+
print(EvalArguments.list_eval_dataset())
|
| 12 |
+
with run_deploy(
|
| 13 |
+
DeployArguments(model='Qwen/Qwen2.5-0.5B-Instruct', verbose=False, log_interval=-1, infer_backend='vllm'),
|
| 14 |
+
return_url=True) as url:
|
| 15 |
+
eval_main(EvalArguments(model='Qwen2.5-0.5B-Instruct', eval_url=url, eval_dataset=['arc']))
|
examples/eval/eval_url/eval.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# You need to have a deployed model or api service first
|
| 2 |
+
swift eval \
|
| 3 |
+
--model '<model_name>' \
|
| 4 |
+
--eval_backend OpenCompass \
|
| 5 |
+
--eval_url http://127.0.0.1:8000/v1 \
|
| 6 |
+
--eval_limit 100 \
|
| 7 |
+
--eval_dataset gsm8k
|
examples/eval/llm/sglang.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift eval \
|
| 3 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 4 |
+
--eval_backend OpenCompass \
|
| 5 |
+
--infer_backend sglang \
|
| 6 |
+
--eval_limit 100 \
|
| 7 |
+
--eval_dataset gsm8k
|
examples/eval/llm/vllm.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift eval \
|
| 3 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 4 |
+
--eval_backend OpenCompass \
|
| 5 |
+
--infer_backend vllm \
|
| 6 |
+
--eval_limit 100 \
|
| 7 |
+
--eval_dataset gsm8k
|
examples/eval/train_eval/train.sh
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift sft \
|
| 3 |
+
--model "Qwen/Qwen2.5-0.5B-Instruct" \
|
| 4 |
+
--tuner_type "lora" \
|
| 5 |
+
--dataset "AI-ModelScope/alpaca-gpt4-data-zh#100" \
|
| 6 |
+
--torch_dtype "bfloat16" \
|
| 7 |
+
--num_train_epochs "1" \
|
| 8 |
+
--per_device_train_batch_size "1" \
|
| 9 |
+
--learning_rate "1e-4" \
|
| 10 |
+
--lora_rank "8" \
|
| 11 |
+
--lora_alpha "32" \
|
| 12 |
+
--target_modules "all-linear" \
|
| 13 |
+
--gradient_accumulation_steps "16" \
|
| 14 |
+
--save_steps "50" \
|
| 15 |
+
--save_total_limit "5" \
|
| 16 |
+
--logging_steps "5" \
|
| 17 |
+
--max_length "2048" \
|
| 18 |
+
--eval_strategy "steps" \
|
| 19 |
+
--eval_steps "5" \
|
| 20 |
+
--per_device_eval_batch_size "5" \
|
| 21 |
+
--eval_use_evalscope \
|
| 22 |
+
--eval_dataset "gsm8k" \
|
| 23 |
+
--eval_dataset_args '{"gsm8k": {"few_shot_num": 0}}' \
|
| 24 |
+
--eval_limit "10"
|
examples/eval/vlm/eval.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
MAX_PIXELS=1003520 \
|
| 3 |
+
swift eval \
|
| 4 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 5 |
+
--infer_backend vllm \
|
| 6 |
+
--eval_limit 100 \
|
| 7 |
+
--eval_dataset realWorldQA \
|
| 8 |
+
--eval_backend VLMEvalKit
|
examples/export/quantize/awq.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip install "transformers<4.52"
|
| 2 |
+
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
swift export \
|
| 5 |
+
--model Qwen/Qwen2.5-72B-Instruct \
|
| 6 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 7 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 8 |
+
--device_map cpu \
|
| 9 |
+
--quant_n_samples 256 \
|
| 10 |
+
--quant_batch_size 1 \
|
| 11 |
+
--max_length 2048 \
|
| 12 |
+
--quant_method awq \
|
| 13 |
+
--quant_bits 4 \
|
| 14 |
+
--output_dir Qwen2.5-72B-Instruct-AWQ
|
examples/export/quantize/bert/bnb.sh
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# merge-lora
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 swift export \
|
| 3 |
+
--adapters swift/test_bert \
|
| 4 |
+
--output_dir output/swift_test_bert_merged \
|
| 5 |
+
--merge_lora true
|
| 6 |
+
|
| 7 |
+
# bnb quantize
|
| 8 |
+
CUDA_VISIBLE_DEVICES=0 swift export \
|
| 9 |
+
--model output/swift_test_bert_merged \
|
| 10 |
+
--output_dir output/swift_test_bert_bnb_int4 \
|
| 11 |
+
--quant_bits 4 \
|
| 12 |
+
--quant_method bnb
|
| 13 |
+
|
| 14 |
+
# infer
|
| 15 |
+
CUDA_VISIBLE_DEVICES=0 swift infer \
|
| 16 |
+
--model output/swift_test_bert_bnb_int4
|
examples/export/quantize/bert/gptq.sh
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# merge-lora
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 swift export \
|
| 3 |
+
--adapters swift/test_bert \
|
| 4 |
+
--output_dir output/swift_test_bert_merged \
|
| 5 |
+
--merge_lora true
|
| 6 |
+
|
| 7 |
+
EXIT_CODE=$?
|
| 8 |
+
|
| 9 |
+
if [ $EXIT_CODE -ne 0 ]; then
|
| 10 |
+
echo "Error: LoRA merge failed with exit code $EXIT_CODE"
|
| 11 |
+
exit $EXIT_CODE
|
| 12 |
+
fi
|
| 13 |
+
|
| 14 |
+
# gptq quantize
|
| 15 |
+
CUDA_VISIBLE_DEVICES=0 swift export \
|
| 16 |
+
--model output/swift_test_bert_merged \
|
| 17 |
+
--load_data_args true \
|
| 18 |
+
--output_dir output/swift_test_bert_gptq_int4 \
|
| 19 |
+
--quant_bits 4 \
|
| 20 |
+
--quant_method gptq \
|
| 21 |
+
--max_length 512
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
EXIT_CODE=$?
|
| 25 |
+
|
| 26 |
+
if [ $EXIT_CODE -ne 0 ]; then
|
| 27 |
+
echo "Error: GPTQ quantization failed with exit code $EXIT_CODE"
|
| 28 |
+
exit $EXIT_CODE
|
| 29 |
+
fi
|
| 30 |
+
|
| 31 |
+
# infer
|
| 32 |
+
CUDA_VISIBLE_DEVICES=0 swift infer \
|
| 33 |
+
--model output/swift_test_bert_gptq_int4
|
examples/export/quantize/bnb.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift export \
|
| 3 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 4 |
+
--quant_method bnb \
|
| 5 |
+
--quant_bits 4 \
|
| 6 |
+
--bnb_4bit_quant_type nf4 \
|
| 7 |
+
--bnb_4bit_use_double_quant true \
|
| 8 |
+
--output_dir Qwen2.5-1.5B-Instruct-BNB-NF4
|
examples/export/quantize/fp8.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Due to the structural changes made to MoE architecture in `transformers>=5.0`,
|
| 2 |
+
# if you need to apply FP8 quantization to MoE models, please use `megatron export`
|
| 3 |
+
# (compatible with vLLM inference).
|
| 4 |
+
# Reference: https://github.com/modelscope/ms-swift/blob/main/examples/megatron/fp8/quant.sh
|
| 5 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 6 |
+
swift export \
|
| 7 |
+
--model Qwen/Qwen2.5-3B-Instruct \
|
| 8 |
+
--quant_method fp8 \
|
| 9 |
+
--output_dir Qwen2.5-3B-Instruct-FP8
|
examples/export/quantize/gptq.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OMP_NUM_THREADS=14 please Check issue: https://github.com/AutoGPTQ/AutoGPTQ/issues/439
|
| 2 |
+
OMP_NUM_THREADS=14 \
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
swift export \
|
| 5 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 6 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 7 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 8 |
+
--quant_n_samples 256 \
|
| 9 |
+
--quant_batch_size 1 \
|
| 10 |
+
--max_length 2048 \
|
| 11 |
+
--quant_method gptq \
|
| 12 |
+
--quant_bits 4 \
|
| 13 |
+
--output_dir Qwen2.5-1.5B-Instruct-GPTQ-Int4
|
examples/export/quantize/gptq_v2.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# You need to install gptqmodel.
|
| 2 |
+
# OMP_NUM_THREADS=14 please Check issue: https://github.com/AutoGPTQ/AutoGPTQ/issues/439
|
| 3 |
+
OMP_NUM_THREADS=14 \
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 5 |
+
swift export \
|
| 6 |
+
--model Qwen/Qwen2.5-1.5B-Instruct \
|
| 7 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 8 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 9 |
+
--quant_n_samples 256 \
|
| 10 |
+
--quant_batch_size 1 \
|
| 11 |
+
--max_length 2048 \
|
| 12 |
+
--quant_method gptq_v2 \
|
| 13 |
+
--quant_bits 4 \
|
| 14 |
+
--output_dir Qwen2.5-1.5B-Instruct-GPTQ-V2-Int4
|
examples/export/quantize/mllm/awq.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip install "transformers==4.51.*"
|
| 2 |
+
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
MAX_PIXELS=1003520 \
|
| 5 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 6 |
+
FPS_MAX_FRAMES=12 \
|
| 7 |
+
swift export \
|
| 8 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 9 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 10 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 11 |
+
'modelscope/coco_2014_caption:validation#500' \
|
| 12 |
+
'swift/VideoChatGPT:Generic#500' \
|
| 13 |
+
--quant_n_samples 256 \
|
| 14 |
+
--quant_batch_size -1 \
|
| 15 |
+
--max_length 2048 \
|
| 16 |
+
--quant_method awq \
|
| 17 |
+
--quant_bits 4 \
|
| 18 |
+
--output_dir Qwen2.5-VL-3B-Instruct-AWQ
|
examples/export/quantize/mllm/bnb.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift export \
|
| 3 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 4 |
+
--quant_method bnb \
|
| 5 |
+
--quant_bits 4 \
|
| 6 |
+
--output_dir Qwen2.5-VL-3B-Instruct-BNB-Int4
|
examples/export/quantize/mllm/fp8.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# use transformers==5.2.0
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 3 |
+
swift export \
|
| 4 |
+
--model Qwen/Qwen3.5-4B \
|
| 5 |
+
--quant_method fp8 \
|
| 6 |
+
--output_dir Qwen3.5-4B-FP8
|
| 7 |
+
|
| 8 |
+
# CUDA_VISIBLE_DEVICES=0 \
|
| 9 |
+
# swift infer \
|
| 10 |
+
# --model Qwen3.5-4B-FP8
|
examples/export/quantize/mllm/gptq.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OMP_NUM_THREADS=14 please Check issue: https://github.com/AutoGPTQ/AutoGPTQ/issues/439
|
| 2 |
+
OMP_NUM_THREADS=14 \
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
MAX_PIXELS=1003520 \
|
| 5 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 6 |
+
FPS_MAX_FRAMES=12 \
|
| 7 |
+
swift export \
|
| 8 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 9 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 10 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 11 |
+
'modelscope/coco_2014_caption:validation#500' \
|
| 12 |
+
'swift/VideoChatGPT:Generic#500' \
|
| 13 |
+
--quant_n_samples 256 \
|
| 14 |
+
--quant_batch_size 1 \
|
| 15 |
+
--max_length 2048 \
|
| 16 |
+
--quant_method gptq \
|
| 17 |
+
--quant_bits 4 \
|
| 18 |
+
--output_dir Qwen2.5-VL-3B-Instruct-GPTQ-Int4
|
examples/export/quantize/moe/awq.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip install "transformers<4.52"
|
| 2 |
+
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 4 |
+
swift export \
|
| 5 |
+
--model Qwen/Qwen3-30B-A3B \
|
| 6 |
+
--dataset 'swift/Qwen3-SFT-Mixin' \
|
| 7 |
+
--device_map auto \
|
| 8 |
+
--quant_n_samples 64 \
|
| 9 |
+
--quant_batch_size -1 \
|
| 10 |
+
--max_length 8192 \
|
| 11 |
+
--quant_method awq \
|
| 12 |
+
--quant_bits 4 \
|
| 13 |
+
--output_dir Qwen3-30B-A3B-AWQ
|
examples/export/quantize/moe/bnb.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift export \
|
| 3 |
+
--model Qwen/Qwen3-30B-A3B \
|
| 4 |
+
--quant_method bnb \
|
| 5 |
+
--quant_bits 4 \
|
| 6 |
+
--output_dir Qwen3-30B-A3B-BNB-Int4
|
examples/export/quantize/moe/fp8.sh
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift export \
|
| 3 |
+
--model Qwen/Qwen3-30B-A3B \
|
| 4 |
+
--quant_method fp8 \
|
| 5 |
+
--output_dir Qwen3-30B-A3B-FP8
|
| 6 |
+
|
| 7 |
+
# CUDA_VISIBLE_DEVICES=0 \
|
| 8 |
+
# swift infer \
|
| 9 |
+
# --model Qwen3-30B-A3B-FP8 \
|
| 10 |
+
# --infer_backend vllm \
|
| 11 |
+
# --stream true
|
examples/export/quantize/moe/gptq.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 2 * 80GB
|
| 2 |
+
OMP_NUM_THREADS=14 \
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 4 |
+
swift export \
|
| 5 |
+
--model Qwen/Qwen2-57B-A14B-Instruct \
|
| 6 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#1000' \
|
| 7 |
+
'AI-ModelScope/alpaca-gpt4-data-en#1000' \
|
| 8 |
+
--quant_n_samples 512 \
|
| 9 |
+
--quant_batch_size 1 \
|
| 10 |
+
--max_length 4096 \
|
| 11 |
+
--quant_method gptq \
|
| 12 |
+
--quant_bits 4 \
|
| 13 |
+
--output_dir Qwen2-57B-A14B-Instruct-GPTQ-Int4
|
examples/export/quantize/omni/gptq.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OMP_NUM_THREADS=14 please Check issue: https://github.com/AutoGPTQ/AutoGPTQ/issues/439
|
| 2 |
+
OMP_NUM_THREADS=14 \
|
| 3 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 4 |
+
MAX_PIXELS=1003520 \
|
| 5 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 6 |
+
FPS_MAX_FRAMES=12 \
|
| 7 |
+
swift export \
|
| 8 |
+
--model Qwen/Qwen2.5-Omni-7B \
|
| 9 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 10 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 11 |
+
'modelscope/coco_2014_caption:validation#500' \
|
| 12 |
+
'swift/VideoChatGPT:Generic#500' \
|
| 13 |
+
--quant_n_samples 256 \
|
| 14 |
+
--quant_batch_size 1 \
|
| 15 |
+
--max_length 2048 \
|
| 16 |
+
--quant_method gptq \
|
| 17 |
+
--quant_bits 4 \
|
| 18 |
+
--output_dir Qwen2.5-Omni-7B-GPTQ-Int4
|