Worked examples — Tensor cores and matrix operations
6.2.12 · D3· Hardware › GPU Architecture › Tensor cores and matrix operations
Yeh page Tensor Cores ka drill ground hai. Parent note ne tumhe bataya tha ki Tensor Core kya hota hai aur kyun exist karta hai. Yahan hum har tarah ki situation enumerate karte hain jo tumhe mil sakti hai — har awkward matrix shape, har precision choice, har "kya yeh fit bhi hoga?" edge case — aur har ek ko number tak kaam karte hain.
Agar tum tiled matrix multiply ki machinery se abhi nahi mile ho, pehle parent ko skim karo. Baaki sab kuch hum yahan zero se build karte hain.
Do notation pieces, pehle banaye gaye
Do symbols har line pe repeat hote hain. Hum inhe use karne se pehle define karte hain.
Scenario matrix
Problems work karne se pehle, aao cases enumerate karein. Ek Tensor Core problem kuch knobs se poori tarah describe hoti hai. Agar ek knob aise value le sakta hai jo naive approach ko tod de, us value ko apni row milti hai.
| Cell | Case class | Kya test ho raha hai | Example |
|---|---|---|---|
| A | Clean fit | Dimensions tile ke exact multiples hain | Ex 1 |
| B | Ragged fit (padding chahiye) | Dimension tile ka multiple nahi → padding / performance cliff | Ex 2 |
| C | Degenerate: , aur / | Sum / output ka size zero hai — answer kya hai? | Ex 3 |
| D | Skinny / vector-like ( ya ) | Tile mostly wasted — utilisation ka sawaal | Ex 4 |
| E | Instruction-count / speedup arithmetic | FMAs aur Tensor Core ops count karna | Ex 5 |
| F | Precision choice (FP16 vs BF16 vs TF32 vs INT8) | Kaun sa mode, aur accuracy ki cost | Ex 6 |
| G | Accumulator overflow / range | Jab low precision silently fail kare | Ex 7 |
| H | Real-world word problem (roofline / timing) | Bytes vs FLOPs, kya yeh compute-bound hai? | Ex 8 |
| I | Exam-style twist (transpose / layout) | row_major vs col_major, off-by-tile traps |
Ex 9 |
Hum yeh symbols poore page mein use karenge — ek baar, yahan define kiye gaye:
Ex 1 — Cell A · Clean fit
Hum kya kar rahe hain: count karna ki tile-sized bites poore output ko kitna cover karte hain.
Niche figure (s01). Alt-text: ek blue output rectangle ko ek patli gray grid se tiles niche aur tiles across mein kaat diya gaya hai; ek tile orange se bhari hai aur labelled hai "ek output tile ()"; ek green arrow labelled " accumulation steps" us orange tile mein andar point kar raha hai yeh dikhane ke liye ki yeh K-chunks sum karke bana hai. Teen grid counts picture se seedhe padho.

- Output-row tiles count karo. (s01 mein grid ki rows). Yeh step kyun? Output hai; iske height ke along hum height ke tiles rakhte hain. Evenly divide hota hai → Cell A, clean.
- Output-column tiles count karo. (grid ke columns). Kyun? Width ke across same logic, tile width .
- Inner (K) tiles count karo. (green arrow ki depth). Kyun? Har output tile ek shot mein complete nahi hota — shared dimension ko ke chunks mein kaata jaata hai, aur hum un chunks ko accumulate karte hain. Har chunk ka product running tile pe add hota hai mein ke zariye: pichle step ka is step ka ban jaata hai.
- Teen counts ko multiply karo. instructions.
Multiply kyun? Har output tile (jitne orange squares hain) ko har K-chunk ke liye ek
mmachahiye (jinka count hai).
Verify: total FMAs doosre tarike se . Har mma karta hai FMAs. Toh . ✓ Do tareekon se same number.
Ex 2 — Cell B · Ragged fit (padding & performance cliff)
Hum kya kar rahe hain: aisi dimension handle karna jise tile size evenly divide nahi karta.
Niche figure (s02). Alt-text: tiles ki horizontal strip; pehle tiles ( columns) solid blue hain aur labelled hain "real, clean"; waan tile split hai — ek orange slice ( columns, "real: 129–130") ke bagal mein ek gray hatched slice ( columns, "padding: 131–136, wasted"). we tile ke upar ek red bracket likha hai "2 extra columns ke liye ek extra tile = the cliff." Dekho kaise tiny orange sliver ek poore gray tile ko saath le aata hai.

