Runoob Tutorial ArchiveEnglish

Model Fine-tuning

Model Fine-tuning

When you need a model specifically for generating e-commerce product descriptions, there are three main options.

Comparison of the three methods:

Method Cost Effect Applicable scenarios
Training from scratch Extremely high (millions of dollars) Fully customized Creating new foundation models (giants only)
Prompt engineering Almost zero Unstable, prompt-dependent Simple tasks, quick validation
Fine-tuning Medium (hundreds to thousands of dollars) Stable and professional Domain-specific tasks, productization

Using a simple analogy:

  • Training from scratch is like training a doctor from zero, which takes over a decade.
  • Prompt engineering is like giving a general practitioner a detailed operating manual.
  • Fine-tuning is like having a licensed doctor go to specialize for a few months to become a specialist.

  • Why is fine-tuning needed?

    Not all tasks require fine-tuning; first, figure out when to use it and when not to.

    Limitations of prompt engineering

    Prompt engineering is very powerful, but it has several hard-to-break ceilings.

    Applicable scenarios for fine-tuning

    Fine-tuning is worth considering when your task has the following characteristics.

    Cost-benefit analysis of fine-tuning

    Before fine-tuning, do a cost calculation.

    Costs mainly come from three aspects: data preparation, computing resources, and manual debugging. Data preparation usually accounts for the largest workload—you need to collect, clean, and label data. Computing resources are now very cheap; with LoRA + QLoRA, a consumer-grade GPU (RTX 3090/4090) can fine-tune 7B/13B models.

    Benefits are reflected in several aspects: better performance, lower inference costs, faster response speed, and more stable output. If your model is to be offered as a service externally, these benefits will accumulate continuously.

    When should you not fine-tune? If the task changes rapidly and the data format changes weekly, Prompt engineering is more flexible. If you are only doing a one-time exploration or only have dozens of data points, fine-tuning is not worth it.

    Factors More suitable for Prompt More suitable for fine-tuning
    Data volume < 100 entries > 500 items
    Task stability Frequently changing Relatively fixed
    Usage frequency Used occasionally High frequency of use
    Cost sensitivity Low High
    Effect requirements Usable is fine Strive for the best

    Full Fine-tuning

    First understand the most traditional fine-tuning methods, then see why we rarely use it today.

    Principles and workflow

    The idea for full fine-tuning is simple: take all the parameters of the pre-trained model and continue training it on your dataset, updating all weights.

    The process is roughly as follows:

    Example

    ============================================

    Full fine-tuning concept demonstration (pseudocode, framework independent)

    Demonstrates the core idea; actual code will use HuggingFace

    ============================================

    def

    full_finetuning_concept

    (

    )

    :

       

    """Core concept demonstration of full fine-tuning"""

       

    1. Load pre-trained model (all parameters are trainable)

    model

    =

    load_pretrained_model

    (

    "llama-2-7b"

    )

       

    The model has 7 billion parameters, and each parameter will be updated

       

    print

    (

    f

    "Total number of model parameters: {count_parameters(model)}"

    )

       

    Output: Total number of model parameters: 7000000000

       

    2. Prepare your specific task data

    train_data

    =

    [

           

    {

    "input"

    :

    "Product: Insulated cup\nGenerate e-commerce description"

    ,

             

    "output"

    :

    "This high-quality insulated cup uses a 304 stainless steel inner lining and vacuum insulation technology, maintaining heat for up to 12 hours."

    }

    ,

           

    {

    "input"

    :

    "Product: Wireless Earbuds\nGenerate E-commerce Description"

    ,

             

    "output"

    :

    "True wireless Bluetooth earbuds, Bluetooth 5.3 stable connection, active noise cancellation, 24-hour battery life, comfortable to wear."

    }

    ,

           

    ... several hundred to thousands of similar data entries

       

    ]

       

    3. Set the optimizer and a very small learning rate

    optimizer

    =

    create_optimizer

    (

    model

    ,

    learning_rate

    =

    2e-5

    )

       

    4. Training Loop

       

    for

    epoch

    in

    range

    (

    3

    )

    :

    Usually train for 2-5 epochs

           

    for

    batch

    in

    create_batches

    (

    train_data

    )

    :

               

    Forward propagation

    loss

    =

    model.

    compute_loss

    (

    batch

    )

               

    Backpropagation, update all parameters!

    loss.

    backward

    (

    )

    optimizer.

    step

    (

    )

    optimizer.

    zero_grad

    (

    )

           

    print

    (

    f

    "Epoch {epoch} completed"

    )

       

    5. Save the complete model (7 billion parameters, about 13GB)

    model.

    save

    (

    "llama-2-7b-ecommerce-finetuned"

    )

       

    print

    (

    "Full fine-tuning completed, new model saved"

    )

    This is just a conceptual demonstration; actual training requires a large amount of VRAM.

    Catastrophic forgetting problem

    Full fine-tuning has a serious problem: Catastrophic Forgetting.

    What does that mean? When you train on your data, the model gradually "forgets" the general knowledge it learned during pre-training. It's like a person who studies intensely for a math exam and ends up forgetting the Chinese and English they previously learned.

    Why does it happen? Because full fine-tuning updates all parameters. The knowledge learned during pre-training is encoded in these parameters, and drastic changes can destroy the original knowledge.

    The result is: the fine-tuned model performs well on your task but performs worse on other general tasks. Worse still, it might lose some basic abilities, such as following instructions or understanding complex questions.

    How to alleviate it? You can mix in pre-training data for training, but this brings back the old problem of "requiring massive amounts of data." Alternatively, you can use regularization to constrain parameters from changing too much, but the effect is limited.

    VRAM requirement calculation

    Another issue with full fine-tuning is the excessive VRAM requirement. Let's calculate:

    VRAM required to train a model = model parameters + gradients + optimizer states + activations.

    For the LLaMA-7B model, in full precision (FP32), 7 billion parameters × 4 bytes = 28 GB. The gradients are also 28 GB, and the optimizer states (Adam optimizer) require 56 GB (2 times the gradients). Activations vary with batch size and sequence length, requiring at least a few GB.

    In total, full fine-tuning a 7B model requires about 100+ GB of VRAM—meaning at least 8 A100 (40GB) or 2 A100 (80GB).

    If using half precision (FP16/BF16), it can be halved, but it still requires about 50-60 GB of VRAM. This is still unaffordable for the average person.

    Model Size Full Fine-tuning VRAM (FP16) Required GPU
    7B 50-60 GB 2×A100 (40GB) or 1×A100 (80GB)
    13B 90-100 GB 3×A100 (40GB) or 2×A100 (80GB)
    70B 400+ GB 12×A100 (40GB) or 6×A100 (80GB)

    Full fine-tuning is not unusable, but it is high in cost and risk. Unless you have sufficient reasons (such as a very large amount of data that requires changing the fundamental behavior of the model), you should prioritize Parameter-Efficient Fine-Tuning (PEFT) methods.


    Parameter-Efficient Fine-Tuning (PEFT)

    PEFT is a general term for a class of methods that only train a small number of parameters. It retains the effectiveness of fine-tuning while significantly reducing costs.

    The core idea of PEFT

    The core insight of PEFT is that pre-trained models already contain enough knowledge; we do not need to modify all parameters, only "adjust" a small subset of parameters to adapt to the new task.

    It is like a piano that has already been built; you do not need to rebuild the entire piano, only tune a few strings to produce the desired tone.

    The benefits of PEFT are obvious:

    Overview of mainstream PEFT methods

    PEFT is not a single method, but a general term for a class of methods. Let's look at several mainstream methods:

    Method Principle Number of trainable parameters Effect
    Full fine-tuning Update all parameters 100% Okay, but might forget
    Adapter Insert small network 0.1%-1% Medium
    Prefix Tuning Add prefix vector 0.1%-1% Medium
    Prompt Tuning Add soft prompt < 0.1% General
    LoRA Low-rank matrix adaptation 0.1%-1% Near full fine-tuning
    QLoRA Quantization + LoRA 0.1%-1% Near full fine-tuning

    Today's best practices are clear:Prefer LoRA, and use QLoRA if VRAM is insufficientThese two methods have good effects, low cost, and a mature ecosystem, making them the optimal choice in most cases.


    LoRA (Low-Rank Adaptation)

    LoRA is the most mainstream fine-tuning method currently, and understanding its principle is very important.

    Low-Rank Decomposition Principle (Intuitive Understanding)

    First, understand what "Rank" and "Low-Rank" mean.

    Suppose you have a 100 × 100 matrix, and the data inside it might not be completely random. If this data can be formed by combining only a few "patterns," we say that the rank of this matrix is very low.

    For example: if every row is a multiple of the first row, then the rank of this matrix is 1. If every row is a linear combination of the first two rows, then the rank is 2. And so on.

    The core insight of LoRA is that when large models adapt to new tasks, the change in weights is usually "low-rank"—meaning this change can be represented by a small number of parameters.

    This is like how, even with 1000 different e-commerce product descriptions, their writing style might only be determined by a few core factors: tone, length, and emphasis. You don't need 1000 different directions to describe the change; 8, 16, or 32 are enough.

    So, LoRA's approach is: freeze all parameters of the original model and add two small matrices, A and B, next to the attention layer. A is d × r, B is r × d, where r is the rank, usually a small number like 8, 16, or 32.

    Original model output = Original model forward pass.

    LoRA output = Original model forward pass + (input × A × B) × scaling factor.

    Only A and B are trained during training; the original model parameters remain completely unchanged.

    LoRA mathematical derivation

    Don't worry, the mathematical derivation is simple, only a few lines.

    Assume that a certain layer of the original model is a linear transformation: h = W₀x, where W₀ is a pre-trained weight matrix with shape d × d.

    During fine-tuning, we want to update W₀, but we don't want to update too much. LoRA's approach is to represent the change in W₀ as the product of two small matrices: ΔW = BA.

    So the fine-tuned output is: h = W₀x + (BA)x.

    Here, the shape of B is d × r, and the shape of A is r × d, where r is the rank.

    To be more precise, the formula in the LoRA paper is:

    h = W₀x + α * (BA)x

    where α is a scaling factor, usually set to a multiple of r, so that hyperparameters do not need to be readjusted when r is changed.

    During training, W₀ is completely frozen, and only A and B are trainable.

    During initialization, A is initialized with a random Gaussian distribution, and B is initialized to zero, so the output of the LoRA part is zero at the start of training, which does not affect the original model's behavior.

    Instance

    ============================================

    Minimal implementation of the core principle of LoRA

    Pure NumPy demonstration without relying on any framework

    ============================================

    import

    numpy

    as

    np

    class

    LoRALayer:

       

    """Minimal implementation of LoRA layer"""

       

    def

    init

    (

    self

    ,

    d:

    int

    ,

    r:

    int

    ,

    alpha:

    float

    =

    1.0

    )

    :

           

    """
    d: Input/output dimension (e.g., 4096)
    r: Rank (e.g., 8, 16, 32)
    alpha: Scaling factor
    """

           

    self

    .

    d

    =

    d

           

    self

    .

    r

    =

    r

           

    self

    .

    alpha

    =

    alpha

           

    Frozen original weights (simulating pre-trained model)

           

    self

    .

    W_0

    =

    np.

    random

    .

    randn

    (

    d

    ,

    d

    )

    0.01

           

    self

    .

    W_0

    .

    flags

    .

    writeable

    =

    False

     

    Marked as non-trainable

           

    LoRA's A and B matrices, trainable

           

    A: r × d, initialized with random Gaussian

           

    self

    .

    A

    =

    np.

    random

    .

    randn

    (

    r

    ,

    d

    )

    0.01

           

    B: d × r, initialized to zero (no effect on the original model in the early stages of training)

           

    self

    .

    B

    =

    np.

    zeros

    (

    (

    d

    ,

    r

    )

    )

       

    def

    forward

    (

    self

    ,

    x: np.

    ndarray

    )

    np.

    ndarray

    :

           

    """Forward pass: Original model output + LoRA output"""

           

    Original model output

    original_output

    =

    x

    @

    self

    .

    W_0

    .

    T

           

    LoRA output: (x @ A.T) @ B.T = x @ (B @ A).T

    lora_output

    =

    (

    x

    @

    self

    .

    A

    .

    T

    )

    @

    self

    .

    B

    .

    T

           

    Merge output

           

    return

    original_output +

    self

    .

    alpha

       

    def

    get_trainable_params

    (

    self

    )

    dict

    :

           

    """Get trainable parameters (only A and B)"""

           

    return

    {

    "A"

    :

    self

    .

    A

    ,

    "B"

    :

    self

    .

    B

    }

       

    def

    count_params

    (

    self

    )

    dict

    :

           

    """Counts the number of parameters"""

    total_original

    =

    self

    .

    d

    self

    .

    d

    total_lora

    =

    self

    .

    r

    self

    .

    d

    self

    .

    d

    self

    .

    r

           

    return

    {

               

    "original_params"

    : total_original

    ,

               

    "lora_params"

    : total_lora

    ,

               

    "ratio"

    : total_lora / total_original *

    100

    ,

           

    }

    ============================================

    Demonstrate the parameter saving effect of LoRA

    ============================================

    Assume d = 4096 (similar to the hidden layer dimension of LLaMA-7B)

    r = 8 (a commonly used rank size)

    d

    =

    4096

    r

    =

    8

    lora

    =

    LoRALayer

    (

    d

    =

    d

    ,

    r

    =

    r

    ,

    alpha

    =

    r

    )

    params_info

    =

    lora.

    count_params

    (

    )

    print

    (

    f

    "Original number of parameters: {params_info['original_params']:,}"

    )

    print

    (

    f

    "Number of LoRA parameters: {params_info['lora_params']:,}"

    )

    print

    (

    f

    "Parameter ratio: {params_info['ratio']:.4f}%"

    )

    Output example:

    Original number of parameters: 16,777,216

    LoRA number of parameters: 65,536

    Parameter proportion: 0.3906%

    See, LoRA only needs to train 0.4% of the parameters to achieve an effect close to full fine-tuning. This is its magic.

    Selection of r (rank) and alpha parameters

    LoRA has two key hyperparameters: rank r and scaling factor alpha.

    r determines the capacity of LoRA. The larger r is, the more complex the changes it can represent, but the larger the number of parameters.

    Common values for r: 8, 16, 32, 64. For most tasks, r = 8 or 16 is sufficient. Values of r exceeding 64 usually show diminishing returns and increase training costs.

    How to choose r? A practical suggestion is: first try r = 8, and if the results are not good, increase it to 16 or 32. Do not start with a very large r.

    α is the scaling factor. A common setting is α = r, which keeps the scale of ΔW = BA roughly stable. Alternatively, set α = 1 and let the user adjust it themselves.

    Other parameters to consider:

    Target layers (target_modules): On which layers should LoRA be applied? Usually, applying it only to the query and value projections of the attention layers (q_proj, v_proj) yields good results. It can also be applied to more layers, but this will increase the number of parameters.

    Dropout: LoRA can add dropout to prevent overfitting, with common values being 0.05 or 0.1.

    Parameters Common values Description
    r (rank) 8, 16, 32 Larger capacity means larger parameter count
    alpha r or 1 Scaling factor, usually set to r
    target_modules ["q_proj", "v_proj"] Layers to add LoRA to
    lora_dropout 0.0, 0.05, 0.1 Prevent overfitting

    Merge LoRA weights

    After training LoRA, there are two options for inference.

    The advantage of merging is faster inference speed, as no special LoRA support is needed. The disadvantage is that once merged, it cannot be undone, and if there are multiple LoRAs, they need to be merged into different model files separately.

    Example

    ============================================

    LoRA Weight Merging Demonstration

    ============================================

    import

    numpy

    as

    np

    def

    merge_lora_weights

    (

    W_0: np.

    ndarray

    ,

    A: np.

    ndarray

    ,

    B: np.

    ndarray

    ,

    alpha:

    float

    =

    1.0

    )

    np.

    ndarray

    :

       

    """
    Merge LoRA weights into the original weights
    W = W_0 + alpha * (B @ A)

    Parameters:
    W_0: Original weights (d, d)
    A: LoRA A matrix (r, d)
    B: LoRA B matrix (d, r)
    alpha: Scaling factor

    Returns:
    Merged weights
    """

       

    Calculate delta_W = alpha * (B @ A)

    delta_W

    =

    alpha *

    (

    B

    @

    A

    )

       

    Merge into original weights

    W_merged

    =

    W_0 + delta_W

       

    return

    W_merged

    ============================================

    Demonstration of the merging process

    ============================================

    d

    =

    4096

     

    Hidden layer dimension

    r

    =

    8

       

    LoRA rank

    Simulate original weights and LoRA weights

    W_0

    =

    np.

    random

    .

    randn

    (

    d

    ,

    d

    )

    0.01

    A

    =

    np.

    random

    .

    randn

    (

    r

    ,

    d

    )

    0.01

    B

    =

    np.

    zeros

    (

    (

    d

    ,

    r

    )

    )

     

    In practice, B is the result after training

    Merge weights

    W_merged

    =

    merge_lora_weights

    (

    W_0

    ,

    A

    ,

    B

    ,

    alpha

    =

    r

    )

    print

    (

    f

    "Original weight shape: {W_0.shape}"

    )

    print

    (

    f

    "Merged weight shape: {W_merged.shape}"

    )

    print

    (

    "Weight merging is complete, it can be used like a regular model"

    )


    QLoRA (Quantized LoRA)

    QLoRA pushes the low cost of LoRA to the extreme—allowing 70B models to be fine-tuned on consumer-grade GPUs.

    4-bit quantization + LoRA

    The idea behind QLoRA is simple: quantize the model to 4-bit, and then perform LoRA fine-tuning on it.

    What is quantization? It is converting floating-point numbers (FP16/BF16, each taking 2 bytes) into a lower precision representation. 4-bit quantization uses 4 bits (0.5 bytes) to represent a weight.

    This reduces the model size by 75%: a 7B model drops from 13 GB to about 3.5 GB, a 13B model drops from 26 GB to about 6.5 GB, and a 70B model drops from 140 GB to about 35 GB.

    However, direct quantization causes a loss of precision. The innovation of QLoRA is the use of a data type called NF4 (Normalized Float 4), which better preserves the information of neural network weights.

    The approach of QLoRA is:

    The effect of this is: the VRAM requirement is further reduced by 75%, while the performance loss is almost negligible.

    bitsandbytes library

    bitsandbytes is the core library for implementing quantization, developed by Tim Dettmers.

    It provides:

    Ordinary users do not need to interact with bitsandbytes directly; the peft and transformers libraries have already encapsulated it. But knowing its existence is useful.

    Consumer-grade GPU fine-tuning solutions

    With QLoRA, ordinary people can also afford fine-tuning.

    RTX 3090/4090 (24GB VRAM) can easily fine-tune 7B/13B models, and even 70B models can be attempted (requires longer sequence length or smaller batch size).

    VRAM requirement estimation:

    Model size QLoRA VRAM requirement Suitable GPU
    7B 5-8 GB RTX 3060/4060 and above
    13B 8-12 GB RTX 3070/4070 and above
    34B 15-20 GB RTX 3090/4090
    70B 30-40 GB RTX 3090/4090 × 2 or A100

    QLoRA is a game-changer. It has turned fine-tuning large models from "only big companies can do it" to "ordinary people can do it on their gaming laptops." This is one of the most important advancements in open-source AI.


    Training data preparation

    Data preparation is the most time-consuming and critical part of the fine-tuning process. Garbage in, garbage out—data quality determines the model's upper limit.

    Data format (Alpaca, ShareGPT format)

    There are several common data formats; choose one and stick with it.

    The first is the Alpaca format. This is one of the most popular formats, promoted by the Stanford Alpaca project.

    The format is: instruction, input (optional), output.

    Example

    ============================================

    Alpaca data format example

    ============================================

    alpaca_data

    =

    [

       

    {

           

    "instruction"

    :

    "Generate an e-commerce product description"

    ,

           

    "input"

    :

    "Product Name: Smart Sports Watch\nFeatures: Heart Rate Monitoring, Sleep Tracking, GPS Positioning, 50m Waterproof"

    ,

           

    "output"

    :

    "This smart sports watch is the ideal companion for sports enthusiasts. It is equipped with precise heart rate monitoring and scientific sleep tracking functions to help you gain a comprehensive understanding of your health status. The built-in GPS allows you to record your exercise trajectory without carrying a phone. With a 50m waterproof rating, you can wear it worry-free even when swimming."

       

    }

    ,

       

    {

           

    "instruction"

    :

    "Rewrite the following text into a more colloquial expression"

    ,

           

    "input"

    :

    "This product adopts advanced technology and features high performance and low power consumption."

    ,

           

    "output"

    :

    "This product uses very advanced technology, strong performance, and saves energy!"

       

    }

    ,

       

    ... more data

    ]

    print

    (

    "Alpaca format includes three fields:"

    )

    print

    (

    "- instruction: task instruction (required)"

    )

    print

    (

    "- input: Additional input (optional, can be an empty string if not provided)"

    )

    print

    (

    "- output: Expected output (required)"

    )

    The second type is the ShareGPT format. This format is used for conversation data and supports multi-turn conversations.

    The format is: conversations (list of conversations), where each turn has from (role) and value (content).

    Example

    ============================================

    ShareGPT Data Format Example

    ============================================

    sharegpt_data

    =

    [

       

    {

           

    "conversations"

    :

    [

               

    {

                   

    "from"

    :

    "human"

    ,

                   

    "value"

    :

    "Hello, I would like to know about your smartwatches"

               

    }

    ,

               

    {

                   

    "from"

    :

    "gpt"

    ,

                   

    "value"

    :

    Hello! Our smartwatch has features like heart rate monitoring, sleep tracking, and GPS positioning, and it is waterproof up to 50 meters. Is there anything specific you would like to know?

               

    }

    ,

               

    {

                   

    "from"

    :

    "human"

    ,

                   

    "value"

    :

    "How is the battery life?"

               

    }

    ,

               

    {

                   

    "from"

    :

    "gpt"

    ,

                   

    "value"

    :

    "Normal use can last 7 days, and enabling GPS sports mode can last 12 hours."

               

    }

           

    ]

       

    }

    ,

       

    ... more conversations

    ]

    print

    (

    "ShareGPT format for multi-turn conversation data:"

    )

    print

    (

    "- conversations: list of conversations"

    )

    print

    (

    "- from: role (usually human and gpt)"

    )

    print

    (

    "- value: conversation content"

    )

    There is also a simple input-output pair format suitable for simple tasks.

    Instance

    ============================================

    Simple input-output pair format

    ============================================

    simple_data

    =

    [

       

    {

           

    "text"

    :

    "User: Generate product description\nProduct: Insulated cup\n\nAssistant: This high-quality insulated cup uses..."

       

    }

    ,

       

    {

           

    "text"

    :

    "User: Generate product description\nProduct: Wireless headphones\n\nAssistant: True wireless Bluetooth headphones, Bluetooth 5.3..."

       

    }

    ,

       

    ... more data

    ]

    print

    (

    "This format directly concatenates all content into a single text field, which is the most flexible but least standardized."

    )

    Which format is best? Alpaca format is the most universal, and most training frameworks support it. For dialogue tasks, ShareGPT is more suitable.

    Key points for data cleaning

    Data cleaning is much more important than you think. 80% of your model's performance depends on data quality.

    Instance

    ============================================

    Simple Data Cleaning Example

    ============================================

    import

    json

    from

    typing

    import

    List

    ,

    Dict

    def

    clean_alpaca_data

    (

    data: List

    [

    Dict

    ]

    )

    List

    [

    Dict

    ]

    :

       

    """Simple data cleaning function"""

    cleaned

    =

    [

    ]

    seen_outputs

    =

    set

    (

    )

       

    for

    item

    in

    data:

           

    1. Check if necessary fields exist

           

    if

    "instruction"

    not

    in

    item

    or

    "output"

    not

    in

    item:

               

    continue

    instruction

    =

    item

    [

    "instruction"

    ]

    .

    strip

    (

    )

    output

    =

    item

    [

    "output"

    ]

    .

    strip

    (

    )

           

    2. Filter outputs that are too short

           

    if

    len

    (

    output

    )

    <

    10

    :

               

    continue

           

    3. Filter overly long outputs (adjust according to the task)

           

    if

    len

    (

    output

    )

    2000

    :

               

    continue

           

    4. Deduplication (approximate deduplication using output)

           

    if

    output

    in

    seen_outputs:

               

    continue

    seen_outputs.

    add

    (

    output

    )

           

    5. Simple format unification

           

    For example, changing Chinese quotes to English quotes

    output

    =

    output.

    replace

    (

    """, """).replace("""

    ,

    """

    )

           

    Remove leading and trailing whitespace

    output

    =

    output.

    strip

    (

    )

    cleaned.

    append

    (

    {

               

    "instruction"

    : instruction

    ,

               

    "input"

    : item.

    get

    (

    "input"

    ,

    ""

    )

    .

    strip

    (

    )

    ,

               

    "output"

    : output

           

    }

    )

       

    return

    cleaned

    Load data

    with

    open

    (

    "data/training_data_raw.json"

    ,

    "r"

    ,

    encoding

    =

    "utf-8"

    )

    as

    f:

        raw_data

    =

    json.

    load

    (

    f

    )

    Clean data

    cleaned_data

    =

    clean_alpaca_data

    (

    raw_data

    )

    print

    (

    f

    "Raw data volume: {len(raw_data)}"

    )

    print

    (

    f

    "Data volume after cleaning: {len(cleaned_data)}"

    )

    print

    (

    f

    Filtered {len(raw_data) - len(cleaned_data)} low-quality data records

    )

    Save the cleaned data

    with

    open

    (

    "data/training_data_cleaned.json"

    ,

    "w"

    ,

    encoding

    =

    "utf-8"

    )

    as

    f:

    json.

    dump

    (

    cleaned_data

    ,

    f

    ,

    ensure_ascii

    =

    False

    ,

    indent

    =

    2

    )

    print

    (

    "The cleaned data has been saved to data/training_data_cleaned.json"

    )

    Data volume experience rules

    How much data is needed? This is one of the most frequently asked questions.

    The answer is: it depends on the task difficulty.

    Of course, more data is usually better, but the marginal returns diminish. 1000 samples are much better than 500, but 10000 samples might not be much better than 5000.

    A practical suggestion is: first prepare 500 high-quality data samples and run a test. If the results are not good, then analyze whether the issue is insufficient data, poor data quality, or hyperparameter problems, and improve accordingly.

    Data quality >> Data quantity. 1000 carefully written data samples are much better than 10000 mediocre ones.

    Spending more time in the data preparation phase is worthwhile. Model training is just a matter of "pressing a button," but data quality determines whether pressing that button is valuable.


    Supervised Fine-Tuning (SFT) Practice

    We have finally reached the practical implementation stage. We use Unsloth or LLaMA-Factory to implement the complete fine-tuning process.

    Environment Configuration

    First step, install the necessary libraries.

    Environment configuration

    ============================================

    Install dependencies (it is recommended to create a new environment using conda)

    ============================================

    Create a new conda environment

    conda create

    -n

    finetuning

    python

    =

    3.10

    -y

    conda activate finetuning

    Install PyTorch (choose the appropriate command based on your CUDA version)

    Visit https://pytorch.org/get-started/locally/ to get the latest commands

    conda

    install

    pytorch pytorch-cuda=

    12.1

    -c

    pytorch

    -c

    nvidia

    Install HuggingFace ecosystem libraries

    pip

    install

    transformers datasets accelerate peft bitsandbytes

    Install Unsloth (optional, for faster training speed)

    pip

    install

    "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"

    pip

    install

    --no-deps

    trl xformers

    or use LLaMA-Factory (all-in-one training framework)

    git clone

    --depth

    1

    https:

    //

    github.com

    /

    hiyouga

    /

    LLaMA-Factory.git

    cd

    LLaMA-Factory

    pip

    install

    -e

    ".[torch,metrics]"

    echo

    "Environment configuration complete!"

    Use Unsloth/LLaMA-Factory

    Unsloth is an optimized training library that is fast and memory-efficient. LLaMA-Factory is an all-in-one training framework that supports various models and methods.

    First, let's look at the code for training with Unsloth + peft:

    Example

    ============================================

    LoRA Fine-tuning with Unsloth (Full Version)

    Can run on RTX 3090/4090

    ============================================

    import

    torch

    from

    datasets

    import

    load_dataset

    ,

    Dataset

    from

    transformers

    import

    (

        AutoModelForCausalLM

    ,

        AutoTokenizer

    ,

        TrainingArguments

    ,

    BitsAndBytesConfig

    ,

    )

    from

    peft

    import

    LoraConfig

    ,

    get_peft_model

    from

    trl

    import

    SFTTrainer

    import

    json

    ============================================

    1. Configuration Parameters

    ============================================

    MODEL_NAME

    =

    "unsloth/mistral-7b-v0.2-bnb-4bit"

     

    Or other models

    DATA_PATH

    =

    "data/training_data_cleaned.json"

       

    Your data

    OUTPUT_DIR

    =

    "output/runoob-ecommerce-model"

       

    Output directory

    4-bit quantization configuration

    bnb_config

    =

    BitsAndBytesConfig

    (

    load_in_4bit

    =

    True

    ,

        bnb_4bit_use_double_quant

    =

    True

    ,

        bnb_4bit_quant_type

    =

    "nf4"

    ,

        bnb_4bit_compute_dtype

    =

    torch.

    bfloat16

    )

    LoRA Configuration

    lora_config

    =

    LoraConfig

    (

        r

    =

    16

    ,

                       

    Rank, 8-64 are both possible, 16 is a good starting point

    lora_alpha

    =

    16

    ,

             

    Scaling factor, usually equals r

    target_modules

    =

    [

           

    Layers to add LoRA to, these are common choices

           

    "q_proj"

    ,

           

    "k_proj"

    ,

           

    "v_proj"

    ,

           

    "o_proj"

    ,

           

    "gate_proj"

    ,

           

    "up_proj"

    ,

           

    "down_proj"

    ,

       

    ]

    ,

    lora_dropout

    =

    0.05

    ,

         

    Dropout prevents overfitting

    bias

    =

    "none"

    ,

    task_type

    =

    "CAUSAL_LM"

       

    Causal Language Model

    )

    Training Arguments

    training_args

    =

    TrainingArguments

    (

        output_dir

    =

    OUTPUT_DIR

    ,

        per_device_train_batch_size

    =

    4

    ,

         

    batch size for each card

    per_device_eval_batch_size

    =

    4

    ,

    gradient_accumulation_steps

    =

    4

    ,

         

    Gradient accumulation, equivalent to a larger batch

    learning_rate

    =

    2e-5

    ,

                     

    Learning rate, 2e-5 to 5e-5 is a common range

    num_train_epochs

    =

    3

    ,

                     

    Number of training rounds, 2-5 rounds is suitable

    logging_steps

    =

    10

    ,

                       

    Record every 10 steps

    evaluation_strategy

    =

    "epoch"

    ,

           

    Evaluate once per epoch

    save_strategy

    =

    "epoch"

    ,

                 

    Save once per epoch

    fp16

    =

    True

    ,

                             

    Train with mixed precision

    bf16

    =

    False

    ,

                             

    If the GPU is Ampere or higher (30/40 series), you can set bf16=True

    optim

    =

    "paged_adamw_32bit"

    ,

             

    Paged optimizer to prevent OOM

    report_to

    =

    "none"

    ,

                       

    Do not report to platforms like wandb

    save_total_limit

    =

    3

    ,

                     

    Save at most 3 checkpoints

    load_best_model_at_end

    =

    True

    ,

           

    Finally load the best model

    metric_for_best_model

    =

    "eval_loss"

    ,

     

    Select the best model using eval loss

    )

    ============================================

    2. Load and format data

    ============================================

    def

    format_example

    (

    example

    )

    :

       

    """Format Alpaca format data into model input"""

    instruction

    =

    example

    [

    "instruction"

    ]

    input_text

    =

    example.

    get

    (

    "input"

    ,

    ""

    )

    output

    =

    example

    [

    "output"

    ]

       

    if

    input_text.

    strip

    (

    )

    ==

    ""

    :

           

    When there is no additional input

    prompt

    =

    f

    """Below is an instruction that describes a task. Write a response that appropriately completes the request.

    Instruction:

    {instruction}

    Response:

    """

       

    else

    :

           

    when there is extra input

    prompt

    =

    f

    """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

    Instruction:

    {instruction}

    Input:

    {input_text}

    Response:

    """

       

    The complete text is prompt + output

       

    return

    {

           

    "prompt"

    : prompt

    ,

           

    "completion"

    : output

    ,

           

    "text"

    : prompt + output

       

    }

    Load data

    dataset

    =

    load_dataset

    (

    "json"

    ,

    data_files

    =

    DATA_PATH

    ,

    split

    =

    "train"

    )

    Split the training set and validation set (90% training, 10% validation)

    dataset

    =

    dataset.

    train_test_split

    (

    test_size

    =

    0.1

    ,

    seed

    =

    42

    )

    train_dataset

    =

    dataset

    [

    "train"

    ]

    eval_dataset

    =

    dataset

    [

    "test"

    ]

    Format data

    train_dataset

    =

    train_dataset.

    map

    (

    format_example

    )

    eval_dataset

    =

    eval_dataset.

    map

    (

    format_example

    )

    print

    (

    f

    "Training set size: {len(train_dataset)}"

    )

    print

    (

    f

    "Validation set size: {len(eval_dataset)}"

    )

    ============================================

    3. Load model and tokenizer

    ============================================

    print

    (

    "Loading model..."

    )

    tokenizer

    =

    AutoTokenizer.

    from_pretrained

    (

    MODEL_NAME

    )

    tokenizer.

    pad_token

    =

    tokenizer.

    eos_token

     

    Set pad token

    tokenizer.

    padding_side

    =

    "right"

             

    padding from the right

    model

    =

    AutoModelForCausalLM.

    from_pretrained

    (

    MODEL_NAME

    ,

    quantization_config

    =

    bnb_config

    ,

    device_map

    =

    "auto"

    ,

    trust_remote_code

    =

    True

    ,

    use_auth_token

    =

    True

    ,

     

    If you need to log in to HuggingFace

    )

    Wrap LoRA

    model

    =

    get_peft_model

    (

    model

    ,

    lora_config

    )

    model.

    print_trainable_parameters

    (

    )

     

    Print the ratio of trainable parameters

    ============================================

    4. Create the trainer and start training

    ============================================

    trainer

    =

    SFTTrainer

    (

    model

    =

    model

    ,

    train_dataset

    =

    train_dataset

    ,

    eval_dataset

    =

    eval_dataset

    ,

    args

    =

    training_args

    ,

    tokenizer

    =

    tokenizer

    ,

    peft_config

    =

    lora_config

    ,

    dataset_text_field

    =

    "text"

    ,

     

    Which field contains the full text

    max_seq_length

    =

    2048

    ,

           

    Maximum sequence length

    packing

    =

    False

    ,

                 

    Do not package samples

    )

    print

    (

    "Starting training..."

    )

    trainer.

    train

    (

    )

    print

    (

    "Training complete!"

    )

    ============================================

    5. Save Model

    ============================================

    Save LoRA adapter (small size, a few MB to tens of MB)

    model.

    save_pretrained

    (

    f

    "{OUTPUT_DIR}/lora_adapter"

    )

    tokenizer.

    save_pretrained

    (

    f

    "{OUTPUT_DIR}/lora_adapter"

    )

    print

    (

    f

    "LoRA adapter saved to {OUTPUT_DIR}/lora_adapter"

    )

    If you want to merge LoRA weights (optional)

    merged_model = model.merge_and_unload()

    merged_model.save_pretrained(f"{OUTPUT_DIR}/merged_model")

    tokenizer.save_pretrained(f"{OUTPUT_DIR}/merged_model")

    The merged model has been saved to {OUTPUT_DIR}/merged_model

    If you want a simpler way, you can use LLaMA-Factory, which provides both a Web UI and a command-line interface:

    Instance

    ============================================

    Training with LLaMA-Factory

    ============================================

    Method one: Start the Web UI (most intuitive)

    cd

    LLaMA-Factory

    python src

    /

    train_web.py

    Method two: Command-line training (suitable for automation)

    python src

    /

    train.py

    --model_name_or_path mistralai

    /

    Mistral-7B-v0.2

       

    --dataset

    runoob_ecommerce

    --dataset_dir .

    /

    data \

    --output_dir .

    /

    output

    /

    runoob-model \

    --finetuning_type lora \

    --quantization_bit

    4

    \

    --lora_rank

    16

    \

    --lora_alpha

    16

    \

    --lora_dropout

    0.05

    \

    --lora_target q_proj,v_proj,k_proj,o_proj,gate_proj,up_proj,down_proj

    --per_device_train_batch_size

    4

    \

    --gradient_accumulation_steps

    4

    \

    --lr_scheduler_type cosine \

    --logging_steps

    10

    \

    --save_strategy epoch \

    --learning_rate 2e-5 \

    --num_train_epochs

    3

    \

       

    --fp16

    true

    \

    --plot_loss

    true

    Training hyperparameter settings

    Hyperparameter selection is an art, but there are also some rules of thumb.

    Learning Rate: This is the most important hyperparameter. For LoRA, 2e-5 to 5e-5 is a safe starting point. If training is unstable (loss oscillates), decrease it a bit. If training is too slow (loss decreases very slowly), increase it a bit.

    Batch Size: The larger, the better, but limited by VRAM. Setting per_device_train_batch_size to 2, 4, or 8 is fine. If VRAM is insufficient, use gradient_accumulation_steps to accumulate gradients. For example, batch_size=2 and accumulation_steps=4 is equivalent to batch_size=8.

    Epochs: 2-5 rounds are relatively suitable. Too few and the model hasn't learned, too many might lead to overfitting. You can monitor the eval loss and stop when the eval loss stops decreasing.

    LoRA Rank (r): 8-64 are all acceptable. 16 is a good starting point. Use 8 for small tasks and 32 or 64 for complex tasks.

    Max Sequence Length: Decide based on your data. 512, 1024, 2048, and 4096 are common. Longer sequences require more VRAM.

    Hyperparameters Recommended starting values Adjustment direction
    learning_rate 2e-5 Decrease if loss oscillates, increase if it decreases too slowly
    per_device_train_batch_size 4 Increase if VRAM is sufficient, decrease if insufficient
    gradient_accumulation_steps 4 Effective batch = batch_size × accumulation
    num_train_epochs 3 Decrease for overfitting, increase for underfitting
    lora_rank (r) 16 Simple tasks 8, complex tasks 32-64
    max_seq_length 1024 or 2048 Adjust according to your data length

    Training monitoring and Loss interpretation

    Which metrics to focus on during training.

    Signs of Overfitting: Eval loss decreases then increases, while train loss continues to decrease. Solutions: reduce epochs, increase dropout, increase data, decrease LoRA rank.

    Signs of Underfitting: Both train loss and eval loss are high and decrease very slowly. Solutions: increase epochs, increase LoRA rank, increase data, slightly increase the learning rate.


    Evaluating Fine-tuning Effectiveness

    After training is complete, how do you know if the model is good?

    Choosing Evaluation Metrics

    The evaluation method depends on your task type.

    The first method is human evaluation. People read the model's output and score the quality. This is the most reliable way, but also the most time-consuming.

    A simple scoring sheet can be created:

    Example

    ============================================

    Simple Human Evaluation Template

    ============================================

    evaluation_prompts

    =

    [

       

    {

           

    "instruction"

    :

    "Generate an e-commerce product description"

    ,

           

    "input"

    :

    "Product Name: Portable Coffee Maker\nFeatures: One-button extraction, portable design, USB charging"

    ,

           

    "reference"

    :

    This portable coffee machine lets you enjoy freshly ground coffee anytime, anywhere. One-button brewing operation is simple, and the compact and portable design is suitable for office, travel, and outdoor use. The USB charging design means you don't have to worry about power issues.

       

    }

    ,

       

    {

           

    "instruction"

    :

    "Generate an e-commerce product description"

    ,

           

    "input"

    :

    "Product Name: Mechanical Keyboard\nFeatures: Blue switches, RGB backlight, 87 keys, PBT keycaps"

    ,

           

    "reference"

    :

    "This 87-key mechanical keyboard uses crisp blue switches, offering an excellent typing feel. Full-key RGB backlighting ensures clarity even at night. The PBT keycaps are durable and resist shine, keeping them looking new even with long-term use."

       

    }

    ,

       

    ... 10-20 test cases

    ]

    def

    evaluate_model

    (

    model

    ,

    tokenizer

    ,

    prompts

    )

    :

       

    """Evaluate the model with a set of prompts"""

    results

    =

    [

    ]

       

    for

    item

    in

    prompts:

           

    Generate output

    inputs

    =

    format_example_for_inference

    (

    item

    )

    output

    =

    generate_with_model

    (

    model

    ,

    tokenizer

    ,

    inputs

    )

    results.

    append

    (

    {

               

    "instruction"

    : item

    [

    "instruction"

    ]

    ,

               

    "input"

    : item

    [

    "input"

    ]

    ,

               

    "model_output"

    : output

    ,

               

    "reference"

    : item

    [

    "reference"

    ]

    ,

               

    Leave blank for rating

               

    "score_relevance"

    :

    None

    ,

     

    1-5, relevance

               

    "score_quality"

    :

    None

    ,

       

    1-5, quality

               

    "score_format"

    :

    None

    ,

       

    1-5, format correctness

           

    }

    )

       

    return

    results

    Run evaluation

    results

    =

    evaluate_model

    (

    model

    ,

    tokenizer

    ,

    evaluation_prompts

    )

    Save the results for subsequent manual scoring

    with

    open

    (

    "evaluation_results.json"

    ,

    "w"

    ,

    encoding

    =

    "utf-8"

    )

    as

    f:

    json.

    dump

    (

    results

    ,

    f

    ,

    ensure_ascii

    =

    False

    ,

    indent

    =

    2

    )

    print

    (

    "Evaluation results saved. Please score manually before analyzing."

    )

    The second method is automatic evaluation, using metrics like BLEU, ROUGE, and BLEURT. These metrics are not perfect, but they allow for rapid iteration.

    The third is A/B testing. Mix the outputs of the old and new models and have people blind-rate them to see if the new model is truly better.

    Prevent overfitting

    Overfitting is the most common problem in fine-tuning. It manifests as good performance on the training set but poor performance on new data.

    Methods to prevent overfitting:

    1. Early Stopping: Monitor eval loss and stop training when it stops decreasing.

    2. Increase data: More and more diverse data is the best way to prevent overfitting.

    3. Data augmentation: Rewrite existing data to create variations.

    4. Reduce model capacity: Reduce LoRA rank and the number of LoRA layers.

    5. Add Dropout: Set lora_dropout in the LoRA configuration to 0.05 or 0.1.

    6. Weight Decay: Add weight_decay=0.01 to the training parameters.


    Fine-tuning model deployment

    The model is trained, how to use it?

    Load LoRA for inference

    The first way is to load the original model, then load the LoRA adapter.

    Example

    ============================================

    Load LoRA and perform inference

    ============================================

    import

    torch

    from

    transformers

    import

    AutoModelForCausalLM

    ,

    AutoTokenizer

    from

    peft

    import

    PeftModel

    def

    load_finetuned_model

    (

    base_model_name

    ,

    lora_adapter_path

    )

    :

       

    """Load the base model and LoRA adapter"""

       

    Load tokenizer

    tokenizer

    =

    AutoTokenizer.

    from_pretrained

    (

    base_model_name

    )

    tokenizer.

    pad_token

    =

    tokenizer.

    eos_token

       

    Load base model

    model

    =

    AutoModelForCausalLM.

    from_pretrained

    (

    base_model_name

    ,

    device_map

    =

    "auto"

    ,

    torch_dtype

    =

    torch.

    float16

    ,

    trust_remote_code

    =

    True

    ,

       

    )

       

    Load LoRA adapter

    model

    =

    PeftModel.

    from_pretrained

    (

    model

    ,

    lora_adapter_path

    )

       

    Merge weights (optional, for faster inference)

    model

    =

    model.

    merge_and_unload

    (

    )

       

    return

    model

    ,

    tokenizer

    def

    generate_product_description

    (

    model

    ,

    tokenizer

    ,

    product_name

    ,

    features

    )

    :

       

    """Generate e-commerce product descriptions"""

       

    Construct the prompt (just like during training!)

    prompt

    =

    f

    """Below is an instruction that describes a task. Write a response that appropriately completes the request.

    Instruction:

    Generate an e-commerce product description

    Input:

    Product Name: {product_name}
    Features: {features}

    Response:

    """

       

    Generate

    inputs

    =

    tokenizer

    (

    prompt

    ,

    return_tensors

    =

    "pt"

    )

    .

    to

    (

    model.

    device

    )

       

    with

    torch.

    no_grad

    (

    )

    :

    outputs

    =

    model.

    generate

    (

    **inputs

    ,

    max_new_tokens

    =

    200

    ,

    temperature

    =

    0.7

    ,

         

    Controls randomness, 0-1, the larger the value the more random

    top_p

    =

    0.9

    ,

    do_sample

    =

    True

    ,

    pad_token_id

    =

    tokenizer.

    eos_token_id

    ,

           

    )

       

    Decode output

    generated_text

    =

    tokenizer.

    decode

    (

    outputs

    [

    0

    ]

    ,

    skip_special_tokens

    =

    True

    )

       

    Only take the Response part

    response

    =

    generated_text.

    split

    (

    "### Response:"

    )

    [

    1

    ]

    .

    strip

    (

    )

       

    return

    response

    ============================================

    Usage example

    ============================================

    BASE_MODEL

    =

    "mistralai/Mistral-7B-v0.2"

    LORA_PATH

    =

    "output/runoob-ecommerce-model/lora_adapter"

    print

    (

    "Loading model..."

    )

    model

    ,

    tokenizer

    =

    load_finetuned_model

    (

    BASE_MODEL

    ,

    LORA_PATH

    )

    print

    (

    "Model loading complete!"

    )

    Test generation

    product_name

    =

    "Smart robot vacuum cleaner"

    features

    =

    "Laser navigation, automatic recharging, APP control, 2000Pa strong suction"

    description

    =

    generate_product_description

    (

        model

    ,

    tokenizer

    ,

    product_name

    ,

    features

    )

    print

    (

    f

    "\nProduct Name: {product_name}"

    )

    print

    (

    f

    "Generated description:\n{description}"

    )

    Deployment methods

    There are several common deployment options.