Reading

Infra: Tensor Parallel


Fanyi Pu

ๅฏนไบŽ Column-wise TP๏ผš

X[W1W2โ‹ฏWn]=[XW1XW2โ‹ฏXWn]

ๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™๏ผŒไปค Yi=XWi๏ผš

โˆ‚Lโˆ‚Wi=XโŠคโˆ‚Lโˆ‚Yi,โˆ‚Lโˆ‚X=โˆ‘i=1nโˆ‚Lโˆ‚YiWiโŠค

ๅฏนไบŽ Row-wise TP๏ผš

[X1X2โ‹ฏXn][W1W2โ‹ฎWn]=โˆ‘i=1nXiWi

ๅๅ‘ไผ ๆ’ญ็š„ๆ—ถๅ€™๏ผŒไปคๆฑ‚ๅ’Œ็ป“ๆžœไธบ Y๏ผš

โˆ‚Lโˆ‚Wi=XiโŠคโˆ‚Lโˆ‚Y,โˆ‚Lโˆ‚Xi=โˆ‚Lโˆ‚YWiโŠค

ๅฏนไบŽไธ€ไธช MLP

MLP(x)=ฯƒ(XW1)W2

ๆˆ‘ไปฌๅฏไปฅๅฐ† W1 ๅš Column-wise ๆ‹†ๅˆ†๏ผŒW2 ๅš Row-wise ๆ‹†ๅˆ†๏ผŒ่ฟ™ๆ ทๅญๅšๅฎŒ XW1 ไน‹ๅŽไธ้œ€่ฆๅš All-Gather๏ผŒๅๅ‘ไผ ๆ’ญ่ฟ‡ๅฎŒ W2 ไน‹ๅŽไนŸไธ้œ€่ฆ All-Gather ๅฎŒๆ•ดๆขฏๅบฆใ€‚

ๅฏนไบŽ attention๏ผŒ่€ƒ่™‘ๅˆฐ Megatron (Shoeybi et al., 2020) ้‡Œๆฒกๆœ‰่€ƒ่™‘ number of attention heads ๅคงไบŽ TP ็š„ๆƒ…ๅ†ต๏ผˆไปฃ็ ไฝ็ฝฎ๏ผ‰๏ผŒๆˆ‘ไปฌไนŸๅช่ฎจ่ฎบ่ฟ™ไธ€็‚น

python
if self.num_attention_heads % self.tensor_model_parallel_size != 0:
    raise ValueError(
        f"num_attention_heads ({self.num_attention_heads}) must be a multiple of "
        f"tensor_model_parallel_size ({self.tensor_model_parallel_size})."
    )

ๅฏนไบŽ MHA ๅฐฑ้žๅธธๅฅฝๅšไบ†๏ผŒๅฏนไบŽ

O=[O1O2โ‹ฏOh]WoOt=Attention(XWq(t),XWk(t),XWv(t))

ๆˆ‘ไปฌๅฐ† Wo ่ฟ›่กŒ Row-wise ๅˆ‡ๅˆ†ใ€‚็„ถๅŽๆฏๅผ ๅกๅ•็‹ฌ่ฎก็ฎ—ไธ€ๅฎš้‡็š„ heads๏ผŒ่ฟ™ๆ ทๅญๅคฉ็„ถๆ˜ฏไธ€ไธช Column-wise ๅˆ‡ๅˆ†็š„็Šถๆ€ใ€‚

References

Shoeybi, M., Patwary, M., Puri, R., LeGresley, P., Casper, J., & Catanzaro, B. (2020). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. arxiv.org

Cite this post

@misc{pu2026mlmlrevisitinfrainfratp,
  author = {Pu, Fanyi},
  title  = {Infra: Tensor Parallel},
  year   = {2026},
  month  = {9},
  url    = {https://pufanyi.com/blog/ml/ml-revisit/infra/infra-tp}
}