- Divisibility check karo. — integer nahi. Yeh ragged case hai. Yeh step kyun? Tensor Cores sirf whole tiles mein bolte hain. Ek partial column strip "16.25 tiles" ke roop mein issue nahi ho sakti.
- Ceiling se round up karo. Column-tiles ki count (yaad karo , upar define kiya) — s02 mein tiles. Round up kyun, down nahi? Extra columns drop karne se data loss hoga. Hume columns 129 aur 130 (orange sliver) cover karne hain, toh hum poora waan tile allocate karte hain.
- Padded width compute karo. tile space ke columns real columns ke liye. Kyun? Last tile columns 129–136 span karta hai; columns 131–136 padding hain ( mein zeros, mein garbage-then-discarded) — gray hatched slice.
- Wasted columns . Care kyun? Un columns ko phir bhi full Tensor Core cycles lagte hain. Yeh hai performance cliff: sirf real columns add karne se ek poora extra tile lag gaya.
Verify: last tile ka wasted fraction idle us strip mein. Overall extra work vs. clean : instructions se ho jaate hain, yaani , 2 extra columns serve karne ke liye 6.25% overhead. ✓
Ex 3 — Cell C · Degenerate sizes (, aur ya )
Hum kya kar rahe hain: har boundary size pe tile counts aur defining sum evaluate karna.
Niche figure (s03). Alt-text: teen chhote panels side by side. Panel (a) "": ek solid blue output square exist karta hai lekin label "" se bhara hai — output tiles real hain, contraction empty hai. Panel (b) "": zero height ki ek flat blue line labelled " — koi rows nahi, koi tiles nahi." Panel (c) "": zero width ki ek patli blue vertical line labelled " — koi cols nahi, koi tiles nahi." Teeno ke niche ek gray caption likha hai "instructions run har case mein."

- Case (a), (empty contraction). Defining sum ka ek empty index range hai. Universal convention ke mutabik zero terms ka sum additive identity hai, toh hai zero matrix (panel (a): ek real square, se bhara).
0 kyun aur "undefined" kyun nahi? Ek empty sum accumulator ko unchanged rehne deta hai; identity jo "kuch nahi add karta" woh hai.
Instruction count:
mmacalls. Output tiles exist karte hain ( non-empty hai) lekin accumulate karne ke liye kuch nahi hai. - Case (b), (koi output rows nahi). hai — ek empty matrix (koi elements nahi; panel (b) ek zero-height line hai). Kyun? Agar mein zero rows hain, toh product mein zero rows hain; literally koi nahi hai compute karne ke liye. Instruction count: .
- Case (c), (koi output columns nahi). hai — phir ek empty matrix (panel (c) ek zero-width line hai). Kyun? (b) se symmetric: zero output columns → likhne ke liye kuch nahi. Instruction count: .
- Unifying rule. Agar koi bhi teen tile counts mein se hai, product zero instructions run karta hai. Lekin wajah alag hai: (a) mein output tiles exist karte hain aur phir bhi zero se initialise hone chahiye; (b)/(c) mein initialise karne ke liye koi output tiles hi nahi hain.
Initialisation mention kyun? Cell C ka classic bug: ke liye phir bhi
fill_fragment(c_frag, 0.0f)karna padta hai warna garbage return hoga — chahe koi multiply kabhi na ho.
Verify: (a) hai zeros, ops; (b) hai , ops; (c) hai , ops. ✓
Ex 4 — Cell D · Skinny matrix (matrix–vector, )
Hum kya kar rahe hain: waste measure karna jab ek dimension tile se bahut chhota ho.
Niche figure (s04). Alt-text: ek output tile ek -wide, -tall blue grid ke roop mein drawn. Sabse left column orange se bhari hai aur labelled hai "useful output ( ka 1 column)"; baaki columns diagonal hatching ke saath gray hain, labelled "wasted tile width (8 mein se 7 columns padding)." Niche ek red caption likha hai "utilisation ." Orange strip ko blue tile ka exactly ek-aathwaan hissa occupy karte hue dekho.

