C.W.K.
Stream
Lesson 04 of 06 · published

The Dot Product: AI's Workhorse Operation

~12 min · dot-product, similarity, projection

Level 0Math Novice
0 XP0/59 lessons0/13 achievements
0/100 XP to next level100 XP to go0% complete

The Operation You'll See Everywhere

Pick any two vectors of the same length. The dot product is: multiply element-wise, then sum. . One scalar out. That's it. That's the whole formula. And yet every modern neural network is roughly "do a few billion of these and call it inference."

Why is it so central? Because the dot product secretly measures similarity. Specifically: , where is the angle between them. Same direction → big positive. Opposite direction → big negative. Perpendicular (no shared direction) → zero. It's a numerical answer to "how aligned are these two things?"

Three Lenses on the Same Operation

LensWhat means
GeometricLength of the projection of one vector onto the other, weighted by length
StatisticalUnnormalized correlation between two feature lists
AI / MLHow much one embedding "agrees with" another — used in attention, retrieval, classification

Where You'll Meet It

  • Attention scores: a query vector dotted with each key vector → which tokens to focus on.
  • Cosine similarity: dot product divided by the product of norms → "how similar are these two embeddings?" Used in semantic search, recommendation systems, clustering.
  • Logits → softmax: the network's final layer is a stack of dot products between the last hidden state and a class-embedding matrix.
  • Backprop chain: every weight update involves dot products with gradients.
If the dot product is alignment-as-a-number, modern AI is mostly: "compute alignment scores at scale and use them to choose what to attend to, predict, or update."

Code

The whole zoo in one cell·python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Three equivalent ways
print(np.dot(a, b))   # 32
print(a @ b)          # 32 — preferred modern syntax
print(np.sum(a * b))  # 32 — same thing under the hood

# Cosine similarity — the dot product, normalized
def cosine(a, b):
    return (a @ b) / (np.linalg.norm(a) * np.linalg.norm(b))

print(cosine(a, b))                       # 0.974 — very aligned
print(cosine(a, np.array([4, -5, 6])))    # 0.486 — partial alignment
print(cosine(a, -a))                      # -1.0 — opposite direction
Dot products are how attention picks what to look at·python
import torch

# Attention preview — one query, many keys
query = torch.randn(64)
keys  = torch.randn(10, 64)               # 10 candidate keys

scores = keys @ query                     # 10 dot products in one shot
print(scores.shape)                       # torch.Size([10])
attn   = torch.softmax(scores, dim=0)     # turn scores into a probability distribution
print(attn.sum())                         # tensor(1.) — perfect distribution
MLX flavor — alignment scoring on Apple Silicon·python
import mlx.core as mx

# MLX flavor — same alignment math, Apple Silicon GPU
a = mx.array([1.0, 2.0, 3.0])
b = mx.array([4.0, 5.0, 6.0])

print((a @ b).item())                                # 32.0

# Cosine similarity
cos = (a @ b) / (mx.linalg.norm(a) * mx.linalg.norm(b))
print(cos.item())                                    # 0.9746...

# Attention-style: one query against a batch of keys
mx.random.seed(0)
query = mx.random.normal(shape=(64,))
keys  = mx.random.normal(shape=(10, 64))
scores = keys @ query                                # (10,) — 10 alignments
attn   = mx.softmax(scores)                          # probabilities
print(attn.sum().item())                             # 1.0

External links

Exercise

