جميع المقالات
AI Engineering

Day 6/100 — Multi-Head Attention: Why Transformers Need Multiple Attention Heads 🧠

‫🧠 Day 6/100 من MustaPro AI Lab: لماذا يستخدم Transformer عدة Attention Heads بدل Head واحدة؟ نتعرف على Multi-Head Attention وParallel Attention وHead Dimension وConcatenation وOutput Projection، ونبني أول Multi-Head Causal Self-Attention Layer باستخدام Python وPyTorch، مع تجربة عملية لفهم Attention Weights وCausal Ma

Day 6/100 — Multi-Head Attention: Why Transformers Need Multiple Attention Heads 🧠

🧠 Day 6/100 — Multi-Head Attention: Why Transformers Need Multiple Attention Heads

لماذا لا يكتفي Transformer بـ Attention Head واحدة؟

في اليوم الخامس من رحلتنا لبناء LLM داخل MustaPro AI Lab، تعرفنا على Self-Attention وكيف تستخدم Query وKey وValue لحساب العلاقات بين Tokens.

لكن هناك سؤال مهم:

**لماذا لا نستخدم Attention Head واحدة لمعالجة جميع العلاقات داخل الجملة؟**

تخيل الجملة التالية:

`The developer fixed the bug in the application.`

قد توجد عدة علاقات مهمة داخل نفس الجملة:

  • العلاقة بين `developer` و`fixed`.
  • العلاقة بين `fixed` و`bug`.
  • العلاقة بين `bug` و`application`.

استخدام عدة Attention Heads يمنح النموذج القدرة على تعلم أنماط مختلفة من العلاقات بالتوازي.

وهذا هو مفهوم **Multi-Head Attention**.

---

1. ما هي Multi-Head Attention؟

Multi-Head Attention هي آلية تستخدم عدة Attention Heads مستقلة نسبيًا داخل نفس الطبقة.

كل Head تمتلك Linear Projections خاصة بها لإنشاء:

  • Query (Q)
  • Key (K)
  • Value (V)

ثم تقوم كل Head بحساب Attention Output.

بعد ذلك يتم دمج النتائج باستخدام Concatenation وتمريرها عبر Output Projection.

المعادلة:

`MultiHead(Q,K,V) = Concat(head1,...,headH) × Wo`

حيث:

`head_i = Attention(QWiQ, KWiK, VWiV)`

**الفكرة الأساسية:** بدل استخدام تمثيل واحد للعلاقات بين Tokens، يستطيع النموذج تعلم عدة تمثيلات مختلفة.

لكن لا توجد قاعدة تضمن أن كل Head ستتعلم وظيفة لغوية مستقلة أو واضحة؛ فهذا يعتمد على التدريب والبيانات والمعمارية.

2. الفرق بين Single-Head وMulti-Head Attention

Single-Head Attention

نستخدم مجموعة واحدة من Q وK وV.

`Input → Q/K/V → Attention → Output`

Multi-Head Attention

نستخدم عدة مجموعات من Q وK وV بالتوازي.

`Input → Head 1 → Attention 1`

`Input → Head 2 → Attention 2`

`Input → Head 3 → Attention 3`

`Input → Head 4 → Attention 4`

ثم:

`Concatenate → Output Projection`

هذه البنية تسمح للنموذج بتعلم أنماط Attention متنوعة.

---

3. ما هو Head Dimension؟

لنفترض أننا نستخدم:

`d_model = 128`

و:

`num_heads = 8`

في المعمارية التقليدية، يمكن تقسيم الأبعاد بالتساوي:

`head_dim = d_model / num_heads`

إذن:

`head_dim = 128 / 8 = 16`

كل Head ستعالج Q وK وV بأبعاد 16.

ومجموع الأبعاد بعد Concatenation يساوي 128.

يجب أن يكون `d_model` قابلًا للقسمة على `num_heads` في هذا التصميم.

بعض المعماريات الحديثة تستخدم ترتيبات مختلفة، مثل اختلاف عدد Query Heads عن Key/Value Heads.

4. كيف تعمل Multi-Head Attention خطوة بخطوة؟

