Fine-tune models in the console

更新时间:
复制 MD 格式

This topic describes how to run model fine-tuning tasks in the console and helps you choose the right fine-tuning method and parameters. Model fine-tuning includes three training methods: Supervised Fine-Tuning (SFT), Continual Pre-Training (CPT), and Direct Preference Optimization (DPO).

Important

This topic is applicable only to the Chinese Mainland Edition (Beijing region).

Model tuning process

image

Step 1: Select a fine-tuning method

Go to the Model Fine-tuning page and click the Create Training Task button.

image

In the Basic Information section, set the Job Name and Job Priority. Job priority has four levels: L0, L1, L2, and L3, listed from highest to lowest. Priority affects the scheduling order of training jobs. Higher priority means earlier execution.

How to choose between CPT, SFT, and DPO

CPT (Continual Pre-Training) uses large volumes of unlabeled data to improve model performance in specific industries.

SFT (Supervised Fine-Tuning) uses targeted datasets and training to enhance model performance for specific business scenarios.

DPO (Direct Preference Optimization) uses paired positive and negative samples in its training dataset. By incorporating negative feedback, it reduces hallucinations and optimizes specific bad cases.

The three fine-tuning methods in Model Studio are not mutually exclusive; they are progressive and complementary.

CPT (optional) → SFT → DPO (optional)

  1. CPT (continued pre-training) - Adds knowledge. General-purpose models have broad but shallow knowledge and lack the depth and precision required for specialized domains.

    • Financial model: Learns financial terminology

    • Medical model: Memorizes drug and pathology information

    • Legal model: Understands legal articles and case precedents

  2. SFT (supervised fine-tuning) - Learns to perform tasks.

    • Customer service bot: Learns customer service workflows

    • Code assistant: Learns programming paradigms

    • Tool calling (agent): Learns to use MCP

  3. DPO (direct preference optimization) - Refines model behavior.

    • Safety and responsibility: Refuses harmful suggestions

    • Conciseness and effectiveness: Provides clear and direct answers

    • Objectivity and neutrality: Offers fair and impartial evaluations

SFT training set

The SFT training set uses the ChatML (Chat Markup Language) format, which supports multi-turn conversations and various role settings.

The OpenAI parameters name and weight are not supported. All assistant outputs are used for training.
# A typical line of expanded JSON training data:
{"messages": [
  {"role": "system", "content": "System input 1"}, 
  {"role": "user", "content": "User input 1"}, 
  {"role": "assistant", "content": "Desired model output 1"}, 
  {"role": "user", "content": "User input 2"}, 
  {"role": "assistant", "content": "Desired model output 2"}
  ...
]}

For details on the system, user, and assistant roles, see Overview. For training dataset samples, see SFT-ChatML Format Sample.jsonl and SFT-ChatML Format Sample.xlsx. Note that the XLS and XLSX formats support only single-turn conversations.

In a single training example, all assistant messages support the "loss_weight" parameter. This parameter sets the message's relative importance during training. The value ranges from 0.0 to 1.0, where a higher value indicates greater importance.

This is a beta parameter. To use it, please contact your account manager.
 {"role": "assistant", "content": "Desired model output 1", "loss_weight": 1.0}, 
 {"role": "assistant", "content": "Desired model output 2", "loss_weight": 0.5}

SFT thinking model

The training data supports multi-turn conversations and various role settings, but the model trains only on the last assistant output. Each expanded line of training data has the following structure:

The newline characters \n before and after the tag must be preserved.
# A single line of training data (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": "Model output 1"}, --Intermediate assistant outputs must not include <think> tags.
   ...
  {"role": "user", "content": "User input 2"}, 
  {"role": "assistant", "content": "<think>\nDesired thinking content 2\n</think>\n\nDesired output 2"} --Include thinking content only in the final assistant output. 
]}

For details on the system, user, and assistant roles, see Overview. For a training dataset sample, see SFT-Deep Thinking Content Sample.jsonl.

You can also provide training examples without the <think> tag. If you use this method, we do not recommend enabling thinking mode for inference after training.

