3.3.9 · HinglishDeep Learning Frameworks

Mixed precision training

3,286 words15 min readRead in English

3.3.9 · AI-ML › Deep Learning Frameworks

What Problem Does This Solve?

Large neural networks train karne mein teen bottlenecks hain:

  1. Memory: Modern models (GPT, Vision Transformers) mein billions of parameters hote hain. Har FP32 parameter 4 bytes leta hai. 175B parameter model ko sirf weights store karne ke liye 700GB chahiye!
  2. Compute: Matrix multiplications training time ko dominate karti hain. GPUs mein specialized hardware (Tensor Cores) hote hain jo FP16 ops ko FP32 se 2-8× faster run karte hain.
  3. Communication: Distributed training mein, gradients ko GPUs ke across sync karna padta hai. Precision aadha karne se bandwidth requirements bhi aadhi ho jaati hain.

Lekin naively FP16 par switch karne se gradient underflow hota hai: tiny gradients zero ho jaate hain, aur training diverge kar jaati hai.

Key insight yeh hai: gradients ka dynamic range bahut bada hota hai. Early layers mein gradients ke around ho sakte hain, jabki later layers mein . FP16 ki limited range dono ko represent nahi kar sakti.

How Mixed Precision Training Works

Figure — Mixed precision training

Is algorithm ke teen core components hain:

1. FP32 Master Weights

Kyun: Weight updates cumulative hote hain. Agar learning rate hai aur gradient hai, to update hoga—jo FP16 ki precision () se bhi chhota hai. Update zero ho jaayega, aur weights kabhi change nahi honge.

Kaise: Weights ki do copies maintain karo:

  • FP16 copy forward/backward passes ke liye (fast compute)
  • FP32 master copy updates accumulate karne ke liye (precision preserve karo)

Derivation from First Principles:

Ek single parameter ko gradient descent se update karte hain:

FP16 mein, agar hai, to update ban jaata hai: (chhota update zero ho jaata hai)

steps ke baad jab koi update nahi hua, humne ka accumulated change kho diya—training ruk jaati hai.

Solution: Master weights ko FP32 mein store karo: Chahe individual updates tiny hon, higher-precision master mein accumulate hote rehte hain. Phir next forward pass ke liye FP16 mein cast karo:

2. Loss Scaling

Kyun: Early layers ke gradients often FP16 ki minimum normal value () se neeche hote hain. Yeh underflow hokar zero ho jaate hain, jisse "dead neurons" ban jaate hain jo kabhi learn nahi karte.

Kya: Loss ko backprop se pehle ek bade scalar se multiply karo (typically to ). Isse gradients FP16 ke representable range mein shift ho jaate hain. Gradients compute karne ke baad, se divide karo taaki master weights update karne se pehle true values restore ho jayein.

Derivation:

Gradients ke liye chain rule deta hai:

Agar hai (deep networks mein common), to FP16 ise represent nahi kar sakta—underflow hokar zero ho jaata hai.

Loss scaling trick: Ek scaled loss define karo jahan . Tab:

Ab agar hai aur hai, to hai, jise FP16 represent kar sakta hai!

Backprop ke baad, unscale karo:

Yeh step kyun?: Scaling loss par hoti hai (computational graph ka top), isliye automatically poore backward pass mein propagate ho jaati hai. Yeh har layer ke gradients ko individually scale karne se zyaada efficient hai.

Dynamic Loss Scaling: Bade se shuru karo (jaise ). Agar gradients overflow karein (inf ya nan produce karein), ko aadha karo aur retry karo. Agar training steps (jaise ) tak stable rahe, ko double karo. Yeh har model ki gradient distribution ke hisaab se adapt karta hai.

3. FP16 Arithmetic for Most Operations

Kyun: Matrix multiplications (GEMM) training time dominate karti hain—often 90%+ compute. Modern GPUs mein Tensor Cores hain jo FP16 ops ko FP32 se 2-16× zyaada throughput par execute karte hain.

Kya: Forward/backward passes ke dauran activations, gradients, aur weights FP16 mein store karo. Sirf optimizer state aur master weights FP32 mein rehte hain.

Kaise:

  • Har forward pass ke start mein FP32 master se weights ko FP16 mein cast karo
  • Activations FP16 mein compute karo:
  • Loss compute karo aur scale karo
  • Backward pass FP16 mein (gradients FP16 mein accumulate hote hain)
  • Optimizer ke liye gradients ko FP32 mein cast karo

Common Pitfalls and Fixes

Implementation Pseudocode

