Skip to main content

Introduction to model fine-tuning

You can use model fine-tuning in Alibaba Cloud Model Studio if a model's performance does not meet your expectations after you have tried optimization methods such as prompt engineering and plugin calls. As a core strategy for improving model performance, model fine-tuning can significantly enhance a model's capabilities in specific industries or business scenarios, align its outputs with human preferences, and reduce output latency. Model fine-tuning includes three training methods: supervised fine-tuning (SFT), continual pre-training (CPT), and direct preference optimization (DPO).

Introduction to model fine-tuning

Model fine-tuning is an important method for optimizing model performance. It can:
  • Improve model performance in specific industries or for specific business needs
  • Reduce model output latency
  • Suppress model hallucination
  • Align the model with human values or preferences
  • Replace larger models with fine-tuned lightweight models
During the fine-tuning process, the model learns business-specific or scenario-specific features from the training data, such as knowledge, tone, expression styles, and self-awareness. Because the model has already learned many examples for specific industries or scenarios during training, its one-shot or zero-shot prompt performance after training is better than its few-shot performance before training. This saves input tokens and reduces model output latency.

Model fine-tuning process

image
For more information, see:

Supported models

  • Singapore
  • China (Beijing)
  • Text generation
  • Visual understanding (Qwen-VL)

Model

Model code

SFT Full Parameter Training

SFT Efficient Training

Qwen3.8-27B

qwen3.8-27b

✓

✓

Qwen3.6-27B

qwen3.6-27b

✓

✓

Qwen3.5-27B

qwen3.5-27b

✓

✓

Qwen3.5-9B

qwen3.5-9b

✓

✓

Qwen3-14B

qwen3-14b

×

✓

Comparison of fine-tuning methods

Attribute

CPT (continued pre-training)

SFT (supervised fine-tuning)

DPO (direct preference optimization)

One-sentence summary

Add knowledge (inject domain knowledge)

Learn to perform tasks (follow instructions)

Do better (align with human preferences)

Input data

10 million+ tokens

Unlabeled domain text

1,000+ items

High-quality "question-answer" pairs

100+ groups

"Better-worse" answer pairs under the same instruction

Core objective

Domain adaptation, learning specialized vocabulary and facts

Teach the model dialogue formats and task execution capabilities

Make model outputs better align with human values and preferences

Learning method

Self-supervised learning (predicting the next word)

Supervised learning(imitating standard answers)

Direct preference learning(increasing the probability of good answers and decreasing that of bad answers)

Model stage

Usually before SFT

After CPT, before DPO

Usually after SFT, as the final step of alignment

Training Mode Comparison

Full Parameter Training

Efficient Training (LoRA, recommended)

Applicable Scenario

• The model needs to learn new capabilities

• Pursuing globally optimal performance

• Optimizing model performance in specific scenarios

• Scenarios sensitive to training time and cost

Training time

Longer, with a slower convergence speed.

Shorter, with a faster convergence speed.

Billing Details

Billing methodBilled based on the amount of data used for training
Billing formulaModel training fee = (Total tokens of training data + Total tokens of mixed training data) × Rounds × Training unit price (Minimum billing unit: 1 token)
You can view the estimated training fee at the bottom of the model fine-tuning console and click Computing Details to view the total training tokens, rounds, and training unit price.

Training unit price

The following are the training unit prices of preset models. The training unit price of a custom model is the same as that of the corresponding preset model.
  • Singapore
  • China (Beijing)
  • Qwen
  • Qwen VL

Model Service

Model code

Pricing

Qwen3.8-27B

qwen3.8-27b

$0.0075/Thousand Token

Qwen3.6-27B

qwen3.6-27b

$0.0075/Thousand Token

Qwen3.5-27B

qwen3.5-27b

$0.0075/Thousand Token

Qwen3.5-9B

qwen3.5-9b

$0.003/Thousand Token

Qwen3-14B

qwen3-14b

$0.0016/Thousand Token

