Blame view

tests/test_embedding_pipeline.py 10.6 KB
0ba0e0fc   tangwang   1. rerank漏斗配置优化
1
  from dataclasses import asdict
950a640e   tangwang   embeddings
2
3
4
  from typing import Any, Dict, List, Optional
  
  import numpy as np
ed948666   tangwang   tidy
5
  import pytest
950a640e   tangwang   embeddings
6
7
8
9
10
  
  from config import (
      FunctionScoreConfig,
      IndexConfig,
      QueryConfig,
950a640e   tangwang   embeddings
11
12
13
14
15
      RerankConfig,
      SPUConfig,
      SearchConfig,
  )
  from embeddings.text_encoder import TextEmbeddingEncoder
7214c2e7   tangwang   mplemented**
16
  from embeddings.image_encoder import CLIPImageEncoder
4650fcec   tangwang   日志优化、日志串联(uid rqid)
17
  from embeddings.text_embedding_tei import TEITextModel
4a37d233   tangwang   1. embedding cach...
18
  from embeddings.bf16 import encode_embedding_for_redis
7214c2e7   tangwang   mplemented**
19
  from embeddings.cache_keys import build_image_cache_key, build_text_cache_key
5a01af3c   tangwang   多模态hashkey调整:1. 加...
20
  from embeddings.config import CONFIG
950a640e   tangwang   embeddings
21
  from query import QueryParser
4650fcec   tangwang   日志优化、日志串联(uid rqid)
22
  from context.request_context import create_request_context, set_current_request_context, clear_current_request_context
950a640e   tangwang   embeddings
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  
  
  class _FakeRedis:
      def __init__(self):
          self.store: Dict[str, bytes] = {}
  
      def ping(self):
          return True
  
      def get(self, key: str):
          return self.store.get(key)
  
      def setex(self, key: str, _expire, value: bytes):
          self.store[key] = value
          return True
  
      def expire(self, key: str, _expire):
          return key in self.store
  
      def delete(self, key: str):
          self.store.pop(key, None)
          return True
  
  
  class _FakeResponse:
      def __init__(self, payload: List[Optional[List[float]]]):
          self._payload = payload
  
      def raise_for_status(self):
          return None
  
      def json(self):
          return self._payload
  
  
  class _FakeTranslator:
      def translate(
          self,
          text: str,
          target_lang: str,
          source_lang: Optional[str] = None,
          prompt: Optional[str] = None,
      ) -> str:
          return f"{text}-{target_lang}"
  
  
  class _FakeQueryEncoder:
b754fd41   tangwang   图片向量化支持优先级参数
70
71
72
      def __init__(self):
          self.calls = []
  
950a640e   tangwang   embeddings
73
      def encode(self, sentences, **kwargs):
b754fd41   tangwang   图片向量化支持优先级参数
74
          self.calls.append({"sentences": sentences, "kwargs": dict(kwargs)})
950a640e   tangwang   embeddings
75
76
77
78
79
          if isinstance(sentences, str):
              sentences = [sentences]
          return np.array([np.array([0.11, 0.22, 0.33], dtype=np.float32) for _ in sentences], dtype=object)
  
  
dc403578   tangwang   多模态搜索
80
81
82
83
84
85
86
87
88
  class _FakeClipTextEncoder:
      def __init__(self):
          self.calls = []
  
      def encode_clip_text(self, text, **kwargs):
          self.calls.append({"text": text, "kwargs": dict(kwargs)})
          return np.array([0.44, 0.55, 0.66], dtype=np.float32)
  
  
ef5baa86   tangwang   混杂语言处理
89
90
91
92
  def _tokenizer(text):
      return str(text).split()
  
  
7214c2e7   tangwang   mplemented**
93
94
95
96
97
98
99
100
101
102
103
104
  class _FakeEmbeddingCache:
      def __init__(self):
          self.store: Dict[str, np.ndarray] = {}
  
      def get(self, key: str):
          return self.store.get(key)
  
      def set(self, key: str, embedding: np.ndarray):
          self.store[key] = np.asarray(embedding, dtype=np.float32)
          return True
  
  