# Initialization
model_fp16 = model.half()  # FP16 copy for compute
master_weights = model.parameters()  # FP32 master copy
optimizer = Adam(master_weights)
scale = 2**16  # Initial loss scale (6536)
 
for batch in dataloader:
    # Forward pass in FP16
    with autocast(dtype=torch.float16):
        output = model_fp16(batch.x)
        loss = criterion(output, batch.y)
    
    # Scale loss to prevent gradient underflow
    scaled_loss = loss * scale
    # Backward pass (gradients computed in FP16, but scaled)
    scaled_loss.backward()
    
    # Unscale gradients
    for param in master_weights:
        if param.grad is not None:
            param.grad = param.grad / scale
    # Clip gradients (on unscaled values!)
    torch.nn.utils.clip_grad_norm_(master_weights, max_norm=1.0)
    
    # Optimizer step on FP32 master weights
    optimizer.step()
    optimizer.zero_grad()
    # Copy updated master weights back to FP16 model
    for param_fp16, param_fp32 in zip(model_fp16.parameters(), master_weights):
        param_fp16.data.copy_(param_fp32.data)
    # Dynamic loss scaling: check for overflow
    if any(torch.isnan(p.grad).any() for p in master_weights if p.grad is not None):
        scale = scale / 2  # Halve scale on overflow
    elif step % 2000 == 0:
        scale = min(scale * 2, 2**16)  # Double scale if stable

Theoretical Guarantees

Convergence: Mixed precision training provably FP32 training ke same optimum par converge karta hai mild conditions ke andar:

  1. Assumption: Gradients satisfy (bounded) aur loss scale ensure karta hai \cdot g_{\min} > \epsilon_{FP16}$ (no underflow).
  2. Result: Agar learning rate (standard SGD condition), to expected distance to optimum FP32 ke same rate se decrease hoti hai: jahan (loss smoothness) par depend karta hai lekin precision par nahi.

Proof sketch: Master weights updates exactly accumulate karte hain (koi precision loss nahi). FP16 forward/backward har operation par rounding errors introduce karte hain. Lekin modern GPUs round-to-nearest mode use karte hain, isliye (unbiased). Error variance hai, jo averaging ki wajah se par vanish ho jaata hai. Loss scaling ensure karti hai ki scaled gradients ke relative measure hota hai, ko chhota rakhte hue.

When to Use Mixed Precision

Tab use karo jab:

  • 10M parameters wale models train kar rahe ho (memory savings matter karti hain)

  • Tensor Cores wale GPUs use kar rahe ho (V100, A100, RTX 20/30 series)
  • Distributed training mein (gradient communication bottleneck hai)
  • Inference memory-bound ho (FP16 models directly deploy kar sakte hain)

Tab use mat karo jab:

  • Numerical issues debug kar rahe ho (mushkil hai batana ki bug tumhara hai ya precision-related)
  • Aisi datasets ke saath kaam kar rahe ho jahan values >5 orders of magnitude span karti hain (jaise scientific computing with huge ranges)
  • Custom CUDA kernels use kar rahe ho jo FP16 ke saath tested nahi hain

Real-world impact: GPT-3 training ne mixed precision use ki aur iske bina infeasible hoti (175B parameters → ~700GB FP32, lekin mixed precision aur activation checkpointing ke saath ~350GB mein fit ho jaata hai).

Recall 12 Saal ke Bachche Ko Samjhao

Pretend karo ki tum ek video game khel rahe ho, aur tumhare paas apne gold coins store karne ke liye ek piggy bank hai. Har coin ko do tareekon se store kiya ja sakta hai:

  1. Chhote pouches (FP16): Coins jaldi store karte hain, kam jagah lete hain, lekin sirf 1 se 100 tak count kar sakte hain.
  2. Bade chests (FP32): Slow, heavy, lekin 0.001 se 1,000,000 tak count kar sakte hain.

Zyaadatar time tum coins collect aur spend karte hue bhaag rahe ho, isliye chhote pouches use karte ho—yeh quick hai! Lekin har raat, tum apne saare pouches ek bade chest mein daalte ho apni total wealth jodne ke liye. Is tarah, chhote coins bhi (jaise 0.01 gold) kho nahi jaate.

Ab kabhi kabhi tumhe bahut chhote treasure milte hain (0.001 gold). Agar seedha chhote pouch mein daalo, to yeh round hokar zero ho jaata hai aur gayab! Isliye ek trick use karte ho: collect karte waqt saare treasure ko 1000 se multiply karo. Ab 0.0001, 0.1 ban jaata hai, jo pouch hold kar sakta hai. Baad mein, jab bade chest mein daalo, 1000 se divide karo real value waapas paane ke liye.