- Output shape. hai . Column-tiles chahiye . Kyun? Ek akela column bhi full width- tile force karta hai — ek orange column, lekin poora blue tile allocated (figure dekho).
- Tile mein useful columns out of (s04 mein orange strip vs. poora blue tile). Kyun? Us tile ke columns 2–8, ke padding (zero) columns ke against compute karte hain — real cycles, discarded results (gray hatched region).
- Column utilisation . Yeh kyun matter karta hai? Tensor Cores fat GEMMs pe chamakte hain. Ek matrix–vector product width dimension ka waste karta hai — yeh memory-bound hai, compute-bound nahi (Ex 8 dekho).
- Row dimension theek hai. , ka multiple hai, toh height utilisation hai. Overall tile utilisation . Dimensions alag kyun karein? Utilisation independent tile axes ke across multiply hoti hai.
Verify: column util ; overall . s04 mein, orange strip (real output) blue tile ke aath columns mein se exactly ek hai. ✓
Ex 5 — Cell E · Speedup arithmetic
Hum kya kar rahe hain: total work ko work-per-instruction se divide karna.
Niche figure (s05). Alt-text: logarithmic x-axis (instruction count) wala ek horizontal bar chart. Ek lamba orange bar tak jaata hai labelled "scalar FMAs (ek per instruction)"; ek bahut chhota blue bar tak jaata hai labelled "Tensor Core mma ops (2048 FMAs each)." Unke beech ek red annotation likha hai " fewer instructions." Blue bar visibly orange ka ek tiny fraction hai.

- Total FMAs. (orange bar). Cube kyun? outputs mein se har ek ko FMAs chahiye.
- FMAs per
mma. . Kyun? Ek instruction ek output tile fill karta hai length- contraction use karke FMAs. - Reduction factor. instructions (blue bar), yaani instruction count factor se gir jaata hai. Tile product kyun? Ek instruction ke andar har chhupa FMA ek kam instruction hai jo tum issue karte ho.
Verify: ; Tensor Core ops; factor . ✓
Recall 2048× kam instructions ka matlab 2048× faster kyun nahi hota?
Kyunki raw speedup clock, memory bandwidth, aur pipeline fill se bounded hota hai — instruction count sirf ceiling hai. Real speedup – hota hai, hardware throughput se set, FMA-per-op ratio se nahi. ::: Instruction reduction ek upper bound hai; memory aur clock actual gain cap karte hain.
Ex 6 — Cell F · Precision choose karna (FP16 vs BF16 vs TF32 vs INT8)
Hum kya kar rahe hain: saare char precision modes ko concrete numbers pe exercise kar rahe hain.
Niche figure (s06). Alt-text: do stacked panels. Top panel — teen horizontal bit-layout bars (FP32, BF16, FP16) equal total length ke, har ek blue "sign" cell, orange "exponent" segment, aur green "mantissa" segment mein split; FP32 aur BF16 same wide orange exponent share karte hain (labelled "range: 8 exp bits"), jabki FP16 ka exponent visibly shorter hai ("range: 5 exp bits") aur iska mantissa BF16 se longer hai. Ek red arrow mark karta hai " falls off FP16's range." Bottom panel — se tak ek number line evenly spaced orange ticks ke saath INT8 ki coarse grid illustrate karta hai, annotated "step ."