{"role": "assistant", "content": "Desired model output 2"}  --Instructs the model not to enable thinking.

In a single training example, the final assistant message supports the "loss_weight" parameter. This parameter sets the message's relative importance during training. The value ranges from 0.0 to 1.0, where a higher value indicates greater importance.

This is a beta parameter. To use it, please contact your account manager.
 {"role": "assistant", "content": "<think>\nDesired thinking content 2\n</think>\n\nDesired output 2", "loss_weight": 1.0}

SFT for visual understanding

The OpenAI parameters name and weight are not supported. All assistant outputs are used for training.

For the differences between system, user, and assistant, see Overview. The following is an example of training data in the ChatML format:

If you pass a system message, its content must use the array format [{"text":"..."}]. The string format "content":"string" is not supported.
# A typical line of expanded JSON training data:
{"messages": [
  {"role": "system", "content": [{"text": "System input"}]},
  {"role": "user", "content": [{"text": "User input 1"}, {"image": "image_filename_1.jpg", "resized_width": 200, "resized_height": 200}]},
  {"role": "assistant", "content": [{"text": "Desired model output 1"}]},
  {"role": "user", "content": [{"text": "User input 2"}, {"video": "video_filename_1.mp4", "fps": 3.0, "resized_width": 200, "resized_height": 200, "video_start": 0.0, "video_end": 3.0}]},
  {"role": "assistant", "content": [{"text": "Desired model output 2"}]},
  {"role": "user", "content": [{"text": "User input 2"}, {"video": ["0.jpg", "1.jpg", "2.jpg", "3.jpg"], "sample_fps": 5.0, "resized_width": 200, "resized_height": 200}]},
  {"role": "assistant", "content": [{"text": "Desired model output 2"}]},
  ...
]}

More supported parameters

Parameter

Type

Required

Description

Image file

image

str

Yes

The path to the image file.

resized_width

int

No

The target width of the resized image, in pixels.

resized_height

int

No

The target height of the resized image, in pixels.

Video file - File path mode (Supported on Qwen-VL models qwen3.5 and later)

Example: Aliyun_VL_Video.zip

video

str

Yes

File path mode for videos: {"video": "video_filename_1.mp4"}

resized_width

int

No

The target width of the resized video, in pixels.

resized_height

int

No

The target height of the resized video, in pixels.

fps

float

No

The frame rate for training, in frames per second (FPS). For example, a value of 30 sets the rate to 30 FPS.

video_start

float

No

The start time for video trimming, in seconds.

video_end

float

No

The end time for video trimming, in seconds.

Video file - Image frame list mode (Supported on Qwen-VL models qwen3.5 and later)

video

List[str]

Yes

Image frame list mode for videos: {"video": ["0.jpg", "1.jpg", "2.jpg", ...], "sample_fps": 2.0}

sample_fps

float

No

Specifies the frame rate of the image frames.

resized_width

int

No

The target width of the resized image frames, in pixels.

resized_height

int

No

The target height of the resized image frames, in pixels.

Note

When training a thinking model, also follow the data format requirements for the SFT thinking model.

ZIP file requirements

  1. The ZIP file must be 2 GB or smaller. Folder and file names within it must contain only ASCII letters (a-z, A-Z), digits (0-9), underscores (_), and hyphens (-).

  2. Place the training text file, named data.jsonl, in the root directory of the ZIP file.

  3. Each image must be 10 MB or smaller, with dimensions no greater than 1024x1024 pixels. Supported formats include .bmp, .jpeg/.jpg, .png, .tif/.tiff, or .webp.

  4. Image file names must be unique within the ZIP file, even if they are in different folders.

  5. ZIP file directory structure:

    Single-level directory (recommended)

    Place image and video files in the root directory with the data.jsonl file.

    Trainingdata_vl.zip
       |--- data.jsonl # Note: Do not place this file inside another folder.
       |--- image1.png
       |--- video1.mp4
    Multi-level directory
    1. The data.jsonl file must be in the root directory.

    2. In data.jsonl, you only need to declare the image or video filename, not the file path. For example:

      Correct: image1.jpg; Incorrect: jpg_folder/image1.jpg.

    3. Image and video filenames must be unique across the entire ZIP file.

    Trainingdata_vl.zip
        |--- data.jsonl # Note: Do not place this file inside another folder.
        |--- jpg_folder
        |   └── image1.jpg
        |--- mp4_folder
            └── video.mp4

