c81b0fc1
tangwang
scripts/evaluatio...
|
1
2
3
4
5
|
"""Core orchestration: corpus, rerank, LLM labels, live/batch evaluation."""
from __future__ import annotations
import json
|
cdd8ee3a
tangwang
eval框架日志独立
|
6
|
import logging
|
c81b0fc1
tangwang
scripts/evaluatio...
|
7
8
9
10
11
12
13
|
import time
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple
import requests
from elasticsearch.helpers import scan
|
a345b01f
tangwang
eval framework
|
14
|
from api.app import get_app_config, get_es_client, init_service
|
c81b0fc1
tangwang
scripts/evaluatio...
|
15
16
17
18
|
from indexer.mapping_generator import get_tenant_index_name
from .clients import DashScopeLabelClient, RerankServiceClient, SearchServiceClient
from .constants import (
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
19
|
DEFAULT_REBUILD_IRREL_LOW_COMBINED_STOP_RATIO,
|
d172c259
tangwang
eval框架
|
20
21
22
23
24
25
26
27
|
DEFAULT_REBUILD_IRRELEVANT_STOP_RATIO,
DEFAULT_REBUILD_IRRELEVANT_STOP_STREAK,
DEFAULT_REBUILD_LLM_BATCH_SIZE,
DEFAULT_REBUILD_MAX_LLM_BATCHES,
DEFAULT_REBUILD_MIN_LLM_BATCHES,
DEFAULT_RERANK_HIGH_SKIP_COUNT,
DEFAULT_RERANK_HIGH_THRESHOLD,
DEFAULT_SEARCH_RECALL_TOP_K,
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
28
|
RELEVANCE_GAIN_MAP,
|
d73ca84a
tangwang
refine eval case ...
|
29
30
31
32
|
RELEVANCE_LV0,
RELEVANCE_LV1,
RELEVANCE_LV2,
RELEVANCE_LV3,
|
a345b01f
tangwang
eval framework
|
33
|
RELEVANCE_NON_IRRELEVANT,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
34
|
VALID_LABELS,
|
d73ca84a
tangwang
refine eval case ...
|
35
|
STOP_PROB_MAP,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
36
|
)
|
2059d959
tangwang
feat(eval): 多评估集统...
|
37
|
from .datasets import EvalDatasetSnapshot, batch_report_run_dir, query_builds_dir
|
465f90e1
tangwang
添加LTR数据收集
|
38
39
40
41
42
43
44
|
from .metrics import (
PRIMARY_METRIC_GRADE_NORMALIZER,
PRIMARY_METRIC_KEYS,
aggregate_metrics,
compute_query_metrics,
label_distribution,
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
45
46
47
48
49
50
51
52
|
from .reports import render_batch_report_markdown
from .store import EvalStore, QueryBuildResult
from .utils import (
build_display_title,
build_rerank_doc,
compact_option_values,
compact_product_payload,
ensure_dir,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
53
54
55
|
sha1_text,
utc_now_iso,
utc_timestamp,
|
167f33b4
tangwang
eval框架前端
|
56
|
zh_title_from_multilingual,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
57
58
|
)
|
cdd8ee3a
tangwang
eval框架日志独立
|
59
60
|
_log = logging.getLogger("search_eval.framework")
|
c81b0fc1
tangwang
scripts/evaluatio...
|
61
|
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
62
63
|
def _metric_context_payload() -> Dict[str, Any]:
return {
|
465f90e1
tangwang
添加LTR数据收集
|
64
65
66
67
68
69
70
71
|
"primary_metric": "Primary_Metric_Score",
"primary_metrics": list(PRIMARY_METRIC_KEYS),
"primary_metric_formula": (
"Primary_Metric_Score = mean("
"NDCG@20, NDCG@50, ERR@10, Strong_Precision@10, Strong_Precision@20, "
"Useful_Precision@50, Avg_Grade@10/3, Gain_Recall@20)"
),
"primary_metric_grade_normalizer": PRIMARY_METRIC_GRADE_NORMALIZER,
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
72
|
"gain_scheme": dict(RELEVANCE_GAIN_MAP),
|
30b490e1
tangwang
添加ERR评估指标
|
73
|
"stop_prob_scheme": dict(STOP_PROB_MAP),
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
74
75
|
"notes": [
"NDCG uses graded gains derived from the four relevance labels.",
|
30b490e1
tangwang
添加ERR评估指标
|
76
|
"ERR (Expected Reciprocal Rank) uses per-grade stop probabilities in stop_prob_scheme.",
|
441f049d
tangwang
评测体系优化,以及
|
77
|
"Strong metrics treat Fully Relevant and Mostly Relevant as strong business positives.",
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
78
79
80
81
82
|
"Useful metrics treat any non-irrelevant item as useful recall coverage.",
],
}
|
167f33b4
tangwang
eval框架前端
|
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
def _zh_titles_from_debug_per_result(debug_info: Any) -> Dict[str, str]:
"""Map ``spu_id`` -> Chinese title from ``debug_info.per_result[].title_multilingual``."""
out: Dict[str, str] = {}
if not isinstance(debug_info, dict):
return out
for entry in debug_info.get("per_result") or []:
if not isinstance(entry, dict):
continue
spu_id = str(entry.get("spu_id") or "").strip()
if not spu_id:
continue
zh = zh_title_from_multilingual(entry.get("title_multilingual"))
if zh:
out[spu_id] = zh
return out
|
d73ca84a
tangwang
refine eval case ...
|
100
101
102
103
104
105
106
107
108
109
|
def _encode_label_sequence(items: Sequence[Dict[str, Any]], limit: int) -> str:
parts: List[str] = []
for item in items[:limit]:
rank = int(item.get("rank") or 0)
label = str(item.get("label") or "")
grade = RELEVANCE_GAIN_MAP.get(label)
parts.append(f"{rank}:L{grade}" if grade is not None else f"{rank}:?")
return " | ".join(parts)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
110
111
112
113
|
class SearchEvaluationFramework:
def __init__(
self,
tenant_id: str,
|
331861d5
tangwang
eval框架配置化
|
114
115
|
artifact_root: Path | None = None,
search_base_url: str | None = None,
|
bdb65283
tangwang
标注框架 批量标注
|
116
117
118
119
|
*,
judge_model: str | None = None,
enable_thinking: bool | None = None,
use_dashscope_batch: bool | None = None,
|
cdd8ee3a
tangwang
eval框架日志独立
|
120
121
|
intent_model: str | None = None,
intent_enable_thinking: bool | None = None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
122
|
):
|
331861d5
tangwang
eval框架配置化
|
123
124
125
|
app_cfg = get_app_config()
se = app_cfg.search_evaluation
init_service(app_cfg.infrastructure.elasticsearch.host)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
126
|
self.tenant_id = str(tenant_id)
|
331861d5
tangwang
eval框架配置化
|
127
|
self.artifact_root = ensure_dir(artifact_root if artifact_root is not None else se.artifact_root)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
128
|
self.store = EvalStore(self.artifact_root / "search_eval.sqlite3")
|
331861d5
tangwang
eval框架配置化
|
129
130
|
sb = search_base_url if search_base_url is not None else se.search_base_url
self.search_client = SearchServiceClient(sb, self.tenant_id)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
131
132
133
134
135
136
137
138
|
rerank_service_url = str(
app_cfg.services.rerank.providers["http"]["instances"]["default"]["service_url"]
)
self.rerank_client = RerankServiceClient(rerank_service_url)
llm_cfg = app_cfg.services.translation.capabilities["llm"]
api_key = app_cfg.infrastructure.secrets.dashscope_api_key
if not api_key:
raise RuntimeError("dashscope_api_key is required for search evaluation annotation")
|
331861d5
tangwang
eval框架配置化
|
139
140
141
142
143
|
model = str(judge_model if judge_model is not None else se.judge_model)
et = se.judge_enable_thinking if enable_thinking is None else enable_thinking
use_batch = se.judge_dashscope_batch if use_dashscope_batch is None else use_dashscope_batch
batch_window = se.judge_batch_completion_window
batch_poll = float(se.judge_batch_poll_interval_sec)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
144
|
self.label_client = DashScopeLabelClient(
|
bdb65283
tangwang
标注框架 批量标注
|
145
|
model=model,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
146
147
|
base_url=str(llm_cfg["base_url"]),
api_key=str(api_key),
|
bdb65283
tangwang
标注框架 批量标注
|
148
149
150
151
|
batch_completion_window=batch_window,
batch_poll_interval_sec=batch_poll,
enable_thinking=et,
use_batch=use_batch,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
152
|
)
|
331861d5
tangwang
eval框架配置化
|
153
154
|
intent_m = str(intent_model if intent_model is not None else se.intent_model)
intent_et = se.intent_enable_thinking if intent_enable_thinking is None else intent_enable_thinking
|
cdd8ee3a
tangwang
eval框架日志独立
|
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
|
self.intent_client = DashScopeLabelClient(
model=intent_m,
base_url=str(llm_cfg["base_url"]),
api_key=str(api_key),
batch_completion_window=batch_window,
batch_poll_interval_sec=batch_poll,
enable_thinking=bool(intent_et),
use_batch=False,
)
self._query_intent_cache: Dict[str, str] = {}
def _ensure_query_intent_block(self, query: str) -> str:
if query not in self._query_intent_cache:
text, _raw = self.intent_client.query_intent(query)
self._query_intent_cache[query] = str(text or "").strip()
return self._query_intent_cache[query]
|
c81b0fc1
tangwang
scripts/evaluatio...
|
171
172
173
174
175
176
177
178
179
180
|
def audit_live_query(
self,
query: str,
*,
top_k: int = 100,
language: str = "en",
auto_annotate: bool = False,
) -> Dict[str, Any]:
live = self.evaluate_live_query(query=query, top_k=top_k, auto_annotate=auto_annotate, language=language)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
181
|
labels = [
|
d73ca84a
tangwang
refine eval case ...
|
182
|
item["label"] if item["label"] in VALID_LABELS else RELEVANCE_LV0
|
c81b0fc1
tangwang
scripts/evaluatio...
|
183
184
185
186
187
188
189
190
|
for item in live["results"]
]
return {
"query": query,
"tenant_id": self.tenant_id,
"top_k": top_k,
"metrics": live["metrics"],
"distribution": label_distribution(labels),
|
a345b01f
tangwang
eval framework
|
191
192
|
"query_profile": None,
"suspicious": [],
|
c81b0fc1
tangwang
scripts/evaluatio...
|
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
|
"results": live["results"],
}
def queries_from_file(self, path: Path) -> List[str]:
return [
line.strip()
for line in path.read_text(encoding="utf-8").splitlines()
if line.strip() and not line.strip().startswith("#")
]
def corpus_docs(self, refresh: bool = False) -> List[Dict[str, Any]]:
if not refresh and self.store.has_corpus(self.tenant_id):
return self.store.get_corpus_docs(self.tenant_id)
es_client = get_es_client().client
index_name = get_tenant_index_name(self.tenant_id)
docs: List[Dict[str, Any]] = []
for hit in scan(
client=es_client,
index=index_name,
query={
"_source": [
"spu_id",
"title",
"vendor",
"category_path",
"category_name",
"image_url",
"skus",
"tags",
],
"query": {"match_all": {}},
},
size=500,
preserve_order=False,
clear_scroll=True,
):
source = dict(hit.get("_source") or {})
source["spu_id"] = str(source.get("spu_id") or hit.get("_id") or "")
docs.append(source)
self.store.upsert_corpus_docs(self.tenant_id, docs)
return docs
def full_corpus_rerank(
self,
query: str,
docs: Sequence[Dict[str, Any]],
|
d172c259
tangwang
eval框架
|
240
|
batch_size: int = 80,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
force_refresh: bool = False,
) -> List[Dict[str, Any]]:
cached = {} if force_refresh else self.store.get_rerank_scores(self.tenant_id, query)
pending: List[Dict[str, Any]] = [doc for doc in docs if str(doc.get("spu_id")) not in cached]
if pending:
new_scores: Dict[str, float] = {}
for start in range(0, len(pending), batch_size):
batch = pending[start : start + batch_size]
scores = self._rerank_batch_with_retry(query=query, docs=batch)
if len(scores) != len(batch):
raise RuntimeError(f"rerank returned {len(scores)} scores for {len(batch)} docs")
for doc, score in zip(batch, scores):
new_scores[str(doc.get("spu_id"))] = float(score)
self.store.upsert_rerank_scores(
self.tenant_id,
query,
new_scores,
model_name="qwen3_vllm_score",
)
cached.update(new_scores)
ranked = []
for doc in docs:
spu_id = str(doc.get("spu_id"))
ranked.append({"spu_id": spu_id, "score": float(cached.get(spu_id, float("-inf"))), "doc": doc})
ranked.sort(key=lambda item: item["score"], reverse=True)
return ranked
|
d172c259
tangwang
eval框架
|
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
|
def full_corpus_rerank_outside_exclude(
self,
query: str,
docs: Sequence[Dict[str, Any]],
exclude_spu_ids: set[str],
batch_size: int = 80,
force_refresh: bool = False,
) -> List[Dict[str, Any]]:
"""Rerank all corpus docs whose spu_id is not in ``exclude_spu_ids``; excluded IDs are not scored via API."""
exclude_spu_ids = {str(x) for x in exclude_spu_ids}
cached = {} if force_refresh else self.store.get_rerank_scores(self.tenant_id, query)
pending: List[Dict[str, Any]] = [
doc
for doc in docs
if str(doc.get("spu_id")) not in exclude_spu_ids
and str(doc.get("spu_id"))
and (force_refresh or str(doc.get("spu_id")) not in cached)
]
if pending:
new_scores: Dict[str, float] = {}
for start in range(0, len(pending), batch_size):
batch = pending[start : start + batch_size]
scores = self._rerank_batch_with_retry(query=query, docs=batch)
if len(scores) != len(batch):
raise RuntimeError(f"rerank returned {len(scores)} scores for {len(batch)} docs")
for doc, score in zip(batch, scores):
new_scores[str(doc.get("spu_id"))] = float(score)
self.store.upsert_rerank_scores(
self.tenant_id,
query,
new_scores,
model_name="qwen3_vllm_score",
)
cached.update(new_scores)
ranked: List[Dict[str, Any]] = []
for doc in docs:
spu_id = str(doc.get("spu_id") or "")
if not spu_id or spu_id in exclude_spu_ids:
continue
ranked.append(
{"spu_id": spu_id, "score": float(cached.get(spu_id, float("-inf"))), "doc": doc}
)
ranked.sort(key=lambda item: item["score"], reverse=True)
return ranked
|
9df421ed
tangwang
基于eval框架开始调参
|
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
|
def _assign_fixed_rerank_scores(
self,
query: str,
spu_ids: Sequence[str],
*,
score: float,
force_refresh: bool = False,
) -> Dict[str, float]:
"""Persist a fixed rerank score for a deduplicated ``spu_id`` list."""
normalized_ids: List[str] = []
seen: set[str] = set()
for spu_id in spu_ids:
sid = str(spu_id or "").strip()
if not sid or sid in seen:
continue
seen.add(sid)
normalized_ids.append(sid)
if not normalized_ids:
return {}
cached = {} if force_refresh else self.store.get_rerank_scores(self.tenant_id, query)
to_store: Dict[str, float] = {}
for sid in normalized_ids:
if force_refresh or sid not in cached or float(cached[sid]) != float(score):
to_store[sid] = float(score)
if to_store:
self.store.upsert_rerank_scores(
self.tenant_id,
query,
to_store,
model_name="search_recall_pool_fixed",
)
return {sid: float(score) for sid in normalized_ids}
|
c81b0fc1
tangwang
scripts/evaluatio...
|
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
|
def _rerank_batch_with_retry(self, query: str, docs: Sequence[Dict[str, Any]]) -> List[float]:
if not docs:
return []
doc_texts = [build_rerank_doc(doc) for doc in docs]
try:
scores, _meta = self.rerank_client.rerank(query=query, docs=doc_texts, normalize=False)
return scores
except Exception:
if len(docs) == 1:
return [-1.0]
if len(docs) <= 6:
scores: List[float] = []
for doc in docs:
scores.extend(self._rerank_batch_with_retry(query, [doc]))
return scores
mid = len(docs) // 2
left = self._rerank_batch_with_retry(query, docs[:mid])
right = self._rerank_batch_with_retry(query, docs[mid:])
return left + right
def annotate_missing_labels(
self,
query: str,
docs: Sequence[Dict[str, Any]],
force_refresh: bool = False,
) -> Dict[str, str]:
labels = {} if force_refresh else self.store.get_labels(self.tenant_id, query)
missing_docs = [doc for doc in docs if str(doc.get("spu_id")) not in labels]
if not missing_docs:
return labels
for start in range(0, len(missing_docs), self.label_client.batch_size):
batch = missing_docs[start : start + self.label_client.batch_size]
batch_pairs = self._classify_with_retry(query, batch, force_refresh=force_refresh)
for sub_labels, raw_response, sub_batch in batch_pairs:
to_store = {str(doc.get("spu_id")): label for doc, label in zip(sub_batch, sub_labels)}
self.store.upsert_labels(
self.tenant_id,
query,
to_store,
judge_model=self.label_client.model,
raw_response=raw_response,
)
labels.update(to_store)
time.sleep(0.1)
return labels
def _classify_with_retry(
self,
query: str,
docs: Sequence[Dict[str, Any]],
*,
force_refresh: bool = False,
) -> List[Tuple[List[str], str, Sequence[Dict[str, Any]]]]:
if not docs:
return []
try:
|
cdd8ee3a
tangwang
eval框架日志独立
|
406
407
408
409
|
intent_block = self._ensure_query_intent_block(query)
labels, raw_response = self.label_client.classify_batch(
query, docs, query_intent_block=intent_block
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
410
|
return [(labels, raw_response, docs)]
|
822ab0fd
tangwang
1. product_enrich...
|
411
412
413
414
415
416
417
418
419
420
|
except Exception as exc:
rid = ""
if isinstance(exc, requests.exceptions.RequestException):
resp = getattr(exc, "response", None)
if resp is not None:
try:
rid = resp.headers.get("x-request-id") or resp.headers.get("X-Request-Id") or ""
except Exception:
rid = ""
rid_part = f" llm_request_id={rid}" if rid else ""
|
286e9b4f
tangwang
evalution
|
421
|
_log.exception(
|
822ab0fd
tangwang
1. product_enrich...
|
422
|
"[eval-rebuild] classify failed query=%r docs=%s;%s %s",
|
286e9b4f
tangwang
evalution
|
423
424
|
query,
len(docs),
|
822ab0fd
tangwang
1. product_enrich...
|
425
|
rid_part,
|
286e9b4f
tangwang
evalution
|
426
427
|
"splitting batch" if len(docs) > 1 else "single-doc failure",
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
428
429
430
431
432
|
if len(docs) == 1:
raise
mid = len(docs) // 2
return self._classify_with_retry(query, docs[:mid], force_refresh=force_refresh) + self._classify_with_retry(query, docs[mid:], force_refresh=force_refresh)
|
d172c259
tangwang
eval框架
|
433
434
435
436
437
438
439
440
441
|
def _annotate_rebuild_batches(
self,
query: str,
ordered_docs: Sequence[Dict[str, Any]],
*,
batch_size: int = DEFAULT_REBUILD_LLM_BATCH_SIZE,
min_batches: int = DEFAULT_REBUILD_MIN_LLM_BATCHES,
max_batches: int = DEFAULT_REBUILD_MAX_LLM_BATCHES,
irrelevant_stop_ratio: float = DEFAULT_REBUILD_IRRELEVANT_STOP_RATIO,
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
442
|
irrelevant_low_combined_stop_ratio: float = DEFAULT_REBUILD_IRREL_LOW_COMBINED_STOP_RATIO,
|
d172c259
tangwang
eval框架
|
443
444
445
|
stop_streak: int = DEFAULT_REBUILD_IRRELEVANT_STOP_STREAK,
force_refresh: bool = True,
) -> Tuple[Dict[str, str], List[Dict[str, Any]]]:
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
446
447
448
449
450
451
|
"""LLM-label ``ordered_docs`` in fixed-size batches along list order.
**Early stop** (only after ``min_batches`` full batches have completed):
Per batch, let *n* = batch size, and count labels among docs in that batch only.
|
35ae3b29
tangwang
批量评估框架,召回参数修改和llm...
|
452
|
- *bad batch* iff **both** (strict ``>``):
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
453
|
|
35ae3b29
tangwang
批量评估框架,召回参数修改和llm...
|
454
|
- ``#(Irrelevant)/n > irrelevant_stop_ratio`` (default 0.939), and
|
441f049d
tangwang
评测体系优化,以及
|
455
|
- ``( #(Irrelevant) + #(Weakly Relevant) ) / n > irrelevant_low_combined_stop_ratio``
|
d73ca84a
tangwang
refine eval case ...
|
456
|
(default 0.959; weak relevance = ``RELEVANCE_LV1``).
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
457
458
|
Maintain a streak of consecutive *bad* batches; any non-bad batch resets the streak to 0.
|
35ae3b29
tangwang
批量评估框架,召回参数修改和llm...
|
459
|
Stop labeling when ``streak >= stop_streak`` (default 3) or when ``max_batches`` is reached
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
460
461
462
463
|
or the ordered list is exhausted.
Constants for defaults: ``eval_framework.constants`` (``DEFAULT_REBUILD_*``).
"""
|
d172c259
tangwang
eval框架
|
464
465
466
467
468
469
470
471
472
473
474
|
batch_logs: List[Dict[str, Any]] = []
streak = 0
labels: Dict[str, str] = dict(self.store.get_labels(self.tenant_id, query))
total_ordered = len(ordered_docs)
for batch_idx in range(max_batches):
start = batch_idx * batch_size
batch_docs = list(ordered_docs[start : start + batch_size])
if not batch_docs:
break
|
286e9b4f
tangwang
evalution
|
475
476
477
478
479
480
481
482
483
|
_log.info(
"[eval-rebuild] query=%r starting llm_batch=%s/%s size=%s offset=%s",
query,
batch_idx + 1,
max_batches,
len(batch_docs),
start,
)
|
d172c259
tangwang
eval框架
|
484
485
486
487
488
489
490
491
492
493
494
495
496
497
|
batch_pairs = self._classify_with_retry(query, batch_docs, force_refresh=force_refresh)
for sub_labels, raw_response, sub_batch in batch_pairs:
to_store = {str(doc.get("spu_id")): label for doc, label in zip(sub_batch, sub_labels)}
self.store.upsert_labels(
self.tenant_id,
query,
to_store,
judge_model=self.label_client.model,
raw_response=raw_response,
)
labels.update(to_store)
time.sleep(0.1)
n = len(batch_docs)
|
d73ca84a
tangwang
refine eval case ...
|
498
499
500
|
exact_n = sum(1 for doc in batch_docs if labels.get(str(doc.get("spu_id"))) == RELEVANCE_LV3)
irrel_n = sum(1 for doc in batch_docs if labels.get(str(doc.get("spu_id"))) == RELEVANCE_LV0)
low_n = sum(1 for doc in batch_docs if labels.get(str(doc.get("spu_id"))) == RELEVANCE_LV1)
|
d172c259
tangwang
eval框架
|
501
502
|
exact_ratio = exact_n / n if n else 0.0
irrelevant_ratio = irrel_n / n if n else 0.0
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
503
504
|
low_ratio = low_n / n if n else 0.0
irrel_low_ratio = (irrel_n + low_n) / n if n else 0.0
|
d172c259
tangwang
eval框架
|
505
506
507
508
509
|
log_entry = {
"batch_index": batch_idx + 1,
"size": n,
"exact_ratio": round(exact_ratio, 6),
"irrelevant_ratio": round(irrelevant_ratio, 6),
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
510
511
|
"low_ratio": round(low_ratio, 6),
"irrelevant_plus_low_ratio": round(irrel_low_ratio, 6),
|
d172c259
tangwang
eval框架
|
512
513
514
515
|
"offset_start": start,
"offset_end": min(start + n, total_ordered),
}
batch_logs.append(log_entry)
|
cdd8ee3a
tangwang
eval框架日志独立
|
516
517
518
519
520
521
522
523
524
525
|
_log.info(
"[eval-rebuild] query=%r llm_batch=%s/%s size=%s exact_ratio=%.4f irrelevant_ratio=%.4f "
"irrel_plus_low_ratio=%.4f",
query,
batch_idx + 1,
max_batches,
n,
exact_ratio,
irrelevant_ratio,
irrel_low_ratio,
|
d172c259
tangwang
eval框架
|
526
527
|
)
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
528
|
# Early-stop streak: only evaluated after min_batches (warm-up before trusting tail quality).
|
d172c259
tangwang
eval框架
|
529
|
if batch_idx + 1 >= min_batches:
|
35ae3b29
tangwang
批量评估框架,召回参数修改和llm...
|
530
531
532
|
bad_batch = (irrelevant_ratio > irrelevant_stop_ratio) and (
irrel_low_ratio > irrelevant_low_combined_stop_ratio
)
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
533
|
if bad_batch:
|
d172c259
tangwang
eval框架
|
534
535
536
537
|
streak += 1
else:
streak = 0
if streak >= stop_streak:
|
cdd8ee3a
tangwang
eval框架日志独立
|
538
539
540
541
542
543
544
545
|
_log.info(
"[eval-rebuild] query=%r early_stop after %s batches (%s consecutive batches: "
"irrelevant>%s and irrel+low>%s)",
query,
batch_idx + 1,
stop_streak,
irrelevant_stop_ratio,
irrelevant_low_combined_stop_ratio,
|
d172c259
tangwang
eval框架
|
546
547
548
549
550
|
)
break
return labels, batch_logs
|
c81b0fc1
tangwang
scripts/evaluatio...
|
551
552
553
554
|
def build_query_annotation_set(
self,
query: str,
*,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
555
|
dataset: EvalDatasetSnapshot | None = None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
556
557
558
559
560
561
562
|
search_depth: int = 1000,
rerank_depth: int = 10000,
annotate_search_top_k: int = 120,
annotate_rerank_top_k: int = 200,
language: str = "en",
force_refresh_rerank: bool = False,
force_refresh_labels: bool = False,
|
d172c259
tangwang
eval框架
|
563
564
565
566
567
568
569
|
search_recall_top_k: int = DEFAULT_SEARCH_RECALL_TOP_K,
rerank_high_threshold: float = DEFAULT_RERANK_HIGH_THRESHOLD,
rerank_high_skip_count: int = DEFAULT_RERANK_HIGH_SKIP_COUNT,
rebuild_llm_batch_size: int = DEFAULT_REBUILD_LLM_BATCH_SIZE,
rebuild_min_batches: int = DEFAULT_REBUILD_MIN_LLM_BATCHES,
rebuild_max_batches: int = DEFAULT_REBUILD_MAX_LLM_BATCHES,
rebuild_irrelevant_stop_ratio: float = DEFAULT_REBUILD_IRRELEVANT_STOP_RATIO,
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
570
|
rebuild_irrel_low_combined_stop_ratio: float = DEFAULT_REBUILD_IRREL_LOW_COMBINED_STOP_RATIO,
|
d172c259
tangwang
eval框架
|
571
|
rebuild_irrelevant_stop_streak: int = DEFAULT_REBUILD_IRRELEVANT_STOP_STREAK,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
572
|
) -> QueryBuildResult:
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
573
574
575
576
577
578
579
580
581
582
|
"""Build per-query annotation pool and write ``query_builds/*.json``.
Normal mode unions search + rerank windows and fills missing labels once.
**Rebuild mode** (``force_refresh_labels=True``): full recall pool + corpus rerank outside
pool, optional skip for "easy" queries, then batched LLM labeling with **early stop**;
see ``_build_query_annotation_set_rebuild`` and ``_annotate_rebuild_batches`` (docstring
spells out the bad-batch / streak rule). Rebuild tuning knobs: ``rebuild_*`` and
``search_recall_top_k`` parameters below; CLI mirrors them under ``build --force-refresh-labels``.
"""
|
d172c259
tangwang
eval框架
|
583
584
585
|
if force_refresh_labels:
return self._build_query_annotation_set_rebuild(
query=query,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
586
|
dataset=dataset,
|
d172c259
tangwang
eval框架
|
587
588
589
590
591
592
593
594
595
596
597
|
search_depth=search_depth,
rerank_depth=rerank_depth,
language=language,
force_refresh_rerank=force_refresh_rerank,
search_recall_top_k=search_recall_top_k,
rerank_high_threshold=rerank_high_threshold,
rerank_high_skip_count=rerank_high_skip_count,
rebuild_llm_batch_size=rebuild_llm_batch_size,
rebuild_min_batches=rebuild_min_batches,
rebuild_max_batches=rebuild_max_batches,
rebuild_irrelevant_stop_ratio=rebuild_irrelevant_stop_ratio,
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
598
|
rebuild_irrel_low_combined_stop_ratio=rebuild_irrel_low_combined_stop_ratio,
|
d172c259
tangwang
eval框架
|
599
600
601
|
rebuild_irrelevant_stop_streak=rebuild_irrelevant_stop_streak,
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
|
search_payload = self.search_client.search(query=query, size=search_depth, from_=0, language=language)
search_results = list(search_payload.get("results") or [])
corpus = self.corpus_docs(refresh=False)
full_rerank = self.full_corpus_rerank(
query=query,
docs=corpus,
force_refresh=force_refresh_rerank,
)
rerank_depth_effective = min(rerank_depth, len(full_rerank))
pool_docs: Dict[str, Dict[str, Any]] = {}
for doc in search_results[:annotate_search_top_k]:
pool_docs[str(doc.get("spu_id"))] = doc
for item in full_rerank[:annotate_rerank_top_k]:
pool_docs[str(item["spu_id"])] = item["doc"]
labels = self.annotate_missing_labels(
query=query,
docs=list(pool_docs.values()),
force_refresh=force_refresh_labels,
)
search_labeled_results: List[Dict[str, Any]] = []
for rank, doc in enumerate(search_results, start=1):
spu_id = str(doc.get("spu_id"))
label = labels.get(spu_id)
search_labeled_results.append(
{
"rank": rank,
"spu_id": spu_id,
"title": build_display_title(doc),
"image_url": doc.get("image_url"),
"rerank_score": None,
"label": label,
"option_values": list(compact_option_values(doc.get("skus") or [])),
"product": compact_product_payload(doc),
}
)
rerank_top_results: List[Dict[str, Any]] = []
for rank, item in enumerate(full_rerank[:rerank_depth_effective], start=1):
doc = item["doc"]
spu_id = str(item["spu_id"])
rerank_top_results.append(
{
"rank": rank,
"spu_id": spu_id,
"title": build_display_title(doc),
"image_url": doc.get("image_url"),
"rerank_score": round(float(item["score"]), 8),
"label": labels.get(spu_id),
"option_values": list(compact_option_values(doc.get("skus") or [])),
"product": compact_product_payload(doc),
}
)
top100_labels = [
|
d73ca84a
tangwang
refine eval case ...
|
659
|
item["label"] if item["label"] in VALID_LABELS else RELEVANCE_LV0
|
c81b0fc1
tangwang
scripts/evaluatio...
|
660
661
|
for item in search_labeled_results[:100]
]
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
662
|
metrics = compute_query_metrics(top100_labels, ideal_labels=list(labels.values()))
|
2059d959
tangwang
feat(eval): 多评估集统...
|
663
664
665
|
output_dir = query_builds_dir(self.artifact_root, dataset.dataset_id) if dataset else ensure_dir(
self.artifact_root / "query_builds"
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
666
667
668
669
670
671
|
run_id = f"{utc_timestamp()}_{sha1_text(self.tenant_id + '|' + query)[:10]}"
output_json_path = output_dir / f"{run_id}.json"
payload = {
"run_id": run_id,
"created_at": utc_now_iso(),
"tenant_id": self.tenant_id,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
672
|
"dataset": dataset.summary() if dataset else None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
673
|
"query": query,
|
310bb3bc
tangwang
eval tools
|
674
|
"config_meta": self.search_client.get_json("/admin/config/meta", timeout=20),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
675
676
677
678
679
680
681
682
683
684
685
|
"search_total": int(search_payload.get("total") or 0),
"search_depth_requested": search_depth,
"search_depth_effective": len(search_results),
"rerank_depth_requested": rerank_depth,
"rerank_depth_effective": rerank_depth_effective,
"corpus_size": len(corpus),
"annotation_pool": {
"annotate_search_top_k": annotate_search_top_k,
"annotate_rerank_top_k": annotate_rerank_top_k,
"pool_size": len(pool_docs),
},
|
c81b0fc1
tangwang
scripts/evaluatio...
|
686
|
"metrics_top100": metrics,
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
687
|
"metric_context": _metric_context_payload(),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
688
689
690
691
|
"search_results": search_labeled_results,
"full_rerank_top": rerank_top_results,
}
output_json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
2059d959
tangwang
feat(eval): 多评估集统...
|
692
693
694
695
696
697
698
699
|
self.store.insert_build_run(
run_id,
self.tenant_id,
query,
output_json_path,
payload,
dataset=dataset,
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
700
701
702
703
704
705
706
707
708
709
|
return QueryBuildResult(
query=query,
tenant_id=self.tenant_id,
search_total=int(search_payload.get("total") or 0),
search_depth=len(search_results),
rerank_corpus_size=len(corpus),
annotated_count=len(pool_docs),
output_json_path=output_json_path,
)
|
d172c259
tangwang
eval框架
|
710
711
712
713
|
def _build_query_annotation_set_rebuild(
self,
query: str,
*,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
714
|
dataset: EvalDatasetSnapshot | None,
|
d172c259
tangwang
eval框架
|
715
716
717
718
719
720
721
722
723
724
725
|
search_depth: int,
rerank_depth: int,
language: str,
force_refresh_rerank: bool,
search_recall_top_k: int,
rerank_high_threshold: float,
rerank_high_skip_count: int,
rebuild_llm_batch_size: int,
rebuild_min_batches: int,
rebuild_max_batches: int,
rebuild_irrelevant_stop_ratio: float,
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
726
|
rebuild_irrel_low_combined_stop_ratio: float,
|
d172c259
tangwang
eval框架
|
727
728
729
730
731
|
rebuild_irrelevant_stop_streak: int,
) -> QueryBuildResult:
search_size = max(int(search_depth), int(search_recall_top_k))
search_payload = self.search_client.search(query=query, size=search_size, from_=0, language=language)
search_results = list(search_payload.get("results") or [])
|
9df421ed
tangwang
基于eval框架开始调参
|
732
733
734
735
736
737
738
739
740
741
|
search_result_spu_ids = [str(doc.get("spu_id") or "").strip() for doc in search_results]
recall_spu_ids: List[str] = []
seen_recall_spu_ids: set[str] = set()
for spu_id in search_result_spu_ids[: int(search_recall_top_k)]:
if not spu_id or spu_id in seen_recall_spu_ids:
continue
seen_recall_spu_ids.add(spu_id)
recall_spu_ids.append(spu_id)
recall_n = len(recall_spu_ids)
pool_spu_ids = set(recall_spu_ids)
|
d172c259
tangwang
eval框架
|
742
743
744
|
corpus = self.corpus_docs(refresh=False)
corpus_by_id = {str(d.get("spu_id")): d for d in corpus if str(d.get("spu_id") or "").strip()}
|
9df421ed
tangwang
基于eval框架开始调参
|
745
746
747
748
749
750
|
self._assign_fixed_rerank_scores(
query=query,
spu_ids=recall_spu_ids,
score=1.0,
force_refresh=force_refresh_rerank,
)
|
d172c259
tangwang
eval框架
|
751
|
|
331861d5
tangwang
eval框架配置化
|
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
|
rerank_pending_n = sum(
1
for d in corpus
if str(d.get("spu_id") or "").strip()
and str(d.get("spu_id")) not in pool_spu_ids
)
_log.info(
"[eval-rebuild] query=%r phase=rerank_outside_pool docs≈%s (pool=%s, force_refresh_rerank=%s); "
"this can take a long time with no further logs until LLM batches start",
query,
rerank_pending_n,
len(pool_spu_ids),
force_refresh_rerank,
)
|
d172c259
tangwang
eval框架
|
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
|
ranked_outside = self.full_corpus_rerank_outside_exclude(
query=query,
docs=corpus,
exclude_spu_ids=pool_spu_ids,
force_refresh=force_refresh_rerank,
)
rerank_high_n = sum(1 for item in ranked_outside if float(item["score"]) > float(rerank_high_threshold))
rebuild_meta: Dict[str, Any] = {
"mode": "rebuild_v1",
"search_recall_top_k": search_recall_top_k,
"recall_pool_size": len(pool_spu_ids),
"pool_rerank_score_assigned": 1.0,
"rerank_high_threshold": rerank_high_threshold,
"rerank_high_count_outside_pool": rerank_high_n,
"rerank_high_skip_count": rerank_high_skip_count,
"rebuild_llm_batch_size": rebuild_llm_batch_size,
"rebuild_min_batches": rebuild_min_batches,
"rebuild_max_batches": rebuild_max_batches,
"rebuild_irrelevant_stop_ratio": rebuild_irrelevant_stop_ratio,
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
787
|
"rebuild_irrel_low_combined_stop_ratio": rebuild_irrel_low_combined_stop_ratio,
|
d172c259
tangwang
eval框架
|
788
789
790
791
792
793
794
795
796
797
798
799
|
"rebuild_irrelevant_stop_streak": rebuild_irrelevant_stop_streak,
}
batch_logs: List[Dict[str, Any]] = []
skipped = False
skip_reason: str | None = None
labels: Dict[str, str] = dict(self.store.get_labels(self.tenant_id, query))
llm_labeled_total = 0
if rerank_high_n > int(rerank_high_skip_count):
skipped = True
skip_reason = "too_many_high_rerank_scores"
|
cdd8ee3a
tangwang
eval框架日志独立
|
800
801
802
803
804
805
806
|
_log.info(
"[eval-rebuild] query=%r skip: rerank_score>%s outside recall pool count=%s > %s "
"(relevant tail too large / query too easy to satisfy)",
query,
rerank_high_threshold,
rerank_high_n,
rerank_high_skip_count,
|
d172c259
tangwang
eval框架
|
807
808
809
810
|
)
else:
ordered_docs: List[Dict[str, Any]] = []
seen_ordered: set[str] = set()
|
9df421ed
tangwang
基于eval框架开始调参
|
811
|
for sid in recall_spu_ids:
|
d172c259
tangwang
eval框架
|
812
813
814
|
if not sid or sid in seen_ordered:
continue
seen_ordered.add(sid)
|
9df421ed
tangwang
基于eval框架开始调参
|
815
816
817
|
doc = corpus_by_id.get(sid)
if doc is not None:
ordered_docs.append(doc)
|
d172c259
tangwang
eval框架
|
818
819
820
821
822
823
824
825
826
827
828
829
830
831
|
for item in ranked_outside:
sid = str(item["spu_id"])
if sid in seen_ordered:
continue
seen_ordered.add(sid)
ordered_docs.append(item["doc"])
labels, batch_logs = self._annotate_rebuild_batches(
query,
ordered_docs,
batch_size=rebuild_llm_batch_size,
min_batches=rebuild_min_batches,
max_batches=rebuild_max_batches,
irrelevant_stop_ratio=rebuild_irrelevant_stop_ratio,
|
dedd31c5
tangwang
1. 搜索 recall 池「1 ...
|
832
|
irrelevant_low_combined_stop_ratio=rebuild_irrel_low_combined_stop_ratio,
|
d172c259
tangwang
eval框架
|
833
834
835
836
837
838
839
840
841
842
843
844
|
stop_streak=rebuild_irrelevant_stop_streak,
force_refresh=True,
)
llm_labeled_total = sum(int(entry.get("size") or 0) for entry in batch_logs)
rebuild_meta["skipped"] = skipped
rebuild_meta["skip_reason"] = skip_reason
rebuild_meta["llm_batch_logs"] = batch_logs
rebuild_meta["llm_labeled_total"] = llm_labeled_total
rerank_depth_effective = min(int(rerank_depth), len(ranked_outside))
search_labeled_results: List[Dict[str, Any]] = []
|
9df421ed
tangwang
基于eval框架开始调参
|
845
846
847
848
|
for rank, search_doc in enumerate(search_results, start=1):
spu_id = str(search_doc.get("spu_id") or "")
doc = corpus_by_id.get(spu_id, search_doc)
in_pool = spu_id in pool_spu_ids
|
d172c259
tangwang
eval框架
|
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
|
search_labeled_results.append(
{
"rank": rank,
"spu_id": spu_id,
"title": build_display_title(doc),
"image_url": doc.get("image_url"),
"rerank_score": 1.0 if in_pool else None,
"label": labels.get(spu_id),
"option_values": list(compact_option_values(doc.get("skus") or [])),
"product": compact_product_payload(doc),
}
)
rerank_top_results: List[Dict[str, Any]] = []
for rank, item in enumerate(ranked_outside[:rerank_depth_effective], start=1):
doc = item["doc"]
spu_id = str(item["spu_id"])
rerank_top_results.append(
{
"rank": rank,
"spu_id": spu_id,
"title": build_display_title(doc),
"image_url": doc.get("image_url"),
"rerank_score": round(float(item["score"]), 8),
"label": labels.get(spu_id),
"option_values": list(compact_option_values(doc.get("skus") or [])),
"product": compact_product_payload(doc),
}
)
top100_labels = [
|
d73ca84a
tangwang
refine eval case ...
|
880
|
item["label"] if item["label"] in VALID_LABELS else RELEVANCE_LV0
|
d172c259
tangwang
eval框架
|
881
882
|
for item in search_labeled_results[:100]
]
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
883
|
metrics = compute_query_metrics(top100_labels, ideal_labels=list(labels.values()))
|
2059d959
tangwang
feat(eval): 多评估集统...
|
884
885
886
|
output_dir = query_builds_dir(self.artifact_root, dataset.dataset_id) if dataset else ensure_dir(
self.artifact_root / "query_builds"
)
|
d172c259
tangwang
eval框架
|
887
888
889
890
891
892
893
|
run_id = f"{utc_timestamp()}_{sha1_text(self.tenant_id + '|' + query)[:10]}"
output_json_path = output_dir / f"{run_id}.json"
pool_docs_count = len(pool_spu_ids) + len(ranked_outside)
payload = {
"run_id": run_id,
"created_at": utc_now_iso(),
"tenant_id": self.tenant_id,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
894
|
"dataset": dataset.summary() if dataset else None,
|
d172c259
tangwang
eval框架
|
895
|
"query": query,
|
310bb3bc
tangwang
eval tools
|
896
|
"config_meta": self.search_client.get_json("/admin/config/meta", timeout=20),
|
d172c259
tangwang
eval框架
|
897
898
899
900
901
902
903
904
905
906
|
"search_total": int(search_payload.get("total") or 0),
"search_depth_requested": search_depth,
"search_depth_effective": len(search_results),
"rerank_depth_requested": rerank_depth,
"rerank_depth_effective": rerank_depth_effective,
"corpus_size": len(corpus),
"annotation_pool": {
"rebuild": rebuild_meta,
"ordered_union_size": pool_docs_count,
},
|
d172c259
tangwang
eval框架
|
907
|
"metrics_top100": metrics,
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
908
|
"metric_context": _metric_context_payload(),
|
d172c259
tangwang
eval框架
|
909
910
911
912
|
"search_results": search_labeled_results,
"full_rerank_top": rerank_top_results,
}
output_json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
2059d959
tangwang
feat(eval): 多评估集统...
|
913
914
915
916
917
918
919
920
|
self.store.insert_build_run(
run_id,
self.tenant_id,
query,
output_json_path,
payload,
dataset=dataset,
)
|
d172c259
tangwang
eval框架
|
921
922
923
924
925
926
927
928
929
930
|
return QueryBuildResult(
query=query,
tenant_id=self.tenant_id,
search_total=int(search_payload.get("total") or 0),
search_depth=len(search_results),
rerank_corpus_size=len(corpus),
annotated_count=llm_labeled_total if not skipped else 0,
output_json_path=output_json_path,
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
931
932
933
934
935
936
937
|
def evaluate_live_query(
self,
query: str,
top_k: int = 100,
auto_annotate: bool = False,
language: str = "en",
force_refresh_labels: bool = False,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
938
|
dataset: EvalDatasetSnapshot | None = None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
939
|
) -> Dict[str, Any]:
|
167f33b4
tangwang
eval框架前端
|
940
941
942
943
|
search_payload = self.search_client.search(
query=query, size=max(top_k, 100), from_=0, language=language, debug=True
)
zh_by_spu = _zh_titles_from_debug_per_result(search_payload.get("debug_info"))
|
c81b0fc1
tangwang
scripts/evaluatio...
|
944
945
946
947
948
949
950
951
952
953
954
955
|
results = list(search_payload.get("results") or [])
if auto_annotate:
self.annotate_missing_labels(query=query, docs=results[:top_k], force_refresh=force_refresh_labels)
labels = self.store.get_labels(self.tenant_id, query)
recalled_spu_ids = {str(doc.get("spu_id")) for doc in results[:top_k]}
labeled = []
unlabeled_hits = 0
for rank, doc in enumerate(results[:top_k], start=1):
spu_id = str(doc.get("spu_id"))
label = labels.get(spu_id)
if label not in VALID_LABELS:
unlabeled_hits += 1
|
167f33b4
tangwang
eval框架前端
|
956
957
958
959
|
primary_title = build_display_title(doc)
title_zh = zh_by_spu.get(spu_id) or ""
if not title_zh and isinstance(doc.get("title"), dict):
title_zh = zh_title_from_multilingual(doc.get("title"))
|
c81b0fc1
tangwang
scripts/evaluatio...
|
960
961
962
963
|
labeled.append(
{
"rank": rank,
"spu_id": spu_id,
|
167f33b4
tangwang
eval框架前端
|
964
965
|
"title": primary_title,
"title_zh": title_zh if title_zh and title_zh != primary_title else "",
|
c81b0fc1
tangwang
scripts/evaluatio...
|
966
967
|
"image_url": doc.get("image_url"),
"label": label,
|
d73ca84a
tangwang
refine eval case ...
|
968
|
"relevance_score": doc.get("relevance_score"),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
969
970
971
972
973
|
"option_values": list(compact_option_values(doc.get("skus") or [])),
"product": compact_product_payload(doc),
}
)
metric_labels = [
|
d73ca84a
tangwang
refine eval case ...
|
974
|
item["label"] if item["label"] in VALID_LABELS else RELEVANCE_LV0
|
c81b0fc1
tangwang
scripts/evaluatio...
|
975
976
|
for item in labeled
]
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
977
|
ideal_labels = [
|
d73ca84a
tangwang
refine eval case ...
|
978
|
label if label in VALID_LABELS else RELEVANCE_LV0
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
979
980
|
for label in labels.values()
]
|
c81b0fc1
tangwang
scripts/evaluatio...
|
981
982
983
984
985
|
label_stats = self.store.get_query_label_stats(self.tenant_id, query)
rerank_scores = self.store.get_rerank_scores(self.tenant_id, query)
relevant_missing_ids = [
spu_id
for spu_id, label in labels.items()
|
a345b01f
tangwang
eval framework
|
986
|
if label in RELEVANCE_NON_IRRELEVANT and spu_id not in recalled_spu_ids
|
c81b0fc1
tangwang
scripts/evaluatio...
|
987
988
989
990
991
992
993
|
]
missing_docs_map = self.store.get_corpus_docs_by_spu_ids(self.tenant_id, relevant_missing_ids)
missing_relevant = []
for spu_id in relevant_missing_ids:
doc = missing_docs_map.get(spu_id)
if not doc:
continue
|
167f33b4
tangwang
eval框架前端
|
994
995
|
miss_title = build_display_title(doc)
miss_zh = zh_title_from_multilingual(doc.get("title")) if isinstance(doc.get("title"), dict) else ""
|
c81b0fc1
tangwang
scripts/evaluatio...
|
996
997
998
999
1000
|
missing_relevant.append(
{
"spu_id": spu_id,
"label": labels[spu_id],
"rerank_score": rerank_scores.get(spu_id),
|
167f33b4
tangwang
eval框架前端
|
1001
1002
|
"title": miss_title,
"title_zh": miss_zh if miss_zh and miss_zh != miss_title else "",
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1003
1004
1005
1006
1007
|
"image_url": doc.get("image_url"),
"option_values": list(compact_option_values(doc.get("skus") or [])),
"product": compact_product_payload(doc),
}
)
|
a345b01f
tangwang
eval framework
|
1008
|
label_order = {
|
d73ca84a
tangwang
refine eval case ...
|
1009
1010
1011
1012
|
RELEVANCE_LV3: 0,
RELEVANCE_LV2: 1,
RELEVANCE_LV1: 2,
RELEVANCE_LV0: 3,
|
a345b01f
tangwang
eval framework
|
1013
|
}
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
|
missing_relevant.sort(
key=lambda item: (
label_order.get(str(item.get("label")), 9),
-(float(item.get("rerank_score")) if item.get("rerank_score") is not None else float("-inf")),
str(item.get("title") or ""),
)
)
tips: List[str] = []
if auto_annotate:
tips.append("Single-query evaluation used cached labels and refreshed missing labels for recalled results.")
else:
tips.append("Single-query evaluation used the offline annotation cache only; recalled SPUs without cached labels were treated as Irrelevant.")
if label_stats["total"] == 0:
tips.append("This query has no offline annotation set yet. Build or refresh labels first if you want stable evaluation.")
if unlabeled_hits:
tips.append(f"{unlabeled_hits} recalled results were not in the annotation set and were counted as Irrelevant.")
if not missing_relevant:
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
1031
|
tips.append("No cached judged useful products were missed by this recall set.")
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1032
1033
1034
|
return {
"query": query,
"tenant_id": self.tenant_id,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1035
|
"dataset": dataset.summary() if dataset else None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1036
|
"top_k": top_k,
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
1037
1038
|
"metrics": compute_query_metrics(metric_labels, ideal_labels=ideal_labels),
"metric_context": _metric_context_payload(),
|
d73ca84a
tangwang
refine eval case ...
|
1039
|
"request_id": str(search_payload.get("_eval_request_id") or ""),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1040
1041
1042
1043
1044
1045
1046
|
"results": labeled,
"missing_relevant": missing_relevant,
"label_stats": {
**label_stats,
"unlabeled_hits_treated_irrelevant": unlabeled_hits,
"recalled_hits": len(labeled),
"missing_relevant_count": len(missing_relevant),
|
d73ca84a
tangwang
refine eval case ...
|
1047
1048
1049
|
"missing_exact_count": sum(1 for item in missing_relevant if item["label"] == RELEVANCE_LV3),
"missing_high_count": sum(1 for item in missing_relevant if item["label"] == RELEVANCE_LV2),
"missing_low_count": sum(1 for item in missing_relevant if item["label"] == RELEVANCE_LV1),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1050
1051
1052
1053
1054
1055
1056
1057
1058
|
},
"tips": tips,
"total": int(search_payload.get("total") or 0),
}
def batch_evaluate(
self,
queries: Sequence[str],
*,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1059
|
dataset: EvalDatasetSnapshot | None = None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1060
1061
1062
1063
1064
1065
|
top_k: int = 100,
auto_annotate: bool = True,
language: str = "en",
force_refresh_labels: bool = False,
) -> Dict[str, Any]:
per_query = []
|
d73ca84a
tangwang
refine eval case ...
|
1066
|
case_snapshot_top_n = min(max(int(top_k), 1), 20)
|
331861d5
tangwang
eval框架配置化
|
1067
1068
1069
|
total_q = len(queries)
_log.info("[batch-eval] starting %s queries top_k=%s auto_annotate=%s", total_q, top_k, auto_annotate)
for q_index, query in enumerate(queries, start=1):
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1070
1071
1072
1073
1074
1075
|
live = self.evaluate_live_query(
query,
top_k=top_k,
auto_annotate=auto_annotate,
language=language,
force_refresh_labels=force_refresh_labels,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1076
|
dataset=dataset,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1077
1078
|
)
labels = [
|
d73ca84a
tangwang
refine eval case ...
|
1079
|
item["label"] if item["label"] in VALID_LABELS else RELEVANCE_LV0
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
|
for item in live["results"]
]
per_query.append(
{
"query": live["query"],
"tenant_id": live["tenant_id"],
"top_k": live["top_k"],
"metrics": live["metrics"],
"distribution": label_distribution(labels),
"total": live["total"],
|
d73ca84a
tangwang
refine eval case ...
|
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
|
"request_id": live.get("request_id") or "",
"case_snapshot_top_n": case_snapshot_top_n,
"top_label_sequence_top10": _encode_label_sequence(live["results"], 10),
"top_label_sequence_top20": _encode_label_sequence(live["results"], case_snapshot_top_n),
"top_results": [
{
"rank": int(item.get("rank") or 0),
"spu_id": str(item.get("spu_id") or ""),
"label": item.get("label"),
"title": item.get("title"),
"title_zh": item.get("title_zh"),
"relevance_score": item.get("relevance_score"),
}
for item in live["results"][:case_snapshot_top_n]
],
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1105
1106
|
}
)
|
331861d5
tangwang
eval框架配置化
|
1107
1108
|
m = live["metrics"]
_log.info(
|
465f90e1
tangwang
添加LTR数据收集
|
1109
1110
|
"[batch-eval] (%s/%s) query=%r Primary_Metric_Score=%s NDCG@20=%s ERR@10=%s "
"Strong_Precision@10=%s Useful_Precision@50=%s Gain_Recall@20=%s total_hits=%s",
|
331861d5
tangwang
eval框架配置化
|
1111
1112
1113
|
q_index,
total_q,
query,
|
465f90e1
tangwang
添加LTR数据收集
|
1114
1115
1116
|
m.get("Primary_Metric_Score"),
m.get("NDCG@20"),
m.get("ERR@10"),
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
1117
|
m.get("Strong_Precision@10"),
|
465f90e1
tangwang
添加LTR数据收集
|
1118
1119
|
m.get("Useful_Precision@50"),
m.get("Gain_Recall@20"),
|
331861d5
tangwang
eval框架配置化
|
1120
1121
|
live.get("total"),
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1122
1123
|
aggregate = aggregate_metrics([item["metrics"] for item in per_query])
aggregate_distribution = {
|
d73ca84a
tangwang
refine eval case ...
|
1124
1125
1126
1127
|
RELEVANCE_LV3: sum(item["distribution"][RELEVANCE_LV3] for item in per_query),
RELEVANCE_LV2: sum(item["distribution"][RELEVANCE_LV2] for item in per_query),
RELEVANCE_LV1: sum(item["distribution"][RELEVANCE_LV1] for item in per_query),
RELEVANCE_LV0: sum(item["distribution"][RELEVANCE_LV0] for item in per_query),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1128
|
}
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1129
1130
1131
1132
1133
1134
1135
|
dataset_id = dataset.dataset_id if dataset else "legacy_default"
dataset_hash = dataset.query_sha1 if dataset else sha1_text("|".join(queries))
batch_id = f"batch_{utc_timestamp()}_{sha1_text(self.tenant_id + '|' + dataset_id + '|' + dataset_hash)[:10]}"
report_dir = batch_report_run_dir(self.artifact_root, dataset_id, batch_id) if dataset else ensure_dir(
self.artifact_root / "batch_reports"
)
config_snapshot_path = report_dir / "config_snapshot.json" if dataset else report_dir / f"{batch_id}_config.json"
|
310bb3bc
tangwang
eval tools
|
1136
|
config_snapshot = self.search_client.get_json("/admin/config", timeout=20)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1137
|
config_snapshot_path.write_text(json.dumps(config_snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
|
dataset_snapshot_path = report_dir / "dataset_snapshot.json" if dataset else None
queries_snapshot_path = report_dir / "queries.txt" if dataset else None
if dataset_snapshot_path is not None:
dataset_snapshot_path.write_text(
json.dumps(dataset.summary(), ensure_ascii=False, indent=2),
encoding="utf-8",
)
if queries_snapshot_path is not None:
queries_snapshot_path.write_text("\n".join(queries) + "\n", encoding="utf-8")
output_json_path = report_dir / "report.json" if dataset else report_dir / f"{batch_id}.json"
report_md_path = report_dir / "report.md" if dataset else report_dir / f"{batch_id}.md"
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1149
1150
1151
1152
|
payload = {
"batch_id": batch_id,
"created_at": utc_now_iso(),
"tenant_id": self.tenant_id,
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1153
|
"dataset": dataset.summary() if dataset else None,
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1154
1155
1156
|
"queries": list(queries),
"top_k": top_k,
"aggregate_metrics": aggregate,
|
7ddd4cb3
tangwang
评估体系从三等级->四等级 Exa...
|
1157
|
"metric_context": _metric_context_payload(),
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1158
1159
1160
|
"aggregate_distribution": aggregate_distribution,
"per_query": per_query,
"config_snapshot_path": str(config_snapshot_path),
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1161
1162
|
"dataset_snapshot_path": str(dataset_snapshot_path) if dataset_snapshot_path is not None else "",
"queries_snapshot_path": str(queries_snapshot_path) if queries_snapshot_path is not None else "",
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1163
1164
1165
|
}
output_json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
report_md_path.write_text(render_batch_report_markdown(payload), encoding="utf-8")
|
2059d959
tangwang
feat(eval): 多评估集统...
|
1166
1167
1168
1169
1170
1171
1172
1173
1174
|
self.store.insert_batch_run(
batch_id,
self.tenant_id,
output_json_path,
report_md_path,
config_snapshot_path,
payload,
dataset=dataset,
)
|
331861d5
tangwang
eval框架配置化
|
1175
1176
1177
1178
1179
1180
|
_log.info(
"[batch-eval] finished batch_id=%s per_query=%s json=%s",
batch_id,
len(per_query),
output_json_path,
)
|
c81b0fc1
tangwang
scripts/evaluatio...
|
1181
|
return payload
|