Lost-in-the-middle siralama + token butcesi (context engineering)
Browse files at this commit00704079568bc6e5c627155e9f840532eecfc484Parent: a3b92b4- feat
- lost-in-the-middle siralama + token butcesi (context engineering)
5 changed files +165 -2
- src/context/__init__.py +5 -0
- src/context/packing.py +64 -0
- src/eval/runner.py +2 -1
- src/generate/generator.py +17 -1
- tests/unit/test_context.py +77 -0
src/context/__init__.pyadded+5 -0
| @@ -0,0 +1,5 @@ | |||
| 1 | +"""Faz — context engineering: token bütçeleme + lost-in-the-middle sıralama.""" | ||
| 2 | +from src.context.packing import (apply_token_budget, reorder_lost_in_middle, | ||
| 3 | + pack_contexts) | ||
| 4 | + | ||
| 5 | +__all__ = ["apply_token_budget", "reorder_lost_in_middle", "pack_contexts"] | ||
src/context/packing.pyadded+64 -0
| @@ -0,0 +1,64 @@ | |||
| 1 | +"""Faz — Context engineering: token bütçeleme + lost-in-the-middle sıralama. | ||
| 2 | + | ||
| 3 | +RES-003 §2-3 + "3 ilke: daha çok context ≠ daha iyi". İki deterministik adım | ||
| 4 | +(LLM YOK, saf mantık) rerank_select çıktısına (RerankedContext listesi, skor | ||
| 5 | +azalan) uygulanır: | ||
| 6 | + | ||
| 7 | +1. **Token bütçesi:** toplam bağlam token'ını sınırla (DeepSeek giriş maliyeti + | ||
| 8 | + context sığdırma). En yüksek skorlu context'ler tutulur; bütçeyi aşınca en | ||
| 9 | + düşük skorlular DÜŞÜRÜLÜR. En az 1 context her zaman kalır (fail-closed eşiği | ||
| 10 | + zaten Generator'da; buraya gelen context alakalı sayılır). | ||
| 11 | +2. **Lost-in-the-middle:** modeller uzun bağlamın ORTASINDAKİ bilgiyi unutur | ||
| 12 | + (Liu 2023). En güçlü kanıtları BAŞA ve SONA, zayıfları ORTAYA yerleştir. | ||
| 13 | + | ||
| 14 | +Atıf/span değişmez — yalnız SIRA + hangi context'lerin dahil edildiği değişir. | ||
| 15 | +""" | ||
| 16 | +from __future__ import annotations | ||
| 17 | + | ||
| 18 | +from ..chunk.chunker import approx_tokens | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def _ctx_text(ctx) -> str: | ||
| 22 | + """Bir context'in token maliyetine sayılan metni (child + varsa parent).""" | ||
| 23 | + text = getattr(ctx, "text", "") or "" | ||
| 24 | + parent = getattr(ctx, "parent_text", None) | ||
| 25 | + if parent and parent.strip() and parent.strip() != text.strip(): | ||
| 26 | + text = f"{text}\n\n{parent}" | ||
| 27 | + return text | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def apply_token_budget(contexts, max_tokens: int): | ||
| 31 | + """Skor-azalan `contexts`'i toplam token bütçesine göre kırp. En yüksek | ||
| 32 | + skorlular tutulur; bütçeyi aşan düşük-skorlular düşer. En az 1 context kalır. | ||
| 33 | + contexts zaten skor-azalan gelir (rerank_select). Sırayı KORUR.""" | ||
| 34 | + if not contexts: | ||
| 35 | + return [] | ||
| 36 | + kept, used = [], 0 | ||
| 37 | + for ctx in contexts: | ||
| 38 | + t = approx_tokens(_ctx_text(ctx)) | ||
| 39 | + if kept and used + t > max_tokens: # ilk context'i her zaman al | ||
| 40 | + break | ||
| 41 | + kept.append(ctx) | ||
| 42 | + used += t | ||
| 43 | + return kept | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def reorder_lost_in_middle(contexts): | ||
| 47 | + """Skor-azalan listeyi 'en güçlü uçlara, zayıf ortaya' düzenine çevir. | ||
| 48 | + Örn. skor sırası [A,B,C,D,E] -> [A,C,E,D,B] (A başta, B sonda; en zayıf D/C orta). | ||
| 49 | + Yöntem: sırayla en güçlüyü BAŞA, sonrakini SONA ekle (deque-benzeri).""" | ||
| 50 | + if len(contexts) <= 2: | ||
| 51 | + return list(contexts) | ||
| 52 | + head, tail = [], [] | ||
| 53 | + for i, ctx in enumerate(contexts): | ||
| 54 | + (head if i % 2 == 0 else tail).append(ctx) | ||
| 55 | + return head + tail[::-1] | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def pack_contexts(contexts, *, max_tokens: int = 8000, reorder: bool = True): | ||
| 59 | + """Bütçe + (opsiyonel) lost-in-the-middle sıralama. Generator bunu | ||
| 60 | + rerank_select'ten SONRA, numaralı kaynakları kurmadan ÖNCE çağırır.""" | ||
| 61 | + packed = apply_token_budget(contexts, max_tokens) | ||
| 62 | + if reorder: | ||
| 63 | + packed = reorder_lost_in_middle(packed) | ||
| 64 | + return packed | ||
src/eval/runner.pymodified+2 -1
| @@ -124,7 +124,8 @@ def build_pipeline(book_path: str = BOOK_PATH) -> dict: | |||
| 124 | from ..guard import LLMSafetyClassifier | 124 | from ..guard import LLMSafetyClassifier |
| 125 | generator = Generator(retriever, reranker, chunks_by_id, span_meta, deepseek, | 125 | generator = Generator(retriever, reranker, chunks_by_id, span_meta, deepseek, |
| 126 | ders="biyoloji", abstain_score=0.30, module="eval", | 126 | ders="biyoloji", abstain_score=0.30, module="eval", |
| 127 | - safety_classifier=LLMSafetyClassifier(deepseek, module="eval")) | 127 | + safety_classifier=LLMSafetyClassifier(deepseek, module="eval"), |
| 128 | + context_packing=True) # token bütçesi + lost-in-the-middle | ||
| 128 | print(f"[eval] pipeline tamamen hazir ({time.time() - t0:.1f}s toplam)") | 129 | print(f"[eval] pipeline tamamen hazir ({time.time() - t0:.1f}s toplam)") |
| 129 | return dict(doc=doc, chunks_by_id=chunks_by_id, span_meta=span_meta, | 130 | return dict(doc=doc, chunks_by_id=chunks_by_id, span_meta=span_meta, |
| 130 | retriever=retriever, reranker=reranker, generator=generator, children=children) | 131 | retriever=retriever, reranker=reranker, generator=generator, children=children) |
src/generate/generator.pymodified+17 -1
| @@ -158,7 +158,8 @@ class Generator: | |||
| 158 | def __init__(self, retriever, reranker, chunks_by_id, span_meta, deepseek=None, *, | 158 | def __init__(self, retriever, reranker, chunks_by_id, span_meta, deepseek=None, *, |
| 159 | ders: str = "", abstain_score: float = 0.30, module: str = "chat", | 159 | ders: str = "", abstain_score: float = 0.30, module: str = "chat", |
| 160 | cost_recorder=None, role_ctx=None, response_cache=None, | 160 | cost_recorder=None, role_ctx=None, response_cache=None, |
| 161 | - safety_classifier=None): | 161 | + safety_classifier=None, context_packing: bool = False, |
| 162 | + context_max_tokens: int = 8000, context_reorder: bool = True): | ||
| 162 | self.retriever = retriever | 163 | self.retriever = retriever |
| 163 | self.reranker = reranker | 164 | self.reranker = reranker |
| 164 | self.chunks_by_id = chunks_by_id | 165 | self.chunks_by_id = chunks_by_id |
| @@ -190,6 +191,12 @@ class Generator: | |||
| 190 | # llm_classifier.py). None ise atlanır (regex check_input tek katman | 191 | # llm_classifier.py). None ise atlanır (regex check_input tek katman |
| 191 | # kalır). Duck-typed: .classify(query) -> GuardVerdict bekler. | 192 | # kalır). Duck-typed: .classify(query) -> GuardVerdict bekler. |
| 192 | self.safety_classifier = safety_classifier | 193 | self.safety_classifier = safety_classifier |
| 194 | + # Context engineering (opsiyonel, bkz. src/context/packing.py): token | ||
| 195 | + # bütçesi + lost-in-the-middle sıralama. Varsayılan KAPALI (mevcut davranış | ||
| 196 | + # korunur); eval/üretim açar. Atıf/span değişmez. | ||
| 197 | + self.context_packing = context_packing | ||
| 198 | + self.context_max_tokens = context_max_tokens | ||
| 199 | + self.context_reorder = context_reorder | ||
| 193 | 200 | ||
| 194 | def _pages_for_span_ids(self, span_ids: list[str]) -> list[int]: | 201 | def _pages_for_span_ids(self, span_ids: list[str]) -> list[int]: |
| 195 | pages = [] | 202 | pages = [] |
| @@ -256,9 +263,18 @@ class Generator: | |||
| 256 | top_n=top_n, candidate_n=candidate_n) | 263 | top_n=top_n, candidate_n=candidate_n) |
| 257 | 264 | ||
| 258 | # FAIL-CLOSED: bağlam yok VEYA en iyi rerank skoru eşik altında → LLM ÇAĞIRMA. | 265 | # FAIL-CLOSED: bağlam yok VEYA en iyi rerank skoru eşik altında → LLM ÇAĞIRMA. |
| 266 | + # (skor-azalan sıra üzerinde kontrol — packing'den ÖNCE) | ||
| 259 | if not contexts or contexts[0].score < self.abstain_score: | 267 | if not contexts or contexts[0].score < self.abstain_score: |
| 260 | return self._abstain("insufficient_data") | 268 | return self._abstain("insufficient_data") |
| 261 | 269 | ||
| 270 | + # CONTEXT ENGINEERING (opsiyonel): token bütçesi + lost-in-the-middle sıralama | ||
| 271 | + # (bkz. src/context/packing.py). Atıf/span değişmez; yalnız sıra + dahil edilen | ||
| 272 | + # context'ler. fail-closed'dan SONRA, numaralı kaynaklardan ÖNCE. | ||
| 273 | + if self.context_packing: | ||
| 274 | + from ..context import pack_contexts | ||
| 275 | + contexts = pack_contexts(contexts, max_tokens=self.context_max_tokens, | ||
| 276 | + reorder=self.context_reorder) | ||
| 277 | + | ||
| 262 | # kaynakları numarala + span_meta'dan gerçek sayfa(lar)ı çıkar; her kaynağın | 278 | # kaynakları numarala + span_meta'dan gerçek sayfa(lar)ı çıkar; her kaynağın |
| 263 | # metnine (varsa) parent genişletmesini ayrı, net biçimde ekle (yalnız bağlam | 279 | # metnine (varsa) parent genişletmesini ayrı, net biçimde ekle (yalnız bağlam |
| 264 | # — atıf/sayfa child span'dan hesaplanır, aşağıda değişmez) | 280 | # — atıf/sayfa child span'dan hesaplanır, aşağıda değişmez) |
tests/unit/test_context.pyadded+77 -0
| @@ -0,0 +1,77 @@ | |||
| 1 | +"""Faz birim testleri — context packing (token bütçe + lost-in-the-middle). LLM gerekmez.""" | ||
| 2 | +import unittest | ||
| 3 | +from dataclasses import dataclass, field | ||
| 4 | + | ||
| 5 | +from src.context import apply_token_budget, reorder_lost_in_middle, pack_contexts | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +@dataclass | ||
| 9 | +class _Ctx: | ||
| 10 | + chunk_id: str | ||
| 11 | + text: str | ||
| 12 | + score: float = 1.0 | ||
| 13 | + parent_text: str | None = None | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def _mk(n, words_each=100): | ||
| 17 | + # her context ~words_each kelime -> approx_tokens ile ölçülebilir token | ||
| 18 | + return [_Ctx(f"c{i}", " ".join(["kelime"] * words_each), score=1.0 - i * 0.1) | ||
| 19 | + for i in range(n)] | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class TokenBudgetTests(unittest.TestCase): | ||
| 23 | + def test_budget_drops_low_score_tail(self): | ||
| 24 | + ctxs = _mk(5, words_each=100) # her biri ~130 token (100 kelime * 1.3) | ||
| 25 | + kept = apply_token_budget(ctxs, max_tokens=300) # ~2 context sığar | ||
| 26 | + self.assertLess(len(kept), 5) | ||
| 27 | + self.assertGreaterEqual(len(kept), 1) | ||
| 28 | + self.assertEqual(kept[0].chunk_id, "c0") # en yüksek skor korunur | ||
| 29 | + | ||
| 30 | + def test_always_keeps_at_least_one(self): | ||
| 31 | + ctxs = _mk(3, words_each=5000) # her biri bütçeden büyük | ||
| 32 | + kept = apply_token_budget(ctxs, max_tokens=10) | ||
| 33 | + self.assertEqual(len(kept), 1) # ilk context her zaman kalır | ||
| 34 | + self.assertEqual(kept[0].chunk_id, "c0") | ||
| 35 | + | ||
| 36 | + def test_all_fit_under_budget(self): | ||
| 37 | + ctxs = _mk(3, words_each=10) | ||
| 38 | + kept = apply_token_budget(ctxs, max_tokens=100000) | ||
| 39 | + self.assertEqual(len(kept), 3) | ||
| 40 | + | ||
| 41 | + def test_empty(self): | ||
| 42 | + self.assertEqual(apply_token_budget([], 100), []) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class LostInMiddleTests(unittest.TestCase): | ||
| 46 | + def test_strong_at_ends_weak_in_middle(self): | ||
| 47 | + ctxs = _mk(5) # c0 en güçlü, c4 en zayıf | ||
| 48 | + out = [c.chunk_id for c in reorder_lost_in_middle(ctxs)] | ||
| 49 | + self.assertEqual(out, ["c0", "c2", "c4", "c3", "c1"]) | ||
| 50 | + self.assertEqual(out[0], "c0") # en güçlü başta | ||
| 51 | + self.assertEqual(out[-1], "c1") # 2. güçlü sonda | ||
| 52 | + self.assertEqual(out[len(out) // 2], "c4") # en zayıf ortada | ||
| 53 | + | ||
| 54 | + def test_two_or_fewer_unchanged(self): | ||
| 55 | + ctxs = _mk(2) | ||
| 56 | + self.assertEqual([c.chunk_id for c in reorder_lost_in_middle(ctxs)], ["c0", "c1"]) | ||
| 57 | + self.assertEqual(reorder_lost_in_middle([]), []) | ||
| 58 | + | ||
| 59 | + def test_pack_combines_budget_and_reorder(self): | ||
| 60 | + ctxs = _mk(5, words_each=10) # hepsi sığar | ||
| 61 | + out = [c.chunk_id for c in pack_contexts(ctxs, max_tokens=100000, reorder=True)] | ||
| 62 | + self.assertEqual(out, ["c0", "c2", "c4", "c3", "c1"]) | ||
| 63 | + | ||
| 64 | + def test_pack_no_reorder(self): | ||
| 65 | + ctxs = _mk(4, words_each=10) | ||
| 66 | + out = [c.chunk_id for c in pack_contexts(ctxs, max_tokens=100000, reorder=False)] | ||
| 67 | + self.assertEqual(out, ["c0", "c1", "c2", "c3"]) | ||
| 68 | + | ||
| 69 | + def test_parent_text_counts_toward_budget(self): | ||
| 70 | + # parent_text token maliyetine dahil edilmeli | ||
| 71 | + c = _Ctx("c0", "kısa", score=1.0, parent_text=" ".join(["uzun"] * 5000)) | ||
| 72 | + kept = apply_token_budget([c, _Ctx("c1", "kısa2", 0.9)], max_tokens=50) | ||
| 73 | + self.assertEqual(len(kept), 1) # c0'ın parent'ı bütçeyi doldurur | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +if __name__ == "__main__": | ||
| 77 | + unittest.main() | ||