Limits
Input file limits
  • Image limits
  • Video limits
  • Image resolution:
    • Minimum size: The width and height of the image must both be greater than 10 pixels.
    • Aspect ratio: For the original image and the scaled image, the ratio of the long side to the short side must not exceed 200:1.
      For image scaling logic, see the smart_resize function in Calculating image tokens.
    • Pixel limit:
      • We recommend that you keep the image resolution within 8K(7680x4320). Images above this resolution may cause API call timeouts due to oversized files or lengthy network transmission.
      • Automatic scaling mechanism: the model can adjust the image size using max_pixels and min_pixels. Therefore, providing ultra-high-resolution images does not improve recognition accuracy, but instead increases the risk of call failures. We recommend scaling images to an appropriate size on the client side in advance.
  • Supported image formats
    • For resolutions below 4K (3840x2160), the supported image formats are as follows:

      Image format

      Common extensions

      MIME Type

      BMP

      .bmp

      image/bmp

      JPEG

      .jpe, .jpeg, .jpg

      image/jpeg

      PNG

      .png

      image/png

      TIFF

      .tif, .tiff

      image/tiff

      WEBP

      .webp

      image/webp

      HEIC

      .heic

      image/heic

    • For resolutions between 4K(3840x2160) and 8K(7680x4320), only JPEG, JPG, and PNG formats are supported
  • Image size:
    • When passed in as a public URL: for the Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, and Qwen3-VL series, a single image must not exceed 20MB; for other models, a single image must not exceed 10MB
    • When passed in as a local path: a single image must not exceed 10MB
    • When passed in as Base64 encoding (OpenAI-compatible interface or DashScope): for the Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, and Qwen3-VL series, the original image file before encoding must not exceed 20MB; for other models, it must not exceed 10MB; and the encoded Data URI string must not exceed 20MB.
    • When passed in as Base64 encoding (Anthropic-compatible interface): subject to the limit that the entire request body must not exceed 6MB, multiple images must share this quota.
    The preceding limits depend on the selected model and cannot be increased by purchasing premium plans or upgrading the model version.
    To compress files, see How to compress images or videos to the required size.
  • Image quantity limits: for multi-image input, the maximum number of supported images varies by input method:
    • When passed in as a public URL or local path:
      • Qwen3.8-Max and Qwen3.7-Plus: up to 2048 images
      • Qwen3.7-Flash, Qwen3.6-Plus, Qwen3.6-Flash, Qwen3.5-Plus, Qwen3.5-Flash, Qwen3-VL, Qwen-VL, and QVQ series: up to 256 images
    • When passed in as Base64 encoding: up to 250 images
    For Qwen-Omni series models, see Omni-modal.
In addition, all images are subject to the model's total token limit for images and text (that is, the maximum input). The total number of tokens of all images must be less than the model's maximum input.
File input methods
  • Public URL: provide a publicly accessible file address that supports the HTTP or HTTPS protocol. For optimal stability and performance, you can upload files to OSS to obtain a public URL. The Model Studio service cannot access OSS internal addresses (endpoints containing -internal, such as https://<bucket>.oss-cn-hangzhou-internal.aliyuncs.com/image.jpg). Passing in an internal address causes the file download to fail and returns InvalidParameter with the message Failed to download multimodal content. Use an OSS public domain name (such as https://<bucket>.oss-cn-hangzhou.aliyuncs.com/image.jpg) or an OSS temporary signed URL to pass in files.
    To ensure that the model can successfully download the file, the response headers of the provided public URL must contain Content-Length (file size) and Content-Type (media type, such as image/jpeg). A missing or incorrect field will cause the file download to fail.
  • Base64 encoding: convert the file into a Base64-encoded string before passing it in.
  • Local file path (DashScope SDK only): pass in the path of a local file.
For suggestions on file input methods, see How do I choose a file upload method?

Calculating image and video tokens

  • Image
  • Video
Formula: Image Token = h_bar * w_bar / token_pixels + 2
  • h_bar、w_bar: the width and height of the scaled image. The model performs preprocessing before processing the image, shrinking it to within a specific pixel limit. This pixel limit depends on the values of the max_pixels and vl_high_resolution_images parameters.
  • token_pixels: the number of pixels corresponding to each visual Token, which varies across models:
    • qwen3.7 series, qwen3.6 series, qwen3.5 series, Qwen3-VL, qwen-vl-max, qwen-vl-plus: each Token corresponds to 32x32 pixels
    • QVQ and other Qwen2.5-VL models: each Token corresponds to 28x28 pixels
The following code demonstrates the approximate scaling logic the model applies to images internally. You can use it to estimate the number of Tokens of an image. For actual billing, refer to the API response.
import math
from PIL import Image  # pip install Pillow

def smart_size(image_path, max_pixels, vl_high_resolution_images):
    """根据模型参数,计算图像缩放后的尺寸,用于估算图像 Token。"""
    image = Image.open(image_path)
    height, width = image.height, image.width

    # The scaling factor is 32 for Qwen3.6, Qwen3.5, and Qwen3-VL. For other models, set factor to 28
    factor = 32
    h_bar = round(height / factor) * factor
    w_bar = round(width / factor) * factor

    # Token lower limit: 4 tokens
    min_pixels = 4 * factor * factor

    # If vl_high_resolution_images=True, the token upper limit is fixed at 16384, and max_pixels is ignored.
    if vl_high_resolution_images:
        max_pixels = 16384 * factor * factor

    # Constrains the total number of pixels to the range [min_pixels, max_pixels].
    if h_bar * w_bar > max_pixels:
        beta = math.sqrt((height * width) / max_pixels)
        h_bar = math.floor(height / beta / factor) * factor
        w_bar = math.floor(width / beta / factor) * factor
    elif h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (height * width))
        h_bar = math.ceil(height * beta / factor) * factor
        w_bar = math.ceil(width * beta / factor) * factor

    return h_bar, w_bar

