Skip to main content
Qwen model tuning

Fine-tune with the API or CLI

Tune Qwen models in Model Studio through the API (HTTP) or CLI (shell). Three tuning methods are supported: supervised fine-tuning (SFT), continual pre-training (CPT), and direct preference optimization (DPO).

Prerequisites

The API supports only token-based billing. To use model training units (prepaid or postpaid), create the job in the console.

Upload tuning files

Preparing fine-tuning files

  • SFT training set
SFT ChatML (Chat Markup Language) format training data supports multi-turn conversations and various role settings.
The OpenAI name and weight parameters are not supported. All assistant outputs will be trained.
# A single line of training data (in JSON format) has the following typical structure when expanded:
{"messages": [
  {"role": "system", "content": "System input 1"},
  {"role": "user", "content": "User input 1"},
  {"role": "assistant", "content": "Expected model output 1"},
  {"role": "user", "content": "User input 2"},
  {"role": "assistant", "content": "Expected model output 2"}
  ...
]}
For information about the differences between system, user, and assistant, see Overview. Sample training datasets: SFT-ChatML_format_example.jsonl, SFT-ChatML_format_example.xlsx. XLS and XLSX formats support only single-turn conversations.All assistant lines in a single training data entry support the "loss_weight" parameter, which sets the relative importance of that line during training. (Range: 0.0 to 1.0. A larger value indicates higher importance.)
This parameter is available for invitational preview. To use it, contact your account manager.
 {"role": "assistant", "content": "Expected model output 1", "loss_weight": 1.0},
 {"role": "assistant", "content": "Expected model output 2", "loss_weight": 0.5}

You can also download a data template from the Model Studio console.

Below the file upload area on the Create Dataset page, you can find the data template download link.

Upload fine-tuning fileto Model Studio

  • OpenAI-compatible Files API
import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    # If you have not configured an environment variable, replace the following line with api_key="sk-xxx" and use your Model Studio API key.
    # API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Singapore region. If you use a service in the China (Beijing) region, replace the URL with: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# test.jsonl is a local sample file.
file_object = client.files.create(file=Path("test.jsonl"), purpose="fine-tune")

print(file_object.model_dump_json())
Limitations:
  • The maximum size of a single file is 300 MB.
  • The total size of all non-deleted files is limited to 5 GB.
  • You can store a maximum of 100 non-deleted files.
  • Files are stored indefinitely.

Model fine-tuning

Create a fine-tuning job

  • HTTP
For Windows CMD, replace ${DASHSCOPE_API_KEY} with %DASHSCOPE_API_KEY%. For PowerShell, use $env:DASHSCOPE_API_KEY.
curl --location "https://dashscope.aliyuncs.com/api/v1/fine-tunes" \
--header "Authorization: Bearer ${DASHSCOPE_API_KEY}" \
--header 'Content-Type: application/json' \
--data '{
    "model":"qwen3-8b",
    "training_file_ids":[
        "<your_training_file_id_1>",
        "<your_training_file_id_2>"
    ],
    "hyper_parameters":
    {
        "n_epochs": 3,
        "batch_size": 16,
        "max_length": 8192,
        "learning_rate": "1.6e-5",
        "lr_scheduler_type": "linear",
        "split": 0.9,
        "warmup_ratio": 0.05,
        "eval_steps": 50,
        "data_augmentation": true,
        "augmentation_ratio": "0.1,0.05,0.15",
        "augmentation_types": "dialogue_CN,general_purpose_CN,NLP",
        "save_strategy": "epoch",
        "save_total_limit": 10
    },
    "training_type":"sft"
}'

Parameters

Parameter

Required

Type

Location

Description

training_file_ids

Yes

Array

Body

A list of file IDs for the training set.

validation_file_ids

No

Array

Body

A list of file IDs for the validation set.

model

Yes

String

Body

Base model ID, or the ID of a previously fine-tuned model.

hyper_parameters

No

Map

Body

Hyperparameters for the fine-tuning job. Default values vary by model; check the console for specifics.

The following parameters are required because they affect training cost: n_epochs, batch_size, and max_length.

training_type

No

String

Body

Fine-tuning method. Valid values:

cpt

sft

efficient_sft

dpo_full

dpo_lora

job_name

No

String

Body

Name of the fine-tuning job.

model_name

No

String

Body

Name of the fine-tuned model (not the system-generated model ID).

Response

