Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ms-swift/docs/source_en/BestPractices/More-Best-Practices.md +7 -0
- ms-swift/docs/source_en/Customization/Custom-model.md +35 -0
- ms-swift/docs/source_en/Customization/Pluginization.md +234 -0
- ms-swift/docs/source_en/GetStarted/SWIFT-installation.md +88 -0
- ms-swift/docs/source_en/Instruction/Agent-support.md +215 -0
- ms-swift/docs/source_en/Instruction/Command-line-parameters.md +675 -0
- ms-swift/docs/source_en/Instruction/Evaluation.md +270 -0
- ms-swift/docs/source_en/Instruction/Frequently-asked-questions.md +716 -0
- ms-swift/docs/source_en/Instruction/GRPO.md +471 -0
- ms-swift/docs/source_en/Instruction/Inference-and-deployment.md +354 -0
- ms-swift/docs/source_en/Instruction/Megatron-SWIFT-Training.md +305 -0
- ms-swift/docs/source_en/Instruction/RLHF.md +114 -0
- ms-swift/docs/source_en/Instruction/Reinforced-Fine-tuning.md +103 -0
- ms-swift/docs/source_en/Instruction/Sample.md +100 -0
- ms-swift/docs/source_en/Instruction/Supported-models-and-datasets.md +0 -0
- ms-swift/docs/source_en/_templates/autosummary/class.rst +10 -0
- ms-swift/docs/source_en/_templates/sobolengine.rst +14 -0
- ms-swift/examples/README.md +13 -0
- ms-swift/examples/app/base_url/demo.py +13 -0
- ms-swift/examples/app/base_url/demo.sh +7 -0
- ms-swift/examples/custom/dataset.py +30 -0
- ms-swift/examples/custom/infer.sh +9 -0
- ms-swift/examples/custom/model.py +33 -0
- ms-swift/examples/deploy/agent/client.py +87 -0
- ms-swift/examples/deploy/agent/server.sh +8 -0
- ms-swift/examples/deploy/bert/client.py +29 -0
- ms-swift/examples/deploy/client/llm/chat/openai_client.py +46 -0
- ms-swift/examples/deploy/lora/server.sh +7 -0
- ms-swift/examples/deploy/reward_model/client.py +17 -0
- ms-swift/examples/deploy/reward_model/server.sh +5 -0
- ms-swift/examples/deploy/server/demo.sh +14 -0
- ms-swift/examples/eval/eval_url/demo.py +14 -0
- ms-swift/examples/eval/eval_url/eval.sh +7 -0
- ms-swift/examples/eval/train_eval/train.sh +24 -0
- ms-swift/examples/eval/vlm/eval.sh +8 -0
- ms-swift/examples/export/ollama.sh +4 -0
- ms-swift/examples/export/push_to_hub.sh +6 -0
- ms-swift/examples/export/quantize/awq.sh +12 -0
- ms-swift/examples/export/quantize/bert/bnb.sh +16 -0
- ms-swift/examples/export/quantize/bert/gptq.sh +18 -0
- ms-swift/examples/export/quantize/bnb.sh +8 -0
- ms-swift/examples/export/quantize/gptq.sh +13 -0
- ms-swift/examples/export/quantize/mllm/awq.sh +19 -0
- ms-swift/examples/export/quantize/moe/awq.sh +14 -0
- ms-swift/examples/infer/demo_reward_model.py +31 -0
- ms-swift/examples/infer/lmdeploy/ddp.sh +7 -0
- ms-swift/examples/infer/lmdeploy/mllm_tp.sh +8 -0
- ms-swift/examples/infer/pt/lora.sh +10 -0
- ms-swift/examples/infer/pt/mllm_device_map.sh +9 -0
- ms-swift/examples/infer/vllm/mllm_tp.sh +11 -0
ms-swift/docs/source_en/BestPractices/More-Best-Practices.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# More Best Practices
|
| 3 |
+
|
| 4 |
+
- [Qwen2.5 self-cognition SFT](https://github.com/modelscope/ms-swift/tree/main/examples/notebook/qwen2_5-self-cognition)
|
| 5 |
+
- [Qwen2-VL Latex-OCR SFT](https://github.com/modelscope/ms-swift/tree/main/examples/notebook/qwen2vl-ocr)
|
| 6 |
+
- [Qwen2.5-VL Grounding Task SFT](https://github.com/modelscope/ms-swift/tree/main/examples/notebook/qwen2_5-vl-grounding)
|
| 7 |
+
- [Qwen3全流程最佳实践](https://github.com/modelscope/ms-swift/issues/4030)
|
ms-swift/docs/source_en/Customization/Custom-model.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Custom Model
|
| 2 |
+
|
| 3 |
+
The models built into ms-swift can be used directly by specifying either `model_id` or `model_path`: `--model <model_id_or_path>`. ms-swift determines the `model_type` based on the suffix of `model_id/model_path` and the `config.json` file. Each `model_type` has a unique model structure, template, and loading method. Of course, you can also manually override these by passing `--model_type` and `--template`. You can check the supported `model_type` and templates in the [Supported Models and Datasets](../Instruction/Supported-models-and-datasets.md).
|
| 4 |
+
|
| 5 |
+
## Model Registration
|
| 6 |
+
|
| 7 |
+
Custom models are typically implemented using model registration. You can refer to the [built-in model](https://github.com/modelscope/ms-swift/blob/main/swift/llm/model/model/qwen.py), the [built-in dialogue template](https://github.com/modelscope/ms-swift/blob/main/swift/llm/template/template/qwen.py), or the example code in the [examples](https://github.com/modelscope/swift/blob/main/examples/custom). You can specify the `--custom_register_path xxx.py` to parse the externally registered content, which is convenient for users installing via pip instead of git clone.
|
| 8 |
+
|
| 9 |
+
The `register_model` function registers a model in the `MODEL_MAPPING`. You can complete the model registration by calling the function `register_model(model_meta)`, where `model_meta` will store the model's metadata. The parameter list for ModelMeta is as follows:
|
| 10 |
+
|
| 11 |
+
- model_type: Required. The model type, which is also the unique ID.
|
| 12 |
+
- model_groups: Required. Lists the ModelScope/HuggingFace model IDs and local paths. Running the [run_model_info.py](https://github.com/modelscope/ms-swift/blob/main/scripts/utils/run_model_info.py) file will automatically generate the [supported models documentation](https://swift.readthedocs.io/en/latest/Instruction/Supported-models-and-datasets.html) and automatically match the model_type based on the `--model` suffix.
|
| 13 |
+
- template: Required. The default template type when `--template` is not specified.
|
| 14 |
+
- get_function: Required. The loading function for the model and tokenizer/processor (for multi-modal models). LLM is typically set to `get_model_tokenizer_with_flash_attn`.
|
| 15 |
+
- model_arch: The model architecture. Defaults to None. Multi-modal model training requires setting this parameter to determine the prefix for llm/vit/aligner.
|
| 16 |
+
- architectures: The architectures item in config.json, used to automatically match the model with its model_type. Defaults to `[]`.
|
| 17 |
+
- additional_saved_files: Files that need to be additionally saved during full parameter training and merge-lora. Defaults to `[]`.
|
| 18 |
+
- torch_dtype: The default dtype when `torch_dtype` is not passed during model loading. Defaults to None, read from config.json.
|
| 19 |
+
- is_multimodal: Indicates whether the model is multi-modal. Defaults to False.
|
| 20 |
+
- ignore_patterns: File patterns to be ignored when downloading from the hub. Defaults to `[]`.
|
| 21 |
+
|
| 22 |
+
The `register_template` function registers a dialogue template in `TEMPLATE_MAPPING`. To complete the registration of the dialogue template, simply call the function `register_template(template_meta)`, where `template_meta` will store the metadata of the template. The parameter list for TemplateMeta is as follows:
|
| 23 |
+
|
| 24 |
+
- template_type: Required. The type of dialogue template, which also serves as a unique ID.
|
| 25 |
+
- prefix: Required. The prefix of the dialogue template, usually encompassing parts like system, bos_token, and is generated independently of multi-turn dialogue loops. For example, the prefix for qwen is `[]`.
|
| 26 |
+
- prompt: Required. Represents the dialogue portion before `{{RESPONSE}}`. We use `{{QUERY}}` as a placeholder for the user's inquiry part. For example, the prompt for qwen is `['<|im_start|>user\n{{QUERY}}<|im_end|>\n<|im_start|>assistant\n']`.
|
| 27 |
+
- chat_sep: Required. The separator for each turn in multi-turn dialogues. If set to None, the template does not support multi-turn dialogue. For example, the chat_sep for qwen is `['<|im_end|>\n']`.
|
| 28 |
+
- suffix: Defaults to `[['eos_token_id']]`. The suffix part of the dialogue template, generated independently of multi-turn dialogue loops, usually the eos_token. For example, the suffix for qwen is `['<|im_end|>']`.
|
| 29 |
+
- template_cls: Defaults to `Template`. Customization is generally required when defining templates for multimodal models, particularly in customizing the `_encode`, `_post_encode`, and `_data_collator` functions.
|
| 30 |
+
- system_prefix: Defaults to None. The prefix for dialogue templates with a system. We use`{{SYSTEM}}`as a placeholder for the system. For example, the system_prefix for qwen is`['<|im_start|>system\n{{SYSTEM}}<|im_end|>\n']`.
|
| 31 |
+
- Note: If the system is empty and `prefix` can be replaced by `system_prefix`, you can write `prefix` as a prefix including the system without setting `system_prefix`.
|
| 32 |
+
- If the prefix does not include `{{SYSTEM}}` and system_prefix is not set, the template does not support the system.
|
| 33 |
+
- default_system: Defaults to None. The default system used when `--system` is not provided. For example, the default_system for qwen is `'You are a helpful assistant.'`.
|
| 34 |
+
- stop_words: Defaults to`[]`. Additional stop words besides eos_token and`suffix[-1]`. For example, the stop_words for qwen is`['<|endoftext|>']`
|
| 35 |
+
- Note: During inference, the output response will be filtered by eos_token and `suffix[-1]`, but additional stop_words will be retained.
|
ms-swift/docs/source_en/Customization/Pluginization.md
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pluginization
|
| 2 |
+
|
| 3 |
+
Pluginization is a significant new feature introduced in SWIFT 3.0. We aim to make the customization of the development process more natural for developers through a plugin-based approach.
|
| 4 |
+
|
| 5 |
+
## Callback Mechanism
|
| 6 |
+
|
| 7 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/callback.py).
|
| 8 |
+
|
| 9 |
+
The `callback` mechanism is a customization feature in the Transformers Trainer that allows developers to control the training process. Typically, customizing a callback looks like the following:
|
| 10 |
+
|
| 11 |
+
```python
|
| 12 |
+
class CustomCallback(TrainerCallback):
|
| 13 |
+
|
| 14 |
+
def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
|
| 15 |
+
# Doing something when the training begins.
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
|
| 19 |
+
# Doing something when saving a checkpoint.
|
| 20 |
+
pass
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Callbacks are registered with the trainer before it is instantiated. The example provided demonstrates a simple version of an EarlyStopping mechanism. Registering your own callback is straightforward:
|
| 24 |
+
|
| 25 |
+
```python
|
| 26 |
+
extra_callbacks = [CustomCallback()]
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Developers can add new callbacks in `plugin/callback.py` and customize their training process. For detailed parameters of callbacks, refer to [this documentation](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 30 |
+
|
| 31 |
+
## Customizing Loss
|
| 32 |
+
|
| 33 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/loss.py).
|
| 34 |
+
|
| 35 |
+
SWIFT supports customizing the loss function through plugins. If this feature is not utilized, the default Cross Entropy Loss (CE Loss) is used. Developers can write code in this file to register their custom loss functions, and the trainer will automatically use the customized loss method.
|
| 36 |
+
|
| 37 |
+
For example, adding the following code in `plugin/loss.py`:
|
| 38 |
+
|
| 39 |
+
```python
|
| 40 |
+
@register_loss_func("custom_loss")
|
| 41 |
+
def loss_scale_func(outputs, labels, loss_scale=None, num_items_in_batch=None) -> torch.Tensor:
|
| 42 |
+
# Write your own loss calculation here
|
| 43 |
+
return loss
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
It is important to note that the loss function is strongly related to the training task. Currently, loss customization supports PT and SFT tasks. For human alignment tasks (e.g., DPO, PPO) or classification tasks (seq_cls), loss customization through plugins is not supported.
|
| 47 |
+
|
| 48 |
+
## Customizing Loss Scale
|
| 49 |
+
|
| 50 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/loss_scale/loss_scale.py).
|
| 51 |
+
|
| 52 |
+
The `loss_scale` mechanism is one of the crucial features in SWIFT. In PT and SFT tasks, the loss for trainable tokens is uniform, meaning each token is equally involved in backpropagation. However, in certain situations, some tokens require higher weights and extra attention. In such cases, `loss_scale` allows developers to define custom token weights.
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
class LastRoundLossScale(LossScale):
|
| 56 |
+
|
| 57 |
+
def get_loss_scale(self, context: str, context_type: ContextType, is_last_round: bool, **kwargs):
|
| 58 |
+
if context_type == ContextType.RESPONSE:
|
| 59 |
+
return [context], [float(is_last_round)]
|
| 60 |
+
return super().get_loss_scale(context, context_type, is_last_round)
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
In the above code, a `Tuple` is returned where the first element is the `context` (or its split parts), and the second element is the corresponding `loss_scale`. The float value represents the weight. For example, the following weight settings:
|
| 64 |
+
|
| 65 |
+
```text
|
| 66 |
+
["学习", "好", "数学", "是", "重要", "的"]
|
| 67 |
+
[1.0, 0.5, 2.0, 0.5, 2.0, 0.1]
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
Here, we place more emphasis on the words "数学" (mathematics) and "重要" (important) by increasing their weights to 2.0.
|
| 71 |
+
|
| 72 |
+
Referring back to the code, we check if the provided `context` is a response. If it is a response and is the last round in a multi-turn dialogue, we return a `loss_scale` of `[1]`. In other cases, we use the base implementation (which sets `loss_scale` to `[0]`). This approach ensures that only the responses from the last round participate in training, while other responses do not. Using this method, we can make all tokens (prompts and responses) participate in training or focus on specific special characters of the agent for training, etc.
|
| 73 |
+
|
| 74 |
+
In PT and SFT, `loss_scale` is uniformly supported (whether to participate in training and the size of the weights). However, in human alignment tasks, only the participation of certain tokens in training is supported, not the size of the weights.
|
| 75 |
+
|
| 76 |
+
## Customizing Metrics
|
| 77 |
+
|
| 78 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/metric.py).
|
| 79 |
+
|
| 80 |
+
Metrics can be customized to evaluate the training process:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
METRIC_MAPPING = {
|
| 84 |
+
'acc': (compute_acc_metrics, preprocess_logits_for_acc),
|
| 85 |
+
'nlg': (compute_nlg_metrics, None),
|
| 86 |
+
'custom': (custom_metric, custom_preprocess),
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def get_metric(metric: str):
|
| 90 |
+
return METRIC_MAPPING[metric]
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
In the above definition, we added a new `custom` metric. Its value consists of two parts: the first is the metric computation process, which returns a dictionary containing metric key-value pairs, and the second is the preprocessing step for logits, which returns the actual predictions.
|
| 94 |
+
|
| 95 |
+
## Customizing Optimizers
|
| 96 |
+
|
| 97 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/optimizer.py).
|
| 98 |
+
- Apply different learning rates to different parts of the model. For example, use separate learning rates for ViT and LLM, as referenced [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/lora_llm_full_vit/custom_plugin.py).
|
| 99 |
+
|
| 100 |
+
Users can add their own optimizers and learning rate schedulers here:
|
| 101 |
+
|
| 102 |
+
```python
|
| 103 |
+
def create_custom_optimizers(args, model, dataset):
|
| 104 |
+
# Create your own optimizer
|
| 105 |
+
return CustomOptimizer(optimizer_grouped_parameters, **optimizer_kwargs), CustomScheduler(...)
|
| 106 |
+
|
| 107 |
+
optimizers_map = {
|
| 108 |
+
'custom': create_custom_optimizers,
|
| 109 |
+
...
|
| 110 |
+
}
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
When developers need to use other optimizers, such as those defined in new research papers, they can define their creation process here and specify the parameter:
|
| 114 |
+
|
| 115 |
+
```shell
|
| 116 |
+
--optimizer custom
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
This will invoke the custom optimizer.
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
## Customizing Agent Template
|
| 123 |
+
|
| 124 |
+
The example is [here](https://github.com/modelscope/swift/blob/main/swift/plugin/agent_template).
|
| 125 |
+
|
| 126 |
+
## Customizing Tuners
|
| 127 |
+
|
| 128 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/tuner.py).
|
| 129 |
+
- For the multimodal model, full-parameter training is applied to the ViT part, while LoRA training is used for the LLM part. Refer to [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal/lora_llm_full_vit).
|
| 130 |
+
- For Phi4-multimodal, train its existing LoRA directly without adding extra LoRA. Refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/plugins/tuner_phi4_mm.sh).
|
| 131 |
+
|
| 132 |
+
Tuner customization is another unique feature of SWIFT. Developers can bypass the complex tuner initialization process and code integration costs by registering new tuners here:
|
| 133 |
+
|
| 134 |
+
```python
|
| 135 |
+
class IA3(Tuner):
|
| 136 |
+
|
| 137 |
+
@staticmethod
|
| 138 |
+
def prepare_model(args: 'TrainArguments', model: torch.nn.Module) -> torch.nn.Module:
|
| 139 |
+
model_arch: ModelKeys = MODEL_ARCH_MAPPING[model.model_meta.model_arch]
|
| 140 |
+
ia3_config = IA3Config(
|
| 141 |
+
target_modules=find_all_linears(model), feedforward_modules='.*' + model_arch.mlp.split('{}.')[1] + '.*')
|
| 142 |
+
return get_peft_model(model, ia3_config)
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def save_pretrained(
|
| 146 |
+
model: torch.nn.Module,
|
| 147 |
+
save_directory: str,
|
| 148 |
+
state_dict: Optional[dict] = None,
|
| 149 |
+
safe_serialization: bool = True,
|
| 150 |
+
**kwargs,
|
| 151 |
+
) -> None:
|
| 152 |
+
model: PeftModel
|
| 153 |
+
model.save_pretrained(save_directory, state_dict=state_dict, safe_serialization=safe_serialization, **kwargs)
|
| 154 |
+
|
| 155 |
+
@staticmethod
|
| 156 |
+
def from_pretrained(model: torch.nn.Module, model_id: str, **kwargs) -> torch.nn.Module:
|
| 157 |
+
return PeftModel.from_pretrained(model, model_id, **kwargs)
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
In the above example, we apply PEFT's IA3 to model training. This class includes three methods:
|
| 161 |
+
|
| 162 |
+
- `prepare_model`: How to wrap the original model using the tuner and set up trainable parameters.
|
| 163 |
+
- `save_pretrained`: How to save the model during training.
|
| 164 |
+
- `from_pretrained`: How to reload checkpoints saved earlier for subsequent training and inference.
|
| 165 |
+
|
| 166 |
+
These three methods are invoked during the SWIFT training process, allowing developers to use their tuners without reading the complex training code.
|
| 167 |
+
|
| 168 |
+
## PRM (Process Reward Model)
|
| 169 |
+
|
| 170 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/prm.py).
|
| 171 |
+
|
| 172 |
+
PRM stands for Process Reward Model, which is used in the `swift sample` command. PRM needs to support simple interfaces:
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
class PRM:
|
| 176 |
+
|
| 177 |
+
def __init__(self):
|
| 178 |
+
# init here
|
| 179 |
+
pass
|
| 180 |
+
|
| 181 |
+
def __call__(self, infer_requests: List[InferRequest], **kwargs) -> List[Union[float, List[float]]]:
|
| 182 |
+
raise NotImplementedError
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
The InferRequest comes from `swift.llm`, and the returned `List[Union[float, List[float]]]` may contain a reward or several rewards. Developers can access queries and responses in infer_requests and split them according to their own methods, for example:
|
| 186 |
+
|
| 187 |
+
```text
|
| 188 |
+
Let's think step by step.
|
| 189 |
+
|
| 190 |
+
Step1: xxx
|
| 191 |
+
|
| 192 |
+
Step2: xxx
|
| 193 |
+
|
| 194 |
+
So, the answer is ...
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Developers can split the process here, batch them into PRM for inference, and return rewards. More generally, developers can call a remote URL here, such as a closed-source PRM large model, and return rewards.
|
| 198 |
+
|
| 199 |
+
## ORM (Outcome Reward Model)
|
| 200 |
+
|
| 201 |
+
An example can be found [here](https://github.com/modelscope/swift/blob/main/swift/plugin/orm.py).
|
| 202 |
+
|
| 203 |
+
ORM stands for Outcome Reward Model. ORM typically uses regular expressions to determine whether a response is correct. For example:
|
| 204 |
+
|
| 205 |
+
```python
|
| 206 |
+
class MathORM(ORM):
|
| 207 |
+
|
| 208 |
+
@staticmethod
|
| 209 |
+
def extract_boxed_result(text):
|
| 210 |
+
pattern = r'\\boxed{([^}]*)}'
|
| 211 |
+
match = re.search(pattern, text)
|
| 212 |
+
if match:
|
| 213 |
+
return match.group(1).strip()
|
| 214 |
+
else:
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
def __call__(self, infer_requests: List[InferRequest], ground_truths: List[str],
|
| 218 |
+
**kwargs) -> List[float]:
|
| 219 |
+
rewards = []
|
| 220 |
+
predictions = [request.messages[-1]['content'] for request in infer_requests]
|
| 221 |
+
for prediction, ground_truth in zip(predictions, ground_truths):
|
| 222 |
+
res1 = MathORM.extract_boxed_result(prediction) or ''
|
| 223 |
+
res2 = MathORM.extract_boxed_result(ground_truth) or ''
|
| 224 |
+
rewards.append(float(res1.strip() == res2.strip()))
|
| 225 |
+
|
| 226 |
+
return rewards
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
orms = {
|
| 230 |
+
'math': MathORM,
|
| 231 |
+
}
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
In the above code, we define a process to parse mathematical responses. If the results are the same, it returns a score of `1.0`; otherwise, it returns `0.0`. Unlike PRM, this class's `infer` method includes an additional parameter `ground_truths`, which corresponds to the actual labels (standard responses defined in the dataset) for the `infer_requests`.
|
ms-swift/docs/source_en/GetStarted/SWIFT-installation.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SWIFT Installation
|
| 2 |
+
|
| 3 |
+
## Wheel Packages Installation
|
| 4 |
+
|
| 5 |
+
You can install it using pip:
|
| 6 |
+
|
| 7 |
+
```shell
|
| 8 |
+
pip install 'ms-swift'
|
| 9 |
+
# For evaluation usage
|
| 10 |
+
pip install 'ms-swift[eval]' -U
|
| 11 |
+
# Full capabilities
|
| 12 |
+
pip install 'ms-swift[all]' -U
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Source Code Installation
|
| 16 |
+
|
| 17 |
+
```shell
|
| 18 |
+
# pip install git+https://github.com/modelscope/ms-swift.git
|
| 19 |
+
|
| 20 |
+
# Full capabilities
|
| 21 |
+
# pip install "git+https://github.com/modelscope/ms-swift.git#egg=ms-swift[all]"
|
| 22 |
+
|
| 23 |
+
git clone https://github.com/modelscope/ms-swift.git
|
| 24 |
+
cd ms-swift
|
| 25 |
+
pip install -e .
|
| 26 |
+
|
| 27 |
+
# Full capabilities
|
| 28 |
+
# pip install -e '.[all]'
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## Older Versions
|
| 32 |
+
|
| 33 |
+
SWIFT underwent an incompatible restructuring starting from version 3.0. If you need to use the old version 2.x, please execute the following command to install:
|
| 34 |
+
|
| 35 |
+
```shell
|
| 36 |
+
pip install ms-swift==2.*
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
## Mirror
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
# vllm0.8.3 (This version of vllm may cause some GRPO training to get stuck; it is recommended to use vllm0.7.3 for GRPO training as a priority).
|
| 43 |
+
modelscope-registry.cn-hangzhou.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.4.0-py311-torch2.6.0-vllm0.8.3-modelscope1.25.0-swift3.3.0.post1
|
| 44 |
+
modelscope-registry.us-west-1.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.4.0-py311-torch2.6.0-vllm0.8.3-modelscope1.25.0-swift3.3.0.post1
|
| 45 |
+
|
| 46 |
+
# vllm0.7.3
|
| 47 |
+
modelscope-registry.us-west-1.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.4.0-py311-torch2.5.1-modelscope1.25.0-swift3.2.2
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
More images can be found [here](https://modelscope.cn/docs/intro/environment-setup#%E6%9C%80%E6%96%B0%E9%95%9C%E5%83%8F).
|
| 51 |
+
|
| 52 |
+
## Supported Hardware
|
| 53 |
+
|
| 54 |
+
| Hardware Environment | Remarks |
|
| 55 |
+
| -------------------- | ------------------------------------------------------ |
|
| 56 |
+
| A10/A100/H100 | |
|
| 57 |
+
| RTX 20/30/40 Series | |
|
| 58 |
+
| T4/V100 | Some models may encounter NAN |
|
| 59 |
+
| Ascend NPU | Some models may encounter NAN or unsupported operators |
|
| 60 |
+
| MPS | |
|
| 61 |
+
| CPU | |
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
## Running Environment
|
| 65 |
+
|
| 66 |
+
| | Range | Recommended | Notes |
|
| 67 |
+
| ------------ |--------------| ----------- | ----------------------------------------- |
|
| 68 |
+
| python | >=3.9 | 3.10 | |
|
| 69 |
+
| cuda | | cuda12 | No need to install if using CPU, NPU, MPS |
|
| 70 |
+
| torch | >=2.0 | | |
|
| 71 |
+
| transformers | >=4.33 | 4.51 | |
|
| 72 |
+
| modelscope | >=1.23 | | |
|
| 73 |
+
| peft | >=0.11,<0.16 | | |
|
| 74 |
+
| trl | >=0.13,<0.18 | 0.17 | RLHF |
|
| 75 |
+
| deepspeed | >=0.14 | 0.14.5 | Training |
|
| 76 |
+
| vllm | >=0.5.1 | 0.7.3/0.8 | Inference/Deployment/Evaluation |
|
| 77 |
+
| lmdeploy | >=0.5 | 0.8 | Inference/Deployment/Evaluation |
|
| 78 |
+
| evalscope | >=0.11 | | Evaluation |
|
| 79 |
+
|
| 80 |
+
For more optional dependencies, you can refer to [here](https://github.com/modelscope/ms-swift/blob/main/requirements/install_all.sh).
|
| 81 |
+
|
| 82 |
+
## Notebook Environment
|
| 83 |
+
|
| 84 |
+
Most models that Swift supports for training can be used on A10 GPUs. Users can take advantage of the free GPU resources offered by ModelScope:
|
| 85 |
+
|
| 86 |
+
1. Visit the [ModelScope](https://www.modelscope.cn) official website and log in.
|
| 87 |
+
2. Click on `My Notebook` on the left and start a free GPU instance.
|
| 88 |
+
3. Enjoy utilizing the A10 GPU resources.
|
ms-swift/docs/source_en/Instruction/Agent-support.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent Support
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
## Dataset Format
|
| 5 |
+
Example data samples for the pure text Agent and multimodal Agent are as follows:
|
| 6 |
+
|
| 7 |
+
```jsonl
|
| 8 |
+
{"tools": ["{\"type\": \"function\", \"function\": {\"name\": \"realtime_aqi\", \"description\": \"Weather forecast. Get real-time air quality, including current air quality, PM2.5, and PM10 information.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name, e.g., Shanghai\"}}, \"required\": [\"city\"]}}}"], "messages": [{"role": "user", "content": "What is the weather like in Beijing and Shanghai today?"}, {"role": "tool_call", "content": "{\"name\": \"realtime_aqi\", \"arguments\": {\"city\": \"Beijing\"}}"}, {"role": "tool_call", "content": "{\"name\": \"realtime_aqi\", \"arguments\": {\"city\": \"Shanghai\"}}"}, {"role": "tool_response", "content": "{\"city\": \"Beijing\", \"aqi\": \"10\", \"unit\": \"celsius\"}"}, {"role": "tool_response", "content": "{\"city\": \"Shanghai\", \"aqi\": \"72\", \"unit\": \"fahrenheit\"}"}, {"role": "assistant", "content": "According to the weather forecast tool, the air quality index (AQI) in Beijing is 10, which indicates good air quality; whereas in Shanghai, the AQI is 72, indicating mild pollution."}]}
|
| 9 |
+
{"tools": ["{\"type\": \"function\", \"function\": {\"name\": \"click\", \"description\": \"Click on a position on the screen\", \"parameters\": {\"type\": \"object\", \"properties\": {\"x\": {\"type\": \"integer\", \"description\": \"X-coordinate representing the horizontal position on the screen\"}, \"y\": {\"type\": \"integer\", \"description\": \"Y-coordinate representing the vertical position on the screen\"}}, \"required\": [\"x\", \"y\"]}}}"], "messages": [{"role": "user", "content": "<image>What time is it now?"}, {"role": "assistant", "content": "<think>\nI can check the current time by opening the calendar app.\n</think>\n"}, {"role": "tool_call", "content": "{\"name\": \"click\", \"arguments\": {\"x\": 105, \"y\": 132}}"}, {"role": "tool_response", "content": "{\"images\": \"<image>\", \"status\": \"success\"}"}, {"role": "assistant", "content": "Successfully opened the calendar app. The current time is 11 o'clock in the morning."}], "images": ["desktop.png", "calendar.png"]}
|
| 10 |
+
```
|
| 11 |
+
- When the `agent_template` is set to "react_en", "hermes", etc., this format is compatible with training for all model Agents and allows easy switching between different models.
|
| 12 |
+
- Here, `tools` is a `List[str]`, where each tool needs to be a JSON string. Additionally, the `content` part of the messages where the role is `'tool_call'` or `'tool_response/tool'` must also be in JSON string format.
|
| 13 |
+
- The `tools` field will be combined with the `{"role": "system", ...}` section during training/inference according to the `agent_template`, forming a complete system section.
|
| 14 |
+
- The `{"role": "tool_call", ...}` part will automatically be converted into corresponding formats of `{"role": "assistant", ...}` based on the `agent_template`. Multiple consecutive `{"role": "assistant", ...}` entries will be concatenated to form a complete assistant_content.
|
| 15 |
+
- The `{"role": "tool_response", ...}` can also be written as `{"role": "tool", ...}`, these two forms are equivalent. This part will also be automatically converted according to the `agent_template`. During training, this part does not participate in loss calculations, similar to `{"role": "user", ...}`.
|
| 16 |
+
- This format supports parallel tool calls; refer to the first data sample for an example. In multimodal Agent data samples, the number of `<image>` tags should match the length of "images", and their positions indicate where the image features are inserted. It also supports other modalities, such as audios and videos.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
The following are the `input_ids` and `labels` after encoding the two data samples mentioned above using the templates for **qwen2_5** and **qwen2_5_vl** , with the selected `agent_template` being **hermes** :
|
| 20 |
+
|
| 21 |
+
Sample One (Parallel Tool Calls):
|
| 22 |
+
|
| 23 |
+
```text
|
| 24 |
+
[INPUT_IDS] <|im_start|>system
|
| 25 |
+
You are Qwen, created by Alibaba Cloud. You are a helpful assistant.
|
| 26 |
+
|
| 27 |
+
# Tools
|
| 28 |
+
|
| 29 |
+
You may call one or more functions to assist with the user query.
|
| 30 |
+
|
| 31 |
+
You are provided with function signatures within <tools></tools> XML tags:
|
| 32 |
+
<tools>
|
| 33 |
+
{"type": "function", "function": {"name": "realtime_aqi", "description": "Weather forecast. Get real-time air quality, including current air quality, PM2.5, and PM10 information.", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name, e.g., Shanghai"}}, "required": ["city"]}}}
|
| 34 |
+
</tools>
|
| 35 |
+
|
| 36 |
+
For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
|
| 37 |
+
<tool_call>
|
| 38 |
+
{"name": <function-name>, "arguments": <args-json-object>}
|
| 39 |
+
</tool_call><|im_end|>
|
| 40 |
+
<|im_start|>user
|
| 41 |
+
What is the weather like in Beijing and Shanghai today?<|im_end|>
|
| 42 |
+
<|im_start|>assistant
|
| 43 |
+
<tool_call>
|
| 44 |
+
{"name": "realtime_aqi", "arguments": {"city": "Beijing"}}
|
| 45 |
+
</tool_call>
|
| 46 |
+
<tool_call>
|
| 47 |
+
{"name": "realtime_aqi", "arguments": {"city": "Shanghai"}}
|
| 48 |
+
</tool_call><|im_end|>
|
| 49 |
+
<|im_start|>user
|
| 50 |
+
<tool_response>
|
| 51 |
+
{"city": "Beijing", "aqi": "10", "unit": "celsius"}
|
| 52 |
+
</tool_response>
|
| 53 |
+
<tool_response>
|
| 54 |
+
{"city": "Shanghai", "aqi": "72", "unit": "fahrenheit"}
|
| 55 |
+
</tool_response><|im_end|>
|
| 56 |
+
<|im_start|>assistant
|
| 57 |
+
According to the weather forecast tool, the air quality index (AQI) in Beijing is 10, which indicates good air quality; whereas in Shanghai, the AQI is 72, indicating mild pollution.<|im_end|>
|
| 58 |
+
|
| 59 |
+
[LABELS] [-100 * 195]<tool_call>
|
| 60 |
+
{"name": "realtime_aqi", "arguments": {"city": "Beijing"}}
|
| 61 |
+
</tool_call>
|
| 62 |
+
<tool_call>
|
| 63 |
+
{"name": "realtime_aqi", "arguments": {"city": "Shanghai"}}
|
| 64 |
+
</tool_call><|im_end|>[-100 * 67]According to the weather forecast tool, the air quality index (AQI) in Beijing is 10, which indicates good air quality; whereas in Shanghai, the AQI is 72, indicating mild pollution.<|im_end|>
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Sample Two (Multimodal, Mixed Assistant and Tool Call):
|
| 68 |
+
|
| 69 |
+
```text
|
| 70 |
+
[INPUT_IDS] <|im_start|>system
|
| 71 |
+
You are a helpful assistant.
|
| 72 |
+
|
| 73 |
+
# Tools
|
| 74 |
+
|
| 75 |
+
You may call one or more functions to assist with the user query.
|
| 76 |
+
|
| 77 |
+
You are provided with function signatures within <tools></tools> XML tags:
|
| 78 |
+
<tools>
|
| 79 |
+
{"type": "function", "function": {"name": "click", "description": "Click on a position on the screen", "parameters": {"type": "object", "properties": {"x": {"type": "integer", "description": "X-coordinate representing the horizontal position on the screen"}, "y": {"type": "integer", "description": "Y-coordinate representing the vertical position on the screen"}}, "required": ["x", "y"]}}}
|
| 80 |
+
</tools>
|
| 81 |
+
|
| 82 |
+
For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
|
| 83 |
+
<tool_call>
|
| 84 |
+
{"name": <function-name>, "arguments": <args-json-object>}
|
| 85 |
+
</tool_call><|im_end|>
|
| 86 |
+
<|im_start|>user
|
| 87 |
+
<|vision_start|>[151655 * 729]<|vision_end|>What time is it now?<|im_end|>
|
| 88 |
+
<|im_start|>assistant
|
| 89 |
+
<think>
|
| 90 |
+
I can check the current time by opening the calendar app.
|
| 91 |
+
</think>
|
| 92 |
+
<tool_call>
|
| 93 |
+
{"name": "click", "arguments": {"x": 105, "y": 132}}
|
| 94 |
+
</tool_call><|im_end|>
|
| 95 |
+
<|im_start|>user
|
| 96 |
+
<tool_response>
|
| 97 |
+
{"images": "<|vision_start|>[151655 * 729]<|vision_end|>", "status": "success"}
|
| 98 |
+
</tool_response><|im_end|>
|
| 99 |
+
<|im_start|>assistant
|
| 100 |
+
Successfully opened the calendar app. The current time is 11 o'clock in the morning.<|im_end|>
|
| 101 |
+
|
| 102 |
+
[LABELS] [-100 * 924]<think>
|
| 103 |
+
I can check the current time by opening the calendar app.
|
| 104 |
+
</think>
|
| 105 |
+
<tool_call>
|
| 106 |
+
{"name": "click", "arguments": {"x": 105, "y": 132}}
|
| 107 |
+
</tool_call><|im_end|>[-100 * 759]Successfully opened the calendar app. The current time is 11 o'clock in the morning.<|im_end|>
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
**react_en** is one of the commonly used agent template formats. Below is an example of the `input_ids` and `labels` after encoding by qwen2_5 using `agent_template='react_en'`:
|
| 111 |
+
|
| 112 |
+
```text
|
| 113 |
+
[INPUT_IDS] <|im_start|>system
|
| 114 |
+
Answer the following questions as best you can. You have access to the following tools:
|
| 115 |
+
|
| 116 |
+
realtime_aqi: Call this tool to interact with the realtime_aqi API. What is the realtime_aqi API useful for? Weather forecast. Get real-time air quality, including current air quality, PM2.5, and PM10 information. Parameters: {"type": "object", "properties": {"city": {"type": "string", "description": "City name, e.g., Shanghai"}}, "required": ["city"]} Format the arguments as a JSON object.
|
| 117 |
+
|
| 118 |
+
Use the following format:
|
| 119 |
+
|
| 120 |
+
Question: the input question you must answer
|
| 121 |
+
Thought: you should always think about what to do
|
| 122 |
+
Action: the action to take, should be one of [realtime_aqi]
|
| 123 |
+
Action Input: the input to the action
|
| 124 |
+
Observation: the result of the action
|
| 125 |
+
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
|
| 126 |
+
Thought: I now know the final answer
|
| 127 |
+
Final Answer: the final answer to the original input question
|
| 128 |
+
|
| 129 |
+
Begin!
|
| 130 |
+
<|im_end|>
|
| 131 |
+
<|im_start|>user
|
| 132 |
+
What is the weather like in Beijing and Shanghai today?<|im_end|>
|
| 133 |
+
<|im_start|>assistant
|
| 134 |
+
Action: realtime_aqi
|
| 135 |
+
Action Input: {'city': 'Beijing'}
|
| 136 |
+
Action: realtime_aqi
|
| 137 |
+
Action Input: {'city': 'Shanghai'}
|
| 138 |
+
Observation:{"city": "Beijing", "aqi": "10", "unit": "celsius"}
|
| 139 |
+
Observation:{"city": "Shanghai", "aqi": "72", "unit": "fahrenheit"}
|
| 140 |
+
According to the weather forecast tool, the air quality index (AQI) in Beijing is 10, which indicates good air quality; whereas in Shanghai, the AQI is 72, indicating mild pollution.<|im_end|>
|
| 141 |
+
|
| 142 |
+
[LABELS] [-100 * 233]Action: realtime_aqi
|
| 143 |
+
Action Input: {'city': 'Beijing'}
|
| 144 |
+
Action: realtime_aqi
|
| 145 |
+
Action Input: {'city': 'Shanghai'}
|
| 146 |
+
Observation:[-100 * 45]According to the weather forecast tool, the air quality index (AQI) in Beijing is 10, which indicates good air quality; whereas in Shanghai, the AQI is 72, indicating mild pollution.<|im_end|>
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
The following code can be used to experiment with more models and `agent_template` options. For more selectable values of `agent_template`, refer to [here](https://github.com/modelscope/swift/blob/main/swift/plugin/agent_template/__init__.py).
|
| 150 |
+
|
| 151 |
+
```python
|
| 152 |
+
from swift.llm import get_model_tokenizer, get_template
|
| 153 |
+
|
| 154 |
+
_, tokenizer = get_model_tokenizer('ZhipuAI/GLM-4-9B-0414', load_model=False)
|
| 155 |
+
template = get_template(tokenizer.model_meta.template, tokenizer, agent_template='hermes')
|
| 156 |
+
data = {...}
|
| 157 |
+
template.set_mode('train')
|
| 158 |
+
encoded = template.encode(data)
|
| 159 |
+
print(f'[INPUT_IDS] {template.safe_decode(encoded["input_ids"])}\n')
|
| 160 |
+
print(f'[LABELS] {template.safe_decode(encoded["labels"])}')
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
## Tools Format
|
| 164 |
+
|
| 165 |
+
The tools field provides information about the APIs that the model can call. You need to provide the name, description, and parameters of the tools, as shown in the example below:
|
| 166 |
+
|
| 167 |
+
```python
|
| 168 |
+
tools = [{
|
| 169 |
+
'type': 'function',
|
| 170 |
+
'function': {
|
| 171 |
+
'name': 'get_current_weather',
|
| 172 |
+
'description': 'Get the current weather in a given location',
|
| 173 |
+
'parameters': {
|
| 174 |
+
'type': 'object',
|
| 175 |
+
'properties': {
|
| 176 |
+
'location': {
|
| 177 |
+
'type': 'string',
|
| 178 |
+
'description': 'The city and state, e.g. San Francisco, CA'
|
| 179 |
+
},
|
| 180 |
+
'unit': {
|
| 181 |
+
'type': 'string',
|
| 182 |
+
'enum': ['celsius', 'fahrenheit']
|
| 183 |
+
}
|
| 184 |
+
},
|
| 185 |
+
'required': ['location']
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
}]
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
## Usage of loss_scale
|
| 192 |
+
|
| 193 |
+
`loss_scale` can be used to adjust the training loss weight for the model's output section. For example, in the ReACT format, you can set `--loss_scale react` (the loss_scale configuration file is written [here](https://github.com/modelscope/swift/blob/main/swift/plugin/loss_scale/config/react.json)). The role of this parameter is as follows:
|
| 194 |
+
|
| 195 |
+
- The weight for the 'Thought:' and 'Final Answer:' sections is 1.
|
| 196 |
+
- The weight for the 'Action:' and 'Action Input:' sections is 2.
|
| 197 |
+
- The weight for the 'Observation:' field itself is 2.
|
| 198 |
+
- The weight for the tool invocation results following the 'Observation:' field is 0.
|
| 199 |
+
|
| 200 |
+
For the detailed design of the `loss_scale` plugin, please refer to the [Plugin-based Architecture](../Customization/Pluginization.md)documentation.
|
| 201 |
+
|
| 202 |
+
## Training
|
| 203 |
+
|
| 204 |
+
- Train the Agent capabilities of Base models by switching different models through modifying `--model`. Refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/agent/qwen2_5.sh).
|
| 205 |
+
- The agent_template for training GLM4 is hermes. Refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/agent/glm4.sh).
|
| 206 |
+
- Use `--loss_scale` to adjust the loss weight of the model output section. Refer to [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/agent/loss_scale).
|
| 207 |
+
|
| 208 |
+
## Inference
|
| 209 |
+
|
| 210 |
+
- 🚀For inference of the original model or fully trained model, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_agent.py).
|
| 211 |
+
- For inference after LoRA training, refer to [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/agent/loss_scale/infer.md).
|
| 212 |
+
|
| 213 |
+
## Deployment
|
| 214 |
+
|
| 215 |
+
For server and client code, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/deploy/agent).
|
ms-swift/docs/source_en/Instruction/Command-line-parameters.md
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Command Line Parameters
|
| 2 |
+
|
| 3 |
+
The introduction to command line parameters will cover base arguments, atomic arguments, and integrated arguments, and specific model arguments. The final list of arguments used in the command line is the integration arguments. Integrated arguments inherit from basic arguments and some atomic arguments. Specific model arguments are designed for specific models and can be set using `--model_kwargs'` or the environment variable. The introduction to the Megatron-SWIFT command-line arguments can be found in the [Megatron-SWIFT Training Documentation](./Megatron-SWIFT-Training.md).
|
| 4 |
+
|
| 5 |
+
Hints:
|
| 6 |
+
|
| 7 |
+
- For passing a list in the command line, you can separate items with spaces. For example: `--dataset <dataset_path1> <dataset_path2>`.
|
| 8 |
+
- For passing a dict in the command line, use JSON format. For example: `--model_kwargs '{"fps_max_frames": 12}'`.
|
| 9 |
+
- Parameters marked with 🔥 are important. New users familiarizing themselves with ms-swift can focus on these command line parameters first.
|
| 10 |
+
|
| 11 |
+
## Base Arguments
|
| 12 |
+
|
| 13 |
+
- 🔥tuner_backend: Options are 'peft', 'unsloth'. Default is 'peft'.
|
| 14 |
+
- 🔥train_type: Options are: 'lora', 'full', 'longlora', 'adalora', 'llamapro', 'adapter', 'vera', 'boft', 'fourierft', 'reft'. Default is 'lora'.
|
| 15 |
+
- 🔥adapters: A list used to specify the id/path of the adapter. Default is `[]`.
|
| 16 |
+
- external_plugins: A list of external plugin py files which will be registered into the plugin mappings,please check [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/grpo/plugin/run_external_rm.sh).
|
| 17 |
+
- seed: Default is 42.
|
| 18 |
+
- model_kwargs: Additional parameters specific to the model that can be passed in. This list of parameters will log a message during training and inference for reference. For example, `--model_kwargs '{"fps_max_frames": 12}'`.
|
| 19 |
+
- load_args: When specifying `--resume_from_checkpoint`, `--model`, or `--adapters`, it will read the `args.json` file saved in the checkpoint, assigning values to the default None `basic arguments` (excluding data and generation arguments) which can be overridden by manually passing them in. The default is True for inference and export, and False for training.
|
| 20 |
+
- load_data_args: If this parameter is set to True, additional data parameters will be read from args.json. The default is False.
|
| 21 |
+
- use_hf: Controls whether ModelScope or HuggingFace is used for model and dataset downloads, and model pushing. Defaults to False, meaning ModelScope is used.
|
| 22 |
+
- hub_token: Hub token. The hub token for ModelScope can be viewed [here](https://modelscope.cn/my/myaccesstoken).
|
| 23 |
+
- custom_register_path: A list of paths to `.py` files for custom registration of models, dialogue templates, and datasets. Defaults to `[]`.
|
| 24 |
+
|
| 25 |
+
### Model Arguments
|
| 26 |
+
- 🔥model: Model ID or local path to the model. If it's a custom model, please use it with `model_type` and `template`. The specific details can be referred to in the [Custom Model](../Customization/Custom-model.md).
|
| 27 |
+
- model_type: Model type. The same model architecture, template, and model loading process are defined as a model_type. The default is None, and it will be automatically selected based on the suffix of `--model` and the architectures attribute in config.json.
|
| 28 |
+
- model_revision: Model revision, default is None.
|
| 29 |
+
- task_type: The default value is 'causal_lm'. Optional values are 'causal_lm', 'seq_cls', and 'embedding'. Examples for seq_cls can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/seq_cls), and examples for embedding can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/embedding).
|
| 30 |
+
- 🔥torch_dtype: Data type of model weights, supports `float16`, `bfloat16`, `float32`. The default is None, and it is read from the 'config.json' file.
|
| 31 |
+
- attn_impl: Type of attention, options are`flash_attn`, `sdpa`, `eager`. The default is sdpa; if not supported, eager is used.
|
| 32 |
+
- Note: These three implementations may not all be supported, depending on the support of the corresponding model.
|
| 33 |
+
- num_labels: This parameter is required for classification models (i.e., `--task_type seq_cls`). It represents the number of labels, with a default value of None.
|
| 34 |
+
- problem_type: This parameter is required for classification models (i.e., `--task_type seq_cls`). The options are 'regression', 'single_label_classification', and 'multi_label_classification'. The default value is None, and it will be automatically set based on the number of labels and the dataset type.
|
| 35 |
+
- rope_scaling: Type of rope, supports `linear` and `dynamic`, should be used in conjunction with `max_length`. Default is None.
|
| 36 |
+
- device_map: Device map configuration used by the model, such as 'auto', 'cpu', JSON string, or the path of a JSON file. The default is None, automatically set based on the device and distributed training conditions.
|
| 37 |
+
- max_memory: When device_map is set to 'auto' or 'sequential', the model weights will be allocated to devices based on max_memory, for example: `--max_memory '{0: "20GB", 1: "20GB"}'`. The default value is None.
|
| 38 |
+
- local_repo_path: Some models depend on a GitHub repo when loading. To avoid network issues during `git clone`, a local repo can be used directly. This parameter needs to be passed with the path to the local repo, with the default being `None`.
|
| 39 |
+
- init_strategy: When loading the model, initialize all uninitialized parameters. Options values are 'zero', 'uniform', 'normal', 'xavier_uniform', 'xavier_normal', 'kaiming_uniform', 'kaiming_normal', 'orthogonal'. Default is None.
|
| 40 |
+
|
| 41 |
+
### Data Arguments
|
| 42 |
+
- 🔥dataset: A list of dataset IDs or paths. Default is `[]`. The input format for each dataset is: `dataset ID or dataset path:sub-dataset#sampling size`, where sub-dataset and sampling data are optional. Local datasets support jsonl, csv, json, folders, etc. Open-source datasets can be cloned locally via git and used offline by passing the folder. For custom dataset formats, refer to [Custom Dataset](../Customization/Custom-dataset.md). You can pass in `--dataset <dataset1> <dataset2>` to use multiple datasets.
|
| 43 |
+
- Sub-dataset: This parameter is effective only when the dataset is an ID or folder. If a subset was specified during registration, and only one sub-dataset exists, the registered sub-dataset is selected by default; otherwise, it defaults to 'default'. You can use `/` to select multiple sub-datasets, e.g., `<dataset_id>:subset1/subset2`. You can also use 'all' to select all sub-datasets, e.g., `<dataset_id>:all`.
|
| 44 |
+
- Sampling Size: By default, the complete dataset is used. If the sampling size is less than the total number of data samples, samples are selected randomly without repetition. If the sampling size exceeds the total number of data samples, then `sampling size%total data samples` samples are randomly sampled additionally, and data samples are repetitively sampled `sampling size//total data samples` times. Note: Streaming datasets only perform sequential sampling. If `--dataset_shuffle false` is set, non-streaming datasets will also perform sequential sampling.
|
| 45 |
+
- 🔥val_dataset: A list of validation set IDs or paths. Default is `[]`.
|
| 46 |
+
- 🔥split_dataset_ratio: Ratio for splitting the training set and validation set when val_dataset is not specified, default is 0.01. Set to 0 if no validation set split is needed.
|
| 47 |
+
- data_seed: Random seed for the dataset, default is 42.
|
| 48 |
+
- 🔥dataset_num_proc: Number of processes for dataset preprocessing, default is 1.
|
| 49 |
+
- 🔥load_from_cache_file: Whether to load the dataset from the cache, default is False.
|
| 50 |
+
- dataset_shuffle: Whether to shuffle the dataset. Defaults to True.
|
| 51 |
+
- Note: The shuffling in CPT/SFT consists of two parts: dataset shuffling, controlled by `dataset_shuffle`; and shuffling in the train_dataloader, controlled by `train_dataloader_shuffle`.
|
| 52 |
+
- val_dataset_shuffle: Whether to perform shuffling on the val_dataset. Default is False.
|
| 53 |
+
- 🔥streaming: Stream reading and processing of the dataset, default is False. It is typically set to True when handling large datasets.
|
| 54 |
+
- Note: You need to set `--max_steps` explicitly, as the streaming dataset does not have a defined length. You can achieve training equivalent to `--num_train_epochs` by setting `--save_strategy epoch` and specifying a sufficiently large `max_steps`. Alternatively, you can set `max_epochs` to ensure training exits after the corresponding number of epochs, at which point the model weights will be validated and saved.
|
| 55 |
+
- interleave_prob: Defaults to None. When combining multiple datasets, the `concatenate_datasets` function is used by default. If this parameter is set, the `interleave_datasets` function will be used instead. This parameter is typically used when combining streaming datasets and is passed to the `interleave_datasets` function.
|
| 56 |
+
- stopping_strategy: Can be either "first_exhausted" or "all_exhausted", with the default being "first_exhausted". This parameter is passed to the `interleave_datasets` function.
|
| 57 |
+
- shuffle_buffer_size: This parameter is used to specify the shuffle buffer size for streaming datasets. Defaults to 1000.
|
| 58 |
+
- download_mode: Dataset download mode, including `reuse_dataset_if_exists` and `force_redownload`, default is reuse_dataset_if_exists.
|
| 59 |
+
- columns: Used for column mapping of the dataset to ensure that the dataset conforms to the format that AutoPreprocessor can handle. For more details, see [here](../Customization/Custom-dataset.md). You can pass in a JSON string, for example: `'{"text1": "query", "text2": "response"}'`, with the default being None.
|
| 60 |
+
- strict: If set to True, any row with an issue in the dataset will throw an error immediately, otherwise, erroneous data samples will be discarded. Default is False.
|
| 61 |
+
- remove_unused_columns: Whether to remove unused columns in the dataset, defaults to True.
|
| 62 |
+
- 🔥model_name: Only applicable to the self-cognition task and effective only on the `swift/self-cognition` dataset. It replaces the `{{NAME}}` placeholder in the dataset. Input the model's name in both Chinese and English, separated by a space, for example: `--model_name 小黄 'Xiao Huang'`. Default is None.
|
| 63 |
+
- 🔥model_author: Only applicable to the self-cognition task and effective only on the `swift/self-cognition` dataset. It replaces the `{{AUTHOR}}` placeholder in the dataset. Input the model author's name in both Chinese and English, separated by a space, for example: `--model_author '魔搭' 'ModelScope'`. Default is None.
|
| 64 |
+
- custom_dataset_info: The path to the JSON file for custom dataset registration. Refer to [Custom Dataset](../Customization/Custom-dataset.md). Default is `[]`.
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
### Template Arguments
|
| 68 |
+
- 🔥template: Type of dialogue template. Default is None, which automatically selects the corresponding model's template type.
|
| 69 |
+
- 🔥system: Custom system field, can take a string or txt file path as input. Default is None, uses the default system of the template.
|
| 70 |
+
- Note: The system priority in the dataset is the highest, followed by `--system`, and finally the `default_system` defined in the template.
|
| 71 |
+
- 🔥max_length: The maximum length of tokens for a single sample. Defaults to None, set to the maximum length of tokens supported by the model (max_model_len).
|
| 72 |
+
- Note: In the cases of PPO, GRPO, and inference, max_length represents max_prompt_length.
|
| 73 |
+
- truncation_strategy: Strategy for handling single sample tokens that exceed `max_length`. Options are `delete`, `left`, and `right`, representing deletion, left-side truncation, and right-side truncation, respectively. The default is 'delete'.
|
| 74 |
+
- 🔥max_pixels: The maximum number of pixels (H*W) for input images to a multimodal model. Images exceeding this limit will be scaled. Default is None, meaning no maximum pixel limit.
|
| 75 |
+
- 🔥agent_template: Agent template, which determines how to convert the list of tools into a system, how to extract tool calls from the model's response, and specifies the template format for `{"role": "tool_call", "content": "xxx"}` and `{"role": "tool_response", "content": "xxx"}`. Optional values include "react_en", "hermes", "glm4", "qwen_en", "toolbench", etc. For more details, please check [here](https://github.com/modelscope/ms-swift/blob/main/swift/plugin/agent_template/__init__.py). The default value is None, meaning it will be selected based on the model type.
|
| 76 |
+
- norm_bbox: Controls how to scale bounding boxes (bbox). Options are 'norm1000' and 'none'. 'norm1000' represents scaling bbox coordinates to one-thousandths, and 'none' means no scaling. Default is None, automatically selected based on the model.
|
| 77 |
+
- response_prefix: The prefix character for the response, for example, setting the response_prefix to `'<think>\n'` for QwQ-32B. The default is None, and it is automatically set according to the model.
|
| 78 |
+
- Note: If you are training the deepseek-r1/qwq model with a dataset that does not include `<think>...</think>`, please pass `--response_prefix ''` additionally when inferring after training.
|
| 79 |
+
- padding_side: Padding side when `batch_size>=2` during training. Options are 'left' and 'right', with 'right' as the default. (For inference with batch_size>=2, only left padding is applied.)
|
| 80 |
+
- loss_scale: Weight setting for the loss of training tokens. Default is `'default'`, which means that all responses (including history) are used with a weight of 1 in cross-entropy loss, and the loss from the corresponding `tool_response` in the agent_template is ignored. Possible values include: 'default', 'last_round', 'all', 'ignore_empty_think', and agent-specific options: 'react', 'hermes', 'qwen', 'agentflan', 'alpha_umi'. For more details about the agent part, please refer to [Pluginization](../Customization/Pluginization.md) and [Agent Training](./Agent-support.md).
|
| 81 |
+
- 'last_round': Only calculate the loss for the last round of response.
|
| 82 |
+
- 'all': Calculate the loss for all tokens.
|
| 83 |
+
- 'ignore_empty_think': On top of 'default', ignore the loss calculation for empty `'<think>\n\n</think>\n\n'`. See [this issue](https://github.com/modelscope/ms-swift/issues/4030) for more details.
|
| 84 |
+
- `'react'`, `'hermes'`, `'qwen'`: On top of `'default'`, set the loss weight of the `tool_call` part to 2.
|
| 85 |
+
- sequence_parallel_size: Sequence parallelism size, default is 1. Currently supported in pt/sft/dpo. The training script refers to [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/long_text/sequence_parallel.sh).
|
| 86 |
+
- use_chat_template: Use chat template or generation template, default is `True`. `swift pt` is automatically set to the generation template.
|
| 87 |
+
- template_backend: Selection of the template backend. Options are 'swift' and 'jinja', with 'swift' as the default. If using jinja, it applies transformer's `apply_chat_template`.
|
| 88 |
+
- Note: The jinja template backend supports only inference, not training.
|
| 89 |
+
|
| 90 |
+
### Generation Arguments
|
| 91 |
+
|
| 92 |
+
Refer to the [generation_config](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig) documentation.
|
| 93 |
+
|
| 94 |
+
- 🔥max_new_tokens: The maximum number of new tokens generated during inference. Defaults to None, meaning unlimited.
|
| 95 |
+
- temperature: The temperature parameter. Defaults to None and is read from generation_config.json.
|
| 96 |
+
- Note: The do_sample parameter has been removed in this version. Set the temperature to 0 to achieve the same effect.
|
| 97 |
+
- top_k: The top_k parameter, defaults to None. It is read from generation_config.json.
|
| 98 |
+
- top_p: The top_p parameter, defaults to None. It is read from generation_config.json.
|
| 99 |
+
- repetition_penalty: The repetition penalty. Defaults to None and is read from generation_config.json.
|
| 100 |
+
- num_beams: The number of beams reserved for parallel beam search, default is 1.
|
| 101 |
+
- 🔥stream: Stream output, default is `False`.
|
| 102 |
+
- stop_words: Additional stop words beyond eos_token, default is`[]`.
|
| 103 |
+
- Note: eos_token will be removed in the output response, whereas additional stop words will be retained in the output.
|
| 104 |
+
- logprobs: Whether to output logprobs, default is False.
|
| 105 |
+
- top_logprobs: The number of top_logprobs to output, defaults to None.
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
### Quantization Arguments
|
| 109 |
+
|
| 110 |
+
The following are the parameters for quantization when loading a model. For detailed meanings, you can refer to the [quantization](https://huggingface.co/docs/transformers/main/en/main_classes/quantization) documentation. Note that this does not include `gptq` and `awq` quantization parameters involved in `swift export`.
|
| 111 |
+
|
| 112 |
+
- 🔥quant_method: The quantization method used when loading the model. Options are `bnb`, `hqq`, `eetq`.
|
| 113 |
+
- 🔥quant_bits: Number of bits for quantization, default is None.
|
| 114 |
+
- hqq_axis: HQQ quantization axis, default is None.
|
| 115 |
+
- bnb_4bit_compute_dtype: The computation type for bnb quantization. Options are `float16`, `bfloat16`, `float32`. The default is None, which sets it to `torch_dtype`.
|
| 116 |
+
- bnb_4bit_quant_type: BNB quantization type, supports `fp4` and `nf4`, default is `nf4`.
|
| 117 |
+
- bnb_4bit_use_double_quant: Whether to use double quantization, default is `True`.
|
| 118 |
+
- bnb_4bit_quant_storage: BNB quantization storage type, default is None.
|
| 119 |
+
|
| 120 |
+
## Atomic Arguments
|
| 121 |
+
|
| 122 |
+
### Seq2SeqTrainer Arguments
|
| 123 |
+
|
| 124 |
+
This parameter list inherits from transformers `Seq2SeqTrainingArguments`, with default values overridden by ms-swift. For unlisted items, refer to the [HF Official Documentation](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Seq2SeqTrainingArguments).
|
| 125 |
+
|
| 126 |
+
- 🔥output_dir: Defaults to None, set as `output/<model_name>`.
|
| 127 |
+
- 🔥gradient_checkpointing: Whether to use gradient checkpointing, default is True.
|
| 128 |
+
- 🔥deepspeed: Defaults to None. It can be set to 'zero0', 'zero1', 'zero2', 'zero3', 'zero2_offload', 'zero3_offload' to use the built-in deepspeed configuration file of ms-swift.
|
| 129 |
+
- zero_hpz_partition_size: Default is `None`. This parameter is a feature of `ZeRO++`, which implements model sharding within nodes and data sharding between nodes. If you encounter grad_norm `NaN` issues, please try using `--torch_dtype float16`
|
| 130 |
+
- 🔥per_device_train_batch_size: Default is 1.
|
| 131 |
+
- 🔥per_device_eval_batch_size: Default is 1.
|
| 132 |
+
- 🔥gradient_accumulation_steps: Gradient accumulation, default is None, meaning set gradient_accumulation_steps such that total_batch_size >= 16. The total_batch_size equals `per_device_train_batch_size * gradient_accumulation_steps * world_size`.
|
| 133 |
+
- weight_decay: Weight decay coefficient, default value is 0.1.
|
| 134 |
+
- adam_beta2: Default is 0.95.
|
| 135 |
+
- 🔥learning_rate: Learning rate, defaults to 1e-5 for full parameters, and 1e-4 for LoRA and other tuners.
|
| 136 |
+
- lr_scheduler_type: Type of lr_scheduler, defaults to 'cosine'.
|
| 137 |
+
- lr_scheduler_kwargs: Other parameters for the lr_scheduler, defaults to None.
|
| 138 |
+
- 🔥gradient_checkpointing_kwargs: Parameters for `torch.utils.checkpoint`. For example, set as `--gradient_checkpointing_kwargs '{"use_reentrant": false}'`. Defaults to None.
|
| 139 |
+
- full_determinism: Ensures reproducible results during training. Note: This will negatively impact performance. Defaults to False.
|
| 140 |
+
- 🔥report_to: Default value is `tensorboard`. You can also specify `--report_to tensorboard wandb swanlab` or `--report_to all`.
|
| 141 |
+
- logging_first_step: Whether to log the first step, defaults to True.
|
| 142 |
+
- logging_steps: Interval for logging, defaults to 5.
|
| 143 |
+
- predict_with_generate: Whether to use generative method during validation, default is False.
|
| 144 |
+
- metric_for_best_model: Default is None, which means that when predict_with_generate is set to False, it is set to 'loss'; otherwise, it is set to 'rouge-l' (during PPO training, the default value is not set; in GRPO training, it is set to 'reward').
|
| 145 |
+
- greater_is_better: Defaults to None, which sets it to False when `metric_for_best_model` contains 'loss', otherwise sets to True.
|
| 146 |
+
- max_epochs: Forces the training to exit after reaching `max_epochs`, and performs validation and saving of the model weights. This parameter is especially useful when using a streaming dataset. Default is None.
|
| 147 |
+
|
| 148 |
+
Other important parameters:
|
| 149 |
+
- 🔥num_train_epochs: Number of training epochs, default is 3.
|
| 150 |
+
- 🔥save_strategy: Strategy for saving the model, options include 'no', 'steps', 'epoch'. Default is 'steps'.
|
| 151 |
+
- 🔥save_steps: Default is 500.
|
| 152 |
+
- 🔥eval_strategy: Evaluation strategy. Default is None and follows the strategy of `save_strategy`.
|
| 153 |
+
- 🔥eval_steps: Default is None. If there is an evaluation dataset, it follows the strategy of `save_steps`.
|
| 154 |
+
- 🔥save_total_limit: Maximum number of checkpoints to save. Older checkpoints will be deleted. Default is None, saving all checkpoints.
|
| 155 |
+
- max_steps: Maximum number of training steps. Should be set when the dataset is streamed. Default is -1.
|
| 156 |
+
- 🔥warmup_ratio: Default is 0.
|
| 157 |
+
- save_on_each_node: Default is False. Should be considered in multi-node training.
|
| 158 |
+
- save_only_model: Whether to save only the model weights without including optimizer state, random seed state, etc. Default is False.
|
| 159 |
+
- 🔥resume_from_checkpoint: Parameter for resuming training from a checkpoint, pass the checkpoint path. Default is None.
|
| 160 |
+
- Note: `resume_from_checkpoint` will load the model weights, optimizer weights, and random seed, and continue training from the last trained steps. You can specify `--resume_only_model` to load only the model weights.
|
| 161 |
+
- 🔥ddp_backend: Options include "nccl", "gloo", "mpi", "ccl", "hccl", "cncl", and "mccl". Default is None, which allows for automatic selection.
|
| 162 |
+
- 🔥ddp_find_unused_parameters: Default is None.
|
| 163 |
+
- ddp_timeout: The default value is 1800, with the unit being seconds.
|
| 164 |
+
- 🔥dataloader_num_workers: Defaults to None. If the platform is Windows, it is set to 0; otherwise, it is set to 1.
|
| 165 |
+
- dataloader_pin_memory: Default is True.
|
| 166 |
+
- dataloader_persistent_workers: Default is False.
|
| 167 |
+
- dataloader_prefetch_factor: Defaults to None. If `dataloader_num_workers > 0`, it is set to 10.
|
| 168 |
+
- train_dataloader_shuffle: Specifies whether the dataloader for CPT/SFT training is shuffled, with the default set to True. This parameter is not applicable to IterableDataset, as IterableDataset reads in a sequential manner.
|
| 169 |
+
- 🔥neftune_noise_alpha: Coefficient of noise added by neftune, default is 0. Usually can be set to 5, 10, 15.
|
| 170 |
+
- 🔥use_liger_kernel: Whether to enable the [Liger](https://github.com/linkedin/Liger-Kernel) kernel to accelerate training and reduce GPU memory consumption. Defaults to False. Example shell script can be found [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/liger).
|
| 171 |
+
- average_tokens_across_devices: Whether to average the number of tokens across devices. If set to True, `num_tokens_in_batch` will be synchronized using all_reduce for accurate loss calculation. Default is False.
|
| 172 |
+
- max_grad_norm: Gradient clipping. Default is 1.
|
| 173 |
+
- push_to_hub: Push checkpoint to hub. Default is False.
|
| 174 |
+
- hub_model_id: Default is None.
|
| 175 |
+
- hub_private_repo: Default is False.
|
| 176 |
+
|
| 177 |
+
### Tuner Arguments
|
| 178 |
+
|
| 179 |
+
- 🔥freeze_llm: This parameter is only effective for multimodal models and can be used for full parameter training and LoRA, but with different meanings. In full parameter training, setting freeze_llm to True will freeze some of the LLM weights. In LoRA training, if `target_modules` is set to 'all-linear', setting freeze_llm to True will prevent adding LoRA modules to the LLM part. The default is False.
|
| 180 |
+
- 🔥freeze_vit: This parameter is only effective for multimodal models and can be used for full parameter training and LoRA, with similar meanings as `freeze_llm`. The default is True.
|
| 181 |
+
- 🔥freeze_aligner: This parameter is only effective for multimodal models and can be used for full parameter training and LoRA, with similar meanings as `freeze_llm`. The default is True.
|
| 182 |
+
- 🔥target_modules: Specifies LoRA modules, with a default of `all-linear`. Its behavior differs in LLM and multimodal LLM. For LLM, it automatically finds all linear modules except lm_head and adds a tuner. For multimodal LLM, by default, it only adds a tuner to the LLM part, and this behavior can be controlled by `freeze_llm`, `freeze_vit`, and `freeze_aligner`. This parameter is not limited to LoRA and can be used for other tuners.
|
| 183 |
+
- 🔥target_regex: Specifies a regex expression for LoRA modules, with a default of `None`. If this value is provided, the target_modules parameter becomes ineffective. This parameter is not limited to LoRA and can be used for other tuners.
|
| 184 |
+
- init_weights: Specifies the method for initializing weights. LoRA can specify `true`, `false`, `gaussian`, `pissa`, `pissa_niter_[number of iters]`. Bone can specify `true`, `false`, `bat`. The default is `true`.
|
| 185 |
+
- 🔥modules_to_save: After attaching a tuner, explicitly specifies additional original model modules to participate in training and storage. The default is `[]`. This parameter is not limited to LoRA and can be used for other tuners.
|
| 186 |
+
|
| 187 |
+
#### Full Arguments
|
| 188 |
+
|
| 189 |
+
- freeze_parameters: Prefix of the parameters to be frozen, default is `[]`.
|
| 190 |
+
- freeze_parameters_regex: Regex for matching the parameters to be frozen,default is None.
|
| 191 |
+
- freeze_parameters_ratio: Ratio of parameters to freeze from bottom to top, default is 0. It can be set to 1 to freeze all parameters, and trainable parameters can be set in conjunction with this.
|
| 192 |
+
- trainable_parameters: Prefix of additional trainable parameters, default is `[]`.
|
| 193 |
+
- trainable_parameters_regex: Regex for matching additional trainable parameters, default is None.
|
| 194 |
+
- Note: `trainable_parameters`, `trainable_parameters_regex` takes precedence over `freeze_parameters`, `freeze_parameters_regex` and `freeze_parameters_ratio`. When full parameter training is specified, all modules are set to trainable, then some parameters are frozen according to `freeze_parameters`, `freeze_parameters_regex` and `freeze_parameters_ratio`, and finally, some parameters are reopened for training according to `trainable_parameters`,`trainable_parameters_regex`.
|
| 195 |
+
|
| 196 |
+
#### LoRA
|
| 197 |
+
|
| 198 |
+
- 🔥lora_rank: Default is `8`.
|
| 199 |
+
- 🔥lora_alpha: Default is `32`.
|
| 200 |
+
- lora_dropout: Default is `0.05`.
|
| 201 |
+
- lora_bias: Defaults to `'none'`. Possible values are 'none', 'all'. If you want to make all biases trainable, you can set it to `'all'`.
|
| 202 |
+
- lora_dtype: Specifies the dtype type for the LoRA modules. Supported types are 'float16', 'bfloat16', 'float32'. The default is None, which follows the original model type.
|
| 203 |
+
- 🔥use_dora: Defaults to `False`, indicating whether to use `DoRA`.
|
| 204 |
+
- use_rslora: Defaults to `False`, indicating whether to use `RS-LoRA`.
|
| 205 |
+
- 🔥lorap_lr_ratio: LoRA+ parameter, default value `None`, recommended values `10~16`. Specify this parameter when using LoRA to enable LoRA+.
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
##### LoRA-GA
|
| 209 |
+
- lora_ga_batch_size: The default value is `2`. The batch size used for estimating gradients during initialization in LoRA-GA.
|
| 210 |
+
- lora_ga_iters: The default value is `2`. The number of iterations for estimating gradients during initialization in LoRA-GA.
|
| 211 |
+
- lora_ga_max_length: The default value is `1024`. The maximum input length for estimating gradients during initialization in LoRA-GA.
|
| 212 |
+
- lora_ga_direction: The default value is `ArB2r`. The initial direction used for gradient estimation during initialization in LoRA-GA. Allowed values are: `ArBr`, `A2rBr`, `ArB2r`, and `random`.
|
| 213 |
+
- lora_ga_scale: The default value is `stable`. The scaling method for initialization in LoRA-GA. Allowed values are: `gd`, `unit`, `stable`, and `weightS`.
|
| 214 |
+
- lora_ga_stable_gamma: The default value is `16`. The gamma value when choosing `stable` scaling for initialization.
|
| 215 |
+
|
| 216 |
+
#### FourierFt
|
| 217 |
+
|
| 218 |
+
FourierFt uses the three parameters `target_modules`, `target_regex`, and `modules_to_save`.
|
| 219 |
+
|
| 220 |
+
- fourier_n_frequency: Number of frequencies in Fourier transform, an `int`, similar to `r` in LoRA. Default value is `2000`.
|
| 221 |
+
- fourier_scaling: Scaling value of matrix W, a `float`, similar to `lora_alpha` in LoRA. Default value is `300.0`.
|
| 222 |
+
|
| 223 |
+
#### BOFT
|
| 224 |
+
|
| 225 |
+
BOFT uses the three parameters `target_modules`, `target_regex`, and `modules_to_save`.
|
| 226 |
+
|
| 227 |
+
- boft_block_size: Size of BOFT blocks, default value is 4.
|
| 228 |
+
- boft_block_num: Number of BOFT blocks, cannot be used simultaneously with `boft_block_size`.
|
| 229 |
+
- boft_dropout: Dropout value for BOFT, default is 0.0.
|
| 230 |
+
|
| 231 |
+
#### Vera
|
| 232 |
+
|
| 233 |
+
Vera uses the three parameters `target_modules`, `target_regex`, and `modules_to_save`.
|
| 234 |
+
|
| 235 |
+
- vera_rank: Size of Vera Attention, default value is 256.
|
| 236 |
+
- vera_projection_prng_key: Whether to store the Vera mapping matrix, default is True.
|
| 237 |
+
- vera_dropout: Dropout value for Vera, default is `0.0`.
|
| 238 |
+
- vera_d_initial: Initial value of Vera's d matrix, default is `0.1`.
|
| 239 |
+
|
| 240 |
+
#### GaLore
|
| 241 |
+
|
| 242 |
+
- 🔥use_galore: Default value is False, whether to use GaLore.
|
| 243 |
+
- galore_target_modules: Default is None, if not provided, applies GaLore to attention and MLP.
|
| 244 |
+
- galore_rank: Default value is 128, GaLore rank value.
|
| 245 |
+
- galore_update_proj_gap: Default is 50, interval for updating decomposed matrices.
|
| 246 |
+
- galore_scale: Default is 1.0, matrix weight coefficient.
|
| 247 |
+
- galore_proj_type: Default is `std`, type of GaLore matrix decomposition.
|
| 248 |
+
- galore_optim_per_parameter: Default value is False, whether to set a separate optimizer for each Galore target parameter.
|
| 249 |
+
- galore_with_embedding: Default value is False, whether to apply GaLore to embedding.
|
| 250 |
+
- galore_quantization: Whether to use q-galore, default is `False`.
|
| 251 |
+
- galore_proj_quant: Whether to quantize the SVD decomposition matrix, default is `False`.
|
| 252 |
+
- galore_proj_bits: Number of bits for SVD quantization.
|
| 253 |
+
- galore_proj_group_size: Number of groups for SVD quantization.
|
| 254 |
+
- galore_cos_threshold: Cosine similarity threshold for updating projection matrices. Default value is 0.4.
|
| 255 |
+
- galore_gamma_proj: As the projection matrix becomes more similar over time, this parameter is the coefficient for extending the update interval. Default value is 2.
|
| 256 |
+
- galore_queue_size: Length of the queue for calculating projection matrix similarity, default is 5.
|
| 257 |
+
|
| 258 |
+
#### LISA
|
| 259 |
+
|
| 260 |
+
Note: LISA only supports full parameters, i.e., `--train_type full`.
|
| 261 |
+
|
| 262 |
+
- 🔥lisa_activated_layers: Default value is `0`, representing LISA is not used. Setting to a non-zero value activates that many layers, it is recommended to set to 2 or 8.
|
| 263 |
+
- lisa_step_interval: Default value is `20`, number of iter to switch to layers that can be backpropagated.
|
| 264 |
+
|
| 265 |
+
#### UNSLOTH
|
| 266 |
+
|
| 267 |
+
🔥Unsloth has no new parameters; adjusting existing ones will suffice to support it:
|
| 268 |
+
|
| 269 |
+
```
|
| 270 |
+
--tuner_backend unsloth
|
| 271 |
+
--train_type full/lora
|
| 272 |
+
--quant_bits 4
|
| 273 |
+
```
|
| 274 |
+
|
| 275 |
+
#### LLAMAPRO
|
| 276 |
+
|
| 277 |
+
- 🔥llamapro_num_new_blocks: Default value is `4`, total number of new layers to insert.
|
| 278 |
+
- llamapro_num_groups: Default value is `None`, number of groups to insert new blocks. If `None`, it equals `llamapro_num_new_blocks`, meaning each new layer is inserted separately into the original model.
|
| 279 |
+
|
| 280 |
+
#### AdaLoRA
|
| 281 |
+
|
| 282 |
+
When the `train_type` parameter is set to `adalora`, the following parameters take effect. The `adalora` parameters such as `target_modules` inherit from the corresponding parameters of `lora`, but the `lora_dtype` parameter does not take effect.
|
| 283 |
+
|
| 284 |
+
- adalora_target_r: Default value is `8`, average rank of AdaLoRA.
|
| 285 |
+
- adalora_init_r: Default value is `12`, initial rank of AdaLoRA.
|
| 286 |
+
- adalora_tinit: Default value is `0`, initial warmup of AdaLoRA.
|
| 287 |
+
- adalora_tfinal: Default value is `0`, final warmup of AdaLoRA.
|
| 288 |
+
- adalora_deltaT: Default value is `1`, step interval of AdaLoRA.
|
| 289 |
+
- adalora_beta1: Default value is `0.85`, EMA parameter of AdaLoRA.
|
| 290 |
+
- adalora_beta2: Default value is `0.85`, EMA parameter of AdaLoRA.
|
| 291 |
+
- adalora_orth_reg_weight: Default value is `0.5`, regularization parameter for AdaLoRA.
|
| 292 |
+
|
| 293 |
+
#### ReFT
|
| 294 |
+
|
| 295 |
+
The following parameters are effective when `train_type` is set to `reft`.
|
| 296 |
+
|
| 297 |
+
> 1. ReFT cannot merge tuners.
|
| 298 |
+
> 2. ReFT is not compatible with gradient checkpointing.
|
| 299 |
+
> 3. If experiencing issues while using DeepSpeed, please uninstall DeepSpeed temporarily.
|
| 300 |
+
|
| 301 |
+
- 🔥reft_layers: Which layers ReFT is applied to, default is `None`, representing all layers. You can input a list of layer numbers, e.g., `reft_layers 1 2 3 4`.
|
| 302 |
+
- 🔥reft_rank: Rank of ReFT matrix, default is `4`.
|
| 303 |
+
- reft_intervention_type: Type of ReFT, supports 'NoreftIntervention', 'LoreftIntervention', 'ConsreftIntervention', 'LobireftIntervention', 'DireftIntervention', 'NodireftIntervention', default is `LoreftIntervention`.
|
| 304 |
+
- reft_args: Other supported parameters for ReFT Intervention, input in json-string format.
|
| 305 |
+
|
| 306 |
+
### LMDeploy Arguments
|
| 307 |
+
|
| 308 |
+
Parameter meanings can be found in the [lmdeploy documentation](https://lmdeploy.readthedocs.io/en/latest/api/pipeline.html#turbomindengineconfig).
|
| 309 |
+
|
| 310 |
+
- 🔥tp: tensor parallelism degree. Default is `1`.
|
| 311 |
+
- session_len: Default is `None`.
|
| 312 |
+
- cache_max_entry_count: Default is `0.8`.
|
| 313 |
+
- quant_policy: Default is `0`.
|
| 314 |
+
- vision_batch_size: Default is `1`.
|
| 315 |
+
|
| 316 |
+
### vLLM Arguments
|
| 317 |
+
|
| 318 |
+
Parameter meanings can be found in the [vllm documentation](https://docs.vllm.ai/en/latest/serving/engine_args.html).
|
| 319 |
+
|
| 320 |
+
- 🔥gpu_memory_utilization: Default value is `0.9`.
|
| 321 |
+
- 🔥tensor_parallel_size: Default is `1`.
|
| 322 |
+
- pipeline_parallel_size: Default is `1`.
|
| 323 |
+
- max_num_seqs: Default is `256`.
|
| 324 |
+
- 🔥max_model_len: Default is `None`.
|
| 325 |
+
- disable_custom_all_reduce: Default is `False`.
|
| 326 |
+
- enforce_eager: Determines whether vllm uses PyTorch eager mode or constructs a CUDA graph, default is `False`. Setting it to True can save memory but may affect efficiency.
|
| 327 |
+
- 🔥limit_mm_per_prompt: Controls the use of multiple media in vllm, default is `None`. For example, you can pass in `--limit_mm_per_prompt '{"image": 5, "video": 2}'`.
|
| 328 |
+
- vllm_max_lora_rank: Default is `16`. This is the parameter supported by vllm for lora.
|
| 329 |
+
- - vllm_quantization: vllm is able to quantize model with this argument,supported values can be found [here](https://docs.vllm.ai/en/latest/serving/engine_args.html).
|
| 330 |
+
- enable_prefix_caching: Enable the automatic prefix caching of vllm to save processing time for querying repeated prefixes. The default is `False`.
|
| 331 |
+
|
| 332 |
+
### Merge Arguments
|
| 333 |
+
|
| 334 |
+
- 🔥merge_lora: Indicates whether to merge lora; this parameter supports lora, llamapro, and longlora, default is `False`. Example parameters [here](https://github.com/modelscope/ms-swift/blob/main/examples/export/merge_lora.sh).
|
| 335 |
+
- safe_serialization: Whether to store safetensors, default is True.
|
| 336 |
+
- max_shard_size: Maximum size of a single storage file, default is '5GB'.
|
| 337 |
+
|
| 338 |
+
## Integration Arguments
|
| 339 |
+
|
| 340 |
+
### Training Arguments
|
| 341 |
+
|
| 342 |
+
Training arguments include the [base arguments](#base-arguments), [Seq2SeqTrainer arguments](#Seq2SeqTrainer-arguments), [tuner arguments](#tuner-arguments), and also include the following parts:
|
| 343 |
+
|
| 344 |
+
- add_version: Add directory to output_dir with `'<version>-<timestamp>'` to prevent weight overwrite, default is True.
|
| 345 |
+
- resume_only_model: Defaults to False. If set to True in conjunction with `resume_from_checkpoint`, only the model weights are resumed.
|
| 346 |
+
- check_model: Check local model files for corruption or modification and give a prompt, default is True. If in an offline environment, please set to False.
|
| 347 |
+
- 🔥create_checkpoint_symlink: Creates additional checkpoint symlinks to facilitate writing automated training scripts. The symlink paths for `best_model` and `last_model` are `f'{output_dir}/best'` and `f'{output_dir}/last'` respectively.
|
| 348 |
+
- loss_type: Type of loss. Defaults to None, which uses the model's built-in loss function.
|
| 349 |
+
- 🔥packing: Whether to use sequence packing to improve computational efficiency. The default value is False.
|
| 350 |
+
- Note: When using packing, please combine it with `--attn_impl flash_attn` and ensure "transformers>=4.44". For details, see [this PR](https://github.com/huggingface/transformers/pull/31629).
|
| 351 |
+
- 🔥lazy_tokenize: Whether to use lazy tokenization. If set to False, all dataset samples are tokenized before training (for multimodal models, this includes reading images from disk). This parameter defaults to False for LLM training, and True for MLLM training, to save memory.
|
| 352 |
+
- acc_strategy: Strategy for calculating accuracy during training and validation. Options are `seq`-level and `token`-level accuracy, with `token` as the default.
|
| 353 |
+
- max_new_tokens: Generation parameter override. The maximum number of tokens to generate when `predict_with_generate=True`, defaulting to 64.
|
| 354 |
+
- temperature: Generation parameter override. The temperature setting when `predict_with_generate=True`, defaulting to 0.
|
| 355 |
+
- optimizer: Custom optimizer name for the plugin, defaults to None.
|
| 356 |
+
- metric: Custom metric name for the plugin. Defaults to None, with the default set to 'acc' when `predict_with_generate=False` and 'nlg' when `predict_with_generate=True`.
|
| 357 |
+
- eval_use_evalscope: Whether to use evalscope for evaluation, this parameter needs to be set to enable evaluation, refer to [example](../Instruction/Evaluation.md#evaluation-during-training). Default is False.
|
| 358 |
+
- eval_datasets: Evaluation datasets, multiple datasets can be set, separated by spaces
|
| 359 |
+
- eval_datasets_args: Evaluation dataset parameters in JSON format, parameters for multiple datasets can be set
|
| 360 |
+
- eval_limit: Number of samples from the evaluation dataset
|
| 361 |
+
- eval_generation_config: Model inference configuration during evaluation, in JSON format, default is `{'max_tokens': 512}`
|
| 362 |
+
|
| 363 |
+
### RLHF Arguments
|
| 364 |
+
|
| 365 |
+
RLHF arguments inherit from the [training arguments](#training-arguments).
|
| 366 |
+
|
| 367 |
+
- 🔥rlhf_type: Type of human alignment algorithm, supporting `dpo`, `orpo`, `simpo`, `kto`, `cpo`, `rm`, `ppo` and `grpo`. Default is 'dpo'.
|
| 368 |
+
- ref_model: Required for full parameter training when using the dpo, kto, ppo or grpo algorithms. Default is None.
|
| 369 |
+
- ref_model_type: Same as model_type. Default is None.
|
| 370 |
+
- ref_model_revision: Same as model_revision. Default is None.
|
| 371 |
+
- 🔥beta: Coefficient for the KL regularization term. Default is `None`, meaning `simpo` algorithm defaults to `2.`, `grpo` algorithm defaults to `0.04`, and other algorithms default to `0.1`. For more details, refer to the [documentation](./RLHF.md).
|
| 372 |
+
- label_smoothing: Whether to use DPO smoothing, default value is `0`.
|
| 373 |
+
- 🔥rpo_alpha: The weight of sft_loss added to DPO, default is `1`. The final loss is `KL_loss + rpo_alpha * sft_loss`.
|
| 374 |
+
- cpo_alpha: Coefficient for nll loss in CPO/SimPO loss, default is `1.`.
|
| 375 |
+
- simpo_gamma: Reward margin term in the SimPO algorithm, with a paper-suggested setting of 0.5-1.5, default is `1.`.
|
| 376 |
+
- desirable_weight: Loss weight $\lambda_D$ for desirable response in the KTO algorithm, default is `1.`.
|
| 377 |
+
- undesirable_weight: Loss weight $\lambda_U$ for undesirable response in the KTO algorithm, default is `1.`.
|
| 378 |
+
- loss_scale: Override template arguments, default is 'last_round'.
|
| 379 |
+
- temperature: Default is 0.9; this parameter will be used in PPO and GRPO.
|
| 380 |
+
|
| 381 |
+
#### Reward Model Parameters
|
| 382 |
+
|
| 383 |
+
The reward model parameters will be used in PPO and GRPO.
|
| 384 |
+
|
| 385 |
+
- reward_model: Default is None.
|
| 386 |
+
- reward_adapters: Default is `[]`.
|
| 387 |
+
- reward_model_type: Default is None.
|
| 388 |
+
- reward_model_revision: Default is None.
|
| 389 |
+
|
| 390 |
+
#### PPO Arguments
|
| 391 |
+
|
| 392 |
+
The meanings of the following parameters can be referenced [here](https://huggingface.co/docs/trl/main/ppo_trainer):
|
| 393 |
+
|
| 394 |
+
- num_ppo_epochs: Defaults to 4
|
| 395 |
+
- whiten_rewards: Defaults to False
|
| 396 |
+
- kl_coef: Defaults to 0.05
|
| 397 |
+
- cliprange: Defaults to 0.2
|
| 398 |
+
- vf_coef: Defaults to 0.1
|
| 399 |
+
- cliprange_value: Defaults to 0.2
|
| 400 |
+
- gamma: Defaults to 1.0
|
| 401 |
+
- lam: Defaults to 0.95
|
| 402 |
+
- num_mini_batches: Defaults to 1
|
| 403 |
+
- local_rollout_forward_batch_size: Defaults to 64
|
| 404 |
+
- num_sample_generations: Defaults to 10
|
| 405 |
+
- response_length: Defaults to 512
|
| 406 |
+
- missing_eos_penalty: Defaults to None
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
#### GRPO Arguments
|
| 410 |
+
- per_device_train_batch_size: The training batch size per device. In GRPO, this refers to the batch size of completions during training.
|
| 411 |
+
- per_device_eval_batch_size: The evaluation batch size per device. In GRPO, this refers to the batch size of completions during evaluation.
|
| 412 |
+
- num_generations: The number of samples for each prompt, referred to as the G value in the paper, needs to be divisible by per_device_batch_size * - gradient_accumulation_steps * nproc_per_node, default is 8.
|
| 413 |
+
- max_completion_length: The maximum generation length in the GRPO algorithm, default is 512.
|
| 414 |
+
- ds3_gather_for_generation: This parameter applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation. The default is True.
|
| 415 |
+
- reward_funcs: Reward functions in the GRPO algorithm; options include `accuracy`,`format`,`cosine` and `repetition`, as seen in `swift/plugin/orm.py`. You can also customize your own reward functions in the plugin. Default is `[]`.
|
| 416 |
+
- reward_weights: Weights for each reward function. The number should be equal to the sum of the number of reward functions and reward models. If `None`, all rewards are weighted equally with weight `1.0`.
|
| 417 |
+
- Note: If `--reward_model` is included in GRPO training, it is added to the end of the reward functions.
|
| 418 |
+
- reward_model_plugin: The logic for the reward model, which defaults to ORM logic. For more information, please refer to [Customized Reward Models](./GRPO.md#customized-reward-models).
|
| 419 |
+
- dataset_shuffle: Whether to shuffle the dataset randomly. Default is True.
|
| 420 |
+
- loss_type: The type of loss normalization. Options are ['grpo', 'bnpo', 'dr_grpo'], default is 'grpo'. For details, see this [pr](https://github.com/huggingface/trl/pull/3256#discussion_r2033213348)
|
| 421 |
+
- log_completions: Whether to log the model-generated content during training, to be used in conjunction with `--report_to wandb`, default is False.
|
| 422 |
+
- Note: If `--report_to wandb` is not set, a `completions.jsonl` will be created in the checkpoint to store the generated content.
|
| 423 |
+
- use_vllm: Whether to use vLLM as the infer_backend for GRPO generation, default is False.
|
| 424 |
+
- num_infer_workers: The number of inference workers per node. This setting is only effective when using vLLM or lmdeploy.
|
| 425 |
+
- vllm_device: Configures the devices for deploying vLLM. You can set it to auto, which will allocate the last few GPUs based on the value of num_infer_workers. Alternatively, specify a number of devices equal to num_infer_workers. For example: --vllm_device cuda:1 cuda:2.
|
| 426 |
+
- vllm_gpu_memory_utilization: vLLM passthrough parameter, default is 0.9.
|
| 427 |
+
- vllm_max_model_len: vLLM passthrough parameter, default is None.
|
| 428 |
+
- vllm_max_num_seqs: vLLM passthrough parameter, default is 256.
|
| 429 |
+
- vllm_enforce_eager: vLLM passthrough parameter, default is False.
|
| 430 |
+
- vllm_limit_mm_per_prompt: vLLM passthrough parameter, default is None.
|
| 431 |
+
- vllm_enable_prefix_caching: vLLM passthrough parameter, default is True.
|
| 432 |
+
- vllm_server_host: The host address of the vLLM server. Default is None. This is used when connecting to an external vLLM server.
|
| 433 |
+
- vllm_server_port: The service port of the vLLM server. Default is 8000.
|
| 434 |
+
- vllm_server_timeout: The connection timeout for the vLLM server. Default is 120 seconds.
|
| 435 |
+
- top_k: Default is 50.
|
| 436 |
+
- top_p: Default is 0.9.
|
| 437 |
+
- repetition_penalty: Repetition penalty term. Default is 1.
|
| 438 |
+
- num_iterations: number of iterations per batch. Default is 1.
|
| 439 |
+
- epsilon: epsilon value for clipping. Default is 0.2.
|
| 440 |
+
- epsilon_high: Upper clip coefficient, default is None. When set, it forms a clipping range of [epsilon, epsilon_high] together with epsilon.
|
| 441 |
+
- async_generate: Use async rollout to improve train speed,default `false`.
|
| 442 |
+
- sleep_level: vllm specific,when both actor and rollout in the same GPU,you can make vllm sleep when model is training.
|
| 443 |
+
- move_model_batches: When moving model parameters to fast inference frameworks such as vLLM/LMDeploy, determines how many batches to divide the layers into. The default is `None`, which means the entire model is not split. Otherwise, the model is split into `move_model_batches + 1` (non-layer parameters) + `1` (multi-modal component parameters) batches.
|
| 444 |
+
- offload_optimizer: Whether to offload optimizer parameters during inference with vLLM/LMDeploy. The default is `False`.
|
| 445 |
+
- offload_model: Whether to offload the model itself during inference with vLLM/LMDeploy. The default is `False`.
|
| 446 |
+
- Note: If this parameter is set to True and the grad_norm remains zero during training, please install vllm==0.7.3.
|
| 447 |
+
- gc_collect_after_offload: Whether to perform garbage collection (both Python GC and GPU GC) after offloading. The default is `False`.
|
| 448 |
+
- multi_turn_func: The multi turn GRPO plugin name. Add your multi-turn implementation in plugin/multi_turn.py
|
| 449 |
+
- dynamic_sample: Exclude data within the group where the reward standard deviation is 0, and additionally sample new data. Default is False.
|
| 450 |
+
- max_resample_times: Under the dynamic_sample setting, limit the number of resampling attempts to a maximum of 3. Default is 3 times.
|
| 451 |
+
- overlong_filter: Skip overlong truncated samples, which will not be included in loss calculation. Default is False.
|
| 452 |
+
The hyperparameters for the reward function can be found in the [Built-in Reward Functions section](#built-in-reward-functions).
|
| 453 |
+
|
| 454 |
+
cosine reward function arguments
|
| 455 |
+
- cosine_min_len_value_wrong (default: 0.0): Reward value corresponding to the minimum length when the answer is incorrect. Default is 0.0
|
| 456 |
+
- cosine_max_len_value_wrong (default: -0.5): Reward value corresponding to the maximum length when the answer is incorrect. Default is -0.5
|
| 457 |
+
- cosine_min_len_value_correct (default: 1.0): Reward value corresponding to the minimum length when the answer is correct. Default is 1.0
|
| 458 |
+
- cosine_max_len_value_correct (default: 0.5): Reward value corresponding to the maximum length when the answer is correct. Default is 0.5
|
| 459 |
+
- cosine_max_len (default value equal to the model's maximum generation capacity): Maximum length limit for generated text. Default value equal to max_completion_length
|
| 460 |
+
|
| 461 |
+
repetition penalty function arguments
|
| 462 |
+
|
| 463 |
+
- repetition_n_grams (default: 3): Size of the n-gram used to detect repetition.
|
| 464 |
+
- repetition_max_penalty (default: -1.0): Maximum penalty value, which controls the intensity of the penalty.
|
| 465 |
+
|
| 466 |
+
Soft overlong reward parameters:
|
| 467 |
+
|
| 468 |
+
- soft_max_length: L_max in the paper, the maximum generation length of the model, default is equal to max_completion_length.
|
| 469 |
+
- soft_cache_length: L_cache in the paper, controls the length penalty interval, which is defined as [soft_max_length - soft_cache_length, soft_max_length].
|
| 470 |
+
|
| 471 |
+
#### SWANLAB
|
| 472 |
+
|
| 473 |
+
- **swanlab_token**: SwanLab's API key
|
| 474 |
+
- **swanlab_project**: SwanLab's project, which needs to be created in advance on the page: [https://swanlab.cn/space/~](https://swanlab.cn/space/~)
|
| 475 |
+
- **swanlab_workspace**: Defaults to `None`, will use the username associated with the API key
|
| 476 |
+
- **swanlab_exp_name**: Experiment name, can be left empty. If empty, the value of `--output_dir` will be used by default
|
| 477 |
+
- **swanlab_mode**: Optional values are `cloud` and `local`, representing cloud mode or local mode
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
### Inference Arguments
|
| 481 |
+
|
| 482 |
+
Inference arguments include the [base arguments](#base-arguments), [merge arguments](#merge-arguments), [vLLM arguments](#vllm-arguments), [LMDeploy arguments](#LMDeploy-arguments), and also contain the following:
|
| 483 |
+
|
| 484 |
+
- 🔥infer_backend: Inference acceleration backend, supporting three inference engines: 'pt', 'vllm', and 'lmdeploy'. The default is 'pt'.
|
| 485 |
+
- 🔥max_batch_size: Effective when infer_backend is set to 'pt'; used for batch inference, with a default value of 1.
|
| 486 |
+
- ddp_backend: Effective when infer_backend is set to 'pt'; used to specify the distributed backend for multi-GPU inference. The default is None, which means automatic selection. For an example of multi-GPU inference, you can refer [here](https://github.com/modelscope/ms-swift/tree/main/examples/infer/pt).
|
| 487 |
+
- 🔥result_path: Path to store inference results (jsonl). The default is None, meaning results are saved in the checkpoint directory (with args.json file) or './result' directory. The final storage path will be printed in the command line.
|
| 488 |
+
- metric: Evaluate the results of the inference, currently supporting 'acc' and 'rouge'. The default is None, meaning no evaluation is performed.
|
| 489 |
+
- val_dataset_sample: Number of samples from the inference dataset, default is None.
|
| 490 |
+
|
| 491 |
+
### Deployment Arguments
|
| 492 |
+
|
| 493 |
+
Deployment Arguments inherit from the [inference arguments](#inference-arguments).
|
| 494 |
+
|
| 495 |
+
- host: Service host, default is '0.0.0.0'.
|
| 496 |
+
- port: Port number, default is 8000.
|
| 497 |
+
- api_key: The API key required for access; the default is None.
|
| 498 |
+
- owned_by: Default is `swift`.
|
| 499 |
+
- 🔥served_model_name: Model name for serving, defaults to the model's suffix.
|
| 500 |
+
- verbose: Print detailed logs, with a default value of True.
|
| 501 |
+
- Note: In `swift app` or `swift eval`, the default is False.
|
| 502 |
+
- log_interval: Interval for printing tokens/s statistics, default is 20 seconds. If set to -1, it will not be printed.
|
| 503 |
+
- max_logprobs: Maximum number of logprobs returned to the client, with a default value of 20.
|
| 504 |
+
- use_async_engine: Whether to use the async engine under the vLLM backend. Default is True.
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
### Web-UI Arguments
|
| 508 |
+
- server_name: Host for the web UI, default is '0.0.0.0'.
|
| 509 |
+
- server_port: Port for the web UI, default is 7860.
|
| 510 |
+
- share: Default is False.
|
| 511 |
+
- lang: Language for the web UI, options are 'zh', 'en'. Default is 'zh'.
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
### App Arguments
|
| 515 |
+
App parameters inherit from [deployment arguments](#deployment-arguments) and [Web-UI Arguments](#web-ui-arguments).
|
| 516 |
+
|
| 517 |
+
- base_url: The base URL for model deployment, for example, `http://localhost:8000/v1`. The default value is `None`, which means using local deployment.
|
| 518 |
+
- studio_title: Title of the studio. Default is None, set to the model name.
|
| 519 |
+
- is_multimodal: Whether to launch the multimodal version of the app. Defaults to None, automatically determined based on the model; if it cannot be determined, set to False.
|
| 520 |
+
- lang: Overrides the Web-UI Arguments, default is 'en'.
|
| 521 |
+
|
| 522 |
+
### Evaluation Arguments
|
| 523 |
+
|
| 524 |
+
Evaluation Arguments inherit from the [deployment arguments](#deployment-arguments).
|
| 525 |
+
|
| 526 |
+
- 🔥eval_backend: Evaluation backend, defaults to 'Native'. It can also be specified as 'OpenCompass' or 'VLMEvalKit'.
|
| 527 |
+
- 🔥eval_dataset: Evaluation dataset, please refer to the [evaluation documentation](./评测.md).
|
| 528 |
+
- eval_limit: Number of samples per evaluation set, defaults to None.
|
| 529 |
+
- eval_output_dir: Directory to store evaluation results, defaults to 'eval_output'.
|
| 530 |
+
- temperature: Override generation parameters, defaults to 0.
|
| 531 |
+
- eval_num_proc: Maximum client concurrency during evaluation, defaults to 16.
|
| 532 |
+
- eval_url: Evaluation URL, e.g., `http://localhost:8000/v1`. Examples can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/eval/eval_url). Defaults to None for local deployment evaluation.
|
| 533 |
+
- eval_generation_config: Model inference configuration during evaluation, should be passed as a JSON string, e.g., `'{"max_new_tokens": 512}'`; defaults to None.
|
| 534 |
+
- extra_eval_args: Additional evaluation parameters, should be passed as a JSON string, defaults to empty. Only effective for Native evaluation. For more parameter descriptions, please refer to [here](https://evalscope.readthedocs.io/en/latest/get_started/parameters.html).
|
| 535 |
+
- local_dataset: Some evaluation sets, such as `CMB`, require additional data packages to be downloaded for utilization. Setting this parameter to `true` will automatically download the full data package, create a `data` folder in the current directory, and start the evaluation. The data package will only be downloaded once, and future evaluations will use the cache. This parameter defaults to `false`.
|
| 536 |
+
- Note: By default, evaluation uses the dataset under `~/.cache/opencompass`. After specifying this parameter, it will directly use the data folder in the current directory.
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
### Export Arguments
|
| 540 |
+
|
| 541 |
+
Export Arguments include the [basic arguments](#base-arguments) and [merge arguments](#merge-arguments), and also contain the following:
|
| 542 |
+
|
| 543 |
+
- 🔥output_dir: The path for storing exported results. The default value is None, and an appropriate suffix path will be automatically set.
|
| 544 |
+
- exist_ok: If output_dir exists, do not raise an exception and overwrite the contents. The default value is False.
|
| 545 |
+
- 🔥quant_method: Options are 'gptq', 'awq', or 'bnb', with the default being None. Examples can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/export/quantize).
|
| 546 |
+
- quant_n_samples: The number of samples for the validation set used by gptq/awq, with a default of 256.
|
| 547 |
+
- max_length: Max length for the calibration set, default value is 2048.
|
| 548 |
+
- quant_batch_size: Quantization batch size, default is 1.
|
| 549 |
+
- group_size: Group size for quantization, default is 128.
|
| 550 |
+
- to_ollama: Generate the Modelfile required by Ollama. Default is False.
|
| 551 |
+
- 🔥to_mcore: Convert weights from HF format to Megatron format. Default is False.
|
| 552 |
+
- to_hf: Convert weights from Megatron format to HF format. Default is False.
|
| 553 |
+
- mcore_model: Path to the mcore format model. Default is None.
|
| 554 |
+
- thread_count: The number of model slices when `--to_mcore true` is set. Defaults to None, and is automatically configured based on the model size, ensuring that the largest slice is less than 10GB.
|
| 555 |
+
- 🔥test_convert_precision: Test the precision error when converting weights between HF and Megatron formats. Default is False.
|
| 556 |
+
- 🔥push_to_hub: Whether to push to the hub, with the default being False. Examples can be found [here](https://github.com/modelscope/ms-swift/blob/main/examples/export/push_to_hub.sh).
|
| 557 |
+
- hub_model_id: Model ID for pushing, default is None.
|
| 558 |
+
- hub_private_repo: Whether it is a private repo, default is False.
|
| 559 |
+
- commit_message: Commit message, default is 'update files'.
|
| 560 |
+
|
| 561 |
+
### Sampling Parameters
|
| 562 |
+
|
| 563 |
+
- prm_model: The type of process reward model. It can be a model ID (triggered using `pt`) or a `prm` key defined in a plugin (for custom inference processes).
|
| 564 |
+
- orm_model: The type of outcome reward model, typically a wildcard or test case, usually defined in a plugin.
|
| 565 |
+
- sampler_type: The type of sampling. Currently supports `sample` (using `do_sample` method). Future support will include `mcts` and `dvts`.
|
| 566 |
+
- sampler_engine: Supports `pt`, `lmdeploy`, `vllm`, `no`. Defaults to `pt`. Specifies the inference engine for the sampling model.
|
| 567 |
+
- output_dir: The output directory. Defaults to `sample_output`.
|
| 568 |
+
- output_file: The name of the output file. Defaults to `None`, which uses a timestamp as the filename. When provided, only the filename should be passed without the directory, and only JSONL format is supported.
|
| 569 |
+
- override_exist_file: Whether to overwrite if `output_file` already exists.
|
| 570 |
+
- num_sampling_per_gpu_batch_size: The batch size for each sampling operation.
|
| 571 |
+
- num_sampling_per_gpu_batches: The total number of batches to sample.
|
| 572 |
+
- n_best_to_keep: The number of best sequences to return.
|
| 573 |
+
- data_range: The partition of the dataset being processed for this sampling operation. The format should be `2 3`, meaning the dataset is divided into 3 parts, and this instance is processing the 3rd partition (this implies that typically three `swift sample` processes are running in parallel).
|
| 574 |
+
- temperature: Defaults to `1.0`.
|
| 575 |
+
- prm_threshold: The PRM threshold. Results below this value will be filtered out. The default value is `0`.
|
| 576 |
+
- easy_query_threshold: For each query, if the ORM evaluation is correct for more than this proportion of all samples, the query will be discarded to prevent overly simple queries from appearing in the results. Defaults to `None`, meaning no filtering is applied.
|
| 577 |
+
- engine_kwargs: Additional parameters for the `sampler_engine`, passed as a JSON string, for example, `{"cache_max_entry_count":0.7}`.
|
| 578 |
+
- num_return_sequences: The number of original sequences returned by sampling. Defaults to `64`. This parameter is effective for `sample` sampling.
|
| 579 |
+
- cache_files: To avoid loading both `prm` and `generator` simultaneously and causing GPU memory OOM, sampling can be done in two steps. In the first step, set `prm` and `orm` to `None`, and all results will be output to a file. In the second run, set `sampler_engine` to `no` and pass `--cache_files` with the output file from the first sampling. This will use the results from the first run for `prm` and `orm` evaluation and output the final results.
|
| 580 |
+
- Note: When using `cache_files`, the `--dataset` still needs to be provided because the ID for `cache_files` is calculated using the MD5 of the original data. Both pieces of information need to be used together.
|
| 581 |
+
|
| 582 |
+
#### MCTS
|
| 583 |
+
- rollout_depth: The maximum depth during rollouts, default is `5`.
|
| 584 |
+
- rollout_start_depth: The depth at which rollouts begin; nodes below this depth will only undergo expand operations, default is `3`.
|
| 585 |
+
- max_iterations: The maximum number of iterations for MCTS, default is `100`.
|
| 586 |
+
- process_reward_rate: The proportion of process reward used in calculating value during selection, default is `0.0`, meaning PRM is not used.
|
| 587 |
+
- exploration_rate: A parameter in the UCT algorithm that balances exploration; a higher value gives more weight to nodes with fewer explorations, default is `0.5`.
|
| 588 |
+
- api_key: Required when using the client as an inference engine, default is `EMPTY`.
|
| 589 |
+
- base_url: Required when using the client as an inference engine, default is 'https://dashscope.aliyuncs.com/compatible-mode/v1'.
|
| 590 |
+
|
| 591 |
+
## Specific Model Arguments
|
| 592 |
+
|
| 593 |
+
Specific model arguments can be set using `--model_kwargs` or environment variables, for example: `--model_kwargs '{"fps_max_frames": 12}'` or `FPS_MAX_FRAMES=12`.
|
| 594 |
+
|
| 595 |
+
### qwen2_vl, qvq, qwen2_5_vl
|
| 596 |
+
The parameter meanings are the same as in the `qwen_vl_utils` or `qwen_omni_utils` library. You can refer to [here](https://github.com/QwenLM/Qwen2.5-VL/blob/main/qwen-vl-utils/src/qwen_vl_utils/vision_process.py#L24)
|
| 597 |
+
|
| 598 |
+
- IMAGE_FACTOR: Default is 28
|
| 599 |
+
- MIN_PIXELS: Default is `4 * 28 * 28`
|
| 600 |
+
- 🔥MAX_PIXELS: Default is `16384 * 28 * 28`, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/ocr.sh#L3)
|
| 601 |
+
- MAX_RATIO: Default is 200
|
| 602 |
+
- VIDEO_MIN_PIXELS: Default is `128 * 28 * 28`
|
| 603 |
+
- 🔥VIDEO_MAX_PIXELS: Default is `768 * 28 * 28`, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/video.sh#L7)
|
| 604 |
+
- VIDEO_TOTAL_PIXELS: Default is `24576 * 28 * 28`
|
| 605 |
+
- FRAME_FACTOR: Default is 2
|
| 606 |
+
- FPS: Default is 2.0
|
| 607 |
+
- FPS_MIN_FRAMES: Default is 4
|
| 608 |
+
- 🔥FPS_MAX_FRAMES: Default is 768, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/video.sh#L8)
|
| 609 |
+
|
| 610 |
+
### qwen2_audio
|
| 611 |
+
- SAMPLING_RATE: Default is 16000
|
| 612 |
+
|
| 613 |
+
### qwen2_5_omni
|
| 614 |
+
qwen2_5_omni not only includes the model-specific parameters of qwen2_5_vl and qwen2_audio, but also contains the following parameter:
|
| 615 |
+
- USE_AUDIO_IN_VIDEO: Default is False.
|
| 616 |
+
- 🔥ENABLE_AUDIO_OUTPUT: Default is True. If training with zero3, set it to False.
|
| 617 |
+
|
| 618 |
+
### internvl, internvl_phi3
|
| 619 |
+
For the meaning of the arguments, please refer to [here](https://modelscope.cn/models/OpenGVLab/Mini-InternVL-Chat-2B-V1-5)
|
| 620 |
+
- MAX_NUM: Default is 12
|
| 621 |
+
- INPUT_SIZE: Default is 448
|
| 622 |
+
|
| 623 |
+
### internvl2, internvl2_phi3, internvl2_5, internvl3
|
| 624 |
+
For the meaning of the arguments, please refer to [here](https://modelscope.cn/models/OpenGVLab/InternVL2_5-2B)
|
| 625 |
+
- MAX_NUM: Default is 12
|
| 626 |
+
- INPUT_SIZE: Default is 448
|
| 627 |
+
- VIDEO_MAX_NUM: Default is 1, which is the MAX_NUM for videos
|
| 628 |
+
- VIDEO_SEGMENTS: Default is 8
|
| 629 |
+
|
| 630 |
+
### minicpmv2_6, minicpmo2_6
|
| 631 |
+
- MAX_SLICE_NUMS: Default is 9, refer to [here](https://modelscope.cn/models/OpenBMB/MiniCPM-V-2_6/file/view/master?fileName=config.json&status=1)
|
| 632 |
+
- VIDEO_MAX_SLICE_NUMS: Default is 1, which is the MAX_SLICE_NUMS for videos, refer to [here](https://modelscope.cn/models/OpenBMB/MiniCPM-V-2_6)
|
| 633 |
+
- MAX_NUM_FRAMES: Default is 64, refer to [here](https://modelscope.cn/models/OpenBMB/MiniCPM-V-2_6)
|
| 634 |
+
|
| 635 |
+
### minicpmo2_6
|
| 636 |
+
- INIT_TTS: Default is False
|
| 637 |
+
- INIT_AUDIO: Default is False
|
| 638 |
+
|
| 639 |
+
### ovis1_6, ovis2
|
| 640 |
+
- MAX_PARTITION: Default is 9, refer to [here](https://github.com/AIDC-AI/Ovis/blob/d248e34d755a95d24315c40e2489750a869c5dbc/ovis/model/modeling_ovis.py#L312)
|
| 641 |
+
|
| 642 |
+
### mplug_owl3, mplug_owl3_241101
|
| 643 |
+
- MAX_NUM_FRAMES: Default is 16, refer to [here](https://modelscope.cn/models/iic/mPLUG-Owl3-7B-240728)
|
| 644 |
+
|
| 645 |
+
### xcomposer2_4khd
|
| 646 |
+
- HD_NUM: Default is 55, refer to [here](https://modelscope.cn/models/Shanghai_AI_Laboratory/internlm-xcomposer2-4khd-7b)
|
| 647 |
+
|
| 648 |
+
### xcomposer2_5
|
| 649 |
+
- HD_NUM: Default is 24 when the number of images is 1. Greater than 1, the default is 6. Refer to [here](https://modelscope.cn/models/AI-ModelScope/internlm-xcomposer2d5-7b/file/view/master?fileName=modeling_internlm_xcomposer2.py&status=1#L254)
|
| 650 |
+
|
| 651 |
+
### video_cogvlm2
|
| 652 |
+
- NUM_FRAMES: Default is 24, refer to [here](https://github.com/THUDM/CogVLM2/blob/main/video_demo/inference.py#L22)
|
| 653 |
+
|
| 654 |
+
### phi3_vision
|
| 655 |
+
- NUM_CROPS: Default is 4, refer to [here](https://modelscope.cn/models/LLM-Research/Phi-3.5-vision-instruct)
|
| 656 |
+
|
| 657 |
+
### llama3_1_omni
|
| 658 |
+
- N_MELS: Default is 128, refer to [here](https://github.com/ictnlp/LLaMA-Omni/blob/544d0ff3de8817fdcbc5192941a11cf4a72cbf2b/omni_speech/infer/infer.py#L57)
|
| 659 |
+
|
| 660 |
+
### video_llava
|
| 661 |
+
- NUM_FRAMES: Default is 16
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
## Other Environment Variables
|
| 665 |
+
|
| 666 |
+
- CUDA_VISIBLE_DEVICES: Controls which GPU to use. By default, all GPUs are used.
|
| 667 |
+
- ASCEND_RT_VISIBLE_DEVICES: Controls which NPU (effective for ASCEND cards) are used. By default, all NPUs are used.
|
| 668 |
+
- MODELSCOPE_CACHE: Controls the cache path.
|
| 669 |
+
- NPROC_PER_NODE: Pass-through for the `--nproc_per_node` parameter in torchrun. The default is 1. If the `NPROC_PER_NODE` or `NNODES` environment variables are set, torchrun is used to start training or inference.
|
| 670 |
+
- MASTER_PORT: Pass-through for the `--master_port` parameter in torchrun. The default is 29500.
|
| 671 |
+
- MASTER_ADDR: Pass-through for the `--master_addr` parameter in torchrun.
|
| 672 |
+
- NNODES: Pass-through for the `--nnodes` parameter in torchrun.
|
| 673 |
+
- NODE_RANK: Pass-through for the `--node_rank` parameter in torchrun.
|
| 674 |
+
- LOG_LEVEL: The log level, default is 'INFO'. You can set it to 'WARNING', 'ERROR', etc.
|
| 675 |
+
- SWIFT_DEBUG: During `engine.infer(...)`, if set to '1', the content of input_ids and generate_ids will be printed.
|
ms-swift/docs/source_en/Instruction/Evaluation.md
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation
|
| 2 |
+
|
| 3 |
+
SWIFT supports eval (evaluation) capabilities to provide standardized evaluation metrics for both raw models and trained models.
|
| 4 |
+
|
| 5 |
+
## Capability Introduction
|
| 6 |
+
|
| 7 |
+
SWIFT's eval capability utilizes the EvalScope evaluation framework from the Magic Tower community, which has been advanced in its encapsulation to support the evaluation needs of various models.
|
| 8 |
+
|
| 9 |
+
> Note: EvalScope supports many other complex capabilities, such as [model performance evaluation](https://evalscope.readthedocs.io/en/latest/user_guides/stress_test/quick_start.html), so please use the EvalScope framework directly.
|
| 10 |
+
|
| 11 |
+
Currently, we support the evaluation process of **standard evaluation datasets** as well as the evaluation process of **user-defined** evaluation datasets. The **standard evaluation datasets** are supported by three evaluation backends:
|
| 12 |
+
|
| 13 |
+
Below are the names of the supported datasets. For detailed information on the datasets, please refer to [all supported datasets](https://evalscope.readthedocs.io/en/latest/get_started/supported_dataset.html).
|
| 14 |
+
|
| 15 |
+
1. Native (default):
|
| 16 |
+
|
| 17 |
+
Primarily supports pure text evaluation, while **supporting** visualization of evaluation results.
|
| 18 |
+
```text
|
| 19 |
+
'arc', 'bbh', 'ceval', 'cmmlu', 'competition_math',
|
| 20 |
+
'general_qa', 'gpqa', 'gsm8k', 'hellaswag', 'humaneval',
|
| 21 |
+
'ifeval', 'iquiz', 'mmlu', 'mmlu_pro',
|
| 22 |
+
'race', 'trivia_qa', 'truthful_qa'
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
2. OpenCompass:
|
| 26 |
+
|
| 27 |
+
Primarily supports pure text evaluation, currently **does not support** visualization of evaluation results.
|
| 28 |
+
```text
|
| 29 |
+
'obqa', 'cmb', 'AX_b', 'siqa', 'nq', 'mbpp', 'winogrande', 'mmlu', 'BoolQ', 'cluewsc', 'ocnli', 'lambada',
|
| 30 |
+
'CMRC', 'ceval', 'csl', 'cmnli', 'bbh', 'ReCoRD', 'math', 'humaneval', 'eprstmt', 'WSC', 'storycloze',
|
| 31 |
+
'MultiRC', 'RTE', 'chid', 'gsm8k', 'AX_g', 'bustm', 'afqmc', 'piqa', 'lcsts', 'strategyqa', 'Xsum', 'agieval',
|
| 32 |
+
'ocnli_fc', 'C3', 'tnews', 'race', 'triviaqa', 'CB', 'WiC', 'hellaswag', 'summedits', 'GaokaoBench',
|
| 33 |
+
'ARC_e', 'COPA', 'ARC_c', 'DRCD'
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
3. VLMEvalKit:
|
| 37 |
+
|
| 38 |
+
Primarily supports multimodal evaluation and currently **does not support** visualization of evaluation results.
|
| 39 |
+
```text
|
| 40 |
+
'COCO_VAL', 'MME', 'HallusionBench', 'POPE', 'MMBench_DEV_EN', 'MMBench_TEST_EN', 'MMBench_DEV_CN', 'MMBench_TEST_CN',
|
| 41 |
+
'MMBench', 'MMBench_CN', 'MMBench_DEV_EN_V11', 'MMBench_TEST_EN_V11', 'MMBench_DEV_CN_V11',
|
| 42 |
+
'MMBench_TEST_CN_V11', 'MMBench_V11', 'MMBench_CN_V11', 'SEEDBench_IMG', 'SEEDBench2',
|
| 43 |
+
'SEEDBench2_Plus', 'ScienceQA_VAL', 'ScienceQA_TEST', 'MMT-Bench_ALL_MI', 'MMT-Bench_ALL',
|
| 44 |
+
'MMT-Bench_VAL_MI', 'MMT-Bench_VAL', 'AesBench_VAL', 'AesBench_TEST', 'CCBench', 'AI2D_TEST', 'MMStar',
|
| 45 |
+
'RealWorldQA', 'MLLMGuard_DS', 'BLINK', 'OCRVQA_TEST', 'OCRVQA_TESTCORE', 'TextVQA_VAL', 'DocVQA_VAL',
|
| 46 |
+
'DocVQA_TEST', 'InfoVQA_VAL', 'InfoVQA_TEST', 'ChartQA_TEST', 'MathVision', 'MathVision_MINI',
|
| 47 |
+
'MMMU_DEV_VAL', 'MMMU_TEST', 'OCRBench', 'MathVista_MINI', 'LLaVABench', 'MMVet', 'MTVQA_TEST',
|
| 48 |
+
'MMLongBench_DOC', 'VCR_EN_EASY_500', 'VCR_EN_EASY_100', 'VCR_EN_EASY_ALL', 'VCR_EN_HARD_500',
|
| 49 |
+
'VCR_EN_HARD_100', 'VCR_EN_HARD_ALL', 'VCR_ZH_EASY_500', 'VCR_ZH_EASY_100', 'VCR_ZH_EASY_ALL',
|
| 50 |
+
'VCR_ZH_HARD_500', 'VCR_ZH_HARD_100', 'VCR_ZH_HARD_ALL', 'MMDU', 'MMBench-Video', 'Video-MME'
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## Environment Preparation
|
| 54 |
+
|
| 55 |
+
```shell
|
| 56 |
+
pip install ms-swift[eval] -U
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Or install from source:
|
| 60 |
+
|
| 61 |
+
```shell
|
| 62 |
+
git clone https://github.com/modelscope/ms-swift.git
|
| 63 |
+
cd ms-swift
|
| 64 |
+
pip install -e '.[eval]'
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
## Evaluation
|
| 68 |
+
|
| 69 |
+
Supports four methods of evaluation: pure text evaluation, multimodal evaluation, URL evaluation, and custom dataset evaluation.
|
| 70 |
+
|
| 71 |
+
**Basic Example**
|
| 72 |
+
|
| 73 |
+
```shell
|
| 74 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 75 |
+
swift eval \
|
| 76 |
+
--model Qwen/Qwen2.5-0.5B-Instruct \
|
| 77 |
+
--eval_backend Native \
|
| 78 |
+
--infer_backend pt \
|
| 79 |
+
--eval_limit 10 \
|
| 80 |
+
--eval_dataset gsm8k
|
| 81 |
+
```
|
| 82 |
+
Where:
|
| 83 |
+
- model: Can specify a local model path or a model ID on modelscope
|
| 84 |
+
- eval_backend: Options are Native, OpenCompass, VLMEvalKit; default is Native
|
| 85 |
+
- infer_backend: Options are pt, vllm, lmdeploy; default is pt
|
| 86 |
+
- eval_limit: Sample size for each evaluation set; default is None, which means using all data; can be used for quick validation
|
| 87 |
+
- eval_dataset: Evaluation dataset(s); multiple datasets can be set, separated by spaces
|
| 88 |
+
|
| 89 |
+
For a specific list of evaluation parameters, please refer to [here](./Command-line-parameters.md#evaluation-arguments).
|
| 90 |
+
|
| 91 |
+
## Evaluation During Training
|
| 92 |
+
|
| 93 |
+
SWIFT supports using EvalScope to evaluate the current model during the training process, allowing for timely understanding of the model's training effectiveness.
|
| 94 |
+
|
| 95 |
+
**Basic Example**
|
| 96 |
+
|
| 97 |
+
```shell
|
| 98 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 99 |
+
swift sft \
|
| 100 |
+
--model "Qwen/Qwen2.5-0.5B-Instruct" \
|
| 101 |
+
--train_type "lora" \
|
| 102 |
+
--dataset "AI-ModelScope/alpaca-gpt4-data-zh#100" \
|
| 103 |
+
--torch_dtype "bfloat16" \
|
| 104 |
+
--num_train_epochs "1" \
|
| 105 |
+
--per_device_train_batch_size "1" \
|
| 106 |
+
--learning_rate "1e-4" \
|
| 107 |
+
--lora_rank "8" \
|
| 108 |
+
--lora_alpha "32" \
|
| 109 |
+
--target_modules "all-linear" \
|
| 110 |
+
--gradient_accumulation_steps "16" \
|
| 111 |
+
--save_steps "50" \
|
| 112 |
+
--save_total_limit "5" \
|
| 113 |
+
--logging_steps "5" \
|
| 114 |
+
--max_length "2048" \
|
| 115 |
+
--eval_strategy "steps" \
|
| 116 |
+
--eval_steps "5" \
|
| 117 |
+
--per_device_eval_batch_size "5" \
|
| 118 |
+
--eval_use_evalscope \
|
| 119 |
+
--eval_datasets "gsm8k" \
|
| 120 |
+
--eval_datasets_args '{"gsm8k": {"few_shot_num": 0}}' \
|
| 121 |
+
--eval_limit "10"
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Note that the launch command is `sft`, and the evaluation-related parameters include:
|
| 125 |
+
- eval_strategy: Evaluation strategy. Defaults to None, following the `save_strategy` policy
|
| 126 |
+
- eval_steps: Defaults to None. If an evaluation dataset exists, it follows the `save_steps` policy
|
| 127 |
+
- eval_use_evalscope: Whether to use evalscope for evaluation, this parameter needs to be set to enable evaluation
|
| 128 |
+
- eval_datasets: Evaluation datasets, multiple datasets can be set, separated by spaces
|
| 129 |
+
- eval_datasets_args: Evaluation dataset parameters in JSON format, parameters for multiple datasets can be set
|
| 130 |
+
- eval_limit: Number of samples from the evaluation dataset
|
| 131 |
+
- eval_generation_config: Model inference configuration during evaluation, in JSON format, default is `{'max_tokens': 512}`
|
| 132 |
+
|
| 133 |
+
More evaluation examples can be found in [examples](https://github.com/modelscope/ms-swift/tree/main/examples/eval).
|
| 134 |
+
|
| 135 |
+
## Custom Evaluation Datasets
|
| 136 |
+
|
| 137 |
+
This framework supports two predefined dataset formats: multiple-choice questions (MCQ) and question-and-answer (QA). The usage process is as follows:
|
| 138 |
+
|
| 139 |
+
*Note: When using a custom evaluation, the `eval_backend` parameter must be set to `Native`.*
|
| 140 |
+
|
| 141 |
+
### Multiple-Choice Question Format (MCQ)
|
| 142 |
+
This format is suitable for scenarios involving multiple-choice questions, and the evaluation metric is accuracy.
|
| 143 |
+
|
| 144 |
+
**Data Preparation**
|
| 145 |
+
|
| 146 |
+
Prepare a CSV file in the multiple-choice question format, structured as follows:
|
| 147 |
+
|
| 148 |
+
```text
|
| 149 |
+
mcq/
|
| 150 |
+
├── example_dev.csv # (Optional) The filename should follow the format `{subset_name}_dev.csv` for few-shot evaluation
|
| 151 |
+
└── example_val.csv # The filename should follow the format `{subset_name}_val.csv` for the actual evaluation data
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
The CSV file should follow this format:
|
| 155 |
+
|
| 156 |
+
```text
|
| 157 |
+
id,question,A,B,C,D,answer
|
| 158 |
+
1,Generally speaking, the amino acids that make up animal proteins are____,4 types,22 types,20 types,19 types,C
|
| 159 |
+
2,Among the substances present in the blood, which is not a metabolic end product?____,Urea,Uric acid,Pyruvate,Carbon dioxide,C
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
Where:
|
| 163 |
+
- `id` is an optional index
|
| 164 |
+
- `question` is the question
|
| 165 |
+
- `A`, `B`, `C`, `D`, etc. are the options, with a maximum of 10 options
|
| 166 |
+
- `answer` is the correct option
|
| 167 |
+
|
| 168 |
+
**Launching Evaluation**
|
| 169 |
+
|
| 170 |
+
Run the following command:
|
| 171 |
+
|
| 172 |
+
```bash
|
| 173 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 174 |
+
swift eval \
|
| 175 |
+
--model Qwen/Qwen2.5-0.5B-Instruct \
|
| 176 |
+
--eval_backend Native \
|
| 177 |
+
--infer_backend pt \
|
| 178 |
+
--eval_dataset general_mcq \
|
| 179 |
+
--dataset_args '{"general_mcq": {"local_path": "/path/to/mcq", "subset_list": ["example"]}}'
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
Where:
|
| 183 |
+
- `eval_dataset` should be set to `general_mcq`
|
| 184 |
+
- `dataset_args` should be set with:
|
| 185 |
+
- `local_path` as the path to the custom dataset folder
|
| 186 |
+
- `subset_list` as the name of the evaluation dataset, taken from the `*_dev.csv` mentioned above
|
| 187 |
+
|
| 188 |
+
**Running Results**
|
| 189 |
+
|
| 190 |
+
```text
|
| 191 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 192 |
+
| Model | Dataset | Metric | Subset | Num | Score | Cat.0 |
|
| 193 |
+
+=====================+=============+=================+==========+=======+=========+=========+
|
| 194 |
+
| Qwen2-0.5B-Instruct | general_mcq | AverageAccuracy | example | 12 | 0.5833 | default |
|
| 195 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
## Question-and-Answer Format (QA)
|
| 199 |
+
This format is suitable for scenarios involving question-and-answer, and the evaluation metrics are `ROUGE` and `BLEU`.
|
| 200 |
+
|
| 201 |
+
**Data Preparation**
|
| 202 |
+
|
| 203 |
+
Prepare a JSON Lines file in the question-and-answer format, containing one file in the following structure:
|
| 204 |
+
|
| 205 |
+
```text
|
| 206 |
+
qa/
|
| 207 |
+
└── example.jsonl
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
The JSON Lines file should follow this format:
|
| 211 |
+
|
| 212 |
+
```json
|
| 213 |
+
{"query": "What is the capital of China?", "response": "The capital of China is Beijing"}
|
| 214 |
+
{"query": "What is the highest mountain in the world?", "response": "It is Mount Everest"}
|
| 215 |
+
{"query": "Why can't penguins be seen in the Arctic?", "response": "Because most penguins live in Antarctica"}
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
**Launching Evaluation**
|
| 219 |
+
|
| 220 |
+
Run the following command:
|
| 221 |
+
|
| 222 |
+
```bash
|
| 223 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 224 |
+
swift eval \
|
| 225 |
+
--model Qwen/Qwen2.5-0.5B-Instruct \
|
| 226 |
+
--eval_backend Native \
|
| 227 |
+
--infer_backend pt \
|
| 228 |
+
--eval_dataset general_qa \
|
| 229 |
+
--dataset_args '{"general_qa": {"local_path": "/path/to/qa", "subset_list": ["example"]}}'
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
Where:
|
| 233 |
+
- `eval_dataset` should be set to `general_qa`
|
| 234 |
+
- `dataset_args` is a JSON string that needs to be set with:
|
| 235 |
+
- `local_path` as the path to the custom dataset folder
|
| 236 |
+
- `subset_list` as the name of the evaluation dataset, taken from the `*.jsonl` mentioned above
|
| 237 |
+
|
| 238 |
+
**Running Results**
|
| 239 |
+
|
| 240 |
+
```text
|
| 241 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 242 |
+
| Model | Dataset | Metric | Subset | Num | Score | Cat.0 |
|
| 243 |
+
+=====================+=============+=================+==========+=======+=========+=========+
|
| 244 |
+
| Qwen2-0.5B-Instruct | general_qa | bleu-1 | default | 12 | 0.2324 | default |
|
| 245 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 246 |
+
| Qwen2-0.5B-Instruct | general_qa | bleu-2 | default | 12 | 0.1451 | default |
|
| 247 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 248 |
+
| Qwen2-0.5B-Instruct | general_qa | bleu-3 | default | 12 | 0.0625 | default |
|
| 249 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 250 |
+
| Qwen2-0.5B-Instruct | general_qa | bleu-4 | default | 12 | 0.0556 | default |
|
| 251 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 252 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-1-f | default | 12 | 0.3441 | default |
|
| 253 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 254 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-1-p | default | 12 | 0.2393 | default |
|
| 255 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 256 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-1-r | default | 12 | 0.8889 | default |
|
| 257 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 258 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-2-f | default | 12 | 0.2062 | default |
|
| 259 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 260 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-2-p | default | 12 | 0.1453 | default |
|
| 261 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 262 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-2-r | default | 12 | 0.6167 | default |
|
| 263 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 264 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-l-f | default | 12 | 0.333 | default |
|
| 265 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 266 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-l-p | default | 12 | 0.2324 | default |
|
| 267 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 268 |
+
| Qwen2-0.5B-Instruct | general_qa | rouge-l-r | default | 12 | 0.8889 | default |
|
| 269 |
+
+---------------------+-------------+-----------------+----------+-------+---------+---------+
|
| 270 |
+
```
|
ms-swift/docs/source_en/Instruction/Frequently-asked-questions.md
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Frequently-asked-questions
|
| 2 |
+
|
| 3 |
+
Here are some common questions encountered during the use of Swift.
|
| 4 |
+
|
| 5 |
+
## Training
|
| 6 |
+
|
| 7 |
+
### Q1: What models and datasets are supported for fine-tuning in Swift?
|
| 8 |
+
Please refer to the documentation on [Supported Models and Datasets](https://swift.readthedocs.io/en/latest/Instruction/Supported-models-and-datasets.html).
|
| 9 |
+
|
| 10 |
+
### Q2: What data formats are supported when training with custom datasets?
|
| 11 |
+
For custom dataset formats, see the documentation on [Custom Dataset](https://swift.readthedocs.io/en/latest/Customization/Custom-dataset.html).
|
| 12 |
+
|
| 13 |
+
### Q3: What is the format for dataset_info.json for custom datasets, and how can I use it?
|
| 14 |
+
The dataset_info.json format can be found in the documentation on [Custom Dataset](https://swift.readthedocs.io/en/latest/Customization/Custom-dataset.html). Use the command line with `--custom_dataset_info xxx.json`, `--dataset <dataset_id_or_path>`.
|
| 15 |
+
|
| 16 |
+
### Q4: How can I train with a custom dataset using the interface?
|
| 17 |
+
Using a custom dataset through the interface is the same as using the command line. Refer to the documentation on [Custom Dataset](https://swift.readthedocs.io/en/latest/Customization/Custom-dataset.html).
|
| 18 |
+
|
| 19 |
+
### Q5: Can I write a line in the jsonl file like this? {"index": "00000", "query": "11111", "response": "22222", 'source':'qqq'}
|
| 20 |
+
You can have additional fields that won't be used.
|
| 21 |
+
|
| 22 |
+
### Q6: Where can I find the command line parameters?
|
| 23 |
+
Please refer to the documentation on [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 24 |
+
|
| 25 |
+
### Q7: What parameters need to be configured for training in an offline environment?
|
| 26 |
+
Use `--model local_path`, `--check_model false`. For more details, see the [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 27 |
+
|
| 28 |
+
### Q8: Where can I check model_type?
|
| 29 |
+
Check the [Supported Models and Datasets](https://swift.readthedocs.io/en/latest/Instruction/Supported-models-and-datasets.html).
|
| 30 |
+
|
| 31 |
+
### Q9: Can I directly convert the model to gguf format after training?
|
| 32 |
+
Currently, only export to ModelFile is supported. See the [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 33 |
+
|
| 34 |
+
### Q10: Does Swift support pre-training? I only see SFT.
|
| 35 |
+
Yes, it supports it. Use the command line `swift pt`, [pt example](https://github.com/modelscope/ms-swift/tree/main/examples/train/pretrain). The dataset format is detailed in [Custom Dataset](https://swift.readthedocs.io/en/latest/Customization/Custom-dataset.html).
|
| 36 |
+
|
| 37 |
+
### Q11: For models fine-tuned with LoRA, should I merge them into one model for resuming training, or can I specify the original model and LoRA block by path directly?
|
| 38 |
+
You do not need to merge. Use `--resume_from_checkpoint output/xxx/vx-xxx/checkpoint-xxx`. See the [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 39 |
+
|
| 40 |
+
### Q12: I would like to control the location where the original model weights downloaded from the internet are stored. How can I place the original model in a specific folder?
|
| 41 |
+
You can set the environment variable `MODELSCOPE_CACHE=your_path` to store the original model in the specified path. For SDK downloads, use `cache_dir="local_path"`. You can also use the `modelscope download` command-line tool or `git` to download it. For details, refer to the [Download Model](https://modelscope.cn/docs/Models/Download-Model). During training, set `--model` to the local path. For offline training, configure `--check_model false`. See the [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 42 |
+
|
| 43 |
+
### Q13: Has anyone encountered this issue with ms-swift?
|
| 44 |
+
```text
|
| 45 |
+
[rank6]: pydantic_core._pydantic_core.ValidationError: 1 validation error for DeepSpeedZeroConfig
|
| 46 |
+
[rank6]: stage3_prefetch_bucket_size
|
| 47 |
+
[rank6]: Input should be a valid integer, got a number with a fractional part [type=int_from_float,input_value=11560550.4,in put_type=float]
|
| 48 |
+
[rank6]: For further information visit https://errors.pydantic.dev/2.8/v/int_fro_float
|
| 49 |
+
```
|
| 50 |
+
Downgrade `deepspeed` to `0.14.*`.
|
| 51 |
+
|
| 52 |
+
### Q14: Is there a complete tutorial and command line for fine-tuning Qwen-2-VL?
|
| 53 |
+
Reference the [example](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal) for multimodal model training.
|
| 54 |
+
|
| 55 |
+
### Q15: Are there any tricks supported for fine-tuning multi-modal large models, similar to the LLM's neftune?
|
| 56 |
+
You can try variations of `lora` like `piassa/olora/dora`, or `fourierft`. Refer to the tricks in the `sft` parameters, as some may not apply to multi-modal.
|
| 57 |
+
|
| 58 |
+
### Q16: The accuracy from eval during training and the accuracy computed from re-inference with the saved checkpoint are not consistent.
|
| 59 |
+
The methods for calculating eval accuracy during training and inference are different. The default `acc_strategy` is `token`, and the selectable values are: `token`, `sentence`.
|
| 60 |
+
|
| 61 |
+
### Q17: Official Magic Mirror image and Swift environment.
|
| 62 |
+
You can start the container using `docker run`, for example: `docker run --gpus all -p 8000:8000 -it -d --name ms registry.cn-beijing.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.1.0-py310-torch2.3.0-tf2.16.1-1.16.0 /bin/bash`. After starting the container, pull the latest code to install Swift.
|
| 63 |
+
|
| 64 |
+
### Q18: Command line for multi-machine multi-card training.
|
| 65 |
+
For details, see the [Multi-node Example](https://github.com/modelscope/ms-swift/tree/main/examples/train/multi-node).
|
| 66 |
+
|
| 67 |
+
### Q19: How to choose a template?
|
| 68 |
+
See [issue](https://github.com/modelscope/ms-swift/issues/1813).
|
| 69 |
+
|
| 70 |
+
### Q20: How to use torchrun and swift sft for multi-card training?
|
| 71 |
+
`swift sft` uses `torchrun`.
|
| 72 |
+
|
| 73 |
+
### Q21: I have a question about my SFT dataset being too large; tokenizing takes a long time. Is there a solution?
|
| 74 |
+
Use `lazy_tokenize`. See [Command Line Parameters documentation](https://swift.readthedocs.io/zh-cn/latest/Instruction/%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0.html).
|
| 75 |
+
|
| 76 |
+
### Q22: When two datasets are simply appended together in the training set, does the model shuffle internally during training, or does it take data in order to train?
|
| 77 |
+
The trainer will shuffle randomly.
|
| 78 |
+
|
| 79 |
+
### Q23: If the model is on two cards and the data is not parallelized, deepspeed will throw an error. How to handle this?
|
| 80 |
+
`deepspeed` and `device_map` are incompatible; you can only choose one.
|
| 81 |
+
|
| 82 |
+
### Q24: Why does it need to download again when retraining offline, despite having already downloaded the dataset online?
|
| 83 |
+
The data file contains URLs, which do not support offline training.
|
| 84 |
+
|
| 85 |
+
### Q25: How to reduce GPU memory usage when training VLM models?
|
| 86 |
+
Set `--freeze_vit true`.
|
| 87 |
+
|
| 88 |
+
### Q26: Why are there fewer models supported in the WEB-UI interface than in the documentation?
|
| 89 |
+
Upgrade `ms-swift`.
|
| 90 |
+
|
| 91 |
+
### Q27: For models that do not have a suitable model_type, can I customize special_tokens and chat_template during SFT?
|
| 92 |
+
Yes, you can. Refer to the PR for model integration and the custom model dataset documentation.
|
| 93 |
+
|
| 94 |
+
### Q28: Can I use DPO to train Qwen2-VL in a Python script?
|
| 95 |
+
Yes, import `rlhf_main` and `RLHFArguments` from `swift.llm`.
|
| 96 |
+
|
| 97 |
+
### Q29: Can I pre-train with pure text before fine-tuning on a VQA dataset for MLLM?
|
| 98 |
+
Yes, you can mix training as well.
|
| 99 |
+
|
| 100 |
+
### Q30: When conducting DPO training based on the qwen2 SFT model on a V100 machine, the training shows NaN?
|
| 101 |
+
Use fp32 for training with the V100 machine.
|
| 102 |
+
|
| 103 |
+
### Q31: Does Swift support distillation?
|
| 104 |
+
Refer to this [example](https://github.com/modelscope/ms-swift/blob/main/examples/sampler/distill/distill.sh).
|
| 105 |
+
|
| 106 |
+
### Q32: Encountered the error `cannot import name 'ftp_head' from 'datasets.utils.file_utils'`. Has anyone faced this issue?
|
| 107 |
+
Try `pip install datasets==2.*`.
|
| 108 |
+
|
| 109 |
+
### Q33: The default maximum number of checkpoints saved after training is two. How can I increase this number?
|
| 110 |
+
Use `--save_total_limit`. See the [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 111 |
+
|
| 112 |
+
### Q34: In grounding tasks, does the universal data format support multiple instances for one category?
|
| 113 |
+
Currently, it supports one object corresponding to multiple bounding boxes. Refer to the documentation on [Custom Dataset](https://swift.readthedocs.io/en/latest/Customization/Custom-dataset.html).
|
| 114 |
+
|
| 115 |
+
### Q35: Why am I getting the error that numpy.object cannot be found?
|
| 116 |
+
Try using `numpy==1.26.3`.
|
| 117 |
+
|
| 118 |
+
### Q36: Does the Swift framework support sequence parallelism now?
|
| 119 |
+
Yes, it supports it. It implements this using `xtuner`.
|
| 120 |
+
|
| 121 |
+
### Q37: When fine-tuning qwen2-1.5B on a V100, I see `loss': 0.0, 'acc': 0.0, 'grad_norm': nan`. What is the issue?
|
| 122 |
+
Try using fp32.
|
| 123 |
+
|
| 124 |
+
### Q38: Is it possible to fully fine-tune GPTQ quantized models?
|
| 125 |
+
No, GPTQ model's int-type parameters cannot participate in gradients; they can only be updated with additional structures like LoRA.
|
| 126 |
+
|
| 127 |
+
### Q39: What parameters should I set for fine-tuning using QLoRA on glm4-chat?
|
| 128 |
+
Refer to the QLoRA [example](https://github.com/modelscope/ms-swift/tree/main/examples/train/qlora).
|
| 129 |
+
|
| 130 |
+
### Q40: I encounter the issue "AdamW' object has no attribute 'train" when training my dataset on qwen2-vl-7b.
|
| 131 |
+
Try `accelerate 0.34.0`.
|
| 132 |
+
|
| 133 |
+
### Q41: How do I expand my vocabulary within the Swift framework?
|
| 134 |
+
Swift currently does not support vocabulary expansion.
|
| 135 |
+
|
| 136 |
+
### Q42: Can I directly use models with the same name from Hugging Face?
|
| 137 |
+
Set the environment variable `USE_HF=1`.
|
| 138 |
+
|
| 139 |
+
### Q43: Can Qwen2-VL-2B conduct incremental pre-training? Is there guidance available?
|
| 140 |
+
Yes, it supports incremental pre-training. Just include all the content in the response.
|
| 141 |
+
|
| 142 |
+
### Q44: When training with videos, how can I control the frame sampling rate in the parameters? The `frame_rate` setting doesn't seem to work, and I'm using MiniCPMV.
|
| 143 |
+
Set the environment variable `MAX_NUM_FRAMES`.
|
| 144 |
+
|
| 145 |
+
### Q45: Can I save the inference results of the validation set during training in Swift?
|
| 146 |
+
After training, run `swift infer` to save the results.
|
| 147 |
+
|
| 148 |
+
### Q46: Why is the saved checkpoint larger than the original model file after full parameter DPO?
|
| 149 |
+
Using V100 for fine-tuning stores the data in fp32 format.
|
| 150 |
+
|
| 151 |
+
### Q47: Training speed slows down when using multi-machine training; using Swift framework for LLM training with deepspeed zero3 causes significant performance drop.
|
| 152 |
+
See the [issue](https://github.com/modelscope/ms-swift/issues/1825).
|
| 153 |
+
|
| 154 |
+
### Q48: Does Swift now support multi-stage pre-training for qwen2-vl? It looks like the official best practices only show SFT training with vit+llm together, not sure if separate fine-tuning is supported.
|
| 155 |
+
Refer to the [issue](https://github.com/modelscope/ms-swift/issues/2222).
|
| 156 |
+
|
| 157 |
+
### Q49: Does qwen2-vl support mixing pure text data?
|
| 158 |
+
It supports both mixed visual-text and pure text data.
|
| 159 |
+
|
| 160 |
+
### Q50: Can I plot loss curves for different datasets during fine-tuning?
|
| 161 |
+
This is not supported; datasets are trained in a mixed manner.
|
| 162 |
+
|
| 163 |
+
### Q51: After model training, the responses have a lot of repeated content.
|
| 164 |
+
Refer to the [Pre-training and Fine-tuning](https://swift.readthedocs.io/en/latest/Instruction/Pre-training-and-Fine-tuning.html). If you notice repetitions during training, try training for more epochs, cleaning the data, and conducting full parameter training, using RLHF to mitigate this issue.
|
| 165 |
+
|
| 166 |
+
### Q52: Does Swift currently support prompt tuning or prefix tuning?
|
| 167 |
+
No, it does not support these methods, as both methods suffer from serious forgetting issues and are not currently recommended.
|
| 168 |
+
|
| 169 |
+
### Q53: I encountered the following error when training with two A10s:
|
| 170 |
+
```text
|
| 171 |
+
[rank0]: torch.distributed.DistBackendError: NCCL error in:../torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp:1970, unhandled system error (run with NCCL_DEBUG=INFO for details),NCCL version 2.20.5
|
| 172 |
+
[rank0]:ncclSystemError: System call (e.g. socket,malloc) or external library call failed or device error.
|
| 173 |
+
```
|
| 174 |
+
Please check if shared memory is too small; NCCL requires shared memory.
|
| 175 |
+
|
| 176 |
+
### Q54: How to solve the issue of certain parameters not participating in backpropagation when freezing layers during DDP fine-tuning?
|
| 177 |
+
Set the parameter `--ddp_find_unused_parameters true`.
|
| 178 |
+
|
| 179 |
+
### Q55: Does Swift have a dataset quality inspection tool?
|
| 180 |
+
[data-juicer](https://github.com/modelscope/data-juicer).
|
| 181 |
+
|
| 182 |
+
### Q56: Where to start model parallelism on the web? I only found the option to check for data parallelism.
|
| 183 |
+
You can specify visible GPUs to enable model parallelism.
|
| 184 |
+
|
| 185 |
+
### Q57: How can I turn off automatic shuffling?
|
| 186 |
+
Currently, you can only modify the [transformers code](https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py).
|
| 187 |
+
|
| 188 |
+
### Q58: What is the parameter 'num_items_in_batch'? I can't find it.
|
| 189 |
+
Upgrade to `ms-swift==2.5.2` or downgrade to `transformers<4.46`.
|
| 190 |
+
|
| 191 |
+
### Q59: How can I set a fixed location for dataset downloads when using --dataset? I can't find this in command line parameters. How can I read from the download location next time?
|
| 192 |
+
`dataset_path` supports folders, typically for datasets downloaded via `git clone`. See [Custom Dataset Documentation](https://swift.readthedocs.io/en/latest/Customization/Custom-dataset.html#dataset-info-json).
|
| 193 |
+
|
| 194 |
+
### Q60: When using --streaming true, I get an error asking me to set max_steps when setting num_train_epochs. Can't I just set num_train_epochs?
|
| 195 |
+
Streaming dataset loading requires setting `max_steps`.
|
| 196 |
+
|
| 197 |
+
### Q61: Why is tools in "[]" format rather than directly using []? Could you explain why tools uses this "[]" format instead of direct [] notation?
|
| 198 |
+
This is because the underlying pyarrow in datasets has strict type control. For the same reason, the objects part in our official grounding dataset also uses str, otherwise pyarrow would report errors about inconsistent types across rows.
|
| 199 |
+
|
| 200 |
+
### Q62: Can't this parameter be used? check_dataset_strategy==discard
|
| 201 |
+
This parameter no longer exists in swift3.0, use the `strict` parameter instead.
|
| 202 |
+
|
| 203 |
+
### Q63: Getting this error when running sft command:
|
| 204 |
+
```text
|
| 205 |
+
RuntimeError: Expected to mark a variable ready only once.This error is caused by one of the following reasons: 1) Use of a module parameter outsid forward function. Please make sure model parameters are not shared across multiple concurrent forward-backward passes. or try to use _set_static_graph( ) as round if this module graph does not change during training loop.2) Reused parameters in multiple reentrant backward passes. For example, if you use multiple oint` functions to wrap the same part of your model, it would result in the same set of parameters been used by different reentrant backward passes multiple and hence marking a variable ready multiple times. DDP does not support such use cases in default. You can try to use _set_static_graph( ) as a workaround if dule graph does not change over iterations.
|
| 206 |
+
```
|
| 207 |
+
Add this parameter: `--gradient_checkpointing_kwargs '{"use_reentrant": false}'`.
|
| 208 |
+
|
| 209 |
+
### Q64: Have you encountered this issue? AttributeError:'TrainerState' object has no attribute 'last_model_checkpoint'
|
| 210 |
+
Dataset is too small, need to add more data. Error occurs when data quantity is less than one step.
|
| 211 |
+
|
| 212 |
+
### Q65: I see preprocess can be defined in CustomPreprocessor. Is this processed all at once before training starts, or loaded during training?
|
| 213 |
+
If `--streaming true` is set, it loads while training. By default, it processes everything before training.
|
| 214 |
+
|
| 215 |
+
### Q66: For full-parameter training of internvl2_5, why do vision_model and mlp1 appear in freeze parameters by default? Documentation shows freeze_parameters defaults to [], and command line settings for freeze vit, freeze aligner, freeze llm are all False. It prints trainable parameters: ['mlp1'] - unclear if only mlp1 is trainable or all parameters
|
| 216 |
+
First freeze parameters then active parameters. The three parameters `freeze vit/freeze aligner/freeze llm` adjust freeze parameters and trainable parameters. Since some models' `vit` contains `aligner`, aligner is separately added to trainable_parameters.
|
| 217 |
+
|
| 218 |
+
### Q67: Does LlamaPro in swift support multimodal adaptation?
|
| 219 |
+
Yes, it's supported.
|
| 220 |
+
|
| 221 |
+
### Q68: I noticed 2.x supports MAX_PIXELS. Is the --max_pixel parameter in 3.x documentation the same thing? What's the processing logic? Using 12000*9000 images with internvl still crashes in 2.x even with resacle_image
|
| 222 |
+
Environment variable parameters correspond to model parameters. `MAX_PIXELS` only supports qwen2vl, internvl has its own environment variables. See [Specific Model Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html#specific-model-argumen).
|
| 223 |
+
|
| 224 |
+
### Q69: Is there documentation for fine-tuning qwen base model to chat model? Any special configurations needed?
|
| 225 |
+
Use `swift sft`, no special configuration needed. See [example](https://github.com/modelscope/ms-swift/tree/main/examples/train/base_to_chat).
|
| 226 |
+
|
| 227 |
+
### Q70: Where can I find sequence parallel examples?
|
| 228 |
+
See this example: [sequence_parallel](https://github.com/modelscope/ms-swift/tree/main/examples/train/sequence_parallel).
|
| 229 |
+
|
| 230 |
+
### Q71: Can swift support training custom model structures?
|
| 231 |
+
Yes, just customize the `get_model_tokenizer_xxx` function to return `model` and `tokenizer`.
|
| 232 |
+
|
| 233 |
+
### Q72: Getting an error using longlora with "name_or_path": "/mnt/workspace/model/Qwen2.5-14B-Instruct". Is longlora only for llama series?
|
| 234 |
+
Yes, `longlora` only works with llama series.
|
| 235 |
+
|
| 236 |
+
### Q73: How to add custom special tokens in swift?
|
| 237 |
+
Add them in the `get_model_tokenizer` function.
|
| 238 |
+
|
| 239 |
+
### Q74: For --freeze_parameters_ratio parameter, if set to 0.7, does it mean only 30% of llm parameters are updated during training? Is it random 30%? What's the update mechanism?
|
| 240 |
+
Freezes from bottom to top.
|
| 241 |
+
|
| 242 |
+
### Q75: Why is the map process so slow? Is this normal?
|
| 243 |
+
```text
|
| 244 |
+
Map: 4%|██ | 9000/203823 [02:18<50:34, 64.19 examples/s]
|
| 245 |
+
```
|
| 246 |
+
Use `--dataset_num_proc` parameter to enable multiple processes.
|
| 247 |
+
|
| 248 |
+
### Q76: How can I delete and redownload a dataset? I think there might be an issue with the dataset.
|
| 249 |
+
Set the `--download_mode` parameter.
|
| 250 |
+
|
| 251 |
+
### Q77: How to solve this error: safetensors_rust.SafetensorError: Error while deserializing header: HeaderTooLarge?
|
| 252 |
+
The disk space is insufficient, and the model wasn't saved completely.
|
| 253 |
+
|
| 254 |
+
### Q78: Does swift3.0 not support get_default_template_type?
|
| 255 |
+
Please check `model.model_meta.template`, the information is available in `model.model_meta` and `model.model_info`.
|
| 256 |
+
|
| 257 |
+
### Q79: Does ModelScope Swift support hermes format agent fine-tuning? I see qwen2.5 uses vllm with native support for hermes format tool calling, why don't I see it in Swift?
|
| 258 |
+
Currently, `hermes` format is not supported. We mainly support `toolbench` and `react` formats, as `react` is more widely used. Swift's deploy currently supports parsing these two formats and provides `openai tool calling`.
|
| 259 |
+
|
| 260 |
+
### Q80: Is the default model training using left padding?
|
| 261 |
+
Training can use either left or right padding. The default is right padding, while `batch infer` uses left padding.
|
| 262 |
+
|
| 263 |
+
### Q81: Does it support grounding tasks now?
|
| 264 |
+
Yes, there's an [example](https://github.com/modelscope/ms-swift/blob/main/examples/train/multimodal/grounding.sh) under examples.
|
| 265 |
+
|
| 266 |
+
### Q82: Does ms-swift support contrastive learning for training llm_emb?
|
| 267 |
+
Yes, here's an [example](https://github.com/modelscope/ms-swift/blob/main/examples/train/embedding/train.sh).
|
| 268 |
+
|
| 269 |
+
### Q83: Is there a big difference in performance between manually coding fine-tuning and GRPO using peft and trl libraries compared to Swift official training with the same parameters?
|
| 270 |
+
The difference is minimal, with Swift additionally supporting multimodality.
|
| 271 |
+
|
| 272 |
+
### Q84: Does Swift currently not support audio modal input training for minicpmo2_6? It shows error: assert media_type in {'image', 'video'}
|
| 273 |
+
Audio is not currently supported.
|
| 274 |
+
|
| 275 |
+
### Q85: Can Swift fine-tune deepseek R1 671B?
|
| 276 |
+
Yes, the template is integrated, but the process is complicated as it requires converting fp8 to bf16 first.
|
| 277 |
+
|
| 278 |
+
### Q86: Isn't the latest Swift framework supposed to specify the model location using this command? This is the location of the model I've already downloaded, but I don't know why it still tries to download and fails with a git clone error
|
| 279 |
+
```shell
|
| 280 |
+
--model /mnt/workspace/.cache/modelscope/hub/deepseek-ai/deepseek-vl2/ \
|
| 281 |
+
```
|
| 282 |
+
Some models require cloning the repo and then specifying through `local_repo_path`.
|
| 283 |
+
|
| 284 |
+
### Q87: Does Swift now support multimodal GRPO?
|
| 285 |
+
Yes, it does.
|
| 286 |
+
|
| 287 |
+
### Q88: Can the GRPO reward function be customized?
|
| 288 |
+
Yes, refer to [examples/train/grpo/plugin](https://github.com/modelscope/ms-swift/tree/main/examples/train/grpo/plugin).
|
| 289 |
+
|
| 290 |
+
### Q89: Why do I get the error when using --torch_dtype float16 (card cannot use bf16): lib/python3.12/site-packages/torch/amp/grad_scaler.py", line 260, in unscale_grads raise ValueError("Attempting to unscale FP16 gradients.") ValueError: Attempting to unscale FP16 gradients.
|
| 291 |
+
FP16 does not support full-parameter training.
|
| 292 |
+
|
| 293 |
+
### Q90: I have a question. I trained a reward model using Swift (baseline is qwen2.5-7b), but when loading it in PPO or GRPO, it shows an error. The reward model was trained using LoRA.
|
| 294 |
+
```shell
|
| 295 |
+
--rlhf_type ppo \
|
| 296 |
+
--model Qwen/Qwen2.5-14B-Instruct \
|
| 297 |
+
--reward_model /mnt/workspace/output/rm/model --train_type lora \
|
| 298 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#20000' --torch_dtype float32 --num_train_epochs 1 \
|
| 299 |
+
--per_device_train_batch_size 1 --per_device_eval_batch_size 1 --learning_rate 1e-5 --lora_rank 8 --lora_alpha 32 \
|
| 300 |
+
--target_modules all-linear \
|
| 301 |
+
--gradient_accumulation_steps 16 --eval_steps 100 --save_steps 100 \
|
| 302 |
+
```
|
| 303 |
+
The LoRA-trained reward model needs to be merged.
|
| 304 |
+
|
| 305 |
+
### Q91: What version of transformers is needed to fine-tune deepseek_vl2? Official docs say <4.42, but it also shows errors with 4.42 and below. Does the peft version need to be lowered too?
|
| 306 |
+
Use `peft==0.11.*`.
|
| 307 |
+
|
| 308 |
+
### Q92: Generate train split is too slow (about 30+ datasets with around a million total data points). Previously Swift 2.x wasn't this slow. Lazy tokenize is already enabled.
|
| 309 |
+
Set `--dataset_num_proc 16`.
|
| 310 |
+
|
| 311 |
+
### Q93: How can I full-parameter fine-tune the visual encoder while using LoRA to fine-tune LLM when fine-tuning qwen2.5vl?
|
| 312 |
+
Refer to this [example](https://github.com/modelscope/ms-swift/tree/main/examples/train/multimodal/lora_llm_full_vit).
|
| 313 |
+
|
| 314 |
+
### Q94: How to use custom loss functions in Swift?
|
| 315 |
+
Add it in the plugin.
|
| 316 |
+
|
| 317 |
+
### Q95: What are the parameters for MoE? Can't find keywords in the parameter table. How to set expert numbers and expert routing parameters?
|
| 318 |
+
Use parameters directly from `config.json`.
|
| 319 |
+
|
| 320 |
+
### Q96: Using lmdeploy in grpo training reports missing functions. The load_weights function isn't found in lmdeployengine class.
|
| 321 |
+
Only supported under turbomind engine.
|
| 322 |
+
|
| 323 |
+
### Q97: Getting errors when fine-tuning Moonlight-16B-A3B-Instruct model. Seems ms-swift doesn't support fine-tuning this model?
|
| 324 |
+
Training is disabled in model files. Refer to deepseek_vl2's solution in the issues.
|
| 325 |
+
|
| 326 |
+
### Q98: How to solve this error: RuntimeError: "triu_tril_cuda_template" not implemented for 'BFloat16'?
|
| 327 |
+
```shell
|
| 328 |
+
CUDA_VISIBLE_DEVICES=01,2,3,4,5,6,7 \
|
| 329 |
+
swift sft \
|
| 330 |
+
--model Internlm3-8b \
|
| 331 |
+
--dataset train.json \
|
| 332 |
+
--train_type full \
|
| 333 |
+
--torch_dtype bfloat16 \
|
| 334 |
+
--num_train_epochs 5 \
|
| 335 |
+
--per_device_train_batch_size 1 \
|
| 336 |
+
--deepspeed zero3 \
|
| 337 |
+
--per_device_eval_batch_size 1 \
|
| 338 |
+
--learning_rate 1e-4 \
|
| 339 |
+
--gradient_accumulation_steps 16 \
|
| 340 |
+
--eval_steps 100 \
|
| 341 |
+
--save_steps 100 \
|
| 342 |
+
--save_total_limit 5 \
|
| 343 |
+
--logging_steps 5 \
|
| 344 |
+
--max_length 2048 \
|
| 345 |
+
--output_dir output \
|
| 346 |
+
--warmup_ratio 0.05 \
|
| 347 |
+
--dataloader_num_workers 4
|
| 348 |
+
```
|
| 349 |
+
Upgrade torch.
|
| 350 |
+
|
| 351 |
+
### Q99: Does it support custom rewards?
|
| 352 |
+
Yes, please check this [example](https://github.com/modelscope/ms-swift/tree/main/examples/train/grpo/plugin).
|
| 353 |
+
|
| 354 |
+
### Q100: Is it normal that both loss and grad_norm are 0 during GRPO training?
|
| 355 |
+
```text
|
| 356 |
+
{'loss': 0.0. 'grad norm':0.0, 'learning_rate':9e-08, 'memory(GiB)':88.1, 'train_speed(iter/s)':0.009252, 'completion_length': 150.00000763, 'response_clip ratio': 0.0, 'rewards/Format':1.0, 'reward
|
| 357 |
+
: 1.0, 'reward std':0.0, 'kl': 0.0, 'clip_ratio': 0.0, 'epoch': 0.0, 'qlobal step/max steps':'1/1052', 'percentage':'0.10% 'elapsed time': '36s 'remaining time': '10h 43m 54s'}
|
| 358 |
+
{'loss': 0.0,'grad_norm':0.0,'learning_rate': 1.8e-07,'memory(GiB)':94.15,'train_speed(iter/s)':0.014782,'completion_length': 133.25000763,'response_clip_ratio': 0.0,'rewards/Format': 1.0, 'rewa rd': 1.0,'reward_std': 0.0, 'kl': 0.0,'clip_ratio': 0.0,'epoch': 0.0, 'global_step/max_steps': '2/1052','percentage': '0.19%', 'elapsed_time': '1m 3s', 'remaining_time': '9h 19m 49s'}
|
| 359 |
+
{'loss': 0.0, 'qrad norm': 0.0, 'learning rate': 2.7e-07,'memory(GiB)': 94.15,'train_speed(iter/s)': 0.018695,'completion_length': 123.08333969,,'response_clip_ratio': 0.0,'rewards/Format': 1.0, 'rewa rd': 1.0, 'reward_ std': 0.0,'kl': 0.0,'clip_ratio': 0.0, 'epoch': 0.0, 'global_step/max_steps': '3/1052','percentage': '0.29%,'elapsed_time': '1m 29s','remaining_time': '8h 39m 34s'}
|
| 360 |
+
```
|
| 361 |
+
Training with loss close to 0 is normal, refer to this [issue](https://github.com/huggingface/open-r1/issues/239#issuecomment-2646297851).
|
| 362 |
+
|
| 363 |
+
### Q101: Where can I pass in accuracy_orm for GRPO's built-in reward function?
|
| 364 |
+
Currently it requires modifying the code directly.
|
| 365 |
+
|
| 366 |
+
### Q102: I notice the reward function has a solution parameter, does it need to be passed from the dataset? Does my dataset must have a solution field?
|
| 367 |
+
Yes, it's necessary for math problems to calculate accuracy.
|
| 368 |
+
|
| 369 |
+
### Q103: Why is there no token_acc during training?
|
| 370 |
+
Some models have mismatched `logits` and `labels` counts, so token accuracy isn't calculated.
|
| 371 |
+
|
| 372 |
+
### Q104: When fine-tuning Ovis2, LoRA parameters don't seem to work? Memory usage doesn't change with or without --train_type lora.
|
| 373 |
+
Limit `--max_length`, this model is special and needs padding to max_length.
|
| 374 |
+
|
| 375 |
+
### Q105: Getting ValueError when running classification task with Qwen2.5: The model did not return a loss from the inputs, only the following keys: logits. For reference, the inputs it received are input_ids,attention_mask.
|
| 376 |
+
dataset format: {"messages": [{"role": "user", "content": "xxxxx"}, {"label": 1}]}
|
| 377 |
+
Put `label` at the same level as `messages`, not inside it.
|
| 378 |
+
|
| 379 |
+
### Q106: Does anyone know what's wrong with this? The training method is VERA
|
| 380 |
+
```text
|
| 381 |
+
KeyError("The 'metric_for_best_model' training argument is set to 'eval_loss', which is not found in the evaluati on metrics. The available evaluation metrics are:['eval_runtime', 'eval_samples_per_second', 'eval_steps_per_sec ond', 'epoch', 'global_step/max_steps', 'percentage', 'elapsed_time', 'remaining_time']. consider changing the 'metric_for_best_model' via the TrainingArguments.")
|
| 382 |
+
Train: 45%| 100/220[09:47<11:44,5.87s/it]
|
| 383 |
+
```
|
| 384 |
+
```shell
|
| 385 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
|
| 386 |
+
swift sft \
|
| 387 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 388 |
+
--dataset '/mnt/workspace/data.json' \
|
| 389 |
+
--train_type vera \
|
| 390 |
+
--torch_dtype bfloat16 \
|
| 391 |
+
--num_train_epochs 4 \
|
| 392 |
+
--per_device_train_batch_size 1 \
|
| 393 |
+
--learning_rate 1e-4 \
|
| 394 |
+
--gradient_accumulation_steps 16 \
|
| 395 |
+
--eval_steps 100 \
|
| 396 |
+
--save_steps 100 \
|
| 397 |
+
--save_total_limit 5 \
|
| 398 |
+
--logging_steps 5 \
|
| 399 |
+
--max_length 4096 \
|
| 400 |
+
--warmup_ratio 0.05 \
|
| 401 |
+
--output_dir output/Qwen2.5-7B-vera \
|
| 402 |
+
```
|
| 403 |
+
Add `--label_names labels` parameter.
|
| 404 |
+
|
| 405 |
+
### Q107: How to exit VllmEngine? I want to release GPU memory after inference rather than keeping it occupied.
|
| 406 |
+
Use sleep mode: `engine.sleep(level=1)/engine.wake_up()` with `enable_sleep_mode=True` during initialization.
|
| 407 |
+
|
| 408 |
+
### Q108: Does trainer_sampler_random have no effect in streaming mode?
|
| 409 |
+
Streaming is not random.
|
| 410 |
+
|
| 411 |
+
### Q109: Can trust_remote_code be set when using VLLM for GRPO training?
|
| 412 |
+
It's true by default.
|
| 413 |
+
|
| 414 |
+
### Q110: For large dataset pretraining using streaming and packing, is there a way to calculate total steps based on epochs, batch size etc when setting max_steps?
|
| 415 |
+
Training will end based on whichever is smaller between `epochs` and `max_steps`.
|
| 416 |
+
|
| 417 |
+
### Q111: Unsloth training error: "assert(type(target modules) in (list,tuple,))" when using --target_modules all-linear
|
| 418 |
+
Don't use `all-linear`, specify concrete module list like `--target_modules q k v`.
|
| 419 |
+
|
| 420 |
+
### Q112: Does Swift support multi-label classification now?
|
| 421 |
+
Yes. Check custom dataset docs for format and search for `problem_type` in command line parameter docs.
|
| 422 |
+
|
| 423 |
+
### Q113: How does flash_attn handle packing - separately or merged?
|
| 424 |
+
Flash attention is required to avoid errors, otherwise attention_mask will have issues.
|
| 425 |
+
|
| 426 |
+
## Inference
|
| 427 |
+
|
| 428 |
+
### Q1: Is there documentation for Swift inference?
|
| 429 |
+
Swift supports inference via Python scripts, command line, and UI interface. See the [Inference and Deployment](https://swift.readthedocs.io/en/latest/Instruction/Inference-and-deployment.html).
|
| 430 |
+
|
| 431 |
+
### Q2: How to use the trained model for inference with a dataset?
|
| 432 |
+
Use the parameters `--load_data_args true` or `--val_dataset <your-val-dataset>`. Refer to the [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 433 |
+
|
| 434 |
+
### Q3: Can I specify a locally saved model during Swift inference?
|
| 435 |
+
Set `--model` to the local path. See [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 436 |
+
|
| 437 |
+
### Q4: How do I infer on a dataset without labels? I see that the dataset format in the documentation is all for the training set.
|
| 438 |
+
Configure the parameter `--val_dataset <your-val-dataset>`.
|
| 439 |
+
|
| 440 |
+
### Q5: How to resolve the error `ValueError: Input length of input_ids is 35, but max_length is set to 20`?
|
| 441 |
+
```text
|
| 442 |
+
raise ValueError(
|
| 443 |
+
ValueError: Input length of input_ids is 35, but `max_length` is set to 20. This can lead to unexpected behavior. You should consider increasing `max_length` or, better yet, setting `max_new_tokens`.
|
| 444 |
+
```
|
| 445 |
+
Set `model.generation_config.max_new_tokens`.
|
| 446 |
+
|
| 447 |
+
### Q6: qwen2-vl inference (training) runs out of memory
|
| 448 |
+
Set the command line parameter `--max_pixels xxx`, environment variable `MAX_PIXELS=xxx`, or specific model parameter `--model_kwargs '{"max_pixels": xxx}'`. Note that the environment variable only takes effect for the corresponding models in the documentation. For more details, please refer to the documentation [Specific Model Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html#specific-model-arguments).
|
| 449 |
+
|
| 450 |
+
### Q7: On a V100 GPU, in a Python virtual environment, following the environment setup instructions from https://swift2x.readthedocs.io/zh-cn/latest/Multi-Modal/qwen2-vl%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5.html, when testing the inference command: `CUDA_VISIBLE_DEVICES=0,1,2,3 swift infer --model_type qwen2-vl-7b-instruct`, an error occurs: `RuntimeError: probability tensor contains either 'inf', 'nan' or element < 0`.
|
| 451 |
+
Try inference on A10 or 3090 machines.
|
| 452 |
+
|
| 453 |
+
### Q8: After running the prediction command, where are the results saved? CUDA_VISIBLE_DEVICES=0 swift infer --ckpt_dir output/glm4v-9b-chat/vx-xxx/checkpoint-xxx-merged --load_data_args true
|
| 454 |
+
Results will be printed in the log.
|
| 455 |
+
|
| 456 |
+
### Q9: For the latest version of swift, can the infer command output probability values through the logprobs parameter?
|
| 457 |
+
Yes, logprobs can be output. For command line inference, set `--logprobs true`. For Python script inference, set `request_config = RequestConfig(..., logprobs=True, top_logprobs=2)`. Please refer to [test_logprobs.py](https://github.com/modelscope/ms-swift/blob/main/tests/infer/test_logprobs.py).
|
| 458 |
+
|
| 459 |
+
### Q10: In the latest version of Swift, while loading the qwen2-32b-instruct-awq quantized model, I was advised to add merge-lora true. After doing this, it throws an error. When I omit it, inference works but slowly.
|
| 460 |
+
Models trained with QLoRA do not support merge-lora; it is recommended to merge-lora after fine-tuning and then quantize.
|
| 461 |
+
|
| 462 |
+
### Q11: Getting the error `assert factor in rope_scaling` with vllm?
|
| 463 |
+
For more details, see qwen2-vl [issue#96](https://github.com/QwenLM/Qwen2-VL/issues/96).
|
| 464 |
+
|
| 465 |
+
### Q12: Does vllm require the models to be merged before calling them during inference?
|
| 466 |
+
Models do not have to be merged. See the documentation on [Command Line Parameters](https://swift.readthedocs.io/en/latest/Instruction/Command-line-parameters.html).
|
| 467 |
+
|
| 468 |
+
Q13: How to use CPU when performing inference with Python scripts?
|
| 469 |
+
Set the environment variable: `os.environ['CUDA_VISIBLE_DEVICES'] = '-1'`.
|
| 470 |
+
|
| 471 |
+
### Q14: Has anyone encountered the error `RuntimeError: "triu_tril_cuda_template" not implemented for'BFloat16'`?
|
| 472 |
+
Upgrade Torch, as the current version may not have implemented this operator.
|
| 473 |
+
|
| 474 |
+
### Q15: Does qwen2-audio support streaming inference?
|
| 475 |
+
Yes, see the [issue](https://github.com/modelscope/ms-swift/issues/1653).
|
| 476 |
+
|
| 477 |
+
### Q16: Where to set `do_sample` for multi-modal inference using inference client?
|
| 478 |
+
Set `temperature=0`.
|
| 479 |
+
|
| 480 |
+
### Q17: Does ms-swift support batch processing for large models?
|
| 481 |
+
Supported. See the [demo](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo.py).
|
| 482 |
+
|
| 483 |
+
### Q18: When quantizing models with ms-swift, there is an insufficient memory display. Can we reduce resource usage during quantization, even if it's slower?
|
| 484 |
+
Try setting `--device_map cpu`.
|
| 485 |
+
|
| 486 |
+
### Q19: Does Swift support quantization for multi-modal models?
|
| 487 |
+
Yes, it supports quantization.
|
| 488 |
+
|
| 489 |
+
### Q20: Encountering the following error while using GPTQ, what is the cause?
|
| 490 |
+
```text
|
| 491 |
+
if llm_config['architectures'][0] == 'LlamaForCausalLM':
|
| 492 |
+
KeyError: 'architectures'
|
| 493 |
+
```
|
| 494 |
+
Try using `transformers==4.44.*`.
|
| 495 |
+
|
| 496 |
+
### Q21: How can I specify where to save evaluation results during swift infer? I can't find where the results are saved.
|
| 497 |
+
Set `--result_path your_path`. See [InferArguments](https://github.com/modelscope/ms-swift/blob/main/swift/llm/argument/infer_args.py).
|
| 498 |
+
|
| 499 |
+
### Q22: I get an error while using AWQ quantized yi-vl-6b:
|
| 500 |
+
```text
|
| 501 |
+
TypeError: swift.llm.utils.model.get_model_tokenizer_with_flash_attn() got multiple values for keyword argument 'automodel_class'.
|
| 502 |
+
```
|
| 503 |
+
Please use GPTQ quantization.
|
| 504 |
+
|
| 505 |
+
### Q23: I would like to ask about using swift export to perform GPTQ INT4 quantization on the qwen2.5 72B model with a max model length of 32768, which is the default value. The calibration dataset provided has 128 samples, but an error occurred during quantization. The error log is: "factorization could not be completed because the input is not positive-definite (the leading minor of order 18145 is not positive-definite)." What is the cause?
|
| 506 |
+
This indicates a problem with the Hessian matrix being non-positive definite. Try using a different dataset.
|
| 507 |
+
|
| 508 |
+
### Q24: Can batch inference only be done through custom code? Can't it be done like SFT with script parameters?
|
| 509 |
+
Yes, it can be done using `swift infer --val_dataset xxx --max_batch_size 16 ...`.
|
| 510 |
+
|
| 511 |
+
### Q25: What's the default temperature value when using swift app for inference?
|
| 512 |
+
It's read from `generation_config.json` by default.
|
| 513 |
+
|
| 514 |
+
### Q26: Can export and quantization be done using multiple GPUs?
|
| 515 |
+
Model loading can use multiple GPUs, but quantization is single-GPU only.
|
| 516 |
+
|
| 517 |
+
### Q27: When using swift export with a custom template_type, does it permanently change the template_type? If we use swift export --template_type custom, does it change the model's template?
|
| 518 |
+
No, it won't be modified. Templates in swift are defined internally, not saved in jinja format.
|
| 519 |
+
|
| 520 |
+
### Q28: AWQ quantization for Qwen2VL gives error: TypeError: Qwen2VLForConditionalGeneration.init() got an unexpected keyword argument 'use_cache'
|
| 521 |
+
Use `gptq` quantization instead.
|
| 522 |
+
|
| 523 |
+
### Q29: For DDP inference, does max_batch_size in infer refer to batch size per GPU or total batch size?
|
| 524 |
+
It refers to batch size per GPU.
|
| 525 |
+
|
| 526 |
+
### Q30: Does swift.inference now support messages format input? It seems to only support query format currently. The answer contains part of the prompt, how should I modify the inference to complete the answer?
|
| 527 |
+
```text
|
| 528 |
+
{"messages": [{"role": "system", "content": "<system>"}, {"role": "user", "content": "<query1>"}, {"role": "assistant", "content": "answer1, "}]}
|
| 529 |
+
```
|
| 530 |
+
This is supported in swift3, refer to [examples/infer/demo_agent](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_agent.py).
|
| 531 |
+
|
| 532 |
+
### Q31: How can I make swift infer write results to result_path in real-time instead of writing everything at once at the end?
|
| 533 |
+
```shell
|
| 534 |
+
swift infer \
|
| 535 |
+
--ckpt_dir model_dir \
|
| 536 |
+
--streaming true \
|
| 537 |
+
--val_dataset dataset.jsonl \
|
| 538 |
+
--result_path result.jsonl
|
| 539 |
+
```
|
| 540 |
+
Use `--stream true`. This will write results one by one, but it's non-batch inference.
|
| 541 |
+
|
| 542 |
+
### Q32: When I trained and did inference in Swift it worked, but after merge_lora when using Ollama's API the effect disappeared.
|
| 543 |
+
Try loading with transformers, Swift's template is aligned with transformers.
|
| 544 |
+
|
| 545 |
+
### Q33: Which parameter should I set if I need to continue inference under a specific prefix during model inference?
|
| 546 |
+
The parameter `--response_prefix`.
|
| 547 |
+
|
| 548 |
+
### Q34: How do I fix this error that keeps appearing?
|
| 549 |
+
```text
|
| 550 |
+
File "/mnt/workspace/swift/swift/1lm/dataset/preprocessor/core. py", line 69, in _check_messages raise
|
| 551 |
+
ValueError(f'assistant_message; {assistant_message}')
|
| 552 |
+
ValueError: assistant_message: {'role' :'assistant', 'content': ''}
|
| 553 |
+
```
|
| 554 |
+
```shell
|
| 555 |
+
CUDA_VISIBLE_DEVICES=0 NPROC_PER_NODE=1 MAX_PIXELS=1003520 swift sft --model Qwen/Qwen2.5-VL-7B-Instruct --train_type lora --dataset /mnt/workspace/data.json --deepspeed zero2 --max_length 16384
|
| 556 |
+
```
|
| 557 |
+
The assistant field in the dataset is empty. If this is for inference, delete this empty string because it will cause NaN during training and will be checked.
|
| 558 |
+
|
| 559 |
+
## Deployment
|
| 560 |
+
|
| 561 |
+
### Q1: How to deploy a trained model?
|
| 562 |
+
Use `swift deploy --adapters xxx`. Refer to the documentation on [Inference and Deployment](https://swift.readthedocs.io/en/latest/Instruction/Inference-and-deployment.html).
|
| 563 |
+
|
| 564 |
+
### Q2: How to use vllm for multi-card deployment?
|
| 565 |
+
For details, see the [example](https://github.com/modelscope/ms-swift/tree/main/examples/deploy).
|
| 566 |
+
|
| 567 |
+
### Q3: How can clients pass images during vllm deployment?
|
| 568 |
+
See [client examples](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/client/mllm) for details..
|
| 569 |
+
|
| 570 |
+
### Q4: I have a question about deploying qwen2-7b and using it with a client. When calling the OpenAI API, should I use `client.completions.create` instead of `client.chat.completions.create`, but when using `qwen2-7b-instruct-q5_k_m.gguf`, I can use `client.chat.completions.create`. Why is that?
|
| 571 |
+
The base model can use `client.chat.completions.create`, but this is a compatibility behavior.
|
| 572 |
+
|
| 573 |
+
### Q5: Q5: After launching the server with swift deploy using two cards, when I exit with Ctrl+C, there is always a Python process that continues to occupy the memory of one card. Is this a normal phenomenon?
|
| 574 |
+
You may need to kill it. This is an issue with vllm.
|
| 575 |
+
|
| 576 |
+
### Q6: Where to check if a model supports lmdeploy or vllm acceleration?
|
| 577 |
+
Vllm and lmdeploy have their own range of supported models. Please check their respective official documentation to determine availability.
|
| 578 |
+
|
| 579 |
+
### Q7: Why does Tongyi Qianwen 2.5-Math-7B-Instruct sometimes return garbled characters when using vllm deployment? Using vllm to deploy,fp16
|
| 580 |
+
Try using bf16.
|
| 581 |
+
|
| 582 |
+
### Q8: After starting the swift inference service, how can I set configurations like temperature interactively?
|
| 583 |
+
Inference only has preset configurations at startup, while deployment can set defaults initially and allow overriding them later on the client side.
|
| 584 |
+
|
| 585 |
+
### Q9: When deploying qwen2vl model locally, how can I input videos during inference? Can I use base64? How to call video with curl?
|
| 586 |
+
base64, see [mllm client example](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/client/mllm) for details.
|
| 587 |
+
|
| 588 |
+
### Q10: When deploying qwen2-vl, I encounter an error about the vllm version not being correct?
|
| 589 |
+
```text
|
| 590 |
+
Unrecognized keys in `rope_scaling`for 'rope_type'='default': {'mrope_section'}
|
| 591 |
+
```
|
| 592 |
+
Refer to the [issue](https://github.com/QwenLM/Qwen2-VL/issues/209).
|
| 593 |
+
|
| 594 |
+
### Q11: When using Swift deploy for inference, I want to output token probabilities. I added logprobs True, but it outputs null. What's the reason?
|
| 595 |
+
```shell
|
| 596 |
+
RAY_memory_monitor_refresh_ms=0 CUDA_VISIBLE_DEVICES=1 nohup swift deploy --ckpt_dir /mnt/workspace/checkpoint_600 --infer_backend vllm --logprobs True --load_data_args false --host 0.0.0.0 --port 8000 &
|
| 597 |
+
```
|
| 598 |
+
Parameters need to be passed from the client side, `request_config = RequestConfig(..., logprobs=True, top_logprobs=2)`.
|
| 599 |
+
|
| 600 |
+
### Q12: Can we set request timeout time for Swift3.0 deployment inference? What happens if the image URL is invalid?
|
| 601 |
+
You can set the `TIMEOUT` environment variable, which defaults to 300 seconds. Alternatively, you can pass parameters in `InferClient`.
|
| 602 |
+
|
| 603 |
+
### Q13: Why can't I get streaming generation with Swift deployed models? I've set stream to True on both server and client side, but it's still not streaming
|
| 604 |
+
It's controlled by the client side. Please check [examples/deploy/client](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/client).
|
| 605 |
+
|
| 606 |
+
### Q14: After deploying a multimodal model with Swift, is there an example of passing PIL.Image from the client?
|
| 607 |
+
Check this [client example](https://github.com/modelscope/ms-swift/blob/main/examples/deploy/client/mllm/openai_client.py).
|
| 608 |
+
|
| 609 |
+
### Q15: When deploying, which parameter should be set to output multiple results in a single response?
|
| 610 |
+
The parameter `n` in `RequestConfig`.
|
| 611 |
+
|
| 612 |
+
## Evaluation
|
| 613 |
+
|
| 614 |
+
### Q1: What evaluation datasets are supported by Swift?
|
| 615 |
+
Pure text evaluation:
|
| 616 |
+
```text
|
| 617 |
+
'obqa', 'cmb', 'AX_b', 'siqa', 'nq', 'mbpp', 'winogrande', 'mmlu', 'BoolQ', 'cluewsc', 'ocnli', 'lambada',
|
| 618 |
+
'CMRC', 'ceval', 'csl', 'cmnli', 'bbh', 'ReCoRD', 'math', 'humaneval', 'eprstmt', 'WSC', 'storycloze',
|
| 619 |
+
'MultiRC', 'RTE', 'chid', 'gsm8k', 'AX_g', 'bustm', 'afqmc', 'piqa', 'lcsts', 'strategyqa', 'Xsum', 'agieval',
|
| 620 |
+
'ocnli_fc', 'C3', 'tnews', 'race', 'triviaqa', 'CB', 'WiC', 'hellaswag', 'summedits', 'GaokaoBench',
|
| 621 |
+
'ARC_e', 'COPA', 'ARC_c', 'DRCD'
|
| 622 |
+
```
|
| 623 |
+
|
| 624 |
+
Multimodal evaluation:
|
| 625 |
+
```text
|
| 626 |
+
'COCO_VAL', 'MME', 'HallusionBench', 'POPE', 'MMBench_DEV_EN', 'MMBench_TEST_EN', 'MMBench_DEV_CN', 'MMBench_TEST_CN',
|
| 627 |
+
'MMBench', 'MMBench_CN', 'MMBench_DEV_EN_V11', 'MMBench_TEST_EN_V11', 'MMBench_DEV_CN_V11',
|
| 628 |
+
'MMBench_TEST_CN_V11', 'MMBench_V11', 'MMBench_CN_V11', 'SEEDBench_IMG', 'SEEDBench2',
|
| 629 |
+
'SEEDBench2_Plus', 'ScienceQA_VAL', 'ScienceQA_TEST', 'MMT-Bench_ALL_MI', 'MMT-Bench_ALL',
|
| 630 |
+
'MMT-Bench_VAL_MI', 'MMT-Bench_VAL', 'AesBench_VAL', 'AesBench_TEST', 'CCBench', 'AI2D_TEST', 'MMStar',
|
| 631 |
+
'RealWorldQA', 'MLLMGuard_DS', 'BLINK', 'OCRVQA_TEST', 'OCRVQA_TESTCORE', 'TextVQA_VAL', 'DocVQA_VAL',
|
| 632 |
+
'DocVQA_TEST', 'InfoVQA_VAL', 'InfoVQA_TEST', 'ChartQA_TEST', 'MathVision', 'MathVision_MINI',
|
| 633 |
+
'MMMU_DEV_VAL', 'MMMU_TEST', 'OCRBench', 'MathVista_MINI', 'LLaVABench', 'MMVet', 'MTVQA_TEST',
|
| 634 |
+
'MMLongBench_DOC', 'VCR_EN_EASY_500', 'VCR_EN_EASY_100', 'VCR_EN_EASY_ALL', 'VCR_EN_HARD_500',
|
| 635 |
+
'VCR_EN_HARD_100', 'VCR_EN_HARD_ALL', 'VCR_ZH_EASY_500', 'VCR_ZH_EASY_100', 'VCR_ZH_EASY_ALL',
|
| 636 |
+
'VCR_ZH_HARD_500', 'VCR_ZH_HARD_100', 'VCR_ZH_HARD_ALL', 'MMDU', 'MMBench-Video', 'Video-MME'
|
| 637 |
+
```
|
| 638 |
+
|
| 639 |
+
See the document [Evaluation](https://swift.readthedocs.io/en/latest/Instruction/Evaluation.html) for details.
|
| 640 |
+
|
| 641 |
+
### Q2: How to use a custom evaluation dataset?
|
| 642 |
+
Custom evaluation datasets, both plain text and multimodal, must match the data format (pattern) of an official dataset. See the document [Evaluation](https://swift.readthedocs.io/en/latest/Instruction/Evaluation.html) for details.
|
| 643 |
+
|
| 644 |
+
### Q3: Error with mmengine in python3.11 environment during evaluation
|
| 645 |
+
Try using the Python 3.10 environment. Or first install all dependencies:
|
| 646 |
+
`pip3 install evalscope[all]`,
|
| 647 |
+
then apply the patch:
|
| 648 |
+
`pip3 install https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/package/evalscope-0.5.3.post1-py3-none-any.whl`.
|
| 649 |
+
|
| 650 |
+
### Q4: After manually downloading the official evaluation dataset, can Swift eval be configured for local path evaluation?
|
| 651 |
+
First, download the evaluation dataset [eval.zip](https://modelscope.cn/datasets/swift/evalscope_resource/files), extract it, and place its contents in the `~/.cache/modelscope/media_resources/evalscope/data` folder. Then execute the `swift eval` command to use the local data.
|
| 652 |
+
|
| 653 |
+
### Q5: Is there a bug with custom evaluation? I modified the standard example to English, but it doesn't work?
|
| 654 |
+
```shell
|
| 655 |
+
swift eval --model_type 'qwen2_5-1_5b-instruct' --eval_dataset no --custom_eval_config '/mnt/workspace/test_data/config_eval.json'
|
| 656 |
+
```
|
| 657 |
+
This relies on the nltk package, which needs to download a punkt_tab zip file. Some environments in China have unstable or failed downloads. The code has been modified to handle this issue; reference [issue](https://github.com/nltk/nltk/issues/3293).
|
| 658 |
+
|
| 659 |
+
### Q6: The model after eval fine-tuning keeps stopping at a fixed percentage, but the vllm service seems to be running normally. The larger the model, the sooner it disconnects.
|
| 660 |
+
Set the `TIMEOUT` environment variable to -1.
|
| 661 |
+
|
| 662 |
+
### Q7: Does evalscope support multi-model comparison?
|
| 663 |
+
See the [documentation](https://evalscope.readthedocs.io/en/latest/user_guides/arena.html) for details.
|
| 664 |
+
|
| 665 |
+
### Q8: Is there a custom evaluation for multimodal datasets?
|
| 666 |
+
Custom evaluation for multimodal datasets can be referenced in the [documentation](https://evalscope.readthedocs.io/en/latest/advanced_guides/custom_dataset/index.html).
|
| 667 |
+
|
| 668 |
+
### Q9: Does ms-swift have methods to test QPS, latency, and tokens/s?
|
| 669 |
+
You can try using evalscope's [Model Inference Stress Testing](https://evalscope.readthedocs.io/en/latest/user_guides/stress_test/index.html).
|
| 670 |
+
|
| 671 |
+
### Q10: Can I control the number of dataset entries during evaluation? It takes over an hour to evaluate an MMLU, which is too slow.
|
| 672 |
+
Use the configuration parameter `--eval_limit`. This `--eval_limit` controls the number of entries in each subset. For example, if MMLU has over 50 subsets, and each limit is set to 10 entries, then that would be over 500 entries in total.
|
| 673 |
+
|
| 674 |
+
### Q11: When evaluating, isn't it just having the model output an answer once and checking if it's correct? Is there a way to record or see the complete answer each time?
|
| 675 |
+
For multiple-choice evaluations like ceval, the evaluation is done by calculating the logits for each option, without outputting the actual answer content. If you want to see the answer content, you can deploy the model as a service with a specified API URL for evaluation, which will evaluate based on parsing the model's output. See the [documentation](https://evalscope.readthedocs.io/en/latest/get_started/basic_usage.html#model-api-service-evaluation) for details. Both methods can be made optional.
|
| 676 |
+
|
| 677 |
+
### Q12: I want to stress test my model using evalscope and would like to use a prompt.txt file format. What should the format of this file look like?
|
| 678 |
+
Configure line_by_line, see the [documentation](https://evalscope.readthedocs.io/en/latest/user_guides/stress_test/parameters.html#dataset-configuration) for details.
|
| 679 |
+
|
| 680 |
+
### Q13: How should I use the 'parallel' and 'number' parameters when conducting model inference performance testing using evalscope perf?
|
| 681 |
+
`number` is the total number of requests, while `parallel` is the number of concurrent requests.
|
| 682 |
+
|
| 683 |
+
### Q14: In swift eval, the model stops generating after 1024 tokens. How can I modify this? Setting --max_new_tokens 5000 doesn't seem to work.
|
| 684 |
+
This parameter hasn't been exposed in swift yet. You can use evalscope to run it, and configure max_tokens in the model according to the [documentation](https://evalscope.readthedocs.io/en/latest/user_guides/backend/vlmevalkit_backend.html#configure-model-evaluation-parameters).
|
| 685 |
+
|
| 686 |
+
### Q15: Does evalscope currently support benchmarks like AIME and MATH-500 for deepseek-r1?
|
| 687 |
+
Yes, it does. Here are the [best practices](https://evalscope.readthedocs.io/en/latest/best_practice/deepseek_r1_distill.html).
|
| 688 |
+
|
| 689 |
+
### Q16: I'm getting this error when using a local path for gpqa evaluation in evalscope: ValueError: BuildingConfig 'gpqa_extended' not found. Available: ['default']
|
| 690 |
+
Parameter configuration:
|
| 691 |
+
```shell
|
| 692 |
+
--datasets gpqa --dataset-args '{"gpqa": {"local_path": "/mnt/workspace/gpqa"} }'
|
| 693 |
+
```
|
| 694 |
+
If you want to use datasets locally, it's recommended to clone the repository from modelscope and then specify the path.
|
| 695 |
+
|
| 696 |
+
### Q17: When evaluating the arc dataset with evalscope, I get this error. What's the reason? I'm using the local data path method.
|
| 697 |
+
```text
|
| 698 |
+
KeyError: 'RequestId'
|
| 699 |
+
```
|
| 700 |
+
```shell
|
| 701 |
+
--datasets arc --dataset-args '{"arc": {"local_path": "/mnt/workspace/arc"}}'
|
| 702 |
+
```
|
| 703 |
+
According to the [documentation](https://evalscope.readthedocs.io/en/latest/get_started/basic_usage.html#using-local-datasets-and-models), the arc dataset needs to be downloaded using a Python script; directly cloning the repository won't work.
|
| 704 |
+
|
| 705 |
+
### Q18: How can I load downloaded datasets locally when using opencompass backend for evaluation?
|
| 706 |
+
The opencompass backend doesn't support setting `data_args`.
|
| 707 |
+
|
| 708 |
+
### Q19: Does swift eval with --eval_backend OpenCompass not support custom datasets?
|
| 709 |
+
```text
|
| 710 |
+
ValueError: eval_dataset: /mnt/workspace/data.jsonl is not supported.
|
| 711 |
+
eval_backend: OpenCompass supported datasets: ['C3', 'summedits', 'WiC', 'csl', 'lambada', 'mbpp', 'hellaswag', 'ARC_e', 'math', 'nq', 'race', 'MultiRC', 'cmb', 'ceval', 'GaokaoBench', 'mmlu', 'winogrande', 'tnews', 'triviaqa', 'CB', 'cluewsc', 'humaneval', 'AX_g', 'DRCD', 'RTE', 'ocnli_fc', 'gsm8k', 'obqa', 'ReCoRD', 'Xsum', 'ocnli', 'WSC', 'siqa', 'agieval', 'piqa', 'cmnli', 'cmmlu', 'eprstmt', 'storycloze', 'AX_b', 'afqmc', 'strategyqa', 'bustm', 'BoolQ', 'COPA', 'ARC_c', 'PMMEval', 'chid', 'CMRC', 'lcsts']
|
| 712 |
+
```
|
| 713 |
+
OpenCompass doesn't support custom datasets; use native mode for custom datasets.
|
| 714 |
+
|
| 715 |
+
### Q20: When I run the RAGAS evaluation task from the evalscope official documentation (https://evalscope.readthedocs.io/zh-cn/latest/user_guides/backend/rageval_backend/ragas.html) locally on a single A100, it takes 10 minutes to run the two examples in the documentation. Is this normal? Are there ways to optimize the running speed?
|
| 716 |
+
RAG evaluation itself is resource-intensive, and using a local critic LLM will indeed be slower as it can't handle batch requests. It's recommended to use frameworks like vllm to launch tasks.
|
ms-swift/docs/source_en/Instruction/GRPO.md
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GRPO
|
| 2 |
+
Paper Links
|
| 3 |
+
|
| 4 |
+
[DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://arxiv.org/abs/2402.03300)
|
| 5 |
+
[DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning](https://arxiv.org/abs/2501.12948)
|
| 6 |
+
|
| 7 |
+
environments
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
pip install math_verify # reward function
|
| 11 |
+
pip install -U trl
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
**Dev Log**
|
| 15 |
+
|
| 16 |
+
- **2025-05-11** — Implemented support for the **Generative Reward Model** and enabled customized reward model processing logic through the reward plugin. For more details, refer to the [Customized Reward Models](#customized-reward-models) section.
|
| 17 |
+
- **2025-04-30** — The startup command for the external vLLM server has been changed to swift rollout.
|
| 18 |
+
|
| 19 |
+
**FAQ**
|
| 20 |
+
1. It is normal for the loss to approach zero during training. Refer to this [issue](https://github.com/huggingface/open-r1/issues/239#issuecomment-2646297851) for more details.
|
| 21 |
+
2. How to calculate the training steps? Refer to this [issue](https://github.com/modelscope/ms-swift/issues/3912) for more details.
|
| 22 |
+
3. Why is the clip_ratio always 1? Refer to this [issue](https://github.com/huggingface/open-r1/issues/239#issuecomment-2646297851) for more details.
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
## Cluster Support
|
| 27 |
+
|
| 28 |
+

|
| 29 |
+
|
| 30 |
+
The GRPO training framework supports the integration of high-performance inference engines (such as vLLM) to accelerate the sampling process, offering the following two deployment modes:
|
| 31 |
+
|
| 32 |
+
### 1. Internal Integration Mode
|
| 33 |
+
|
| 34 |
+
- Launch the inference service directly within the Trainer.
|
| 35 |
+
- Provides two resource allocation strategies:
|
| 36 |
+
- **Colocate Mode**: Training and inference share GPU resources.
|
| 37 |
+
- **Async Mode**: Training and inference use separate GPU resources.
|
| 38 |
+
|
| 39 |
+
### GRPO Training Resource Allocation Scheme
|
| 40 |
+
|
| 41 |
+
| Configuration Scenario | NPROC_PER_NODE | num_infer_workers | Resource Allocation Description |
|
| 42 |
+
|-------------------------|----------------|-------------------|---------------------------------------|
|
| 43 |
+
| **Colocate** | = Total GPUs | = Total GPUs | Training and inference share all GPU resources. |
|
| 44 |
+
| **Async** | = Training GPUs| = Inference GPUs | Must satisfy: Training GPUs + Inference GPUs = Total GPUs. |
|
| 45 |
+
|
| 46 |
+
**Note:**
|
| 47 |
+
1. In Colocate mode, it is recommended to set `sleep_level=1` to release the GPU memory occupied by vLLM during model training.
|
| 48 |
+
2. Total GPUs refers to the total number of visible GPU devices.
|
| 49 |
+
|
| 50 |
+
### 2. External Service Mode
|
| 51 |
+
|
| 52 |
+
Connect to an external vLLM inference server.
|
| 53 |
+
When using this mode, configure the external vLLM server with the following parameters:
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
--vllm_server_host <Server IP> \
|
| 57 |
+
--vllm_server_port <Server Port> \
|
| 58 |
+
--vllm_server_timeout <Timeout> \
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Deploy the vLLM server using the `swift rollout` command. Currently, only the vLLM backend is supported.
|
| 62 |
+
```bash
|
| 63 |
+
CUDA_VISIBLE_DEVICES=2 \
|
| 64 |
+
swift rollout \
|
| 65 |
+
--model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 66 |
+
--tensor_parallel_size 2 \
|
| 67 |
+
```
|
| 68 |
+
The complete script can be found [here](../../../examples/train/grpo/multi_node/Qwen2_5_32B_full.sh) .
|
| 69 |
+
|
| 70 |
+
## Reward Functions
|
| 71 |
+
### Custom Reward Functions
|
| 72 |
+
A reward function takes the text `completions` generated by a model and other columns from the dataset as parameters(kwargs), and scores the model's generated text. Below is an example that demonstrates how to implement a simple length-based reward function. This function will give a reward signal of 1.0 if the length of the generated text exceeds 1024; otherwise, the reward signal will be 0.0.
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
from swift.plugin import ORM, orms
|
| 76 |
+
|
| 77 |
+
class DummyLengthRewardFunction(ORM):
|
| 78 |
+
def __call__(self, completions, **kwargs):
|
| 79 |
+
return [1.0 if len(completion) > 1024 else 0.0 for completion in completions]
|
| 80 |
+
|
| 81 |
+
orms['dummy']= DummyLengthRewardFunction
|
| 82 |
+
```
|
| 83 |
+
You can add this reward function in `swift/examples/train/grpo/plugin/plugin.py` and register it using the parameter `--external_plugins examples/train/grpo/plugin/plugin.py`, then specify it using the reward_funcs parameter.
|
| 84 |
+
|
| 85 |
+
For an example of how to execute the script, refer to [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/grpo/plugin/run_external_rm.sh).
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
### Built-in Reward Functions
|
| 90 |
+
Swift provides five rule-based reward functions built into the system(The code can be found in swift/plugin/orm.py.)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
| Reward Function | Paper |
|
| 94 |
+
|----------------|----------------------------------------------------------------------------|
|
| 95 |
+
| accuracy | [DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via RL](https://arxiv.org/abs/2501.12948) |
|
| 96 |
+
| format | Same as above |
|
| 97 |
+
| cosine | [Demystifying Long Chain-of-Thought Reasoning in LLMs](https://arxiv.org/abs/2502.03373) |
|
| 98 |
+
| repetition | Same as above |
|
| 99 |
+
| soft_overlong | [Decoupled Clip and Dynamic sAmpling Policy Optimization (DAPO)](https://arxiv.org/abs/2503.14476) |
|
| 100 |
+
|
| 101 |
+
#### 1. **accuracy**
|
| 102 |
+
|
| 103 |
+
This function compares the model's generated result with the solution column in the dataset to calculate an accuracy score. If the generated result matches the standard answer, the score is 1.0; otherwise, it is 0.0.
|
| 104 |
+
|
| 105 |
+
Note: This reward function uses the math_verify library to parse the generated results and the answers in the solution, and it may only be applicable to specific mathematical datasets.
|
| 106 |
+
|
| 107 |
+
#### 2. **format**
|
| 108 |
+
|
| 109 |
+
The paper uses the following system prompt to enforce a fixed format for model responses:
|
| 110 |
+
```
|
| 111 |
+
A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within <think>
|
| 112 |
+
```
|
| 113 |
+
This function checks whether the model generates text in the format `<think>think content</think><answer>answer content</answer>`. If the generated text adheres to the format requirements, the score is 1.0; otherwise, it is 0.0.
|
| 114 |
+
|
| 115 |
+
#### 3. **cosine**
|
| 116 |
+
|
| 117 |
+
The paper found that training with only the accuracy reward function could lead to overly long generated sequences, affecting training performance. The cosine reward function optimizes the training process by controlling the length of the generated sequences:
|
| 118 |
+
|
| 119 |
+
- For text that generates the correct answer, the reward value decreases as the length increases, encouraging concise responses.
|
| 120 |
+
- For text that generates incorrect answers, the reward value increases as the length increases, encouraging deeper reasoning.
|
| 121 |
+
|
| 122 |
+
A cosine function is used to smoothly adjust the reward value, ensuring that the changes are within a reasonable range. The parameters for the cosine function include the length of the generated text, the maximum length limit, and the minimum and maximum reward values.
|
| 123 |
+
|
| 124 |
+
Parameters:
|
| 125 |
+
- cosine_min_len_value_wrong (default: -0.5): Reward value corresponding to the minimum length when the answer is incorrect.
|
| 126 |
+
- cosine_max_len_value_wrong (default: 0.0): Reward value corresponding to the maximum length when the answer is incorrect.
|
| 127 |
+
- cosine_min_len_value_correct (default: 1.0): Reward value corresponding to the minimum length when the answer is correct.
|
| 128 |
+
- cosine_max_len_value_correct (default: 0.5): Reward value corresponding to the maximum length when the answer is correct.
|
| 129 |
+
- cosine_max_len (default value equal to the model's maximum generation capacity): Maximum length limit for generated text.
|
| 130 |
+
|
| 131 |
+
#### 4. **repetition**
|
| 132 |
+
|
| 133 |
+
This function penalizes repetition in generated text by detecting repeated n-gram patterns and assigning penalties based on the level of repetition.
|
| 134 |
+
|
| 135 |
+
The function splits the generated text into words and extracts n-grams of a specified size (default is 3-gram). It calculates the repetition ratio based on the proportion of unique n-grams to the total number of n-grams. If the proportion of repeated n-grams is high, a significant negative reward (penalty) is applied. The penalty value is computed based on the repetition ratio and a maximum penalty value (default: -1.0).
|
| 136 |
+
|
| 137 |
+
Parameters:
|
| 138 |
+
- repetition_n_grams (default: 3): Size of the n-gram used to detect repetition.
|
| 139 |
+
- repetition_max_penalty (default: -1.0): Maximum penalty value, which controls the intensity of the penalty.
|
| 140 |
+
|
| 141 |
+
#### 5. **soft overlong punishment**
|
| 142 |
+
Define the length penalty interval. Within this interval, a linear penalty of [-1, 0] is applied.
|
| 143 |
+
|
| 144 |
+
Parameters:
|
| 145 |
+
- soft_max_length: L_max in the paper, the maximum generation length of the model, default is equal to max_completion_length.
|
| 146 |
+
- soft_cache_length: L_cache in the paper, controls the length penalty interval, which is defined as [soft_max_length - soft_cache_length, soft_max_length].
|
| 147 |
+
|
| 148 |
+
Original text from the paper:
|
| 149 |
+
> a length-aware penalty mechanism designed to shape the reward for truncated samples. Specifically, when the response length exceeds the predefined maximum value, we define a punishment interval. Within this interval, the longer the response, the greater the punishment it receives. This penalty is added to the original rule-based correctness reward, thereby signaling to the model to avoid excessively long responses.
|
| 150 |
+
|
| 151 |
+
#### 6. **Reward Models**
|
| 152 |
+
|
| 153 |
+
In addition to rule-based reward functions, this framework also supports using reward models as reward functions. When using a reward model, you need to specify the `reward_model` parameter, similar to the `model` parameter, which is used to specify the path or name of the reward model. Note that either `reward_model` or `reward_funcs` needs to be specified.
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
## Arguments and Execution Script
|
| 157 |
+
Arguments
|
| 158 |
+
- per_device_train_batch_size: The training batch size per device. In GRPO, this refers to the batch size of completions during training.
|
| 159 |
+
- per_device_eval_batch_size: The evaluation batch size per device. In GRPO, this refers to the batch size of completions during evaluation.
|
| 160 |
+
- num_generations: The number of samples for each prompt, referred to as the G value in the paper, needs to be divisible by per_device_batch_size * - gradient_accumulation_steps * nproc_per_node, default is 8.
|
| 161 |
+
- max_completion_length: The maximum length for sampling generation, default is 512.
|
| 162 |
+
- ds3_gather_for_generation: This parameter applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation. The default is True.
|
| 163 |
+
- reward_funcs: Reward functions to score the results generated by the model. Includes built-in accuracy, format , cosine and repetition rule-based functions, detailed in the swift/plugin/orm.py file.
|
| 164 |
+
- reward_weights: Weights for each reward function. The number should be equal to the sum of the number of reward functions and reward models. If `None`, all rewards are weighted equally with weight `1.0`.
|
| 165 |
+
- Note: If `--reward_model` is included in GRPO training, it is added to the end of the reward functions.
|
| 166 |
+
- reward_model: Same as the model, using a reward model as a reward function. At least one of reward_funcs and reward_model needs to be specified.
|
| 167 |
+
- reward_model_plugin: The logic for the reward model, which defaults to ORM logic. For more information, please refer to [Customized Reward Models](#customized-reward-models).
|
| 168 |
+
- dataset_shuffle: Whether to shuffle the dataset randomly. Default is True.
|
| 169 |
+
- loss_type: The type of loss normalization. Options are ['grpo', 'bnpo', 'dr_grpo'], default is 'grpo'. For details, see this [pr](https://github.com/huggingface/trl/pull/3256#discussion_r2033213348)
|
| 170 |
+
- log_completions: Whether to log the model-generated content during training, to be used in conjunction with `--report_to wandb`, default is False.
|
| 171 |
+
- Note: If `--report_to wandb` is not set, a `completions.jsonl` will be created in the checkpoint to store the generated content.
|
| 172 |
+
- use_vllm: Whether to use vLLM as the back-end for sampling generation; default is False, using it is recommended to speed up training.
|
| 173 |
+
- vllm_device: Device for deploying vLLM, default is auto, meaning the first unused GPU. Use cuda:x to specify a particular card.
|
| 174 |
+
- vllm_gpu_memory_utilization: vLLM passthrough parameter, default is 0.9.
|
| 175 |
+
- vllm_max_model_len: vLLM passthrough parameter, default is None.
|
| 176 |
+
- vllm_max_num_seqs: vLLM passthrough parameter, default is 256.
|
| 177 |
+
- vllm_enforce_eager: vLLM passthrough parameter, default is False.
|
| 178 |
+
- vllm_limit_mm_per_prompt: vLLM passthrough parameter, default is None.
|
| 179 |
+
- vllm_enable_prefix_caching: vLLM passthrough parameter, default is True.
|
| 180 |
+
- vllm_server_host: The host address of the vLLM server. Default is None. This is used when connecting to an external vLLM server.
|
| 181 |
+
- vllm_server_port: The service port of the vLLM server. Default is 8000.
|
| 182 |
+
- vllm_server_timeout: The connection timeout for the vLLM server. Default is 120 seconds.
|
| 183 |
+
- num_iterations: number of iterations per batch. Default is 1.
|
| 184 |
+
- epsilon: epsilon value for clipping. Default is 0.2.
|
| 185 |
+
- epsilon_high: Upper clip coefficient, default is None. When set, it forms a clipping range of [epsilon, epsilon_high] together with epsilon.
|
| 186 |
+
- async_generate: Use async rollout to improve train speed,default `false`.
|
| 187 |
+
- sleep_level: vllm specific,when both actor and rollout in the same GPU,you can make vllm sleep when model is training.
|
| 188 |
+
- move_model_batches: When moving model parameters to fast inference frameworks such as vLLM/LMDeploy, determines how many batches to divide the layers into. The default is `None`, which means the entire model is not split. Otherwise, the model is split into `move_model_batches + 1` (non-layer parameters) + `1` (multi-modal component parameters) batches.
|
| 189 |
+
- offload_optimizer: Whether to offload optimizer parameters during inference with vLLM/LMDeploy. The default is `False`.
|
| 190 |
+
- offload_model: Whether to offload the model itself during inference with vLLM/LMDeploy. The default is `False`.
|
| 191 |
+
- Note: If this parameter is set to True and the grad_norm remains zero during training, please install vllm==0.7.3.
|
| 192 |
+
- gc_collect_after_offload: Whether to perform garbage collection (both Python GC and GPU GC) after offloading. The default is `False`.
|
| 193 |
+
- multi_turn_func: The multi turn GRPO plugin name. Add your multi-turn implementation in plugin/multi_turn.py
|
| 194 |
+
- dynamic_sample: Exclude data within the group where the reward standard deviation is 0, and additionally sample new data. Default is False.
|
| 195 |
+
- max_resample_times: Under the dynamic_sample setting, limit the number of resampling attempts to a maximum of 3. Default is 3 times.
|
| 196 |
+
- overlong_filter: Skip overlong truncated samples, which will not be included in loss calculation. Default is False.
|
| 197 |
+
The hyperparameters for the reward function can be found in the [Built-in Reward Functions section](#built-in-reward-functions).
|
| 198 |
+
|
| 199 |
+
You can use vLLM and LMDeploy as sampling backends to accelerate training.
|
| 200 |
+
|
| 201 |
+
Multi-GPU vLLM
|
| 202 |
+
```bash
|
| 203 |
+
# async mode
|
| 204 |
+
# The requirement is that num_infer_workers (deployment) + NPROC_PER_NODE (training) = device_count.
|
| 205 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
|
| 206 |
+
NPROC_PER_NODE=7 \
|
| 207 |
+
swift rlhf \
|
| 208 |
+
--rlhf_type grpo \
|
| 209 |
+
--model Qwen/Qwen2.5-7B \
|
| 210 |
+
--reward_funcs accuracy format cosine repetition\
|
| 211 |
+
--use_vllm true \
|
| 212 |
+
--vllm_device auto \
|
| 213 |
+
--vllm_gpu_memory_utilization 0.7 \
|
| 214 |
+
--vllm_max_model_len 8192 \
|
| 215 |
+
--num_infer_workers 1 \
|
| 216 |
+
--train_type full \
|
| 217 |
+
--torch_dtype bfloat16 \
|
| 218 |
+
--dataset 'AI-MO/NuminaMath-TIR#5000' \
|
| 219 |
+
--max_completion_length 2048 \
|
| 220 |
+
--num_train_epochs 1 \
|
| 221 |
+
--per_device_train_batch_size 1 \
|
| 222 |
+
--per_device_eval_batch_size 1 \
|
| 223 |
+
--learning_rate 1e-6 \
|
| 224 |
+
--gradient_accumulation_steps 2 \
|
| 225 |
+
--eval_steps 200 \
|
| 226 |
+
--save_steps 200 \
|
| 227 |
+
--save_total_limit 2 \
|
| 228 |
+
--logging_steps 5 \
|
| 229 |
+
--max_length 4096 \
|
| 230 |
+
--output_dir output \
|
| 231 |
+
--warmup_ratio 0.05 \
|
| 232 |
+
--dataloader_num_workers 4 \
|
| 233 |
+
--dataset_num_proc 4 \
|
| 234 |
+
--num_generations 7 \
|
| 235 |
+
--temperature 0.9 \
|
| 236 |
+
--system 'examples/train/grpo/prompt.txt' \
|
| 237 |
+
--deepspeed zero2 \
|
| 238 |
+
--log_completions true
|
| 239 |
+
|
| 240 |
+
# colocate mode
|
| 241 |
+
# The requirement is that num_infer_workers (deployment) = NPROC_PER_NODE (training) = device_count.
|
| 242 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
|
| 243 |
+
NPROC_PER_NODE=8 \
|
| 244 |
+
swift rlhf \
|
| 245 |
+
--rlhf_type grpo \
|
| 246 |
+
--model Qwen/Qwen2.5-1.5B \
|
| 247 |
+
--reward_funcs accuracy format \
|
| 248 |
+
--use_vllm true \
|
| 249 |
+
--vllm_device auto \
|
| 250 |
+
--vllm_gpu_memory_utilization 0.7 \
|
| 251 |
+
--vllm_max_model_len 8192 \
|
| 252 |
+
--num_infer_workers 8 \
|
| 253 |
+
--train_type full \
|
| 254 |
+
--torch_dtype bfloat16 \
|
| 255 |
+
--dataset 'AI-MO/NuminaMath-TIR#5000' \
|
| 256 |
+
--max_completion_length 2048 \
|
| 257 |
+
--num_train_epochs 1 \
|
| 258 |
+
--per_device_train_batch_size 1 \
|
| 259 |
+
--per_device_eval_batch_size 1 \
|
| 260 |
+
--learning_rate 1e-6 \
|
| 261 |
+
--gradient_accumulation_steps 2 \
|
| 262 |
+
--eval_steps 200 \
|
| 263 |
+
--save_steps 200 \
|
| 264 |
+
--save_total_limit 2 \
|
| 265 |
+
--logging_steps 5 \
|
| 266 |
+
--max_length 4096 \
|
| 267 |
+
--output_dir output \
|
| 268 |
+
--warmup_ratio 0.05 \
|
| 269 |
+
--dataloader_num_workers 4 \
|
| 270 |
+
--dataset_num_proc 4 \
|
| 271 |
+
--num_generations 8 \
|
| 272 |
+
--temperature 0.9 \
|
| 273 |
+
--system 'examples/train/grpo/prompt.txt' \
|
| 274 |
+
--deepspeed zero2 \
|
| 275 |
+
--log_completions true \
|
| 276 |
+
--sleep_level 1 \
|
| 277 |
+
--offload_model true \
|
| 278 |
+
--offload_optimizer true \
|
| 279 |
+
--gc_collect_after_offload true \
|
| 280 |
+
--log_completions true \
|
| 281 |
+
```
|
| 282 |
+
|
| 283 |
+
Single-GPU
|
| 284 |
+
```bash
|
| 285 |
+
# PT backend
|
| 286 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 287 |
+
swift rlhf \
|
| 288 |
+
--rlhf_type grpo \
|
| 289 |
+
--model Qwen/Qwen2.5-7B \
|
| 290 |
+
--reward_funcs accuracy format cosine repetition\
|
| 291 |
+
--train_type lora \
|
| 292 |
+
--lora_rank 8 \
|
| 293 |
+
--lora_alpha 32 \
|
| 294 |
+
--target_modules all-linear \
|
| 295 |
+
--torch_dtype bfloat16 \
|
| 296 |
+
--dataset 'AI-MO/NuminaMath-TIR#1000' \
|
| 297 |
+
--max_completion_length 1024 \
|
| 298 |
+
--num_train_epochs 1 \
|
| 299 |
+
--per_device_train_batch_size 4 \
|
| 300 |
+
--per_device_eval_batch_size 4 \
|
| 301 |
+
--learning_rate 1e-5 \
|
| 302 |
+
--gradient_accumulation_steps 1 \
|
| 303 |
+
--eval_steps 100 \
|
| 304 |
+
--save_steps 100 \
|
| 305 |
+
--save_total_limit 2 \
|
| 306 |
+
--logging_steps 5 \
|
| 307 |
+
--max_length 2048 \
|
| 308 |
+
--output_dir output \
|
| 309 |
+
--warmup_ratio 0.05 \
|
| 310 |
+
--dataloader_num_workers 4 \
|
| 311 |
+
--dataset_num_proc 4 \
|
| 312 |
+
--num_generations 4 \
|
| 313 |
+
--temperature 0.9 \
|
| 314 |
+
--system 'examples/train/grpo/prompt.txt' \
|
| 315 |
+
--log_completions true
|
| 316 |
+
|
| 317 |
+
# vLLM backend
|
| 318 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 319 |
+
swift rlhf \
|
| 320 |
+
--rlhf_type grpo \
|
| 321 |
+
--model Qwen/Qwen2.5-7B \
|
| 322 |
+
--vllm_gpu_memory_utilization 0.5 \
|
| 323 |
+
--use_vllm true \
|
| 324 |
+
--sleep_level 1 \
|
| 325 |
+
--offload_model true \
|
| 326 |
+
--offload_optimizer true \
|
| 327 |
+
--gc_collect_after_offload true \
|
| 328 |
+
--reward_funcs accuracy format \
|
| 329 |
+
--train_type lora \
|
| 330 |
+
--lora_rank 8 \
|
| 331 |
+
--lora_alpha 32 \
|
| 332 |
+
--target_modules all-linear \
|
| 333 |
+
--torch_dtype bfloat16 \
|
| 334 |
+
--dataset 'AI-MO/NuminaMath-TIR#1000' \
|
| 335 |
+
--max_completion_length 1024 \
|
| 336 |
+
--num_train_epochs 1 \
|
| 337 |
+
--per_device_train_batch_size 4 \
|
| 338 |
+
--per_device_eval_batch_size 4 \
|
| 339 |
+
--learning_rate 1e-5 \
|
| 340 |
+
--gradient_accumulation_steps 1 \
|
| 341 |
+
--eval_steps 100 \
|
| 342 |
+
--save_steps 100 \
|
| 343 |
+
--save_total_limit 2 \
|
| 344 |
+
--logging_steps 5 \
|
| 345 |
+
--max_length 2048 \
|
| 346 |
+
--output_dir output \
|
| 347 |
+
--warmup_ratio 0.05 \
|
| 348 |
+
--dataloader_num_workers 4 \
|
| 349 |
+
--dataset_num_proc 4 \
|
| 350 |
+
--num_generations 4 \
|
| 351 |
+
--temperature 0.9 \
|
| 352 |
+
--system 'examples/train/grpo/prompt.txt' \
|
| 353 |
+
--log_completions true
|
| 354 |
+
```
|
| 355 |
+
|
| 356 |
+
For multi-node training, refer to [here](../../../examples/train/grpo/multi_node/) .
|
| 357 |
+
|
| 358 |
+
Note : In the internal integration mode, the GPU configurations and training parameters must be identical across different nodes.
|
| 359 |
+
|
| 360 |
+
## Customized Reward Models
|
| 361 |
+
By default, a reward model refers to classification models that include a value head (commonly known as Output Reward Model (ORM)). These models score the outputs of other models, producing a scalar value that represents the quality of the response.
|
| 362 |
+
|
| 363 |
+
Currently, we can leverage the **reward_model_plugin** to flexibly customize the processing logic of these reward models. This enables the implementation of advanced techniques such as Generative Reward Models, which include:
|
| 364 |
+
|
| 365 |
+
- Customizing the Model's System Prompt: Defining specific instructions and context to guide the evaluation process.
|
| 366 |
+
- Handling Model Interaction History: Managing the conversational context to provide meaningful and contextually aware evaluations.
|
| 367 |
+
- Defining Custom Evaluation Criteria: Setting unique standards and metrics for assessing the model's responses beyond default accuracy and relevance measures.
|
| 368 |
+
|
| 369 |
+
Through the **reward_model_plugin**, developers can tailor the reward evaluation process to meet the specific requirements of their applications. This flexibility allows for more nuanced and effective reward-based training strategies.
|
| 370 |
+
|
| 371 |
+
We provide a simple generative reward model example (GenRMPlugin) in [rm_plugin.py](../../../swift/plugin/rm_plugin.py)
|
| 372 |
+
|
| 373 |
+
You can also customized your reward model plugin in [plugin.py](../../../examples/train/grpo/plugin/plugin.py), and register with `external_plugins` argument
|
| 374 |
+
|
| 375 |
+
Here is an example training script to train GRPO with two reward models: one ORM and one Gen-RM (using qwen2.5-3B-Instruct in this case):
|
| 376 |
+
|
| 377 |
+
```
|
| 378 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
|
| 379 |
+
NPROC_PER_NODE=8 \
|
| 380 |
+
swift rlhf \
|
| 381 |
+
--rlhf_type grpo \
|
| 382 |
+
--model Qwen/Qwen2.5-7B \
|
| 383 |
+
--dataset AI-MO/NuminaMath-TIR#5000 \
|
| 384 |
+
--external_plugins examples/train/grpo/plugin/plugin.py \
|
| 385 |
+
--reward_funcs format \
|
| 386 |
+
--reward_model Qwen/Qwen2.5-3B-Instruct Shanghai_AI_Laboratory/internlm2-7b-reward \
|
| 387 |
+
--reward_model_plugin genrm my_rmplugin \
|
| 388 |
+
--reward_weights 0.1 1 1 \
|
| 389 |
+
--num_infer_workers 8 \
|
| 390 |
+
--vllm_gpu_memory_utilization 0.5 \
|
| 391 |
+
--sleep_level 1 \
|
| 392 |
+
--offload_model true \
|
| 393 |
+
--offload_optimizer true \
|
| 394 |
+
--gc_collect_after_offload true \
|
| 395 |
+
--log_completions true \
|
| 396 |
+
--deepspeed zero3
|
| 397 |
+
```
|
| 398 |
+
|
| 399 |
+
Notes:
|
| 400 |
+
|
| 401 |
+
1. In the GRPOTrainer, reward_model instances are appended sequentially to reward_funcs. Therefore, the order of reward_weights corresponds to [reward_funcs, reward_model].
|
| 402 |
+
2. The default value for reward_model_plugin is default, which uses the ORM processing logic.
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
## DAPO
|
| 406 |
+
Decoupled Clip and Dynamic Sampling Policy Optimization (DAPO) introduces several tricks based on GRPO, which are:
|
| 407 |
+
- Clip Higher
|
| 408 |
+
- Dynamic Sampling
|
| 409 |
+
- Overlong Filtering
|
| 410 |
+
- Token level Loss
|
| 411 |
+
- Soft Overlong Punishment
|
| 412 |
+
|
| 413 |
+
Among these, Token level Loss is implemented by default and does not require additional settings. For the other tricks, we can achieve the desired setup based on GRPOTrainer by configuring the following parameters.
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
| Parameter | Type | Value |
|
| 417 |
+
|----------------------|-----------|-------------|
|
| 418 |
+
| `--epsilon_high` | `float` | `0.28` |
|
| 419 |
+
| `--dynamic_sample` | `bool` | `true` |
|
| 420 |
+
| `--overlong_filter` | `bool` | `true` |
|
| 421 |
+
| `--reward_funcs` | `str` | `soft_overlong`|
|
| 422 |
+
| `--max_resample_times` | `int` | `3` |
|
| 423 |
+
|
| 424 |
+
Reference training script (for 8-card colocate mode):
|
| 425 |
+
|
| 426 |
+
```bash
|
| 427 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
|
| 428 |
+
NPROC_PER_NODE=8 \
|
| 429 |
+
WANDB_API_KEY=xxx \
|
| 430 |
+
swift rlhf \
|
| 431 |
+
--rlhf_type grpo \
|
| 432 |
+
--model Qwen/Qwen2.5-1.5B \
|
| 433 |
+
--reward_funcs accuracy soft_overlong \
|
| 434 |
+
--max_completion_length 4096 \
|
| 435 |
+
--soft_cache_length 819 \
|
| 436 |
+
--epsilon 0.2 \
|
| 437 |
+
--epsilon_high 0.28 \
|
| 438 |
+
--dynamic_sample true \
|
| 439 |
+
--overlong_filter true \
|
| 440 |
+
--max_resample_times 3 \
|
| 441 |
+
--use_vllm true \
|
| 442 |
+
--vllm_gpu_memory_utilization 0.6 \
|
| 443 |
+
--num_infer_workers 8 \
|
| 444 |
+
--train_type full \
|
| 445 |
+
--torch_dtype bfloat16 \
|
| 446 |
+
--dataset AI-MO/NuminaMath-TIR#5000 \
|
| 447 |
+
--num_train_epochs 1 \
|
| 448 |
+
--per_device_train_batch_size 4 \
|
| 449 |
+
--per_device_eval_batch_size 4 \
|
| 450 |
+
--learning_rate 1e-6 \
|
| 451 |
+
--eval_steps 1000 \
|
| 452 |
+
--save_steps 1000 \
|
| 453 |
+
--save_total_limit 2 \
|
| 454 |
+
--logging_steps 5 \
|
| 455 |
+
--warmup_ratio 0.05 \
|
| 456 |
+
--dataloader_num_workers 4 \
|
| 457 |
+
--dataset_num_proc 4 \
|
| 458 |
+
--num_generations 8 \
|
| 459 |
+
--temperature 1.0 \
|
| 460 |
+
--top_p 1.0 \
|
| 461 |
+
--deepspeed zero2 \
|
| 462 |
+
--log_completions true \
|
| 463 |
+
--num_iterations 1 \
|
| 464 |
+
--report_to tensorboard wandb \
|
| 465 |
+
--beta 0.0 \
|
| 466 |
+
--sleep_level 1 \
|
| 467 |
+
--offload_model true \
|
| 468 |
+
--offload_optimizer true \
|
| 469 |
+
--gc_collect_after_offload true \
|
| 470 |
+
--log_completions true
|
| 471 |
+
```
|
ms-swift/docs/source_en/Instruction/Inference-and-deployment.md
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Inference and Deployment
|
| 2 |
+
|
| 3 |
+
Below are the inference engines supported by Swift along with their corresponding capabilities. The three inference acceleration engines provide inference acceleration for Swift's inference, deployment, and evaluation modules:
|
| 4 |
+
|
| 5 |
+
| Inference Acceleration Engine | OpenAI API | Multimodal | Quantized Model | Multiple LoRAs | QLoRA | Batch Inference | Parallel Techniques |
|
| 6 |
+
| ------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | --------------- | ------------------------------------------------------------ | ----- | ------------------------------------------------------------ | ------------------- |
|
| 7 |
+
| pytorch | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/deploy/client/llm/chat/openai_client.py) | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/app/mllm.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_lora.py) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/batch_ddp.sh) | DDP/device_map |
|
| 8 |
+
| [vllm](https://github.com/vllm-project/vllm) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/vllm/mllm_tp.sh) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/deploy/lora/server.sh) | ❌ | ✅ | TP/PP/DP |
|
| 9 |
+
| [lmdeploy](https://github.com/InternLM/lmdeploy) | ✅ | [✅](https://github.com/modelscope/ms-swift/blob/main/examples/infer/lmdeploy/mllm_tp.sh) | ✅ | ❌ | ❌ | ✅ | TP/DP |
|
| 10 |
+
|
| 11 |
+
## Inference
|
| 12 |
+
|
| 13 |
+
ms-swift uses a layered design philosophy, allowing users to perform inference through the command-line interface, web UI, or directly using Python.
|
| 14 |
+
|
| 15 |
+
To view the inference of a model fine-tuned with LoRA, please refer to the [Pre-training and Fine-tuning documentation](./Pre-training-and-Fine-tuning.md#inference-fine-tuned-model).
|
| 16 |
+
|
| 17 |
+
### Using CLI
|
| 18 |
+
|
| 19 |
+
**Full Parameter Model:**
|
| 20 |
+
|
| 21 |
+
```shell
|
| 22 |
+
CUDA_VISIBLE_DEVICES=0 swift infer \
|
| 23 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 24 |
+
--stream true \
|
| 25 |
+
--infer_backend pt \
|
| 26 |
+
--max_new_tokens 2048
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
**LoRA Model:**
|
| 30 |
+
|
| 31 |
+
```shell
|
| 32 |
+
CUDA_VISIBLE_DEVICES=0 swift infer \
|
| 33 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 34 |
+
--adapters swift/test_lora \
|
| 35 |
+
--stream true \
|
| 36 |
+
--infer_backend pt \
|
| 37 |
+
--temperature 0 \
|
| 38 |
+
--max_new_tokens 2048
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
**Command-Line Inference Instructions**
|
| 42 |
+
|
| 43 |
+
The above commands are for interactive command-line interface inference. After running the script, you can simply enter your query in the terminal. You can also input the following special commands:
|
| 44 |
+
|
| 45 |
+
- `multi-line`: Switch to multi-line mode, allowing line breaks in the input, ending with `#`.
|
| 46 |
+
- `single-line`: Switch to single-line mode, with line breaks indicating the end of input.
|
| 47 |
+
- `reset-system`: Reset the system and clear history.
|
| 48 |
+
- `clear`: Clear the history.
|
| 49 |
+
- `quit` or `exit`: Exit the conversation.
|
| 50 |
+
|
| 51 |
+
**Multimodal Model**
|
| 52 |
+
|
| 53 |
+
```shell
|
| 54 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 55 |
+
MAX_PIXELS=1003520 \
|
| 56 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 57 |
+
FPS_MAX_FRAMES=12 \
|
| 58 |
+
swift infer \
|
| 59 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 60 |
+
--stream true \
|
| 61 |
+
--infer_backend pt \
|
| 62 |
+
--max_new_tokens 2048
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
To perform inference with a multimodal model, you can add tags like `<image>`, `<video>`, or `<audio>` in your query (representing the location of image representations in `inputs_embeds`). For example, you can input `<image><image>What is the difference between these two images?` or `<video>Describe this video.` Then, follow the prompts to input the corresponding image/video/audio.
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
Here is an example of inference:
|
| 69 |
+
```
|
| 70 |
+
<<< <image><image>What is the difference between these two images?
|
| 71 |
+
Input an image path or URL <<< http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png
|
| 72 |
+
Input an image path or URL <<< http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png
|
| 73 |
+
The first image depicts a cute, cartoon-style kitten with large, expressive eyes and a fluffy white and gray coat. The background is simple, featuring a gradient of colors that highlight the kitten's face.
|
| 74 |
+
|
| 75 |
+
The second image shows a group of four cartoon-style sheep standing on a grassy field with mountains in the background. The sheep have fluffy white wool, black legs, and black faces with white markings around their eyes and noses. The background includes green hills and a blue sky with clouds, giving it a pastoral and serene atmosphere.
|
| 76 |
+
--------------------------------------------------
|
| 77 |
+
<<< clear
|
| 78 |
+
<<< <video>Describe this video.
|
| 79 |
+
Input a video path or URL <<< https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4
|
| 80 |
+
A baby wearing glasses is sitting on a bed and reading a book. The baby is holding the book with both hands and is looking down at it. The baby is wearing a light blue shirt and pink pants. The baby is sitting on a white pillow. The baby is looking at the book with interest. The baby is not moving much, just turning the pages of the book.
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
**Dataset Inference:**
|
| 84 |
+
|
| 85 |
+
```
|
| 86 |
+
CUDA_VISIBLE_DEVICES=0 swift infer \
|
| 87 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 88 |
+
--stream true \
|
| 89 |
+
--infer_backend pt \
|
| 90 |
+
--val_dataset AI-ModelScope/alpaca-gpt4-data-zh \
|
| 91 |
+
--max_new_tokens 2048
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
The above example provides streaming inference for both full parameters and LoRA, and below are more inference techniques available in SWIFT:
|
| 95 |
+
|
| 96 |
+
- Interface Inference: You can change `swift infer` to `swift app`.
|
| 97 |
+
- Batch Inference: For large models and multimodal models, you can specify `--max_batch_size` for batch inference by using `infer_backend=pt`. For specific details, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/batch_ddp.sh). Note that you cannot set `--stream true` when performing batch inference.
|
| 98 |
+
- DDP/device_map Inference: `infer_backend=pt` supports parallel inference using DDP/device_map technology. For further details, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/mllm_device_map.sh).
|
| 99 |
+
- Inference Acceleration: Swift supports using vllm/lmdeploy for inference acceleration across the inference, deployment, and evaluation modules by simply adding `--infer_backend vllm/lmdeploy`. You can refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/vllm/ddp.sh).
|
| 100 |
+
- Multimodal Models: We provide shell scripts for multi-GPU inference for multimodal models using [pt](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/mllm_device_map.sh), [vllm](https://github.com/modelscope/ms-swift/blob/main/examples/infer/vllm/mllm_tp.sh), and [lmdeploy](https://github.com/modelscope/ms-swift/blob/main/examples/infer/lmdeploy/mllm_tp.sh).
|
| 101 |
+
- Quantized Models: You can directly select models that are quantized with GPTQ, AWQ, or BNB, for example: `--model Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4`.
|
| 102 |
+
- More Model Types: We also provide inference scripts for [bert](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/bert.sh), [reward_model](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/reward_model.sh), and [prm](https://github.com/modelscope/ms-swift/blob/main/examples/infer/pt/prm.sh).
|
| 103 |
+
|
| 104 |
+
**Tips:**
|
| 105 |
+
|
| 106 |
+
- SWIFT saves inference results, and you can specify the save path using `--result_path`.
|
| 107 |
+
- To output log probabilities, simply specify `--logprobs true` during inference. SWIFT will save these results. Note that setting `--stream true` will prevent storage of results.
|
| 108 |
+
- Using `infer_backend=pt` supports inference for all models supported by SWIFT, while `infer_backend=vllm/lmdeploy` supports only a subset of models. Please refer to the documentation for [vllm](https://docs.vllm.ai/en/latest/models/supported_models.html) and [lmdeploy](https://lmdeploy.readthedocs.io/en/latest/supported_models/supported_models.html).
|
| 109 |
+
- If you encounter OOM when using `--infer_backend vllm`, you can lower `--max_model_len`, `--max_num_seqs`, choose an appropriate `--gpu_memory_utilization`, or set `--enforce_eager true`. Alternatively, you can address this by using tensor parallelism with `--tensor_parallel_size`.
|
| 110 |
+
- When inferring multimodal models using `--infer_backend vllm`, you need to input multiple images. You can set `--limit_mm_per_prompt` to resolve this, for example: `--limit_mm_per_prompt '{"image": 10, "video": 5}'`.
|
| 111 |
+
- If you encounter OOM issues while inferring qwen2-vl/qwen2.5-vl, you can address this by setting `MAX_PIXELS`, `VIDEO_MAX_PIXELS`, and `FPS_MAX_FRAMES`. For more information, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/app/mllm.sh).
|
| 112 |
+
- SWIFT's built-in dialogue templates align with dialogue templates run using transformers. You can refer to [here](https://github.com/modelscope/ms-swift/blob/main/tests/test_align/test_template/test_vision.py) for testing. If there are any misalignments, please feel free to submit an issue or PR for correction.
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
### Using Web-UI
|
| 116 |
+
|
| 117 |
+
If you want to perform inference through a graphical interface, you can refer to the [Web-UI documentation](../GetStarted/Web-UI.md).
|
| 118 |
+
|
| 119 |
+
### Using Python
|
| 120 |
+
|
| 121 |
+
**Text Model:**
|
| 122 |
+
|
| 123 |
+
```python
|
| 124 |
+
import os
|
| 125 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 126 |
+
|
| 127 |
+
from swift.llm import PtEngine, RequestConfig, InferRequest
|
| 128 |
+
model = 'Qwen/Qwen2.5-0.5B-Instruct'
|
| 129 |
+
|
| 130 |
+
# Load the inference engine
|
| 131 |
+
engine = PtEngine(model, max_batch_size=2)
|
| 132 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 133 |
+
|
| 134 |
+
# Using 2 infer_requests to demonstrate batch inference
|
| 135 |
+
infer_requests = [
|
| 136 |
+
InferRequest(messages=[{'role': 'user', 'content': 'Who are you?'}]),
|
| 137 |
+
InferRequest(messages=[{'role': 'user', 'content': 'Where is the capital of Zhejiang?'},
|
| 138 |
+
{'role': 'assistant', 'content': 'The capital of Zhejiang Province, China, is Hangzhou.'},
|
| 139 |
+
{'role': 'user', 'content': 'What are some fun places here?'}]),
|
| 140 |
+
]
|
| 141 |
+
resp_list = engine.infer(infer_requests, request_config)
|
| 142 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 143 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 144 |
+
print(f'response1: {resp_list[1].choices[0].message.content}')
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
**Multimodal Model:**
|
| 148 |
+
|
| 149 |
+
```python
|
| 150 |
+
import os
|
| 151 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 152 |
+
os.environ['MAX_PIXELS'] = '1003520'
|
| 153 |
+
os.environ['VIDEO_MAX_PIXELS'] = '50176'
|
| 154 |
+
os.environ['FPS_MAX_FRAMES'] = '12'
|
| 155 |
+
|
| 156 |
+
from swift.llm import PtEngine, RequestConfig, InferRequest
|
| 157 |
+
model = 'Qwen/Qwen2.5-VL-3B-Instruct'
|
| 158 |
+
|
| 159 |
+
# Load the inference engine
|
| 160 |
+
engine = PtEngine(model, max_batch_size=2)
|
| 161 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 162 |
+
|
| 163 |
+
# Using 3 infer_requests to demonstrate batch inference
|
| 164 |
+
infer_requests = [
|
| 165 |
+
InferRequest(messages=[{'role': 'user', 'content': 'Who are you?'}]),
|
| 166 |
+
InferRequest(messages=[{'role': 'user', 'content': '<image><image> What is the difference between these two images?'}],
|
| 167 |
+
images=['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png',
|
| 168 |
+
'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']),
|
| 169 |
+
InferRequest(messages=[{'role': 'user', 'content': '<video> Describe the video'}],
|
| 170 |
+
videos=['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']),
|
| 171 |
+
]
|
| 172 |
+
resp_list = engine.infer(infer_requests, request_config)
|
| 173 |
+
query0 = infer_requests[0].messages[0]['content']
|
| 174 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 175 |
+
print(f'response1: {resp_list[1].choices[0].message.content}')
|
| 176 |
+
print(f'response2: {resp_list[2].choices[0].message.content}')
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
We also provide more demos for Python-based inference:
|
| 180 |
+
|
| 181 |
+
- For streaming inference using `VllmEngine` and `LmdeployEngine` for inference acceleration, you can refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo.py).
|
| 182 |
+
- Multimodal Inference: In addition to the aforementioned multimodal input formats, Swift is compatible with OpenAI's multimodal input format; refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_mllm.py).
|
| 183 |
+
- Grounding Tasks: For performing grounding tasks with multimodal models, you can refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_grounding.py).
|
| 184 |
+
- Multiple LoRA Inference: Refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_lora.py).
|
| 185 |
+
- Agent Inference: Refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo_agent.py).
|
| 186 |
+
- Asynchronous Interface: For Python-based inference using `engine.infer_async`, refer to [here](https://github.com/modelscope/ms-swift/blob/main/examples/infer/demo.py).
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
## Deployment
|
| 190 |
+
|
| 191 |
+
If you want to see the deployment of a model fine-tuned with LoRA, you can refer to the [Pre-training and Fine-tuning documentation](./Pre-training-and-Fine-tuning.md#deployment-fine-tuned-model).
|
| 192 |
+
|
| 193 |
+
This section primarily focuses on the deployment and invocation of multimodal models. For text-based large models, we provide a simple deployment and invocation example:
|
| 194 |
+
|
| 195 |
+
**Server Deployment:**
|
| 196 |
+
|
| 197 |
+
```shell
|
| 198 |
+
CUDA_VISIBLE_DEVICES=0 swift deploy \
|
| 199 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 200 |
+
--infer_backend vllm \
|
| 201 |
+
--max_new_tokens 2048 \
|
| 202 |
+
--served_model_name Qwen2.5-7B-Instruct
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
**Client Invocation Test:**
|
| 206 |
+
|
| 207 |
+
```shell
|
| 208 |
+
curl http://localhost:8000/v1/chat/completions \
|
| 209 |
+
-H "Content-Type: application/json" \
|
| 210 |
+
-d '{
|
| 211 |
+
"model": "Qwen2.5-7B-Instruct",
|
| 212 |
+
"messages": [{"role": "user", "content": "What should I do if I can’t sleep at night?"}],
|
| 213 |
+
"max_tokens": 256,
|
| 214 |
+
"temperature": 0
|
| 215 |
+
}'
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
### Server Side
|
| 220 |
+
|
| 221 |
+
```shell
|
| 222 |
+
# test environment: pip install transformers==4.49.* vllm==0.7.3
|
| 223 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 224 |
+
MAX_PIXELS=1003520 \
|
| 225 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 226 |
+
FPS_MAX_FRAMES=12 \
|
| 227 |
+
swift deploy \
|
| 228 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 229 |
+
--infer_backend vllm \
|
| 230 |
+
--gpu_memory_utilization 0.9 \
|
| 231 |
+
--max_model_len 8192 \
|
| 232 |
+
--max_new_tokens 2048 \
|
| 233 |
+
--limit_mm_per_prompt '{"image": 5, "video": 2}' \
|
| 234 |
+
--served_model_name Qwen2.5-VL-3B-Instruct
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
### Client Side
|
| 238 |
+
|
| 239 |
+
We introduce three methods for invoking the client: using curl, the OpenAI library, and the Swift client.
|
| 240 |
+
|
| 241 |
+
**Method 1: curl**
|
| 242 |
+
|
| 243 |
+
```shell
|
| 244 |
+
curl http://localhost:8000/v1/chat/completions \
|
| 245 |
+
-H "Content-Type: application/json" \
|
| 246 |
+
-d '{
|
| 247 |
+
"model": "Qwen2.5-VL-3B-Instruct",
|
| 248 |
+
"messages": [{"role": "user", "content": [
|
| 249 |
+
{"type": "image", "image": "http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png"},
|
| 250 |
+
{"type": "image", "image": "http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png"},
|
| 251 |
+
{"type": "text", "text": "What is the difference between these two images?"}
|
| 252 |
+
]}],
|
| 253 |
+
"max_tokens": 256,
|
| 254 |
+
"temperature": 0
|
| 255 |
+
}'
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
**Method 2: OpenAI Library**
|
| 259 |
+
|
| 260 |
+
```python
|
| 261 |
+
from openai import OpenAI
|
| 262 |
+
|
| 263 |
+
client = OpenAI(
|
| 264 |
+
api_key='EMPTY',
|
| 265 |
+
base_url=f'http://127.0.0.1:8000/v1',
|
| 266 |
+
)
|
| 267 |
+
model = client.models.list().data[0].id
|
| 268 |
+
print(f'model: {model}')
|
| 269 |
+
|
| 270 |
+
messages = [{'role': 'user', 'content': [
|
| 271 |
+
{'type': 'video', 'video': 'https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4'},
|
| 272 |
+
{'type': 'text', 'text': 'describe the video'}
|
| 273 |
+
]}]
|
| 274 |
+
|
| 275 |
+
resp = client.chat.completions.create(model=model, messages=messages, max_tokens=512, temperature=0)
|
| 276 |
+
query = messages[0]['content']
|
| 277 |
+
response = resp.choices[0].message.content
|
| 278 |
+
print(f'query: {query}')
|
| 279 |
+
print(f'response: {response}')
|
| 280 |
+
|
| 281 |
+
# Using base64
|
| 282 |
+
import base64
|
| 283 |
+
import requests
|
| 284 |
+
resp = requests.get('https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4')
|
| 285 |
+
base64_encoded = base64.b64encode(resp.content).decode('utf-8')
|
| 286 |
+
messages = [{'role': 'user', 'content': [
|
| 287 |
+
{'type': 'video', 'video': f'data:video/mp4;base64,{base64_encoded}'},
|
| 288 |
+
{'type': 'text', 'text': 'describe the video'}
|
| 289 |
+
]}]
|
| 290 |
+
|
| 291 |
+
gen = client.chat.completions.create(model=model, messages=messages, stream=True, temperature=0)
|
| 292 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 293 |
+
for chunk in gen:
|
| 294 |
+
if chunk is None:
|
| 295 |
+
continue
|
| 296 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 297 |
+
print()
|
| 298 |
+
```
|
| 299 |
+
|
| 300 |
+
**Method 3: Swift Client**
|
| 301 |
+
|
| 302 |
+
```python
|
| 303 |
+
from swift.llm import InferRequest, InferClient, RequestConfig
|
| 304 |
+
from swift.plugin import InferStats
|
| 305 |
+
|
| 306 |
+
engine = InferClient(host='127.0.0.1', port=8000)
|
| 307 |
+
print(f'models: {engine.models}')
|
| 308 |
+
metric = InferStats()
|
| 309 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 310 |
+
|
| 311 |
+
# Using 3 infer_requests to demonstrate batch inference
|
| 312 |
+
# Supports local paths, base64, and URLs
|
| 313 |
+
infer_requests = [
|
| 314 |
+
InferRequest(messages=[{'role': 'user', 'content': 'Who are you?'}]),
|
| 315 |
+
InferRequest(messages=[{'role': 'user', 'content': '<image><image> What is the difference between these two images?'}],
|
| 316 |
+
images=['http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/cat.png',
|
| 317 |
+
'http://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/animal.png']),
|
| 318 |
+
InferRequest(messages=[{'role': 'user', 'content': '<video> Describe the video'}],
|
| 319 |
+
videos=['https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4']),
|
| 320 |
+
]
|
| 321 |
+
|
| 322 |
+
resp_list = engine.infer(infer_requests, request_config, metrics=[metric])
|
| 323 |
+
print(f'response0: {resp_list[0].choices[0].message.content}')
|
| 324 |
+
print(f'response1: {resp_list[1].choices[0].message.content}')
|
| 325 |
+
print(f'response2: {resp_list[2].choices[0].message.content}')
|
| 326 |
+
print(metric.compute())
|
| 327 |
+
metric.reset()
|
| 328 |
+
|
| 329 |
+
# Using base64
|
| 330 |
+
import base64
|
| 331 |
+
import requests
|
| 332 |
+
resp = requests.get('https://modelscope-open.oss-cn-hangzhou.aliyuncs.com/images/baby.mp4')
|
| 333 |
+
base64_encoded = base64.b64encode(resp.content).decode('utf-8')
|
| 334 |
+
messages = [{'role': 'user', 'content': [
|
| 335 |
+
{'type': 'video', 'video': f'data:video/mp4;base64,{base64_encoded}'},
|
| 336 |
+
{'type': 'text', 'text': 'describe the video'}
|
| 337 |
+
]}]
|
| 338 |
+
infer_request = InferRequest(messages=messages)
|
| 339 |
+
request_config = RequestConfig(max_tokens=512, temperature=0, stream=True)
|
| 340 |
+
gen_list = engine.infer([infer_request], request_config, metrics=[metric])
|
| 341 |
+
print(f'response0: ', end='')
|
| 342 |
+
for chunk in gen_list[0]:
|
| 343 |
+
if chunk is None:
|
| 344 |
+
continue
|
| 345 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 346 |
+
print()
|
| 347 |
+
print(metric.compute())
|
| 348 |
+
```
|
| 349 |
+
|
| 350 |
+
We also provide more deployment demos:
|
| 351 |
+
|
| 352 |
+
- Multiple LoRA deployment and invocation: Refer to [this link](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/lora).
|
| 353 |
+
- Deployment and invocation of the Base model: Refer to [this link](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/client/llm/base).
|
| 354 |
+
- More model types: We provide deployment scripts for [bert](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/bert) and [reward_model](https://github.com/modelscope/ms-swift/tree/main/examples/deploy/reward_model).
|
ms-swift/docs/source_en/Instruction/Megatron-SWIFT-Training.md
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Megatron-SWIFT Training
|
| 3 |
+
|
| 4 |
+
SWIFT incorporates Megatron's parallelization techniques to accelerate the training of large models, including data parallelism, tensor parallelism, pipeline parallelism, sequence parallelism, context parallelism, and expert parallelism. It supports the pre-training and fine-tuning of models such as Qwen3, [Qwen3-MoE](https://github.com/modelscope/ms-swift/blob/main/examples/train/megatron/qwen3_moe.sh), Qwen2.5, Llama3, and the Deepseek-R1 distillation series. For a complete list of supported models, please refer to the [Supported Models and Datasets documentation](./Supported-models-and-datasets.md).
|
| 5 |
+
|
| 6 |
+
## Environment Setup
|
| 7 |
+
|
| 8 |
+
To use Megatron-SWIFT, in addition to installing the `swift` dependencies, you also need to install the following:
|
| 9 |
+
|
| 10 |
+
```shell
|
| 11 |
+
# Recommended PyTorch version: 2.5 / 2.6
|
| 12 |
+
pip install pybind11
|
| 13 |
+
# transformer_engine
|
| 14 |
+
# If an installation error occurs, you can refer to this issue for resolution: https://github.com/modelscope/ms-swift/issues/3793
|
| 15 |
+
pip install git+https://github.com/NVIDIA/TransformerEngine.git@stable
|
| 16 |
+
|
| 17 |
+
# apex
|
| 18 |
+
git clone https://github.com/NVIDIA/apex
|
| 19 |
+
cd apex
|
| 20 |
+
pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" ./
|
| 21 |
+
|
| 22 |
+
# megatron-core
|
| 23 |
+
pip install git+https://github.com/NVIDIA/Megatron-LM.git@core_r0.12.0
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Alternatively, you can also use the image:
|
| 27 |
+
```
|
| 28 |
+
modelscope-registry.cn-hangzhou.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.4.0-py311-torch2.6.0-vllm0.8.3-modelscope1.25.0-swift3.3.0.post1
|
| 29 |
+
modelscope-registry.us-west-1.cr.aliyuncs.com/modelscope-repo/modelscope:ubuntu22.04-cuda12.4.0-py311-torch2.6.0-vllm0.8.3-modelscope1.25.0-swift3.3.0.post1
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
The training module in the dependent library Megatron-LM will be cloned and installed by swift via `git clone`. Alternatively, you can use the environment variable `MEGATRON_LM_PATH` to point to the path of an already downloaded repository (in offline environments, use the [core_r0.12.0 branch](https://github.com/NVIDIA/Megatron-LM/tree/core_r0.12.0)).
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
## Quick Start Example
|
| 36 |
+
|
| 37 |
+
This section introduces a quick start example for fine-tuning the self-awareness of the Qwen2.5-7B-Instruct model using two 80GiB A100 GPUs. The following best practices can be completed within 10 minutes.
|
| 38 |
+
|
| 39 |
+
First, we need to convert the weights from HF (Hugging Face) format to Megatron format:
|
| 40 |
+
|
| 41 |
+
```shell
|
| 42 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 43 |
+
swift export \
|
| 44 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 45 |
+
--to_mcore true \
|
| 46 |
+
--torch_dtype bfloat16 \
|
| 47 |
+
--output_dir Qwen2.5-7B-Instruct-mcore
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Next, use the following script to start training. The required GPU memory resources are 2*80GiB:
|
| 51 |
+
|
| 52 |
+
```shell
|
| 53 |
+
NPROC_PER_NODE=2 \
|
| 54 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 55 |
+
megatron sft \
|
| 56 |
+
--load Qwen2.5-7B-Instruct-mcore \
|
| 57 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 58 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 59 |
+
'swift/self-cognition#500' \
|
| 60 |
+
--tensor_model_parallel_size 2 \
|
| 61 |
+
--micro_batch_size 4 \
|
| 62 |
+
--global_batch_size 16 \
|
| 63 |
+
--recompute_granularity selective \
|
| 64 |
+
--train_iters 100 \
|
| 65 |
+
--eval_iters 5 \
|
| 66 |
+
--finetune true \
|
| 67 |
+
--cross_entropy_loss_fusion true \
|
| 68 |
+
--lr 1e-5 \
|
| 69 |
+
--lr_warmup_iters 10 \
|
| 70 |
+
--min_lr 1e-6 \
|
| 71 |
+
--save megatron_output/Qwen2.5-7B-Instruct \
|
| 72 |
+
--save_interval 100 \
|
| 73 |
+
--max_length 2048 \
|
| 74 |
+
--system 'You are a helpful assistant.' \
|
| 75 |
+
--num_workers 4 \
|
| 76 |
+
--no_save_optim true \
|
| 77 |
+
--no_save_rng true \
|
| 78 |
+
--dataset_num_proc 4 \
|
| 79 |
+
--model_author swift \
|
| 80 |
+
--model_name swift-robot
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
Finally, convert the Megatron format weights back to HF format:
|
| 84 |
+
|
| 85 |
+
```shell
|
| 86 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 87 |
+
swift export \
|
| 88 |
+
--mcore_model megatron_output/Qwen2.5-7B-Instruct/vx-xxx \
|
| 89 |
+
--to_hf true \
|
| 90 |
+
--torch_dtype bfloat16 \
|
| 91 |
+
--output_dir megatron_output/Qwen2.5-7B-Instruct/vx-xxx-hf
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
We then perform inference on the generated HF format weights:
|
| 95 |
+
|
| 96 |
+
```shell
|
| 97 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 98 |
+
swift infer \
|
| 99 |
+
--model megatron_output/Qwen2.5-7B-Instruct/vx-xxx-hf \
|
| 100 |
+
--stream true \
|
| 101 |
+
--temperature 0 \
|
| 102 |
+
--max_new_tokens 2048
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
The inference results are as follows:
|
| 106 |
+
|
| 107 |
+
```
|
| 108 |
+
<<< who are you?
|
| 109 |
+
I am a language model developed by swift, you can call me swift-robot. How can I assist you?
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
- For pretraining, you can use `megatron pt` instead of `megatron sft`, which will use a generative template for training.
|
| 113 |
+
- **More examples**: Including packing, multi-node training, 32K context, MoE models, and pre-training, can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/megatron).
|
| 114 |
+
|
| 115 |
+
## Benchmark
|
| 116 |
+
The speed comparison of full-parameter training for Dense/MoE models using `megatron sft` and `swift sft` on a single machine with eight A800 GPUs is shown below. The corresponding scripts can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/megatron/benchmark).
|
| 117 |
+
|
| 118 |
+
**Dense** Qwen2.5-14B:
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
| | Megatron-LM | Deepspeed-ZeRO2 | Deepspeed-ZeRO3 |
|
| 122 |
+
| ---------------- | ----------- | --------------- | --------------- |
|
| 123 |
+
| Training Speed | 9.04s/it | 10.32s/it | 10.56s/it |
|
| 124 |
+
| GPU Memory Usage | 8\*64GB | 8\*80GB | 8\*58GB |
|
| 125 |
+
|
| 126 |
+
**MoE** Qwen1.5-MoE-A2.7B:
|
| 127 |
+
|
| 128 |
+
| | Megatron-LM | Deepspeed-ZeRO2 | Deepspeed-ZeRO3 |
|
| 129 |
+
| ---------------- | ----------- | --------------- | --------------- |
|
| 130 |
+
| Training Speed | 2.93s/it | 6.02s/it | 24.30s/it |
|
| 131 |
+
| GPU Memory Usage | 8\*66GB | 8\*72GB | 8\*50GB |
|
| 132 |
+
|
| 133 |
+
## Command Line Arguments
|
| 134 |
+
|
| 135 |
+
### Megatron Parameters
|
| 136 |
+
|
| 137 |
+
**Training Parameters**:
|
| 138 |
+
|
| 139 |
+
- 🔥micro_batch_size: Batch size per device, default is 1.
|
| 140 |
+
- 🔥global_batch_size: Total batch size, equivalent to `micro_batch_size * data parallel size * gradient accumulation steps`. Default is 16.
|
| 141 |
+
- 🔥recompute_granularity: Granularity of activation recomputation, options are 'full', 'selective'. 'full' means recomputing the entire transformer layer, while 'selective' means only recomputing the core attention part of the transformer layer. 'selective' is generally recommended. Default is 'selective'.
|
| 142 |
+
- 🔥recompute_method: This parameter takes effect only when recompute_granularity is set to 'full', options are 'uniform', 'block'. Default is None.
|
| 143 |
+
- 🔥recompute_num_layers: This parameter takes effect only when recompute_granularity is set to 'full'. Default is None. If `recompute_method` is set to uniform, this parameter specifies the number of transformer layers in each uniformly divided recomputation unit. For example, you can specify `--recompute_granularity full --recompute_method uniform --recompute_num_layers 4`. The larger the recompute_num_layers, the smaller the memory usage but higher computation cost. Default is None.
|
| 144 |
+
- recompute_modules: Options include "core_attn", "moe_act", "layernorm", "mla_up_proj", "mlp", and "moe". The default value is `["core_attn"]`. For example, during MoE training, you can reduce memory usage by specifying `--recompute_granularity selective --recompute_modules core_attn moe`. Among these, "core_attn", "mlp", and "moe" use normal checkpointing, while "moe_act", "layernorm", and "mla_up_proj" use output-discarding checkpointing.
|
| 145 |
+
- "core_attn": Recomputes the core attention part of the Transformer layer.
|
| 146 |
+
- "mlp": Recomputes the dense MLP layer.
|
| 147 |
+
- "moe": Recomputes the MoE layer.
|
| 148 |
+
- "moe_act": Recomputes the MLP activation function part in the MoE module.
|
| 149 |
+
- "layernorm": Recomputes the input_layernorm and pre_mlp_layernorm.
|
| 150 |
+
- "mla_up_proj": Recomputes the MLA up-projection and RoPE application parts.
|
| 151 |
+
- deterministic_mode: Deterministic mode, which may lead to slower training speed, default is False.
|
| 152 |
+
- 🔥train_iters: Total number of training iterations, default is None.
|
| 153 |
+
- 🔥log_interval: Log interval (unit: iters), default is 5.
|
| 154 |
+
- tensorboard_dir: Directory where TensorBoard logs are written. Default is None, meaning logs will be stored in the `f'{save}/runs'` directory.
|
| 155 |
+
- no_masked_softmax_fusion: Default is False. Disables scaling, masking, and softmax fusion for query_key_value.
|
| 156 |
+
- no_bias_dropout_fusion: Default is False. Disables bias and dropout fusion.
|
| 157 |
+
- no_bias_swiglu_fusion: Default is False. Specify `--no_bias_dropout_fusion true` to disable bias and swiglu fusion.
|
| 158 |
+
- no_rope_fusion: Default is False. Specify `--no_rope_fusion true` to disable rope fusion.
|
| 159 |
+
- no_gradient_accumulation_fusion: Default is False. Specify `--no_gradient_accumulation_fusion true` to disable gradient accumulation fusion.
|
| 160 |
+
- 🔥cross_entropy_loss_fusion: Enables cross-entropy loss calculation fusion. Default is False.
|
| 161 |
+
- calculate_per_token_loss: Scales the cross-entropy loss according to the number of non-padded tokens in the global batch. Default is True.
|
| 162 |
+
- 🔥attention_backend: The attention backend to use (flash, fused, unfused, local, auto). Defaults to auto.
|
| 163 |
+
- optimizer: Optimizer type, options are 'adam', 'sgd'. Default is adam.
|
| 164 |
+
- dataloader_type: Default is 'cyclic', options are 'single', 'cyclic', 'external'. If `--streaming` is enabled, set it to external.
|
| 165 |
+
- manual_gc: Disables the default garbage collector and manually triggers garbage collection. Default is False.
|
| 166 |
+
- manual_gc_interval: Interval at which garbage collection is triggered. Default is 0.
|
| 167 |
+
- seed: Random seed for python, numpy, pytorch, and cuda, default is 42.
|
| 168 |
+
- 🔥num_workers: Number of workers for the dataloader, default is 4.
|
| 169 |
+
- Note: If `--streaming true` is set, it will be set to 1.
|
| 170 |
+
seq_length: Defaults to None, meaning it is set to `max_length`. To restrict the dataset length, please use the `--max_length` parameter in the basic arguments; there is no need to set this parameter.
|
| 171 |
+
- use_cpu_initialization: Initializes weights on the CPU, default is False. Used during HF and MCore weight conversion.
|
| 172 |
+
- no_create_attention_mask_in_dataloader: Does not create an attention mask in the dataloader, default is True.
|
| 173 |
+
|
| 174 |
+
**Learning Rate Parameters**:
|
| 175 |
+
|
| 176 |
+
- 🔥lr: Initial learning rate, which will ultimately determine the learning rate for each iteration based on the warm-up and decay strategy, default is 1e-5.
|
| 177 |
+
- lr_decay_style: Learning rate decay strategy, default is 'cosine'. Commonly set to 'cosine', 'linear', or 'constant'.
|
| 178 |
+
- 🔥lr_decay_iters: Number of iterations for learning rate decay. Default is None, meaning it will be set to `--train_iters`.
|
| 179 |
+
- 🔥lr_warmup_iters: Number of iterations for linear learning rate warm-up, default is 0.
|
| 180 |
+
- 🔥min_lr: Minimum value of the learning rate, clipping any learning rate below this threshold to this value, default is 0.
|
| 181 |
+
|
| 182 |
+
**Regularization Parameters**:
|
| 183 |
+
|
| 184 |
+
- 🔥weight_decay: Default is 0.1.
|
| 185 |
+
- 🔥clip_grad: L2 gradient clipping, default is 1.0.
|
| 186 |
+
- adam_beta1: Default is 0.9.
|
| 187 |
+
- adam_beta2: Default is 0.95.
|
| 188 |
+
- adam_eps: Default is 1e-8.
|
| 189 |
+
- sgd_momentum: Default is 0.9.
|
| 190 |
+
|
| 191 |
+
**Checkpoint Parameters**:
|
| 192 |
+
|
| 193 |
+
- 🔥save: Output directory for checkpoints, default is None. During training, if this parameter is not set, it defaults to `f'megatron_output/{model_suffix}'`, e.g., `'megatron_output/Qwen2.5-7B-Instruct'`.
|
| 194 |
+
- Note: When training on multiple machines, ensure that the save paths on each node point to the same location. Otherwise, you will need to manually consolidate these weights after training.
|
| 195 |
+
- 🔥save_interval: Checkpoint saving interval (steps), default is 500.
|
| 196 |
+
- Note: Weights will always be saved at the end of training.
|
| 197 |
+
- 🔥no_save_optim: Do not save optimizer, default is False.
|
| 198 |
+
- 🔥no_save_rng: Do not save RNG, default is False.
|
| 199 |
+
- 🔥load: Directory of the checkpoint to load, default is None.
|
| 200 |
+
- 🔥no_load_optim: Do not load optimizer, default is False.
|
| 201 |
+
- 🔥no_load_rng: Do not load RNG, default is False.
|
| 202 |
+
- 🔥finetune: Load the model and fine-tune. Does not load the optimizer and random seed states from the checkpoint and resets the iteration count to 0. Default is False.
|
| 203 |
+
- ckpt_format: Format of the checkpoint. Options are 'torch', 'torch_dist', 'zarr'. Default is 'torch_dist'.
|
| 204 |
+
- no_initialization: Do not initialize weights, default is True.
|
| 205 |
+
- auto_detect_ckpt_format: Automatically detect whether the checkpoint format is legacy or distributed. Default is True.
|
| 206 |
+
- exit_on_missing_checkpoint: If `--load` is set but no checkpoint is found, exit directly instead of initializing. Default is True.
|
| 207 |
+
|
| 208 |
+
**Distributed Parameters**:
|
| 209 |
+
|
| 210 |
+
- distributed_backend: Distributed backend, options are 'nccl', 'gloo'. Default is nccl.
|
| 211 |
+
- 🔥use_distributed_optimizer: Use a distributed optimizer. Default is True.
|
| 212 |
+
- 🔥tensor_model_parallel_size: TP (Tensor Parallelism) size, default is 1.
|
| 213 |
+
- 🔥pipeline_model_parallel_size: PP (Pipeline Parallelism) size, default is 1.
|
| 214 |
+
- decoder_first_pipeline_num_layers: The number of Transformer layers in the first pipeline stage of the decoder. Default is None, which means the Transformer layers are evenly distributed across all pipeline stages.
|
| 215 |
+
- decoder_last_pipeline_num_layers: The number of Transformer layers in the last pipeline stage of the decoder. Default is None, which means the Transformer layers are evenly distributed across all pipeline stages.
|
| 216 |
+
- 🔥sequence_parallel: Enable sequence parallel optimization. Default is False.
|
| 217 |
+
- 🔥context_parallel_size: CP (Context Parallelism) size, default is 1.
|
| 218 |
+
- tp_comm_overlap: Overlap tensor parallel communication with GEMM (General Matrix Multiplication) kernels (to reduce communication time). Default is False.
|
| 219 |
+
- overlap_grad_reduce: Overlap grad reduction operations in DDP (to reduce DP communication time). Default is False.
|
| 220 |
+
- overlap_param_gather: Overlap all-gather of parameters in the distributed optimizer (to reduce DP communication time). Default is False.
|
| 221 |
+
- distributed_timeout_minutes: Timeout duration for torch.distributed (in minutes), default is 60 minutes.
|
| 222 |
+
|
| 223 |
+
**Logging Parameters**:
|
| 224 |
+
|
| 225 |
+
- log_params_norm: Logs the norm of parameters. Default is False.
|
| 226 |
+
- log_throughput: Logs throughput per GPU. Default is True.
|
| 227 |
+
- Note: In non-packing scenarios, log_throughput is not accurate because `seq_length` does not equal the actual sequence length.
|
| 228 |
+
- tensorboard_log_interval: Interval (steps) for logging to TensorBoard, default is 1.
|
| 229 |
+
- tensorboard_queue_size: Queue length (related to disk I/O), similar to write intervals. Default is 50.
|
| 230 |
+
- log_timers_to_tensorboard: Logs timers to TensorBoard. Default is True.
|
| 231 |
+
- no_log_learning_rate_to_tensorboard: Do not log learning rate to TensorBoard. Default is False.
|
| 232 |
+
- log_validation_ppl_to_tensorboard: Writes validation perplexity to TensorBoard. Default is True.
|
| 233 |
+
- log_memory_to_tensorboard: Writes memory logs to TensorBoard. Default is True.
|
| 234 |
+
- logging_level: Logging level. Default is None.
|
| 235 |
+
- wandb_project: The name of the wandb project. Defaults to '', which means ignoring wandb.
|
| 236 |
+
- wandb_exp_name: The name of the wandb experiment. Defaults to ''.
|
| 237 |
+
- wandb_save_dir: The local path to save wandb results. Defaults to ''.
|
| 238 |
+
|
| 239 |
+
**Evaluation Parameters**:
|
| 240 |
+
|
| 241 |
+
- 🔥eval_iters: Number of evaluation iterations, default is 100.
|
| 242 |
+
- 🔥eval_interval: Evaluation interval (steps), default is None, meaning it will be set to save_interval.
|
| 243 |
+
|
| 244 |
+
**Mixed Precision Parameters**:
|
| 245 |
+
|
| 246 |
+
- fp16: FP16 mode. The default is None, and it will be set according to the model's torch_dtype. The torch_dtype is read from the config.json by default.
|
| 247 |
+
- bf16: BF16 mode. The default is None, and it will be set according to the model's torch_dtype.
|
| 248 |
+
- apply_query_key_layer_scaling: Scales `Q * K^T` by `1 / layer number` (e.g., divide by layer_num for layer_num-th layer). This is helpful for FP16 training. Default is None, meaning that if `--fp16` is used, it will be set to True.
|
| 249 |
+
- attention_softmax_in_fp32: Uses FP32 for computations in attention_mask and softmax. Default is True.
|
| 250 |
+
|
| 251 |
+
**Model Parameters**: (The following parameters typically do not need to be set as they will be configured based on the HF model’s config.json; users don’t need to worry about them)
|
| 252 |
+
|
| 253 |
+
- num_layers: Number of transformer layers, default is None.
|
| 254 |
+
- hidden_size: Transformer hidden size, default is None.
|
| 255 |
+
- ffn_hidden_size: Hidden size of the FFN layer in the transformer. Default is None, set to `4*hidden_size`.
|
| 256 |
+
- num_attention_heads: Number of transformer attention heads, default is None.
|
| 257 |
+
- group_query_attention: Default is None. If `num_query_groups > 1`, group_query_attention is set to True, otherwise False.
|
| 258 |
+
- num_query_groups: Default is 1.
|
| 259 |
+
- max_position_embeddings: Maximum length of positional embeddings, default is None.
|
| 260 |
+
- position_embedding_type: Type of positional embedding, options are 'learned_absolute', 'rope', 'relative', and 'none'. Default is 'rope'.
|
| 261 |
+
- rotary_base: Default is 10000.
|
| 262 |
+
- rotary_percent: Default is 1.
|
| 263 |
+
- normalization: Options are 'LayerNorm', 'RMSNorm'. Default is RMSNorm.
|
| 264 |
+
- norm_epsilon: Default is 1e-5.
|
| 265 |
+
- swiglu: Uses swiglu instead of the default gelu. Default is True.
|
| 266 |
+
- untie_embeddings_and_output_weights: Unties embedding and output weights. Default is True.
|
| 267 |
+
- disable_bias_linear: Disables bias in linear layers. Default is True.
|
| 268 |
+
- add_qkv_bias: Adds bias only to QKV linear layers. Default is True.
|
| 269 |
+
- attention_dropout: Default is 0.
|
| 270 |
+
- hidden_dropout: Default is 0.
|
| 271 |
+
- kv_channels: Defaults to None, set to `args.hidden_size // args.num_attention_heads`.
|
| 272 |
+
- qk_layernorm: Whether to apply layer normalization to Q and K.
|
| 273 |
+
- transformer_impl: Which transformer implementation to use, options are 'local' and 'transformer_engine'. Default is transformer_engine.
|
| 274 |
+
- padded_vocab_size: Full vocabulary size, default is None.
|
| 275 |
+
- rope_scaling: Related parameters for rope_scaling, default is None. Refer to the format in [llama3.1 config.json](https://modelscope.cn/models/LLM-Research/Meta-Llama-3.1-8B-Instruct/file/view/master?fileName=config.json&status=1). Pass the value as a JSON string.
|
| 276 |
+
- model_type: The model_type in the config.json of the Huggingface model weights.
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
**MoE Parameters**:
|
| 280 |
+
|
| 281 |
+
- num_experts: The number of experts in MoE, default is None. Automatically read from config.json.
|
| 282 |
+
- moe_ffn_hidden_size: The hidden layer size of the feed-forward network (ffn) for each expert. Default is None, set to ffn_hidden_size. Automatically read from config.json.
|
| 283 |
+
- moe_shared_expert_intermediate_size: The total FFN hidden layer size for shared experts. If there are multiple shared experts, it should equal `num_shared_experts * ffn_size_of_each_shared_expert`. Default is None. Automatically read from config.json.
|
| 284 |
+
- moe_router_topk: The number of experts each token is routed to. Default is None. Automatically read from config.json.
|
| 285 |
+
- moe_router_pre_softmax: Enable pre-softmax routing for MoE, meaning that softmax will be applied before top-k selection. Default is None. Automatically read from config.json.
|
| 286 |
+
- 🔥moe_aux_loss_coeff: Scaling coefficient for the auxiliary loss: the recommended initial value is 1e-2. Default is None. Automatically read from config.json.
|
| 287 |
+
- 🔥expert_model_parallel_size: The degree of expert parallelism, default is 1.
|
| 288 |
+
- moe_token_dispatcher_type: The type of token dispatcher to use. Options include 'allgather', 'alltoall', and 'alltoall_seq'. Default is 'alltoall'.
|
| 289 |
+
- moe_grouped_gemm: When each rank contains multiple experts, improve utilization and performance by launching multiple local GEMM kernels across multiple streams using GroupedLinear in TransformerEngine. Default is False.
|
| 290 |
+
- moe_router_load_balancing_type: Determines the load balancing strategy for the router. Options are "aux_loss", "seq_aux_loss", "sinkhorn", "none". Default is "aux_loss".
|
| 291 |
+
- moe_z_loss_coeff: Scaling coefficient for z-loss. Default is None.
|
| 292 |
+
- moe_expert_capacity_factor: Capacity factor for each expert, None means no tokens will be dropped. Default is None.
|
| 293 |
+
- moe_shared_expert_overlap: Enable overlapping of shared expert computation with scheduler communication. If this option is not enabled, shared experts will execute after the routing experts. Only effective when `moe_shared_expert_intermediate_size` is set. Default is False.
|
| 294 |
+
|
| 295 |
+
### Megatron Training Parameters
|
| 296 |
+
|
| 297 |
+
Megatron training parameters inherit from Megatron parameters and basic parameters. For information on basic parameters, see [here](./Command-line-parameters.md#base-arguments). Additionally, the following parameters are included:
|
| 298 |
+
|
| 299 |
+
- add_version: Adds a directory `<version>-<timestamp>` to `save` to prevent overwriting weights, default is True.
|
| 300 |
+
- 🔥packing: Whether to use sequence packing, defaults to False.
|
| 301 |
+
- 🔥streaming: Stream reading and processing of the dataset, default is False. It is typically set to True when handling large datasets. For more information on streaming parameters, refer to the command-line parameters documentation.
|
| 302 |
+
- lazy_tokenize: Default is False. If this parameter is set to False, all dataset samples are tokenized before training (this avoids errors during training); if set to True, tokenization occurs during training (this saves memory).
|
| 303 |
+
- dataloader_persistent_workers: A parameter passed directly to the dataloader, with a default value of True.
|
| 304 |
+
- dataloader_prefetch_factor: A parameter passed directly to the dataloader, with a default value of 10.
|
| 305 |
+
- max_epochs: Forces the training to exit after reaching `max_epochs`, and performs validation and saving of the model weights. This parameter is especially useful when using a streaming dataset. Default is None.
|
ms-swift/docs/source_en/Instruction/RLHF.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RLHF
|
| 2 |
+
|
| 3 |
+
This document provides training scripts for various human preference alignment algorithms. If you want to learn more about the algorithms and how to choose them, please refer to the [documentation](https://github.com/modelscope/modelscope-classroom/blob/main/LLM-tutorial/M.%E4%BA%BA%E7%B1%BB%E5%81%8F%E5%A5%BD%E5%AF%B9%E9%BD%90%E8%AE%AD%E7%BB%83.md).
|
| 4 |
+
|
| 5 |
+
## Dataset
|
| 6 |
+
The data required by the PPO and GRPO algorithm consists solely of model inputs, which include the system prompt (optional) and the query. In the case of the GRPO algorithm, the reward function may require additional data columns. For example, to calculate accuracy, a `solution` column is needed as a reference answer.
|
| 7 |
+
|
| 8 |
+
For RM and DPO-type algorithms such as ORPO, CPO, and SimPO, $(x,y_w,y_l)$ formatted data is required, where $x$ is the model input, $y_w$ is the preferred answer that aligns with human preferences, and $y_l$ is the rejected answer that does not align with human preferences, as shown in .
|
| 9 |
+
|
| 10 |
+
In contrast, the KTO algorithm has a special data format that only requires $(x,y,\text{label})$, where $x$ is the model input, $y$ is the model output, and the label indicates whether the answer aligns with human preferences, as shown in .
|
| 11 |
+
|
| 12 |
+
For RLHF training of text models or multimodal large models using a custom dataset, you can refer to the [custom dataset documentation](../Customization/Custom-dataset.md#rlhf).
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
## GRPO
|
| 16 |
+
[Paper on arXiv](https://arxiv.org/abs/2402.03300)
|
| 17 |
+
|
| 18 |
+
Reference the training script [here](./GRPO.md).
|
| 19 |
+
|
| 20 |
+
## DPO
|
| 21 |
+
[Paper on arXiv](https://arxiv.org/abs/2305.18290)
|
| 22 |
+
|
| 23 |
+
Hyperparameters:
|
| 24 |
+
|
| 25 |
+
- beta: KL regularization coefficient. A larger value imposes a stronger penalty for deviation from the reference model. Default is 0.1.
|
| 26 |
+
|
| 27 |
+
It is recommended to perform SFT training on the preferred answers from the preference dataset before starting DPO training to ensure the data meets the distribution requirements of the DPO algorithm.
|
| 28 |
+
We also mixed SFT loss into the DPO loss for stable training. You can adjust the coefficient of SFT loss with the hyperparameter `rpo_alpha`, which defaults to `1.`.
|
| 29 |
+
|
| 30 |
+
Reference the training script [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf/dpo.sh).
|
| 31 |
+
|
| 32 |
+
## RM
|
| 33 |
+
[Paper on arXiv](https://arxiv.org/abs/2203.02155)
|
| 34 |
+
|
| 35 |
+
Reward Modeling stage in RLHF.
|
| 36 |
+
|
| 37 |
+
Use the base model or instruct model trained with SFT as the foundation model. Add a value head and train it using the preference dataset to create the reward model.
|
| 38 |
+
|
| 39 |
+
The weights of the added value head will be saved in `value_head.safetensors` or `value_head.bin`.
|
| 40 |
+
|
| 41 |
+
Reference the training script [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf/rm.sh).
|
| 42 |
+
|
| 43 |
+
## PPO
|
| 44 |
+
[Paper on arXiv](https://arxiv.org/abs/2203.02155)
|
| 45 |
+
|
| 46 |
+
PPO (proximal policy optimization) stage in RLHF involves four models:
|
| 47 |
+
- model: The training model, either the base model or the instruct model trained with SFT.
|
| 48 |
+
- ref_model: The reference model, which defaults to the model.
|
| 49 |
+
- reward_model: The reward model obtained from the RM stage.
|
| 50 |
+
- value_model: The value model initialized by the reward model, updated synchronously during training.
|
| 51 |
+
|
| 52 |
+
Hyperparameters:
|
| 53 |
+
|
| 54 |
+
- local_rollout_forward_batch_size: Batch size for each data sample, default is 64.
|
| 55 |
+
- whiten_rewards: Normalize rewards, default is False.
|
| 56 |
+
- kl_coef: Coefficient for the KL divergence term, default is 0.05.
|
| 57 |
+
- cliprange: Clip range in the PPO policy loss function, default is 0.2.
|
| 58 |
+
- vf_coef: Coefficient for the value loss function, default is 0.1.
|
| 59 |
+
- cliprange_value: Clip range in the PPO value loss function, default is 0.2.
|
| 60 |
+
- gamma: Discount factor for cumulative rewards, default is 1.0.
|
| 61 |
+
- lam: Lambda coefficient in [GAE](https://arxiv.org/abs/1506.02438), default is 0.95.
|
| 62 |
+
- num_sample_generations: Number of debugging samples generated during training, default is 10.
|
| 63 |
+
|
| 64 |
+
Note: When training the base model, perform SFT first and then proceed to RLHF. Specify the chat template, and it is recommended to use `full` for sft_type.
|
| 65 |
+
|
| 66 |
+
Refer to the [documentation](https://huggingface.co/docs/trl/ppov2_trainer#explanation-of-the-logged-metrics) for metric explanations during training.
|
| 67 |
+
|
| 68 |
+
## KTO
|
| 69 |
+
[Paper on arXiv](https://arxiv.org/abs/2402.01306)
|
| 70 |
+
|
| 71 |
+
Hyperparameters:
|
| 72 |
+
|
| 73 |
+
- beta: KL regularization coefficient. A larger value leads to a greater penalty for deviation from the reference model. Default is 0.1.
|
| 74 |
+
- desirable_weight: The $\lambda_D$ term in the loss function represents the loss weight for the preferred response samples, with a default value of 1.0.
|
| 75 |
+
- undesirable_weight: The $\lambda_U$ term in the loss function represents the loss weight for rejected samples, with a default value of 1.0.
|
| 76 |
+
|
| 77 |
+
Let $n_D$ and $n_U$ represent the number of preferred and rejected samples in the dataset, respectively. For hyperparameters $\lambda_D$ and $\lambda_U$, the authors recommend setting $\frac{\lambda_D n_D}{\lambda_U n_U} \in [1, \frac{4}{3}]$.
|
| 78 |
+
|
| 79 |
+
Training script:
|
| 80 |
+
Train using data in the $(x,y,\text{label})$ format.
|
| 81 |
+
|
| 82 |
+
Reference the training script [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf/kto.sh).
|
| 83 |
+
|
| 84 |
+
## CPO
|
| 85 |
+
[Paper on arXiv](https://arxiv.org/abs/2401.08417)
|
| 86 |
+
|
| 87 |
+
Hyperparameters:
|
| 88 |
+
|
| 89 |
+
- beta: Coefficient before the implicit reward, default is 0.1.
|
| 90 |
+
- cpo_alpha: Coefficient for NLL loss, default is 1.0.
|
| 91 |
+
|
| 92 |
+
Reference the training script [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf/cpo.sh).
|
| 93 |
+
|
| 94 |
+
## ORPO
|
| 95 |
+
[Paper on arXiv](https://arxiv.org/abs/2403.07691)
|
| 96 |
+
|
| 97 |
+
Hyperparameters:
|
| 98 |
+
|
| 99 |
+
- lambda: Odds Ratio loss coefficient.
|
| 100 |
+
|
| 101 |
+
Note: ORPO uses the parameter `--beta` to pass the hyperparameter `lambda`.
|
| 102 |
+
|
| 103 |
+
Reference the training script [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf/orpo.sh).
|
| 104 |
+
|
| 105 |
+
## SimPO
|
| 106 |
+
[Paper on arXiv](https://arxiv.org/abs/2405.14734)
|
| 107 |
+
|
| 108 |
+
Hyperparameters:
|
| 109 |
+
|
| 110 |
+
- beta: Coefficient before the implicit reward, default is 2.0.
|
| 111 |
+
- simpo_gamma: Reward margin term, default is 1.0.
|
| 112 |
+
- cpo_alpha: The mixed CPO NLL loss for improving training stability; defaults to 1.0, set to 0.0 to use the original SimPO algorithm.
|
| 113 |
+
|
| 114 |
+
Reference the training script [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rlhf/simpo.sh).
|
ms-swift/docs/source_en/Instruction/Reinforced-Fine-tuning.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reinforced Fine-Tuning
|
| 2 |
+
|
| 3 |
+
Reinforced fine-tuning is one of the most important functionalities in current model training, with various implementations. SWIFT has already supported the atomic capabilities required for reinforced fine-tuning, such as sampling, reinforcement learning, and fine-tuning. Currently, we provide a specific example of rejection sampling fine-tuning, which can be found [here](https://github.com/modelscope/ms-swift/tree/main/examples/train/rft/rft.py).
|
| 4 |
+
|
| 5 |
+
## Concept of Reinforced Fine-Tuning
|
| 6 |
+
|
| 7 |
+
The concept of reinforced fine-tuning has been proposed since 2022 (or even earlier). Its general workflow typically includes the following steps:
|
| 8 |
+
|
| 9 |
+
1. Generate data using a specific model or augment the original dataset.
|
| 10 |
+
2. Train the target model using the generated data.
|
| 11 |
+
3. Repeat the above process if necessary.
|
| 12 |
+
|
| 13 |
+
**Step 1:**
|
| 14 |
+
|
| 15 |
+
- If the data-generating model is a larger model, such as GPT, Qwen-Max, DeepSeek-V3/R1, etc., this process can be understood as distillation.
|
| 16 |
+
- If the data-generating model is the same model being trained, this can be considered self-improvement fine-tuning.
|
| 17 |
+
- If the sampling process involves sampling a batch, fitting the data with KL divergence and rewards, and iterating continuously, it can be classified as on-policy algorithms like PPO or GRPO.
|
| 18 |
+
- Sampling algorithms include Monte Carlo sampling, do_sample, group beam search, DVTS, etc.
|
| 19 |
+
- The sampling process can incorporate ORM (Outcome Reward Model), PRM (Process Reward Model), diversity filtering, language filtering, etc.
|
| 20 |
+
|
| 21 |
+
**Step 2:**
|
| 22 |
+
|
| 23 |
+
- If SFT (Supervised Fine-Tuning) is used, it is referred to as rejection sampling fine-tuning.
|
| 24 |
+
- If reinforcement learning is used, it is called reinforcement learning fine-tuning.
|
| 25 |
+
|
| 26 |
+
**Step 3:**
|
| 27 |
+
|
| 28 |
+
- If distillation is performed using a larger model (e.g., Monte Carlo sampling distillation with a larger model), the process usually does not involve iterations.
|
| 29 |
+
- If the same model is used for sampling or algorithms like PPO are applied, iterations are typically included.
|
| 30 |
+
|
| 31 |
+
In general, the common approaches to reinforced fine-tuning include:
|
| 32 |
+
|
| 33 |
+
1. **Distillation**: Sampling high-quality data in bulk from a larger model using methods like Monte Carlo or do_sample, and training a smaller model on this data.
|
| 34 |
+
2. **Self-improvement**: Sampling a portion of high-quality data from the same model, filtering it, and training the model iteratively.
|
| 35 |
+
3. **On-policy RL**: Using methods like PPO or GRPO for iterative training.
|
| 36 |
+
|
| 37 |
+
The sampling process is usually much more time-consuming than the training process. If data is distilled using GPT or other large models, token costs must be considered. Thus, reinforced fine-tuning is generally a supplementary mechanism for fine-tuning, except for special cases like DeepSeek-R1.
|
| 38 |
+
|
| 39 |
+
DeepSeek-R1 uses the GRPO algorithm to enable the emergence of CoT (Chain-of-Thought) capabilities from scratch in a base model. This method requires large-scale cluster support and sufficiently large models for capability emergence. This is not discussed in detail here, but more information can be found in the [paper analysis](https://zhuanlan.zhihu.com/p/19714987272).
|
| 40 |
+
|
| 41 |
+
Some related papers on reinforced fine-tuning:
|
| 42 |
+
|
| 43 |
+
- Rejection Sampling Fine-Tuning: https://arxiv.org/pdf/2308.01825
|
| 44 |
+
- ReST: https://arxiv.org/pdf/2308.08998
|
| 45 |
+
- B-STAR: https://arxiv.org/pdf/2412.17256
|
| 46 |
+
- DeepSeekMath: https://arxiv.org/pdf/2402.03300
|
| 47 |
+
- Qwen-Math-PRM: https://arxiv.org/pdf/2501.07301
|
| 48 |
+
- DeepSeek-R1: https://github.com/deepseek-ai/DeepSeek-R1/tree/main
|
| 49 |
+
|
| 50 |
+
## When to Use Reinforced Fine-Tuning
|
| 51 |
+
|
| 52 |
+
Since LLaMA3, we have observed a very noticeable yet rarely mentioned phenomenon: when training an Instruct model using a CoT-enabled training dataset and evaluating it on the corresponding test set, the test set performance tends to degrade. For example, training `llama3.1-8b-instruct` on the GSM8K training set and evaluating the generated checkpoint on the test set reveals performance degradation.
|
| 53 |
+
|
| 54 |
+
This phenomenon mainly arises from the issue of knowledge forgetting disaster in models. During fine-tuning by model manufacturers, a significant amount of CoT data is often included. When solving mathematical tasks, the model's capability often originates not from the math dataset itself but potentially from datasets like ARC. This inference is supported by [some works](https://zhuanlan.zhihu.com/p/19269451950). Continued training on general tasks disrupts the model's existing capabilities, leading to performance degradation.
|
| 55 |
+
|
| 56 |
+
However, it is always correct to prioritize fine-tuning. Fine-tuning allows the model to quickly adapt to the dataset distribution at a low cost. Reinforced fine-tuning should be used under the following conditions:
|
| 57 |
+
|
| 58 |
+
1. The model has already been fine-tuned but does not meet the requirements.
|
| 59 |
+
2. Stronger CoT capabilities are needed.
|
| 60 |
+
3. Base model training for general capabilities is necessary, and the original dataset no longer improves performance.
|
| 61 |
+
4. The output results for corresponding queries can be relatively accurately evaluated, such as tasks with clear results (math, code) or clear processes (translation, style fitting).
|
| 62 |
+
|
| 63 |
+
Reinforced fine-tuning heavily depends on the accuracy of reward evaluations. If the evaluations are inaccurate, the training may oscillate without progress or even degrade the model performance.
|
| 64 |
+
|
| 65 |
+
## SWIFT Implementation
|
| 66 |
+
|
| 67 |
+
SWIFT supports the `sample` command, which is used for model sampling. Currently supported sampling methods include:
|
| 68 |
+
|
| 69 |
+
- **do_sample**: A sampling method for open-source models; future updates will include support for model distillation.
|
| 70 |
+
- URL sampling will also be supported in the future for large-model distillation.
|
| 71 |
+
|
| 72 |
+
- **mcts**: Monte Carlo sampling, currently under review, with future support planned.
|
| 73 |
+
- **dvts**: Currently under investigation.
|
| 74 |
+
|
| 75 |
+
We have provided a general [RFT script](https://github.com/modelscope/ms-swift/tree/main/examples/train/rft/rft.py). This script supports self-improvement training and allows dynamic adjustments of sampling temperature, PRM thresholds, and other hyperparameters. The training method is flexible (e.g., fine-tuning, DPO) and supports iterative retraining of the original model or continued training from the previous iteration, even loading all training states from the previous iteration. Developers can incorporate additional data filtering (e.g., ensuring rows with the same ID come from the same query), including diversity checks, language filtering, etc.
|
| 76 |
+
|
| 77 |
+
## Experimental Results
|
| 78 |
+
|
| 79 |
+
We used the RFT script to train and evaluate the `competition_math` dataset in the math domain. The results are as follows:
|
| 80 |
+
|
| 81 |
+
| Model | MATH Score | Training Method | Iterations | Post-Training MATH Score |
|
| 82 |
+
|----------------------------|------------|-----------------|------------|---------------------------|
|
| 83 |
+
| LLaMA3.1_8b | 12.0 | SFT | 3 | 25.2 (LLaMA3.1_8b_sft) |
|
| 84 |
+
| LLaMA3.1_8b_sft | 25.2 | RFT | 2 | 32.4 |
|
| 85 |
+
| LLaMA3.1_8b_instruct | 52.2 | SFT | 2 | 39.0 |
|
| 86 |
+
| LLaMA3.1_8b_instruct | 52.2 | RFT | 3 | 58 |
|
| 87 |
+
| Qwen2.5_math_7b_instruct | 79.6 | RFT | 2 | 83.2 |
|
| 88 |
+
|
| 89 |
+
As shown, applying SFT to the `competition_math` dataset resulted in significant performance degradation for the instruct model. However, RFT improved the model's capabilities, even for the state-of-the-art `Qwen2.5_math_7b_instruct` math model.
|
| 90 |
+
|
| 91 |
+
Specifically, we tested the GSM8K metric for `Qwen2.5_math_7b_instruct`:
|
| 92 |
+
|
| 93 |
+
| Model | GSM8K Score | Post-RFT GSM8K Score |
|
| 94 |
+
|----------------------------|-------------|-----------------------|
|
| 95 |
+
| Qwen2.5_math_7b_instruct | 92.8 | 91.6 |
|
| 96 |
+
|
| 97 |
+
As shown, RFT training did not significantly change the GSM8K score, avoiding the previously mentioned performance degradation phenomenon.
|
| 98 |
+
|
| 99 |
+
## Future Roadmap
|
| 100 |
+
|
| 101 |
+
1. More sampling methods,MCTS for example
|
| 102 |
+
2. Distill from super huge model
|
| 103 |
+
3. On policy RFT like PPO
|
ms-swift/docs/source_en/Instruction/Sample.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sampling
|
| 2 |
+
|
| 3 |
+
Sampling is one of the newly supported key capabilities of SWIFT. This feature can be understood as the practical implementation of `test-time compute`. Additionally, this capability is crucial for the implementation of RFT (Reinforcement Fine-Tuning).
|
| 4 |
+
|
| 5 |
+
## Capability Introduction
|
| 6 |
+
|
| 7 |
+
The sampling capability of SWIFT can be demonstrated with the following example:
|
| 8 |
+
|
| 9 |
+
```shell
|
| 10 |
+
swift sample --model LLM-Research/Meta-Llama-3.1-8B-Instruct --sampler_engine pt --num_return_sequences 5 --dataset AI-ModelScope/alpaca-gpt4-data-zh#5
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
A `jsonl` file with a timestamp as the filename will be generated in the `sample_output` directory of the current folder. This file should contain 25 lines, each representing a complete `messages` format data.
|
| 14 |
+
|
| 15 |
+
For a list of sampling parameters, please refer to [here](Command-line-parameters.md).
|
| 16 |
+
|
| 17 |
+
## Environment Setup
|
| 18 |
+
|
| 19 |
+
```shell
|
| 20 |
+
pip install ms-swift[llm] -U
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Or install swift from source:
|
| 24 |
+
|
| 25 |
+
```shell
|
| 26 |
+
git clone https://github.com/modelscope/ms-swift.git
|
| 27 |
+
cd ms-swift
|
| 28 |
+
pip install -e '.[llm]'
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## Using PRM and ORM for Result Filtering
|
| 32 |
+
|
| 33 |
+
An important capability of sampling is supervising the process and results, which can be supported by setting additional parameters.
|
| 34 |
+
|
| 35 |
+
```shell
|
| 36 |
+
swift sample --model LLM-Research/Meta-Llama-3.1-8B-Instruct --sampler_engine lmdeploy --num_return_sequences 5 --n_best_to_keep 2 --dataset tastelikefeet/competition_math#5 --prm_model AI-ModelScope/GRM-llama3.2-3B-rewardmodel-ft --orm_model math
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
A `jsonl` file with a timestamp as the filename will be generated in the `sample_output` directory of the current folder. This file **will contain at most** 10 lines, each representing a complete `messages` format data.
|
| 40 |
+
> The reason it contains at most 10 lines is that although 5 data points are processed in total, and 2 are kept for each data point (`n_best_to_keep`), ORM may fail some validations, and failed data will not be retained in the file.
|
| 41 |
+
> Additionally, after adding `--prm_model` or `--orm_model`, the file format is slightly different and includes a `rejected_response` key, which contains the responses with the lowest PRM scores.
|
| 42 |
+
|
| 43 |
+
## Customizing PRM or ORM
|
| 44 |
+
|
| 45 |
+
PRM and ORM can be customized by adding a new implementation in the plugin according to the existing code. For example:
|
| 46 |
+
|
| 47 |
+
```python
|
| 48 |
+
class CustomPRM:
|
| 49 |
+
|
| 50 |
+
# The constructor should be parameterless
|
| 51 |
+
def __init__(self):
|
| 52 |
+
# Initialize here
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
def __call__(self, infer_requests: List[InferRequest], ground_truths: List[str], **kwargs) -> List[Union[float, List[float]]]:
|
| 56 |
+
...
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
prms = {'custom': CustomPRM}
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
Afterward, use `--prm_model custom` in the command line.
|
| 63 |
+
|
| 64 |
+
## Memory Control
|
| 65 |
+
|
| 66 |
+
If the sampled model and PRM are loaded into memory simultaneously, it may lead to an OOM (Out of Memory) issue. To address this, sampling can be divided into two stages:
|
| 67 |
+
|
| 68 |
+
- **Stage 1**: Specify `--model` and `--sampler_engine` without specifying `--orm_model` and `--prm_model`. Perform sampling only and save the results to a file.
|
| 69 |
+
- **Stage 2**: Specify `--sampler_engine no`, along with `--orm_model` and `--prm_model`, and also specify `--cache_files`. Perform only RM data filtering without re-sampling.
|
| 70 |
+
|
| 71 |
+
By dividing the process into two stages, only one model is loaded at a time, avoiding OOM issues.
|
| 72 |
+
|
| 73 |
+
## Practical Example
|
| 74 |
+
|
| 75 |
+
Please refer to the [Reinforcement Fine-Tuning Script](https://github.com/modelscope/ms-swift/tree/main/examples/train/rft/rft.py). This script provides a practical example of using sampling for reinforcement fine-tuning.
|
| 76 |
+
|
| 77 |
+
> **Note:** The actual effectiveness of this script is strongly related to the quality of the model, data, and RM. Therefore, it is presented only as an example. Users should modify this script and train their own RM and generator models accordingly.
|
| 78 |
+
|
| 79 |
+
## Sampling From Large Model
|
| 80 |
+
|
| 81 |
+
SWIFT's sample supports using the OpenAI API to distill data with large models. Example:
|
| 82 |
+
|
| 83 |
+
```shell
|
| 84 |
+
OPENAI_API_KEY="your_api_key" \
|
| 85 |
+
swift sample \
|
| 86 |
+
--sampler_type distill \
|
| 87 |
+
--sampler_engine client \
|
| 88 |
+
--model deepseek-r1 \
|
| 89 |
+
--stream true \
|
| 90 |
+
--dataset tastelikefeet/competition_math#5 \
|
| 91 |
+
--num_return_sequences 1 \
|
| 92 |
+
--temperature 0.6 \
|
| 93 |
+
--top_p 0.95 \
|
| 94 |
+
--engine_kwargs '{"base_url":"https://dashscope.aliyuncs.com/compatible-mode/v1"}'
|
| 95 |
+
```
|
| 96 |
+
In this example:
|
| 97 |
+
|
| 98 |
+
`base_url` and `model` represent the API endpoint and model name, respectively. `stream` indicates the stream parameter for the request.
|
| 99 |
+
|
| 100 |
+
Note: For Deepseek-R1 series models, the output will be formatted as:`<thinking>{reasoning_content}</thinking>\n\n<answer>{content}</answer>`.
|
ms-swift/docs/source_en/Instruction/Supported-models-and-datasets.md
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
ms-swift/docs/source_en/_templates/autosummary/class.rst
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. currentmodule:: {{ module }}
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
{{ name | underline}}
|
| 5 |
+
|
| 6 |
+
.. autoclass:: {{ name }}
|
| 7 |
+
:inherited-members:
|
| 8 |
+
:members:
|
| 9 |
+
|
| 10 |
+
.. autogenerated from source/_templates/autosummary/class.rst
|
ms-swift/docs/source_en/_templates/sobolengine.rst
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. currentmodule:: {{ module }}
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
{{ name | underline}}
|
| 5 |
+
|
| 6 |
+
.. autoclass:: {{ name }}
|
| 7 |
+
:members:
|
| 8 |
+
:exclude-members: MAXBIT, MAXDIM
|
| 9 |
+
:undoc-members:
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
..
|
| 13 |
+
autogenerated from source/_templates/sobolengine.rst
|
| 14 |
+
note it has specific options
|
ms-swift/examples/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Instructions
|
| 2 |
+
|
| 3 |
+
The example provides instructions for using SWIFT for training, inference, deployment, evaluation, and quantization. By default, the model will be downloaded from the ModelScope community.
|
| 4 |
+
|
| 5 |
+
If you want to use the Huggingface community, you can change the command line like this:
|
| 6 |
+
|
| 7 |
+
```shell
|
| 8 |
+
...
|
| 9 |
+
swift sft \
|
| 10 |
+
--model <model_id_or_path> \
|
| 11 |
+
--use_hf 1 \
|
| 12 |
+
...
|
| 13 |
+
```
|
ms-swift/examples/app/base_url/demo.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 5 |
+
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
from swift.llm import AppArguments, app_main, DeployArguments, run_deploy
|
| 8 |
+
# Here's a runnable demo provided.
|
| 9 |
+
# In a real scenario, you can simply remove the deployed context.
|
| 10 |
+
with run_deploy(
|
| 11 |
+
DeployArguments(model='Qwen/Qwen2.5-1.5B-Instruct', verbose=False, log_interval=-1, infer_backend='vllm'),
|
| 12 |
+
return_url=True) as url:
|
| 13 |
+
app_main(AppArguments(model='Qwen2.5-1.5B-Instruct', base_url=url, stream=True, max_new_tokens=2048))
|
ms-swift/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
|
ms-swift/examples/custom/dataset.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
from typing import Any, Dict, Optional
|
| 3 |
+
|
| 4 |
+
from swift.llm 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]}')
|
ms-swift/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 pt \
|
| 7 |
+
--max_batch_size 16 \
|
| 8 |
+
--max_new_tokens 256 \
|
| 9 |
+
--temperature 0
|
ms-swift/examples/custom/model.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
from swift.llm import (InferRequest, Model, ModelGroup, ModelMeta, PtEngine, RequestConfig, TemplateMeta,
|
| 3 |
+
get_model_tokenizer_with_flash_attn, register_model, register_template)
|
| 4 |
+
|
| 5 |
+
register_template(
|
| 6 |
+
TemplateMeta(
|
| 7 |
+
template_type='custom',
|
| 8 |
+
prefix=['<extra_id_0>System\n{{SYSTEM}}\n'],
|
| 9 |
+
prompt=['<extra_id_1>User\n{{QUERY}}\n<extra_id_1>Assistant\n'],
|
| 10 |
+
chat_sep=['\n']))
|
| 11 |
+
|
| 12 |
+
register_model(
|
| 13 |
+
ModelMeta(
|
| 14 |
+
model_type='custom',
|
| 15 |
+
model_groups=[
|
| 16 |
+
ModelGroup([Model('AI-ModelScope/Nemotron-Mini-4B-Instruct', 'nvidia/Nemotron-Mini-4B-Instruct')])
|
| 17 |
+
],
|
| 18 |
+
template='custom',
|
| 19 |
+
get_function=get_model_tokenizer_with_flash_attn,
|
| 20 |
+
ignore_patterns=['nemo']))
|
| 21 |
+
|
| 22 |
+
if __name__ == '__main__':
|
| 23 |
+
infer_request = InferRequest(messages=[{'role': 'user', 'content': 'who are you?'}])
|
| 24 |
+
request_config = RequestConfig(max_tokens=512, temperature=0)
|
| 25 |
+
engine = PtEngine('AI-ModelScope/Nemotron-Mini-4B-Instruct')
|
| 26 |
+
response = engine.infer([infer_request], request_config)
|
| 27 |
+
swift_response = response[0].choices[0].message.content
|
| 28 |
+
|
| 29 |
+
engine.default_template.template_backend = 'jinja'
|
| 30 |
+
response = engine.infer([infer_request], request_config)
|
| 31 |
+
jinja_response = response[0].choices[0].message.content
|
| 32 |
+
assert swift_response == jinja_response, (f'swift_response: {swift_response}\njinja_response: {jinja_response}')
|
| 33 |
+
print(f'response: {swift_response}')
|
ms-swift/examples/deploy/agent/client.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
|
| 6 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_infer_request():
|
| 10 |
+
messages = [{'role': 'user', 'content': "How's the weather in Beijing today?"}]
|
| 11 |
+
tools = [{
|
| 12 |
+
'name': 'get_current_weather',
|
| 13 |
+
'description': 'Get the current weather in a given location',
|
| 14 |
+
'parameters': {
|
| 15 |
+
'type': 'object',
|
| 16 |
+
'properties': {
|
| 17 |
+
'location': {
|
| 18 |
+
'type': 'string',
|
| 19 |
+
'description': 'The city and state, e.g. San Francisco, CA'
|
| 20 |
+
},
|
| 21 |
+
'unit': {
|
| 22 |
+
'type': 'string',
|
| 23 |
+
'enum': ['celsius', 'fahrenheit']
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
'required': ['location']
|
| 27 |
+
}
|
| 28 |
+
}]
|
| 29 |
+
return messages, tools
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def infer(client, model: str, messages, tools):
|
| 33 |
+
messages = messages.copy()
|
| 34 |
+
query = messages[0]['content']
|
| 35 |
+
resp = client.chat.completions.create(model=model, messages=messages, tools=tools, max_tokens=512, temperature=0)
|
| 36 |
+
response = resp.choices[0].message.content
|
| 37 |
+
print(f'query: {query}')
|
| 38 |
+
print(f'response: {response}')
|
| 39 |
+
print(f'tool_calls: {resp.choices[0].message.tool_calls}')
|
| 40 |
+
|
| 41 |
+
tool = '{"temperature": 32, "condition": "Sunny", "humidity": 50}'
|
| 42 |
+
print(f'tool_response: {tool}')
|
| 43 |
+
messages += [{'role': 'assistant', 'content': response}, {'role': 'tool', 'content': tool}]
|
| 44 |
+
resp = client.chat.completions.create(model=model, messages=messages, tools=tools, max_tokens=512, temperature=0)
|
| 45 |
+
response2 = resp.choices[0].message.content
|
| 46 |
+
print(f'response2: {response2}')
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# streaming
|
| 50 |
+
def infer_stream(client, model: str, messages, tools):
|
| 51 |
+
messages = messages.copy()
|
| 52 |
+
query = messages[0]['content']
|
| 53 |
+
gen = client.chat.completions.create(
|
| 54 |
+
model=model, messages=messages, tools=tools, max_tokens=512, temperature=0, stream=True)
|
| 55 |
+
response = ''
|
| 56 |
+
print(f'query: {query}\nresponse: ', end='')
|
| 57 |
+
for chunk in gen:
|
| 58 |
+
delta = chunk.choices[0].delta.content
|
| 59 |
+
response += delta
|
| 60 |
+
print(delta, end='', flush=True)
|
| 61 |
+
print()
|
| 62 |
+
print(f'tool_calls: {chunk.choices[0].delta.tool_calls}')
|
| 63 |
+
|
| 64 |
+
tool = '{"temperature": 32, "condition": "Sunny", "humidity": 50}'
|
| 65 |
+
print(f'tool_response: {tool}')
|
| 66 |
+
messages += [{'role': 'assistant', 'content': response}, {'role': 'tool', 'content': tool}]
|
| 67 |
+
gen = client.chat.completions.create(
|
| 68 |
+
model=model, messages=messages, tools=tools, max_tokens=512, temperature=0, stream=True)
|
| 69 |
+
print(f'query: {query}\nresponse2: ', end='')
|
| 70 |
+
for chunk in gen:
|
| 71 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 72 |
+
print()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == '__main__':
|
| 76 |
+
host: str = '127.0.0.1'
|
| 77 |
+
port: int = 8000
|
| 78 |
+
client = OpenAI(
|
| 79 |
+
api_key='EMPTY',
|
| 80 |
+
base_url=f'http://{host}:{port}/v1',
|
| 81 |
+
)
|
| 82 |
+
model = client.models.list().data[0].id
|
| 83 |
+
print(f'model: {model}')
|
| 84 |
+
|
| 85 |
+
messages, tools = get_infer_request()
|
| 86 |
+
infer(client, model, messages, tools)
|
| 87 |
+
infer_stream(client, model, messages, tools)
|
ms-swift/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 |
+
--gpu_memory_utilization 0.9 \
|
| 5 |
+
--max_model_len 8192 \
|
| 6 |
+
--max_new_tokens 2048 \
|
| 7 |
+
--agent_template hermes \
|
| 8 |
+
--served_model_name Qwen2.5-7B-Instruct
|
ms-swift/examples/deploy/bert/client.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
from swift.llm 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 |
+
])
|
ms-swift/examples/deploy/client/llm/chat/openai_client.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from openai import OpenAI
|
| 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 |
+
print(chunk.choices[0].delta.content, end='', flush=True)
|
| 24 |
+
print()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def run_client(host: str = '127.0.0.1', port: int = 8000):
|
| 28 |
+
client = OpenAI(
|
| 29 |
+
api_key='EMPTY',
|
| 30 |
+
base_url=f'http://{host}:{port}/v1',
|
| 31 |
+
)
|
| 32 |
+
model = client.models.list().data[0].id
|
| 33 |
+
print(f'model: {model}')
|
| 34 |
+
|
| 35 |
+
query = 'Where is the capital of Zhejiang?'
|
| 36 |
+
messages = [{'role': 'user', 'content': query}]
|
| 37 |
+
response = infer(client, model, messages)
|
| 38 |
+
messages.append({'role': 'assistant', 'content': response})
|
| 39 |
+
messages.append({'role': 'user', 'content': 'What delicious food is there?'})
|
| 40 |
+
infer_stream(client, model, messages)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
from swift.llm import run_deploy, DeployArguments
|
| 45 |
+
with run_deploy(DeployArguments(model='Qwen/Qwen2.5-1.5B-Instruct', verbose=False, log_interval=-1)) as port:
|
| 46 |
+
run_client(port=port)
|
ms-swift/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
|
ms-swift/examples/deploy/reward_model/client.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
from swift.llm 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}')
|
ms-swift/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 pt
|
ms-swift/examples/deploy/server/demo.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 |
+
# }'
|
ms-swift/examples/eval/eval_url/demo.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 5 |
+
|
| 6 |
+
if __name__ == '__main__':
|
| 7 |
+
from swift.llm import EvalArguments, eval_main, run_deploy, DeployArguments
|
| 8 |
+
# Here's a runnable demo provided. Use the eval_url method for evaluation.
|
| 9 |
+
# In a real scenario, you can simply remove the deployed context.
|
| 10 |
+
print(EvalArguments.list_eval_dataset())
|
| 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 |
+
eval_main(EvalArguments(model='Qwen2.5-1.5B-Instruct', eval_url=url, eval_dataset=['arc']))
|
ms-swift/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
|
ms-swift/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 |
+
--train_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_datasets "gsm8k" \
|
| 23 |
+
--eval_datasets_args '{"gsm8k": {"few_shot_num": 0}}' \
|
| 24 |
+
--eval_limit "10"
|
ms-swift/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-VL-2B-Instruct \
|
| 5 |
+
--infer_backend vllm \
|
| 6 |
+
--eval_limit 100 \
|
| 7 |
+
--eval_dataset realWorldQA \
|
| 8 |
+
--eval_backend VLMEvalKit
|
ms-swift/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
|
ms-swift/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
|
ms-swift/examples/export/quantize/awq.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 2 |
+
swift export \
|
| 3 |
+
--model Qwen/Qwen2.5-72B-Instruct \
|
| 4 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 5 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 6 |
+
--device_map cpu \
|
| 7 |
+
--quant_n_samples 256 \
|
| 8 |
+
--quant_batch_size 1 \
|
| 9 |
+
--max_length 2048 \
|
| 10 |
+
--quant_method awq \
|
| 11 |
+
--quant_bits 4 \
|
| 12 |
+
--output_dir Qwen2.5-72B-Instruct-AWQ
|
ms-swift/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
|
ms-swift/examples/export/quantize/bert/gptq.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# gptq quantize
|
| 8 |
+
CUDA_VISIBLE_DEVICES=0 swift export \
|
| 9 |
+
--model output/swift_test_bert_merged \
|
| 10 |
+
--load_data_args true \
|
| 11 |
+
--output_dir output/swift_test_bert_gptq_int4 \
|
| 12 |
+
--quant_bits 4 \
|
| 13 |
+
--quant_method gptq \
|
| 14 |
+
--max_length 512
|
| 15 |
+
|
| 16 |
+
# infer
|
| 17 |
+
CUDA_VISIBLE_DEVICES=0 swift infer \
|
| 18 |
+
--model output/swift_test_bert_gptq_int4
|
ms-swift/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
|
ms-swift/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
|
ms-swift/examples/export/quantize/mllm/awq.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip uninstall autoawq
|
| 2 |
+
pip install git+https://github.com/casper-hansen/AutoAWQ.git --no-deps # or "autoawq>=0.2.9"
|
| 3 |
+
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 5 |
+
MAX_PIXELS=1003520 \
|
| 6 |
+
VIDEO_MAX_PIXELS=50176 \
|
| 7 |
+
FPS_MAX_FRAMES=12 \
|
| 8 |
+
swift export \
|
| 9 |
+
--model Qwen/Qwen2.5-VL-3B-Instruct \
|
| 10 |
+
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
|
| 11 |
+
'AI-ModelScope/alpaca-gpt4-data-en#500' \
|
| 12 |
+
'modelscope/coco_2014_caption:validation#500' \
|
| 13 |
+
'swift/VideoChatGPT:Generic#500' \
|
| 14 |
+
--quant_n_samples 256 \
|
| 15 |
+
--quant_batch_size -1 \
|
| 16 |
+
--max_length 2048 \
|
| 17 |
+
--quant_method awq \
|
| 18 |
+
--quant_bits 4 \
|
| 19 |
+
--output_dir Qwen2.5-VL-3B-Instruct-AWQ
|
ms-swift/examples/export/quantize/moe/awq.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pip uninstall autoawq
|
| 2 |
+
pip install git+https://github.com/casper-hansen/AutoAWQ.git --no-deps # or "autoawq>=0.2.9"
|
| 3 |
+
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 5 |
+
swift export \
|
| 6 |
+
--model Qwen/Qwen3-30B-A3B \
|
| 7 |
+
--dataset 'swift/Qwen3-SFT-Mixin' \
|
| 8 |
+
--device_map auto \
|
| 9 |
+
--quant_n_samples 64 \
|
| 10 |
+
--quant_batch_size -1 \
|
| 11 |
+
--max_length 8192 \
|
| 12 |
+
--quant_method awq \
|
| 13 |
+
--quant_bits 4 \
|
| 14 |
+
--output_dir Qwen3-30B-A3B-AWQ
|
ms-swift/examples/infer/demo_reward_model.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
| 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.llm import InferEngine, InferRequest, PtEngine, load_dataset
|
| 16 |
+
model = 'Shanghai_AI_Laboratory/internlm2-1_8b-reward'
|
| 17 |
+
engine = PtEngine(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)])
|
ms-swift/examples/infer/lmdeploy/ddp.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NPROC_PER_NODE=2 \
|
| 2 |
+
CUDA_VISIBLE_DEVICES=0,1 \
|
| 3 |
+
swift infer \
|
| 4 |
+
--model Qwen/Qwen2.5-7B-Instruct \
|
| 5 |
+
--infer_backend lmdeploy \
|
| 6 |
+
--val_dataset AI-ModelScope/alpaca-gpt4-data-zh#1000 \
|
| 7 |
+
--max_new_tokens 2048
|
ms-swift/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 |
+
--tp 2 \
|
| 7 |
+
--vision_batch_size 8 \
|
| 8 |
+
--max_new_tokens 2048
|
ms-swift/examples/infer/pt/lora.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 |
+
# To disable this behavior, please set `--load_args false`.
|
| 4 |
+
CUDA_VISIBLE_DEVICES=0 \
|
| 5 |
+
swift infer \
|
| 6 |
+
--adapters swift/test_lora \
|
| 7 |
+
--infer_backend pt \
|
| 8 |
+
--stream true \
|
| 9 |
+
--temperature 0 \
|
| 10 |
+
--max_new_tokens 2048
|
ms-swift/examples/infer/pt/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 pt \
|
| 7 |
+
--val_dataset AI-ModelScope/LaTeX_OCR#1000 \
|
| 8 |
+
--max_batch_size 16 \
|
| 9 |
+
--max_new_tokens 512
|
ms-swift/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 |
+
--gpu_memory_utilization 0.9 \
|
| 8 |
+
--tensor_parallel_size 2 \
|
| 9 |
+
--max_model_len 32768 \
|
| 10 |
+
--max_new_tokens 2048 \
|
| 11 |
+
--limit_mm_per_prompt '{"image": 5, "video": 2}'
|