if __name__ == "__main__":
    # Note: The values of max_pixels and vl_high_resolution_images must match the parameters passed when calling the model.
    h_bar, w_bar = smart_size("xxx/test.jpg", max_pixels=2560 * 32 * 32, vl_high_resolution_images=False)
    print(f"缩放后的图像尺寸:高度 {h_bar},宽度 {w_bar}")

    # Each image includes one <vision_bos> and one <vision_eos> token.
    token = int(h_bar * w_bar / (32 * 32)) + 2
    print(f"图像的 Token 数:{token}")

Before you start model fine-tuning

  • Although text generation model fine-tuning can achieve excellent results in specific businesses/scenarios, it has the following limitations:
    • It is time-consuming, including: building a large-scale CPT dataset (at least 50 million tokens), constructing an effective SFT dataset (1000+ items), collecting enough bad cases (100+) to build an effective DPO dataset, and slow model optimization iterations.
    • It is costly. A fine-tuned model can only be used after deployment, and model deployment billing is relatively high.
  • Alibaba Cloud Model Studio recommends that before considering text generation model fine-tuning, you first try Prompt engineering (Prompt Engineering) or plug-in calling (Function Calling) to customize your application, and model fine-tuning is also often the "last resort" for improving model performance, because:
    1. In many tasks, the model may initially perform poorly, but applying the right Prompt techniques can improve results, so model fine-tuning is not always necessary.
    2. Iterating on Prompts and plug-ins is more agile and less costly than model fine-tuning iterations, because a fine-tuning iteration may require re-collecting data, cleaning and optimizing data, collecting bad cases, and conducting customer research.
    3. Even if model fine-tuning is ultimately required, the initial Prompt engineering and plug-in iteration work is not wasted. You can fully reuse this preliminary work when building fine-tuning datasets (as input for dataset construction).

QuickStart

Fine-tune a model in the console

  1. Log on to the Model Studio console. In the left-side navigation pane, choose Model Training > Model Fine-tuning, and click Create Training Task.
    创建训练任务
  2. Complete the following configuration in the Training Configuration section:
    • Training Method: Select SFT fine-tuning training.
    • Select a model: Select Qwen3-8B.
    • Training Method: Select Efficient Training.
    This combination requires a short training time and low data requirements.
  3. In the Hyperparameter Configuration section, keep the default parameter settings. Model Studio provides recommended configurations for fine-tuning hyperparameters.
  4. Complete the following configuration in the Data Configuration section:
    • Training set: Select the fine-tuning dataset you have uploaded. Data sample: SFT-ChatML format example.jsonl.
    • Mixed Training: Keep it disabled.
    • Validation set: Select Automatic Splitting to split 10% of the training set as the validation set.
    数据配置
  5. In the Training Output section, configure how model parameter snapshots (Checkpoints) are saved. You can keep the default settings for the following configurations:
    • Model: After training is complete, the last output Checkpoint will be automatically published to My Models under this name.
    • Up to : Set the number of models finally exported by the training task.
    • Checkpoint saving interval: You can select By epoch or By step.
    训练产出
    After model fine-tuning is complete, you must export the parameter snapshot. Only after export can you deploy the model on Model Studio based on that version of the parameter snapshot. Exported parameter snapshots are stored in cloud storage and cannot be accessed or downloaded at this time.
  6. Click Start Training and wait for model training to complete.
  7. In Model Inference > Dedicated Deployment, deploy the trained custom model. After deployment, you can evaluate the fine-tuned model. For more information, see Dedicated Deployment overview.

Typical fine-tuning workflow