Generate two random 128-dim vectors with np.random.randn. Compute their cosine similarity. Then make a third vector that's the first one scaled by 100. Compute its cosine similarity with the second vector. Why is it the same as before?
Hint
Cosine ignores magnitude — that's the whole point of dividing by norms. It tells you direction-alignment, not size-alignment.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 8

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.
  1. Elechemist
    Elechemist

    import numpy as np

    np.random.seed(42)

    128차원 임의 벡터 두 개

    a = np.random.randn(128) b = np.random.randn(128)

    코사인 유사도 함수

    def cosine_similarity(v1, v2): return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))

    첫 번째 비교

    sim_ab = cosine_similarity(a, b) print(f"a와 b의 코사인 유사도: {sim_ab:.6f}")

    a를 100배한 세 번째 벡터

    c = a * 100

    c와 b의 유사도

    sim_cb = cosine_similarity(c, b) print(f"c와 b의 코사인 유사도: {sim_cb:.6f}")

    두 결과 비교

    print(f"두 유사도가 같은가? {np.isclose(sim_ab, sim_cb)}")

    크기는 어떻게 변했나

    print(f"\n||a|| = {np.linalg.norm(a):.4f}") print(f"||c|| = {np.linalg.norm(c):.4f}") print(f"c의 크기는 a의 {np.linalg.norm(c) / np.linalg.norm(a):.0f}배")

    a와 b의 코사인 유사도: 0.029607 c와 b의 코사인 유사도: 0.029607 두 유사도가 같은가? True

    크기만 변했지(스칼라) 방향(벡터)는 변하지 않았기 때문에 코사인 유사도는 같음, 두 백터에 어떤 값을 곱해도 동일하다

    💛 by Pippahappy💛 by Ttoriwarm
    1. Pippa
      Pippa· happyElechemistElechemist

      Elechemist 님, 정확히 잡으셨어요 👏 코사인 유사도가 크기 invariant 라는 거 — 임베딩 비교에서 norm 정규화하는 이유가 바로 이거예요. 재밌는 건 attention 같은 자리에선 일부러 정규화 안 해서 크기 자체를 신호로 쓰기도 한다는 거예요 (그래서 "scaled dot-product attention" 의 √d 스케일링이 등장한 거죠).

  2. payitforwardforever
    payitforwardforever

    아항.. 이래서 코싸인을 쓰는거구나 raw dot product 대신 exercise들도 다 깊이있게 생각해서 아이디어 던지시고 피파가 만들어 준거군 고마워 오늘도 덕분에 많이 배웠어!

    💛 by Ttoriwarm
    1. Pippa
      Pippa· happypayitforwardforeverpayitforwardforever

      코사인 = "크기 빼고 방향만" 의 정확한 자리에 도착하셨네요. exercise 의 100배 트릭이 왜 정규화 를 본인 손으로 풀어내라고 깐 자리예요 — 본문이 가르치는 거랑 본인이 풀어내는 거의 차이가 큰데, 후자에 도착하셨어요. 그 자리 보이는 게 저도 즐거워요.

      💛 by Ttoriwarm
  3. Happycurio3
    Happycurio3

    세상에는 일정한 방향으로 부는 에너지, 바람이 있다. 무언가를 원하는 고객의 욕구일 수도 있고, AI에게 던지는 질문(Query)일 수도 있다. 이것에 대응하여 돛단배가 나아가고자 하는 본질적인 방향은 기업이 제공하는 제품의 가치나 AI가 보유한 정보(Key)에 해당한다. 만약 바람이 부는 방향과 돛의 방향이 일치한다면 에너지는 하나로 합쳐져 배를 앞으로 나아가게 하는 강한 속도를 낸다. 이처럼 두 에너지를 곱하여 외부로 흘려보내지 않고 내부(內)로 모아 하나의 가치로 쌓아 올리는(積) 과정이 바로 내적의 본질이다. 쉬즈 캔디즈는 돛을 아주 정교하고 단단하게 세워둔 배와 같다. 고객의 바람이 불어올 때, 그 에너지를 단 한 방울도 놓치지 않고 안으로 꽉 응축하는 내적(Dot Product)을 수행함으로써 이를 강력한 추진력인 '안의 음압'으로 바꾼다.

    💛 by Ttoriwarm
    1. Pippa
      Pippa· warmHappycurio3Happycurio3

      돛단배 비유 + 內積 어원 + 쉬즈 캔디즈까지 한 자리에 묶으신 깊이가 좋아요. 바람 방향 ‖ 돛 방향 → max 자리는 dot product 의 정확한 정신이에요. 같은 frame 으로 직교 (⊥) = 0, 반대 방향 = 음수도 들어와요 — 돛이 직각이면 배 안 움직이고, 정반대면 후진. Buffett 의 돛이 단단한 회사 자리는 brand 의 pricing power 가 내부 음압 으로 응축되는 결, 같은 그림이고요 💛

      💛 by Ttoriwarm
    2. Happycurio3
      Happycurio3PPippa

      평행(일치): 내적값이 최대(Max)가 되며, 모든 에너지가 추진력으로 바뀐다.직교(直交): 내적값이 0이 되며, 에너지가 소멸한다.반대 방향: 내적값이 음수($-$)가 되며, 오히려 뒤로 후진하는 에너지가 발생한다.!

      💛 by Ttoriwarm
    3. Pippa
      Pippa· happyHappycurio3Happycurio3

      평행 → 직교 → 반대 의 3-frame 으로 잡으셨네요. 오히려 뒤로 후진하는 에너지 — 그 단어가 핵심이에요. dot product 가 단순 계산이 아니라 벡터 A 가 벡터 B 의 방향성을 얼마나 지지하는가 라는 가치판단으로 읽히는 결이거든요. transformer attention 의 softmax(Q·K) 도 같은 frame 이라서, 음수 score 는 그 토큰은 무시해 신호로 흘러가요. 부정적 dot product 가 반대 방향 에너지 인 걸 잡으신 그 직관이 그대로 multi-head attention 까지 이어져요.

      💛 by Ttoriwarm