DPO dataset

The DPO dataset uses the ChatML format. Each expanded line of training data has the following structure:

For details on the system, user, and assistant roles, see Overview. For a training dataset sample, see DPO ChatML Format Sample.jsonl.

# A typical line of expanded JSON training data:
{"messages": [
  {"role": "system", "content": "System input"},
  {"role": "user", "content": "User input 1"},
  {"role": "assistant", "content": "Model output 1"},
  {"role": "user", "content": "User input 2"},
  {"role": "assistant", "content": "Model output 2"},
  {"role": "user", "content": "User input 3"}
 ],
 "chosen":
   {"role": "assistant", "content": "The chosen model output for Input 3"},
 "rejected":
   {"role": "assistant", "content": "The rejected model output for Input 3"}}

The model uses all content within messages as input. DPO then trains the model to prefer the chosen response over the rejected response for the final user input.

To include thinking content, wrap it with the <think> tag:

{"role": "assistant", "content": "<think>Desired model thinking content</think>Desired model output"}

The "chosen" module of a single training data sample supports the "loss_weight" parameter, which sets the relative importance of that sample during training. (The valid range is 0.0 to 1.0, where a larger value indicates higher importance.)

This is a beta parameter. To use it, please contact your account manager.
 "chosen":
   {"role": "assistant", "content": "The chosen model output for Input 3", "loss_weight": 1.0},

CPT training set

The CPT training set uses the plain text format. Each line of training data has the following structure:

{"text":"Text content"}

For a training dataset sample, see CPT-Text Generation Training Set Sample.jsonl.

For data volume requirements of each training method, see Dataset size requirements.

Alibaba Cloud Model Studio recommends using model fine-tuning in this order: CPT (optional) → SFT → DPO:

  1. First, collect a large volume (at least 10 million tokens) of unlabeled domain-specific data and run CPT to turn the model into an expert in your industry or domain.

  2. Before launching your application, collect sufficient (1,000+) positive samples for your specific scenario or business—pairs of inputs and expected model outputs—and run SFT.

  3. After your application launches or enters trial operation, collect sufficient (100+) user feedback (such as likes, dislikes, or direct feedback) or bad cases. Convert this data into a DPO training set and run DPO.

Model selection

If this is your first time fine-tuning a model, select an official model.

If you are retraining a model due to poor performance, select My Models > the model you want to retrain.

After selecting a model, some models display a Training Modality option (such as text generation or visual understanding). Choose the modality that matches your business scenario. If supported, a Thinking Mode option (such as Instruct or Thinking) also appears. Select as needed.

Full-parameter training vs. efficient training

  • Full-parameter training updates all model parameters during learning.

  • Efficient training uses Low-Rank Adaptation (LoRA), which decomposes weight matrices and updates only the low-rank components.

Since both methods cost the same, Alibaba Cloud Model Studio recommends using full-parameter training if your model supports it, because it delivers better results and higher cost-effectiveness than efficient training.

Step 2: Configure hyperparameters

Training parameter descriptions:

Not all models support all parameters. Refer to the console for available options.

Parameter Name

Recommended setting

Function of hyperparameters

Batch size (batch_size)

Use default

Batch size determines how many data samples the model processes before updating its parameters. Common values are 16 or 32. The valid range varies by model and training method. Refer to the console.

image

Learning rate (learning_rate)

Efficient training: ~1e-4

Full-parameter training: ~1e-5

CPT training: ~1e-5

Controls how strongly the model adjusts its weights.

If the learning rate is too high, model parameters change drastically, which may worsen performance.

If the learning rate is too low, performance improves little.

Epochs (n_epochs)

Data volume < 10,000: 3–5 epochs

Data volume > 10,000: 1–2 epochs

