Large-Model Training and Inference on Limited GPU Resources: Engineering Practices

    This article examines engineering choices for training and serving very large models when GPU capacity is limited and supply is unstable. It covers 3D hybrid parallelism and partitioning metrics, checkpointing and recovery, KV cache estimation and concurrency, latency metrics and speculative decoding, and a minimal Kubernetes deployment with an operational checklist. Readers get practical rules for measuring tradeoffs and avoiding common failure modes.

    Training and serving very large models with limited, unstable GPU supply is fundamentally an engineering problem. The choices made during implementation directly determine whether training completes and whether inference services can launch reliably. This article discusses common approaches for both training and inference, including their principles, applicable conditions, and costs, and provides configuration guidance for cloud-native deployment. It does not include benchmark scores for specific models. To compare model capabilities, use public evaluation sets and results from the same comparison baseline.

    Training: 3D Hybrid Parallelism and Partitioning Decisions

    A single GPU usually cannot hold the parameters, gradients, and optimizer states of a very large model. Training must be partitioned across multiple GPUs and nodes. The industry commonly combines data parallelism, tensor parallelism, and pipeline parallelism into 3D hybrid parallelism, with each method serving a different role:

    • Data parallelism: each replica processes a different data batch, mainly to increase throughput. Communication occurs during gradient synchronization.
    • Tensor parallelism: splits matrix operations within a layer across multiple GPUs. Communication is frequent, so it is usually kept within a node and depends on high-bandwidth intra-node interconnects.
    • Pipeline parallelism: divides the model by layers into different stages, passing only activations between stages. It scales across nodes but introduces pipeline bubbles.

    There is no universal answer for the partitioning ratio. It depends on the number of model layers, per-GPU memory, intra-node and inter-node network bandwidth, and batch size. In practice, first set the tensor parallelism degree based on the number of GPUs per node, then split the model with pipeline parallelism, and finally scale out with data parallelism to the target size.

    At each step, use quantifiable metrics to decide whether the configuration meets expectations. At least four metrics should be observed:

    1. Communication share: communication time as a proportion of total step time. If it remains high, check whether tensor parallelism is crossing nodes.
    2. Pipeline bubble share: with GPipe-style scheduling, the bubble ratio can be approximated as (p-1)/(m+p-1), where p is the number of pipeline stages and m is the number of microbatches. Increasing m can reduce bubbles but increases memory usage.
    3. Per-GPU memory headroom: the gap between peak training memory and available per-GPU memory. If headroom is too small, long sequences or large batches can suddenly cause out-of-memory errors at a particular step. The safety margin should be determined through stress testing.
    4. Scaling efficiency: after each scale-up, how much effective throughput per GPU drops relative to the small-scale baseline. A significant drop indicates that communication or waiting has consumed the scaling benefit.

    The decision rule is: if communication share or bubble share exceeds the baseline measured by the team at small scale, step back by reducing cross-node tensor parallelism, or adjust the number of pipeline stages and microbatches, then measure again. Only after the metrics return to the expected range should data parallelism be scaled further.

    FlashAttention reduces memory reads and writes of intermediate results by computing attention in blocks, with greater benefits in long-sequence scenarios. It depends on specific GPU architectures and operator versions. After upgrading the framework or driver, numerical results and training speed must be revalidated.

    Common pitfalls:

    • Deploying tensor parallelism across nodes, so communication queues on inter-node links and throughput decreases.
    • Looking only at total throughput without monitoring communication share, and discovering low scaling efficiency only after scaling up.
    • Reusing old configurations after a framework upgrade without rechecking the loss curve and numerical results.

    Training: Checkpointing and Recovery

    In large-scale clusters, hardware failures and network jitter will occur. Training jobs should assume interruptions will happen and keep the loss from each interruption manageable.

    Distributed checkpointing is the primary mechanism. A checkpoint should include model parameters, optimizer states, learning rate scheduler state, data reader position, and random seeds. Saving only parameters is insufficient for full recovery, because data order will be misaligned and the learning rate may jump.

    Asynchronous writes can reduce training stalls. The process is to copy state to memory first, then have a background thread write it to highly available storage, so the main training process does not need to wait for storage completion. Write failures should trigger alerts, and the most recent successful checkpoints should be retained to avoid overwriting the only usable copy.

    The checkpoint interval involves a tradeoff between two costs. More frequent saves increase storage writes and training stalls; less frequent saves increase the number of steps that must be recomputed after a failure. The Young-Daly approximation can be used as a starting point:

    Optimal interval ≈ √(2 × blocking time per checkpoint × mean time between failures)

    Both inputs should come from the team’s own cluster monitoring data. If save time increases or failures become more frequent, the interval should be shortened accordingly. The formula only provides an order-of-magnitude estimate; the final interval still needs to be reviewed against the actual training curve and storage cost.

    Recovery time depends on checkpoint size, storage bandwidth, and how quickly the scheduler can replace nodes. Teams should run recovery drills regularly, record the time of each phase from failure detection to training resumption, and use measured data to calibrate the checkpoint strategy.

    Common pitfalls:

    • Saving only model parameters, so after recovery the data order and learning rate differ from those before the interruption.
    • Storing checkpoints and training data in the same failure domain, so both fail together during a storage failure.
    • Never rehearsing the recovery process, and discovering script or permission issues only during a real failure.

    Inference: KV Cache Estimation and Concurrency Settings

    The bottleneck in inference is often GPU memory. During autoregressive generation, each request’s KV cache grows with context length. If contiguous memory is reserved for each request at maximum length, large amounts of fragmentation remain and concurrency is limited.

    The per-request KV cache footprint can be estimated with the following formula:

    Per-request KV cache bytes = 2 × layers × KV heads × head dimension × bytes per element × context length

    Here, 2 represents the Key and Value caches. For example, assume 80 layers, 8 KV heads, head dimension 128, FP16 (2 bytes per element), and a context length of 4096 tokens. The per-request requirement is approximately 2 × 80 × 8 × 128 × 2 × 4096 ≈ 1.34 × 10^9 bytes, or about 1.25 GiB. Actual parameters should be taken from the model configuration file.

    Concurrency can be determined as follows:

    Memory available for KV cache = GPU memory × memory utilization cap − model weights − activation and runtime overhead
    Concurrency upper bound ≈ memory available for KV cache ÷ per-request KV cache bytes

    This result is only a theoretical upper bound. Request length distributions are usually uneven, and averages hide long-tail requests. Actual concurrency must be confirmed through stress testing.

    PagedAttention divides the KV cache into fixed-size blocks allocated on demand, similar to operating system paging. This reduces internal fragmentation and allows the same amount of memory to hold more requests. Continuous batching dynamically adds and removes requests at each decoding step, preventing long requests from slowing down an entire batch of short requests.

    Tuning can be checked in the following order:

    1. Confirm whether the maximum context length exceeds actual business needs. Lowering the cap reduces the per-request KV cache footprint.
    2. Observe memory levels and distinguish model weight usage from KV cache usage.
    3. Gradually increase concurrency and record changes in throughput and queue time.
    4. Stop increasing load when queue time rises significantly, return to the previous stable point, and use that point as the capacity limit.

    Whether GPU utilization can be improved depends on batching strategy, memory level, and request length distribution. High utilization does not mean low latency; both should be observed together.

    Common pitfalls:

    • Reserving contiguous memory for each request at the maximum context length, causing concurrency to be far below the level the system can actually support.
    • Judging capacity solely by GPU utilization while ignoring that queue time has already increased.
    • Planning capacity using average request length, so the service suddenly slows down when long requests arrive together.

    Inference: TTFT, TPOT, and Speculative Decoding

    Online services usually focus on two latency metrics. Time to first token (TTFT) is the time from request arrival to the first output token, mainly affected by prefill computation over the input length. Time per output token (TPOT) measures the speed of each subsequent output token, mainly limited by memory bandwidth during decoding.

    Common ways to reduce TTFT include:

    • Limiting the maximum input length per request, or applying chunked prefill to very long inputs.
    • Using prefix caching to reuse the KV cache of repeated prefixes such as system prompts.
    • In load balancing, preferring instances with higher cache hit rates.

    Speculative decoding uses a small model to quickly generate candidate tokens, which are then verified in parallel by the large model. A single forward pass of the large model can determine whether multiple candidates are accepted.

    The speedup depends on the acceptance rate. Under a simplified assumption with acceptance rate α and draft length k per round, the average number of tokens obtained per large-model verification round is approximately (1 - α^(k+1)) ÷ (1 - α). When the acceptance rate is low, lengthening the draft adds little benefit, while the extra computation of the draft model is always paid.

    Before launch, use the following method to decide:

    1. On a request distribution similar to production, measure end-to-end throughput with speculative decoding enabled and disabled, including the extra cost of the draft model.
    2. Measure the actual acceptance rate. If it is below the threshold set by the team, disable speculative decoding for that scenario.
    3. Compare output quality using an evaluation set. With the standard acceptance criterion, the output distribution is theoretically consistent with the large model, but implementation details and numerical errors still need to be confirmed through evaluation.

    Frequently Asked Questions

    How do you determine whether TTFT needs optimization? First look at the input length distribution. If long inputs dominate, TTFT is mainly determined by prefill, and chunked processing and prefix caching should be prioritized. If TTFT is also high for short inputs, check queue time; the problem is often in scheduling rather than computation.

    Does speculative decoding always accelerate inference? No. If the small model quality is poor or the task output is highly random, the acceptance rate will decrease, and the extra computation of the draft model will offset the benefit. Use measured end-to-end throughput as the basis.

    Common pitfalls:

    • Looking only at speculative decoding speed for a single request without measuring end-to-end throughput in batch scenarios.
    • Applying the default draft length directly even when the draft model and large model have very different distributions.

    Cloud-Native Deployment: Minimal Configuration and Elastic Scaling

    When models need to scale dynamically with peak and off-peak traffic, manually managing bare-metal servers struggles to keep up with iteration speed. Many enterprises choose to build a model-as-a-service (MaaS) platform on Kubernetes, with container platforms and elastic GPU resources provided by cloud providers.

    The following is a minimal configuration example for an inference service. It is illustrative only. The image, model path, node labels, and probe paths must be replaced with the team’s actual values and validated in a test cluster before production use.

    1. apiVersion: apps/v1
    2. kind: Deployment
    3. metadata:
    4. name: llm-inference-service
    5. labels:
    6. app: llm-inference
    7. spec:
    8. replicas: 2
    9. selector:
    10. matchLabels:
    11. app: llm-inference
    12. template:
    13. metadata:
    14. labels:
    15. app: llm-inference
    16. spec:
    17. nodeSelector:
    18. accelerator: nvidia-gpu-example # Replace with the node label for a validated instance type in the cluster
    19. containers:
    20. - name: inference
    21. image: registry.example.com/llm-serving:1.0.0 # Replace with your own image
    22. args:
    23. - "--model=/models/llm-demo"
    24. - "--max-model-len=8192"
    25. - "--port=8000"
    26. ports:
    27. - containerPort: 8000
    28. env:
    29. - name: MODEL_DIR
    30. value: /models/llm-demo
    31. resources:
    32. requests:
    33. cpu: "4"
    34. memory: 32Gi
    35. nvidia.com/gpu: 1
    36. limits:
    37. cpu: "8"
    38. memory: 48Gi
    39. nvidia.com/gpu: 1
    40. readinessProbe:
    41. httpGet:
    42. path: /health/ready
    43. port: 8000
    44. initialDelaySeconds: 60
    45. periodSeconds: 10
    46. livenessProbe:
    47. httpGet:
    48. path: /health/live
    49. port: 8000
    50. initialDelaySeconds: 300
    51. periodSeconds: 20
    52. volumeMounts:
    53. - name: model-cache
    54. mountPath: /models
    55. - name: shm
    56. mountPath: /dev/shm
    57. volumes:
    58. - name: model-cache
    59. persistentVolumeClaim:
    60. claimName: model-cache-pvc
    61. - name: shm
    62. emptyDir:
    63. medium: Memory
    64. sizeLimit: 16Gi
    65. ---
    66. apiVersion: v1
    67. kind: Service
    68. metadata:
    69. name: llm-inference-service
    70. spec:
    71. selector:
    72. app: llm-inference
    73. ports:
    74. - port: 80
    75. targetPort: 8000

    Configuration notes:

    • GPU scheduling: request GPUs through nvidia.com/gpu, and requests and limits must be equal. Node labels pin the service to validated GPU instance types and prevent scheduling onto nodes with different memory specifications.
    • Model loading: place weights on a persistent volume and load from that path at startup. When multiple replicas read the same directory, the storage must support multi-node reads; otherwise, prewarm a local cache on each node. Cold start time must be measured, and the initial delay should be set accordingly.
    • Shared memory: multi-GPU inference often passes data through /dev/shm. The default size is usually too small and must be explicitly expanded with a memory-backed emptyDir.
    • Health checks: the readiness probe should fail before model loading completes so traffic does not reach unready instances. The liveness probe should use a lightweight endpoint and have a sufficiently long initial delay to avoid false restarts during loading.
    • Elastic scaling: CPU utilization has limited reference value for GPU inference services. Use custom metrics such as queued requests, KV cache utilization, or TTFT P95 to drive HorizontalPodAutoscaler scaling.
    • Logging and monitoring: at minimum, collect TTFT, TPOT, queue time, KV cache utilization, GPU memory usage, error rate, and restart count. These metrics are the basis for determining whether the tuning described above is effective.

    Pre-Launch Checklist

    • Parallel partitioning: communication share, pipeline bubble share, and scaling efficiency have been measured at small scale, and rollback conditions have been defined.
    • Checkpoints: parameters, optimizer states, scheduler state, data position, and random seeds are saved, and at least one recovery drill has been completed.
    • Checkpoint interval: the interval has been estimated using measured blocking time and failure interval, and checked against storage cost.
    • KV cache: per-request footprint has been estimated with the formula, concurrency stress testing has been completed, and the capacity limit has been recorded.
    • Latency observability: TTFT, TPOT, and queue time are connected to monitoring, with alert thresholds configured.
    • Speculative decoding: acceptance rate and end-to-end throughput have been measured on a distribution similar to production; scenarios below the threshold have been disabled, and output quality has been evaluated.
    • Kubernetes configuration: GPU requests and instance labels have been checked, probe paths and initial delays have been set according to measured cold start time, and shared memory has been expanded.
    • Elastic scaling: scaling metrics are not based solely on CPU utilization, and scaling behavior has been validated under stress-test traffic.