Aman045 commited on
Commit
da927c9
·
1 Parent(s): 178f9f9

remove: delete old server/retrieval.py and rewards.py

Browse files
Files changed (2) hide show
  1. server/retrieval.py +0 -379
  2. server/rewards.py +0 -510
server/retrieval.py DELETED
@@ -1,379 +0,0 @@
1
- """
2
- Retrieval system for the Search RL Environment.
3
- Implements BM25 search, with hooks for future hybrid search.
4
- """
5
-
6
- from __future__ import annotations
7
-
8
- import math
9
- import re
10
- from collections import defaultdict
11
- from typing import Any
12
-
13
- try:
14
- from ..models import Chunk, ChunkSummary
15
- except ImportError:
16
- from models import Chunk, ChunkSummary
17
-
18
-
19
- class BM25Index:
20
- """
21
- BM25 search index for document retrieval.
22
-
23
- A simple but effective implementation of Okapi BM25 for the MVP.
24
- Can be replaced with more sophisticated hybrid search later.
25
- """
26
-
27
- def __init__(
28
- self,
29
- k1: float = 1.5,
30
- b: float = 0.75,
31
- epsilon: float = 0.25,
32
- ):
33
- """
34
- Initialize BM25 index.
35
-
36
- Args:
37
- k1: Term frequency saturation parameter
38
- b: Length normalization parameter
39
- epsilon: Floor for IDF to handle terms in all docs
40
- """
41
- self.k1 = k1
42
- self.b = b
43
- self.epsilon = epsilon
44
-
45
- # Document storage
46
- self.chunks: dict[str, Chunk] = {}
47
- self.doc_freqs: dict[str, int] = defaultdict(int) # term -> doc count
48
- self.doc_lens: dict[str, int] = {} # chunk_id -> doc length
49
- self.avg_doc_len: float = 0.0
50
- self.corpus_size: int = 0
51
- self._total_doc_len: int = 0
52
-
53
- # Inverted index: term -> {chunk_id: term_freq}
54
- self.inverted_index: dict[str, dict[str, int]] = defaultdict(dict)
55
-
56
- # Token count cache
57
- self._token_counts: dict[str, int] = {}
58
-
59
- def _tokenize(self, text: str) -> list[str]:
60
- """Simple tokenization: lowercase, split on non-alphanumeric."""
61
- text = text.lower()
62
- tokens = re.findall(r"\b\w+\b", text)
63
- return tokens
64
-
65
- def _estimate_tokens(self, text: str) -> int:
66
- """Estimate token count (roughly 4 chars per token for English)."""
67
- return max(1, len(text) // 4)
68
-
69
- def add_chunk(self, chunk: Chunk) -> None:
70
- """Add a chunk to the index."""
71
- if chunk.chunk_id in self.chunks:
72
- return
73
-
74
- self.chunks[chunk.chunk_id] = chunk
75
-
76
- # Tokenize content
77
- tokens = self._tokenize(chunk.content)
78
- doc_len = len(tokens)
79
- self.doc_lens[chunk.chunk_id] = doc_len
80
-
81
- # Update token count
82
- if chunk.token_count == 0:
83
- chunk.token_count = self._estimate_tokens(chunk.content)
84
- self._token_counts[chunk.chunk_id] = chunk.token_count
85
-
86
- # Count term frequencies
87
- term_freqs: dict[str, int] = defaultdict(int)
88
- for token in tokens:
89
- term_freqs[token] += 1
90
-
91
- # Update inverted index and document frequencies
92
- for term, freq in term_freqs.items():
93
- if chunk.chunk_id not in self.inverted_index[term]:
94
- self.doc_freqs[term] += 1
95
- self.inverted_index[term][chunk.chunk_id] = freq
96
-
97
- self.corpus_size += 1
98
- self._total_doc_len += doc_len
99
- self.avg_doc_len = self._total_doc_len / self.corpus_size
100
-
101
- def add_chunks(self, chunks: list[Chunk]) -> None:
102
- """Add multiple chunks to the index."""
103
- for chunk in chunks:
104
- self.add_chunk(chunk)
105
-
106
- def _compute_idf(self, term: str) -> float:
107
- """Compute IDF for a term."""
108
- doc_freq = self.doc_freqs.get(term, 0)
109
- if doc_freq == 0:
110
- return 0.0
111
-
112
- idf = math.log((self.corpus_size - doc_freq + 0.5) / (doc_freq + 0.5) + 1)
113
- return max(idf, self.epsilon)
114
-
115
- def _score_document(self, chunk_id: str, query_terms: list[str]) -> float:
116
- """Compute BM25 score for a document given query terms."""
117
- score = 0.0
118
- doc_len = self.doc_lens.get(chunk_id, 0)
119
-
120
- for term in query_terms:
121
- if term not in self.inverted_index:
122
- continue
123
- if chunk_id not in self.inverted_index[term]:
124
- continue
125
-
126
- tf = self.inverted_index[term][chunk_id]
127
- idf = self._compute_idf(term)
128
-
129
- # BM25 formula
130
- numerator = tf * (self.k1 + 1)
131
- denominator = tf + self.k1 * (
132
- 1 - self.b + self.b * doc_len / self.avg_doc_len
133
- )
134
- score += idf * (numerator / denominator)
135
-
136
- return score
137
-
138
- def search(
139
- self,
140
- query: str,
141
- top_k: int = 10,
142
- exclude_ids: set[str] | None = None,
143
- ) -> list[tuple[str, float]]:
144
- """
145
- Search the index.
146
-
147
- Args:
148
- query: Search query string
149
- top_k: Number of results to return
150
- exclude_ids: Chunk IDs to exclude from results
151
-
152
- Returns:
153
- List of (chunk_id, score) tuples, sorted by score descending
154
- """
155
- exclude_ids = exclude_ids or set()
156
- query_terms = self._tokenize(query)
157
-
158
- if not query_terms:
159
- return []
160
-
161
- # Find candidate documents (those containing at least one query term)
162
- candidates: set[str] = set()
163
- for term in query_terms:
164
- if term in self.inverted_index:
165
- candidates.update(self.inverted_index[term].keys())
166
-
167
- # Remove excluded IDs
168
- candidates -= exclude_ids
169
-
170
- # Score candidates
171
- scores: list[tuple[str, float]] = []
172
- for chunk_id in candidates:
173
- score = self._score_document(chunk_id, query_terms)
174
- if score > 0:
175
- scores.append((chunk_id, score))
176
-
177
- # Sort by score descending
178
- scores.sort(key=lambda x: x[1], reverse=True)
179
-
180
- return scores[:top_k]
181
-
182
- def get_chunk(self, chunk_id: str) -> Chunk | None:
183
- """Get a chunk by ID."""
184
- return self.chunks.get(chunk_id)
185
-
186
- def get_chunks(self, chunk_ids: list[str]) -> list[Chunk]:
187
- """Get multiple chunks by ID."""
188
- return [self.chunks[cid] for cid in chunk_ids if cid in self.chunks]
189
-
190
- def get_token_count(self, chunk_id: str) -> int:
191
- """Get token count for a chunk."""
192
- return self._token_counts.get(chunk_id, 0)
193
-
194
- def create_summary(
195
- self, chunk_id: str, score: float = 0.0, snippet_length: int = 200
196
- ) -> ChunkSummary | None:
197
- """Create a ChunkSummary from a chunk ID."""
198
- chunk = self.chunks.get(chunk_id)
199
- if not chunk:
200
- return None
201
-
202
- # Create snippet (first N characters)
203
- snippet = chunk.content[:snippet_length]
204
- if len(chunk.content) > snippet_length:
205
- snippet = snippet.rsplit(" ", 1)[0] + "..."
206
-
207
- # Get title from metadata or use doc ID
208
- title = chunk.metadata.get("title", chunk.document_id)
209
-
210
- return ChunkSummary(
211
- chunk_id=chunk_id,
212
- document_id=chunk.document_id,
213
- title=title,
214
- snippet=snippet,
215
- score=score,
216
- token_count=chunk.token_count,
217
- )
218
-
219
- @property
220
- def size(self) -> int:
221
- """Number of chunks in the index."""
222
- return self.corpus_size
223
-
224
-
225
- class DocumentCorpus:
226
- """
227
- Document corpus manager.
228
-
229
- Wraps the search index and provides higher-level operations.
230
- """
231
-
232
- def __init__(self, config: dict[str, Any] | None = None):
233
- """Initialize corpus with optional config."""
234
- self.config = config or {}
235
- self.index = BM25Index(
236
- k1=self.config.get("bm25_k1", 1.5),
237
- b=self.config.get("bm25_b", 0.75),
238
- )
239
-
240
- # Track documents (groups of chunks)
241
- self.documents: dict[str, list[str]] = defaultdict(
242
- list
243
- ) # doc_id -> [chunk_ids]
244
-
245
- def add_document(
246
- self,
247
- doc_id: str,
248
- content: str,
249
- metadata: dict[str, Any] | None = None,
250
- chunk_size: int = 1000,
251
- chunk_overlap: int = 200,
252
- ) -> list[str]:
253
- """
254
- Add a document to the corpus, chunking if necessary.
255
-
256
- Args:
257
- doc_id: Document identifier
258
- content: Full document content
259
- metadata: Document metadata
260
- chunk_size: Target chunk size in characters
261
- chunk_overlap: Overlap between chunks
262
-
263
- Returns:
264
- List of chunk IDs created
265
- """
266
- metadata = metadata or {}
267
- chunks = self._chunk_text(content, chunk_size, chunk_overlap)
268
- chunk_ids = []
269
-
270
- for i, chunk_text in enumerate(chunks):
271
- chunk_id = f"{doc_id}_chunk_{i}"
272
- chunk = Chunk(
273
- chunk_id=chunk_id,
274
- document_id=doc_id,
275
- content=chunk_text,
276
- metadata={**metadata, "chunk_index": i, "total_chunks": len(chunks)},
277
- )
278
- self.index.add_chunk(chunk)
279
- self.documents[doc_id].append(chunk_id)
280
- chunk_ids.append(chunk_id)
281
-
282
- return chunk_ids
283
-
284
- def add_chunk(self, chunk: Chunk) -> None:
285
- """Add a pre-created chunk to the corpus."""
286
- self.index.add_chunk(chunk)
287
- self.documents[chunk.document_id].append(chunk.chunk_id)
288
-
289
- def _chunk_text(self, text: str, chunk_size: int, overlap: int) -> list[str]:
290
- """Split text into overlapping chunks."""
291
- if len(text) <= chunk_size:
292
- return [text]
293
-
294
- chunks = []
295
- start = 0
296
-
297
- while start < len(text):
298
- end = start + chunk_size
299
-
300
- # Try to break at sentence boundary
301
- if end < len(text):
302
- # Look for sentence end near the chunk boundary
303
- search_start = max(start + chunk_size - 100, start)
304
- search_end = min(start + chunk_size + 100, len(text))
305
- search_region = text[search_start:search_end]
306
-
307
- # Find last sentence boundary in search region
308
- for sep in [". ", ".\n", "! ", "? "]:
309
- last_sep = search_region.rfind(sep)
310
- if last_sep != -1:
311
- end = search_start + last_sep + len(sep)
312
- break
313
-
314
- chunk_text = text[start:end].strip()
315
- if chunk_text:
316
- chunks.append(chunk_text)
317
-
318
- start = end - overlap
319
- if start >= len(text) - overlap:
320
- break
321
-
322
- return chunks
323
-
324
- def search(
325
- self,
326
- query: str,
327
- top_k: int = 10,
328
- exclude_ids: set[str] | None = None,
329
- snippet_length: int = 200,
330
- ) -> list[ChunkSummary]:
331
- """
332
- Search the corpus.
333
-
334
- Args:
335
- query: Search query
336
- top_k: Number of results
337
- exclude_ids: Chunk IDs to exclude
338
- snippet_length: Length of snippets in results
339
-
340
- Returns:
341
- List of ChunkSummary objects
342
- """
343
- results = self.index.search(query, top_k, exclude_ids)
344
- summaries = []
345
-
346
- for chunk_id, score in results:
347
- summary = self.index.create_summary(chunk_id, score, snippet_length)
348
- if summary:
349
- summaries.append(summary)
350
-
351
- return summaries
352
-
353
- def get_chunk(self, chunk_id: str) -> Chunk | None:
354
- """Get a chunk by ID."""
355
- return self.index.get_chunk(chunk_id)
356
-
357
- def get_chunks(self, chunk_ids: list[str]) -> list[Chunk]:
358
- """Get multiple chunks."""
359
- chunks: list[Chunk] = []
360
- for chunk_id in chunk_ids:
361
- chunk = self.get_chunk(chunk_id)
362
- if chunk is not None:
363
- chunks.append(chunk)
364
- return chunks
365
-
366
- def get_document_chunks(self, doc_id: str) -> list[Chunk]:
367
- """Get all chunks for a document."""
368
- chunk_ids = self.documents.get(doc_id, [])
369
- return self.get_chunks(chunk_ids)
370
-
371
- @property
372
- def num_chunks(self) -> int:
373
- """Total number of chunks."""
374
- return self.index.size
375
-
376
- @property
377
- def num_documents(self) -> int:
378
- """Total number of documents."""
379
- return len(self.documents)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
server/rewards.py DELETED
@@ -1,510 +0,0 @@
1
- """
2
- Reward functions for the Search RL Environment.
3
- Implements F-beta reward with trajectory tracking.
4
- """
5
-
6
- from __future__ import annotations
7
-
8
- import re
9
- from dataclasses import dataclass, field
10
- from difflib import SequenceMatcher
11
- from collections.abc import Iterable
12
-
13
-
14
- @dataclass
15
- class RewardMetrics:
16
- """Metrics computed for reward calculation."""
17
-
18
- output_precision: float = 0.0
19
- output_recall: float = 0.0
20
- trajectory_recall: float = 0.0
21
- f_beta: float = 0.0
22
- beta: float = 4.0
23
- answer_correct: bool = False
24
- answer_similarity: float = 0.0
25
- answer_found_in_context: bool = False
26
- steps_used: int = 0
27
- max_steps: int = 20
28
- tokens_used: int = 0
29
- max_tokens: int = 32768
30
- f_beta_reward: float = 0.0
31
- trajectory_reward: float = 0.0
32
- answer_reward: float = 0.0
33
- efficiency_reward: float = 0.0
34
- turn_penalty: float = 0.0
35
- prune_penalty: float = 0.0
36
- pre_penalty_reward: float = 0.0
37
- reward_floor: float = 0.0
38
- total_reward: float = 0.0
39
-
40
-
41
- @dataclass
42
- class TrajectoryTracker:
43
- """
44
- Tracks chunks encountered during an episode.
45
-
46
- Used to compute trajectory recall - rewarding exploration even if
47
- relevant chunks are later pruned.
48
- """
49
-
50
- chunks_seen: set[str] = field(default_factory=set)
51
- chunks_in_context: set[str] = field(default_factory=set)
52
- queries: list[str] = field(default_factory=list)
53
- consecutive_prunes: int = 0
54
- total_prunes: int = 0
55
-
56
- def record_search(self, query: str, chunk_ids: list[str]) -> None:
57
- """Record a search action."""
58
- self.queries.append(query)
59
- self.chunks_seen.update(chunk_ids)
60
- self.consecutive_prunes = 0 # Reset prune streak
61
-
62
- def record_read(self, chunk_ids: list[str]) -> None:
63
- """Record chunks added to context."""
64
- self.chunks_in_context.update(chunk_ids)
65
- self.chunks_seen.update(chunk_ids)
66
- self.consecutive_prunes = 0
67
-
68
- def record_prune(self, chunk_ids: list[str]) -> None:
69
- """Record chunks removed from context."""
70
- self.chunks_in_context -= set(chunk_ids)
71
- self.consecutive_prunes += 1
72
- self.total_prunes += 1
73
-
74
- def reset(self) -> None:
75
- """Reset tracker for new episode."""
76
- self.chunks_seen.clear()
77
- self.chunks_in_context.clear()
78
- self.queries.clear()
79
- self.consecutive_prunes = 0
80
- self.total_prunes = 0
81
-
82
-
83
- class RewardCalculator:
84
- """
85
- Calculate rewards for the Search RL Environment.
86
-
87
- Based on the Context-1 paper's reward formula:
88
- R = F_β(precision, recall) + R_answer - penalties
89
-
90
- Components:
91
- - F-beta score: Measures retrieval quality (0 to 1)
92
- - Answer bonus: +1.0 if context contains the gold answer
93
- - Trajectory recall: Optional process reward for exploration
94
- - Penalties: Turn count and excessive pruning penalties
95
-
96
- Total reward range: approximately -0.5 to 2.0
97
- """
98
-
99
- def __init__(
100
- self,
101
- beta: float = 4.0,
102
- f_beta_weight: float = 1.0,
103
- answer_reward_weight: float = 1.0,
104
- trajectory_reward_weight: float = 0.0,
105
- efficiency_reward_weight: float = 0.0,
106
- successful_trajectory_floor: float = 0.0,
107
- use_trajectory_reward: bool = False,
108
- prune_penalty_threshold: int = 3,
109
- prune_penalty_per_excess: float = 0.1,
110
- prune_penalty_cap: float = 0.5,
111
- turn_penalty_start: int = 15,
112
- turn_penalty_end: int = 20,
113
- turn_penalty_max: float = 0.5,
114
- ):
115
- """
116
- Initialize reward calculator.
117
-
118
- Args:
119
- beta: F-beta parameter. >1 favors recall, <1 favors precision.
120
- Paper uses β=4 initially (recall-heavy), annealing to β=1.
121
- f_beta_weight: Weight for the F-beta component (default 1.0 per paper)
122
- answer_reward_weight: Bonus if answer found in context (default 1.0)
123
- trajectory_reward_weight: Weight for trajectory recall (exploration credit)
124
- efficiency_reward_weight: Weight for efficiency (usually 0)
125
- successful_trajectory_floor: Minimum reward floor
126
- use_trajectory_reward: Whether to include trajectory recall in reward
127
- prune_penalty_threshold: Consecutive prunes before penalty starts
128
- prune_penalty_per_excess: Penalty per excess prune (0.1 per paper)
129
- prune_penalty_cap: Maximum prune penalty (0.5 per paper)
130
- turn_penalty_start: Turn at which penalty begins
131
- turn_penalty_end: Turn at which penalty reaches max
132
- turn_penalty_max: Maximum turn penalty (0.5 per paper)
133
- """
134
- self.beta = beta
135
- self.f_beta_weight = f_beta_weight
136
- self.answer_reward_weight = answer_reward_weight
137
- self.trajectory_reward_weight = trajectory_reward_weight
138
- self.efficiency_reward_weight = efficiency_reward_weight
139
- self.successful_trajectory_floor = successful_trajectory_floor
140
- self.use_trajectory_reward = use_trajectory_reward
141
- self.prune_penalty_threshold = prune_penalty_threshold
142
- self.prune_penalty_per_excess = prune_penalty_per_excess
143
- self.prune_penalty_cap = prune_penalty_cap
144
- self.turn_penalty_start = turn_penalty_start
145
- self.turn_penalty_end = turn_penalty_end
146
- self.turn_penalty_max = turn_penalty_max
147
-
148
- @staticmethod
149
- def _normalize_text(text: str) -> str:
150
- """Normalize text for lightweight string matching."""
151
- return " ".join(text.strip().lower().split())
152
-
153
- def compute_f_beta(
154
- self, precision: float, recall: float, beta: float | None = None
155
- ) -> float:
156
- """
157
- Compute F-beta score.
158
-
159
- Args:
160
- precision: Precision value [0, 1]
161
- recall: Recall value [0, 1]
162
- beta: Beta parameter (uses self.beta if None)
163
-
164
- Returns:
165
- F-beta score [0, 1]
166
- """
167
- beta = beta if beta is not None else self.beta
168
-
169
- if precision + recall == 0:
170
- return 0.0
171
-
172
- beta_sq = beta**2
173
- f_beta = (1 + beta_sq) * (precision * recall) / (beta_sq * precision + recall)
174
- return f_beta
175
-
176
- def compute_precision_recall(
177
- self,
178
- retrieved_chunks: set[str],
179
- gold_chunks: set[str],
180
- ) -> tuple[float, float]:
181
- """
182
- Compute precision and recall.
183
-
184
- Args:
185
- retrieved_chunks: Set of chunk IDs in output
186
- gold_chunks: Set of gold chunk IDs
187
-
188
- Returns:
189
- Tuple of (precision, recall)
190
- """
191
- if not retrieved_chunks:
192
- return 0.0, 0.0
193
-
194
- if not gold_chunks:
195
- return 0.0, 1.0 # No gold chunks means recall is trivially 1
196
-
197
- true_positives = len(retrieved_chunks & gold_chunks)
198
- precision = true_positives / len(retrieved_chunks)
199
- recall = true_positives / len(gold_chunks)
200
-
201
- return precision, recall
202
-
203
- def compute_answer_similarity(
204
- self,
205
- predicted: str,
206
- gold: str,
207
- method: str = "fuzzy",
208
- ) -> tuple[bool, float]:
209
- """
210
- Evaluate answer quality.
211
-
212
- Args:
213
- predicted: Predicted answer
214
- gold: Gold answer
215
- method: Evaluation method ("exact", "fuzzy", "contains")
216
-
217
- Returns:
218
- Tuple of (is_correct, similarity_score)
219
- """
220
- pred_lower = self._normalize_text(predicted)
221
- gold_lower = self._normalize_text(gold)
222
-
223
- if method == "exact":
224
- is_correct = pred_lower == gold_lower
225
- similarity = 1.0 if is_correct else 0.0
226
-
227
- elif method == "fuzzy":
228
- similarity = SequenceMatcher(None, pred_lower, gold_lower).ratio()
229
- is_correct = similarity >= 0.8 # 80% threshold
230
-
231
- elif method == "contains":
232
- is_correct = gold_lower in pred_lower or pred_lower in gold_lower
233
- similarity = (
234
- 1.0
235
- if is_correct
236
- else SequenceMatcher(None, pred_lower, gold_lower).ratio()
237
- )
238
-
239
- else:
240
- raise ValueError(f"Unknown method: {method}")
241
-
242
- return is_correct, similarity
243
-
244
- def compute_answer_found_in_context(
245
- self,
246
- context_texts: Iterable[str] | None,
247
- gold_answer: str,
248
- ) -> bool:
249
- """
250
- Check whether the final context includes key parts of the gold answer.
251
-
252
- Uses a lenient matching approach: extracts key entities/facts from
253
- the gold answer and checks if they appear in the context.
254
- """
255
- if not context_texts:
256
- return False
257
-
258
- gold_normalized = self._normalize_text(gold_answer)
259
- if not gold_normalized:
260
- return False
261
-
262
- # Extract key phrases from gold answer
263
- # This handles cases like "Mark Zuckerberg was born in White Plains, New York"
264
- # The full normalized answer is used for matching, plus we split on punctuation
265
- # to extract sub phrases like "mark zuckerberg" and "white plains new york"
266
- key_phrases = []
267
- sub_phrases = re.split(r"[,;:\-\(\)]", gold_normalized)
268
- for sub in sub_phrases:
269
- sub = sub.strip()
270
- if len(sub) > 3:
271
- key_phrases.append(sub)
272
-
273
- # Also add the full normalized gold answer
274
- key_phrases.append(gold_normalized)
275
- context_combined = " ".join(self._normalize_text(t) for t in context_texts)
276
-
277
- if gold_normalized in context_combined:
278
- return True
279
-
280
- # Key phrase matching: require majority of key phrases found
281
- if key_phrases:
282
- found_count = sum(1 for phrase in key_phrases if phrase in context_combined)
283
- required = min(2, max(1, len(key_phrases) // 2))
284
- if found_count >= required:
285
- return True
286
-
287
- return False
288
-
289
- def compute_efficiency_reward(
290
- self,
291
- steps_used: int,
292
- max_steps: int,
293
- tokens_used: int,
294
- max_tokens: int,
295
- ) -> float:
296
- """
297
- Compute efficiency reward.
298
-
299
- Args:
300
- steps_used: Number of steps taken
301
- max_steps: Maximum allowed steps
302
- tokens_used: Tokens used in context
303
- max_tokens: Maximum token budget
304
-
305
- Returns:
306
- Efficiency reward [0, 1]
307
- """
308
- step_efficiency = 1 - (steps_used / max_steps) if max_steps > 0 else 0
309
- token_efficiency = 1 - (tokens_used / max_tokens) if max_tokens > 0 else 0
310
-
311
- return (step_efficiency + token_efficiency) / 2
312
-
313
- def compute_turn_penalty(self, steps: int) -> float:
314
- """
315
- Compute turn count penalty.
316
-
317
- Linear penalty from turn_penalty_start to turn_penalty_end.
318
- """
319
- if steps <= self.turn_penalty_start:
320
- return 0.0
321
-
322
- if self.turn_penalty_end == self.turn_penalty_start:
323
- return self.turn_penalty_max
324
-
325
- progress = (steps - self.turn_penalty_start) / (
326
- self.turn_penalty_end - self.turn_penalty_start
327
- )
328
- return min(self.turn_penalty_max, self.turn_penalty_max * progress)
329
-
330
- def compute_prune_penalty(self, consecutive_prunes: int) -> float:
331
- """
332
- Compute penalty for excessive consecutive pruning.
333
-
334
- Discourages pruning one chunk at a time.
335
- """
336
- if consecutive_prunes <= self.prune_penalty_threshold:
337
- return 0.0
338
-
339
- excess = consecutive_prunes - self.prune_penalty_threshold
340
- return min(self.prune_penalty_cap, excess * self.prune_penalty_per_excess)
341
-
342
- def calculate_reward(
343
- self,
344
- tracker: TrajectoryTracker,
345
- gold_chunks: set[str],
346
- gold_answer: str,
347
- predicted_answer: str,
348
- context_texts: list[str] | None,
349
- steps_used: int,
350
- max_steps: int,
351
- tokens_used: int,
352
- max_tokens: int,
353
- answer_method: str = "fuzzy",
354
- all_seen_texts: list[str] | None = None,
355
- ) -> RewardMetrics:
356
- """
357
- Calculate full reward for an episode.
358
-
359
- Args:
360
- tracker: Trajectory tracker with episode history
361
- gold_chunks: Set of gold chunk IDs
362
- gold_answer: Gold answer string
363
- predicted_answer: Agent's predicted answer
364
- context_texts: Full text of chunks currently kept in context
365
- steps_used: Number of steps taken
366
- max_steps: Maximum allowed steps
367
- tokens_used: Tokens used in context
368
- max_tokens: Maximum token budget
369
- answer_method: Method for answer evaluation
370
- all_seen_texts: Optional list of all chunk texts seen (for content-based matching)
371
-
372
- Returns:
373
- RewardMetrics with all components
374
- """
375
- metrics = RewardMetrics(
376
- beta=self.beta,
377
- steps_used=steps_used,
378
- max_steps=max_steps,
379
- tokens_used=tokens_used,
380
- max_tokens=max_tokens,
381
- )
382
-
383
- # Primary: ID-based matching (matches gold chunk IDs directly)
384
- output_precision, output_recall = self.compute_precision_recall(
385
- tracker.chunks_in_context, gold_chunks
386
- )
387
- _, trajectory_recall = self.compute_precision_recall(
388
- tracker.chunks_seen, gold_chunks
389
- )
390
-
391
- # Content-based fallback: if ID matching finds nothing but we have a gold answer,
392
- # check if the agent found content containing the answer (handles ID mismatches)
393
- if trajectory_recall == 0 and gold_answer:
394
- gold_norm = self._normalize_text(gold_answer)
395
-
396
- # Check if any seen content contains the gold answer
397
- if all_seen_texts:
398
- seen_relevant = sum(
399
- 1
400
- for text in all_seen_texts
401
- if gold_norm in self._normalize_text(text)
402
- )
403
- if seen_relevant > 0:
404
- trajectory_recall = 1.0 # Found relevant content
405
-
406
- # Check if context contains gold answer
407
- if context_texts:
408
- context_relevant = sum(
409
- 1
410
- for text in context_texts
411
- if gold_norm in self._normalize_text(text)
412
- )
413
- if context_relevant > 0 and len(context_texts) > 0:
414
- output_recall = 1.0
415
- output_precision = context_relevant / len(context_texts)
416
-
417
- metrics.output_precision = output_precision
418
- metrics.output_recall = output_recall
419
- metrics.trajectory_recall = trajectory_recall
420
-
421
- # F-beta score on output
422
- metrics.f_beta = self.compute_f_beta(output_precision, output_recall)
423
-
424
- # Answer evaluation
425
- answer_correct, answer_similarity = self.compute_answer_similarity(
426
- predicted_answer, gold_answer, answer_method
427
- )
428
- metrics.answer_correct = answer_correct
429
- metrics.answer_similarity = answer_similarity
430
- metrics.answer_found_in_context = self.compute_answer_found_in_context(
431
- context_texts, gold_answer
432
- )
433
-
434
- efficiency = self.compute_efficiency_reward(
435
- steps_used, max_steps, tokens_used, max_tokens
436
- )
437
- metrics.efficiency_reward = efficiency * self.efficiency_reward_weight
438
- metrics.turn_penalty = self.compute_turn_penalty(steps_used)
439
- metrics.prune_penalty = self.compute_prune_penalty(tracker.consecutive_prunes)
440
-
441
- metrics.f_beta_reward = metrics.f_beta * self.f_beta_weight
442
- metrics.trajectory_reward = (
443
- trajectory_recall * self.trajectory_reward_weight
444
- if self.use_trajectory_reward
445
- else 0.0
446
- )
447
-
448
- metrics.answer_reward = (
449
- self.answer_reward_weight if metrics.answer_found_in_context else 0.0
450
- )
451
-
452
- metrics.pre_penalty_reward = (
453
- metrics.f_beta_reward + metrics.trajectory_reward + metrics.answer_reward
454
- )
455
- metrics.reward_floor = self.successful_trajectory_floor
456
-
457
- total = (
458
- metrics.pre_penalty_reward - metrics.turn_penalty - metrics.prune_penalty
459
- )
460
-
461
- # Clamp to [0.0, 1.0] as required by OpenEnv spec
462
- metrics.total_reward = max(0.0, min(1.0, max(metrics.reward_floor, total)))
463
- return metrics
464
-
465
-
466
- class BetaScheduler:
467
- """
468
- Schedule beta parameter for curriculum learning.
469
-
470
- High beta (e.g., 4.0) → Emphasizes recall → Agent learns to find relevant docs
471
- Lower beta (e.g., 2.0) → Shifts toward precision as pruning improves
472
- """
473
-
474
- def __init__(
475
- self,
476
- start_beta: float = 4.0,
477
- end_beta: float = 2.0,
478
- warmup_steps: int = 1000,
479
- decay_steps: int = 10000,
480
- ):
481
- """
482
- Initialize beta scheduler.
483
-
484
- Args:
485
- start_beta: Initial beta value (recall-heavy)
486
- end_beta: Final beta value (balanced)
487
- warmup_steps: Steps to hold at start_beta
488
- decay_steps: Steps over which to decay to end_beta
489
- """
490
- self.start_beta = start_beta
491
- self.end_beta = end_beta
492
- self.warmup_steps = warmup_steps
493
- self.decay_steps = decay_steps
494
-
495
- def get_beta(self, step: int) -> float:
496
- """
497
- Get beta value for a given training step.
498
-
499
- Args:
500
- step: Current training step
501
-
502
- Returns:
503
- Beta value for this step
504
- """
505
- if step < self.warmup_steps:
506
- return self.start_beta
507
-
508
- decay_progress = min(1.0, (step - self.warmup_steps) / self.decay_steps)
509
-
510
- return self.start_beta + (self.end_beta - self.start_beta) * decay_progress