dc403578   tangwang   多模态搜索
105
  def _build_test_config(*, image_embedding_field: Optional[str] = None) -> SearchConfig:
950a640e   tangwang   embeddings
106
107
108
109
110
111
112
113
      return SearchConfig(
          field_boosts={"title.en": 3.0},
          indexes=[IndexConfig(name="default", label="default", fields=["title.en"], boost=1.0)],
          query_config=QueryConfig(
              supported_languages=["en", "zh"],
              default_language="en",
              enable_text_embedding=True,
              enable_query_rewrite=False,
950a640e   tangwang   embeddings
114
              rewrite_dictionary={},
950a640e   tangwang   embeddings
115
              text_embedding_field="title_embedding",
dc403578   tangwang   多模态搜索
116
              image_embedding_field=image_embedding_field,
950a640e   tangwang   embeddings
117
          ),
77ab67ad   tangwang   更新测试用例
118
          function_score=FunctionScoreConfig(),
950a640e   tangwang   embeddings
119
120
121
          rerank=RerankConfig(),
          spu_config=SPUConfig(enabled=True, spu_field="spu_id", inner_hits_size=3),
          es_index_name="test_products",
950a640e   tangwang   embeddings
122
          es_settings={},
950a640e   tangwang   embeddings
123
124
125
126
      )
  
  
  def test_text_embedding_encoder_response_alignment(monkeypatch):
7214c2e7   tangwang   mplemented**
127
128
      fake_cache = _FakeEmbeddingCache()
      monkeypatch.setattr("embeddings.text_encoder.RedisEmbeddingCache", lambda **kwargs: fake_cache)
950a640e   tangwang   embeddings
129
  
77ab67ad   tangwang   更新测试用例
130
      def _fake_post(url, json, timeout, **kwargs):
950a640e   tangwang   embeddings
131
132
          assert url.endswith("/embed/text")
          assert json == ["hello", "world"]
b754fd41   tangwang   图片向量化支持优先级参数
133
          assert kwargs["params"]["priority"] == 0
ed948666   tangwang   tidy
134
          return _FakeResponse([[0.1, 0.2], [0.3, 0.4]])
950a640e   tangwang   embeddings
135
136
137
138
139
140
141
142
143
  
      monkeypatch.setattr("embeddings.text_encoder.requests.post", _fake_post)
  
      encoder = TextEmbeddingEncoder(service_url="http://127.0.0.1:6005")
      out = encoder.encode(["hello", "world"])
  
      assert len(out) == 2
      assert isinstance(out[0], np.ndarray)
      assert out[0].shape == (2,)
ed948666   tangwang   tidy
144
145
146
147
148
      assert isinstance(out[1], np.ndarray)
      assert out[1].shape == (2,)
  
  
  def test_text_embedding_encoder_raises_on_missing_vector(monkeypatch):
7214c2e7   tangwang   mplemented**
149
150
      fake_cache = _FakeEmbeddingCache()
      monkeypatch.setattr("embeddings.text_encoder.RedisEmbeddingCache", lambda **kwargs: fake_cache)
ed948666   tangwang   tidy
151
  
77ab67ad   tangwang   更新测试用例
152
      def _fake_post(url, json, timeout, **kwargs):
ed948666   tangwang   tidy
153
154
155
156
157
158
159
          return _FakeResponse([[0.1, 0.2], None])
  
      monkeypatch.setattr("embeddings.text_encoder.requests.post", _fake_post)
  
      encoder = TextEmbeddingEncoder(service_url="http://127.0.0.1:6005")
      with pytest.raises(ValueError):
          encoder.encode(["hello", "world"])
950a640e   tangwang   embeddings
160
161
162
  
  
  def test_text_embedding_encoder_cache_hit(monkeypatch):
7214c2e7   tangwang   mplemented**
163
      fake_cache = _FakeEmbeddingCache()
950a640e   tangwang   embeddings
164
      cached = np.array([0.9, 0.8], dtype=np.float32)
7214c2e7   tangwang   mplemented**
165
166
      fake_cache.store[build_text_cache_key("cached-text", normalize=True)] = cached
      monkeypatch.setattr("embeddings.text_encoder.RedisEmbeddingCache", lambda **kwargs: fake_cache)
