Field Log · Entry

Instruction·Multitask·LLM Embedding은 무엇이 다른가 (6/14)

Task instruction과 query 또는 document가 encoder-only와 bidirectionalized decoder LLM을 지나 task-conditioned embedding vector가 되는 비교

이번 글의 결론

  • Instruction embedding은 자연어 설명을 장식으로 붙이는 것이 아니라, 같은 text를 어떤 관계 기준으로 표현할지 조건화합니다.
  • Query instruction과 document template은 반드시 model card의 학습 형식을 따라야 합니다. 양쪽에 같은 prompt를 붙이는 것이 항상 맞지 않습니다.
  • Decoder-only LLM을 embedder로 바꾸는 핵심 문제는 causal attention과 pooling입니다. Last-token, input repetition, bidirectional mask, learned latent pooling이 서로 다른 해법입니다.
  • 큰 LLM backbone은 언어·code·instruction transfer를 줄 수 있지만 encoding 비용, dimension, license, contamination risk도 커집니다.
  • Multi-task 평균이 좋아도 retrieval 하나에 최적인 것은 아닙니다. Task instruction robustness와 in-domain Pareto를 따로 평가합니다.

앞 글의 E5는 query/document prefix를 사용했습니다. 이번 글은 이 작은 prefix가 어떻게 범용 embedding의 중요한 축으로 확장됐는지 살펴봅니다.


1. 같은 Text, 다른 Task

문장 “Apple이 2026년 공개한 개발 도구”가 있다고 합시다.

Task A: 검색 — 질문에 답하는 문서를 찾는다.
Task B: 분류 — 기술/금융/음식 topic을 구분한다.
Task C: STS — 뜻이 비슷한 문장을 찾는다.
Task D: entity — 회사 Apple과 과일 apple을 구분한다.

하나의 task-agnostic vector가 모든 관계를 완벽히 보존하기 어렵습니다. Instruction은 encoder에 어떤 관계를 우선할지 알려 줍니다.

2. INSTRUCTOR의 형태

INSTRUCTOR는 text와 task/domain instruction을 함께 embedding하도록 330개 task mixture에 contrastive learning을 적용했습니다.

[instruction: Represent the support question for retrieving an answer]
[text: 제품 3.2의 지원 종료일은?]

논문은 학습에서 보지 않은 task를 포함한 70개 embedding task를 평가했습니다. 핵심 아이디어는 model 하나가 instruction으로 task-specific space를 조건화하는 것입니다.

3. Prefix와 자연어 Instruction

Role Prefix

query: ...
passage: ...

짧고 학습 분포가 명확합니다.

Task Instruction

Instruct: Given a Korean technical support question,
retrieve passages that directly contain the answer.
Query: 제품 3.2의 지원 종료일은?

새 task를 표현하기 쉽지만 wording sensitivity가 생깁니다.

Input Contract 실수

  • Query instruction을 document에도 붙임
  • query: prefix 누락
  • 학습 때 없던 chat template 사용
  • system/user token을 임의로 삽입
  • instruction 뒤 separator 변경
  • max length 계산에서 instruction token 누락

Model A/B 비교 때 각 model의 공식 최적 template과 동일한 공통 generic template을 둘 다 평가하면 공정성을 더 잘 이해할 수 있습니다.

4. Encoder-only와 Decoder-only

Encoder-only

모든 token이 서로를 양방향으로 봅니다.

t1 ↔ t2 ↔ t3 ↔ ... ↔ tT

Mean·CLS pooling으로 전체 표현을 만들기 자연스럽고 보통 작고 빠릅니다.

Decoder-only

Causal mask에서는 token (t_i)가 뒤 token을 보지 못합니다.

t1 → t2 → t3 → ... → tT

마지막 token은 앞을 모두 봤지만 초기 token은 전체 문맥을 모릅니다. 생성 pretraining의 지식과 scaling benefit을 얻는 대신 representation extraction을 다시 설계해야 합니다.

5. Decoder LLM을 Embedder로 바꾸는 네 방법

Last-token/EOS

마지막 hidden state를 사용합니다. 단순하지만 마지막 위치 bottleneck과 padding side에 민감합니다.

Echo Embedding

입력을 반복하고 두 번째 구간을 pooling해 causal model의 token들이 첫 번째 전체 입력을 보게 합니다. Forward token 수가 늘어납니다.

Bidirectional Attention

LLM2Vec는 causal attention을 양방향으로 바꾸고 masked next-token prediction, unsupervised contrastive learning으로 적응합니다. NV-Embed도 bidirectional mask를 사용하고 latent attention pooling을 제안합니다.

Special/Latent Pooling

학습 가능한 latent가 token state를 attention해 vector를 모읍니다. Pooler도 checkpoint의 일부이며 base LLM만 같다고 재사용할 수 있는 것은 아닙니다.

6. E5-Mistral과 Synthetic Instruction Data

Improving Text Embeddings with Large Language Models는 LLM으로 93개 언어와 다양한 task의 synthetic data를 만들고 Mistral-7B 기반 embedder를 contrastive fine-tuning했습니다. Query에 task instruction을 사용합니다.

Instruct: Retrieve relevant passages for the question
Query: ...

Document에는 같은 instruction을 반드시 넣는 형식이 아닙니다. 이 비대칭은 model별 공식 usage를 따라야 합니다.

7. NV-Embed · Architecture와 Data를 함께 바꾼다

NV-Embed는 다음을 결합했습니다.

  • decoder LLM의 causal mask 제거
  • latent attention pooling
  • retrieval-focused stage 후 non-retrieval task stage
  • positive-aware hard-negative mining
  • curated·synthetic data