{
    "request_id": "635f7047-003e-4be3-b1db-6f98e239f57b",
    "output":
    {
        "job_id": "ft-202511272033-8ae7",
        "job_name": "ft-202511272033-8ae7",
        "status": "PENDING",
        "finetuned_output": "qwen3-8b-ft-202511272033-8ae7",
        "model": "qwen3-8b",
        "base_model": "qwen3-8b",
        "training_file_ids":
        [
            "9e9ffdfa-c3bf-436e-9613-6f053c66aa6e"
        ],
        "validation_file_ids":
        [],
        "hyper_parameters":
        {
            "n_epochs": 3,
            "batch_size": 16,
            "max_length": 8192,
            "learning_rate": "1.6e-5",
            "lr_scheduler_type": "linear",
            "split": 0.9,
            "warmup_ratio": 0.05,
            "eval_steps": 50,
            "data_augmentation": true,
            "augmentation_ratio": "0.1,0.05,0.15",
            "augmentation_types": "dialogue_CN,general_purpose_CN,NLP",
            "save_strategy": "epoch",
            "save_total_limit": 10
        },
        "training_type": "sft",
        "create_time": "2025-11-27 20:33:15",
        "workspace_id": "llm-8v53etv3hwb8orx1",
        "user_identity": "1654290265984853",
        "modifier": "1654290265984853",
        "creator": "1654290265984853",
        "group": "llm",
        "max_output_cnt": 10
    }
}
Supported models
  • Singapore
  • North China 2 (Beijing)
  • Tab
  • Tab
Text generation

Model name

Model code

SFT full-parameter training (sft)

SFT efficient training (efficient_sft)

Qwen3-14B

qwen3-14b

×

Supported

Comparison of tuning methods

Feature

CPT (Continual Pre-training)

SFT (Supervised Fine-tuning)

DPO (Direct Preference Optimization)

Summary

Supplements knowledge (Injects domain knowledge)

Learns to perform tasks (Follows instructions)

Performs tasks better (Aligns with human preferences)

Input data

10 million+ tokens

Unlabeled domain text

Over 1,000 entries

High-quality "question-answer" pairs

100+ sets

"Better-worse" response pairs for the same instruction

Core objective

Domain adaptation. Learns specialized vocabulary and facts.

Teaches the model conversation formats and task execution capabilities.

Makes model outputs better align with human values and preferences.

Learning method

Self-supervised learning (Predicts the next word)

Supervised learning (Imitates the ground truth)

Direct preference learning (Increases the probability of good responses and decreases the probability of bad responses)

Model stage

Typically before SFT

After CPT and before DPO

Typically after SFT, as the final step for alignment.

Comparison of training patterns

Full-parameter training

Efficient training (LoRA, recommended)

Scenarios

• The model needs to acquire new capabilities

• Achieving optimal global performance.

• Optimizing model performance for specific scenarios.

• For cost-sensitive and time-sensitive scenarios.

Training time

Longer, with slower convergence.

Shorter, with faster convergence.

Supported parameters and their default values vary by model. To view specific default values, go to theconsoleand select the model and training method.

Parameter

Recommended setting

Type

Description

n_epochs

(Number of epochs) [Required]

Data size < 10,000: 3–5

Data size > 10,000: 1–2

Integer

How many times the model iterates over the full training set.

More epochs increase training time and cost.

learning_rate

(Learning rate)

Use the recommended default value provided by Model Studio.

Float

Controls the step-size for weight updates during training.

  • Too high: training may diverge.

  • Too low: slow convergence with minimal improvement.

freeze_vit

(Freeze visual backbone)

Adjust as needed

Boolean

Freezes the visual backbone so its weights are not updated during training. Applies only to Qwen-VL models.

Token-based billing is available only when freeze_vit is set to “true”.

batch_size

(Batch size) [Required]

Use the recommended default value provided by Model Studio.

Integer

Number of training examples per iteration. Small values significantly increase training time. Defaults vary by model.

eval_steps

(Evaluation steps)

Adjust as needed

Integer

Step interval for evaluating training accuracy and loss.

Controls how often Validation Loss and Validation Token Accuracy are reported.

logging_steps

(Logging steps)

Adjust as needed

Integer

Step interval for logging training progress.

lr_scheduler_type

(Learning rate scheduler)

Recommended linear/Inverse_sqrt

String

Strategy for adjusting the learning rate during training.

Each strategy is described in Fine-tune a model in the console.

max_length

(Sequence length) [Required]

8192

Integer