Hum kya kar rahe hain: saare char precision modes ko concrete numbers pe exercise kar rahe hain.
- (i) FP16 vs BF16 — range test. ko har format ke smallest normal se compare karo. → FP16 ise zero ki taraf underflow kar deta hai. → BF16 ise rakhta hai. Kyun? FP16 exponent pe sirf 5 bits spend karta hai (narrow range, s06 ka top panel); BF16 FP32 ka full 8-bit exponent rakhta hai, range ke liye mantissa bits trade karta hai. Training ke liye BF16 choose karo.
- (ii) TF32 — free speed test. Relative rounding error lagbhag last mantissa bit mein ek unit hai: , FP32 ke se compare mein. Care kyun? relative error se kam hai — zyaadatar models ke liye invisible — aur TF32 ko koi code change nahi chahiye jabki FP32 se faster run karta hai. Default fast FP32 ke roop mein TF32 choose karo.
- (iii) INT8 — quantisation step test. levels () ke saath range width ke across, neighbouring representable weights ke beech step hai (tick spacing, s06 ka bottom panel). Yeh kyun matter karta hai? Koi bhi weight ke nearest multiple pe round hota hai; INT8 yeh coarse grid accept karta hai exchange mein throughput aur FP32 vs smaller weights ke liye — training ke baad inference ke liye theek. Post-training inference ke liye INT8 choose karo.
Verify: (i) aur ; (ii) , , aur ; (iii) . ✓ Dekho 8.3.4-Mixed-precision-training aur 8.4.2-Quantization-techniques.
Ex 7 — Cell G · Accumulator overflow (kyun FP32 accumulate exist karta hai)
Hum kya kar rahe hain: accumulator ko bound karna aur iske capacity se compare karna.
- Worst-case per-product magnitude. . Max kyun? sabse bada signed INT8 value hai; worst single term.
- Worst-case sum. . se multiply kyun? Contraction aise terms add karta hai; worst case sabhi max sign pe hain.
- INT16 ceiling se compare karo (). → sirf kuch terms ke baad massive overflow. Yeh sab kuch kyun barbaad karta hai? Ek overflowed INT16 silently wrap around karta hai → garbage output, koi error nahi.
- INT32 ceiling se compare karo (). → comfortably fit karta hai. Hardware INT32 accumulate kyun use karta hai: yeh guarantee karta hai realistic ke liye koi overflow nahi, aur yahi reason hai ki Tensor Cores INT8 inputs ko ek INT32 accumulator ke saath pair karte hain (aur FP16 inputs ko FP32 ke saath) — accumulate result wide type mein rehta hai chahe narrow hon.
Verify: ; (INT16 overflows); (INT32 safe). ✓ Yeh concrete reason hai ki "mixed precision" hamesha wide accumulate karta hai.
Ex 8 — Cell H · Real-world word problem (compute- vs memory-bound)
Hum kya kar rahe hain: roofline model apply karna — woh single test jo kehta hai "compute ya memory."
- FLOPs. Matrix–vector FMAs karta hai FMAs FLOPs mein FLOPs. kyun? Har FMA ek multiply aur ek add hai.
- Bytes moved. Hume read karna hai (dominant): FP16 elements bytes bytes B. ( aur negligible hain.) kyun dominate karta hai? sirf elements hai; hai — ek million times zyaada data.
- Arithmetic intensity FLOP/byte. Yeh ratio kyun? Yeh batata hai ki har fetched byte se hum kitna compute nikalte hain.
- Machine balance FLOP/byte. Compare: hamari intensity → bahut bade margin se memory-bound.
- Time estimate (memory). s s. Bandwidth kyun use karo, FLOP/s nahi? Jab memory-bound ho, memory pipe time set karta hai; Tensor Cores idle rehte hain.
Verify: intensity ; balance ; (memory-bound); s. ✓ (Compute-only time hoga s — bahut chhota, confirm karta hai ki memory dominate karta hai.)
Ex 9 — Cell I · Exam twist (layout / transpose trap)
Hum kya kar rahe hain: layout flags ko transpose operators ke roop mein track karna, kyunki exactly yahi woh hain.
- Layout ka matlab kya hai. Row-major buffer ko col-major ki tarah padhna mathematically transpose padhne ke barabar hai. Toh
col_majorload flag jo bhi bytes read karta hai us par ek transpose apply karta hai. Kyun? Row-major stored, column-major padha, mathematically deta hai. - Student ne memory mein pre-transpose kiya → buffer ab hold karta hai. Unhone kyun kiya: woh transpose chahte the jo unhe chahiye tha.
- Phir col_major flag dobara transpose karta hai → fragment hold karta hai . Yeh trap kyun hai: do transposes cancel ho jaate hain. .
- Result:
mma_synccompute karta hai — desired nahi. Do flips cancel ho gaye; student silently galat product leta hai (koi error nahi). Fix: exactly ek transpose karo — ya buffer flip karo ya layout flag set karo, dono kabhi nahi.
Verify: , se: intended lekin double-flip deta hai . Dono matrices alag hain → bug confirm hota hai. ✓ (Dekho 7.3.6-cuBLAS-and-cuDNN: libraries ek explicit transA/transB flag expose karti hain taki tum ek baar, deliberately flip karo.)
Recap
Recall Kaun sa cell tumhe tile count
upar ceiling se round karne force karta hai? Cell B (ragged fit): tile size se divide na hone wali dimension tiles use karti hai, padding aur performance cliff create karti hai. ::: Ragged / padding case — ceiling use karo, wasted columns expect karo.
Recall Empty sizes:
, , aur mein kya fark hai?
Teeno 0 mma instructions run karte hain. Lekin phir bhi ek real (zero-filled) output tile produce karta hai jo initialise hona chahiye, jabki ya ek empty matrix produce karte hain jisme koi output tiles nahi hote. ::: Zero instructions har case mein; sirf ko phir bhi accumulator init chahiye.
Recall INT8 Tensor Core hardware INT32 mein accumulate kyun karta hai?
Kyunki INT8 products ka length- contraction tak pahunch sakta hai, jo modest par bhi INT16 overflow karta hai lekin INT32 ke range mein comfortably rehta hai. ::: Accumulated sum ka silent overflow avoid karne ke liye.
Recall Skinny matmul (
): compute-bound ya memory-bound? Memory-bound — arithmetic intensity FLOP/byte machine balance () se bahut niche hai, aur tile utilisation sirf hai. ::: Memory-bound aur low utilisation; fix karne ke liye batch karo.
Related depth: 6.2.1-GPU-vs-CPU-architecture, 6.2.8-Memory-hierarchy-in-GPUs, 6.2.10-Warp-scheduling-and-execution.