**Step 1 — Input Embeddings**

نبدأ بتمثيلات Tokens:

`X.shape = [batch_size, seq_len, d_model]`

**Step 2 — Linear Projections**

ننشئ Q وK وV باستخدام أوزان قابلة للتعلم.

**Step 3 — Split into Heads**

نعيد تشكيل Tensors لإضافة Head Dimension.

**Step 4 — Scaled Dot-Product Attention**

كل Head تحسب Attention Scores وWeights الخاصة بها.

**Step 5 — Concatenation**

نجمع نتائج Heads داخل Tensor واحدة.

**Step 6 — Output Projection**

نمرر النتائج عبر Linear Layer لإنتاج Output النهائي.

---

5. بناء Multi-Head Attention باستخدام PyTorch

سنقوم الآن بتطوير مثال Day 5.

هذه المرة سنضيف:

  • Multiple Heads.
  • Batch Dimension.
  • Causal Mask.
  • Output Projection.
  • Attention Weights.

Step 1 — Install PyTorch

pip install torch

Step 2 — Create Multi-Head Attention Class

import math
import torch
import torch.nn as nn
import torch.nn.functional as F


class MultiHeadSelfAttention(nn.Module):

    def __init__(self, d_model=8, num_heads=2):
        super().__init__()

        assert d_model % num_heads == 0

        self.d_model = d_model
        self.num_heads = num_heads
        self.head_dim = d_model // num_heads

        self.q_proj = nn.Linear(d_model, d_model)
        self.k_proj = nn.Linear(d_model, d_model)
        self.v_proj = nn.Linear(d_model, d_model)

        self.out_proj = nn.Linear(d_model, d_model)

    def split_heads(self, x):
        batch_size, seq_len, _ = x.shape

        x = x.view(
            batch_size,
            seq_len,
            self.num_heads,
            self.head_dim
        )

        return x.transpose(1, 2)

    def forward(self, x):

        batch_size, seq_len, _ = x.shape

        Q = self.split_heads(self.q_proj(x))
        K = self.split_heads(self.k_proj(x))
        V = self.split_heads(self.v_proj(x))

        scores = (
            Q @ K.transpose(-2, -1)
        ) / math.sqrt(self.head_dim)

        mask = torch.triu(
            torch.ones(
                seq_len,
                seq_len,
                dtype=torch.bool,
                device=x.device
            ),
            diagonal=1
        )

        scores = scores.masked_fill(
            mask,
            float("-inf")
        )

        weights = F.softmax(scores, dim=-1)

        context = weights @ V

        context = context.transpose(1, 2)
        context = context.contiguous().view(
            batch_size,
            seq_len,
            self.d_model
        )

        output = self.out_proj(context)

        return output, weights

Step 3 — Test Our Layer

torch.manual_seed(42)

x = torch.randn(1, 4, 8)

attention = MultiHeadSelfAttention(
    d_model=8,
    num_heads=2
)

output, weights = attention(x)

print("Input:", x.shape)
print("Output:", output.shape)
print("Weights:", weights.shape)

Expected Output:

Input: torch.Size([1, 4, 8])
Output: torch.Size([1, 4, 8])
Weights: torch.Size([1, 2, 4, 4])

لقد بنينا أول **Multi-Head Causal Self-Attention Layer**!

الأبعاد تعني:

  • Batch Size = 1
  • Number of Heads = 2
  • Sequence Length = 4
  • Model Dimension = 8

كل Head لديها Attention Matrix بالأبعاد `4 × 4`.

---

6. Visualize Attention Heads

لنرسم Attention Matrix الخاصة بكل Head.

import matplotlib.pyplot as plt

attention_maps = weights.detach()[0]

for head_index in range(attention_maps.shape[0]):

    plt.figure(figsize=(5, 4))

    plt.imshow(
        attention_maps[head_index].numpy(),
        cmap="viridis",
        vmin=0,
        vmax=1
    )

    plt.colorbar(label="Attention Weight")

    plt.xlabel("Key Position")
    plt.ylabel("Query Position")

    plt.title(f"Attention Head {head_index + 1}")

    plt.show()