Maximum sequence length (in tokens) per training example. Longer examples are discarded.

How to convert between tokens and characters.

max_split_val_dataset_sample

(Max validation set samples)

Use the recommended default value provided by Model Studio.

Integer

When "validation_file_ids" is not set, the validation set that is automatically split by Model Studio contains a maximum of 1,000 entries.

This parameter has no effect when "validation_file_ids" is set.

split

(Training set ratio)

Use the recommended default value provided by Model Studio.

Float

If "validation_file_ids" is not set, Model Studio splits the training file: 80% for training, 20% for validation.

When "validation_file_ids" is set, this parameter has no effect.

warmup_ratio

(Warm-up ratio)

Use the recommended default value provided by Model Studio.

Float

Fraction of training steps used for learning rate warm-up (linear ramp from near-zero to the target rate).

Stabilizes early training by limiting large weight updates.

Too high: resembles a low learning rate with minimal performance change.

Too low: resembles a high learning rate and may degrade performance.

This parameter has no effect if the learning rate scheduler is set to constant.

weight_decay

(Weight decay)

Use the recommended default value provided by Model Studio.

Float

L2 regularization strength. Helps preserve generalization, but excessively high values reduce fine-tuning effectiveness.

Parameters for efficient fine-tuning (supportsefficient_sft and dpo_lora)

When you perform a second round of efficient fine-tuning on a model that has already been efficiently fine-tuned, the lora_rank, lora_alpha, and lora_dropout parameters must remain consistent.

lora_rank

(LoRA rank)

64

Integer

Rank of the LoRA low-rank matrices. Higher ranks can improve results but slightly increase training time.

lora_alpha

(LoRA alpha)

Use the recommended default value provided by Model Studio.

Integer

Scaling factor for combining base model weights with the LoRA correction.

Larger alpha: more weight to task-specific LoRA updates.

Smaller alpha: more retention of base model knowledge.

lora_dropout

(LoRA dropout)

Use the recommended default value provided by Model Studio.

Float

Dropout rate for LoRA low-rank matrices. The default balances generalization; overly large values diminish fine-tuning effectiveness.

Parameters for publishing model parameter snapshots (forefficient_sft and sftonly)

save_strategy

(Snapshot save strategy)

It can be set to epoch or steps.

  • When set to steps, you can adjust the save interval by setting the save_steps parameter.

String

Strategy for saving model parameter snapshots (checkpoints): epoch (after each epoch) or steps (at a specified step interval).

save_steps

(Save steps)

If you need to modify it manually, set it to an integer multiple of the eval_steps parameter.

Integer

Interval, in training steps, between snapshot saves.

save_total_limit

(Snapshot save limit)

10

Integer

Maximum snapshots to retain. Older snapshots are auto-deleted when the limit is reached.

Retrieve a fine-tuning job

Use the job_id from the create response to retrieve job details.
  • HTTP
curl 'https://dashscope.aliyuncs.com/api/v1/fine-tunes/<job_id>' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'

Request parameters

Parameter

Type

Location

Required

Description

job_id

String

Path

Yes

The ID of the fine-tuning job.

Successful response

{
    "request_id": "d100cddb-ac85-4c82-bd5c-9b5421c5e94d",
    "output":
    {
        "job_id": "ft-202511272033-8ae7",
        "job_name": "ft-202511272033-8ae7",
        "status": "RUNNING",
        "finetuned_output": "qwen3-8b-ft-202511272033-8ae7",
        "model": "qwen3-8b",
        "base_model": "qwen3-8b",
        "training_file_ids":
        [
            "9e9ffdfa-c3bf-436e-9613-6f053c66aa6e"
        ],
        "validation_file_ids":
        [],
        "hyper_parameters":
        {
            "n_epochs": 3,
            "batch_size": 16,
            "max_length": 8192,
            "learning_rate": "1.6e-5",
            "lr_scheduler_type": "linear",
            "split": 0.9,
            "warmup_ratio": 0.05,
            "eval_steps": 50,
            "data_augmentation": true,
            "augmentation_ratio": "0.1,0.05,0.15",
            "augmentation_types": "dialogue_CN,general_purpose_CN,NLP",
            "save_strategy": "epoch",
            "save_total_limit": 10
        },
        "training_type": "sft",
        "create_time": "2025-11-27 20:33:15",
        "workspace_id": "llm-8v53etv3hwb8orx1",
        "user_identity": "1654290265984853",
        "modifier": "1654290265984853",
        "creator": "1654290265984853",
        "group": "llm",
        "max_output_cnt": 10
    }
}