The three fine-tuning methods provided by Model Studio are not mutually exclusive, but progressive and complementary. CPT (optional) → SFT → DPO (optional)
  1. CPT (continued pre-training) - supplements knowledge (the "breadth" and "shallowness" of general model knowledge cannot meet the "depth" and "precision" requirements of specialized domains)
    • Financial models: Learn financial terminology
    • Medical models: Memorize drugs and pathology
    • Legal models: Understand statutes and precedents
  2. SFT (supervised fine-tuning) - learns to perform tasks
    • Customer service bot: Learn customer service workflows
    • Code assistant: Learn programming paradigms
    • Tool calling (Agent): Learn to use MCP
  3. DPO (direct preference optimization) - do better
    • Safety and responsibility: Refuse harmful advice
    • Conciseness and effectiveness: Answer crisply and cleanly
    • Objectivity and neutrality: Evaluate fairly and objectively

Fine-tuning data format

For the data format specifications, packaging rules, size and quantity limits, and API upload quotas of each training method (SFT/DPO/CPT), see Fine-tuning data upload rules. An overview of the file formats supported by each training method:

Training method

File format

SFT text generation

jsonl (ChatML messages multi-turn structure)

SFT multi-modal (images/videos)

zip (data.jsonl + image/video files)

DPO

jsonl (chosen/rejected preference pairs)

CPT

jsonl (plain text {text})

Evaluation Set

xlsx (prompt&completion)/ jsonl, xls, xlsx (ChatML-messages)/ zip (multi-modal: visual understanding, text-to-image, image-to-image, image-to-video)

Dataset construction tips

Dataset scale requirements

For CPT, the dataset requires at least 50 million tokens of high-quality pre-training data; for SFT, at least thousands of high-quality fine-tuning samples; for DPO, typically hundreds of human preference samples. If the model's evaluation results after fine-tuning are unsatisfactory, the simplest improvement is to collect more data for training. If you lack data, we recommend building an agent application (Agent 1.0) and using knowledge base indexing to enhance model capabilities. In many complex business scenarios, you can also adopt a combined technical approach that integrates model fine-tuning with knowledge base retrieval. Take the customer service scenario as an example: model fine-tuning can address the tone, expression habits, and self-identity of customer service responses, while the domain-specific knowledge involved in the scenario can be dynamically injected into the model's context via a knowledge base. Alibaba Cloud Model Studio recommends that you first build a RAG application for a trial run, and then continue to improve model performance through model fine-tuning once sufficient application data has been collected. You can also expand your dataset with the following strategies:
  1. Have a large model simulate and generate content relevant to specific business/scenario needs, helping you produce more fine-tuning data. (For the generation model, we recommend selecting one with strong performance and a larger scale)
  2. Manually obtain more data through various channels such as collection from application scenarios, web crawlers, social media and online forums, public datasets, partners and industry resources, and user contributions.

Data diversity and balance

Model fine-tuning applies to different scenarios: for specific business scenarios, specialization matters more; for Q&A scenarios, generality matters more. You need to design data use cases based on the business module or usage scenario the model serves. Therefore, training effectiveness depends not only on data volume, but also on specialization and diversity for the target scenario. Using the intelligent AI conversation scenario as an example, the following introduces the various business scenarios that a specialized, diverse dataset should cover:

Specific business

Diversified scenarios/businesses

E-commerce customer service

Event notifications, pre-sales consultation, in-sales guidance, after-sales service, after-sales follow-up, complaint handling, etc.

Financial Services

Loan consultation, investment and wealth management advisory, credit card services, bank account management, etc.

Online healthcare

Symptom consultation, appointment registration, visit guidelines, medicine information queries, health tips, etc.

AI secretary

IT information, administrative information, HR information, employee benefit answers, company calendar queries, etc.

Travel assistant

Trip planning, entry and exit guides, travel insurance consultation, introductions to destination customs and culture, etc.

Corporate legal advisor

Contract review, intellectual property protection, compliance checks, labor law Q&A, cross-border transaction consultation, case-specific legal analysis, etc.

Also note that the amount of data for each scenario/business should be relatively balanced, with data proportions matching real-world scenario proportions, to prevent an excess of one type of data from causing the model to over-learn that type of features, which would affect the model's generalization capability.

Training set and validation set splitting

When you use the console for model fine-tuning, you can choose to
  • Automatically split a complete training dataset, randomly extracting a small amount of data to form a validation set.
  • Select a separately uploaded dataset.
The console can promptly and conveniently display the validation set Loss and Token Accuracy during training.
image

FAQ

Can I fine-tune my own model?

Model Studio does not support fine-tuning, uploading your own models, or exporting downloaded models.