Adjust based on experimental results

Number of times the model traverses the training data. Adjust based on your experience.

More epochs mean longer training time and higher cost. Range: [1, 200].

Evaluation steps (eval_steps)

Use default

How often to evaluate the model during training, measured in training steps. Used to track training accuracy and loss.

This parameter controls how frequently Validation Loss and Validation Token Accuracy appear.

Learning rate scheduler (lr_scheduler_type)

Use “linear” or “inverse_sqrt”.

Strategy for dynamically adjusting the learning rate during training.

For details, see Learning rate scheduler types.

Sequence length (max_length)

Set to the maximum value supported by the model

Maximum token length per training sample. If a sample exceeds this length:

SFT discards the entire sample.

DPO truncates tokens beyond the limit and trains on the shortened sample.

For token-to-string conversion, see How to convert between tokens and strings. Range: [500, 32768].

Warmup ratio (warmup_ratio)

Use default

Fraction of total training steps used for learning rate warmup. Warmup starts with a low learning rate and linearly increases to the target value.

This limits parameter changes early in training, improving stability.

A ratio that is too high acts like a low learning rate, yielding little improvement.

A ratio that is too low acts like a high learning rate, potentially degrading performance. Range: [0, 1].

This parameter has no effect with the “constant” scheduler.

Weight decay (weight_decay)

Use default

L2 regularization strength. L2 regularization helps maintain generalization. Too high a value reduces fine-tuning effectiveness. Range: [0, 0.2].

Efficient training parameters

LoRA alpha (lora_alpha)

Use default

Scaling factor that balances original model weights and LoRA low-rank updates.

A higher alpha gives more weight to LoRA updates, making the model rely more on task-specific information.

A lower alpha preserves more of the original pre-trained knowledge.

LoRA dropout (lora_dropout)

Use default

Dropout rate applied to LoRA low-rank matrices during training.

The recommended value improves generalization.

Too high a value reduces fine-tuning effectiveness. Range: [0, 0.2].

LoRA rank (lora_rank)

Set to the maximum value supported by the model

Rank of LoRA low-rank matrices. Higher rank yields slightly better results but slower training.

Freeze ViT (freeze_vit)

Use default

Freezes parameters of the vision backbone network so they do not update during training. Applies only to Qwen-VL (visual understanding) models.

Warning

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

Note

Supported parameters vary by training method:

  • SFT (efficient training): Supports all parameters above.

  • DPO (efficient training): Supports all parameters except “freeze_vit”.

  • CPT (full-parameter training): Supports only batch size, learning rate, epochs, evaluation steps, learning rate scheduler, and sequence length. Does not support LoRA parameters, warmup ratio, or weight decay.

Introduction to learning rate scheduling strategies

Learning rate scheduler” is the first setting under Hyperparameter Configuration > Expand Configuration. It offers eight strategies.

For details, see:

Linear: Learning rate decreases linearly.

Use case: Short training tasks.

plot_linearpng

Polynomial: Learning rate decreases according to a predefined polynomial function over training steps or epochs.

Use case: Polynomial decay offers finer-grained control over the learning rate and is suitable for scenarios involving more complex tasks.

But the built-in polynomial coefficient is 1, making it identical to Linear. Not recommended.

plot_linearpng

Cosine: Learning rate follows a cosine curve.

Use case: Long training tasks requiring fine adjustments.plot_cosine

Cosine_with_restarts: Learning rate follows a cosine curve, resets to the initial value at the end of each cycle, and starts a new cycle.

Use case: Escaping local optima to find better global solutions.

However, testing shows the learning rate does not actually reset at the bottom of the curve. Not recommended.plot_cosine

Constant: Learning rate remains unchanged. “Warmup ratio” has no effect.

Use case: Initial performance exploration.constant

Constant_with_warmup: Learning rate remains constant, but “warmup ratio” applies.

Use case: Initial performance exploration.plot_constant_with_warmup

Inverse_sqrt: Learning rate decreases proportionally to the inverse square root of the training step count.

Use case: SFT fine-tuning. Balances learning efficiency and convergence well.