논문 결과를 “latent pooling 하나가 전부”로 해석하면 안 됩니다. Architecture, training order, data curation의 joint recipe입니다.

8. GritLM · 생성과 Embedding을 한 Model에

Generative Representational Instruction Tuning, GRIT은 instruction으로 generation task와 embedding task를 구분해 하나의 LLM을 함께 학습합니다.

instruction route
  ├─ represent → embedding objective
  └─ generate  → language modeling objective

장점:

  • RAG에서 retriever와 generator weight 공유 가능성
  • memory·deployment footprint 통합
  • generation knowledge가 representation에 transfer 가능

위험:

  • 두 objective의 gradient interference
  • batching·serving pattern이 다름
  • embedding 전용 작은 encoder보다 비쌀 수 있음
  • 한쪽 update가 다른 쪽 behavior를 바꿀 수 있음

논문은 두 task를 통합하면서 각각만 학습한 조건과 견줄 수 있다고 보고했지만, 실제 traffic에서는 memory·throughput을 다시 측정합니다.

9. Qwen3 Embedding · Foundation Model 기반 Multi-stage

Qwen3 Embedding 기술 보고서는 0.6B·4B·8B embedding/reranker 계열을 소개하고 다음 요소를 설명합니다.

  • Qwen3 foundation model backbone
  • 대규모 unsupervised pretraining
  • 고품질 supervised fine-tuning
  • model merging
  • LLM 기반 multilingual·multi-domain data synthesis
  • instruction-aware text embedding

Foundation model의 language/code 능력을 가져오면서 size별 deployment trade-off를 제공합니다. Public benchmark 강점은 shortlist 근거이고, 한국어 query·내 corpus·내 prompt로 재평가해야 합니다.

10. Task LoRA와 Adapter Routing

Jina Embeddings v3는 retrieval, classification, clustering, text matching 등에 task-specific LoRA adapter를 사용합니다.

shared backbone
  + retrieval adapter
  + classification adapter
  + text-matching adapter

Instruction token만으로 task를 조건화하는 것과 parameter adapter를 바꾸는 것은 다릅니다.

방식조건장점운영 위험
Prefixtext token단순·연속적wording 민감도
Natural instructiontext token새 task 표현prompt drift
Adapter/LoRAparameter routetask specializationadapter 선택·version
Separate modelcheckpoint명확한 분리memory·운영 수 증가

11. Multi-task Sampling

Task (t)의 dataset 크기를 (n_t)라 할 때 확률을 단순 (n_t/Σn)로 두면 큰 retrieval dataset이 지배합니다. Temperature sampling 예:

p_t ∝ n_t^α

α = 1   raw proportional
α < 1   smaller tasks upsampled

Task별 loss scale과 negative count도 다릅니다. Batch를 task-homogeneous하게 만들지, mixed하게 만들지 ablation합니다.

12. Instruction Robustness Evaluation

같은 intent를 여러 표현으로 만듭니다.

I1: Retrieve passages that answer the question.
I2: Find evidence containing the direct answer.
I3: 한국어 기술 질문에 답할 근거 문서를 검색하세요.
I4: Return relevant documents.

Metric:

  • instruction별 nDCG/Recall
  • rank correlation
  • top-k overlap
  • worst-instruction performance
  • empty/irrelevant instruction degradation

Best prompt 하나만 보고 model의 instruction-following을 주장하지 않습니다.

13. Model Size 비교를 공정하게

bakeoff:
  quality:
    - exact_ndcg_at_10
    - recall_at_100
    - task_instruction_robustness
  encoding:
    batch_sizes: [1, 32, 128]
    length_buckets: [64, 256, 1024, 4096]
    report: [texts_per_second, tokens_per_second, p95]
  vectors:
    dimensions: official_supported
    dtype: [fp32, fp16, int8]
  system:
    corpus_size: 10000000
    ann_recall_target: 0.95
    storage: measured

7B model의 query latency만 재고 corpus 1천만 개 re-embedding 비용을 빼면 실제 비용을 놓칩니다.

14. 입력 Manifest

embedding_contract:
  model: qwen3-embedding-example
  revision: pinned
  query_template: |
    Instruct: {task}
    Query: {query}
  document_template: "{document}"
  task_instruction: "Retrieve Korean support passages that directly answer the query."
  max_length:
    query: 512
    document: 2048
  pooling: official
  normalize: true
  dimension: 1024

Vector index에는 이 contract hash를 붙입니다. Contract가 다르면 같은 dimension이어도 섞지 않습니다.

15. 언제 어떤 구조를 선택할까

요구먼저 볼 선택
낮은 latency·CPUsmall encoder-only
여러 embedding taskinstruction/task-adapter model
code·복합 multilingualLLM-based embedding shortlist
generation과 weight 공유GRIT류 unified model 실험
on-devicesub-500M + MRL/quantization
매우 긴 문서long-context + contextual/chunk strategy

결론이 아니라 bake-off 시작점입니다.

스스로 확인하기

  1. Instruction이 같은 text의 embedding을 바꿔야 하는 이유는 무엇인가?
  2. Decoder-only LLM에서 causal mask가 mean pooling을 어렵게 만드는 이유는 무엇인가?
  3. LLM2Vec와 echo embedding은 causal context 한계를 어떻게 다르게 해결하는가?
  4. GritLM처럼 generation과 representation을 통합할 때 생기는 운영 trade-off는 무엇인가?
  5. Model A/B 비교에서 공식 prompt와 공통 prompt를 모두 평가하면 무엇을 알 수 있는가?

다음 글에서는 LLM synthetic pair, Cross-Encoder teacher, distillation과 domain adaptation을 안전하게 조합합니다.

참고자료