Mixed precision training exactly yahi hai: zyaadatar kaam ke liye fast, chhota storage (FP16) use karo, lekin ek careful ledger (FP32 master weights) rakho taaki tiny updates vanish na hon. Gradients ko scale up karo taaki woh disappear na hon. Isse huge AI models train karna 2× faster aur 30% kam memory use karta hai—jaise video game boss ko speed potion ke saath harna!

Connections

  • 3.3.08-Gradient-accumulation – Mixed precision ko aksar gradient accumulation ke saath combine kiya jaata hai bade batches fit karne ke liye
  • 3.3.05-Learning-rate-schedules – Loss scaling LR ke saath interact karti hai: dono gradient magnitude affect karte hain
  • 4.2.03-Tensor-cores – Mixed precision ke liye hardware motivation
  • 3.3.10-Gradient-checkpointing – Ek aur memory optimization, aksar saath use hoti hai
  • 2.4.06-Batch-normalization – Special handling chahiye (FP32 running stats)
  • 5.1.02-Model-parallelism – Mixed precision distributed training mein communication reduce karti hai
  • 1.3.07-Numerical-stability – Speed aur precision ke beech fundamental tradeoffs

#flashcards/ai-ml

Mixed precision training ke teen core components kya hain? :: (1) Accurate updates ke liye FP32 master weights, (2) Gradient underflow rokne ke liye Loss scaling, (3) Compute speed up karne ke liye forward/backward passes mein FP16 arithmetic.

Hum poori tarah FP16 mein train kyun nahi kar sakte?
FP16 ki limited range ( to ) se (1) gradient underflow (tiny gradients → zero) aur (2) weight update underflow (chhote learning rates × gradients → koi change nahi) hota hai. FP32 mein master weights update underflow ko prevent karte hain.

Derive karo ki loss scaling gradient underflow kyun rokti hai :: Agar gradient (FP16 min) hai, to yeh 0 par underflow hota hai. Loss ko se scale karo: backward deta hai (representable). Unscale karo: optimizer step se pehle FP32 mein true value recover karta hai.

Mixed precision training ka memory formula kya hai?
Memory (FP16 weights + FP32 master weights + FP16 gradients + FP16 activations + FP32 optimizer state). Typically pure FP32 se 25-35% savings, mainly activations se jo memory ka ~50% hoti hain.
Gradients unscale kab karna chahiye—gradient clipping se pehle ya baad mein?
Clipping se pehle. Scaled gradients ke norms bade hote hain. Agar scaled grads ko norm 1.0 par clip karo, to actually true grads ko par clip kar rahe ho (with ), jo bahut zyaada aggressive hai.
Batch normalization running statistics ko FP32 mein kyun rehna chahiye?
Running mean/var EMA se update hote hain: . chhota value update often (FP16 precision limit) hota hai, underflow cause karta hai. Accumulated error inference tod deta hai.
Dynamic loss scaling kya hai aur kyun zaroori hai?
Bade scale se shuru karo (jaise ). Agar gradients overflow karein (inf/nan produce karein), scale aadha karo. Agar training steps tak stable rahe, scale double karo. Zaroori hai kyunki alag models mein gradient distributions magnitude mein 1000× span karti hain—koi ek static scale universally kaam nahi karta.

FP16 vs BF16 compare karo :: FP16: 5 exp bits, 10 mantissa bits. Range to , precision . BF16: 8 exp bits, 7 mantissa bits. FP32 jaisi range ( to ), kam precision. BF16 mein overflow issues kam hote hain lekin accuracy kam hai; TPUs aur newer GPUs par preferred hai.

Modern GPUs par mixed precision training se speedup kitna hota hai?
V100/A100 par Tensor Cores ke saath typically 2-3× end-to-end training speedup. Raw matrix multiply FP16 mein 8-16× faster ho sakta hai, lekin overhead (data loading, optimizer CPU work) total speedup limit karta hai. Memory savings (25-35%) se bade batch sizes allow hote hain, jo aur speedup deta hai.

Concept Map

solved by

uses fast

keeps critical in

speeds up

reduces

causes

fixed by

fixed by

accumulates tiny

cast to

alt with FP32 range

prevents

Training bottlenecks

Mixed Precision Training

FP16 compute

FP32 precision

Compute on Tensor Cores

Memory and bandwidth

Gradient underflow

FP32 master weights

Loss scaling

Weight updates

BF16 format

Rounding to zero