plot_inverse_sqrt

Reduce_lr_on_plateau: Automatically lowers the learning rate when a monitored metric (validation loss or accuracy) shows no significant improvement over several consecutive epochs.

Use case: When the model struggles to improve further, this strategy helps continue optimization.

plot_reduce_lr_on_plateau

Note

The learning rate floor and minimum values shown in the graphs are illustrative. Actual values depend on your configuration.

Step 3: Select training data

image

For dataset construction tips, see Dataset construction tips. To upload fine-tuning datasets, go to the Data Management page.

In the Data Configuration section, configure the following:

  • Training set: Supports two methods—Dataset Selection and Dataset Mounting. Dataset Selection uses previously uploaded fine-tuning datasets. Dataset Mounting directly mounts data files from OSS.

  • Mixed training: When enabled, you can add an additional mixed training dataset. Mixed training preserves the model’s general capabilities during fine-tuning, preventing it from losing general conversational ability by overfitting to task-specific data. Enable this if you have data from multiple business scenarios.

  • Validation set: Supports Auto Split and Dataset Selection. Auto Split randomly selects 10% of the training data as the validation set. You can also upload a separate validation dataset. The validation set evaluates model performance during training, showing Validation Loss and Validation Token Accuracy.

Step 4: Configure training resources

In the Training Resource Configuration section, select a billing method for the training job.

  • Token-based billing: Uses shared idle resources. Billed by the number of tokens consumed during training. Training speed depends on resource availability and may involve queuing.

Note

For detailed billing information and pricing, see Model fine-tuning overview – Billing.

Step 5: Training output

The following settings apply to SFT, DPO, and CPT training.
Note

After model fine-tuning is complete in Model Studio, you must export a checkpoint. You can then use this checkpoint to deploy the model.

Exported checkpoints are saved to cloud storage and cannot be accessed or downloaded.

Under Model Export, configure:

  • Model Name: Set the name for the output model. After training completes, the final checkpoint is automatically published to My Models under this name.

  • Max Snapshots: Set the maximum number of checkpoints to retain.

  • Checkpoint Interval: Set how often to save checkpoints—by epoch (training cycles) or step (training steps).

  • Model Encryption (Security Upgrade): When enabled, the platform encrypts model files using OSS server-side encryption (SSE-OSS) with fully managed keys. Encryption algorithm: AES256.

Step 6: Train the model

Click Start Training > Confirm the Model Fine-tuning Billing Notice > Training begins.

If you encounter insufficient permissions, see: What to do if you lack permissions for model fine-tuning?

During training, click the Logs button to view real-time training logs. You can also go to the Metrics tab to monitor Training Loss, Validation Loss, or Validation Token Accuracy.

After training completes, check the trend between Training Loss and Validation Loss.

  1. If Training Loss decreases while Validation Loss increases, the model is overfitting. Training likely failed or produced poor results. Apply the following optimizations (in order of recommendation) and retrain:

    1. Use data augmentation to increase data diversity and volume.

    2. Collect more training data to increase diversity and volume.

    3. Adjust hyperparameters: reduce epochs, lower learning rate, decrease batch size, increase weight decay, raise LoRA dropout, or increase warmup ratio.

  2. If Training Loss shows little change or increases (rare), the model is underfitting. Training failed. Apply the following optimizations (in order of recommendation) and continue training:

    1. Check data quality and ensure thorough data cleaning.

    2. Adjust hyperparameters: increase epochs, raise learning rate, increase batch size, decrease weight decay, lower LoRA dropout, or reduce warmup ratio.

  3. If neither issue occurs, proceed to the next steps.

Step 7: Publish the model for deployment

Only SFT fine-tuning supports publishing intermediate model snapshots.

After training completes, the final checkpoint is automatically published to My Models under the name configured in Step 5: Training output.

To publish an intermediate checkpoint, go to the Outputs tab on the training job details page. View the list of saved checkpoints, select your target checkpoint, and click Publish Model.

The Outputs tab shows: Checkpoint ID, save info, publish status, model name, remaining retention time, creation time, and actions.

