LLM Fine-Tuning Preparation and GPU Memory Optimization: Scaling from a 4B to a 9B Base Model

    This article explains how to prepare a LoRA fine-tuning run when moving from a roughly 4B-parameter base model to a roughly 9B-parameter model on a single 40GB GPU. It covers the main sources of GPU memory use, why a maximum sequence length of 5120 is a safer starting point than 8192, how to choose LoRA rank, alpha, learning rate, and epochs, and how to handle long samples. It also describes out-of-memory troubleshooting, experiment logging, and a pre-launch checklist.

    1. Background and Goals: Why Training Preparation Needs Reassessment at 9B

    In practical LLM fine-tuning, moving the base model from about 4B to about 9B parameters is not a simple model swap that keeps the old configuration. A larger model changes the memory used by weights, activations, and temporary buffers, and it also changes the pressure on data throughput. Sequence length, batch size, and gradient accumulation settings that ran well on a smaller model may need to be recalibrated for the new training environment.

    The previous round used a base model of about 4B parameters. This round switches to a base model of about 9B parameters, running on a single accelerator with 40GB of GPU memory. The initial training settings are: LoRA rank 32, LoRA alpha 64, learning rate 1e-4, 2 epochs, and a maximum sequence length of 5120. The original plan was to set the maximum sequence length to 8192. In practice, that setting caused frequent out-of-memory (OOM) errors, so 5120 became the more stable starting point.

    This change shows that fine-tuning preparation should not stop at checking whether the model can load. The team also needs to confirm that training can finish reliably, that long samples will not cause memory peaks, that evaluation and checkpoint saving do not exhaust memory, and that the experiment can be reproduced. The sections below cover memory budgeting, parameter configuration, data organization, stability troubleshooting, and experiment records.

    2. Memory Budget and Sequence Length: Why 5120 Is Safer Than 8192

    2.1 Main Components of GPU Memory Use

    Training memory usually consists of several parts: model weights, trainable parameters and their optimizer states, forward activations, intermediate results from backpropagation, temporary buffers, workspace for communication or fused operators, and overhead from evaluation and logging. Parameter-efficient fine-tuning has fewer trainable parameters, so optimizer state pressure is easier to control. However, the base model weights still stay resident in GPU memory, and forward activations still grow with batch size and sequence length.

    At 16-bit precision, a rough estimate puts the weights of a 9B-parameter model at about 18GB. On a 40GB GPU, the remaining space must hold activations, temporary buffers, and training framework overhead. If the batch size or sequence length is too large, that remaining space fills up quickly. A 4B-parameter model has weights of about 8GB, which leaves much more room. For this reason, a long-sequence configuration that worked on 4B may not work after the move to 9B.

    2.2 How Sequence Length Affects Memory

    A longer sequence adds pressure in several ways. Activations grow with sequence length. In some implementations, attention intermediate results grow more sharply with length. Long sequences also increase temporary memory use during data loading, tokenization, batch packing, and evaluation.

    Raising the maximum sequence length from 5120 to 8192 looks like only about a 60% increase. In practice, the peak memory can rise much more because of attention intermediate tensors, the longest sample in each batch, whether gradient checkpointing is enabled, and temporary buffers.

    On a single 40GB GPU, 5120 is a conservative starting point that runs reliably. It covers most medium-length samples and leaves some headroom for training stability. If many samples in the dataset exceed 5120 tokens, the first step should be to analyze the length distribution. Raising the limit without that analysis is not recommended.

    2.3 Handling Tasks That Need 8K Sequences

    If a task really depends on a length of 8192, the following combination of strategies can help:

    • Calculate the length distribution of the training set, including the P95 and P99 lengths, and confirm the share of samples near 8K.
    • Use task-aware truncation for very long samples. Keep the question, the instruction, and the key context first, and avoid cutting off the end of the answer.
    • Use gradient checkpointing to reduce activation memory, accepting some extra compute cost.
    • Reduce the per-device batch size and use gradient accumulation to keep the effective batch size the same.
    • Split long samples into chunks or segments for training, and keep the necessary overlap at segment boundaries.
    • Set a smaller batch size for evaluation separately, so that evaluation does not run out of memory after training succeeds.
    • When the environment allows, use parameter sharding, optimizer state sharding, or other finer-grained memory optimization methods.

    The maximum sequence length is not a setting where bigger is always better. If only a small share of samples is long, raising the limit significantly increases memory pressure and training cost, and it may not bring a matching benefit. A more reasonable approach is to first run stably at 5120, then adjust based on the length distribution and evaluation results.

    3. Parameter-Efficient Fine-Tuning Settings: Trade-offs Among Rank, Alpha, Learning Rate, and Epochs

    3.1 LoRA Rank and Alpha

    In this configuration, the LoRA rank is 32 and alpha is 64. Rank sets the capacity of the low-rank adaptation matrices, and alpha controls how strongly the adapter output is scaled. The ratio of alpha to rank is often used as a reference for adaptation strength. Here, alpha is twice the rank, which is a common mid-range setting. For a base model of about 9B parameters, a rank of 32 can cover a reasonable range of task adaptation needs. It also avoids the rise in memory use and overfitting risk that comes with too many trainable parameters.

    The right choice depends on task complexity, dataset size, and the capability of the base model. For tasks such as format alignment, style transfer, or light instruction following, a smaller rank is a reasonable place to start. For tasks that involve complex domain knowledge injection or a mix of several tasks, the rank can be increased. In that case, training stability and validation set performance need close attention.

    3.2 Learning Rate of 1e-4

    A learning rate of 1e-4 falls in a range that needs careful monitoring for parameter-efficient fine-tuning. A rate that is too high can cause loss oscillation, degraded generation quality, or overfitting in the adapter layers. A rate that is too low can make convergence slow. Use warmup, gradient clipping, and validation set evaluation together, and watch the loss curve closely in the early stage of training.

    If the loss drops briefly and then rebounds, or if validation metrics clearly worsen, try lowering the learning rate, increasing the warmup ratio, or reducing the rank. If the loss falls too slowly, compare candidate values such as 2e-4, 1e-4, and 5e-5 in a small grid search. Do not decide based on training loss alone. Also check task metrics and sample generations.

    3.3 Two Epochs

    Two epochs is a reasonable first attempt. Parameter-efficient fine-tuning on a small dataset can overfit after several epochs, especially when the data lacks diversity. Two epochs give the model enough time to adapt initially while leaving room for observation. During training, save checkpoints and record validation metrics for each epoch, so that the final model is not the only one kept.

    If the dataset is large and the task is complex, two epochs may not be enough. If the dataset is small and highly templated, two epochs may already approach overfitting. A safer approach is to set an evaluation interval and select the best checkpoint based on validation performance, rather than mechanically using the last checkpoint.

    4. Data and Sequence Organization: Length Strategy Matters More Than Tuning Alone

    When the maximum sequence length is limited, the data organization strategy directly affects training results. Start by analyzing the length distribution to determine the share of short, medium, and very long samples. For samples longer than 5120, do not simply truncate everything. Otherwise, the answer or key context may be lost.

    Use a task-aware truncation strategy. For question-answering or instruction data, keep the instruction and question first. If the answer must be truncated, keep its beginning and its end. For summarization or extraction tasks, keep the main body of the input and the key passages first. For multi-turn dialogue, keep the most recent turns and the system instructions. If sample packing is used to improve throughput, make sure each sample has a clear boundary, and use attention masks to prevent cross-sample attention contamination.

    Also check the difference between token length and character length. Estimating length by character count can lead to actual sequences exceeding the limit. For the evaluation set, use the same length handling logic as the training set. Otherwise, offline metrics may be misleading.

    5. OOM Troubleshooting and Training Stability: From Running to Running Reliably

    When out-of-memory errors appear, do not only lower the maximum sequence length. Systematically identify where the memory peak comes from. A common troubleshooting sequence is:

    1. Confirm the training batch size, the gradient accumulation steps, and the maximum sequence length.
    2. Check whether gradient checkpointing is enabled, and whether turning it off noticeably increases memory use.
    3. Determine whether the OOM occurs early in training, on specific long samples, or during evaluation or checkpoint saving.
    4. Check whether data loading creates oversized temporary tensors.
    5. Confirm that the mixed precision settings match the model loading precision.
    6. Reduce the batch size separately for evaluation.
    7. Avoid keeping too many intermediate states when saving checkpoints.

    For training stability, enable gradient clipping, and record the gradient norm, learning rate, loss, and peak memory usage. If the loss becomes NaN, check the learning rate, data anomalies, mixed precision overflow, and the gradient accumulation logic. For long-sequence training, first run the full pipeline on a small data subset, then gradually increase the dataset size and sequence length.

    6. Training Monitoring, Evaluation, and Experiment Logging

    A reproducible fine-tuning experiment should record at least the following: base model size, training precision, maximum sequence length, LoRA rank and alpha, learning rate, number of epochs, batch size, gradient accumulation steps, gradient checkpointing setting, data version, truncation strategy, evaluation metrics, and the basis for selecting the best checkpoint.

    Evaluation should not rely only on training loss. Combine validation loss, task metrics, generated samples, and length robustness for a complete assessment. In particular, check whether the model stays stable on samples close to 5120 tokens, and whether performance regresses on short samples. For generation tasks, run a fixed test set with manual or rule-based evaluation, so that a single metric does not drive the decision.

    7. Configuration Example

    The following is a generic training configuration example. The field names convey general meaning only. Adjust them to your training framework and task requirements before use.

    1. experiment:
    2. base_model_scale: "9b"
    3. precision: "bf16"
    4. data:
    5. max_seq_length: 5120
    6. truncation_policy: "task_aware"
    7. eval_batch_size: 1
    8. lora:
    9. rank: 32
    10. alpha: 64
    11. dropout: 0.05
    12. target: "attention_and_mlp_linear"
    13. training:
    14. learning_rate: 0.0001
    15. num_train_epochs: 2
    16. per_device_batch_size: 1
    17. gradient_accumulation_steps: 8
    18. gradient_checkpointing: true
    19. warmup_ratio: 0.03
    20. max_grad_norm: 1.0
    21. logging_steps: 10
    22. save_steps: 500
    23. eval_steps: 500

    The core idea of this configuration is to treat the 40GB single-GPU memory as the main constraint and keep training reliably runnable first. A small per-device batch size with gradient accumulation keeps the effective batch size at the intended level. Gradient checkpointing controls activation memory. Evaluation intervals and checkpoint saving make it possible to track overfitting and identify the best model.

    8. Pre-Launch Checklist

    • Confirm that the precision used to load the model weights matches the training precision.
    • Confirm that the maximum sequence length covers the main business samples.
    • Confirm that the truncation strategy for very long samples keeps the key information.
    • Confirm that the LoRA rank and alpha match the task complexity.
    • Confirm that the learning rate, warmup, and gradient clipping settings are reasonable.
    • Confirm that training, evaluation, and checkpoint saving all run without OOM errors.
    • Record the data version, configuration files, and random seed.
    • Save the best checkpoint, not only the final checkpoint.
    • Complete generation quality and length robustness evaluation on a fixed test set.

    Conclusion

    Moving from a base model of about 4B parameters to one of about 9B parameters shifts the focus of fine-tuning preparation. The question is no longer only whether the configuration runs, but whether the memory budget, sequence length, data organization, and evaluation loop work together reliably. On a single 40GB GPU, reducing the maximum sequence length from 8192 to 5120 is a practical compromise for managing peak memory. The LoRA rank of 32, alpha of 64, learning rate of 1e-4, and 2 training epochs form an initial plan that can be observed, adjusted, and reproduced. High-quality fine-tuning does not come from raising parameters all at once. It comes from systematic logging, staged validation, and stability troubleshooting, which together help find a workable balance between task performance and training cost.