950a640e   tangwang   embeddings
167
168
169
  
      calls = {"count": 0}
  
77ab67ad   tangwang   更新测试用例
170
      def _fake_post(url, json, timeout, **kwargs):
950a640e   tangwang   embeddings
171
172
173
174
175
176
177
178
179
180
181
182
183
          calls["count"] += 1
          return _FakeResponse([[0.3, 0.4]])
  
      monkeypatch.setattr("embeddings.text_encoder.requests.post", _fake_post)
  
      encoder = TextEmbeddingEncoder(service_url="http://127.0.0.1:6005")
      out = encoder.encode(["cached-text", "new-text"])
  
      assert calls["count"] == 1
      assert np.allclose(out[0], cached)
      assert np.allclose(out[1], np.array([0.3, 0.4], dtype=np.float32))
  
  
4650fcec   tangwang   日志优化、日志串联(uid rqid)
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
  def test_text_embedding_encoder_forwards_request_headers(monkeypatch):
      fake_cache = _FakeEmbeddingCache()
      monkeypatch.setattr("embeddings.text_encoder.RedisEmbeddingCache", lambda **kwargs: fake_cache)
  
      captured = {}
  
      def _fake_post(url, json, timeout, **kwargs):
          captured["headers"] = dict(kwargs.get("headers") or {})
          return _FakeResponse([[0.1, 0.2]])
  
      monkeypatch.setattr("embeddings.text_encoder.requests.post", _fake_post)
  
      context = create_request_context(reqid="req-ctx-1", uid="user-ctx-1")
      set_current_request_context(context)
      try:
          encoder = TextEmbeddingEncoder(service_url="http://127.0.0.1:6005")
          encoder.encode(["hello"])
      finally:
          clear_current_request_context()
  
      assert captured["headers"]["X-Request-ID"] == "req-ctx-1"
      assert captured["headers"]["X-User-ID"] == "user-ctx-1"
  
  
7214c2e7   tangwang   mplemented**
208
209
210
211
  def test_image_embedding_encoder_cache_hit(monkeypatch):
      fake_cache = _FakeEmbeddingCache()
      cached = np.array([0.5, 0.6], dtype=np.float32)
      url = "https://example.com/a.jpg"
5a01af3c   tangwang   多模态hashkey调整:1. 加...
212
213
214
      fake_cache.store[
          build_image_cache_key(url, normalize=True, model_name=CONFIG.MULTIMODAL_MODEL_NAME)
      ] = cached
7214c2e7   tangwang   mplemented**
215
216
217
218
219
220
      monkeypatch.setattr("embeddings.image_encoder.RedisEmbeddingCache", lambda **kwargs: fake_cache)
  
      calls = {"count": 0}
  
      def _fake_post(url, params, json, timeout, **kwargs):
          calls["count"] += 1
b754fd41   tangwang   图片向量化支持优先级参数
221
          assert params["priority"] == 0
7214c2e7   tangwang   mplemented**
222
223
224
225
226
227
228
229
230
231
232
233
          return _FakeResponse([[0.1, 0.2]])
  
      monkeypatch.setattr("embeddings.image_encoder.requests.post", _fake_post)
  
      encoder = CLIPImageEncoder(service_url="http://127.0.0.1:6008")
      out = encoder.encode_batch(["https://example.com/a.jpg", "https://example.com/b.jpg"])
  
      assert calls["count"] == 1
      assert np.allclose(out[0], cached)
      assert np.allclose(out[1], np.array([0.1, 0.2], dtype=np.float32))
  
  
b754fd41   tangwang   图片向量化支持优先级参数
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
  def test_image_embedding_encoder_passes_priority(monkeypatch):
      fake_cache = _FakeEmbeddingCache()
      monkeypatch.setattr("embeddings.image_encoder.RedisEmbeddingCache", lambda **kwargs: fake_cache)
  
      def _fake_post(url, params, json, timeout, **kwargs):
          assert params["priority"] == 1
          return _FakeResponse([[0.1, 0.2]])
  
      monkeypatch.setattr("embeddings.image_encoder.requests.post", _fake_post)
  
      encoder = CLIPImageEncoder(service_url="http://127.0.0.1:6008")
      out = encoder.encode_batch(["https://example.com/a.jpg"], priority=1)
      assert len(out) == 1
      assert np.allclose(out[0], np.array([0.1, 0.2], dtype=np.float32))
  
  