Job status

Description

PENDING

The job is waiting to start.

QUEUING

The job is queued. Only one fine-tuning job runs at a time.

RUNNING

The job is running.

CANCELING

The job is being canceled.

SUCCEEDED

The job succeeded.

FAILED

The job failed.

CANCELED

The job was canceled.

After the job succeeds, the finetuned_output field contains the model ID for deployment.

Get fine-tuning job logs

  • HTTP
curl 'https://dashscope.aliyuncs.com/api/v1/fine-tunes/<job_id>/logs?offset=0&line=1000' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'
Use offset (starting line) and line (max lines to return) to paginate log output.
Sample response:
{
    "request_id":"1100d073-4673-47df-aed8-c35b3108e968",
    "output":{
        "total":57,
        "logs":[
            "{Fine-tuning log 1}",
            "{Fine-tuning log 2}",
            ...
            ...
            ...
        ]
    }
}

Query and publish model checkpoints

Only SFT fine-tuning (efficient_sft and sft) supports saving and publishing checkpoints from intermediate training states.

List checkpoints for a fine-tuning job

curl 'https://dashscope.aliyuncs.com/api/v1/fine-tunes/<job_id>/checkpoints' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'
Request parameters

Parameter

Type

Parameter location

Required

Description

job_id

String

Path Parameter

Yes

The ID of the fine-tuning job.

Sample response
The checkpoint field contains the checkpoint ID, which specifies the checkpoint to publish in the Model publishing (optional) API. The model_name field contains the model ID used for model deployment. The finetuned_output field in the original fine-tuning job response is the model_name of the final checkpoint.
{
    "request_id": "c11939b5-efa6-4639-97ae-ed4597984647",
    "output":
    [
        {
            "create_time": "2025-11-11T16:25:42",
            "full_name": "ft-202511272033-8ae7-checkpoint-20",
            "job_id": "ft-202511272033-8ae7",
            "checkpoint": "checkpoint-20",
            "model_name": "qwen3-8b-instruct-ft-202511272033-8ae7",
            "status": "SUCCEEDED"
        }
    ]
}

Status

Description

PENDING

The checkpoint is pending publication. You must publish it using the Model publishing API before you can use it for model deployment and invocation.

PROCESSING

The checkpoint is being published.

SUCCEEDED

The checkpoint has been published successfully. You can now use it for model deployment and invocation.

FAILED

The checkpoint failed to publish.

Model publishing (optional)

After a fine-tuning job completes, export a checkpoint before deploying the model.Exported checkpoints are stored in cloud storage and cannot be downloaded.
curl --request GET 'https://dashscope.aliyuncs.com/api/v1/fine-tunes/<job_id>/export/<checkpoint_id>?model_name=<model_name>' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'
Request parameters

Parameter

Type

Parameter location

Required

Description

job_id

String

Path Parameter

Yes

The ID of the fine-tuning job.

checkpoint_id

String

Path Parameter

Yes

The ID of the checkpoint to publish.

model_name

String

Path Parameter

Yes

The custom model ID to assign to the published model.

Sample response
{
    "request_id": "ed3faa41-6be3-4271-9b83-941b23680537",
    "output": true
}
Publishing is asynchronous. Use the List checkpoints for a fine-tuning job API to monitor status.

More fine-tuning operations

List fine-tuning jobs

curl 'https://dashscope.aliyuncs.com/api/v1/fine-tunes' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'

Cancel a fine-tuning job

Cancels a running fine-tuning job.
curl --request POST 'https://dashscope.aliyuncs.com/api/v1/fine-tunes/<job_id>/cancel' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'

Delete a fine-tuning job

You cannot delete a running fine-tuning job.
curl --request DELETE 'https://dashscope.aliyuncs.com/api/v1/fine-tunes/<job_id>' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY} \
--header 'Content-Type: application/json'

Model deployment and invocation

Model deployment

To deploy the model, go to the model deployment console.

Model invocation

Once deployment status is RUNNING, invoke the fine-tuned model like any other model. You can also get the Model Code from the model deployment console. Usage and parameters: DashScope API Reference.
curl 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Authorization: Bearer '${DASHSCOPE_API_KEY}  \
--header 'Content-Type: application/json' \
--data '{
    "model": "<your_model_instance_id>",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'
Token Plan
Model Playground
  • Music generation
Statistics and Monitoring
Support