ستلاحظ أن Heads قد تنتج Attention Weights مختلفة.

كما ستلاحظ أن المنطقة فوق القطر الرئيسي تساوي صفرًا بسبب Causal Mask.

**ملاحظة:** هذه الأوزان عشوائية لأن النموذج لم يتدرب بعد، لذلك لا ينبغي تفسيرها كعلاقات لغوية تعلمها النموذج.

7. لماذا نحتاج إلى Output Projection؟

بعد حساب نتائج Heads، نقوم بدمجها:

`Concat(head1, head2, ..., headH)`

ثم نستخدم Linear Projection:

`Output = Concat × Wo`

هذه الطبقة تسمح بدمج المعلومات الناتجة عن Heads المختلفة داخل تمثيل جديد.

وهي جزء أساسي من Multi-Head Attention التقليدية.

---

8. Multi-Head Attention داخل MustaPro AI

هدفنا هو بناء نموذج متخصص في تطوير البرمجيات.

مثلاً:

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService service;

    @GetMapping("/{id}")
    public UserDto findById(@PathVariable Long id) {
        return service.findById(id);
    }
}

عند تدريب النموذج على Source Code، قد تتعلم Heads أنماطًا مختلفة، مثل:

  • العلاقات بين Methods وParameters.
  • العلاقات بين Annotations وEndpoints.
  • العلاقات بين Classes وDependencies.
  • العلاقات بين Variables واستخداماتها.

لكن لا يمكننا افتراض أن Head معينة ستتعلم وظيفة محددة دون إجراء تحليل تجريبي.

هدفنا هو اختبار ما يتعلمه النموذج بالفعل.

9. هل المزيد من Attention Heads يعني نموذجًا أفضل؟

ليس بالضرورة.

زيادة عدد Heads لا تضمن تحسين الأداء.

يجب مراعاة:

  • Model Dimension.
  • Head Dimension.
  • Training Dataset.
  • Computational Cost.
  • Memory Usage.
  • Evaluation Results.

إذا أبقينا `d_model` ثابتًا، فإن زيادة عدد Heads في التصميم التقليدي تقلل `head_dim`، ولا تزيد بالضرورة عدد Parameters.

لذلك سنحتاج لاحقًا إلى مقارنة عدة Configurations باستخدام نفس Dataset وTraining Conditions.

---

10. Mini Challenge — Day 6

جرب تنفيذ التجارب التالية:

1. شغّل النموذج باستخدام `num_heads=1`.
2. أعد التجربة باستخدام `num_heads=2`.
3. جرّب `num_heads=4`.
4. قارن Shapes الخاصة بـ Q وK وV.
5. ارسم Attention Matrix لكل Head.
6. تحقق من أن Future Tokens لا تحصل على Attention داخل Causal Mode.

**Bonus Challenge**

جرّب استخدام:

`torch.nn.MultiheadAttention`

وقارن بنيتها ونتائجها مع Implementation التي أنشأناها.

لا تتوقع تطابق القيم مباشرة، لأن الأوزان وطريقة تهيئتها قد تختلف.

---

الخلاصة

اليوم تعلمنا:

  • الفرق بين Single-Head وMulti-Head Attention.
  • كيف نقسم Q وK وV إلى عدة Heads.
  • مفهوم Head Dimension.
  • طريقة حساب Attention بالتوازي.
  • كيفية دمج النتائج باستخدام Concatenation.
  • أهمية Output Projection.
  • كيفية تطبيق Causal Masking.

وبنينا أول Multi-Head Self-Attention Layer باستخدام PyTorch.

**أصبحنا الآن أقرب إلى بناء Transformer Block كامل.**

لكن Attention وحدها لا تكفي.

نحتاج أيضًا إلى Feed-Forward Networks وResidual Connections وLayer Normalization.

**Next — Day 7/100: Feed-Forward Networks — What Happens After Attention?**

MustaPro AI Lab | Building Intelligent Software, Step by Step.

Mustapha
Mustapha

مطور ومؤسس MustaPro. أشارك هنا أفكاري وتجاربي في بناء الحلول الرقمية.