950a640e   tangwang   embeddings
250
  def test_query_parser_generates_query_vector_with_encoder():
b754fd41   tangwang   图片向量化支持优先级参数
251
      encoder = _FakeQueryEncoder()
950a640e   tangwang   embeddings
252
253
      parser = QueryParser(
          config=_build_test_config(),
b754fd41   tangwang   图片向量化支持优先级参数
254
          text_encoder=encoder,
950a640e   tangwang   embeddings
255
          translator=_FakeTranslator(),
ef5baa86   tangwang   混杂语言处理
256
          tokenizer=_tokenizer,
950a640e   tangwang   embeddings
257
258
259
260
261
      )
  
      parsed = parser.parse("red dress", tenant_id="162", generate_vector=True)
      assert parsed.query_vector is not None
      assert parsed.query_vector.shape == (3,)
b754fd41   tangwang   图片向量化支持优先级参数
262
263
      assert encoder.calls
      assert encoder.calls[0]["kwargs"]["priority"] == 1
950a640e   tangwang   embeddings
264
265
  
  
dc403578   tangwang   多模态搜索
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
  def test_query_parser_generates_image_query_vector_with_clip_text_encoder():
      text_encoder = _FakeQueryEncoder()
      image_encoder = _FakeClipTextEncoder()
      parser = QueryParser(
          config=_build_test_config(image_embedding_field="image_embedding.vector"),
          text_encoder=text_encoder,
          image_encoder=image_encoder,
          translator=_FakeTranslator(),
          tokenizer=_tokenizer,
      )
  
      parsed = parser.parse("red dress", tenant_id="162", generate_vector=True)
      assert parsed.query_vector is not None
      assert parsed.image_query_vector is not None
      assert parsed.image_query_vector.shape == (3,)
      assert image_encoder.calls
      assert image_encoder.calls[0]["text"] == "red dress"
      assert image_encoder.calls[0]["kwargs"]["priority"] == 1
  
  
950a640e   tangwang   embeddings
286
287
288
289
290
  def test_query_parser_skips_query_vector_when_disabled():
      parser = QueryParser(
          config=_build_test_config(),
          text_encoder=_FakeQueryEncoder(),
          translator=_FakeTranslator(),
ef5baa86   tangwang   混杂语言处理
291
          tokenizer=_tokenizer,
950a640e   tangwang   embeddings
292
293
294
295
      )
  
      parsed = parser.parse("red dress", tenant_id="162", generate_vector=False)
      assert parsed.query_vector is None
dc403578   tangwang   多模态搜索
296
      assert parsed.image_query_vector is None
4650fcec   tangwang   日志优化、日志串联(uid rqid)
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
  
  
  def test_tei_text_model_splits_batches_over_client_limit(monkeypatch):
      monkeypatch.setattr(TEITextModel, "_health_check", lambda self: None)
      calls = []
  
      class _Response:
          def __init__(self, payload):
              self._payload = payload
  
          def raise_for_status(self):
              return None
  
          def json(self):
              return self._payload
  
      def _fake_post(url, json, timeout):
          inputs = list(json["inputs"])
          calls.append(inputs)
          return _Response([[float(idx)] for idx, _ in enumerate(inputs, start=1)])
  
      monkeypatch.setattr("embeddings.text_embedding_tei.requests.post", _fake_post)
  
      model = TEITextModel(
          base_url="http://127.0.0.1:8080",
          timeout_sec=20,
          max_client_batch_size=24,
      )
      vectors = model.encode([f"text-{idx}" for idx in range(25)], normalize_embeddings=False)
  
      assert len(calls) == 2
      assert len(calls[0]) == 24
      assert len(calls[1]) == 1
      assert len(vectors) == 25