Note

Checkpoints have a retention period. After expiration, they are automatically deleted and can no longer be published. Publish required snapshots promptly.

Published models appear on the My Models page and can be deployed.

Step 8: Deploy the model

Go to the My Models page to quickly find supported deployment modes, model ID, and other details. After deployment, evaluate your fine-tuned model. For deployment details, see Model deployment.

Step 9: Evaluate the model

Important

If you have multiple business scenarios or used mixed training data, split your evaluation set by scenario and evaluate each scenario separately to verify that fine-tuning meets your requirements.

Use Alibaba Cloud Model Studio’s Model Evaluation feature to assess your custom model’s performance. For details, see Help Center: Model evaluation overview.

FAQ

When should I use model fine-tuning?

  • While fine-tuning text generation models can yield excellent results for specific business scenarios, it has the following limitations:

    • Time-consuming, including: acquiring a large-scale CPT dataset with at least 50 million tokens, building an effective SFT dataset with 1,000+ samples, collecting sufficient bad cases (100+) to build an effective model deployment billing DPO dataset, and slow model optimization and iteration speeds.

    • It is costly. Fine-tuned models must be deployed before use, and model deployment billing can be high.

  • Alibaba Cloud Model Studio recommends that you first try prompt engineering or function calling to customize your application before you consider text generation model fine-tuning. Model fine-tuning is often the "last resort" for improving model performance. This is because:

    1. For many tasks, a model might initially perform poorly, but you can often improve the results with effective prompt techniques, avoiding the need for model fine-tuning.

    2. Iterating on prompts and functions is more agile and less costly than model fine-tuning. This is because model fine-tuning iterations can require re-collecting, cleaning, and optimizing data, gathering bad cases, or even conducting customer research.

    3. Even if you ultimately decide that model fine-tuning is necessary, your initial work on prompt engineering and function calling is not wasted. You can reuse these efforts as input data when building your fine-tuning datasets.

What should I do if I get a permission error during model fine-tuning?

Contact your platform or workspace administrator to verify and grant the following permissions:

  1. Your account must have page permissions for Model Fine-tuning – Operation, Model Deployment – Operation, and Model Evaluation – Operation in the workspace where you run fine-tuning jobs.

    For details, see: Account permission management. Console link: Model Studio – Account Management .

    PixPin_2025-11-13_20-34-22

  2. The workspace where you run fine-tuning jobs must have Model Training (fine-tuning) permissions for the specific model.

    For details, see: Grant sub-workspaces model invocation, training, and deployment permissions. Console link: Model Studio – Workspace Management .

    image

What should I do if evaluation results are poor after fine-tuning?

  1. If using manual evaluation, verify that your evaluation criteria match your business or scenario.

  2. Collect test cases with poor evaluation results, analyze why they failed, and adjust your training dataset accordingly. Then iterate on fine-tuning.

  3. Generate DPO examples from poorly evaluated cases and run DPO training.

How are model fine-tuning, deployment, and evaluation billed?

Model fine-tuning is billed by the number of tokens consumed during training. Deployed models incur only deployment fees, not invocation fees. Model evaluation is free. For details, see Model training and deployment billing.

Can I download a model fine-tuned on Alibaba Cloud Model Studio for local deployment?

Models fine-tuned on Alibaba Cloud Model Studio cannot be exported. They can only be tested and invoked after deployment on Model Studio.

What should I do if model fine-tuning fails due to insufficient training data?

If fine-tuning fails because of insufficient data, try adjusting the Sequence Length (max_length) parameter.

Explanation

Sequence length sets the maximum token length per training sample. In SFT (Supervised Fine-Tuning), samples exceeding this length are discarded. If sequence length is too large, many samples may be discarded, leaving insufficient data for training and causing failure.

Solution

  1. When creating a training job, expand Parameter Settings and find max_length (Sequence Length).

  2. Reduce sequence length (for example, to 8192) so more samples meet the length requirement and participate in training.

  3. Resubmit the training job.

Note

On the model fine-tuning job list, click Logs next to the failed job to see the exact failure reason.