GPU สำหรับ AI ฉบับเข้าใจง่าย: VRAM, CUDA Cores, Tensor Cores และทุกเรื่องที่เกี่ยวข้อง¶
ประโยคนี้คุณคงได้ยินจนชิน: "จะ train AI model ต้องมี GPU" แต่ทำไมต้องเป็น GPU? GPU ทำอะไรได้ที่ CPU ทำไม่ได้? CUDA Cores, Tensor Cores และ VRAM คืออะไร แล้วทำไม AI engineer ถึงจ้องตัวเลขพวกนี้กันนัก?
บทความนี้เริ่มจากศูนย์ ค่อย ๆ ปูพื้นจนเห็นภาพ GPU hardware สำหรับ AI ครบทั้งระบบ อ่านจบแล้วคุณจะรู้ว่าตอน model กำลัง train ข้างในชิปเกิดอะไรขึ้นบ้าง และจะเลือก hardware ให้เหมาะกับงานยังไง
ตอนที่ 1: ทำไม AI ต้องรันบน GPU ไม่ใช่ CPU¶
โจทย์จริง: AI คือ Matrix Math จำนวนมหาศาล¶
ถ้าตัดรายละเอียดออกให้หมด ทุก layer ของ neural network ทำงานอยู่อย่างเดียวซ้ำไปเรื่อย ๆ:
ตรง weights × input คือ matrix multiplication ก็คือ multiply-add จำนวนมากเรียงกันเป็นตาราง แค่ train transformer layer เดียวกับ batch เดียว ก็ต้องคำนวณแบบนี้เป็นพันล้านครั้งแล้ว
CPU ออกแบบมาเพื่อ งานที่ทำทีละขั้นและมีทางแยกเยอะ เช่น รัน operating system, จัดการ database transaction, รัน business logic CPU มี core ความถี่สูงแค่ 16–128 core แต่ละ core เก่งเรื่องรันงานซับซ้อนให้จบเร็ว ๆ ทีละงาน
ส่วน GPU ออกแบบมาเพื่อ งานแบบ parallel ที่ทำซ้ำเหมือนกันหมด คือคิดเลขง่าย ๆ สูตรเดียวกันกับข้อมูลเป็นพันชุดในเวลาเดียวกัน
CPU: 128 powerful cores
→ great at complex, sequential tasks
→ 128 matrix multiplications at once
GPU: 16,384 simpler cores
→ great at simple, repetitive tasks
→ 16,384 matrix multiplications at once
พอเป็น matrix math GPU ชนะขาดหลาย order of magnitude GPU รุ่นใหม่ทำ floating-point operation ต่อวินาทีได้มากกว่า CPU ราว 1,000 เท่า บน workload เดียวกัน
เทียบให้เห็นภาพ¶
CPU = a team of 16 expert surgeons
Each can do complex, multi-step procedures.
Sequential, specialized.
GPU = a factory floor with 16,000 workers
Each does one simple repetitive action.
Parallel, coordinated.
train neural network คืองานโรงงาน ไม่ใช่งานผ่าตัด
ตอนที่ 2: ผ่า GPU ดูข้างใน — Architecture ตั้งแต่บนจนล่าง¶
ก่อนไปถึง CUDA Cores กับ Tensor Cores ต้องรู้จักบ้านของทั้งคู่ก่อน นั่นคือ Streaming Multiprocessor (SM)
Streaming Multiprocessor (SM)¶
SM คือหน่วยพื้นฐานที่ประกอบกันเป็น NVIDIA GPU ลองนึกว่าเป็น processor ตัวเล็ก ๆ ข้างในมี compute unit หลายแบบ มี shared memory และมี scheduler ของตัวเอง
┌─────────────────────────────────────────────────────┐
│ Streaming Multiprocessor (SM) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ CUDA │ │ Tensor │ │ Special Function│ │
│ │ Cores │ │ Cores │ │ Units (SFU) │ │
│ │ (FP32) │ │ (MMA) │ │ (sin, cos, etc) │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Shared Memory / L1 Cache (192 KB on H100) │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ Warp │ │ Register│ │ Load/Store │ │
│ │ Scheduler│ │ File │ │ Units (LSU) │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────┘
GPU หนึ่งตัวก็คือ SM จำนวนมากวางเรียงกันเป็น grid ทุกตัวต่อเข้ากับ shared L2 cache และต่อไปที่ VRAM ผ่าน memory bus ที่ bandwidth สูงมาก:
GPU Die:
┌─────────────────────────────────────────────┐
│ SM SM SM SM SM SM SM SM SM SM │
│ SM SM SM SM SM SM SM SM SM SM │
│ ... (132 SMs on H100) │
│ │
│ ████████████ L2 Cache ████████████████ │
│ │
│ ════════════ Memory Bus (5120-bit) ════ │
│ │
│ HBM3 HBM3 HBM3 HBM3 HBM3 HBM3 (VRAM) │
└─────────────────────────────────────────────┘
สเปก GPU ที่ต้องดู และแต่ละตัวบอกอะไร¶
| Spec | วัดอะไร | สำคัญยังไง |
|---|---|---|
| CUDA Core count | FP32 parallelism | throughput ของงาน compute ทั่วไป |
| Tensor Core count | ความเร็วในการคูณ matrix | throughput ของ AI training/inference |
| VRAM capacity (GB) | ข้อมูลบนชิปจุได้เท่าไร | model ใหญ่สุดที่ใส่ได้ |
| Memory bandwidth (TB/s) | ส่งข้อมูลไปถึง core ได้เร็วแค่ไหน | ความเร็วของ op ที่ติด memory-bound |
| TFLOPs | floating-point op หน่วยล้านล้านครั้งต่อวินาที | peak compute performance |
| TDP (Watts) | กินไฟเท่าไร | ค่า cooling และ infrastructure |
ตอนที่ 3: CUDA Cores — แรงงานหลักสารพัดประโยชน์ของ GPU¶
CUDA Core คืออะไร?¶
CUDA Core คือหน่วยคำนวณ floating-point หนึ่งหน่วย เจาะจงลงไปคือ FP32 (32-bit float) multiply-add unit CUDA Core หนึ่งตัวทำ FP32 multiply-add ได้หนึ่งครั้งต่อ clock cycle
H100 GPU มี 16,896 CUDA Cores ถ้าคิดที่ base clock 1.8 GHz:
CUDA Cores ทำงานยังไง: Warps กับ SIMT¶
CUDA Cores ไม่ได้รัน thread ทีละตัว แต่ทำงานแบบ SIMT (Single Instruction, Multiple Threads) scheduler จับ thread 32 ตัวมัดรวมเป็น warp หนึ่งชุด แล้วสั่งให้ทั้ง 32 ตัวรัน instruction เดียวกัน พร้อมกัน
Warp (32 threads):
Thread 0: output[0] = weight[0] × input[0]
Thread 1: output[1] = weight[1] × input[1]
Thread 2: output[2] = weight[2] × input[2]
...
Thread 31: output[31] = weight[31] × input[31]
All 32 threads run the SAME instruction,
on DIFFERENT data, at the SAME time.
เพราะแบบนี้ code ที่แตกทาง if/else เยอะจึงไม่เหมาะกับ GPU สมมติ thread ครึ่ง warp เข้า if อีกครึ่งเข้า else GPU ต้องรันทั้งสองทางเรียงกันให้ทั้ง warp อาการนี้เรียกว่า warp divergence
Occupancy: อย่าปล่อยให้ core ว่าง¶
Occupancy คือสัดส่วนของ warp ที่ทำงานอยู่ เทียบกับจำนวน warp สูงสุดที่ SM รับได้ ถ้า occupancy ต่ำ core จะนั่งว่างรอ memory การดัน occupancy ให้สูงเลยเป็นเทคนิคหลักข้อหนึ่งของการ optimize CUDA
# PyTorch example: checking GPU utilization
import torch
# Check CUDA availability
print(torch.cuda.is_available()) # True
print(torch.cuda.get_device_name(0)) # NVIDIA H100 80GB HBM3
# Profile occupancy during a kernel
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CUDA],
record_shapes=True,
) as prof:
x = torch.randn(4096, 4096, device='cuda')
y = torch.randn(4096, 4096, device='cuda')
z = torch.matmul(x, y)
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=5))
ตอนที่ 4: Tensor Cores — ตัวเร่งงาน AI ที่ซ่อนอยู่ใน GPU¶
Tensor Core คืออะไร?¶
Tensor Core คือ matrix multiply-accumulate (MMA) unit ที่ทำมาเพื่อ AI workload โดยเฉพาะ CUDA Core ทำ FP32 multiply-add ได้ทีละครั้งต่อ clock cycle แต่ Tensor Core ทำ matrix-multiply-accumulate บน matrix ขนาดเล็กได้ทั้งก้อนในหนึ่ง cycle
สิ่งที่ Tensor Core คำนวณ:
D = A × B + C
Where:
A = 16×16 matrix (input activations)
B = 16×16 matrix (weight matrix)
C = 16×16 matrix (accumulator / bias)
D = 16×16 matrix (output)
That's 16×16×16 = 4,096 multiply-adds in ONE OPERATION.
A CUDA Core does 1. A Tensor Core does 4,096.
CUDA Core กับ Tensor Core ต่างกันตรงไหน¶
CUDA Core:
1 multiply-add per clock
Works on scalars
Supports FP32, FP64, INT32
Tensor Core:
4,096 multiply-adds per clock (4th gen, FP16)
Works on matrices
Supports FP16, BF16, TF32, FP8, INT8, INT4
→ ~16× throughput vs CUDA Cores on matrix workloads
ตัวเลขที่ต้องดูสำหรับงาน AI จึงเป็น Tensor Core TFLOPs ไม่ใช่ CUDA Core TFLOPs:
| GPU | CUDA Core TFLOPs (FP32) | Tensor Core TFLOPs (BF16) |
|---|---|---|
| RTX 4090 | 82.6 | 330 |
| A100 80GB | 19.5 | 312 |
| H100 SXM | 60 | 989 |
| H200 SXM | 60 | 989 |
| B200 SXM | ~90 | ~4,500 |
Precision Format ที่ Tensor Core รองรับ¶
Tensor Core แต่ละ generation รองรับ precision format ใหม่เพิ่มขึ้น precision ยิ่งต่ำ ก็ยิ่งคำนวณได้มากต่อวินาที training และ inference ก็เร็วขึ้นตาม:
FP32 (32-bit float): Full precision. Used for optimizer states.
TF32 (19-bit float): NVIDIA's "free" speedup — same range as FP32,
less mantissa. Default in PyTorch AMP.
BF16 (16-bit float): Same exponent range as FP32, less precision.
Training standard in 2026.
FP16 (16-bit float): Smaller range than BF16. Needs loss scaling.
FP8 (8-bit float): Used for inference and forward pass in 2026.
INT8 (8-bit int): Quantized inference. ~2× speedup over FP16.
INT4 (4-bit int): Ultra-compressed inference (GPTQ, AWQ).
Precision impact on throughput (H100, relative to FP32):
FP32 → 1× (baseline)
TF32 → 3×
BF16 → 16×
FP8 → 32×
INT8 → 32×
ทำไม BF16 ถึงชนะ FP16 ในการ train LLM¶
BF16 กับ FP16 ใช้ 16 bit เท่ากัน ต่างกันที่แบ่ง bit ไปใช้คนละแบบ:
FP32: 1 sign | 8 exponent | 23 mantissa
BF16: 1 sign | 8 exponent | 7 mantissa ← same exponent range as FP32
FP16: 1 sign | 5 exponent | 10 mantissa ← smaller range → overflow/underflow
BF16 keeps the wide dynamic range of FP32 (crucial for gradient stability)
while halving the memory footprint.
LLMs train in BF16 by default in 2026.
เรียกใช้ Tensor Cores ใน PyTorch¶
import torch
# Enable TF32 for matmul (default in PyTorch >= 1.12)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
# BF16 mixed precision training — activates Tensor Cores
from torch.cuda.amp import autocast, GradScaler
model = MyTransformer().cuda()
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
# BF16 doesn't need a GradScaler (stable range)
for batch in dataloader:
optimizer.zero_grad()
with autocast(dtype=torch.bfloat16): # Tensor Cores kick in here
loss = model(batch)
loss.backward()
optimizer.step()
# Check that Tensor Cores are active:
# If input matrices are multiples of 16 (or 8 for FP8),
# cuBLAS will automatically route through Tensor Cores.
print(f"Input shape divisible by 16: {4096 % 16 == 0}") # True
กฎข้อสำคัญ: dimension ของ matrix ต้องหารด้วย 16 ลงตัว (BF16/FP16) หรือหารด้วย 8 ลงตัว (FP8/INT8) Tensor Cores ถึงจะทำงาน ถ้าไม่ลงตัวก็ pad dimension ให้ตรง
ตอนที่ 5: VRAM — memory ที่ตัดสินว่า model จะรอดหรือไม่รอด¶
VRAM คืออะไร?¶
VRAM (Video RAM) คือ memory ที่อยู่บนตัว GPU เอง (หรือซ้อนอยู่บน die เลย) system RAM ต้องส่งข้อมูลผ่าน PCIe bus กว่าจะถึง GPU แต่ VRAM ไม่ต้อง GPU อ่านได้ตรง ๆ ที่ memory bandwidth เต็มกำลัง
ของทุกอย่างที่ GPU ใช้คำนวณต้องอยู่ใน VRAM ให้หมด: - Model weights - Activations (output ของแต่ละ layer ระหว่างทาง) - Gradients (ใช้ตอน training) - Optimizer states (vector m และ v ของ Adam) - KV cache (ใช้ตอน LLM inference) - ข้อมูล input ของ batch
VRAM is the GPU's workspace.
If your model + data don't fit, training fails with:
RuntimeError: CUDA out of memory.
VRAM หายไปไหนบ้าง? (คิดให้ครบทุกก้อน)¶
สมมติ model มี P parameters และ train ด้วย AdamW แบบ BF16:
Weights: P × 2 bytes (BF16)
Gradients: P × 2 bytes (BF16)
Optimizer states: P × 8 bytes (Adam m + v in FP32 = 2 × 4 bytes each)
─────────────────────────────────────────────────────
Total for weights: P × 12 bytes
Plus activations (batch-size and sequence-length dependent):
Activations ≈ batch_size × seq_len × hidden_dim × num_layers × 2 bytes
ตัวอย่างจริง:
| Model | Parameters | VRAM ขั้นต่ำ (Inference BF16) | VRAM ขั้นต่ำ (Training BF16) |
|---|---|---|---|
| Llama 3.2 3B | 3B | ~6 GB | ~36 GB |
| Llama 3.1 8B | 8B | ~16 GB | ~96 GB |
| Llama 3.1 70B | 70B | ~140 GB | ~840 GB |
| GPT-4 class | ~1.8T | ~3.6 TB | node เดียวไม่ไหว |
# Estimate VRAM for inference
def vram_estimate_inference(params_billions, dtype_bytes=2):
"""BF16 = 2 bytes, FP32 = 4 bytes, INT8 = 1 byte"""
params = params_billions * 1e9
return (params * dtype_bytes) / (1024**3) # in GB
print(f"7B BF16: {vram_estimate_inference(7):.1f} GB") # 14.0 GB
print(f"13B BF16: {vram_estimate_inference(13):.1f} GB") # 26.0 GB
print(f"70B INT4: {vram_estimate_inference(70, 0.5):.1f} GB") # 35.0 GB
VRAM สองแบบ: GDDR6X กับ HBM3¶
VRAM แต่ละแบบไม่เท่ากัน GPU ฝั่ง consumer ใช้ GDDR6X ส่วน GPU ใน data center ใช้ HBM (High Bandwidth Memory):
GDDR6X (RTX 4090):
Capacity: 24 GB
Bandwidth: 1,008 GB/s
Location: Separate chips on PCB, connected via 384-bit bus
HBM3 (H100 SXM):
Capacity: 80 GB
Bandwidth: 3,350 GB/s
Location: Stacked directly beside/on the GPU die (2.5D/3D packaging)
HBM ซ้อน memory เป็นชั้น ๆ เหมือนตึกสูง และต่อเข้ากับ GPU die ด้วยจุดเชื่อมเล็ก ๆ หลายพันจุด bandwidth ของ H100 เลยสูงกว่า RTX 4090 ถึง 3.3 เท่า ทั้งที่ CUDA Cores สำหรับงาน gaming น้อยกว่า
Memory Bandwidth: คอขวดที่คนมองข้าม¶
AI workload หลายแบบ โดยเฉพาะ inference กับ attention ไม่ได้ติดที่ compute (Tensor Cores) แต่ติดที่ memory bandwidth คือส่ง model weights จาก VRAM ไปให้ compute unit ได้เร็วแค่ไหน
Roofline model:
Arithmetic Intensity (AI) = FLOPs ÷ bytes_accessed
If your operation's AI is BELOW the hardware ridge point:
→ Memory-bound: bandwidth is the limit
If your operation's AI is ABOVE the hardware ridge point:
→ Compute-bound: Tensor Cores are the limit
LLM inference (small batch): Memory-bound
LLM training (large batch): Compute-bound
Attention with long sequences: Memory-bound
FlashAttention เกิดมาเพื่อแก้ปัญหานี้ตรง ๆ FlashAttention เรียงลำดับการคำนวณใหม่ให้แตะ memory น้อยลง attention จึงเปลี่ยนจาก memory-bound มาเป็น compute-bound
# FlashAttention in PyTorch 2.x (uses SDPA with Flash under the hood)
import torch
import torch.nn.functional as F
q = torch.randn(1, 32, 2048, 128, device='cuda', dtype=torch.bfloat16)
k = torch.randn(1, 32, 2048, 128, device='cuda', dtype=torch.bfloat16)
v = torch.randn(1, 32, 2048, 128, device='cuda', dtype=torch.bfloat16)
# PyTorch 2.0+ automatically uses FlashAttention when available
with torch.backends.cuda.sdp_kernel(
enable_flash=True,
enable_math=False,
enable_mem_efficient=False
):
output = F.scaled_dot_product_attention(q, k, v)
# Result: same output, 2-4× faster, much less VRAM (no N×N attention matrix stored)
ตอนที่ 6: GPU แต่ละรุ่น และสถานการณ์ปี 2026¶
ไล่ Architecture ของ NVIDIA ตามปี¶
Ampere (2020) → A100: 312 TFLOPS BF16, 80GB HBM2e, 2TB/s bandwidth
The workhorse of 2021–2024 cloud AI
Hopper (2022) → H100: 989 TFLOPS BF16, 80GB HBM3, 3.35TB/s bandwidth
NVLink 4.0, Transformer Engine (FP8 dynamic scaling)
→ H200: 989 TFLOPS BF16, 141GB HBM3e, 4.8TB/s bandwidth
Same compute as H100, ~2× more memory & bandwidth
Blackwell(2024)→ B100: 1,800 TFLOPS BF16, 192GB HBM3e, 8TB/s bandwidth
→ B200: 4,500 TFLOPS BF16, 192GB HBM3e, 8TB/s bandwidth
→ GB200: B200 GPU + Grace ARM CPU in one NVL72 rack system
Transformer Engine (H100 ขึ้นไป)¶
NVIDIA ใส่ Transformer Engine มาตั้งแต่ Hopper เป็น hardware ที่เลือกให้เองว่าแต่ละ layer จะใช้ FP8 หรือ BF16 ระหว่าง training ไม่ต้องมานั่ง tune เอง:
Transformer Engine:
→ Monitors per-tensor statistics each forward pass
→ Automatically scales to FP8 where safe
→ Falls back to BF16 where precision is critical
→ 2× throughput vs BF16-only training, no accuracy loss
Enabled in PyTorch automatically when:
- GPU is H100 or later
- Using torch.float8_e4m3fn or transformer-engine library
Consumer กับ Data Center ต่างกันยังไง?¶
| Feature | RTX 4090 (Consumer) | H100 SXM (Data Center) |
|---|---|---|
| ราคา | ~$1,600 | ~$30,000 |
| VRAM | 24 GB GDDR6X | 80 GB HBM3 |
| Bandwidth | 1.0 TB/s | 3.35 TB/s |
| TFLOPs (BF16) | 330 | 989 |
| FP64 (งานวิทยาศาสตร์) | 1.5 TFLOPS | 34 TFLOPS |
| NVLink | ❌ | ✅ (900 GB/s) |
| ECC memory | ❌ | ✅ |
| PCIe form factor | Consumer slot | SXM5 board |
| เหมาะกับ | train เล่น ๆ, inference | production LLM training |
NVLink กับการ Scale หลาย GPU¶
พอ GPU ตัวเดียวไม่พอ ก็ต้องใช้หลายตัวและให้ทุกตัวคุยกันได้ ตรงนี้ interconnect ชี้ขาดเลยว่าจะ scale ได้แค่ไหน:
PCIe 4.0 (×16): ~32 GB/s bidirectional
Consumer GPUs connected to the CPU and each other
via the CPU's PCIe lanes
NVLink 4.0: 900 GB/s bidirectional (per GPU pair)
Direct GPU-to-GPU high-speed link
28× faster than PCIe
NVSwitch (DGX H100): All 8 GPUs connected all-to-all
Every GPU sees every other GPU at full NVLink speed
= 3.6 TB/s all-reduce for 8-GPU training
ผลที่เห็นจริงใน distributed training:
8× A100 via PCIe: all-reduce bottleneck = 32 GB/s
→ data parallelism poorly scaled
8× H100 via NVLink: all-reduce bottleneck = 900 GB/s
→ near-linear scaling in data parallelism
ตอนที่ 7: เลือก GPU ให้ตรงงาน¶
งาน Inference: เน้น Bandwidth ต่อเงินที่จ่าย¶
Inference ส่วนใหญ่ติด memory-bound ให้หา VRAM ที่จุพอกับ model ก่อน แล้วเลือกตัวที่ memory bandwidth สูงที่สุดเท่าที่งบไหว
Rule of thumb (inference, BF16 weights):
Model params × 2 = minimum VRAM in GB
Llama 3.1 8B → 16 GB min → RTX 4080 (16GB) or better
Llama 3.1 70B → 140 GB min → 2× H100 80GB (160GB total)
Llama 3.1 70B → 40 GB INT4 → 2× A100 40GB with GPTQ/AWQ
# Run quantized inference to fit larger models
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch
# INT4 quantization — fits 70B in ~40GB VRAM
quant_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.bfloat16, # Tensor Cores for compute
bnb_4bit_quant_type="nf4", # NormalFloat4: best accuracy
bnb_4bit_use_double_quant=True, # Extra compression
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3.1-70B-Instruct",
quantization_config=quant_config,
device_map="auto",
)
# 70B model now fits in ~40GB VRAM with <2% accuracy drop
งาน Training: เน้น TFLOPS และ VRAM Capacity¶
Training ที่ batch ใหญ่มักติด compute-bound ให้ใช้ BF16 เปิด Tensor Cores แล้วใช้ gradient checkpointing ช่วย scale คือยอมคำนวณเพิ่มเพื่อแลกกับ memory ที่ลดลง
import torch
from torch.utils.checkpoint import checkpoint_sequential
model = MyLargeTransformer(num_layers=48).cuda()
# Gradient checkpointing: recompute activations on backward pass
# Trades ~33% extra compute for ~60% less VRAM
model.gradient_checkpointing_enable()
# Combine with BF16 mixed precision
from torch.cuda.amp import autocast
optimizer = torch.optim.AdamW(model.parameters())
for batch in dataloader:
with autocast(dtype=torch.bfloat16):
loss = model(**batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
งาน Fine-Tuning: ใช้ LoRA ลด VRAM ลงฮวบ¶
Full fine-tuning model 7B กิน VRAM ราว 84GB แต่ถ้าใช้ LoRA (Low-Rank Adaptation) จะเหลือแค่ราว 16GB:
from peft import get_peft_model, LoraConfig, TaskType
from transformers import AutoModelForCausalLM
import torch
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3.1-8B",
torch_dtype=torch.bfloat16, # Half precision weights
device_map="auto",
)
lora_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=16, # Rank: low-rank matrices
lora_alpha=32, # Scaling factor
target_modules=["q_proj", "v_proj"], # Which layers to adapt
lora_dropout=0.1,
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# trainable params: 6,815,744 || all params: 8,037,384,192
# trainable%: 0.08% ← only 0.08% of weights are trained!
ตารางเลือก GPU ปี 2026¶
| Use Case | VRAM ที่ต้องใช้ | GPU ที่แนะนำ | ราคาคร่าว ๆ |
|---|---|---|---|
| ศึกษา / ทดลอง | 8–16 GB | RTX 4070 Ti (16GB) | $800 |
| 7B–13B inference | 16–24 GB | RTX 4090 (24GB) | $1,600 |
| 7B fine-tuning (LoRA) | 24 GB | RTX 4090 | $1,600 |
| 70B inference (quantized) | 48 GB | 2× RTX 4090 | $3,200 |
| 7B full fine-tuning | 80 GB | H100 (cloud) | ~$3/hr |
| 70B full fine-tuning | 640 GB+ | 8× H100 DGX | ~$25/hr |
| LLM pre-training | หลัก TB | H100/B200 cluster | Enterprise |
ตอนที่ 8: จัดการ GPU Memory ในงานจริง¶
ดู VRAM แบบ Real Time¶
import torch
def vram_status():
if not torch.cuda.is_available():
return "No CUDA GPU available"
allocated = torch.cuda.memory_allocated() / 1024**3
reserved = torch.cuda.memory_reserved() / 1024**3
total = torch.cuda.get_device_properties(0).total_memory / 1024**3
return (
f"Allocated: {allocated:.2f} GB\n"
f"Reserved: {reserved:.2f} GB\n"
f"Total: {total:.2f} GB\n"
f"Free: {total - reserved:.2f} GB"
)
print(vram_status())
# After a CUDA OOM, clear cache before retrying
torch.cuda.empty_cache()
CUDA OOM ที่เจอบ่อยและวิธีแก้¶
# ❌ Problem 1: Accumulating computation graph across batches
losses = []
for batch in dataloader:
loss = model(batch)
losses.append(loss) # Keeps the entire graph in VRAM!
total = sum(losses)
# ✅ Fix: Detach the scalar value
losses.append(loss.item()) # .item() breaks the graph
# ❌ Problem 2: Not freeing VRAM between evaluation and training
with torch.no_grad():
val_output = model(val_batch)
# val_output still lives in VRAM
# ✅ Fix: Delete explicitly or scope tightly
del val_output
torch.cuda.empty_cache()
# ❌ Problem 3: Full precision where half is fine
embeddings = model.embed(text) # FP32 by default
# ✅ Fix: Move model to BF16 upfront
model = model.to(torch.bfloat16)
ตอนที่ 9: สรุปภาพ AI Hardware ปี 2026¶
NVIDIA รุ่น Blackwell¶
ปี 2026 training platform ตัวหลักคือ B200 กับ GB200 NVL72:
B200 SXM (single GPU):
Tensor Cores TFLOPs: ~4,500 BF16 / ~9,000 FP8
VRAM: 192 GB HBM3e
Bandwidth: 8 TB/s
NVLink 5.0: 1.8 TB/s bidirectional
GB200 NVL72 (full rack):
72× B200 GPUs + 36× Grace CPUs
Total VRAM: 13.8 TB
All-reduce bandwidth: 130 TB/s
Used for: GPT-5 class pre-training
AMD MI300X — คู่แข่งที่น่าจับตา¶
ปี 2026 MI300X ของ AMD แย่งส่วนแบ่งตลาดมาได้เยอะ:
MI300X:
VRAM: 192 GB HBM3 ← most of any single-chip GPU (tied with B200)
Bandwidth: 5.3 TB/s
TFLOPs: 1,307 BF16
Best at: inference of very large models due to massive VRAM
Software: ROCm 6.x, PyTorch 2.x full support
Cloud เจ้าไหนมี GPU อะไรบ้าง (2026)¶
| Provider | GPU ที่มี | เหมาะกับ |
|---|---|---|
| AWS | H100, H200, A100 | training สเกลใหญ่ |
| Google Cloud | H100, A100, TPU v5 | workload บน JAX/TensorFlow |
| Azure | H100, ND B200 (2026) | Enterprise, จับมือกับ OpenAI |
| Lambda Labs | H100, A100 | training ราคาคุ้ม |
| RunPod | H100, A100, RTX 4090 | inference / fine-tuning งบจำกัด |
สรุป¶
GPU ครองงาน AI เพราะ neural network คือ matrix math ปริมาณมหาศาล และ GPU ออกแบบ hardware มาเพื่องานนี้โดยตรง
CUDA Cores คือหน่วยคำนวณ FP32 ใช้งานทั่วไป มีเป็นพันตัว รัน instruction เดียวกันกับข้อมูลเป็นพันชุดพร้อมกันผ่าน SIMT และ warp งานไหนไม่ใช่ matrix ก็ตกมาที่ CUDA Cores และถ้าใช้ Tensor Cores ไม่ได้ ก็ต้องกลับมาพึ่ง CUDA Cores
Tensor Cores คือตัวเร่ง AI ตัวจริงใน GPU เป็น matrix multiply-accumulate unit ที่ทำ multiply-add ได้ 4,096 ครั้งใน clock cycle เดียว แทนที่จะได้ครั้งเดียว H100 ถึงทำได้ 989 TFLOPS BF16 แทนที่จะค้างอยู่ที่ 60 Tensor Cores ทำงานเองอัตโนมัติเมื่อ dimension ของ matrix หารด้วย 16 ลงตัว และใช้ BF16, FP16, TF32 หรือ FP8 การจัด dimension ใน model ให้ลงตัวจึงไม่ใช่ทางเลือก ต้องทำ
VRAM คือพื้นที่ทำงานของทุก GPU operation capacity บอกว่า model ขนาดไหนใส่ได้ bandwidth บอกว่าคำนวณได้เร็วแค่ไหน HBM ใน GPU ฝั่ง data center วาง memory ซ้อนชิดข้าง die จึงได้ bandwidth 3–8 เท่าของ GDDR6X ฝั่ง consumer ถ้าเป็น LLM inference ตัวเลขที่สำคัญที่สุดคือ memory bandwidth ถ้าเป็น training ที่ batch ใหญ่ ให้ดู Tensor Core TFLOPs
ปี 2026 stack ทั้งหมดลงตัวแล้ว BF16 เป็น default ของ training FP8 เป็นมาตรฐานของ forward pass บน H100 ขึ้นไป LoRA ทำให้ fine-tune บน consumer GPU ตัวเดียวได้ และ FlashAttention ปลดคอขวด memory ของ attention ไม่ว่าคุณจะ train จากศูนย์บน B200 cluster หรือรัน quantized 70B model บน RTX 4090 สองตัว หลักก็เหมือนกัน: ป้อนงานให้ Tensor Cores ไม่ให้ว่าง ใช้ VRAM ให้น้อยที่สุด และรู้ให้ได้ว่า hardware ด้านไหนจะตันก่อน
มีคำถามหรืออยากคุยต่อ? ติดต่อได้ทาง LinkedIn, X หรือส่ง email
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.